#templates-archived
1 messages Β· Page 7 of 1
Yeah i wanted two...it works now...i just tried 3 to see if it works
Why float(0) instead of just float ? What does it funtion ?
The (0) is a default value in case your brightness attribute is not available (like if the light is off). Without this it will generate errors.
Okay....okay thanks .....one small question ...just wondering where all i can use.... What happens when i use (2) or (1)
Then 2 or 1 will be substituted if the float filter can't convert the value to a number. You can use anything you want. e.g. one of mine that ensures a known result in case of missing values: {% if states('sensor.lounge_room_temperature')|float(25) <= states('input_number.upstairs_ac_temp_set_heat')|float(21) - 2 %}
Okay i get it..if i use
{{ state_attr('light.bedroom_lamp','brightness') | float(10) }} and when light.bedroom_lamp brightness is unavailable ...it supported to push 10 ryt?
Correct
Yeah it works ..thanks π€©
hi
can i have a timeout action inside a step of sequence?
#automations-archived might know. This channel is about templates.
ok
I gave you a rough idea of what the maths should be, i reccomend going to google and using google calculator to figure out the final equasion, once you have a number like 0.23594538 then you can apply a round to it
Yeah..thanks ....figured that out ....π€©
Are there any decent guides on how templates work, I've gone over the HA docs and Im not really getting it. Maybe something with smaller words and sock-puppets perhaps?
come to think of it this might do the trick ((1.0 - 0.2) * (brightness / 255 + 0.2)) | round(1)
Or a moralizing robot side-kick who talks about recycling or something π
I don't know of any but you may want to try youtube see if there's any tutorials on there.
Yeah im looking but its never great when most of them are like "Yeah you do this for some reason I dont understand".. good for specific examples of what they are doing but rather lacking in 'well I want to do something a little different' π
yeah sadly i dont think most of the HA video makers are programmers so they don't explain things half the time
Yeah, Im at the stage of "Eitehr copy and paste this automation 14 times.. or learn templating" and Im rather torn which is the lesser hell π
come to think of it you may want to look into jinja2 thats what templates use, but home assistant adds it's own functions and filters on top of that
What are you trying to do?
Instead of looking for a guide try building the thing you need, or at least explaining it.
If you don't have a mind for programming, jinja isn't going to help your problems
it's code, no way around it
Motion Sensor last action: Need some code to find the last action of the motion sensors. Sometimes my zigbee devices need to be repaired and it would be good to know this as soon as possible. No action longer than 12h i have to check. It happens about 8-12 weeks one.
TBH what I need is to setup some automations to be 'general' in that for each remote/light in my home I can use the same codeblock again and again.. So for example this code block.. - alias: "Zigbee2MQTT Lights - Hold On to Full Brightness" trigger: - platform: state entity_id: - sensor.office_switch_action to: "on_hold" action: - service: light.turn_on data_template: entity_id: light.office_light brightness: 254 transition: 1 That ideally I could change it so entity_id works for anything called 'sensor.roomname_switch.action' and convert that into a trigger for 'light.roomname;
I did have something like this working with Deconz, but z2m is different enough that breaks beyond my ability to fix it
(So I dont need to make 9+ copies of this same automation for every single room /light combo in my home)
(I need an automation for every 'interaction' for the light, so 1 swithc is actually about 8 automations per room, so its going to really grow arms and legs)
for reference.. this is what I made/kinda lifted from the internet for Deconz π ```## Turn a light On and set it to 100% if On is long-pressed
- alias: "Hue Light Remote: Long Press On"
trigger:- platform: event
event_type: deconz_event
event_data:
event: 1001
action: - service: light.turn_on
data_template:
entity_id: "light.{{ trigger.event.data.id | regex_replace(find='_switch.*', replace='', ignorecase=False) }}"
brightness: 254
transition: 1 - service: input_boolean.turn_on
data:
entity_id: "input_boolean.{{ trigger.event.data.id | regex_replace(find='_switch.*', replace='_light_override', ignorecase=False) }}"
- platform: event
This seems easy, but I cannot find a way:
My Espressomachine needs to be switched on 30 minutes before my alarm goes off in the morning to make it preheat. How can I set the trigger for the Espresso switch to power on 30 minutes before the alarm (set by input_datetime.alarm)?
Was hoping this would work ...
trigger:
- platform: time
at:
entity_id: input_datetime.alarm
offset: -00:30:00
But it seems I need a template trigger. Can anyone help with an example of such a template
I don't see an input_datetime.alarm service. Assuming that your input_datetime only has a time, you can use this:
{{ today_at(states('input_datetime.date_test')) - timedelta(minutes=30) }}
For a trigger you'll need to compare that with now()
I had that in there, but I would probably just set the input_datetime each day in an automation
in any case, OP vanished
That's also a possibility

If you have any opinons on my question, Im still here? π
there's about 100 different ways to do that, but it's going to be just as verbose as making the individual automations. It might be worthwhile for you to just make blueprints so you can quickly create all these automations.
otherwise, you'd need to get in deep with templating
@limber haven if you post all your sensors and all your lights that you're doing using a share site, i'll take a look and see how feasible it is
.share @limber haven
apparently the bot is dead
Mm, I managed to do it for Deconz wsithout too much trouble. Basically using a set naming scheme and using string replacements to format it in a way that HA would like
Ah, well Im still porting all the lights / switches over, but they should be all "light.roomname" and "sensor.roomname_switch_action" π
if it's that simple, then...
- alias: "Zigbee2MQTT Lights - Hold On to Full Brightness"
trigger:
- platform: state
entity_id:
- sensor.office_switch_action
- list
- sensors
- here
to: "on_hold"
action:
- service: light.turn_on
data_template:
entity_id: light.{{ trigger.to_state.object_id.split('_')[0] }}_light
brightness: 254
transition: 1
and if your room names have multiple underscores in them, then the template would be this instead
- alias: "Zigbee2MQTT Lights - Hold On to Full Brightness"
trigger:
- platform: state
entity_id:
- sensor.office_switch_action
- list
- sensors
- here
to: "on_hold"
action:
- service: light.turn_on
data_template:
entity_id: light.{{ trigger.to_state.object_id.split('_')[:-2] | join('_') }}_light
brightness: 254
transition: 1
remove the _light if you don't have that on your entity_id
anyways, that should get you started
So that is taking the trigger.. in this case the Entity_id for the switch (Which I'll have to list, I guess I cant do something similar for 'find anything that is sensor.*...
you could, but it's more work
you'd need a second automation that makes a group list. But triggers are limited
so it's not worth the effort IMO
Is there a way in HA to.. test.. what the results are for some of these templates? Like have it run it through in a simulation to give me the end result of what light.{{ trigger.to_state.object_id.split('')[:-2] | join('') }}_light does?
in the template editor
you can use this
{% set trigger = {'to_state':{'object_id': 'office_switch_action'}} %}
Should have known I would be too slow on mobile
{% set trigger = {'to_state':{'object_id': 'office_switch_action'}} %}
entity_id: light.{{ trigger.to_state.object_id.split('_')[:-2] | join('_') }}_light
lol yes, I'm on desktop atm
β‘
Great! OK, let me fuzt around with this and see what I can make it do.. having a easy way to test what its actually doing will make this a bit easier π
{% set trigger = {'to_state':{'object_id': 'office_room_slyboots_this_will_work_regarless_of_the_amount_of_underscores_switch_action'}} %}
entity_id: light.{{ trigger.to_state.object_id.split('_')[:-2] | join('_') }}_light
returns
entity_id: light.office_room_slyboots_this_will_work_regarless_of_the_amount_of_underscores_light
Would be a silly room name though
haha yes
just wanted to make sure it catches dining_room and crap like that
rompus_room
You could also just do | replace('_switch_action', '_light')
yah that oo
many ways to skin this cat
not sure which one is more efficient
probably | replace
1 iteration vs potentially 3
okay I see. So the split_ splits the entity_id into an array and the [x] is what calls what part of the result to use.. Neat. although once the trigger in this case be called 'sensor.... whatever?, so the result would be.. light.sensor.office_light ? Although if can do | regex_replace(find='sensor.*', replace='', ignorecase=False) I suppose?
Or just replace
It takes the object_id, which is the part after the .
Ahh, okay.. Makes sense π
why not do it based on the area of the entity? you can get the area of the trigger and apply that to the entity you want to set i basically do that in my automations
haha that just worked π
Now the next tricky bit is for the MQTT publishes π
Getting MQTT wasnt that bad but.. funny problem, the 'trigger' name is all lowercase, but the topic requires it to be Sentence case.. π So "/light/office/set" to MQTT is differnt to /light/Office/set" still.. might be able to figure this one out π
Thank you for your help Petro, and for going that extra step to help me understand it as well π
expand(states) | selectattr('domain', 'eq', 'light') <-- is that the correct syntax to get all lights ?
states.light
assuming that replaces the whole lot?
also if I wanted to use the selectattr domain eq light i assume i can just use states and then apply selectattr as a filter? using it to create a debugging sensor to see the end results
What I suggested results in the same thing without a ton of extra processing time and memory
using expand() on states doesn't do anything useful, anyway
the reason for the debugging sensor is i'm trying to see where this goes wrong ```
- name: Light Living Room
unique_id: light_living_room
state: >-
{% set current_values = expand(area_entities('living_room')) | selectattr('domain', 'eq', 'light') | map(attribute='attributes.brightness') | map('int') | list %}
{% if current_values | count > 0 %}
{{ current_values | average | int }}
{% else %}
{{ this.state|int(0) }}
{% endif %}
so creating a debug sensor that mimiks that expand on the area entities and one that just gets all lights in the house which i wont bother with expand on
ok
the above is on a template number:
I guess
the above was suggested to me by petro, unless there's a better way to achieve that
well the expand(area_entities('kitchen')) | selectattr('state', 'eq', 'on') | map(attribute='attributes.brightness') | map('int') | list | average | int bit was
that's okay as long as they're all lights
I added selectattr('domain', 'eq', 'light') to account for that but for some reason kitchen returns unknown value, i get a value for living room fine, but when the entities are reloaded it defaults to 127 so i can only assume it's getting a 0 value and a 255 value and averaging them
you'll need to debug that in
-> Templates
Thanks, I've never noticed the really noticed template tab before, I always wondered if there was something similar to that, in the past I just created a sensor to see what the values were outputting.
it's invaluable
Any idea why this doesnt work? area_entities('living_room') | map('regex_search', '^light\.') the result of area_entities does return light.living_room
managed to achieve desired result with | select('match', 'light.') it seems
and since that appears to be regex i replaced with '^light.'
found the select match in a random ha forum post, the jinja2 template reference was useless for that
map() applies a function or extracts a value, it doesn't filter the results
It's from the second link in the channel topic
Can anyone see anything wrong with this? https://pastebin.com/0xAFzMeu i tested the values in state: and they were working fine, but it's showing as unavailable in developer tools
looks like it's the use of expand as a filter
Yep, it was that validation error, though annoyingly - name: Light Living Room unique_id: light_living_room state: > {% set light_values = expand(area_entities('living_room') | select('match', '^light\.')) | map(attribute='attributes.brightness') | map('int') | list %} {% if light_values | count < 1 %}{{ value|int(0) }}{% else %}{{ light_values | average | int }}{% endif %} still resets to 127 when the entities are reloaded rather than the current value of the living room light
Think i found another bug if you do
set light_values = expand(area_entities(area_id(this.entity_id)) | select('match', '^light.'))
then do something like if light_values | list | count < 1 and try to use the value of light_values it acts as if it's been converted to a list, rather than the state it was at when it was set, also happens if you echo the value out with {{ light_values | list }} in the dev tools for example then try and use it again
i've managed to get around it, but it's annoying
The seiect() part isn't good. You should do selectattr('domain', 'eq', 'light')
What you have will work, it's just not optimal
Isn't the problem that lights which are off don't have the attribute brightness?
Yeah, in that one. They've been trying various random things: #templates-archived message
Switch > light lights also don't have brightness when on (and maybe other types). Wouldn't it be better to check on brightness being defined first?
Morning all. I have a question regarding yaml files. My template sensors file is growing and Iβd like to split it up into multiple files if possible. I have the include line in the config file for my sensors.yaml file but when I try to create a new file and include it, it tells me sensors is a duplicate. How do i create multiple files and include them? Example:
cost_sensors.yaml
count_sensors.yaml
power_sensors.yaml
And include them all in the config.yaml?
Put them all in the folder sensor and use:
sensor: !include_dir_merge_list sensor
I'll give it a try. Thanks
if I create a folder 'custom_files', would it then be sensor: !include_dir_merge_list custom_files/sensor?
Thanks. Just done that and now all my sensors have disappeared
Did you make sure all the entries in each file are in a list?
yes, i think so
#=== Get Daily Cost of Tumble Dryer
#==============================
- platform: template
sensors:
tumble_dryer_daily_cost_total:
unique_id: tumble_dryer_daily_cost_total
friendly_name: "Tumble Dryer Daily Cost"
device_class: monetary
icon_template: mdi:currency-gbp
unit_of_measurement: GBP
value_template: >-
{% set state = states('sensor.tumble_dryer_daily_energy_usage') %}
{{ (state | float * 0.2706) | round(2) if is_number(state)}}
#==============================
#=== Get Last Month Cost of Tumble Dryer
#==============================
- platform: template
sensors:
tumble_dryer_last_month_cost_total:
unique_id: tumble_dryer_last_month_cost_total
friendly_name: "Tumble Dryer Last Month Cost"
device_class: monetary
icon_template: mdi:currency-gbp
unit_of_measurement: GBP
value_template: >-
{% set state = state_attr('sensor.tumble_dryer_monthly_energy_usage', 'last_period') %}
{{ (state | float * 0.2706) | round(2) if is_number(state)}}```
Hi. Recently i got some awesome advice here with declaring a list of switches in a variable. I wanted to add additional functionality to that automation and i was wondering what is the best way to check if any of the switches declared in a variable are on
You probably want a group: https://www.home-assistant.io/integrations/group
a couple of days ago i've been recommended a very elegant template solution, so i would prefer to keep it tempalate only
A template can easily expand a group
And it would save you re-declaring the same list twice in the example you linked
Please don't use Pastebin, since it can randomly add spaces to the main view. π
Looks okay, where did you place these files, and how did you do the include?
Location: custom_files/sensor
Include: sensor: !include_dir_merge_list custom_files/sensor
Example inside cost_sensors.yaml inside the custom_files/sensor folder:
#=== Get Daily Cost of Tumble Dryer
#==============================
- platform: template
sensors:
tumble_dryer_daily_cost_total:
unique_id: tumble_dryer_daily_cost_total
friendly_name: "Tumble Dryer Daily Cost"
device_class: monetary
icon_template: mdi:currency-gbp
unit_of_measurement: GBP
value_template: >-
{% set state = states('sensor.tumble_dryer_daily_energy_usage') %}
{{ (state | float * 0.2706) | round(2) if is_number(state)}}
#==============================
#=== Get Last Month Cost of Tumble Dryer
#==============================
- platform: template
sensors:
tumble_dryer_last_month_cost_total:
unique_id: tumble_dryer_last_month_cost_total
friendly_name: "Tumble Dryer Last Month Cost"
device_class: monetary
icon_template: mdi:currency-gbp
unit_of_measurement: GBP
value_template: >-
{% set state = state_attr('sensor.tumble_dryer_monthly_energy_usage', 'last_period') %}
{{ (state | float * 0.2706) | round(2) if is_number(state)}}```
And custom_files is in the same folder as where you configuration.yaml is?
yes
Anything in the log? And did you reload template entities?
I dont see anything in the log. Yes, I reloaded the templates.
im trying to do something like that but it doesnt work:
{{ switches | selectattr('state', 'eq', 'off') | list | count == 0 }}"
also tried replacing switches with expand(switches)
Well that's a domain, not a group
no, a variable
What's in the variable? You might need to expand it first
the thing is that the list of switches will be modified in the future, if i will also create a group out of it - i will need to modify three different lists every time i add or remove a switch just for one automation
You can use automations to set groups π
could it be because I have
sensors:```
on every sensor I create?
No, that should not be an issue
Then only use the group
but this is that automation youve been helping me with a couple of days ago - only one switch can be on at a time
How does using a group prevent that?
PM'd with images
ok i will try to move the list to a group
found the issue. Called the folder 'sensors' and had 'sensor' in the config file. FML. thanks for the help
Having a group actually helps to maintain it more easily
so now ive created a group. With this automation, can i just replace the variable name with group name for this to work?
Well, you do need to make some changes, you'll need other templates
Can you share the current automation again?
Okay, I will come back to this when I finished doing the groceries
no worries, i will try to crack on with this until then
hmmm i think i can make it work, except i have change the trigger to the group and now the automation doesnt know which switch has actually been switched so wont get a correct trigger.entity_id for this bit:
entity_id: '{{ switches | reject(''eq'', trigger.entity_id) | list }}'
would it be possible to use a template trigger to expand a group and then get a trigger.entity_id later on in the action field?
Thank you, @inner mesa. Yes, the input__datetime only has the time for the alarm to go off.
I got to something like this:
{% set x = expand('switch.private_office_consoles') | selectattr('state', 'eq', 'on') | sort(attribute='last_changed', reverse=true) | list %} {{ expand('switch.private_office_consoles') | reject('eq', x[0].entity_id) | list }}
but reject doesnt want to work
You probably need rejectattr('state'.
im getting TemplateRuntimeError: No test named 'switch.private_office_console_strip_1_l3'.
I don't understand what you are doing with that if. The goal was to have only one of the group members on, so the others will always be off and the condition there will always be false
Anyway, hoe is your group called?
switch.private_office_consoles
I would use this as a template trigger: {{ expand('switch.private_office_consoles') | selectattr('state', 'eq', 'on') | list | count > 1 }}
so this automation should do the following:
- make sure that maximum one of the group members is on - if another device is switched on, switch off previous one
- If a particular group member is turned on - send an IR command
those two were working in a previous version (without a group), what i wanted to add to it is: - if any of the group members is on - also switch on a monitor
Okay, still not sure what you are doing with the template in the if on line 21, that will only be true if all switches are on
ahh, thats the functionality i was trying to add (3) - that line may be wrong, didnt get to a point where i can test it
I assumed that, but now it checks for 0 switches being off, meaning all are on
Anyway, you can combine it all in one automation, but I would suggest to do it in 3 separate ones
Makes it all a lot easier
- use the trigger I suggested above, I will come back on how to determine which ones to turn off
- trigger on that specific member turning on
- trigger on the group itself turning on
To determine which switches to turn on for 1) you can use
{{ (expand('switch.private_office_consoles') | sort(attribute='last_changed) | map(attribute='entity_id') | list)[:-1] }}`
ok, we can try that if i can use a single group to store the consoles
ok many thanks, i have slightly modified this:
{{ (expand('switch.private_office_consoles') | selectattr('state', 'eq','on') | sort(attribute='last_changed',reverse=true) | map(attribute='entity_id') | list)[:-1] }}
but now it works flawlessly
but how can i check if any member grouip is on/a particular member group is on
I already mentioned that, but to check in the particular member, just use a state trigger on that specific entity
And the group will be on if any member is on, so for that use a state trigger on the group turning on
Either use 3 separate automations or use 3 triggers in one statistics automation, add trigger ids and use choose to determine the action based on the trigger id
aaaahhh right
one last thing, what trigger should i use for this template?
currently i made a simple
- platform: state entity_id: switch.private_office_consoles
but it only seems to trigger when the group changes its state, not when members do
Why would you want that?
You mean this trigger? #templates-archived message
You should not reverse the sort, or use [1:] instead of [:-1].
The way you have it now you will turn off the last switch which was turned on, instead of leaving that one on
What is wrong here? My automation never triggers, even though I would think the timestamp comparison would be correct.
trigger:
- platform: template
value_template: >-
{% set espresso_on = today_at(states('input_datetime.alarmtid')) - timedelta(minutes=30) %}
{{as_timestamp(now()) == as_timestamp(espresso_on) }}
Here is my output
AS TIMESTAMP ESPRESSO ON: 1662290700.0
AS TIMESTAMP NOW: 1662291592.743583
```
input_datetime.alarmtid needs to be a time only datetime
how?
it's part of the configuration
doesnt work. I tried evaluating this template in Dev Tools and get: "TemplateRuntimeError: No test named 'state'."
so converting to timestamp will not help?
secondly, you can just use >= without the timestamps
I want it to triggar "at" the time set
no, converting it to a timestamp is going to make it into those long numbers
and I thought it was more accurate..
no
assuming it's a time only datetime, you can remove the as_timestamps
{{ now() == espresso_on }}
and if that doesn't work, because of the microseconds...
{{ today_at(now().time() | string) == espresso_on }}
This is what I get:
ALARM: 2022-09-04 13:55:00+02:00
ESPRESSO_ON: 2022-09-04 13:25:00+02:00
NOW: 2022-09-04 13:43:32.857665+02:0
right, but now() in a template resolves at the minute
now() in the editor resolves when you hit enter and on the minute
Right! I was concerned it would matter but did not fully understand it
Thank you @mighty ledge IΒ΄ll investigate this further using your suggestions. π
Corrected, needed selectattr
Still not getting it right...
{% set espresso_on = today_at(states('input_datetime.alarmtid')) - timedelta(minutes = 30) %}
{{ today_at(now().time() | string) == espresso_on }}
Returns this: ValueError: could not convert str to datetime: '14:01:16.894377'
IΒ΄m confused
Then donβt use that and use >= with just now()
You just need it to resolve from false to true
So youβll only get 1 trigger with >= not multiple
Meaning you want it to trigger on the minute right? >= will do that
ah! got it. Testing in the automation, now.
Aight I gotta go for a run
Sure thanx for helping me furhter
This did work, using >= and now()
Can you not template triggers? for example: ```trigger:
- platform: state
entity_id: "{{ trigger_lights + trigger_booleans + trigger_blinds + [ 'input_text.current_presence' ] }}"``` where each variable is a list of entity_ids? i get an error Message malformed: Entity {{ trigger_lights + trigger_booleans + trigger_blinds + [ 'input_text.current_presence' ] }} is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
Nope, you can't use templates for the entity_id in a state trigger
what about a template trigger loop through all of them and check if state has changed within the last n seconds?
You could do that
No need for a loop
{{ expand( trigger_lights + trigger_booleans + trigger_blinds + [ 'input_text.current_presence' ] ) | selectattr('last_changed', '>', now() - timedelta(seconds=10)) | list | count > 0 }}
@rare linden Where are those variables defined?
Variables: section in the root https://pastebin.com/787TyCF6
Only trigger_variables are available in template triggers
https://www.home-assistant.io/docs/automation/yaml/#trigger_variables
Those are limited to limited templates though
Is there an add on or something like that that would let me define a template and evaluate it on a historical state recorded in the HA database β to see whether my definition of a trigger works as if is supposed to etc? A sort of history tab with a function of entities instead of entity
Hi have a question on calculation with times.
I have a couple of helpers (times) that i want to subtract from a time i set in the lovelace interface, also a helper (time)
How do i do that because i cant get input_datetime to work in templates.
I have the following helpers, the input is set to time for all the helpers
- input_datetime.time_work_start
- input_datetime.travel_time_work
- input_datetime.travel_time_manual
- input_datetime.prep_time_home
I want to do the calculation: input_datetime.time_work_start - input_datetime.travel_time_work - input_datetime.travel_time_manual - input_datetime.prep_time_home
to get my wake-up time.
I have daly different wake-up times depending on the start time and start location for work
The wake-up time will be the base for other events that precedes the actually wake-up
I assume work start is like 9:00, and the others are more like 0:45, 0:30 etc?
So work start is an actual time, and the others are more like time durations
you assume correctly
Is it possible to say in a way:
For i in range(0,variable_1 | length)
{% set my_array[i] = [variable_1[i], [variable_2[i] %}
End if
Everytime when I write [i] after my_array I get an error.
No, you can't change array contents like that
You can just build the list with mylist = mylist + [...]
But then you also need to use a namespace
But the list variable_1 and variable_2 could be very long or very short :/
{% set w = today_at(states('input_datetime.time_work_start')) %}
{% set tw = states('input_datetime.travel_time_work').split(':')
{% set tm = states('input_datetime.travel_time_manual').split(':') %}
{% set pt = states('input_datetime.prep_time_home').split(':') %}
{% set h = tw[0] | int + tm[0] | int + pt[0] | int %}
{% set m = tw[1] | int + tm[1] | int + pt[1] | int %}
{{ w - timedelta(hours=h, minutes=m) }}
I meant that they are an unknown quantity of elemnts/ variables.
but that part doesn't change
But I skipped that part. Is there a away to ask:
Is this_string in my_string?
Like:
Is 'test' in 'hello this is a test'
Answer: yes
Is 'hello 'in ' hello this is a test'
Answer: yes
Is 'tree' in 'hello this is a test'
Answer: no
I'm just addressing your issue, which was that you're trying to modify an array/list based on indicies. You can't do that
what you wanted to assign to each list item is exactly the same
what is your actual question?
Exactly like that
{{ "foo" in "foobar" }} -> true
Thx @marble jackal , that did the trick.
Learned some new things today. π π
I have 2 lists that each have elemnts in it. These elements are touples. They belong to each other. It is a name and a value.
So name_list[1] should be related to value_list[1] and so on.
So I wanted an array that put those 2 lists in 1 list with touples
Very straight forward thank you
sounds like you really want a dict
this creates a dict that I think does something like what you want:
{% set list1 = ['foo', 'bar', 'blah'] %}
{% set list2 = [1, 2, 3] %}
{% set ns = namespace(mylist={}) %}
{% for i in range(0, list1|length) %}
{% set ns.mylist = dict(ns.mylist.items(), **{list1[i]: list2[i]}) %}
{% endfor %}
{{ ns.mylist }}
->
{
"foo": 1,
"bar": 2,
"blah": 3
}
if you really want a list of lists:
{% set list1 = ['foo', 'bar', 'blah'] %}
{% set list2 = [1, 2, 3] %}
{% set ns = namespace(mylist=[]) %}
{% for i in range(0, list1|length) %}
{% set ns.mylist = ns.mylist + [(list1[i], list2[i])] %}
{% endfor %}
{{ ns.mylist }}
Thank you that did work π
I have now a problem with my Marksdown Card. I want a table (all numbers are now working)
But with that many lines of code I destroyed the table layout.
I tryed now all possibilities of {%- and -%}
I do not really know what they do the minusses for and after the {%
They remove whitespace
@marble jackal seems to work perfectly. Thank you very much for your help and patience!
at the end of the day i have done two automations, one for switching and ir blast - managed to do both with one trigger and the other one for the monitor
ππΌ
{% set this_month_tally = [1,2,3] %}
{% set this_month_tally_name = ['test1', 'test2', 'test3'] %}
{%- if this_month_tally|length == this_month_tally_name|length -%}
{%- set endvalue = 0 -%}
|Ausgabe| | EUR |
|:--------------------|---|:-:|
{%- for i in range(0,this_month_tally|length) -%}
{%- set name = this_month_tally_name[i].replace(' GmbH','').replace(' Ltd','').replace(' Germany','').replace(' & Co.','').replace('.com','').replace('.de','').replace('B.V.','').replace('Payments','') -%}
{%- set filtername = states('input_text.legro_ausgaben_einnahmen_name_filter') -%}
{%- if filtername == '' -%}
{%- set value = this_month_tally[i] -%}
{%- if value >= 0 -%}
|{{ name }}| |{{ value }}|
{%- else -%}
|{{ name }}| |{{ value }}|
{%- endif -%}
{%- else -%}
{%- if filtername in name -%}
{%- set value = this_month_tally[i] -%}
{%- if value >= 0 -%}
|{{ name }}| |{{ value }}|
{%- else -%}
|{{ name }}| |{{ value }}|
{%- endif -%}
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{%- else -%}
FEHLER!
{%- endif -%}
I cannot figure out, that there is no completed table. I know possibly it is a hideous work, but can someone pls help me?
Iβll take a look when I get home
Thank you, that would be so cool and kind of you
is there a way to get a list of all areas?
{%- set filtername = states('input_text.legro_ausgaben_einnahmen_name_filter') -%} must not return an empty string
also, you're using -%} in 4 spots that shouldn't have it
before each |{{ name }}| | {{ value }}|
each |{{ name }}| {{ value }}| shouldn't have an indentation in front of it either.
if you make those changes, you should have a markdown table
mhhh but I wanted it to use it like a filter. In LoveLace a text field, where I delete or type something
I tryed every possible combination xD that were the last changes I did before I gave up
yeah, you can, but when not empty it outputs nothing
either way, if you just ignore the filtername crap I said and make the other changes, it will probably work the way you want
can I just if claused it? like if states('input_text.legro_ausgaben_einnahmen_name_filter') is string then {%- set filtername = states('input_text.legro_ausgaben_einnahmen_name_filter') -%} ??
but my table has 3 coloums, 2 with variables and 1 in the middle with whitespace
right, but when you use the -%} it removes all leading whitespace including the carriage return
you want the carriage return, but not the spaces π
@mental violet fyi this does the same thing
{% set data = [
dict(name='test1', tally=1),
dict(name='test2', tally=2),
dict(name='test3', tally=3),
] %}
{%- if data %}
{%- set filter = states('input_text.legro_ausgaben_einnahmen_name_filter') %}
|Ausgabe| | EUR |
|:--------------------|---|:-:|
{%- if filter %}
{%- set data = data | rejectattr('name','!=', filter) | list %}
{%- endif %}
{%- for item in data %}
|{{ item.name }}| |{{ item.tally }}|
{%- endfor %}
{%- else %}
FEHLER!
{%- endif %}
can I set the data with a for loop?
name and tally are: {%- set this_month_tally = state_attr('sensor.legro_spending_list',('monthly_tally_'+ (now().month)|string)) -%} {%- set this_month_tally_name = state_attr('sensor.legro_spending_list_name',('monthly_tally_'+(now().month) |string)) -%}
ok, change that to
hold on, trying to think of the best way to handle this
where are tallies and names coming from?
what's the integration that's making those sensors?
{%- set attr = 'monthly_tally_' ~ now().month %}
{%- set tallies = state_attr('sensor.legro_spending_list', attr ) %}
{%- set names = state_attr('sensor.legro_spending_list_name', attr) %}
{%- set filter = states('input_text.legro_ausgaben_einnahmen_name_filter') %}
{%- set ns = namespace(data=[]) %}
{%- for i in range(tallies) %}
{% set ns.data = ns.data + [ dict(name=names[i], tally=tallies[i]) ] %}
{%- endfor %}
{%- if ns.data %}
|Ausgabe| | EUR |
|:--------------------|---|:-:|
{%- if filter %}
{%- set ns.data = ns.data | rejectattr('name','!=', filter) | list %}
{%- endif %}
{%- for item in ns.data %}
|{{ item.name }}| |{{ item.tally }}|
{%- endfor %}
{%- else %}
FEHLER!
{%- endif %}
that would work as is, but it's not optimal
it'll be fine on any system, there just might be better ways if you can change sensor.legro_spending_list and sensor.legro_spending_list_name
this isn't a template question, head over to #integrations-archived
sry for my late answer. Suddenly I had to work at work xD Thank you for your efforts
{%- set ns.data = ns.data | rejectattr('name','!=', filter) | list %}
here I want that it doesnt have to match completly rather if filter matches any string combination in name.
change it to selectattr('name', 'search', filter)
thank you
Having a weird issue with a pretty basic script:
- if:
- condition: state
entity_id: '{{states(''sensor.music_leader'')}}'
state: 'paused'```
is throwing the error `Message malformed: Entity {{states('sensor.music_leader')}} is neither a valid entity ID nor a valid UUID for dictionary value @ data['sequence'][0]['if'][0]['entity_id']`. The template state is the name of a media_player entity and it works fine later in the script. Also resolves correctly in the template dev tool. The script works fine if I plug in a media_player entity too.
you can't template entity_id
it's probably not a state condition entity_id
that would be why
general rule of thumb
target, and anything in data for a service call can be templated
everything else, you have to read the docs
Understood, that's super helpful
yeah, in the docs it'll say next to the field if it can be templated or not
i think it's just template
next to the field name
Is there a filter for a list which only includes the last 30 entrys?
I'm a bit perplexed by regex capture. This works fine to extract "upstairs" in the template editor, but results in \x01 if I use exactly the same thing in an automation:
{{ 'sensor.kit_keypad_upstairs_lights_scene'|regex_replace('sensor.*_keypad_(.*)_lights_scene', '\\1') }}
it fails to parse with only a single \
seems to work fine in the Python implementation of regex_replace, but I get the same bad result with a single \:
>>> import re
>>> p=re.compile('sensor.*_keypad_(.*)_lights_scene')
>>> p.sub('\1', 'sensor.kit_keypad_upstairs_lights_scene')
'\x01'
>>> p.sub('\\1', 'sensor.kit_keypad_upstairs_lights_scene')
'upstairs'
Okay, so it works if you use it in a multiline template, but not a single-line template
This works:
floor: >-
{{ trigger.event.data.entity_id|regex_replace('sensor.*_keypad_(.*)_lights_scene', '\\1') }}
This doesn't (results in '\0x01'):
floor: "{{ trigger.event.data.entity_id|regex_replace('sensor.*_keypad_(.*)_lights_scene', '\\1') }}"
hi, trying to create a trigger based on my proximity sensor when it equals to 1 km.
trigger:
- platform: template
value_template: "'{{(states.proximity.my_name.state) == 1}}'"
the above does not seem to fire the automation
It would have to be exactly 1km (e.g. not 0.98 then 1.01) to trigger. Trying using < or > as is appropriate to capture a range of values that is more reliable to trigger, based on the frequency and accuracy of that location entity..
And...states are strings
I was thinking about that, however, I don't think my proximity is that granular, it has a resolution of 1 km. so number are always whole. I see the state being 1 when I'm about 1 km away.
should I change it to value_template: '{{(states.proximity.my_name.state) == 1}}' or value_template: "{(states.proximity.my_name.state) == 1}}"
Neither address my comment
You just added parentheses
First, you should use states() as shown in the second link in the channel topic. Second, you need to add |float to convert a string to a number
{{ states('proximity.my_name') | float == 1 }}
Yes. But the earlier comment about using a > or < rather than an absolute number is also advisable. Or between two values
thanks! ITs not liking my syntax, how do I actually use the or? {{ states('proximity.my_name') | float > 0.8 or < 1.2 }}
oh geeze, I was searching the documentation, could not find that!
for my own, could you link the documentation for this?
thank you!
it's typical Python syntax, I'm not sure if it's explicitly called out for Jinja
is there any online template testing tool/ demo Homeassitant?
> templates
that is with local Homeassistant
I don't have access to a working HA right now
What would be the use of that? You won't have access to your entities, so it will also no be a proper test.
I would suggest to either set up a VPN connection to your HA, or arrange remote access in another way.
I am in house, my UPS is working but my HA is down, it is not connected to the UPS
power was down and I wanted to try out ```
{% set days = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] %} {{ days[now().weekday()] }}
Well, I can tell you that that is going to work
{{ now().strftime('%A') }} will have the same result though
I would only use your approach for other languages besides English
# Time check
sensor time:
- platform: time_date
display_options:
- 'time'
- 'date'
- 'date_time'
- 'date_time_utc'
- 'date_time_iso'
- 'time_date'
- 'time_utc'
- 'beat'
- {{ now().strftime('%A') }}
this is how I I should setup?
Huh? No
Configuration invalid!
Error loading /config/configuration.yaml: invalid key: "OrderedDict([("now().strftime('%A')", None)])"
in "/config/configuration.yaml", line 176, column 0
I have no idea what you are trying to do now?
I am trying to create a weekday sensor
Then create a template sensor with that template for the state
unfinished business
you can not simply add options to the time_date sensor
template:
- sensor:
- name: Weekday
state: "{{ now().strftime('%A') }}"
template:
- sensor:
- name: Weekday
state: "{{ now().strftime('%A') }}"
output is ```yaml
template:
- sensor:
- name: Weekday
state: "Monday"
- name: Weekday
Isn't that what you want?
It will be Tuesday tomorrow
if you add that to your configuration it will create a sensor.weekday with the current weekday as it's state
Hey All. Could anyone help me with debugging a REST sensor template? I can't seem to find any useful info as to where this is going wrong. debugging rest only logs the http response which is fine but the sensors don't seem to be getting updated.
EDIT: Nevermind. It seems to have started working. π€·ββοΈ

