#templates-archived
1 messages Β· Page 152 of 1
Don't know how that affects the template though, I just need it to scrub the name for VLC
What does the sensor looked like in developer tools or is that from DT?
This.Means.War.2012.UNRATED.BluRay.DD5.1.x264-ThD.mkv - VLC media player
It changes with every file
But always has VLC at the end
Do you know the template?
and what do you want to do with it?
what is the entities name?
is this the state? This.Means.War.2012.UNRATED.BluRay.DD5.1.x264-ThD.mkv - VLC media player
I fell asleep sorry. I pasted its name above, don't know what use there is to paste it again but here goes:
thegoat420_activewindow
And yes your intuition was correct, that whole string is the entities' state, as it appears in DT.
But all this is a time waste, I mean the template is gonna look the same regardless of the entities name, state, or purpose for that matter. Could have just used "X" for me to insert the name afterwards instead. Wouldn't have the expectation for people to tailor the code for me
Hey folks. When I try the following template in Developer Tools, it tells me that it only listens for state changed events for sun.sun. What am I missing?
{{ state_attr("sun.sun", "elevation") < 10 or states("sensor.downstairs_motion_sensor_light_level")| int < 55 or (states("sensor.downstairs_motion_sensor_light_level")| int < 70 and is_state("binary_sensor.morning", "on")) }}
Okay. So, in reality, it's not a problem, then? The rest will be evaluated if the first condition fails...?
Correct. But you may want to add explicit parentheses to make the order of operations clearer
Thought about that. Will do. Thanks!
Hey guys, how can I fetch a bulb's brightness as a percentage?
This doesn't work, the result is 'None'.
front lantern brightness: {{ state_attr('light.front_door_lantern_bulb', 'brightness') }} (0-255)
front lantern brightness: {{ state_attr('light.front_door_lantern_bulb', 'brightness_pct') }} percent
Result:
front lantern brightness: 38 (0-255)
front lantern brightness: None percent
Does the attribute exist?
The auto-generated automation created this:
device_id: fa9aa9fb054278cc0a1f233febc7ef6a
entity_id: light.front_door_lantern_bulb
domain: light
brightness_pct: 1
Hum, didn't think to check. No it doesn't exist in the devo tools -> States:
supported_color_modes: brightness
color_mode: brightness
brightness: 38
friendly_name: Front Door Lantern bulb
supported_features: 32```
I'm trying to read the current brightness, then change it for 90 secs, then set it back to what it was. It's the setting back to what it was that's causing me issues.
Can I just change that auto-gen brightness_pct to brightness ?
Use a scene for that
Or, like I said, calculate it yourself. Or just set the brightness
That's what that's for
Great, thanks, i'll look into it.
It works! Amazing, thank-you !
Well its not. If the name with VLC in it was the state then the template code would be different than if the name was an attribute.
Do you know the template?
If I understand correctly you want to show the title of what is playing is VLC is part of the entity state. What shouls the sensor show if that is not the case
It's a sensor that shows a changing window title which sometimes isn't VLC. and it works as intended. I need a template to use in an automation trigger for when VLC is selected
Okay so a binary sensor which is on when VLC is in the state?
Ok yes that could also work
{{ 'VLC' in states('sensor.your_sensor') }}
Cool thanks dude
Is there a way to trigger the button.press service for a group of buttons? I used to be able to trigger a bunch of firmware updates (for Shelly units) back in the days they appeared as switches by hitting the header switch in the LoveLace frontend. That is impossible now that they are buttons without a 'state'. I would like to trigger all the buttons matching the pattern*ota_update*...
You can do that with a template for the entity_id
{{ states.button|selectattr('entity_id', 'search', 'ota_update')|map(attribute='entity_id')|list }}
anyone know how to create a template for a detached reed switch on a shelly?
What do you need a template for?
@inner mesa just to figure out if it's open or closed. The shelly integration only gives me the option to open close the garage door, but I want a status to show it being open or closed.
That's just the state of an entity, right?
I am trying to automate sending zwave pings to devices that have magically become unavailable, following direction I've found in the forums. The first step is creating a template sensor that should return a list of these entities. The jinja "code" returns the proper list using the Developer Tools, but the sensor only always shows as "unavailable". Here's the content of my templates.yaml:
- sensor:
- name: "Dead ZWave Devices"
unique_id: dead_zwave_devices
state: >-
{{ states | selectattr("entity_id", "search", "node_status") |
selectattr('state', 'in', 'dead, unavailable, unknown') |
map(attribute='entity_id') | list }}
- name: "Dead ZWave Devices"
This seems to have worked for others, so I truly don't understand what's going on. Is it possible that this sensor doesn't return a state until an entity is added to the list?
I'm surprised that that template works
But perhaps it's not happy with an empty list. Try adding |default('Nothing', True) before |list
Why are you surprised it works? What looks wrong to you? When I use the Developer Tools to evaluate this:
{{ states | selectattr("entity_id", "search", "node_status") |
selectattr('state', 'in', 'dead, unavailable, unknown') |
map(attribute='entity_id') | list }}
I get the list of entities that I expect to get, but I get nothing for the sensor's state.
That the comma-delimited string is properly interpreted as a list. But it does work
Try what I suggested
It worked! Thanks ... but why????
Because it was an empty list
A state of [] or None is, I suppose, considered as unavailable
But it's NOT empty. Now it is returning the list of the nodes that need pinging.
If it now says 'Nothing', then it was empty
It wasn't empty. https://www.screencast.com/t/bJMF5Q4SxnC
I would use this instead:
{{ states | selectattr("entity_id", "search", "node_status") |
selectattr('state', 'in', ['dead', 'unavailable', 'unknown']) |
map(attribute='entity_id') | default("Nothing", True) | list }}
did the state become "Nothing"? then the template was returning an empty list
When using Discord's Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Use Shift + click on the Reply option, or click @ ON to @ OFF to stop this - on the right side of the compose bar.
You have to change this every time (thank the Discord devs for that).
Now I'm confused
there's no reason that adding that default() part would suddenly cause the state to reflect a proper list of entities
Me too. The sensor returned "Unavailable" until I put that default in. Then it returned the proper list of dead zwave node_status entities.
When using Discord's Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Use Shift + click on the Reply option, or click @ ON to @ OFF to stop this - on the right side of the compose bar.
You have to change this every time (thank the Discord devs for that).
please, stop
no, that's not what the bot message says
it doesn't say "type @off"
anyway, adding default() to that template won't, by itself, cause it to suddenly start working. It's possible that you also reloaded template entities, which fixed a problem in the template that was currently loaded
(Tried the Shift + Click on Reply ... hope that got it) Well, reloading Templates would make the sensor disappear, while restarting HA made it appear, so I have been restarting HA after making any changes to the templates.yaml. And adding the default DID suddenly make it work. In fact, the automation that uses the sensor ran, and brought all the devices back to life that it could. Right now, I'll take it. Thank you so much!
Switching from the old z-wave integration to the new zwave_js has been quite the time-consuming adventure.
It looks like zwave_js.ping is deprecated now. That's a big mistake, because it's going to break a lot of folks' automations that seem to be needed for keeping zwave nets running these days. Using the button press is going to require a bunch of string manipulation to go from the node status entity names to the button entity name. Can you direct me to where I should ask that they keep the old ping service available too?
Hi all. I'm trying to get the description of the weather from a weather sensor:
forecast:
- detailed_description: >-
Mostly sunny, with a high near 78. Southwest wind 12 to 15 mph, with gusts
as high as 23 mph.
However, this: The forecast is currently {{ state_attr('weather.xxxx_daynight', 'forecast').detailed_description }} doesn't give me the decrscription. Am I doing something wrong here?
Hi there, I have some trouble with getting a button to work properly with a template in it: https://www.codepile.net/pile/VDLa16ny
The tap_action does not work. It gives me the error message: Failed to call service button/turn_off.Service not found.
I'm afraid I'm overlooking something pretty simple, but after a whole day of struggling with this button, I'm at a loss.
Well, thats what I thought but I don't see an entity in the shelly integration.
templates aren't magic, so the first step is figuring out how that state is represented
hmm, after looking at this a bit, it does look like there are some disabled entities by default
not sure why the integration would disable them.
Hey guys, I have a script that I want to repeat every 5 minutes. How can I do that?
make an automation with a time_pattern trigger
you can't put a trigger on a script. that's an automation
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
you already have a repeat in there
what do you want to do?
It also looks like you're trying to recreate an alert based on some code you found somewhere π
If one of the entity-s temperature is above 23 say in on the nest
But I want it every 5 minutes
you can simply add a - delay: '00:05:00' at the end of the sequence: block
but you should really look into making an alert instead
and if you want it to trigger, then you should rewrite it as an automation
you don't have a trigger there
if you wrote some automation with a numeric_state trigger, then that's how it works
How can I do that, say every 5 minutes that somewhere the temperature is above 23
again, you really want an alert
Ohh okay
Thanks for you reaction. I do however see 'toggle' everywhere on the tap_action. If I read the custom button card I also do not find the press action mentioned.
I have however tried to insert the press command on the action: press, but it won't do anything.
Error message is gone though.
"press" is a service call
tap_action:
action: call-service
service: button.press
service_data:
entity_id: button.whatever
Gonna try that now
some actions have shortcuts, like toggle, and act on the entity you assigned to the button-card. Others you have to code manually
Alright. Strange thing for me to get is that a the same button with the normal button card does work, although then I'm not able to check for the state of another entity to color the button.
I get a new error message based on this though.
'must contain at least one of entity_id,device_id,area_id'
name: Poort
icon: mdi:gate
show_icon: true
tap_action:
action: toggle
entity: button.doorstation_1ccae37421ec_relay_1```
this works
But I want to use a template to figure out with another sensor if the gate is open or not
it doesn't really make sense
and then color the icon and change the label
I agree
maybe they special-case it. custom button card is not a core card
no you're right. And as the template is working, probably I should find a better spot to get it sorted.
Just pulling my hair out on this one
what I suggested should work fine
I made a mistake in the copying of your code. I put in service-data ....
Found it by trying your solution on another piece of code which I made this afternoon to see if I could prevent the use of a template.
That now works and that made me re-look at the templated code.
Thanks so much!!!
I have put both solutions here: https://www.codepile.net/pile/VXOw0PXZ
Not sure which would be the better one, but I like the simplicity of the second.
I'm trying to add a binary sensor from an MQTT topic. I need to have a condition on the transmitter ID and as as the status. Can I have an "and" in a value_template?
{% if value_json[0].txid == '12674812' and value_json[0].message.payload.status.alarm1 == 'true' %}
Yes
The JSON payload is enclosed in []'s, [{"txid":"12674812"}], how should I refer to the first item in the array in the template? Should I be using something like value_json.data[0].txid?
{{ value_json[0].txid }}
That got it, thank you!
I'm writing a template sensor which calculates my electricity bill based on tariffs here. For the unit_of_measurement, is it possible for me to somehow invoke the currency setting defined in configuration.yaml ?
Another question: how do I obtain the timestamp of "noon on the most recent 11th day of a month" and "noon on the next 11th day of a month" .... anybody have any ideas?
What would be the most recent 11th day of the month today? 22nd of February?
11th of Feb
oh okay
and what time should the timestamp be? 00:00?
@trail ginkgo and what do you want previous and next to be on the 11th of the month, so in 4 days basically, when it is the 11th of March
No I mean at noon π
Oops
I mean noon 12:00
I basically want to know how far along I am on a scale between the prior and upcoming β11th at noonβ
Ah, that is important information
But I see you mentioned that already
I missed that
Iβve tried faffing around in the template page but I canβt get anything reasonable to work. On the command line with date itβs easy, but I prefer using a template sensor.
{{ now().replace(month=now().month-1,day=11,hour=12,minute=0,second=0) }} last month
{{ now().replace(month=now().month+1,day=11,hour=12,minute=0,second=0) }} next month
No, that won't work, that will give feb and april now, he needs feb and mar
and next week, he needs mar and apr
I just finished this:
{%- set check_value = today_at('12:00').replace(day=11) %}
{%- set days_prev_month = (today_at('00:00').replace(day=1) - timedelta(hours=1)).strftime('%d') | int %}
{%- set prev = check_value if now() > check_value else check_value - timedelta(days=days_prev_month) %}
{{ prev }}
{%- set check_value = today_at('12:00').replace(day=11) %}
{%- set days_this_month = (today_at('00:00').replace(day=1).replace(month=now().month +1) - timedelta(hours=1)).strftime('%d') | int %}
{%- set next = check_value if now() < check_value else check_value + timedelta(days=days_this_month) %}
{{ next }}
It would have been easier if timedelta works with months π
Yeah.
replacing months also doesn't work when you add 1 to the 12th month, or remove 1 from the first month I guess, and with replace years is not supported
Oh yeah. I've had that issue before.
So that's why I came up with this, which seems to give the result I think @trail ginkgo expects
Sorry I didnβt hear any pings until now π
Just as well. My attempt was no good.
It also works with in December or January
as it uses timedelta, so on the 12th of December it adds 31 days to the 11th of December at noon, resulting in January 11th 2023 at 12:00
Let me go to my computer and play with this a sec
{% set prev_timestamp = as_timestamp(prev)|int %}
{% set next_timestamp = as_timestamp(next)|int %}
{% set prev_next_delta = next_timestamp-prev_timestamp %}
{% set prev_now_delta = as_timestamp(now())|int-prev_timestamp %}
{{ prev_now_delta/prev_next_delta }}
using your code with the above, gets me % of time completed
whats the difference between {% and {%- ?
whitespace control
but I do need to change something, the days_this_month won't work in December
that feels right
"Based on usage pattern this billing cycle so far, you will be ending up with a bill this high"
That is so awesome.
Thanks, @marble jackal and @fossil venture !
wtf is that number you pay in rusian rouble?
thai baht, i live in thailand
1.5 million thai baht is about $30k
i dont actually use 282000 kWh ... thats the result of playing around trying to get utility_meter working and the utility_meter.reset service not showing up and me just shrugging because its a lost cycle anyway
You should change the template to this:
{%- set check_value = today_at('12:00').replace(day=11) %}
{%- set days_prev_month = (today_at('00:00').replace(day=1) - timedelta(hours=1)).strftime('%d') | int %}
{%- set prev = check_value if now() > check_value else check_value - timedelta(days=days_prev_month) %}
{{ prev }}
{%- set check_value = today_at('12:00').replace(day=11) %}
{%- set days_this_month = ((today_at('00:00').replace(day=28) + timedelta(days=5)).replace(day=1) - timedelta(hours=1)).strftime('%d') | int %}
{%- set next = check_value if now() < check_value else check_value + timedelta(days=days_this_month) %}
{{ next }}
no sorry, $50k
The days_this_month will not work in December with the other version
@slate tundra i dont actually use 282000 kWh ... thats the result of playing around trying to get utility_meter working and the utility_meter.reset service not showing up and me just shrugging because its a lost cycle anyway
ha i got scared a bit π
@marble jackal Code replaced! Thanks so much π
@slate tundra Meter cycles on the 11th, so from that moment on this will hopefully be reliable data. utility_meter can be given an offset when the month resets to 0. The energy bits dont.
i used the meter in the past too
So I use the whole-home power monitor in two ways. Feed the data into the energy page for nice graphs and data insights, and into utility_meter for the bill tracking.
but i've use it for other propose, to calculate kW/h
thats what the energy tab does now, if i understand you correctly
yep
@marble jackal Thanks a lot!!!
ofc u can use utility meter for other stuff too even for statistics (how many times a door open last month, as example) :))
idd π
Hehe, another one here!
I know, I saw your github π
Sometimes π
While we're still here, made some small improvements π
{%- set check_value = today_at('12:00').replace(day=11) %}
{%- set days_prev_month = (now().replace(day=1) - timedelta(days=1)).day %}
{%- set prev = check_value if now() > check_value else check_value - timedelta(days=days_prev_month) %}
{{ prev }}
{%- set check_value = today_at('12:00').replace(day=11) %}
{%- set days_this_month = 31 if now().month == 12 else (now().replace(month=now().month+1, day=1) - timedelta(days=1)).day %}
{%- set next = check_value if now() < check_value else check_value + timedelta(days=days_this_month) %}
{{ next }}
days_prev_month and days_this_month
Using a timedelta with days now, instead of hours, removing the need to use the time at 00:00 and also added an check for December in days_this_month removing the need to juggle with adding and removing days like I had before
and replaced strftime('%d') with a simple day
YOu've spent more time with jinja than i have! π
Trying to migrate some messy automations into binary sensors for landscape lighting based on: Time of day, nightly arrivals, and now if there's severe weather. But I'm stumped on converting events to a binary sensor.
But the documentation regarding that isn't clear: https://www.home-assistant.io/integrations/template/#turning-an-event-into-a-binary-sensor
Like, how do I tie an event to a particular sensor?
Ideally I'd like a list of persons that on entering home to fire an event that sets a Recent Arrival sensor that auto-offs after some set time.
You may be able to fix the energy values using this method https://community.home-assistant.io/t/how-to-fix-statistics-data-e-g-energy-data/360966
I think I figured it ```yaml
- trigger:
platform: state
entity_id:
- [People Here]
to: home
binary_sensor:- name: Recent Arrival
auto_off:
minutes: 5
state: "true"
- name: Recent Arrival
@fickle gale posted a code wall, it is moved here --> https://hastebin.com/xezodihovo
The whole finished thing is ate by that bot if you want to check it.
Hm, I have made a template sensor, but its not showing up in HA after restart and I cant figure out why...
Tried the template debugger and it shows the value I want, so it's working.
sensor:
kostnad_vp_per_time:
friendly_name: "Kostnad VP per time"
unit_of_measurement: "kr"
value_template: >-
{{ ((states('sensor.shelly_vp_timesforbruk')|float)
*(states('sensor.nordpool_kwh_oslo_nok_3_10_025')|float)) | round(2)
}}
That >- looks like it might cause trouble. >?
so you dont need that?
I've been using > for my templates.
hm, no difference..
The - is for whitespace control, but the result will be the same
Ah.
Does the template return a result in
> templates
Looks like they might've.
Hm, I have made a template sensor, but its not showing up in HA after restart and I cant figure out why...
Tried the template debugger and it shows the value I want, so it's working.
@oak moth posted a code wall, it is moved here --> https://hastebin.com/qiqefosako
Looking at the docs, the way you seemed to defined it is the legacy format. Maybe try something like this: ```yaml
template:
- sensor:
- name: "Kostnad VP per time"
unit_of_measurement: "kr"
- name: "Kostnad VP per time"
Corrected from value_template
state: >-
{{ ((states('sensor.shelly_vp_timesforbruk')|float)
*(states('sensor.nordpool_kwh_oslo_nok_3_10_025')|float)) | round(2)
}}
Repeat the same edits for everything else.
Aaah, thanks
If you need kostnad_vp_per_time for any reason, you can add unique_id: kostnad_vp_per_time
But "Kostnad VP per time" will become "kostnad_vp_per_time" regardless.
Oh, true. I'm a bit drowsy and didn't pick up on that.
thats the punishment for copying old code π
but, learned something new today, thanks again β€οΈ
No problem.
hi guys! i am trying my first sensor template like the following one :
- platform: template
sensors:
home_total_w:
friendly_name: 'Total Energy'
value_template: "{{ (
(states.sensor.lavastoviglie | float) +
(states.sensor.forno | float) +
(states.sensor.induzione | float) +
(states.sensor.asciugatrice | float) +
(states.sensor.lavatrice | float) +
(states.sensor.condizionatore_mitsubishi | float) +
(states.sensor.condizionatore_samsung | float)
) | round(3) }}"
but i dunno why is showing 0 while the sensors are populated
does anyone can give me an help on that?
Well, if it is your first template sensor, you might want to use the new template sensor format, instead of the legacy format you are using now
besides that, you are also incorrectly using an method to get the state which is advised against
π thanks, can you please refer the new template sensor format?
is there any first citizen object for getting the sum of multiple sensors?
To use what you have now, you need to add .state after all the sensors.
But, you should use states('sensor.lavastoviglie') instead of states.sensor.lavastoviglie.state
you can do this right now
And here are the docs for the new format: https://www.home-assistant.io/integrations/template/
{{ expand('senxor.1', 'sensor.2', ... etc) | selecattr('state', 'is_number') | map(attribute='state') | map('float') | sum | round(3) }}
this will also fallback in case of error to the zero value of the type?
it removes non-numbers, so you'll get a lower sum
Coming up to the 11th and donβt have much data for the past month. So itβs all good. Thanks for the suggestion.
how do I subtract 5 minutes from "{{ states('input_datetime.sleep_time') }}" which is "22:00:00"
i need to do an alert 5 minutes before that time using input_datetime.sleep_time
use this as an automation trigger
- platform: template
value_template: >
{{ now() >= today_at(states('input_datetime.sleep_time')) - timedelta(minutes=5) }}
Hi, I was hoping some one could help, I would like to play random music from my media folder on my RPi, I canβt seem to figure out the right yaml, can someone help, thank you
@mighty ledgeis a trigger so {{ today_at(states('input_datetime.damian_sleep_time')) - timedelta(minutes=5) }} without now() works great
ty man
i want to trigger at that time, and 5 mins before
5 mins before to announce and at the time of input_datetime to turn off lights
so can be used without now()
or it has to be like that to give true, false
This will return a datetime object
For a template trigger it needs to be true or false
So you need to compare it to now()
just make a second trigger with the same syntax but remove the - timedelta(minutes=5)
you can put an id on both triggers and then use choose with a trigger id condition to call whatever service you want
you can use the folder integration to get the contents of the folder, and then use that to choose one of the files in the folder
You stated {{ today_at(states('input_datetime.damian_sleep_time')) - timedelta(minutes=5) }} would work great for a trigger, but it will not, as it will return a datetime, and not a boolean.
But maybe I'm missing something here
i dunno, this is why i am asking, will this work?
trigger:
- platform: template
value_template: "{{ today_at(states('input_datetime.damian_sleep_time')) - timedelta(minutes=5) }}"
id: "school_day_announce"
- platform: time
at: input_datetime.damian_sleep_time
id: "school_day_off_lights"
yeah
well, platform: time using at with an input_datetime will also work
so, what you have should work
er, no, you need the now() >=
sorry
just use my template from above as-is
Hello, I've been sent here from the automation channel.
basically I can monitor the power usage of a dishwasher and I would like to create some variables that are visible in the dashboard starting from that.
I would like to know where I can find some documentation/the name of the process I need to follow in order to do that
I will check those, I'm quite new and I don't really know what is the proper name of the thinks I'm looking for haha
I recommend checking the pins posts in channels as well π
@upbeat swiftfrom what i've understand if you want to display that dishwasher power usage on the ui then i think you need this: https://github.com/custom-cards/secondaryinfo-entity-row
mhh looking at the templates, I need to have a list of possible states (heating, first washing, etc) so that I can pick them in the automation page
but mostly people use binary sensors
like I can set W>90 and have the sensor output dishwasher on
otherwise output dishwasher off
I use an input select and the power usage cycles me through that as it goes
it there anyway i can dynamically change a rest resource? or insert a template value to change a URL dynamically.?
- resource: https://statsapi.web.nhl.com/api/v1/game/2021020886/linescore
scan_interval: 2
sensor:
2021020886 is an ID that changes
resource_template
is it possible to import array of values (lets say separated by a , ) as attributes of a sensor. Have a bash script on remote server that can export some (all int) in any format needed however i cant find any examples on how i can achieve this via REST or the command_line platform.
it's easiest if you pass the payload as JSON
example from the docs to use a REST API and parse the JSON results into state and attributes: https://www.home-assistant.io/integrations/sensor.rest/#fetch-multiple-json-attributes-and-present-them-as-values
specifically, this bit:
sensor:
- platform: rest
name: JSON users
json_attributes_path: "$.[0].address"
json_attributes:
- street
- suite
- city
- zipcode
resource: https://jsonplaceholder.typicode.com/users
value_template: "{{ value_json[0].name }}"
thank you
When a function says it can be used as a filter, can it filter lists of items? For instance should something like this work?
{{ area_devices("living_room")|device_entities }} (I'm aware of area_entites())
no
it just means you can use it as a filter
device_entities('device_id') vs 'device_id' | device_entities
that method/filter still only takes 1 argument
you can however map it, but you'll have a list of lists
heyya petro
got a brain twister: {{ states("input_select.rgbcolors") }} returns unknown
ok?
rgbcolors is an input select of several colors... none of which is unknown. what am I doing wrong
?
if it's showing unknown in template editor, then you've got the wrong entity_id
ok, than ks
related to parsing out REST attributes, is there a good way to handle an arbitrary/unknown number of attributes? it seems like the json_attributes assumes a known list of key names
id look for spelling errors, like rbg instead of rgb... not that i've done that before
(i have)
put them inside a single attribute
that was it RBG colors
yep, pretty standard when dealing with rgb
@mighty ledge Thanks, will look into mapping
Also I just noticed there's a function called device_attr. What exactly is a device attribute? I thought only entities have attributes
they are attributes that devices have
basically, info that's stored in the device registry
like mfg, what integration, other crap
what do you mean? i don't want to predefine the attributes. to be clear, i'm trying to create sensors to track version uptake of my custom component: https://analytics.home-assistant.io/custom_integrations.json
right, so you predefine a single attribute that's a dictionary of values
Ah yeah I can see now from the websockets API. They have things like manufacturer, model, area, etc.
Interesting an entity has a device class but a device doesn't lol
{'x': { all your dynamic crap }}. Then when you make your rest sensor you specify x. And when accessing your dynamic attributes, you'd get x and then get an attribute in x. I.e. states.senxor.xyz.attributes.x.<whatever>
it was named before devices existed
too late to change it now
petro: Changed the input_select name, and automation is rotating the colors, but state template is still returning unknown, with correct name
ah i see. testing... π
Can you post the full config
one sec.
@pine musk posted a code wall, it is moved here --> https://hastebin.com/ewumedufip
thanks hassbot
Still have it reversed
Either in the template or in the target but they are different
@pine musk posted a code wall, it is moved here --> https://hastebin.com/iberoviwiv
yah, so whats the problem now then
this worked perfectly, thanks!
now the trick is how to visualize the attributes in the frontend
the states(input_select.rgbcolors) is still coming up unknown
Is input_select.rgbcolors the correct entity ID?
now giving test: 'unknown'
Where is this at? Developer tools > template?
tyes
Double check the entity ID then
I did
hey, anyone who can help me create numeric state / template sensor to capture avrerage future price from nordpool sensor attribute https://pastebin.com/nzSM2zh4
What is the state of input_select.rgbcolors right now? check at developer tools > states
its the "today:" part, next 3 hours avrage
no clue how it can still be unknown.
especially if it's working for the turn_on service call
it is not working for the turn on call
Then you've got the entity ID wrong somewhere
Hi all, I'm seeking help to solve the following.
I'm trying to use a binaiy sensor to calculate the difference between in- and outside temperature in config.yaml:
- binary_sensor:
- name: "LWP binnen"
state: >
{{ states('sensor.gem_temp_bg')|float > states('sensor.masterbedroom_outside_temperature')|float }}
- name: "LWP binnen"
- binary_sensor:
- name: "LWP buiten"
state: >
{{ states('sensor.masterbedroom_outside_temperature')|float > states('sensor.gem_temp_bg')|float }}
- name: "LWP buiten"
At this moment I'm receiving errors in the log, like:
Template warning: 'float' got invalid input 'unavailable' when rendering template '{{ states('sensor.gem_temp_bg')|float > states('sensor.masterbedroom_outside_temperature')|float }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
Template warning: 'as_timestamp' got invalid input 'None' when rendering template '{{ ( as_timestamp(now()) - as_timestamp(state_attr('automation.heating_on_outside_temp', 'last_triggered')) | int(0) ) > 3600 }}' but no default was specified. Currently 'as_timestamp' will return 'None', however this template will fail to render in Home Assistant core 2022.1
Oh joy
https://www.home-assistant.io/docs/configuration/templating/#numeric-functions-and-filters This explains how to set a default
I'm having trouble understanding how to operate on lists. For instance, if I have the following template, how could I operate on each list entry?
{{ area_entities("living_room") }}
Such as filtering them by entities that start with "binary_sensor" or calling device_id() on each entry
you have to map each result
I understand the concept of mapping/filtering, I just don't know how to translate that into a jinja template
{{ area_entities("living_room") | select('search', 'binary_sensor') }}
when i say map, i mean map
{{ area_entities("living_room") | map('device_id') }}
Oh interesting, so the first param is/can be the name of a function? I assume the next is the param to that function?
no, it has to be a filter
Alternatively you can let it invoke a filter by passing the name of the filter and the arguments afterwards. A good example would be applying a text conversion filter on a sequence:
Users on this page: {{ titles|map('lower')|join(', ') }}
By that you mean functions documented saying they "Can also be used as a filter."?
filters and functions are not always shared
Or just other native filter functions
they are different
a function can be a filter, and a filter can be a function. But it depends on the filter/function if that's allowed
I see. So the fact that they are filters is actually just a name overlap but there's no connection?
right
if there is a filter that's identical as a function, then they are usable in both places
check out the 4th pin
does_something(arg1, arg2, arg3) if usable as a filter will be arg1 | does_something(arg2, arg3)
the only way to know if you can use a function as a filter is if the docs say you can
that's it
Anyone care to nudge me in the right direction regarding what I'm doing wrong if I'm still getting alot of decimals with: value_template: "{{value_json / 60000 | round(1) }}" ?
There is so much info on that page and I'm not really a programmer so I'm seeking al little more help. Can somebody please be so kind to help me with this?
Bummer, state_attr isn't a filter. Was hoping to filter entities by their device_class
Anyways, filters are a bit of a shortcut anyways, right? I can just do a normal loop inside a template too I believe?
you rarely need state_attr as a filter
expand
can you just ask what you're trying to do
For sure, but I appreciate you explaining the details so I have a deeper understanding going forward.
I'm trying to get motion sensors by area. So given an area, what motion sensors are in there. At least for now assuming there's only 1
right but what are you trying to get from that?
I don't understand why you want device_id in there too as well as state_attr
Just read the blue box exactly where the link drops you off
AND your warning messages.
Oh I think how I mentioned device_id earlier that was me just playing around with how things worked. But I guess the high level explanation of what I'm trying to do is automate turning on/off lights based on motion in an area with support for different timeouts per area. So rather than write an "automation" (actually doing this in node-red) for each room or each sensor, I want to write something generic that will apply to all areas. So a motion or turn_on event would trigger it and it would get that sensor or light's area, associated motion sensor by area (if it's a light) and determine actions to take on the light.
I don't think you'll be able to make anything generic like that
you'll need separate triggers
unless you listen to all state changes and apply a condition
I think I should just need two triggers, one for light-on events and one for motion events
you'll still need multiple automations for that as well
yeah but you'll need to list out all then sensors or lights for both of those triggers
its working now... just found friendly name, causing problem
there's no way to make a generic trigger for something like that
I'm not sure what you mean by generic trigger?
a trigger without listing the entity_ids
In node red there's the "all events" trigger node
yes, but then you have to filter based on that, which means a separate automation for each 'filter' if you want it to continue
you can attempt to lump it all together with a choose
in one automation, but you'll still have everything "separate"
Oh well like I said I'm doing this in node-red
Using an automation you're probably right
I still don't understand it; both entity's are returning a number and logs says invalid imput?
I wouldn't even attempt this in an automation probably lol
at startup they are not numbers, that's when the error occurs
I just recently migrated basically all my automations over to node-red and have been deep diving since
I don't see how a template will help then, because node red wouldn't use the template
Yeah. At some point they returned unavailable. That's when that warning appeared.
so when system is started the binary sensors should be working correctly?
Not sure what you mean? Node-red has support for rendering HA jinja templates
i did not know that
Until they don't. It never hurts to have a default.
Not sure if it's something new since I just started using it but it's one of the handful of HA-specific nodes
It also supports JS, right?
i've never used node-red and always thought they used JS
Just figure out how you want the sensor to react in case one or more of them are unavailable, and then set one to float(default=1) and the other to float(default=0).
@atomic blade eitehr way, the only templates you need are the entity_id's associated with your area.
{{ area_entities("living_room") | select('search', 'binary_sensor.') | list }}
{{ area_entities("living_room") | select('search', 'light.') | list }}
and possibly check to see if the entity_id is in those lists
{{ entity_id in area_entities("living_room") | select('search', 'binary_sensor.') | list }}
oh snap, auto-complete just popped up for me in the template editor
i no longer have to use the only entity_id I remember when helping people
which is light.living_room
if you asked me any other entity_id in my system, I would draw a blank without looking at my config
Lol, same. switch.fr_table_lamp for me
I think I can type out the lights in the demo integration in my sleep... ```yaml
- light.bed_light
- light.ceiling_lights
- light.kitchen_lights```
That's what I use for all demos.
I don't use the demo integration on my production system tho
that's all I have access to at work
but i'm totally working
xkcd 303
Well there are other binary sensors in areas that aren't motion sensors. So I need to look for device classes of occupancy and motion (I have aqara and hue sensors)
then simply add that to the generator
that will require expand though
Generator?
I interpretate the message that it isn't supported anymore and should use somethng different, right?
{% set entities = area_entities("living_room") | select('search', 'binary_sensor.') | list %}
{{ expand(entities) | selectattr('attributes.device_class', 'in', ['occupancy', 'motion']) | map(attribute='entity_id') | list }}
a generator is the result you get when using filter on a list (typically)
this is why you need to add | list to get a list of the entity_ids
Ah selectattr
you could approach this differently and completely skip the filter of binary sensor
True
{{ expand(area_entities("living_room")) | selectattr('object_id', 'eq', 'binary_sensor') | selectattr('attributes.device_class', 'in', ['occupancy', 'motion']) | map(attribute='entity_id') | list }}
the only time you should need to loop is if you're comparing a string to a number, other than that, you can always use filters
Family Room π
damn
Is the family room in the front?
It is not
@mighty ledge Sorry I tried π
Also thanks for the templates. I think I need to wrap my head around expand. For some reason that one always confused me
it's the thought that counts
It takes a list of entity IDs and converts them into State objects
I think object_id here should have been domain?
ya
Also generally how performant are templates? I'm a little worried about doing a lot of processing for my light-on actions because of a potential delay
I've had some ideas of creating a cache in node-red (not sure how I'd do this yet) since a lot of these things don't need to be real-time. For instance, the output of this template isn't going to change often since it only changes when devices are added and such. I know there are device/entity registry events even I could listen to
they are fast if you use stick to generators before applying list
even then, they are still fast
Yes, I have automations that create groups on startup or integration reloading
Thanks again. Think I got my automation squared away
Maybe I shouldn't have spent so much time on this automation cuz it's kinda something I shouldn't need. It's just necessary cuz of how I set my scenes. I update brightness/temperature throughout the day as it gets later and it was annoying how lights would turn on that weren't on before
Hate to be a bother again, is there anyway to dynamically set the scan interval of a resource or template resource based on a sensor state?
Some sensors accept a scan_interval: option. Otherwise, use a time pattern trigger
yea. so this one does, but can it dynamically be changed based on another state value.
- resource_template: https://statsapi.web.nhl.com/api/v1/game/{{ states.sensor.flames.attributes.get("game_id", "") }}/linescore
scan_interval: 2
Yeah, unfortunately not
can i change scan_interval: 2 to say 300
The hacs intergration i am using does this in py, i was just wondering if i could somehow do it in templates
You could use a time_pattern trigger and a configurable delay
to trigger the rest call, instead of an interval your saying
so my goal. if game = active. scan interval should be 1 second. if game = notactive scan interval = 300 seconds.
so i am not hammering the API during non game time. ,
Trigger every second or 5 seconds whatever, homeassistant.update_entity, then delay based on an input_number
Then you should just use a condition based on whether a game is on
No, you don't send a delay as payload
oh
You update an entity with that call and then add a delay as a separate step
the update entity service call replaces the scan intrval
Or...use a condition instead
Effectively
Yes
You would want to set the scan_interval to a big number to make sure you're controlling the interval
ill look it up
ahh okay.
so like set it 600
but then trigger it howerver often i want
based on automations
cool beans
ill look up time patterns
thanks man!
appreciate it again.
okay so sorry. since time pattern is a trigger.
i would need to set multiple automations and enable disable the different automations based on a sensor value?
like activegame scanner to scan every 1 second, or nonactivegame scanner to scan every 600 or whatevers?
or wait.. i can just use the built in scan interval as the default longer non game value, and then trigger more frequently during game time.
how hard would it be on CPU to trigger with automations rather than a scan_interval is there any overhead difference?
Hey, I have a sensor with values from 1 to 50. If it's > 1 it should show "x days". When it's ==1 it should say "1 day". How do I have to set the value_template?
{%- set state = states('sensor.your_sensor') %}
{{ state ~ (' day' if state == 1 else ' days') }}
That's simpler than I thought. Thank you!
Is it possible to build a template once and then use it for multiple sensors? Or do I have to produce duplicated code?
If you're doing everything in yaml and in the same file you can use node anchors.
nice hint, thank you
That is one nice list of tricks!
But if you refer to a different sensor every time, you will need to set up variables.
Automation 1:
action:
- variables:
entity: sensor.your_sensor
message: &template "{{ states(sensor) ~ (' day' if states(sensor) == 1 else ' days') }}"
Automation 2:
action:
- variables:
entity: sensor.your_other_sensor
message: *template
keep in mind that those anchors only work in the same file
Hi, is this where you make the folder into a sensor? if so i have done that, whats my next step to use it to accses random music files in a timed automation
@tardy jewel Something like: {{ state_attr('sensor.your_folder_sensor', 'file_list') | random }}
Oh man, I had not added anything (manually defined template sensor, binary_sensor) in a long time and I could not get my new additions to work. so i looked at the docs and what do you know, the sensor definition format changed?!?! When did that happen??
some time ago, but the old ones still work
They are mentioned on the bottom of that page (as legacy format)
But the trigger based templates were introduced in 2021.4, so the format exists at least that long (almost a year now)
thanks! I was able to find the call service -> input select
I already created a helper but I wasn't able to access it before
thanks a lot, there are a ton of integrations that do not support the new format, so the realization that this all changed was a little surprising. Since I hadn't needed to make changes to those sensors or wanted to add new template sensor driven automations, I was caught off guard. thanks for the response
I'm not sure what you mean here, other integrations don't care how a sensor is created. The only thing is that the new format supports more attributes like state_class which you could also add using customize
You can still use the old style. You're most likely screwing up the old style format when you added your additional sensors.
Thanks for the response, I added all my new sensors with the new formatting. the code checker in vscode was screaming at the whole time when i used the old format.
That's a bug in the VSCode HA extension, the code was probably fine
that could very well be. I wanted more control over individual integrations/custom component configs anyway, so I split most of it out to packages (ex: switchbot, ping, unifi gateway, worldclock, calendar based alerts, etc..). This pilled all the parts (sensors, input_booleans, etc) into one place per integration.
Hey All, back again w another question on templating
im currently using the 4 button zha hue remote blue print to control my lights
I use the following template to control the brightness of only lights that are on
data_template:
brightness_step_pct: -10
entity_id: >
{%- set lights = [
states.light.living_room_desk,
states.light.living_room_lamp,
states.light.nanowall,
states.light.tv1
] %}
{{ lights | selectattr('state','eq','on') | map(attribute='entity_id') |
list | join(',') }}```
my question is how cna i encorporate this template to give me a dynamic list based on srea then based on state
`{{ states.light|selectattr('entity_id', 'in', area_entities('Living Room'))|map(attribute='entity_id')|list }}`
You were almost there:
{{ states.light | selectattr('entity_id', 'in', area_entities('Living Room')) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
BTW data_template has been depreciated a long time ago, just use data
How would I do this in hours rather than seconds?
"{{ (now() - states.climate.master_bedroom.last_updated).seconds > 20 }}"
How many seconds are in an hour?
3600 but I wasn't sure if it could be changed to hours rather than using seconds
Nope, you just divide
Alright thank you. Is it possible instead of just looking at last updated or last changed to specify a state such as last_updated to cool?
Check for both last updated and the state:
"{{ (now() - states.climate.master_bedroom.last_updated).seconds > 20 and is_state('climate.master_bedroom', 'cool') }}"
Would that be able to tell me that in the last 20 seconds it was switched to cool? I'm trying to track whether a door was opened in the last 5 seconds. But I don't just want to see last updated as it doesn't tell me if it was on or off.
No, in this case it will tell you that is had been on cool for at least 20 seconds. But what you now ask can be done in similar way
How would that work because the door would be closed already presumably open for a second or 2 then closed. I just want to know if it was opened specifically in the last 5 seconds. A door could be left open and then closed which Is why I am trying to see if this is possible as last changed wouldn't work
Ah, like that. You could create a trigger based binary sensor which goes on when the door opens, and has an auto_off of 5 seconds
How would I do that?
Thank you
Would I need the platform: time_pattern? I took that from the home assistant docs.
- trigger:
- platform: time_pattern
hours: 0
minutes: 1
sensor:
- unique_id: Daniels_Bedroom_Door_Last_Opened
name: "Daniels Bedroom Door Last Opened"
state: '{{ is_state('binary_sensor.daniels_bedroom_door_sensor_access_control_window_door_is_open','on') }}'
device_class: "door"
auto_off: 120
@silent vector No you need a state trigger on a state change from off to on for the door sensor
And you need a binary_sensor
template:
- trigger:
- platform: state
entity_id: binary_sensor.your_door_sensor
from: 'off'
to: 'on'
binary_sensor:
- unique_id: Daniels_Bedroom_Door_Last_Opened
name: "Daniels Bedroom Door Last Opened"
state: true
device_class: "door"
auto_off: "00:02:00"
I see thank you.
Hi all, hoping someone can help a beginner like me with what I assume is an easy script. I mistakenly posted in the automation channel and was directed here. I want to create an automation/script that will announce when entities are on ... So for example if three lights are turned on... I would like "Alexa" to say "kitchen, bedroom and garage lights are on" sorry for the newbie question.... ( I have Alexa tts working)
I've looked at the documentation.... I just need a push in the correct direction...I'm confused about how templates...does the template constantly check for state change in background....or is it created and then inserted into an automation?
I dont know if I am on the right topic, redirect if not.
I have renamed binary_sensor.updater and it dont go so well.
I now have one renamed Entity as Integration "Updater", and onw Entity with my old name as Integration "Binary Sensor".
Anyone know how to fix this?
Templates are used in automation actions are resolved when the action is performed. Template sensors update when the sensors that they use update.
{{ sensor.light | selectattr('state', 'eq', 'on') | map(attribute='name') | list | join(", ") }} lights are on.
delete the entity that is the wrong one
aa got it. How would I ask home assistant to remove these entities when they're off but not announce it. and add them when they're on and announce it. Would I create a second automation without a TTS action?
Can anyone please help me with a template please?
I need to plot the brightness of a light as a history graph.
I have a template I was able to make from some into I found, but all it does is give a constant "0"
- sensor:
- name: "Bedroom light brightness graph"
state: >
{% if state_attr('light.bedroom_bulb_3', 'brightness') %}
{{ state_attr('light.bedroom_bulb_3', 'brightness') }}
{% else %}
0
{% endif %}
you don't need to, just make a service call with the template
use that in your message
no need for a template sensor, unless you want it
so theres nothing to delete
That template will always be zero if the light is off
Cool!!
but is it otherwise correct?
yep
Sorry, but I just so I understand ....when the light turns off it removes itself from the list?
ok, thank you!
read the code left to right outlout, what do you think it does?
remember, it updates when every included entity updates
Honestly I'm nlvery weak at coding, I'm just starting out ... So I don't mean to be frustrating... π© to me it seems like it only joins the list when it's on. If it's off I would assume it doesn't join the list but I don't see where lt would remove itself from the list if it was previously on
... Unless the list starts new each time it's called... I'm not sure if that's the behavior.
You're not frustrating, I'm trying to get you to read it
just say it outloud
literally
left to right
that's all I'm asking
Ok, so the template works, but it shows the brightness as 0-255 instead of percentage
what do I need to add to it, to get it to show me a percentage?
how do you mathematically take 0 to 255 and change it to 0 to 100?
if 255 = 100, then what do you need to do to 255 to get it equal to 100?
Thanks
I could only delete one of them and I think I might deleted the wrong one.
Is there any way to restore binary_sensor.updater?
I don't know how to template. What I have is something I found somewhere and was able to slightly modify, using another template as an example
this has nothign to do with templating. This is 2nd grade math
If I knew what I needed to to, I wouldn't have asked here
what do you need to do to take 255 to make it 100?
devide by 2.55
ok, HOW DO I DO THAT?
what's the division symbol?
i don't care what age you are, you've used a calculator
I'm trying to show you that it's not hard, and that you're putting on what I call the "It's coding" blinders
255 / 2.55
let me rephrase. HOW AND WHERE DO I PUT A DIVISION IN THAT TEMPLATE?
well, what is your brightness?
you're gettijng the brightness out using state_attr(), so isn't that your brightness?
yes
ok, so if state_attr() is your brightness, and 255 is your brightness and you know you need to divide 255 (your brightness) by 2.5.... then where should it go? Keep in mind that your output is between the {{ }}, not the {% %}. {% %} means non-outputting code
also, you can test this all in the template editor
developer tools -> template tab
Asking for help her is always like pulling teeth. Everyone acts like you're supposed to be an expert programmer and no one will even entertain the notion that maybe you're not.
Screw this, it's not worth it.
you're asking for a spoon fed answer, i'm giving you the answer
i literally pointed it out in the exact spot you needed, you'rebeing difficult because you don't want to think
here
{% if state_attr('light.bedroom_bulb_3', 'brightness') %}
{{ state_attr('light.bedroom_bulb_3', 'brightness') / 2.55 }}
{% else %}
0
{% endif %}
those 3 characters were really hard.
I'm not a coder! Which means I don't know how to code. Why is that so hard to believe?
That one edit is simple enough for you, but it's not if you don't know how
you don 't have to be a coder to follow directions and try to learn
you don't want to learn
you want to be spoon fed
there's a difference
i'm done here
Whatever, I'm sorry to have wasted your time with my noob question.
I should just go learn to code
You didn't waste my time. You're wasting your own by not reading what I said
Because otherwise, I'm asking to be spoonfed
I gave you the answer, and you didn't even want to try in the template editor
instead you complained about not being a coder
without even attempting it yourself
that says alot.
You didn't give me a straight answer, you started patronizing me, with the kind of answers one gives to a toddler.
But whatever, I hope it's only you who's this condescending to newbs.
My man, I was not condesending I was asking you questions you should already know the answer to.
math is something we all know
you've used a computer calculator
you know what the division symbol is
I was tyring to get you to use your brain and think instead of throwing your hands in the air. And you started using all caps like a todler. You might need to step back and look in the mirror at who was acting like a child. Another person even helped you with the math and it's clear the other person is a beginner
It's not rocket science, I was just trying to get you to try. But you value your time more than mine, the person helping you.
which is why you didn't like my answers, because it required you to actually do alittle critical thinking.
{{ dict((states.binary_sensor)|groupby('state'))['on']|count }}
How can I filter by entity id wildcard? Want to only count binary_sensor.radio*
You're g oing about it in an odd way
you can select binary_sensors by state using selectattr
and then you can also use seelctattr to filter entity_id's that contain radio
not at all familiar with the syntax or functions, piecing this together via different forum threads
but there's no "wildcard" functionality in select, there's regex, which is a pita
you said the R word. π
count the number of binary_sensors set to on for entites that start with "radio"
example: binary_sensor.radio10003402
it's kind of a neat use case - I'm tracking radio unit ID's in a local P25 trunked radio system
getting these into HASS via restful API
ok
so
regex for starts with is "^radio"
to filter binary_sensors by state (or any entity) by state that is on is selectattr('state','eq','on')
and to use regex with select attr, you use 'search'
selectattr('object_id','search','^radio')
an entity_id's object_id is the ending part of the entity
entity_id = domain.object_id, e.g. light.livingroom
light is the domain, object_id is the livingroom
{{ states.binary_sensor | selectattr('state','eq','on') | selectattr('object_id','search','^radio') | list | count }}
wow, that works wonderfully, thank you for the example and more importantly the explanation. π
np
the other part of this that I'm struggling with is how to assign a unique ID to entities created via restful API
I don't think it supports it
so many forum threads that are dead ends, seems not possible
it doesn't support it, i'm trying to find a workaround
You won 't be able to work around that
seems like a not crazy use case
Unique_id's are for registering entities in the entity_registry. It on ly gives you the ability to change information in the UI. Why are you trying to add it?
Would like to track radios added over time, give friendly names via UI over time as they're identified/validated, etc.
they're ephemeral and lost on HASS restart when creating an entity via rest API
sounds like you'd need a custom integration for that
was afraid of that
thanks for the brain power on the templating, much appreciated
I mean, the rest endpoint is going to be a single sensor but it seems like it's a series of sensors?
I guess I don't understand how you have it set up to get different sensors
are you using a resource template?
no
curl -s -X POST \ -H "Authorization: Bearer TOKEN" \ -H "Content-Type: application/json" \ -d '{ "state": "on" }' \ http://172.16.1.55:8123/api/states/binary_sensor.radio$2 > /dev/null
where $2 is the unitID of the radio, guaranteed unique
this is in a script that's run on an external box on the LAN every time a radio is turned on, it registers with the network
starting small with binary sensor, but there's other attributes that can be tracked as well, such as talkgroup (channel) number the radio is set to, etc.
Anyway, will look into resource templates π
thx again
inexperience?
this is day one of kicking the tires on this, thought was to start easy with on/off
see how badly the 1-5 POSTs per second thrashes my HA blue
etc.
well, what you could do is post the id to a sensor with the information, then make template sensors using unique_id's
or learn MQTT and put the information in a topic
You're controlling it from the outside, you can post to a topic instead, and you can also have it create a discovery config
yeah wasn't sure if restful api or MQTT was the best path forward, rest was quick to get started with
then you'll be able to provide unique_id's
MQTT is the way you want to go IMO
because you can create a discovery config and post updates. And you'll get what you want. It's more setup but it's more in line with what you want to do.
good deal, will give it a look
anyway you guys could help with this automation for variable notification template? would like the object that is detected to be included in the notification
@molten chasm posted a code wall, it is moved here --> https://hastebin.com/geninolefi
what's the problem with it? Seems good accept for the typo on the truck template, you have an extra _ at the end of your entity_id
There is a quote missing in the second template (shown by the syntax highlighting being messed up)
it throws error in log and does not send notification
you check what thefes said?
you've got an extra data: with nothing in it below message
try a notification without using a template in the service caller
developer tools -> services
see if you can fire a notification without the tempalte
yes its good
then it should be working, what does the trace say?
guessing you figured it out then?
So unless I'm misreading it . It only adds to the list and doesn't remove correct? I have read it multiple times
Ah, think of it as a filter
Thanks for all your help Petro
you're starting with all sensors and you're widdling it down
Ok let me reread it.... with that perspective
it should read like a sentance, you may not understand them, but if you have questions, i can help
So it basically will only ever have entities on list that are on.
right
when you use states.binary_sensor
any binary_sensor state change will cause that template to evaluate
or any light if you use states.light
light.sensor isn't a thing, so you shouldn't use that
well thats not a thing either π
states is all your states
states.light is all your lights
states.switch is all your switches, etc
Ohhh, that's what you put on the snippet
probably a mistake
my bad
Ok got it!
Np at all
I have been enlightened
Appreciate your help
Now the fun part
I may be back haha
yep, feel free to ask questions, did you look at the template editor?
developer tools -> templates
Yes I did
you can put templates in there and play around
I'm going to play with it shortly
states('sensor.bedroom_roku_idle_time') | int > 30 -%}
switch.turn_on
{%- else -%}
switch.turn_off
{%- endif %} ```
So I want this little template to simply just run all the time and turn that switch on or off depending on my media_player device status. How do I just make this run continuously? A script?
And if you're curious, this is to turn a noisy air filter on/off when I'm using my roku. The 'idle time' is so it doesnt turn on and off every time I pause for less than 30 seconds
@mellow knot posted a code wall, it is moved here --> https://hastebin.com/aceqelugul
hey guys. so i have a json list that looks as such (https://www.toptal.com/developers/hastebin/aceqelugul) and im trying to iterate through the list and grab name, dob, amount in each row using https://www.home-assistant.io/integrations/sensor.rest/#fetch-multiple-json-attributes-and-present-them-as-values. i can see the example talks about grabbing single rows of data but what of situation where the json output is a list of more than a single rows worth data. appreciate any input.
THANK YOU for this!
I can get this to turn ON the switch by simply using an automation with a template platform but what about my "else" condition that will turn it off any other time. Do I have to make a 2nd automation?
how would i exclude an entity if its name includes the word group?
I am trying to create a graph of runtime per cycle of a fridge compressor tracked through ESPHome as a binary sensor. Currently an automation on compressor start sets a time stamp to now and an automation on compressor stop sets a timestamp to now. How using templates on the stop automation do I set a value to the time in seconds elapsed during the compressor run?
Does this result in a timestamp or string? https://www.toptal.com/developers/hastebin/ufuvazotim.less
String
@fossil venture Thanks. I was able to get it working. The issue with the statement was YAML formatting.
| rejectattr('entity_id', 'search', 'group') (corrected from selectattr to rejectattr)
Hi, i have this automation action : action: - service: mqtt.publish data: topic_template: > {% if trigger.entity_id == 'input_select.boiler_timer_select' %} cmnd/Boilers/Pulsetime1 {% elif trigger.entity_id == 'input_select.turbo_boiler_timer_select') %} cmnd/Boilers/Pulsetime2 {% elif trigger.entity_id == 'input_select.2nd_boiler_timer_select' %} cmnd/2nd_Boiler/Pulsetime1 {% endif %} payload_template: "{{states('trigger.entity_id') | int * 60}}"
but i still get error Invalid config for [automation]: template value should be a string for dictionary value @ data['action'][0]['data']. Got None.
can't found what the problem
you mistakingly turned your trigger entity_id into the literal string "trigger.entity_id", which is not a valid entity_id. The variable trigger.entity_id contains the entity_id, do not wrap it in quotes because that makes it a string.
payload_template: "{{states(trigger.entity_id) | int * 60}}"
Secondly, if this is a state trigger, you can just get the state from the trigger
payload_template: "{{trigger.to_state.state | int * 60}}"
i change it to "{{trigger.to_state.state | int * 60}}" but still get the same error
Your toptic template is most likely providing an empty topic. Are you triggering this via the UI without actually having a trigger? If yes, the topic_template will contain nothing
not in UI
So how are you triggering it?
ok, again, how are you triggering it?
Yes, but are you triggering it manually from the GUI?
yes
Then there is no trigger
Ok then, as I said before, that won't work
this repsonse
so topic_template got only if the trigger is mqtt trigger ?
The information in your action will only populate if you actually trigger the automation via the supplied triggers
I.e. Adjusting the input_selects
Your automation relies on trigger.entity_id
Without an actual trigger, there is no trigger.entity_id
- platform: state
entity_id:
- input_select.boiler_timer_select
- input_select.turbo_boiler_timer_select
- input_select.2nd_boiler_timer_select```
this is no trigger ?
There is a trigger in your automation, but if you now start your automation from Configuration > Automatons, Scenes & Scripts and hit the play button there, there is no actual trigger triggering the automation
If you trigger it by changing the state of one of those input_selects, it should work
but it didn't pass the "Check Configurtion"
There's nothing wrong with the format, what's the error that you're getting in the config check?
Also, your topics are incorrect, remove the quotes around them inside your template. The > implies the quotes.
And conditions are AND by default, so the and-condition is not needed π
Invalid config for [automation]: template value should be a string for dictionary value @ data['action'][0]['data_template']. Got None. (See /config/configuration.yaml, line 278).
your error is pointing somewhere else
do you see the word data_template in that automation?
yes
Then you are using a different version as you posted above
I don't see it. You're using data. Not data_template
certainly not in the one you posted to us
This one has no data_template
It probably had it before, based on the reply Tinkerer gave in #automations-archived π
i know ... i try to check with or without
data_template is depreciated for over 2 years, so just use data
not quite 2 years yet π
Invalid config for [automation]: template value should be a string for dictionary value @ data['action'][0]['data']. Got None. (See /config/configuration.yaml, line 278).
this is with only data:
yes, you need data
ah
can you post EXACTLY what you have in your automation
I see it now, there is a ) missing in your first if statement
Which you would have noticed immediately if you tested your template in
> templates
oh year right
Well, I've put it in there π TemplateSyntaxError: unexpected ')'
But you are right, an extra one in the 2nd
But generally it is a good idea to test your templates, especially if it doesn't work as expected π
might be a pita tho because i uses trigger objects
It can be a little bit tricky though when you use trigger objects
which still need to be implemented somehow in the template editor
but this one was clear even then
yes you right but can't check it if you are using th trigger.entity_id
You can do something like {% set trigger = { 'entity_id', 'some.entity' } %} at the top
i over on it many time but still miss it..
So it is not impossible, but it requires some additional variables to be set, same with repeat {% set repeat = { 'index' = 1 } %} for example
@mighty ledge i did not, anyway you can help? https://pastebin.com/Nz1SeJ8v
it sends notification that says Doods nas_gate detected at Gate
what's it supposed to send
Then you should be pulling those words from the summary
right now you're feeding the friendly name of your entity, not the contents of the summary.
I tried to add a template to a motion trigger like that:
type: no_motion
platform: device
device_id: 1f5b47325eba6ea772141442dc77df38
entity_id: binary_sensor.presence_2
domain: binary_sensor
for:
hours: 0
minutes: "{% if int(states('sensor.humidity_13')) > 65 %} 30 {% else %} 15 {% endif %}"
seconds: 0
but i get Message malformed: expected float for dictionary value @ data['for']['minutes'].
Is what i'm trying to do even possible and if yes, what am i doing wrong?
I don't think templates are allowed in a device trigger
platform: template
value_template: >
{%- set minutes = 30 if int(states('sensor.humidity_13')) > 65 else 15 %}
{{ is_state('binary_sensor.presence_2', 'on') and (now() - states.binary_sensor.presence_2.last_changed).seconds / 60 > minutes }}
Thank you very much. You forgot a ")" when using is_state, but after correcting that it got accepted.
I will test it later when i get home. Thanks for helping me out.
Do i need to add {{ before (now() - states.binary_sensor.presence_2.last_changed).seconds / 60 > minutes?
No, the other one should not have been there
I corrected it
Okay, thank you very much
What would be the best way to do that? Thanks!
Well, it depends on what's in summary
how are you getting truck from summary right now?
that code doesn't explain what's in summary, so you could just use state_attr(..., 'summary') part and hope it gives you the word truck
good morning, how would i code template to exclude a specific switch or a few switches?
rejectattr('entity_id', 'equals', 'switch.xyz')
or
rejectattr('entity_id', 'in', ['switch.xyz', 'switch.abc'])
amazing thanks!!
starting with states.switch if you remember
you have selectattr, rejectattr, select, and reject
you'll mostly be using selectattr and rejectattr with states or states.<domain>
select will select regardless of condition?
you mean regardless of state?
right, because you aren't selecting or rejecting the state attribute
got it
the 1st argument is your attribute you're looking at
which in this case is entity_id
yesterday it was state
yeah im getting the hang of it
take a look at state objects
you're filtering a list of state objects, use that link to determine what property you're filtering based off of
super helpful! thanks
now i dont need to bother you as much lol]
@mighty ledge thanks like this? "{{ trigger.state.attributes.friendly_name, "summary' }} Detected at Gate"
No, look at your condition, what code is extracting your summary? It'll be identical.
To clarify, you're looking for truck in your summary as a condition, right?
'truck' in state_attr('image_processing.doods_nas_gate', 'summary')
so if you're looking for 'truck' inside your summary (in), what section of code extracts your summary?
remember what I said earlier
this
@mighty ledge ah matches: {}
summary: {}
total_matches: 0
process_time: 0.11037838501215447
friendly_name: Doods nas_gate
so matches i think
{{ trigger.state.attributes.friendly_name, "matches' }} Detected at Gate"
would that be it
One last thing, the is_state is supposed to be on off, right? Because I want to detect how long there has been no motion for
Yeah, you're right ππΌ didn't read carefully enough
hey guys. im trying to get data from a server over ssh. i have looked into the command_line platform however i dont see any references to where i can grab multiple values (lets say if i format my remote server bash file to output into json or xml format). REST platform does allow this which comes closest to what im looking for. Can anyone please give me some input on what are any extended capabilities of the command line platform that i can use to achieve this.
You can't with that integration
if your json is less than 255 characters, you can stuff it in the state and then make a template sensor based on that, extracting each item. Otherwise you'll have to make your own command line integration with extra abilities or go a different route
If it's a json dictionary, you can just use https://www.home-assistant.io/integrations/sensor.command_line/#json_attributes and plop each item in an attribute
then make template sensors based on each attribute
my output is infact less than a 100 chars. and yes the output from my bash script is formatted to be acceptable json which i can verifiably test in json path validation tools.
can you post the json here?
your best option is to stuff them in the attributes, which has no limit
stuffing them in the state can lead to problems
i maybe off on my count but i can create two seperate calls to get data in two parts.
well, if you just post the json you m ight not need to do that
sorry my browser was lagging a little.
ok, then all you need is
sensor:
- platform: command_line
command: SENSOR_COMMAND
value_template: "{{ value_json.total_witnesses }}"
json_attributes:
- total_witnesses
- sending_witnesses
- resending_witnesses
- successful_witnesses
- failedtodial_witnesses
- failedtosendresend_witnesses
- challenger_notfound
- challenger_timeout
- challenger_refused
- challenger_unreachable
- challenger_nolistenaddr
- peer_activity_list
- peer_timeout
- peer_timeout_proxy_session
- peer_timeout_relay_session
- peer_normal_exit
- peer_not_found
- peer_server_down
- peer_fail_dial_proxy
- peer_econnrefused
- peer_closed
you'll have a sensor with a bunch of attributes
you can then make separate entities for them if you want using a template sensor.
aah. i was all wrapped up in json paths and attribute paths.
to further process
template:
- sensor:
- unique_id: total_witnesses
name: Total Witnesses
state: "{{ state_attr('sensor.whatever_the_command_line_is', 'total_witnesses') }}"
- unique_id: sending_witnesses
name: Sending Witnesses
state: "{{ state_attr('sensor.whatever_the_command_line_is', 'sending_witnesses') }}"
etc
thank you so much. question. what is the purpose of this line. value_template: "{{ value_json.total_witnesses }}" (line 4)
is there where im accepting the first response from output to match (like an OK, data is there).
Thatβs just the state of that sensor, it needs to have some state
i see
You can just set it to OK if you want
i beleive in an example i saw in docs was using OK as state.
gotcha
would the sensor need to return ok for that to match or is it just reading anything to keep going for attributes.
up to you
it's just the state of your sensor
if you aren't using the state and just the attribute, who cares what the state is
sorry wrong paste. this what what i formatted it to.
- platform: template
sensors:
- unique_id: helium_miner_total_witnesses
name: Helium Sensecap Total Witnesses
state: "{{ state_attr('sensor.hmc_hass_json_data', 'total_witnesses') }}"
- unique_id: helium_miner_sending_witnesses
name: Helium Sensecap Sending Witnesses
state: "{{ state_attr('sensor.hmc_hass_json_data', 'sending_witnesses') }}"
petro any feedback if i'm looking for one of those matches in the notification
sorry meant to add that i HA is showing error saying "Invalid config for [sensor.template]: expected dictionary for dictionary value...."
@mighty ledgethank you again. i was able to make the template sensor work as well. appreciate it.
Thank you again!
@mighty ledge I changes from restful api to MQTT auto discovery... wow, what a difference, thank you again for the pointers
using mqtt is like swimming with the current instead of against π
Is there a way for trigger template sensors NOT to loose state when templates are reloaded or HA restarts?
(assuming I can compute state only when trigger occurs)
Add event triggers for a restart and reload of automations
- platform: homeassistant
event: start
- platform: event
event_type:
- automation_reloaded
This wouldn't work in case I need to access data from trigger (e.g. trigger.from_state)
I was thinking about template entities so the event type would probably be event_template_reloaded
how do i programmatically set the icon? I tried to use templates syntax without luck:
type: entities
entities:
- entity: cover.sonoff_yadayada
icon: >
{% if True %}
"mdi:window-shutter-open"
{% endif %}
i'm following the example in https://jinja.palletsprojects.com/en/latest/templates/ but i'm confused
Templates are for the backend. You cant use them in the frontend (Lovelace) except for the markdown card. You can add templating to Lovelace using a third party card but in this case it is not the appropriate solution. You should add device_class: shutter to your cover configuration. Or if it is a discovered entity use the GUI, Configuration / Devices & Services and find your device to edit it.
mmh i don't see any way to do it from the web interface, it's an entity
because i can edit it in the developer tools, but as soon as it moves the edit gets wiped
Which integration are you using to bring your cover into Home Assistant?
SonoffLAN
Ok, I'm not familiar with that 3rd party integration but looking at its documentation there is a way to apply a device class. See the 6th example here https://github.com/AlexxIT/SonoffLAN#custom-device_class-for-any-mode Also lets move this over to #integrations-archived as it has little to do with templating.
Hello,
I'm having trouble getting a template right. I just need a template to fire when both contact sensors are closed for 5 mins {{ ((states('binary_sensor.bedroom_door_contact_sensor') + states('binary_sensor.bedroom_2_door_contact_sensor') = off }}
I know this is unbelievably wrong but I've struggled on this longer than I should've and I've come for help. Can somebody help my template please?
assuming that "off" is "closed" for these sensors, then this:
trigger:
platform: template
value_template: "{{ is_state('binary_sensor.bedroom_door_contact_sensor', 'off') and is_state('binary_sensor.bedroom_2_door_contact_sensor', 'off') }}"
for: "00:05:00"
@modern sluice
that is a correct assumption. Thank you!
keep in mind that that will only trigger if it becomes true and stays that way for 5 minutes, so a state change is required
Yes, I only want this to be true if they are both off for 5 minutes but I'm not sure I follow you on the state change. You mean like in case a door gets reopened/closed in that 5 mins?
it's probably fine for your needs, but it won't trigger if HA starts up and they're already both closed, for instance
understood and not a worry. Thanks!
point is that the timer starts when the template transitions from false to true
Is it possible for the template cover system to have custom states or am I limited to open, opening, closed, closing? I wanted a way to represent a stopped gate with an icon change but to do that I have to remove the value template currently which is not ideal
value_template template (optional)
Defines a template to get the state of the cover. Valid output values from the template are open, opening, closing and closed which are directly mapped to the corresponding states. In addition, true is valid as a synonym to open and false as a synonym to closed. If both a value_template and a position_template are specified, only opening and closing are set from the value_template.