π©
With templating is there a way I can get context on how a light was turned off?. For context I have one or more automations to turn a light on and usually one to turn them off (decouples and really simplifies the logic). Problem I'm trying to solve is I have motion based automation that constantly turns the light on and I basically want to ignore turning on if the light was manually turned off... Was hoping to find basically the state info that is shown in the log history of what turned it off and use that in an automation.
{{states.light.office.context}} wondering how how I can serialize that to json so I can see all the properties...
doesn't like to_json
looking more into the context it doesn't seem to be consistent across the light group
especially for parent id
kinda shocked context doesn't persist trigger_id
There are three contexts that you have to test. See this post on the forum: https://community.home-assistant.io/t/state-context-to-ui-automation/427861/14?u=tom_l
I see that table and I'm not seeing that in real life
the context is not in sync
I have 4 zwave switches using switch as light.. I then have a light group triggered by motion. I'd expect all of the light context to be somewhat in the same state.
Which is very very od the context ids/reference are different
This doesn't say much without knowing what caused the lights to change. bar and main have a user_id in the context, so they are changed by something a user did, not by an automation
I told alexa to turn them all off.
then walked in the room triggering them all on by a single automation (granted cabinet shouldn't have came on, expect that one to have different context as it only comes on before sunset).
adding last_updated might also give some more insight as you can see if they are changed at about the same time (so also by the same action).
it could be that other automations also affected the lights, no way for us to know whay you have set up
or maybe both last_changed and last_updated
I get that 100%, just nothing else in the log book and like I said I have one automation to turn on the lights and one automation to turn off the lights after no motion for 15 minutes
I may need to dig into this deeper and get reproduction steps and possibly log a bug
seems like there might be an issue with switch as
Kitchen Main turned on triggered by service light.turn_on
7:08:18 AM - 1 minute ago - Blake
Kitchen Sink turned on
7:09:13 AM - 1 minute ago
Turned them all on via ha ui and one of the switch as and the light group helpers (turned on all lights of the group) are missing the user_id on the context.
yeah, just got it into a good state and it's not syncing properly, there's two different context ids and the update times are all different all going through light.turn_on:light.kitchen (light group helper).
So if I did get this working, still seems like it would be nice for templating to provide some more helpers (to easier detect physical press instead of checking three different states) and maybe even flow through trigger_id.
context is only passed from whatever triggered it, context is not passed from the light group parent to it's children. Only the light group will have the context of the automation/script. Context is not recursive and context is not stored in the state machine. Context is only different in templates within automations or scripts.
I.e. you can't use the template editor to test context
I am hitting a wall in converting a string into a datetime object.
I have a dropdown with various times and i want to store the selected dropdown item from 'input_select.start_work_time' in a second helper 'input_datetime.time_work_start
if i dont select a pre programmed start_work_time then i have to manual fill in the start_work_time into the 'input_datetime.time_work_start'
In this way the start_work_time is always a datetime object which makes further processing of the start_work_time easier.
i have this in my automation:
service: input_datetime.set_datetime
data:
time: "{{ as_local(today_at( states('input_select.start_work_time')+':00' )) }}"
target:
entity_id: input_datetime.time_work_start
But it gives the error:
Invalid time specified: 2022-09-05 05:30:00+02:00 for dictionary value @ data['time']
if this {{ expand('group.zwavejs_fw_updates') | selectattr('state', 'eq', 'unavailable') | map(attribute='entity_id') | list |join(', ') | default(none)}} produces update.kitchen_light_firmare. What do I need to do to get just kitchen light? unfortunately, map(attribute='name') does not produce the desired results so I need to use replace but I cant figure it out
Name is what you need
Whatβs it producing
Time has to be a time format. Hh:mm:ss
I know and I asked in zwave, maybe it is just a bug but the friendly name is Firmware
I wish I understood your comment but i dont
Then why does part of my group have the context? Automation only calls the group
You never named an entity?
in customize.yaml? yes, but the name is right when the entity is available. it is only when it is unavailable that the friendly name is not respected
Everything has context. It just changes based on what was called and how it was called. But the context stored in the state machine i.e. available from templates using the state method or states, will always be an empty context object.
Yes, given that. Whatβs the best way to see how something was turned off given I need only that context information of what changed the main state (not state attributes)
when it is available the friendly name is Kitchen Light Firmware
Edit it through the UI.
Through an automation or a script
it is not worth all that. If there is no way to fix it in a template I will just move on
Iβve been trying to figure that out, see my original post above for context
Only want to turn on lights if it they were manually turned off for at least x minutes
you can take the object_id, split on the underscore and join everything besides the last item with a space
but only if all the sensors following the same entity_id structure
Youβre gonna have to build the logic yourself. Conext when manually pressed will be empty. You can detect the automation only
using the object_id actually looks a lot nicer. Where would I do the split?
well, as you are creating a string already, you can als just do | replace('_firmware', '')
{{ expand('group.zwavejs_fw_updates') | selectattr('state', 'eq', 'unavailable') | map(attribute='object_id') | join(', ') | replace('_firmware', '') | default(none)}}
The automation only?
This really should be easier todo⦠like I see this asked quite a bit on forums.
auh yes, that is exactly what I was trying but order mattered. thanks
you indeed need to do the replace after the join, because as of then it is a string π
The automation only.
What does that even mean
Context will only tel you what automation fired it or what user fired it
It will not tell you who or what pressed the physical switch
Yeah I get that via automation triggers context
Right, so you need to come up with a way to cancel your automation when the context is empty
Seems like a big hole is missing because your trigger context might not contain light state but motion state.
You can filter that with trigger ids
And it seems like entity context changes on any entity state attr changes
yes, thanks. Looks great now. is there a way to capitalize the first letter of each word?
But still would be useless because I trigger on an entirely different device/entity
Thanks for bouncing ideas off. Feels like if I see something in the logbook, I should be able to drive automations or templates from the last log book entries values
You can, the context is what builds the logbook
No, context is only alive during automations
I donβt know how else to explain it
What you see in the state machine is not your current context
So it looks random
|title
If you use states.xxx.xxx.context, youβre getting the wrong context
Bam!!! Thank you !!!
you can use | map('title') before the join
{{ expand('group.zwavejs_fw_updates') | selectattr('state', 'eq', 'unavailable') | map(attribute='object_id') | join(', ') | replace('_firmware', '') | replace('_', ' ') | title }}
This probably can be done more efficient though
ehh, its just a markdown and I am happy with working over efficient. thanks again and just | title worked
So how do I get the current context in an automation of an entity not in a trigger
You donβt. It doesnβt exist. Literally.
You have to capture it when it occurs
oh, hehe, that works on a comma separated string π
And store it where? I donβt want to maintain it, I have literally hundred switches
Z-Wave JS Firmware Status
Total: 45
Update Needed: 0
Up-To-Date: 44
Dead: 1
Dead Devices: Kitchen Light
RIP Kitchen Light π’
Where ever you want, probably a template sensor.
RIP Kitchen Light Firmware status π
Any examples for this?
It doesn't say that, as you ripped off the Firmware part π
Just make a template trigger entity that produces the current context. Iβm on mobile so Iβm not going to write any yaml
Thought you said the current context canβt be trusted..
i'm sorry, but dont know how to use the Hh:mm:ss format, do you have an example?
00:00:00 is midnight, 01:00:00 is 1 etc
Pretty sure 00:00 also works
Hi guys, I was wondering if templates are the way to go for creating a virtual light entity which maps to an existing light. I want to map the new entity's brightness 0-100% to the existing light 0-70%.
Hi, I'm trying to map a text output to a sensor value coming from ESPhome. This is nearly the same as what is discussed on the forum link below but in my case I somehow need to read the sensor value and convert it to an integer before I can map it. https://community.home-assistant.io/t/wanting-to-map-sensor-number-value-to-words/40663/15
I tried the YAML config below but it gives met the "else" clause output while it should be the "0" output so I'm gessing the value isn't coverted to an integer. Could somebody please assist as I'm not familiar with these templates...
`sensor:
- platform: template
sensors:
hc1_mode_text:
friendly_name: "Werkingsmodus HC1"
entity_id: sensor.hc1_mode_text
value_template: >-
{% set mapper = {
'0' : 'Standby',
'1' : 'Only DHW',
'2' : 'Heating + DHW',
'3' : 'Constantly reduced',
'4' : 'Constantly standard' } %}
{% set state = states('sensor.ketel_sens_hc1_mod_operation') | int %}
{{ mapper[state] if state in mapper else 'Foutief' }}`
your "mapper" is using characters, not integers
you need to choose one or the other and be consistent
'0' is not the same as 0
Thanks a lot!
the better question is why don't you send number values from esphome in the first place?
they're still going to end up as strings
meh, esphome disappoints again
it's just because all HA states are strings
how would I go about creating a single automation that monitors all my leak sensors and sends a notification reporting which one had a state change?
what's a keyword there to google?
You probably want to use an automation trigger variable: https://www.home-assistant.io/docs/automation/templating/
thanks
You can add multiple IDs to the state trigger too: https://www.home-assistant.io/docs/automation/trigger#state-trigger
got it thanks
Hello, I'm a shite coder and would appreciate some assistance.
{% set T = ((states('sensor.tent_temperature') | float)) %}
This is what I currently have. It is working. I would like to add a second sensor and divide it by two to get the average of both. How would I do that?
{% set T = ((states('sensor.tent_temperature') | float + states('sensor.second_tent_temperature') )) /2 %}
is this correct?
No. You converted the first to a float, but not the second?
{% set T = ((states('sensor.tent_temperature') | float + states('sensor.second_tent_temperature') | float )) /2 %}
I'm at the level where I can only really copy from others and try to adjust things - I have no actual knowledge of what I'm doing.
*understanding.
This would be a good time to walk through it. It's quite simple
interesting so float is the conversion to a real number
right so float is more accurate at the expense of processing time?
Compared to what? You cannot do math by adding strings
Ah right. Sorry again, I have some learning difficulties so I apologize if I'm being slow.
I got it working. Thank you for your help.
Hi, I have power plug that is added automatically by local tuya and unlike the previous ones that I added using yaml this one has no separate sensors for current consumption but instead it's added as attribute of switch itself. I tried adding sensor as template but I'm doing something wrong. Here is What I have tried:
"sensor: gas_heater_current_consumption: friendly_name: "Gas Heater Power Consumption" device_class: power state: >- {% if {{state_attr('switch.plug2', 'current_consumption')}} %} {{state_attr('switch.plug2', 'current_consumption')}} {% else %} '0' {% endif %}"
but I'm getting error "Invalid config for [template]: [gas_heater_current_consumption] is an invalid option for [template]. Check: template->sensor->0->gas_heater_current_consumption."
Understanding this took me a year of unexpected pain.
Looks like you are mixing the new format and the legacy format
I may be stupid but I'm trying right now all possible combinations and still getting nowhere π¦
....well obviously not all...
@flat shell you have this in template.yaml now? Or at least under the template integration?
sensor:
- unique_id: sensor_gas_heater_power_consumption
name: Gas Heater Power Consumption
device_class: power
state_class: measurement
state: "{{ state_attr('switch.plug2', 'current_consumption') | default(0, true) }}"
the entity_id will be sensor.gas_heater_power_consumption, you can change that by editing the entity_id in the GUI (only if a unique_id is provided)
yes it's in my template.yaml I just tried it and it's not working. Maybe because I already have some binary sensors?
this is my complete template.yaml:
@flat shell posted a code wall, it is moved here --> https://hastebin.com/otedicidiw
you need to add - for each sensor type. template: expects a list
template:
- sensor:
- name: sensor 1
state: "{{ some template }}"
- name: sensor 2
state: "{{ some other template }}"
- binary_sensor:
- name: binary sensor 1
state: "{{ yet another template }}"
That was not an issue when you had only binary_sensor, because with one item it will be treated as a list, but after you added sensor as well, that caused errors
ok, ill try and fix it
your binary sensors are also wrong btw, and using the same mix of new and legacy format
and your indentation is off
I know now... I'm trying right now to rewrite it to new format
It's working! Thank you very much!!!
Is there a way in my dictionary set_color_temp to use at 8pm and after9pm 400 and 370. Check if it's not equal to either 400 or 370. I'm not sure with selectattr if 'not in' can be used
Seems dpaste is down?
https://pastebin.com/si6N8ST8
use rejectattr(attribute, 'in', value) for that
How would I do that? As I only want to check for 2 temperatures on those 2
The rest are single numbers.
rejectattr('attributes.color_temp', 'in' , [400, 370])
I assume that goes here
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) |
selectattr('attributes.color_temp', 'defined') |
selectattr('attributes.color_temp', 'ne', set_color_temp[script_type]) | rejectattr('attributes.color_temp', 'in' , [400, 370]) |
list | count == number_of_lights }}
you can simplify that:
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.color_temp', 'defined') | rejectattr('attributes.color_temp', 'in', [ set_color_temp[script_type], 400, 370 ]) | list | count == number_of_lights }}
forgot to remove one pipe
And this would allow it to still work if it's 222? The goal is to accept if any of the lights are 400 or 370 when the dictionary is 370 or 400. Essentially don't accept 370 if it should be 222
if what is 222
set_color_temp[script_type]
you first selected all lights with the color_temp not equal to that variable, and then rejected all with color_temp equal to 370 and 400
I combined those in one rejectattr
I see. So if it is false at 222 because the lights are at 370 then it won't become true because the lights are 370 at the rejectattr. It would use rejectattr if the first select attr is false when the lights are 370 or 400? Then it will reject both and count the lights? I'm sure I probably confused you. I'm trying to wrap my head around trying explain this.
I just want to make sure if it's Day and the lights are 370 when they should be 222 that it will be false not true. Only true when it should be 370 and it's not equal because the lights are 400 for example so then it becomes true.
number_of_lights seems to be all the lights in a particular area which are on
What are you trying to do with that condition then?
that condition will be always be false if one of those lights which are on doesn't support color_temp
For that condition to be true, all the lights in the area need to support color_temp and the color_temp should be set to anything besides set_color_temp[script_type], 400 and 370
that's what your current, updated, condition does
Yes not equal to set_color_temp[script_type] and if the set_color_temp[script_type] is 370 then all lights in the area must not equal 370 or 400
ah, so when it's 222 you only want to check for 222, but when it is 370 you also want to check for 400
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.color_temp', 'defined') | rejectattr('attributes.color_temp', 'in', iif(set_color_temp[script_type] == 370, [370, 400],[set_color_temp[script_type]])) | list | count == number_of_lights }}
small correction applied
Yes I didn't know this could be done.
Thank you.
Missed another ) at the rejectattr but I found and fixed that, by learning from the best at Jinja (you,Petro, a few others).
I don't see anything missing π
Hello there, I am relatively new in ha. I learned to crawl and do some stuff I wanted to do. But now I can't find the answer to the question how to set a default value within a template, if the e.g. sensor.xyz is not yet having data. How can I set an initial value to a sensor within a template? Maybe a link to an example will be enough... I could not find one...
can you give some more details on what you actually want to do
I simply add different sensor data into a new one. And as long as not all haver received a value (after restart of ha) the visualisation gives an error, that the data is not available. So I thought just give an initial default to make it work.
.share your current template
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
Can I paste the four lines?
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
- name: "Solare Leistung Summe"
unique_id: "solar_power_sum"
unit_of_measurement: 'W'
state: '{{ (states("sensor.wr1_powerdc_1k") | int + states("sensor.wr1_powerdc_2k") | int + states("sensor.wr2_powerdc_1k") | int + states("sensor.wr2_powerdc_2k") | int + states("sensor.wr2_powerdc_3k") | int) }}'
device_class: power
please see the bot message
And you and add defaults to your int filters to avoid the errors are startup
int(0)
is there nice simply way to sort a list of states by last changed? timestamp
such as a filter instead of having to loop through it
{{ expand(["switch.fr_table_lamp", "switch.fr_reading_lamp"])|sort(attribute="last_changed")|map(attribute='entity_id')|list }}
like that?
yeah i think that will do the trick, thanks
Just posting this for anyone looking to do the same in future, code to create a sensor to get the last motion sensor detected with an on state else fall back to the last sensor that changed- name: "[Motion] Last Active Sensor" state: "{{ (states.binary_sensor | selectattr('entity_id', 'match', '^binary_sensor\\.motion_') | sort(attribute='last_changed', reverse = True) | sort(attribute='state', reverse = True)| map(attribute='entity_id') | list)[0] }}" icon: mdi:motion-sensor and you can create another sensor to display the name or area "{{ states[states.sensor.motion_last_active_sensor.state].name | regex_replace('^\\s*\\[.*?\\]\\s*', '') }}" and "{{ area_name(states.sensor.motion_last_active_sensor.state) }}" , may require a tweak to the '^binary_sensor\\.motion_' based on your naming convention, my sensors don't show under motion domain so i target them using my own naming convention. the regex for the name is to strip out any prefixes contained within square brackets aka [Motion Sensor] Computer Desk and leave just Computer Desk
yes, that's what I would like to do. But how, I found no documentation of the syntax, nor an example. So one example would help, that what I am searching. Can you post one example of how it would look like? Thanks!
There is a link to a post about defaults in the pinned posts in this channel
Thanks!!!!! That is what I didn't find....
For template sensors, what's the best way to handle when the source sensor is unknown/unavailable? Should everything be wrapped w/ an if chain to check and pass through that status or is there a better way? I'd rather not default it to a value since that'd technically be reporting an incorrect state for the template sensor
Ex. {{ states('sensor.garage_door_y_axis') | int > -720 }}, where that sensor is unavailable for a few during start up, the template sensor should report unavailable as well, but as is since there's no default (and shouldn't be one), it'll error.
Best practice is to supply a default value, e.g. {{ states('sensor.garage_door_y_axis') | int(0) > -720 }} if you want it to show unavailable as well then use the template integration rather than the template sensor platform ("new" style templates) for which you can supply an availability template like this: availability: "{{ states('sensor.garage_door_y_axis')|is_number }}"
Ahh, interesting. So if I apply that availability attribute, even though the actual template may be returning inaccurate data, the sensor won't report that and instead will report as unavailable?
If the availability: template returns false the state becomes unknown, no matter what the state template resolves to. The state template can still generate errors in the log though, which is why the default for the int filter is required.
I gotcha, that makes sense. Thanks for that @fossil venture
There's also availability_template in the legacy format
Doh. So there is.
It's quite a while since I've used it.
@cloud mirage https://www.home-assistant.io/integrations/command_line/
Only binary_sensors
If the original sensor doesnt have that option you could wrap it in a template_sensor (https://www.home-assistant.io/integrations/template/#binary_sensor): ```yaml
template:
binary_sensor:
- delayed_sensor:
state: "{{ states('binary_sensor.original_sensor') }}"
delay_on: "0:01:00"
delay_off: "0:01:00"
that's a good thought, but you'd need state: "{{ states('binary_sensor.original_sensor') }}"
Oops. Simple mistake to make when writing stuff without testing it
I have a working example of sorting the hourly energy price and comparing if the actual hour is the cheapest or not. However I only want to sort the coming 7 hours, not the entire day of 24 hours. How do I solve it?
{%- set sorted_prices = state_attr('sensor.nordpool_kwh_se3_sek_3_095_025','today')|sort %}
{{ states('sensor.nordpool_kwh_se3_sek_3_095_025')|float <= sorted_prices[0]|float }}
can you post an example of the 'today' attribute on 'sensor.nordpool_kwh_se3_sek_3_095_025'?
The values are like this https://paste.debian.net/1253109/
ok, are the top 7 the last 7 hours?
{%- set sorted_prices = state_attr('sensor.nordpool_kwh_se3_sek_3_095_025','today')[:7]|sort %}
{{ states('sensor.nordpool_kwh_se3_sek_3_095_025')|float <= sorted_prices[0] }}
you also could just get the min or max out of it
instead of sorting
{{ states('sensor.nordpool_kwh_se3_sek_3_095_025')|float <= state_attr('sensor.nordpool_kwh_se3_sek_3_095_025','today')[:7] | min }}
Thanks a lot! Will try that out.
noob question: how do you do a simple string compare in a template if condition?
i wanna do
{{user}} == Hypnopunch
you can't get that information in the backend
user is only available in the front end and multiple people can be logged in at the same time
π i have a button and wanna add to an input counter if i press the button on my app and a different counter if my wife presses it on her app
That is possible to do, but it's advanced templating. YOu'd need to explain what you expect to happen if the user is not one of the ones in question
The users have to be people though.
Please use a code share site to share code or logs, for example:
-
http://pastie.org/ (select YAML for the language)
-
https://dpaste.org/ (select YAML for the language)
-
https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
it's a simple button card. when pressed it calls a script
can you post the script please
ye 1 sec
its just playing a thing on the speaker for now, but i'll eventually do other stuff
http://pastie.org/p/7wfCdxYGJRqswI9acUj9YU this is the buttons YAML
right, but I need to see the full counter script
what you posted is only a single action in your full script
post the trace variables
click on the trace, then click on the step variables tab and paste the contents
will do, but noticed something. if i change to visual editor and click Test on the template condition i get this
Error occurred while testing condition template value should be a string for dictionary value @ data['value_template']. Got None
did you copy exactly what I pasted or did you alter it?
i altered just my name and the quotes around No Person
did you alter the quotes around the name == 'husband'?
theres interior quotes and exterior quotes, both are needed.
they are there
- condition: template
value_template: "{{ user == 'Husband' }}"
then:```
I don't know how you can be getting that error as that's the only value_template
are you sure you're looking at the correct trace and not an old one?
so.. i dont see a step variables tab. i clicked debug script -> clicked on the branch button on the left -> Step Config tab
and i get this
http://pastie.org/p/6r44cMS1WvJXrSPgeskpnC
step variables are at the bottom of the page
and what you see there is fine
changed variables, sorry
if you don't get changed variables, then you didn't add the variable
see my paste dump again and look at the top of the script, you'll see a variables section
na, give me a sec tho
sorry, mistake in a line
``
{% set person = states.person | selectattr('attributes.user_id', 'eq', context.user_id) | first | default %}
replace that line with what I just posted
same result
post trace
post what you have for the user variable
I've got a binary_sensor for a Dahua camera that goes to on when a human is detected. I'd like to populate the last time that sensor went to on. Getting the last_changed attribute will only get me the last state change. My thought was to make a helper variable that populates when the switch goes to on, but is there a way of doing this strictly within a template?
variables:
user: >
{% if context is defined and context.user_id is defined and context.user_id
%} {% set person = states.person | selectattr('attributes.user_id', 'eq',
context.user_id) | first | default %}
{{ person.name }}
{% else %}
No Person
{% endif %}
sequence:```
should be working
change it to
{{ states.person | selectattr('attributes.user_id', 'eq', context.user_id) | map(attribute='name') | first | default }}
didn't work either
when it doesn't work, just jump straight to the trace
are you pressing test or pressing the button
and are you 100% sure your user is a person
ive tried pressing the button, running script directly from the script
it should work from the button only
anyways, I need to see the output of the template, i.e. the trace variables
no
it should take 2 seconds to get this info
update -> press button -> go to trace,
you didn't change the template
im pretending to work at the same time sorry
it's still outputting No Person and what I posted above will not do that
replace the whole user template with
{{ states.person | selectattr('attributes.user_id', 'eq', context.user_id) | map(attribute='name') | first | default }}
i see
failed to call service script/1662586451099. UndefinedError: 'context' is undefined
are you using the button or the test script button
button
that makes no sense
unless the button doesn't transfer context
does the button press show up in logbook?
... what do you mean
counterscript started triggered by service script.1662586451099
thats what i get in logbook
the trace shows that context exists.
i hadnt replaced the entire thing when i sent the last trace
after replacing it it doesnt work
Stopped because of unknown reason "null" at September 7, 2022 at 3:53:02 PM (runtime: 0.01 seconds) i get that in Trace Timeline
i gotta hop off, got a meeting in 3 mins
really appreciate your help. enjoy the coffee π
thanks, giove me a moment to set this up on my end
ok, it's a stupid bug
change your button to
- type: button
entity: script.counterscript
tap_action:
action: call-service
service: script.turn_on
data:
entity_id: script.counterscript
in the UI
instead of using script.counterscript as the service, use script.turn_on
and send entity_id in the data
I have been trying to get a MQTT sensor issue resolved that has objects that are not always in the published topic:
{"windDir": "326.66798419", "rain24_in": "0.0", "hourRain_in": "0.0", "txBatteryStatus": "0.0", "windSpeed_mph": "4.0", "outTempBatteryStatus": "4.0",
"rainRate_inch_per_hour": "0.0", "dateTime": "1662591804.0", "dayRain_in": "0.0", "usUnits": "1.0"}
{"windDir": "326.66798419", "rain24_in": "0.0", "hourRain_in": "0.0", "txBatteryStatus": "0.0", "windSpeed_mph": "1.0", "outTempBatteryStatus": "1.0",
"rainRate_inch_per_hour": "0.0", "dateTime": "1662591850.0", "dayRain_in": "0.0", "outTemp_F": "75.30", "windchill_F": "75.3", "usUnits": "1.0"}
value_json.windchill_f | default(none)
that will stop the values bouncing from zero?
it will be unavailable when it doesn't get the attribute
thank you
np
I tried value_template: "{{ value_json.windchill_F | default(none) }}" but instead of zero I am getting none.
i would like to have previous value remain.
@mighty ledge i was able to get it working like this. i got my user_id from the trace and entered it there
user: >
{% set person = states.person|selectattr("attributes.user_id", "==",
"7b6ad9dsgfsdgdsdsg9c36")|map(attribute="attributes.friendly_name")|first
%}
{{ person }}```
Add this. Before the conext.user_id
In the selectattr
In combo with the button config change
what exactly does selectattr do?
@mighty ledge is there a way of retaining the previous value if that object is not present?
https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.selectattr it's a filter to the condition you specify
@summer iron posted a code wall, it is moved here --> https://hastebin.com/zimuzamuyu
Damnit.. i intended to do a code block. But... Ah well.. My entire message is in the one above.
If anyone could point me at where i would do what i wish.. i would be a very happy camper.
if it is your first template sensor, you can place it in configuration.yaml
template:
- sensor:
- the code you posted
As soon as you create more, you'll probably want to put them in a separate template.yaml
YEah, Got some help on that by a friend who knows the structure of HA a lot more.
Set myself up some .yaml files and includes in preperation for all the stuff i intend to do π
Thanks a lot for the reply tho.
in the condition of an automation how do i check if trigger.event.data.file contains the string abc123 using a template condition
{{ 'abc123' in trigger.event.data.file }}
I'm not sure if it's possible in MQTT. You might want to just make a template sensor that uses an MQTT topic as a trigger.
Hi,
when I do this:
{%- set gesamttally = gesamttally + item.tally |float %}
in a for loop and declare before like this:
{%- set gesamttally = 0 %}
after the for loop, it is still 0. π¦ why?
jinja's doesn't have access to information in the loop. It's scope is 1 dimensional. Meaning, things that happen in the loop can only be accessed in the loop.
if you want a counter, you have to use namespace
i.e. the code I provided days ago does that π
@mental violet ^
i think I have done it, thank you π
Is the formatting for templates different in the automation editor? I see there is an asterisk but i cannot see what that means
I copied in a template that worked fine in YAML, but it adds ' where there should be and puts it on two lines.
post what you're talking about
My template is:
{{ states('input_select.home_away') != 'away' and now().month >= 5 and now().month <= 9 }}
when you save that in the UI, you'll get double '' for every '
that's expected
it will also cut it up into multiple lines
Is that a bug or is that how it is supposed to be? And is there documentation somewhere how I am supposed to write them? I searched but I could not really find anything very detailed for the automation editor
see this
as for "how to write them", you can write them however you want as long as it gets the result you want
the documentation covers methods and filters you can use, it doesn't really cover the 'best practices'
Can you just not write templates in the automation editor then?
you can
they still work
see pin 1 about the test button, as I have a feeling that's why you're asking these questions
They will still work even with the double ' and it being on two lines?
yes
It fails in vs code and in the template editor under developer tools with the format that the automation editor uses
yep, it will
as for vscode, why are you looking at that if you're using the automation editor?
Well originally because the test button wasn't working with the templates
hi guys, I had this automation working for my sprinkler to irrigate only if precipitation forecast is > 0 but since weeks the test goes wrong with this error "template value should be a string for dictionary value @ data['value_template']. Got None"
{{ state_attr('weather.rome', 'forecast')[0].precipitation > 0.1 }}
anybody knows if anything changed in HA?
thank you
you'll need to look at that entity in
-> States
it's a pretty straightforward template
I get "true" instead a number. i suppo se this might be the problem. the strange part is that it ahs been working for months
so what you're saying is that you're not really the task master yet
not at this for sure π but maybe you can tell me what "template value should be a string for dictionary value @ data['value_template']. does mean because I got no clue.β₯οΈ
Well for you it is for sure, I wouldn't be here otherwise π
if it's true/false just remove the > 0.1
I get true if I test in developer tools->models, but in states i see numeric values:
forecast:
- condition: partlycloudy
temperature: 25.5
wind_speed: 17.3
** precipitation: 0.4**
but you said it was true before
this
so what is it?
thst's what i suppose because while testing model in developer tools I get string result. But I expected to get the number value as presented in states
any numerical comparision is going to give you a true or false
that's what > or < does
is 4 greater than 5? -> false
is 4 greater than 3? -> true
so when you use the > or < or <= or >= or == or !=, you're going to get a True/False
perfect that could be enought but if i test the condition inside automation this template provides an error (while I get true in the model test)
did you put quotes around your template?
"{{ ' ' }}"
outside quotes = ", inside quotes = '
if you're using the automation editor, quotes don't matter but see pin 1, as the test condition button doesn't work
yes i did
so it is an interface bug?π²
yes, that's why we have pins
because 90394802938409283409820348024 people ask this a day π
π
oh the pin is that thing on the top right? great i should have a discord tutorial first in this case π anyway thank you, I'll take a look at those pins right now (my next task)
hi...I want to merge two entities and create one myself ? is it possible ...
reason : for android tv one entity provides some informations and other entity provides some more which aren't available in other entity ...soo if I could merge them together by adding as a custom sensor ..I can get attributs of both together ...is it possible ?
you can build a template sensor
Hi guys, i'm setting up a dashboard to control my pool/spa pumps and heaters. I'm using a mushroom template card for this. Basically for the secondary info on the card I want it to Display "On / 80Β°F" where the temp is the current_temperature attribute of climate.pentair_pool_heat
{{ states('switch.pentair_pool') | title }} / {{ state_attr("climate.pentair_pool_heat", "current_temperature")}}Β°F
This works as expected, but how would I make it only show the / 80Β°F part if the attribute is available? I don't want it to display / UnavailableΒ°F basically. Any help appreciated
can you share me any templete example with custom sensor and attributes ? trying to find one under templetes manual
there are lots of examples here: https://www.home-assistant.io/integrations/template/
thanks
one doubt ...can I skip the state and directly get to attributes ?
also this is a media device... should I add a device type ?
the docs indicates what's required. an entity without a state doesn't make sense
such a dump question
yeah....just realised
What is the meaning behind these when assigning icons etc?
|
|-
lucky for you, there's a whole site for that: https://yaml-multiline.info/
what am i doing wrong here?
it shows unavailable? and it shows as sensor.mitv...instead i want it to show as media_player.mitv
here is the code can yu please help?
`template:
- sensor:
- name: mitv
state: "{{ media_player.android_tv }}"
attributes:
media_title: >
{% if is_state('media_player.android_tv', 'playing') %}
{{state_attr('media_player.android_tv','media_title')}}
{% endif %} `
- name: mitv
first, you haven't provided an alternative if your if statement evaluates to false
second, this is the right syntax:
state: "{{ media_player.android_tv }}"
third:
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), http://pastie.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
fourth, you're creating a sensor, not a media_player entity
perhaps you really wanted this? https://www.home-assistant.io/integrations/universal/
ha....sorry for being nobbie..and guess this is want i needed ..thanks
but just as i trying to learn is this ryt way of making a sensor? i want the state of that entity to reflect in this custom sensor state
state: >
{{states('media_player.android_tv')}}
attributes:
media_title: >
{% if is_state('media_player.android_tv', 'playing') %}
{{state_attr('media_player.android_tv','media_title')}}
{% else %}
unavailable
{% endif %}```
it looks empty to me.. nothing is visible
Hi, i'm using mini graph cards
im trying to set a secondary entity but it shows up as NaN in the card
if i do this, it works correctly
state_map:
- value: "steady"
label: steady
- value: "falling slightly"
label: falling slightly
and so on...
how would i do this without hardcoding? theres more than 20 states
hi i tried and these are the results
when i use children it does not overwrite or create any new attribute
and when i try the below code..it shows the state but cant find none of the below attributes.
platform: universal
name: mitv
attributes:
state: media_player.android_tv
media_title: media_player.android_tv|media_title
entity_picture: media_player.android_tv_192_168_0_137|entity_picture
app_name: media_player.android_tv_192_168_0_137|app_name```
im not actually getting things right..i guess only limited attributes can be used may be.
what i really wanted is to have is a media player with all the attributes of this media player `media_player.android_tv_192_168_0_137` and also add extra attributes from other media player...like media_title
Inside of an automation blueprint I'm creating, am I able to use templating to call expand on a group of entities in a single input, e.g. !input target_lights so I can iterate over them?
Assuming target_lights is defined in the top of the blueprint as:
name: Lights
description: The lights to keep in sync.
selector:
target:
entity:
domain: light```
include the target in a variable, then use the variable where ever you want in a template.
variables:
my_target: !include target_lights
my_iterating_crap: >
{% for t in my_target.entity_id %}
...
{% endfor %}
Hello, is it possible to query a sensor value at a past timestamp? Best regards
you need to get that out of the database using an sql sensor
Here's one I prepared earlier: ```
SELECT state FROM states WHERE entity_id = 'sensor.total_cost_today' AND HOUR(TIMEDIFF(UTC_TIMESTAMP(), last_updated))>=24 ORDER BY last_updated DESC LIMIT 1
This gives me the total cost 24 hours ago.
I have a Z-wave lock that reports events, like so:
https://imgur.com/a/iHTyul8
Is there any way to make a template sensor that indicates what the most recent event was?
Someone once helped me with a template, of which this is a part:
{% set end = 'light_energy' %}
{% set ns = namespace(states=[]) %}
{% for s in states.sensor %}
{% if s.object_id.endswith(end) %}
It checks for sensors whose entity_id ends with light_energy. I was wondering if there is a function that can check if a sensor contains a certain string instead of if it ends with this string?
I don't remember writing that, but π€·
hey guys I'm trying to build an automation that sets a guest mode until a certain time (guesttimer_end) is reached. I need to calculate the time between now and the end time and delay that much. But I'm stuck a bit, any pointers would be appreciated:
{{ today_at(states('input_datetime.guestmode_end')) - now() }}```
I know I still need to convert the delta back to military time format so that the delay works
i'm on a mission to see if I can have all of my NR flows as HA automations, but this is one of the more tricky ones π
delay also works with seconds, do you can use (today_at(states('input_datetime.guestmode_end')) - now()).total_seconds()
tx. still struggling tho. this one stays in NR for a bit π
If you would save date and time in your input_datetime instead of time only, it would be easier
Good morning guys π Could I get some help with some templates? I have been getting these errors in a bunch of templates and been trying to fix them for a long time. Il share the simplest one to start with
In 'condition':
In 'template' condition: UndefinedError: 'None' has no attribute 'object_id'```
would like to figure out how I can protect the template from triggering if the entity trigering has no entity_id or object_id or if the device is not available
I cant seem to find any solution online on how to fix this error when using this as a trigger
- platform: event
event_type: state_changed```
This automation will probably trigger multiple times per second if you have a lot of entities
You can create a template sensor which has as state a count of all battery sensors you consider as low
And as an attribute the list of the sensors which are low
Trigger on a state change, check in the condition if it increased and compare the attribute in the to_state and for_state to see which entity causes the increase
Yes, I have hundreds of sensors so it does trigger very often. but its been working fine for years.
Main thing I wanted to achieve templating like this is the template needs to be flexible, meaning if i add or remove a new sensor as long as i name it right it should be transparent to the template and not have to modify any code for it to work
Im not sure im following your sugestion and if that can be implemented to achieve the above
I created this:
/config/configuration.yaml
template:
- binary_sensor:
- name: "Washer Status"
state: >
{% if state_attr('sensor.washer_current_power', 'W')|float >= 5 %}
on
{% else %}
off
{% endif %}
I tried to add it to the dashboard, but I cant find it. How do i do this
Nevermind, i forgot to restart HA after i coded it
Sure, you can use similar templates as you do now te determine which sensors should be taken into account
I need to wrap my head around what you are sugesting, I think i kind of get but not sure how to implement it
i need to think about it maybe do some tests, so i create a new template sensor using a for loop to filter out only the sensors im interested in
and then use that info in the state change condition to trigger this template?
its kind of what im understanding
but this will not change
{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt`) | selectattr('state', 'eq', 'on') | list | count }}
You don't need a loop, and it won't trigger that much
The template above will give you a count of all binary_sensors for which the entity_id ends with batt and which are on
ok..
Use that as the state of the template sensor
For the attribute you can use
{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt`) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
Then you have all you need for the trigger and to determine which entity caused it
Ok It turns out it still doesnt work
template:
- binary_sensor:
- name: "Washer Status"
state: >
{%- if states('sensor.washer_current_power') >= 5 -%}
on
{% else %}
off
{% endif %}
https://paste.debian.net/hidden/90ea33de to see the other two sensors that I experimented with to show that the above should work
"Washer Watts" and "Jinja Test" both work, but "Washer Status" doesn't work. Why?
The only think you need for the state template is
{{ states('sensor.washer_current_power') | float(0) >= 5 }}
And states are strings, so you need to convert that to a number using the float filter
thank you
This returns true or false which is what the binary sensor template expects
ok i need to go out 30 min, when i get back will test your code and take it from there, I would like to avoid modifing my templates to much, i have a few other templates a lot more complex and convoluted that are constructed in the same fashion that throw a lot more of these errors (this is the simplest template of all so i thought i would start here)
Getting this error:
You need quotes around the template
- platform: template
sensors:
Low_battery_count:
friendly_name: Low Battery count template
value_template: "{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt') | selectattr('state', 'eq', 'on') | list | count }}"
attribute_templates:
entities: "{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}"
Invalid config for [sensor.template]: extra keys not allowed @ data['attribute_templates']. Got OrderedDict([('entities', "{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt`) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}")])
invalid slug Low_battery_count (try low_battery_count) for dictionary value @ data['sensors']. Got OrderedDict([('Low_battery_count', OrderedDict([('friendly_name', 'Low Battery count template'), ('value_template', "{{ states.binary_sensor | selectattr('entity_id', 'match', '.*batt`) | selectattr('state', 'eq', 'on') | list | count }}")]))]). (See ?, line ?).```
still same error π€
Fixed it a second time
yes i noticed π
but still same error argg
fixed the capital letter and now i get the above
Got a backticks instead of a quote there
after batt?
that did it π
ok so just checked and this works now and counts the low batteries that are ON
Yes, that was the intention, and those entities should be listed in the attribute
and shows the entities that they are also in the attributes
yes
now how do i trigger my template based on this sensor?
but will the rest of the automation still work? meaning its all based on state_change https://hastebin.com/etabucupuv.csharp
IΒ΄m not programmer, it took me hundreds of hours to come up with these templates, i have a bunch or more complex ones using the same method, I cant aford to rebuild them all π
Bear with me, im proud of them personaly, put a lot of effort making them, but also ashamed to share them.. lol IΒ΄m sure a programmer with good knowledge of HA might trow his hands up in the air because I screwed up a lot and maybe overcomplicated things, buy hey they work and do excatly what i want:
https://hastebin.com/rifidaxame.kotlin
https://hastebin.com/netaloqaxa.http
and back in the day everyone advised me to go the state_change route for what i wanted to do
(I just wanna get rid of the warning in the logs)
these kind of warnings: https://hastebin.com/rohigosoti.coffeescript
you mean here and new_state.status != 'unknown' and new_state.status != 'unavailable' and new_state.status != 'none' and new_state.entity_id != 'none' and new_state.object_id != 'none'
Yes
will that change avoid the template becoming true which is what i have been trying in this section? precisely to avoid these errors
I think so, I'm on mobile so it's a bit cumbersome to review the entire thing
LOL you guys dont stop amazing me, writing code on your phones, I need a few screens to make sense of anything π€£
and new_state.status != 'unknown' and new_state.status != 'unavailable' and new_state.status is not none
and new_state.entity_id is not none and new_state.object_id is not none
but entity_id and object_id will always be populated, so not sure why you have to check for those
The errors he posted indicated that
just trying things out of desperation tbh
Which I found strange as well though
but yeas as TheFes said i guided my self by the errors in the logs
well it is coming from a state changed event, so many that event has some oddness to it
Petro you left some in the != format in you repply, should i not change all?
what should i use where?
exactly what I wrote π
ok ill try π
added your suggestion to all my state_change based templates, rebooted fine, i guess i just need to let it run a few days and see if errors have gone away
unless you know how i could test the change now with the developer tools and try to force these warnings
they have been happening randomly so I dont know how i can force them to happen
To test an automation there's three stages you can follow. Testing the action, the condition and action, and the whole automation:
- Use Configuration -> Automations to find the automation and then push Run Actions. If this fails your problem is in the
action:section, and details should be found in your log file - Use Developer tools -> Services and call
automation.triggeron the automation withskip_condition: false. If the first passes but this fails then the problem is in yourcondition:block - Use Developer tools -> States to find the trigger entity, click the name, then change the state (at the top) to something that'll trigger the automation before pushing Set State. If this fails then the problem is with your
trigger:section, or the automation is turned off (you can check that in Developer tools -> States).
You can also see this section in the docs and with HA 2021.4 onwards debug automations.
You could try 3)
But I'm not sure if that will cause a state changed event
Or create a trigger based template binary sensor which matches your filter criteria and use an input boolean as the trigger
that is what i was playing around for a while cant seem to trigger it, i will just let ir run a few days and see π
one more question, im upgrading an old install 2021 to current release and having this problem, i know i need tro set a default value if sensor not available but not sure how exactly:
You should use states() to get the state.
For the defaults there is an explanation in the pinned posts in this channel
But I would advice to use availability_template to check if your source sensors are providing a numeric value
yes i was reading that but struggle to understand how to implement it
something along these lines? https://hastebin.com/ufusoweruc.yaml
The availability_template should return true or false
And it's availability_template: not just availability:
availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
And you are not using states() everywhere. You only changed it in the if statement
If wait, you were already using it there
like this?
value_template: "{% if states('sensor.airconlr01a_current_power_usage') | int(0) > 10 %} {{ states('sensor.airconlr01a_current_power_usage.state')| float*7) | round(2) }} {% else %} {{ states('sensor.airconlr01a_current_power_usage.state') | round(2) }} {%endif %}"
availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
unit_of_measurement: W```
Indentation seems off, but besides that it looks fine
Well, I would use the multi line yaml format for that state template
if you type "yaml" then go to next sentence after the first three ` code block start then your code gets colored and easier to read like this: yaml value_template: "{% if states('sensor.airconlr01a_current_power_usage') | int(0) > 10 %} {{ states('sensor.airconlr01a_current_power_usage.state')| float*7) | round(2) }} {% else %} {{ states('sensor.airconlr01a_current_power_usage.state') | round(2) }} {%endif %}" availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}" unit_of_measurement: W
value_template: >
{% if states('sensor.airconlr01a_current_power_usage') | int(0) > 10 %}
{{ states('sensor.airconlr01a_current_power_usage.state')| float*7) | round(2) }}
{% else %}
{{ states('sensor.airconlr01a_current_power_usage.state') | round(2) }}
{%endif %}
availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
unit_of_measurement: W
Took me a couple of times to get that right on mobile
how exactly to do this can you write a small example?
Type three then no spaces type yaml then hit enter then paste code then type three
Shit
It ate my ` after each three lol
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), http://pastie.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
Just add yaml directly after the backticks to format it as YAML
got it thanks π
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensors']['airconlr01a_current_corrected_power_usage']['value_template']. Got "{% if states('sensor.airconlr01a_current_power_usage') | int(0) > 10 %}\n {{ states('sensor.airconlr01a_current_power_usage.state')| float*7) | round(2) }}\n{% else %}\n {{ states('sensor.airconlr01a_current_power_usage.state') | round(2) }}\n{%endif %}\n". (See ?, line ?).```
That's not valid YAML π
jaja yeah just testing your sugestion
What's your complete code for the sensor now?
your last post
That's not the complete code
- platform: template
sensors:
airconlr01a_current_corrected_power_usage:
friendly_name: AirConLr01a Current Corrected Power Usage
value_template: >
{% if states('sensor.airconlr01a_current_power_usage') | int > 10 %}
{{ states('sensor.airconlr01a_current_power_usage')| float*7) | round(2) }}
{% else %}
{{ states('sensor.airconlr01a_current_power_usage') | round(2) }}
{%endif %}
availability_template: "{{ states('sensor.airconlr01a_current_power_usage') | is_number }}"
unit_of_measurement: W```
You should remove .state after every entity_id