#templates-archived
1 messages · Page 4 of 1
Ok got it, thanks @marble jackal and @trail ginkgo . I didn't realise a new sensor would be created doh! So followed the tut again, and got it working, this time looking for the newly created entity and not at the old wemos.
butthats what I am doing isnt it? state: > {{(states('sensor.calculated_bruto_verbruik')|float(0) - states('sensor.sensors_huidig_verbruik_summed')|float(0))|round(2,none)}} availability: > {% set x = ['unavailable','unknown'] %} {{states('sensor.calculated_bruto_verbruik') not in x and states('sensor.sensors_huidig_verbruik_summed') not in x and (0 <(states('sensor.calculated_bruto_verbruik')|float(0) - states('sensor.sensors_huidig_verbruik_summed')|float(0)) < 4000)}} . Repeating the full state template?
Oh right, my bad.. was still early when I replied
hehe, thanks for your response !
maybe I can even simplify to {{states('sensor.calculated_bruto_verbruik')|is_number and states('sensor.sensors_huidig_verbruik_summed')|is_number and (0 <(states('sensor.calculated_bruto_verbruik')|float(0) - states('sensor.sensors_huidig_verbruik_summed')|float(0)) < 4000)}}
theres an issue with this template though. Because the calculated_bruto_verbruik doenst update as frequently as the huidig_verbruik_summed, there are many negative results, and thus many 'unavailables'. Maybe it be better off to add an 'positive' filter to the state template
like:```
{{[0, (states('sensor.calculated_bruto_verbruik')|float(0) -
states('sensor.sensors_huidig_verbruik_summed')|float(0))|round(2,none)]|max}}
To avoid the unavailables you could also try to keep it on the current state in the state template
I need to grab "last_changed" from an input_boolean convert it to "date" without specific time and then check if x days have elapsed? Can't seem to get the syntax right :/
ValueError: Template error: as_timestamp got invalid input 'None' when rendering template '{% if is_state("input_boolean.chore_vacuum_badevaerelse", "on") -%}
{{ as_timestamp(state_attr("input_boolean.chore_vacuum_badevaerelse", "last_changed")) }}
{%- endif %}' but no default was specified
true
{% else %}
false
{%- endif %}```
kinda got it working, but how to use as a condition for automation?
Hmm {{ as_timestamp(now())-as_timestamp(states.input_boolean.chore_vacuum_badevaerelse.last_changed) > 2 }}
That returns true, but it doesn't seem to run the automation and the test button still spews an error?
However it works under dev tools
regarding the test button, see the first pinned message
and that looks like 2 seconds...
Yeah I found out, how do i combine 2 checks in the template? Like the toggle must be on AND now() - last_changed > 2
I know it's 2 seconds for testing 🙂
exactly like that
I would do this, BTW: {{ states.switch.fr_table_lamp.last_changed < now() - timedelta(days=2) }}
that's alot more readable thanks
AND doesn't seem to work tho, to combine multiple checks
pretty much only that
god damn i hate syntax diffs between languages 😄
this jinja is weird mix between json and python or something
{{ states.input_boolean.chore_vacuum_badevaerelse.state == 'on' }}
is this the simplest way to check if boolean is true?
no
see giant warning box and surrounding text: https://www.home-assistant.io/docs/configuration/templating/#states
but there is no way to use states() to get last_changed right?
so i would have to use states. anyways?
you asked about {{ states.input_boolean.chore_vacuum_badevaerelse.state == 'on' }}
you're doing two different things and would use two different ways to do them
{{ is_state('input_boolean.chore_vacuum_badevaerelse','on') and states.input_boolean.chore_vacuum_badevaerelse.last_changed < now() - timedelta(seconds=2) }}
yes
Is there a way to hide modes with a climate entity?
{% if state.state == "on" %}
{{ state.entity_id }}
{% endif %}
{% endfor %}```
With this I was able to generate a list of entity_ids that the lights are on.
Is there anyway that I could automatically get it to update an entities card only with devices that are turned on?
use the auto-entities custom card
Wot a legend
There is also no need for a for loop here: {{ states.light | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
Yep, thomas has some really good custom cards, recommend most of them.
Ahaha I was trying to iterate for entity ids and put it into a list or something and then use a for loop to generate cards.
But no need, as recommended from petro, thomas cards are sick af
Yeah, no need for templates to show all lights which are on then
Quick question - Is one better than the other? I kinda got used to using templates...```
- condition: state
entity_id: input_boolean.helper
state: 'on'
vs - condition: template
value_template: "{{ is_state('input_boolean.helper', 'on') }}"
The non template ones are a lot more clear in the trace
It shows you what state was wanted, and in what state the entity was. With the template you will only know that it resulted in true or false
Hmmm... So no major impact to resources like CPU/RAM?
No, it basically does the same, check the current state and compare it to the wanted state
Cool! If the trace is the only major downside, I guess it cant hurt using them as they read easier to me
Does someone knows why this is not working ```
- conditions: "{{(states('sensor.lumi_lumi_weather_a372b807_temperature')|float) > (state_attr('weather.maison_accuweather', 'temperature')+5)}}"``` ?
maybe convert right part of conversion to float as well?
good evening guys, I want to compare two float values inside an automation f.e. valueNew=55.09 and valueOld=57
I get the valueNew from a device in my smarthome and at the last step of my automation the current valueNew will be set to valueOld
right now it is always telling me that the valueNew is bigger than valueOld (doesn't matter if it is the case or vise versa)
This is how my template looks like:
{{ ( states.sensor.valueNew ) < ( states.input_number.valueOld) }}
The input_number is a helper that I created and I can't find a solution to get an input helper that allows float from scratch? Can someone help me with this?
ha, I had to put automation: two times, ty
Can’t you just convert them both to float when doing the comparison, like this?
{{ ( states.sensor.valueNew ) | float < ( states.input_number.valueOld) | float }}
Hi all (I’m new here),
I’m trying to create a sensor using templates, whose value (state) increases if the value of another sensor is greater than the current value. To do this, I interpret the documentation that I can use the ’this’ variable to self reference the sensor state. However, I get an error in the log saying ’Template Loop detected, skipping template render’. Any idea what I’m doing wrong?
- name: "h60_aux_cons_hot_water" unique_id: h60_aux_cons_hot_water state_class: total_increasing device_class: energy unit_of_measurement: kWh state: > {% if states('sensor.aux_cons_hot_water') | float(0) > this.state | float(0) %} {{ states('sensor.aux_cons_hot_water') | float }} {%- endif %}
Quick question (hopefully):
are self-referential restful json payload templates a thing?
- name: "USNO Astronomical Moon Current Phase"
json_attributes_path: "$.properties.data"
json_attributes:
- "curphase"
value_template: "{{ state_attr('sensor.usno_astronomical_moon_current_phase', 'curphase') }}"
I'm not even sure I'm making sense. I'm trying to assign one of the JSON payload leafs to attributes, and then asign one of the attributes to the state of a sensor using a value_template that is self-referential.
I've verified that the JSON payload is being assigned to attributes.
okay. I just saw the sensors update... that was weird. Not sure why there is a lag. It DID work though. 🤷♂️
Your logic is a little confused. In this line in your template:
if states('sensor.aux_cons_hot_water') | float(0) > this.state | float(0)
this.state and states('sensor.aux_cons_hot_water') are exactly the same
the problem is that because you haven't specified a trigger, HA sees states('sensor.aux_cons_hot_water'), decides to listen for changes to that entity, and you're also defining the value for the entity
did you just change it?
did it always have the h60_ in the name?
yes it did.
My sensor I'm trying to create is the h60_ one, the other one is the one I'm listening to
ok, then nevermind
I suggest adding a trigger for the other sensor
- trigger:
platform: state
entity_id: sensor.aux_cons_hot_water
sensor:
- name: "h60_aux_cons_hot_water"
unique_id: h60_aux_cons_hot_water
state_class: total_increasing
device_class: energy
unit_of_measurement: kWh
state: >
{% if states('sensor.aux_cons_hot_water') | float(0) > this.state | float(0) %}
{{ states('sensor.aux_cons_hot_water') | float }}
{%- endif %}
The problem seems to be that HASS doesn’t recognize the input_number as a number 😦 I tryed setting it with the dev menu to 56 f.e. (That works) but after I try to send a notification message with this value it only shows me „unknown“ so an unknown value can’t be a float … how can I just store a float value with an input helper
{{ ( states.sensor.valueNew ) | float < ( states.input_number.valueOld) | float }} is just incorrect syntax
How would I setup a for loop to iterate through the list results checking that last updated is > 30 minutes?
https://dpaste.org/1GRAq
the input_booleans or the cameras?
The input booleans.
you don't need to loop for that
The list will list corresponding booleans. So there could be 2 booleans. 1 or 4. How would I do that without a loop?
change {{ input_boolean.items()|selectattr('0', 'in', select_camera)|map(attribute='1') | list }} to:
{% set boolean_list = input_boolean.items()|selectattr('0', 'in', select_camera)|map(attribute='1') | list %}
{{ expand(boolean_list) | selectattr('last_changed', '<', now() - timedelta(minutes=30)) | map(attribute='entity_id') | list }}
those will be the input_booleans which have changed longer than 30 minutes ago
I assume it should not have listed this?
https://dpaste.org/g0nWs
Worked thank you!
can someone help me out on chat with a noob template sensor?
Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
im not sure what im doing so hear goes... i got a template sensor for tracking multiple devices but im struggling with the syntax.
i think i need to have the sensor report home & away / not_home
but it keeps showing as on/off
-
platform: template
sensors:
people_home:value_template: >- {{ is_state('device_tracker.cph2127', 'home') or is_state('device_tracker.70dda8741b60', 'home') or is_state('device_tracker.sm_n9860', 'home') }}
im i misunderstanding something, i tried to use device_class: presence but it says binary sensor cant use that device class
oh sorry
and please format your code as code
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).
But anyway, easiest for this is to group the device trackers in a legacy group, that will do what you want, it will show home when one of the device trackers is home
https://www.home-assistant.io/integrations/group/#old-style-groups
there is an example for device trackers in the yaml there
thank you for your assistance!
GJ TheFes...
Howdy folks 🙂 I'm building a template sensor that's averaging all temperature sensors on a floor. Now this works as expected, but I'm actually using template sensors depending on template sensors, so when these things start up, they throw an exception in my logs saying that "None" can't be averaged (obvs).
The question I've got is how to get this sensor to show "Unavailable", in case items received for averaging not meeting the criteria required?
for example: https://dpaste.org/ma7No
the t != 'None' is... well, quite awful
This will not work:
twill never be the stringNone, sot != 'None'will always be true. It will also not benone, it will be[]if no sensors match the criteria. You should uset != []- You are better of with an availability template in your sensor which checks if any of the source sensors is providing a numeric value
yeah t='None': absolutely. On the availability template that would actually run a pretty similar set of filters (except for mapping/averaging)
- you should start your template with states.sensor instead of states to avoid it having to go through all state objects
3 - oh awe, thanks - there's a few of these and thought about running some tests to see how this impacts performance
I imagine that on many sensors will have an impact
well, states is throttled to update only once every 10 seconds if I'm correct, states[domain] every second
periods could be different
on availability_template: so this would essentially be looking if the result is a list with at least one item that's a float.
why are you leaving out state 0 btw?
without that, your template could be this:
{% set t=states.sensor |selectattr('entity_id', 'search', 'sensor.area_fsz_.*_temperature')
|selectattr('state', 'is_number')
|map(attribute='state')|map('float')|list %}
hmmm ohhh 🙂
and your availability template this:
{% set t=states.sensor |selectattr('entity_id', 'search', 'sensor.area_fsz_.*_temperature')
|selectattr('state', 'is_number')
|list |count > 0 %}
and with that availability template in place, you can put the average filter in your state filter
so the availability template would be something like {{ states.sensor |selectattr('entity_id', 'search', 'sensor.area_fsz_.*_temperature') |selectattr('state', 'is_number')|list|count>0 }}
yes, that is what I just placed above your post
oh lol - I actually went through the thought process before reading the end of your recommendation
that's awesome, thanks a lot for your help!
the other thing I was wondering about if there's an easy way to get |median out of these values
state: >
{{ states.sensor |selectattr('entity_id', 'search', 'sensor.area_fsz_.*_temperature')
|selectattr('state', 'is_number')
|map(attribute='state')|map('float')|avarage }}
availability: >
{{ states.sensor |selectattr('entity_id', 'search', 'sensor.area_fsz_.*_temperature')
|selectattr('state', 'is_number')
|list |count > 0 }}
is there a |median alternative, or do I just build a min_max out of that?
I have an example of that from the past - but should the list be of even floats, I'll need to avg the middle two
thanks, will keep running with that
{% set values = states.sensor |selectattr('entity_id', 'search', 'sensor.area_fsz_.*_temperature')
|selectattr('state', 'is_number')
|map(attribute='state')|map('float')|sort %}
{{ values[((values | count) / 2) | round(0,'floor')] }}
But you could also just use statistics sensors for these kind of calculations
https://www.home-assistant.io/integrations/statistics/
Is there a way to set entity_id for template / sensor? Previously I used something like:
sensor:
- platform: template
sensors:
my_entity_id: ...
Now this one has the option to set "state" and "availability" properly:
template:
- sensor:
- name: ...
My ignorance: both look like template sensors to me
I see something like unique_id - but that's stg different
they are both template sensor formats, the first one is the legacy template, the 2nd one is the current (new) format
in the new format, the entity_id will be based on the name provided
Why is that?
So name: This is a template Sensor will result in sensor.this_is_a_template_sensor
If you provide a unique_id, you can change both name and entity_id in the GUI
and no way to set the entity_id from yaml?
if you don't add a name, and it will be based on the unique_id
so ideally I set both from Yaml. The entity_id allows me to create a pattern that's easy to find in code, the second one helps avoiding setting that individually on each card I create on the UI.
oh I see - so name is not required - will be uniqueID when that's not set
name is not required, basically only state
so am I clear on these?:
- The legacy way has the option to set both name and entity_id in Yaml, but relies value_template instead of state - and lacking the option to add "availability" for that sensor.
- The new way has the option to add name, which will automatically create an entity_id that cannot be changed from YAML. Relies on state, and has availability option for that sensor
the legacy template also has an option to provide availability using availability_template:
the new format supports state_class which the old one doesn't support
for long term statistics
and self referencing using this
ewww 🙂 those are neat things
i am trying to make a template with states.sun.sun.attributes.next_setting but i dont really know how to make an offset after the next_setting. the moment the timestamp of the nextsetting runs to 0 it is replaced with the next next_setting in which an offset of 30 minutes passed the next setting seems to be impossible. does anyone have any ideas
and other types, like select, number, button
oic, thanks!
put the next setting in an trigger based template sensor which updates just after midnight, and use that one
didnt know i could do this with a sensor. thanks
How could I make sure this checks all booleans in the list. To ensure all are true. I changed this to | list | count > 0 but that would only be true if one of them is true. It's possible 1 is true and 1 is false if there's 2. Or 2 are true and 1 is false for example.
no that would be true if the list contains 2 input_booleans which match the filter criteria, as 2 > 0 is true
I really don't understand what you are trying to say
If the select_camera has more than 1 value. Does the boolean_condition check to ensure all corresponding booleans were updated greater than 30 minutess ago? Vs checking any 1 is true and not checking all to ensure all are true.
https://dpaste.org/agJ8b
Can you help me with the right one?
the boolean_condition checks for all entities out of boolean_list, which are all input_booleans for which the corresponding binary_sensor is on
Yes I get that part. What I am trying to achieve is the boolean_condition variable. I want to know if all of the values it is given were updated greater than 30 minutes ago. Currently it will become true if even just 1 boolean was updated more than 30 minutes ago. However if there's more than 1 value. It is possible not all were updated more than 30 minutes ago.
@desert plover use states('sensor.cucumber')
{% set boolean_condition = expand(boolean_list) | selectattr('last_changed', '<', now() - timedelta(minutes=30)) | list | count == boolean_list | count %}
Perfect that is what I was looking for. Sorry for the confusion.
fixed it.... I was too much fixed on the calculation in the template instead on the condition with the template, ty again 🙂
don't know if that is correct channel now, but it seems there is no service available where I can set an input_number the the value of a sensor's value, is that correct?
How about input_number.set_value?
You can use a template to get the state of the sensor
And use that for value:
yeah that is what I'm looking for but the field for the value is not fillable with an other variable, so only in yaml mode
created this one but as always I think there is a mistake in my syntax
service: input_number.set_value
data:
value: {{ states('sensor.valueNew') }}
target:
entity_id: input_number.test
you need to surround your template in quotes
yeeeeaah tyyyyyyyyyyyyy
hah I think I ran onto a breaking change 😄
I'm getting this: "UndefinedError: 'jinja2.utils.Namespace object' has no attribute 'mapped'" for running through results of a namespace var called 'mapped'
this seems to be responsible:
{% for l in ns.mapped|selectattr('e', 'lt', states('input_number.expiring_certificates_warning_treshold')|int)|sort(attribute='exp') -%}
{%- set ns.list=ns.list+'• {}: {}\n'.format(l.n, l.e) -%}
{%- endfor %}
is there a change in syntax that results in this error?
how did you define the namespace?
Hey RobC! 🙂
{%- set ns = namespace(mapped=[], num=0) %}
dpaste: https://dpaste.org/DcH9N#L1,8,10
before this for l in ns.mapped line, I can see there there's data in ns.mapped
[{'n': 'boot.mb', 'e': 2401},...]
this works fine:
{% set ns = namespace(foo=[]) %}
{% set ns.foo = ['foo', 'bar'] %}
{% for item in ns.foo %}
{{ item }}
{% endfor %}
yeah
I'm trying to understand how the "-" in templates changes them, e.g. '{% ... %}' vs '{%- ... -%}'. Any help on this will be appreciated
RobC: can you selectattr in that?
but the error calls out ns.mapped, not ns.list
Add list="" to the first time you define ns
yeah it works like that
Or just use a different name for your namespace
was it always like this?
You don't have to use ns
yes, otherwise it would be magic
interesing - I thought this thing worked last week 😄
It's always been like this, if you overwrite a variable, the previous value will be gone
I mean: this template actually ended up sending me notifications without erroring out
namespaces are no different from any data structure
It differs in how whitespaces are handled
yeah, makes sense - better look for some other items like this in my code
thanks guys, this enlightenment is much appreciated
I'm trying to wrap my head around how it handles the whitespace - I have a block consisting of a bunch of nested if statements, and would like the result to render on one line, but struggling to find the right places to put the "-". Any documentation where I can read up on this?
I usually just keep adding them until I get what I want in the dev tool
it's easier than trying to understand what logic creates newlines and what doesn't
from old forum posts, it appears that it used to be standard practice to use "-" everywhere. Now it's the opposite
most of the time it doesn't matter at all
Been busy at the dev tool for over an hour - almost to the point where I'm going to put the whole thing in one line... hehe
The biggest stumbling block currently is, I have some options in the if statement, which starts with a " ", and the "-" seems to clear those too.
Correct
I'm going to be mocked for this block of code, but that is how I learn, tinker with it till it works... 🙂 https://pastebin.com/FCqRMZtx
The end result I am aiming for should be a single line sentence which will be sent via telegram. That block will go into the message: >
The reason for all the line breaks is to read easier in the dev tool
that's a lot of repetition 🙂
Why don't you use an input datetime for your snooze time input?
Instead of a separate one for hours and minutes
the input_datetime is a pain to use in the UI - So for simple inputs like these delays, input numbers work easy on the UI and equally easy to implement on the automation.
I'm sure there must be an simpler way of expressing it, but I started at a point and tried to express each "if" with is results. e.g minute vs minutes etc
The input_datetime which I do use I also manage with input_numbers from the UI, and automations to updtae the datetime entity for use. Al lot of extra work, but makes the experience in the UI much less frustrating.
{%- set h = states('input_number.all_notifications_snooze_timer_hours') |int(0) %}
{%- set m = states('input_number.all_notifications_snooze_timer_hours') |int(0) %}
{%- if h + m == 0 %}
Please set snooze time in configuration!
{%- else %}
Notifications Disabled for {{ h }} hour{{ 's' if h != 1 }} and {{ m }} minute{{ 's' if m != 1 }}.
{%- endif %}
you gotta be kidding...
This just makes me realise once again I got a long road ahead of learning... Appreciate the help and insight 🙏
the first 2 lines would have been a big improvement for your template, so you don't have to repeat the entire states template every time
I tried it, but I failed to get the variables set, so I went for the crude method 🙂 At least now I have a working example to learn from. I spotted *_hours is repeated in the variables the m= should be _minutes.
{%- set h = states('input_number.all_notifications_snooze_timer_hours') |int(0) %}
{%- set m = states('input_number.all_notifications_snooze_timer_hours') |int(0) %}
should be
{%- set h = states('input_number.all_notifications_snooze_timer_hours') |int(0) %}
{%- set m = states('input_number.all_notifications_snooze_timer_minutes') |int(0) %}
Thank you once again! much appreciated...
ah, yeah, I replaced them with something like {% set h = 5 %} after that, as I don't have these input_numbers anyway
it's always 5 o'clock somewhere
This was an eye opener to me```
hour{{ 's' if h != 1 }}
Is it possible to get the result, if the hours are set to 0, to get this result: Notifications Disabled for 11 minutes. instead of Notifications Disabled for 0 hours and 11 minutes.
@civic hedge posted a code wall, it is moved here --> https://hastebin.com/ecitokekif
I changed it to this and seems to function as expected```
{%- set h = states('input_number.all_notifications_snooze_timer_hours') |int(0) %}
{%- set m = states('input_number.all_notifications_snooze_timer_minutes') |int(0) %}
{%- if h + m == 0 %}
Please set snooze time in configuration!
{%- elif h == 0 %}
Notifications Disabled for {{ m }} minute{{ 's' if m != 1 }}.
{%- else %}
Notifications Disabled for {{ h }} hour{{ 's' if h != 1 }} and {{ m }} minute{{ 's' if m != 1 }}.
{%- endif %}
@civic hedge you can't template in the frontend. You'd have to make a script and call the script instead.
Thank you, Petro. I'll have a look at putting it in a script.
Thanks again, worked great!
alias: Alarm - Call relevant service based on armed status - Perimiter
sequence:
- service: |
{% if is_state('alarm_control_panel.partition_perimeter','disarmed') %}
alarm_control_panel.alarm_arm_away
{% else %}
alarm_control_panel.alarm_disarm
{% endif %}
data: {}
target:
entity_id: alarm_control_panel.partition_perimeter```
guys, please help: I have a board with 12 relays and 12 inputs, HA is talking ModBUS with this board. I can toggle the relays - I have switch.<RelayID> for each relay and also read their status - binary_sensor.<RelayID>. How can I have in HA a button for each relay so I can toggle them but also the state based on binary_sensor.<RelayID>?
Is that related to templates in some way? Seems like it's just this https://www.home-assistant.io/integrations/modbus/
the Modbus part works fine, I need to use the template part so the relays state is based on binary_sensor state
by "button", do you mean in the frontend?
nope, i'm thinking on creating a template switch which when toggled toggles the relay and its state is based on binary_sensor
I think I've found an example on my config, I'll give it a shot
nope, it doesn't look to work
Ok
any clue what's wrong?
You provided no details
please see the pastebin URL above
when checking config I get an error
Invalid config for [switch.template]: invalid slug switch.etd8a12_1_output1_template (try switch_etd8a12_1_output1_template) for dictionary value @ data['switches']. Got OrderedDict([('switch.etd8a12_1_output1_template', OrderedDict([('value_template', "{{ is_state('binary_sensor.etd8a12_1_status_output1', 'on') }}"), ('turn_on', OrderedDict([('service', 'switch.turn_on'), ('data', OrderedDict([('entity_id', 'switch.etd8a12_1_output1')]))])), ('turn_off', OrderedDict([('service', 'switch.turn_off'), ('data', OrderedDict([('entity_id', 'switch.etd8a12_1_output1')]))]))]))]). (See ?, line ?).
It told you what's wrong and even how to fix it
if I had understood the error code, I certainly would not have asked for help
yep, i'm a bit blind this evening, thanks and sorry for bothering you
Can anyone see an issue with this? https://pastebin.com/T25b3JrQ the specific erro ri'm getting is with the brightness field claiming it expects an int, i've tried the |int filter to no effect
I suspect the if around the color_temp: is probably also erroneous but not 100% sure
You can't template keys like that
The easiest solution is to use a choose: to decide between two service calls
was hoping to avoid that, i do that in the automation i'm basing the script on but was hoping to simplify, ive removed the key if statement
any idea about the brightness?
Failed to call service script/smart_light_control. expected int for dictionary value @ data['brightness']
Yes, you need to surround the template in quotes
now it complains brightness is undefined, i originally had the value with a different name that doesnt work, i removed the quotes due to that error originally
i'm trying to run the script from the script editior, had thought that the default value would take effect, is there anyway to pass it in from the script editor to test it? or do i have to specify a variable with the same name? and if i do will that cause a conflict? or will the field overwrite it
Those fields do nothing
You have to call it with the parameters
They're just to guide humans
i've just added them in as variables to test for the moment, thanks
sensors:
verbrauch_schultz_w:
friendly_name: "Current Power Usage"
unit_of_measurement: "W"
value_template: "{{ states('sensor.verbrauch_schultz_KW')|float * 1000 }}"```
how can i remove the comma , from my wattage meter?
try (states('sensor.verbrauch_schultz_KW')|float * 1000)|int
awesome. thank you
No problem
Is there a way to say wait for trigger. if the trigger happens stop the Automation rather than the default of continuing.
if the trigger does not happen continue after 3 seconds.
I beleive there is a wait action that also has a timeout but not sure if the one that waits on state includes a timeout as i've wanted to do this myself but had issues if i recall, then after the wait just do an if or choose based on the state condition
Wait for trigger has a timeout but it is intended to continue after the trigger. Im looking to actually stop if the trigger happens and only continue on timeout.
you can do a wait for trigger, and then have a condition directly after that checks if the condition the trigger is what you want if not the condition will cancel any further actions
Yes except my trigger is an event trigger that will be variablized. I think I found a way. I am trying to wait for trigger on an automation trigger. I can potentially use the event trigger then a condition with a template for last triggered.
I see this may be helpful "{{ not wait.completed }}"
That will not work for wait_for_trigger
You'll need to check for a trigger.id
In case it timed out wait.trigger is none will be true (corrected)
Confused why it wouldn't work? I see it works for wait_template does that mean it doesn't work for wait_for_trigger? I'm not using trigger.ids where is trigger.id is none coming into play?
read carefully
wait.completed exists only after wait_template
So not after wait_for_trigger
And your triggers will have a trigger id by default
If you leave it blank, the trigger index will be used
Even when the trigger is in a wait for trigger and not the trigger section?
It has an id?
Yes
Sorry, my bad
You need to use wait.trigger
Which will be contain the trigger id (or trigger index) of the trigger in the wait
I see and be none if no trigger happened before timeout expired which I'm looking to stop the automation if the trigger happened. So I could put in a condition after the wait for trigger. wait.trigger != 'none'
It's just null?
wait.trigger is not none
Hi im trying to combine 2 power sensors and added the following code to my config.yaml file but it does not show up as an entity. What i'm I doing wrong
template:
- sensor:
- name: "PVH"
unit_of_measurement: "watts"
state: "{{ (states(sensor.shelly_shem_485519c99f26_1_current_consumption')|float + states('ssensor.shelly_shem_485519c99f26_2_current_consumption')|float) }}"
- name: "PVH"
I have a template like this in the dev tools
{{ states.sensor.sm_n975f_next_alarm.attributes }}```
I get these attributes:
```js
{
"Local Time": "Thu Aug 18 06:50:00 GMT+02:00 2022",
"Package": "com.google.android.deskclock",
"Time in Milliseconds": 1660798200000,
"device_class": "timestamp",
"icon": "mdi:alarm",
"friendly_name": "Pixel 6 pro Next Alarm"
}
when typing states.sensor.sm_n975f_next_alarm.attributes.Local Time this obviously doesnt work. states.sensor.sm_n975f_next_alarm.attributes.Local_Time also doesnt work how do i get this attribute in the template
never mind this is the answer for people that want to know...
{{ states.sensor.sm_n975f_next_alarm.attributes['Local Time'] }}
There's a typo in the second sensor which will make the float filter error because you did not provide a default
Doesn't seem to be working.
https://dpaste.org/EKTxq
The goal here is sometimes zha groups have an issue if a device in the group updated state is lost after it receives a command so this just checks and "turns off" an already off light so ha can see the group as off. However stop the process if the corresponding automation triggered. Which would mean the lights are going to be turned back on. If no trigger then proceed to turn any lights that are "on" off
ah yeah I see double s at sensor 🙃 although that still does not make it visible
If no trigger then proceed indicates you actually want to check on wait.trigger is none
Oops that was easy. Sorry.
What happens when you put your template in
> templates
{{ state_attr('sensor.sm_n975f_next_alarm', 'Local Time') }} is better and safer.
That's indeed what I also should have said 😅
Oh wait, there is a quote missing before the first sensor
This is what I get in the template editor
template:
- sensor:
- name: "PVH1"
unit_of_measurement: "watts"
state: "-373.0"
- name: "PVH1"
as a result
I assume after correcting that missing quote
yes, although the sensor is still not visible as an entitiy
Ah a needed to reload entities
How do I take the absolute value of of a custom sensor
Need the help of a jinja master. I have this template that does not seem to be updating as I would expect when render_template is used to update specific entities so I imagine my template needs help to update with this API. This is my current template that updates fine if its constantly re-evaluated https://pastebin.com/HFANybFR the goal is to just print a list of open contacts in a group or say nothing is open when nothing is open 🙂 the template is pretty old lol
That'll be throttled down to 1 update per minute, max
ah ok, do those update send once per minute or do i need to add some logic lol
well
do you need to add a trigger for that entity?
I didn't realize that entity updates would also be throttled like that
just now() and such
Template entities will by default update as soon as any of the referenced data in the template updates.
so just when you're referencing all states in the system
{{ dict(expand('group.inside_area') | groupby('state') | list).get('on', []) | map(attribute='name') | list | join(', ') or "No open windows/doors" }}
there's other ways to do this too
like
{{ expand('group.inside_area') | selectattr('state', 'eq', 'on') | map(attribute='name') | list | join(', ') or "No open windows/doors" }}
both of those will update immediately
and will not be throttled
So...
states | will be throttled to at most 1 update per minute
yes, as in the link above 🙂
states.<domain> | will be throttled to at most 1 update per second
states.sensor | will be throttled to at most 1 update per minute
it's the exception
everything else is live
aka, avoid states if you can
I practically killed somebody's Pi instance with states| once
if you want dynamic entity sets based on wildcards using states, make an automation that sets a group
I was like: works great on my i5!
was taking like 30-45s or something like that
He was the chief tester for the rate limiting IIRC
because all his systems have crazy templates
Yeah, that was before the rate limiting was probably introduced
bdraco made those changes specifically to counter act poorly optimized templates on slow machines
90's NBC FTW
This exception is not mentioned in the link, they even use sensor as an example for the 1 second limit
he (bdraco) might have changed it, I vaguely remember having a conversation with him where he (or I) didn't want to single out the sensor category
It's somewhere on the forums, but I'm avoiding that place for a while.
thank you @mighty ledge 🙏
np
Hehe. I have since cut down on templates 😉
I really do not like datetime.
This works and gives me something like 3 days, 3:29:14.948179 ... BUT how do i format that to "3 days"? or "3days, 3 hours" ... I just can't figure out the magic bullet...
{{ (now() - (as_datetime(states('input_datetime.some_helper')).astimezone()))}}
in the configuration.yaml i have 3 input selects is it possible to create all 3 with a loop so the code isn't duplicated and if I want to change one it changes them all, also is it possible for me to point the options to a script field with the same options so they dynamically match?
I know you cant use jinja for constructs in automations and scripts to generate keys but not sure if it's valid in the config
if not is it possible i create a template "input_select" that i can reuse in all 3 to minimise duplication?
you can technically generate key/value pairs, but you have to template the whole data section and generate a dict
That's not a datetime, that's a timedelta. If you want hours/minutes/seconds, you have to calculate them yourself
or you could use the relative time, which will output the most relevant sig fig, in that case it would just read '3 days ago'.
THank you.. Of course it is a timedelta now.. Doh.. Sooo, whats the shortcut to get relative time out of that mess then?
doing the calculation by hand. I.e. dividing the seconds by 60 to get minutes, and by another 60 to get hours.
Or use timestamps instead of datetimes and use timestamp_custom
that won't necessarily work if the number of days is greater than 31
Yeah, I started entagnling myself when i ran into that input_datetime was timezone naive, which complicated things for me, as my other states are not...
This will work untill you reach a year difference
{% set test = now() - timedelta(days=3, hours=3, minutes=29, seconds=24) %}
{% set diff = as_timestamp(now()) - as_timestamp(test) %}
{% set d = diff | timestamp_custom('%j', false) | int - 1 %}
{% set h = diff | timestamp_custom('%-H', false) | int %}
{% set m = diff | timestamp_custom('%-M', false) | int %}
{{ d }} days {{ h }} hours and {{ m }} minutes
Oh, thanks!
Add as_local
still seems easier to do the calc yourself
{% set td = now() - states('input_datetime.some_helper') | as_datetime | as_local %}
{{ td.days }} days {{ td.seconds // 3600 }} hours {{ td.seconds // 60 }} minutes {{ td.seconds % 60 }} seconds
maybe i'll add a strfdelta filter & func
Consused... Let's say I have
{{ (relative_time(states.input_datetime.andrades.state | as_datetime)) }}
Nowhere seem suitable to add as_local. i just get complaints of not having tzinfo
{{ (relative_time(states.input_datetime.andrades.state | as_datetime | as_local)) }}
Of course.. it isnt a method....
{{ relative_time(as_local(states.input_datetime.andrades.state | as_datetime )) }}
Btw you should use states('input_datetime.andrades')
probably the cleanest IMO:
{{ states('input_datetime.andrades') | as_datetime | as_local | relative_time }}
So many options 😅
the least amoutn of () is always the best option when you can't use multiple lines IMO
I'll steal that 🙂
Yeah.. Hah.. I am most thankful.
I was close to just firing up a new app in appdaemon.... 😛
is there a way to reference script fields?
i mean outside of the script though
because i want to create a set of input_selects that have the same options as one of the fields from a script input_select for example
but it's looking like the best thing will be to create a sensor with all the items then reference that for the options of both the field and the input_select helpers
that's the first i've heard of anchors
yaml -> anchors
input_select:
who_cooks:
name: Who cooks today
options: &options
- Paulus
- Anne Therese
living_room_preset:
options: *options
ok, thanks
Hi, Is it possible to add brightness control for modbus lights without using a template?
Dare I ask another date-related question.... If "as_local" returns english "3 days" and not the actual local "3 dagar".. despite the user having "Swedish" selection in their profiles, AND from what I can see, using the proper settings on their browser and on their phone / companion app.. What if anything have I overlooked then?
Again, using the {{ states('input_datetime.andrades') | as_datetime | as_local | relative_time }} that was so gracefully shared previously.
as_local just adds your local timezone, it doesn't do translations
aaaaah... the doh's just keep doh'ing.
I suppose i could wrangle regexp_replace then... Thanks
The bot has been taken out by a fibre seeking backhoe...
I want to pass an entity_id to a script. That script will wait until the state of the entity is, for this example, "off" Here is the link to my snippet code https://dpaste.org/ZWqD0
The problem is that the variable isn't evaluated. I how do I force the evaluation of the variable so that it becomes an entity_id?
you surrounded the variable in quotes
it's also way overcomplicated
but this is the problem:
value_template: '{{ ( is_state(''sensor_for_which_to_wait'',"off") ) }}' ->
value_template: '{{ is_state(sensor_for_which_to_wait,"off") }}'
a wait_template or wait_for_trigger would be enough. Instead, you've created a tight loop that will kill your device
OK, so when the entity_id is not a variable, it is surrounded in quotes.
if you want a string, you put it in quotes. If you want a variable, you don't
What do you mean by, "...kill your device"?
it's going to sit there and spin in the loop as fast as possible
I could put a delay in my sequence, right?
That's called Busy waiting. It'll keep checking if the condition is true over and over and over again. Instead you can ask Home Assistant to just tell you when it's true and go to sleep in the mean time.
I my actual code, I have four conditions, any one of which should trigger the exit of the tight loop
you could add them all in a wait_for_trigger and it would be much better for HA
or a wait_template, if it's possible that it's already changed state and you just want to know that right away
OK, a wait_template with four "is_state" eg. - wait_template "{{ is_state( 'b1','on') or is_state( 'b2','on') or is_state( 'b3','on') or is_state( 'b4','on') }}"
Is timeout: nn required?
that can't be right
what is "b1"?
unless you just mean a placeholder for somethign else
a timeout is only needed if you want it
right, If I had varibles, there wouldn't be quotes around the b1
ok
but if I had actual entities it would be something like 'switch.b1'
yes
OK, thanks, that should keep me busy until dinner (and not longer, I hope 😉
you could further simplify that, but that's just an optimization
Can a template be on multiple lines?
- wait_template: "{{
not is_state(var1, "0.0")
or not is_state(var2, "0.0")
or is_state(''binary_sensor.esp3"", "on")
}}"
- wait_template: ->
"{{
not is_state(var1, "0.0")
or not is_state(var2, "0.0")
or is_state(''binary_sensor.esp3"", "on")
}}"
It can, but neither of those will do it
- wait_template: >-
{{ not is_state(var1, "0.0")
or not is_state(var2, "0.0")
or is_state("binary_sensor.esp3", "on")
}}
I want to track the event trigger for script_started and use a condition that the script entity_id contains lights I assume I need a wildcard. How would I do that?
Not sure if the match part is useful for what I'm trying to do?
{{ states.light | selectattr('entity_id', 'match', '.+_lights$') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
hey, dont suppose its possible in a template to check a condition of a state_attr?
looking to check if a stat_attr is greater than X
state_attr('sensor.foo', 'bar') > X
Driving
{% else %}
{{states("device_tracker.XXX")}}
{% endif %}```
this is what ive got so far
but it doesnt seem to work?
You have {{% and %}}, there should be one curly bracket there
ok - i did that as well with the same output
{% if is_state_attr("device_tracker.XXX", "speed")| float > 10 %}
Driving
{% else %}
{{states("device_tracker.XXX")}}
{% endif %}
or do i need to drop the is_state_attr to just state_attr?
And you should replace is_state_attr with state_attr
is_state_attr expects a third argument, the state you are comparing it with
But can only be used for equal to
right ok
Probably something like 'light' in trigger.event.data.entity_id
But I'm not sure how the event data structure looks like. You can check that in the trace
Trace https://dpaste.org/LTEsx
Can I also reject 'off' with a wildcard in the entity_id by saying 'off' not in trigger.event.data.entity_id
okay, that's matching what I suggested
ah, was just going to mention the quotes, but yes, that would work
Perfect. Sometimes the solution is significantly easier than I thought.
BTW, in this trace you can also see that the trigger has a trigger.id 🙂
Yes it does from our conversation yesterday lol.
@marble jackal - quick question if i may, is there a way in what ive done to swap the "Driving" text to an MDI?
Just tested it and it worked.
nonot easy, but you can use emoji
{% if atate_attr("device_tracker.XXX", "speed")| float > 10 %}
🚗
{% else %}
{{states("device_tracker.XXX")}}
{% endif %}
he can with the custom button card, but it would take alot of effort.
I did it for a few things, wasn't worth the effort in the end
basically need to add the html svg into a custom field and select the correct html based on the state
I ended up just switching to the custom icon offering through the favicon custom integration
then you don't need the SVG, you can just output the html pointing to the mdi/fav/favpro(custom) icon name and it will show it
Well, emoji is easy, just press windows key + . (on windows of course) and select one you like
yea emoji is a way to go haha
thanks
im using a template card
This is the function I use
function getEntityIcon(state, units, icon, color){
units = (units !== null) ? `<span style="font-size: 75%;">${units}</span>` : '';
icon = (icon) ? icon : 'mdi:eye';
return `<ha-icon
icon="${icon}"
style="width: 1.4em; height: 1.4em; color: var(--paper-item-icon-active-color);">
</ha-icon><span style="font-weight: bold;"> ${state}</span>${units}`;
};
you can strip that down just to be an icon if you want
which would be...
function getEntityIcon(icon){
icon = (icon) ? icon : 'mdi:eye';
return `<ha-icon
icon="${icon}"
style="width: 1.4em; height: 1.4em; color: var(--paper-item-icon-active-color);">
</ha-icon>`;
};
then just call return getEntityIcon("mdi:anything"); and it will return the icon in whatever spot you're putting it.
ill have a play 🙂
so if the state of your entity is driving.... the field would look like this:
[[[
function getEntityIcon(icon){
icon = (icon) ? icon : 'mdi:eye';
return `<ha-icon
icon="${icon}"
style="width: 1.4em; height: 1.4em; color: var(--paper-item-icon-active-color);">
</ha-icon>`;
};
return getEntityIcon(`mdi:${entity.state}`);
]]]
Howdy folks 🙂
Is there a way to profile templates to spot performance issues?
There's few switches I'm using that require short impulses, e.g. 250ms on/off to just kick a shutter switch, and it looks like that out of 5/10 times that is not achievable. When I remove all the "heavier looking" template sensors, that problem goes away.
I can go through them one-by-one, but if there's a better alternative, that'd be awesome 🙂
not really.
I can guarentee you can simplify your 'heavier looking' templates
post them and me or @marble jackal can help you optimize them
Hey, I want create counter to count all the lights which are on, it works otherwise but it also counts itself. So there is always +1 to the amount of lights are on. How can I fix it?
sensor:
- platform: template
sensors:
count_lights_on:
friendly_name: "# Lights on"
unit_of_measurement: "on"
value_template: >
{{ states.light | rejectattr('entity_id', 'eq', 'sensor.count_lights_on') | selectattr('state', 'eq', 'on') | list | count }}
that's impossible for it to count itself. Your +1 is coming from something else
most likely a light group
when you use states.light you filter your selections down to things only in the light domain
oh yeah, i have "all lights" group
i.e. sensor.count_lights_on is not included in the template
can I reject light group based on it's identity?
so filter out the all lights light instead of sensor.count_lights_on
Yeah, got it working
Petro, TheFes, the heavier looking templates are... heavy 🙂 Let me collect them up.
The other thing is that relatively lightweight template repeats are also adding to the mix. For example: I've got a filter TheFes helped me optimising the other day. The idea is: get all temperature sensors from an area, and average & median their values. This runs per room, and depending template sensors averaging the rooms by floor. So this is actually x10 times the weight of the lightweight.
The benefit I gain with this is that I can swap my sensors all around back & forth, for as long are they're a "temperature" class and in the "room" room, they're going to be picked up, regardless if that's a motion device's temperature sensors or not.
I'm thinking however that for performance reasons, I may need to go back to min_max to average predefined entity_ids, instead of dynamically grabbing them (or severely limit where I do this)
This one looks like the heaviest: https://dpaste.org/x010Y#L5
I've been looking at optimizing this for starters. Things I've spotted right away based on my recent learnings:
- With stricter naming conventions I can easily get rid of some of the regexps there
- Getting those regexp filters out of the for loop is probably not a bat idea
- I haven't made much progress on fine tuning that sensor, light, switch etc query list as lights doesn't seem to have any device_class or state_class, or anything else that'd allow me to grab them specifically (while other sensors do); but running 2 queries can be slower than running one with both (profiling would help haha)
right now, those will update at most once per minute
So even though it's heavy, it's only executing once per minute
Yeap, which is fine for this purpose
Draining sensors: https://dpaste.org/hsG0N - same with these
Expiring certs: https://dpaste.org/QmC7e - also 1/min
why is that first template doing anything after you generate the list?
it's updating names and doing other crap that it doesn't need to do when you're just getting a count
filters needed, otherwise |list|count would be enough there, yes
what happens when I timestamp now() before and after in the template editor and see the perf difference?
you are only counting stuff there, you don't need a for loop and map stuff and sort it, when you only need a count
(making notes :))
that seems to work:
Poormans profiler 😄
{% set s=as_timestamp(now())%}
{{ states|selectattr('domain','in',['device'])|map(attribute='entity_id')|list}}
{% set f=as_timestamp(now())%}
Takes = {{ f-s }}
I used it on my own config, and because he removes parts of the name, and then uses unique at the end, some entities are combined and then removed in the count
yeah I get it, but he's just looking for missing sensors. You could just map the entity_id, map it to a device_id and get the count that way
well, ideally I'm looking for the device itself (I wouldn't need all the sensors)
but I haven't found an option for that 😕
what are those filters doing? Are they trying to filter out entities that are duplicates? Or do you just want devices themselves?
When I have a device called "Living Room Sensor" that has entities for "Living Room Sensor Temperature", "Living Room Sensor Humidity", etc. It aims to get rid of many of those and count as 1 device missing.
weak attempt, but there was a day in time when that looked logical 🙂
do you have any entities that come from yaml that do not have a device?
like a template sensor?
well, that would go unavailable
I write all my templates to have 100% uptime or purposeful unavailablity because they are based on a sensor. I.e. I don't care about the template, only the device
what i'm getting at: Do you only want to find devices that are unavailable that come from the UI
if yes, then you can greatly reduce this template
the purpose of this is to find all zigbee sensors throwing themselves off network
they are all real devices
oh really?
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
do me a solid, post the entity of a zigbee device in here, i'm going to give you a template to run
and you're going to give me the result
sure, one sec
not sure what petro is going to post, but if it concerns one integration only, integration_entities() would be the first filter to get only the Zigbee ones
oh hmmm would that be stg like integration_entities(zha)?
integration_entities('zha')
yeah but htere's like 10 ways to integrate zha
petro:
RH3052 device (Friendly: Garázs Páramérő) entities:
sensor.garazs_paramero_humidity (Friendly: Garázs Páramérő Páratartalom)
sensor.garazs_paramero_temperature (Friendly: Garázs Páramérő Hőmérséklet)
post the results of this
{{ device_attr('sensor.garazs_paramero_humidity', 'identifiers') }}
use the template tester
{('zha', '14:b4:57:ff:fe:3c:68:0d')}
😄
ok, so it's zha
integration_entities('zha') seems to work
that helps massively reducing the filters used
interesting results from the side:
{{ states.device|map(attribute='entity_id')|list}} is 0.4ms faster than {{ states|selectattr('domain','in',['device'])|map(attribute='entity_id')|list}}
sorry, got sidetracked
{{ integration_entities('zha') | expand | selectattr('state','in', ['unknown', 'unavailable']) | map(attribute='entity_id') | map('device_id') | unique | list | count }}
and for the names...
map(device_id)|selectattr('name'...?
guess you meant zha instad of zwave_js
yeah no worries there
{% set devices = integration_entities('zha') | expand | selectattr('state','in', ['unknown', 'unavailable']) | map(attribute='entity_id') | map('device_id') | unique | list %}
{% set ns = namespace(names=[]) %}
{% for device in devices %}
{% set ns.names = ns.names + [ device_attr(device, 'name') ] %}
{% endfor %}
{{ ns.names }}
oh interesting
any reason for not expand(integration_entities('zha')) but integration_entities('zha')|expand?
it's the same
this one looks better tho (follows pattern)
there are issues with it as afilter, but i believe those issues were fixed
isn't there a bug with the filter making it only work in the template editor, but not in sensor entities?
flip it then
could be it's fixed 🙂
awesome, thank you!
fez, do you have access to your device_registry?
I do not
'name' is not necessarily what we want in the second template
but I don't have the means to find the correct device_attr
uhm, you mean in .storage?
yes
yeah, I can access it
can you tell me the field that contains the user set name
of the device
the key itself
oh ffs, i tried everything
that in core.device_registry?
yes
anywayys... this would be the template then
{% set devices = integration_entities('zha') | expand | selectattr('state','in', ['unknown', 'unavailable']) | map(attribute='entity_id') | map('device_id') | unique | list %}
{% set ns = namespace(names=[]) %}
{% for device in devices %}
{% set ns.names = ns.names + [ device_attr(device, 'name_by_user') or device_attr(device, 'name') ] %}
{% endfor %}
{{ ns.names }}
so device_attr(device, 'name_by_user') is available then awesome
would that apply to all other attributes in device registry?
device_attr(device, 'connections') for example
device_attr gets any attribute that's in the device registry for that devicde
yep
try it
oh ffs if I had known that a week ago 😄
several new worlds opened up just now
need a drink
I just about pooped myself with this and zwave
then I realized that button entities have a default state of 'unknown'
so... you might want to reject them
{% set devices = integration_entities('zha') | expand | rejectattr('domain', 'in', ['button']) | selectattr('state','in', ['unknown', 'unavailable']) | map(attribute='entity_id') | map('device_id') | unique | list %}
{% set ns = namespace(names=[]) %}
{% for device in devices %}
{% set ns.names = ns.names + [ device_attr(device, 'name_by_user') or device_attr(device, 'name') ] %}
{% endfor %}
{{ ns.names | sort }}
oh that is for the "identify" stuff ?
or any ZHA entities that end up being a button?
well, it's for firmware updates
interesting it brings up way more than what I've had hoped - legit results
there's a radiator valve that reports temperature and on/off state, but power is "unknown"
device_attr(device, 'id') can also be used to create deeplink URLs 
/config/devices/device/{id}
I feel like that when wife looks at me after spending some time with templates 😄
well, that's because it drains your energy when you use it
can you post one of your devices from the conf.device_entry?
well, I've learned a lot today folks, many thanks for all your help both!
yeah sure, one sec
don't make hassbot angry 😛
I'm wondering if it contains the entity registry information
I don't seem to have a conf.device_entry
./core.device_registry?
ya that one
heres one
oh nice
it has links to the config entry
what we really want is the entity registry
because then you can filter out entities that are for 'configuration'
I'm pretty sure that's stored in entity_registry
but we'd need a new func/filter for that
is there a way to add multiple integration_entities?
e.g. integration_entities('zha', 'androidtv') (which fails)
https://dpaste.org/4KgTT this is the first entity of my entity registry
expand(integration_entities('zha'), integration_entities('androidtv')) is the only way
works for me
( I diddn't try it, assuming it works)
ya, only use the + as a last resort tho
oh, why is that?
when you use + you iterate through the second list, then the whole list
with expand
ah, while using expand you mean
it does
nice
optimize when you can, iterating lists is what you want to reduce in all cases.
(integration_entities(x) + integration_entities(y)) | expand would not have that issue?
it would because the + operation is adding each item to the first list
if you use states, you immediately move into non-instant-updates
I avoid states like the plague
always expand a set of entities if you can
depends on what you want out of it
instant at all times 😆
whenever I use states, I'll use it to make a dynamic group through an automation that runs at set times.
then my template will expand the group and have instant updates
right. my comment above was assuming that the integration entities was static and didn't need updates
well integration entities will re-execute when new entities are added
where as states would but would be more taxing on your system, but at the same time less taxing because it's trottled
is there a way to rate limit template sensors to 1/minute without using the legacy syntax?
you could just add {% set x = states %}
I've got a few of these:
{{ expand(area_entities('Dolgozó'))
|selectattr('attributes.device_class', 'defined')
|selectattr('attributes.device_class', 'eq', 'temperature')
|rejectattr('entity_id', 'search', '.*device_?temperature.*|sensor.(ups_.*)')
|selectattr('state', 'is_number')
|map(attribute='state')|map('float')|average|round(1) }}
but why would you want to rate limit it?
this is running for every area (19)
and frankly 1/minute is enough for temperature sensors report
well, x2 as I have avg and median too now
it's stil not that computation heavy
also, 8 sensors depending on values these provide in the same manner, such as:
{{ states.sensor|selectattr('entity_id', 'search', 'sensor.area_fsz_.*_atlaghomerseklet')
|selectattr('state', 'is_number')
|map(attribute='state')|map('float')|average|round(1) }}
so this is: all temp sensors per area + averaging per floor
I really don't think you need to rate limit it
you're looking at what, 5 temp sensors at most in each area?
2-4 depending on the room
yeah, that's nothing
you'll get slow computations when you iterate your entire states
with what you have there, it's looking at 5 states at most and filtering it down.
almost no computation time whatso ever
yeap, not more than that
it's akin to adding 1 + 1 + 1 + 1
in the second template it can go up to 10
but that's quite strictly |selected not to bring up more than needed
so your area ones:
yeah
{{ expand(area_entities('Dolgozó'))
|selectattr('attributes.device_class', 'defined')
|selectattr('attributes.device_class', 'eq', 'temperature')
|rejectattr('entity_id', 'search', '.*device_?temperature.*|sensor.(ups_.*)')
|selectattr('state', 'is_number')
|map(attribute='state')|map('float')|average|round(1) }}
those are small overhead
correct
no need to worry
{{ states.sensor|selectattr('entity_id', 'search', 'sensor.area_fsz_.*_atlaghomerseklet')
|selectattr('state', 'is_number')
|map(attribute='state')|map('float')|average|round(1) }}
anything I can add to those template sensors that allow me to get out of states.sensor?
that's throttled to 1 update per second at most
(out of already existing values)
the first one is called area_fsz_this_that, and the second one is area_group_this_that
what I do for those is make a dynamic group
like this
- alias: Create Average Group
trigger:
- platform: time_pattern
minutes: "/1"
action:
- service: group.set
data:
object_id: dynamic_average_group
entities: >
{{ states.sensor|selectattr('entity_id', 'search', 'sensor.area_fsz_.*_atlaghomerseklet')
|selectattr('state', 'is_number')
|map(attribute='entity_id') | list }}
then
make a template sensor that just expands that group
{{ expand('group.dynamic_average_group') | map(attribute='state') | map('float')| average | round(1) }}
instant updates, with the bulk of the math being performed once a minute
an automation:?
yes

man - that group.set...
I was looking for something like that for getting my UPS statuses matched up, so I can get notifications out for partial or full power outages
let me take that to dance and see where I land 🙂
hmm expand is not a valid filter 🙂
okay, so not fixed yet
is it possible to get a function inside a selectattr? like I want an attr that contains today's isodayofweek
yes
I have a PR out for that
yeah looks like I'm running onto the bug where things work in template UI, but will not pass config checker validation
selectattr('attributes.foo', 'eq', now().isoweekday())
can I add on to that at all?
What do you mean?
selectattr('entity_id','match','input_boolean.(0[0-9|1[0-2])' + now().isoweekday())
link?
add | string after isoweekday() or change the + to ~
sick. thanks so much 😄
aaah, I thought you had a pr for
is it possible to get a function inside a selectattr?
No, sorry
I was thinking "how tf you pull that off"
if we only knew how they worked...
my input bool for each kid for to-do's that can be time and day of week dependent, and global
{{ states.input_boolean |
selectattr('entity_id',
'match',
'input_boolean.(0[0-9|1[0-2])\d{2}_('+now().isoweekday()|string+'|8)_(kidname|all)'
) |
map(attribute='entity_id') |
list
}}
😂
idea being that certain to-do's can be completed by anyone (like emptying the dish washer) and certain to-do's only occur on a certain day of the week (like putting trash at the curb)
oof, you have to create them tho
that seems like alot of work
unless you use yaml
I've been creating them here and there as we determine what chores each kid should be doing
I've been making them all as helpers
the kids?
yes, but also yes.
That seems to be for states|expand vs expand('states').
I'm looking at {{ expand() failing
expand() just works
I was referring to this:
hmm expand is not a valid filter 🙂
which my PR fixes
oh yeah man my bad - please disregard 😄
Hi Guys, Im not sure if this is a #templates-archived question or an #automations-archived question, but Im trying to achieve the following and not entirely sure the best way to go about it.
I've created a drop down helper with a few different times in it (23:30, 23:45, 00:00 etc) and depending on the selected option I would like an automation to run at that time.
Some information on what I'm trying to achieve: This will be for an electric car charger, Im fine handling the charging side of things but need to be able to set the start time in the drop down which will then start the automation at that time to charge the car.
My first thought is use an automation with a state trigger based on that input_select helper that sets an input_datetime helper based on the time (probably using a template like {{ today_at(states('input_select.whatever')) }}
then an automation with a time trigger using that input_datetime helper to trigger at the right time
That sounds good, I'll give it a try now - Thanks again RobC
how to write this as a template:
- condition: state state: not_home for: minutes: 30 entity_id: device_tracker.iphone
Why do you want it as a template?
because i've forgotten how to do it... 🙂
{{ is_state('device_tracker.iphone', 'not_home') and now() - states.device_tracker.iphone.last_changed > timedelta(minutes=30) }}
- one tiny single quote to the left of
not_home
Added, thanks
please let me ask: why not create the group once (eg a startup) and then trigger the template once a minute?
I know how people just copy and paste things around here 🙂
thanks mate, i was trying to used as_timestamp on the device_tracker
how long has timedelta been around
years?
oh
maybe 2 years
Long, but I haven't used it for this until recently
been away for a little while but previously i was doing thigns like: value_template: "{{ (as_timestamp(now())-as_timestamp(states.device_tracker.iphone.last_changed)) | int(0) > 450 }}"
Im used (now() - states.some.entity.last_updates).total_seconds() / 60 > 30 before that
Until @floral shuttle showed me this version
much cleaner
Yeah, you can do that too. That’s what I have for most of my dynamic groups. I also trigger them at midnight too
Hi guys, i don't want my sensor reset time on 00:00, can I somehow change it so that it resets at 7:30am?, thx.
Also on template reload
yep, that's a known trio here too 😉
- platform: history_stats
name: Calling Time
entity_id: sensor.milan_phone_phone_state
state: "offhook"
type: time
start: "{{ now().replace(hour=0, minute=0, second=0) }}"
end: "{{ now() }}"
- trigger:
- platform: time_pattern
hours: 0
minutes: 0
- platform: homeassistant
event: start
- platform: event
event_type: event_template_reloaded
Change hour to 7, minute to 30
hour to 11
loads of the time/day sensors use that, no need to update each minute
or, when absolutely required: - platform: time_pattern hours: '/6'
end: '{{ now().replace(hour=07, minute=30, second=0) }}' ?? good
thx
Invalid config for [sensor.history_stats]: invalid template (TemplateSyntaxError: expected token ',', got 'integer') for dictionary value @ data['end']. Got '{{ now().replace(hour=07, minute=30, second=0) }}'. (See ?, line ?).
@mighty ledge hm
Post your full config for it, looks correct otherwise
it may not like the 07 padding
That shouldn’t matter, it’s still an int
without 0 before 7 working
Well, doesn’t matter in python,
👍
I have EU time, and if I have USA time how would it distinguish between morning and evening?
It’s based on the location set in your configuration
Hi there! Hope everyone is doing well! I apologize if this is not the correct channel for this question, but "templates" seems to be the closest to my situation.
I have a command line sensor that pulls data usage from vnstat on a pfSense box. The sensor has a scan_interval of 2 weeks, but updates daily at 11:55PM via an automation task to collect the daily usage before vnstat resets at midnight; this works as expected (I can see the data is present and accurate when I look at the sensor's history). What I'm trying to do is take this data and display it on a statistics-graph card in bar form showing the data usage of each day for the last 10 days (or more if I can make it happen). The sensor does not appear as an entity/statistic I can select on the graph card. Right now all I have configured is the command line sensor, 'square 1', so to speak (config copied below). I'm open to all suggestions and willing to try just about anything at this point. Thanks in advance!
# Daily ISP Data Usage from pfSense, collected at 11:55PM each day via automation task
- platform: command_line
name: "Data Usage GB Daily"
unique_id: datacap_daily_gb
# Refresh rate: 2 weeks, updated every day at 11:55PM via automation
scan_interval: 1209600
command: >-
ssh -o UserKnownHostsFile=/config/dzresources/ssh_hosts <USERNAME>@X.X.X.X -i /config/dzresources/pfha_id_rsa 'vnstat -i wan1 --oneline b' | cut -d';' -f 6
unit_of_measurement: "GB"
# Convert from B to GB
value_template: '{{ value | multiply(0.000000001) | round(2) }}'
To clarify on this as well, this is the entry in my sensors.yaml file as the config is broken out into separate files. It does work as expected, just not the graphing
try a template sensor and your quotes in the shell command don't look right for shell or yaml
@tepid onyx Thanks for the reply! Do you happen to have an example of how I can use a template sensor? I’ve tried a few different ways and none are presenting historical statistics so I’m at a loss. Regarding the command itself, it’s working and returning the correct values. I just can’t figure out how to have the sensor present the historical statistics so I can add to a statistics graph
https://www.home-assistant.io/integrations/template/ checkout first example
if you wanna do graphing definietelt checkout influxdb and grafana addons if you haven't already
can anyone see an issue with this? https://pastebin.com/w6zY5Tp3
Remove the quotes around trigger.entity_id
You are now checking for that as a string, not for the variable
oops, I've changed it but it's still not triggering, I've also tried the trigger.entity_id | area_id syntax I've seen on a post and that didn't work either
It is not triggering? Or is it not performing the action?
And how are you testing this?
it's not performing action, will confirm if it's triggering in a moment, i'm testing it by walking into one of the areas where there's a motion sensor
hmm it looks like it may partially be working, looks like the desk sensor triggered and turned off the living room light the others haven't triggered from the looks of the trace timeline
looks like an issue with the trigger
maybe not it does say triggered by kitchen in the logbook entries
looks like it was due to having multiple entities under
- platform: state
entity_id:
changed them all to have their own
- platform: state
entity_id:
looks like i spoke too soon
I think it's a timing thing with the triggering, i remember reading something about how depending on how many entities and such you have specified can change it to checking every few seconds to every few minutes.
If you were using the RUN ACTIONS button, that will never work using trigger variables. As there is no trigger then
With trigger variables you really need a trigger 🙂
no i was letting it trigger normally
And this trigger should work fine
it's just not triggering instantly for some reason, it seems delayed / intermittent
What does the trace show
Shows it was last triggered 5 mins ago tried to call light.toggle i beleive it triggered light.livingroom off (the icon just has a white cirle no dot in it) then shows finished, which is indeed the current state of my living room light
it's just triggered again for living room but on this time
for kitchen ah it tries to run light toggle but for some reason isnst able to find entities in that area id from the looks of it
You are doing a light.toggle, so if it is is off, it will be turned on
did you add all lights to the corresponding area?
and the same for the binary_sensors
they should be i did that over the weekend added anything that was missing but will recheck the lights
and do you want the lights to follow the state of the motion sensor? So if the motion sensor is on, the lights should be as well?
no just toggle for now, i plan on making it trigger a more advanced script i setup the other day
i created the test mostly to test the area stuff worked as i could never get it to trigger in the past
How can I check the color_temp of all lights in an area. I know the attribute exists and I know the area is good as I stepped it back to checking the area and I saw the output of all the lights and their attributes. I was trying something along these lines but I am getting an error that color_temp doesn't exist when it does for all lights.
{% set number_of_lights = states.light | selectattr('entity_id', 'in', area_entities('Kitchen')) | selectattr('state', 'eq','on') | map(attribute='entity_id') | list %}
{{ states.light | selectattr('entity_id', 'in', area_entities('Kitchen')) | selectattr('color_temp', '=', '222') | list | count == number_of_lights | count }}
the entitys were set to kitchen for the lights but not the device so i fixded that but it's still not triggering
just shows light.toggle and then just ending for kitchen
selectattr('color_temp', '=', '222') is wrong
I changed it to eq I forgot to make the change in what I posted
you need to use '==' or 'eq' or 'equalto'
And the '222' is wrong too, color_temp: is an attribute, so it can have a native typ (int in this case)
so you need to check for a number, not a string
Tried that too.
It might be good if you actually mention that when posting the question 😛
oh, and you need to use attributes.color_temp
'homeassistant.helpers.template.TemplateState object' has no attribute 'color_temp'
Even weirder. After changing it to attributes.color_temp
'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'color_temp'
Actually nevermind I had the lights off.. lol. I just turned them on and it works with attributes.color_temp it doesn't have that attribute when off
correct
you need to check for that
I would also probably turn your selection around, first select on area entities, then select on domain
What would the difference be?
{{ expand(area_entities('Kitchen')) | selectattr('domain', 'eq', 'light') | selectattr('attributes.color_temp', 'defined') | selectattr('attributes.color_temp', 'eq', 222) | list | count }}
It will not be throttled to one update per second
and you probably have less entities in your Kitchen than you have lights in total
So your first selection will be less entities
It also not actually evaluating as expected. It saying true when the color_temp of the lights is 370
My version above?
.share the trace json using one of these websites
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.
Nope my Verizon. Let me add the variable number of lights to see if it becomes true. It has the correct number right now when I changed it to 370
Well, your version is throttled, so updates are delayed
Seems okay, should have toggled all lights in area living_room
Worked now. This would be used in an automation. So it will evaluate without issue then right? As in it won't be a template sensor
living_room seems to work fine it's all the other areas that dont
It would be nice to have a trace of one which did not work then
yes, should work fine anywhere (trigger, condition, template sensor)
Awesome thank you.
This is the action it performed
service: light.toggle
target:
area_id:
- kitchen
So your template is working fine
What happens if you use the above service call in developer tools > services
works for living room but not kitchen
found the issue -_- for the kitchen at least
switch was off in kitchen, bedroom still not working though and that's on
I think the variable number_of_lights is causing this error. I tried count and length
Error rendering variables: TypeError: object of type 'int' has no len()
your number_of_lights variable is already providing the count
You are trying to count this integer again
I thought so too but I kept getting {}
color_temp_condition: >-
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) |
selectattr('attributes.color_temp', 'defined') |
selectattr('attributes.color_temp', 'eq', set_color_temp) | list | count ==
number_of_lights | count }}
remove the count at the end here
Yeah because now I'm getting this in trace
number_of_lights:
- light.closet_1
- light.closet_2
set_color_temp: '{ ''Day'': 222, ''Night'':370, ''8pm'': 370, ''After9pm'': 370 }'
color_temp_condition: false
Your change would count the list instead of what I had which wouldn't work here
you changed the number_of_lights template than after you posted the link
Something funky is happening. Sometimes it renders this [] I made no changes. Other times it actually renders the list
I will need to look into this. I like that you can setup an automation with the stop action. Allows fast testing. Never tried this before.
I normally just added something like - delay: 0
number_of_lights: >-
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) |
selectattr('state', 'eq','on') | map(attribute='entity_id') | list |
length }}
This is what is in your link, that should provide an integer
And not:
number_of_lights:
- light.closet_1
- light.closet_2
length and count do exactly the same
Yeah I know. I removed | count from the condition. How would I access the dictionary to get the color_temp. In the condition template. I tried script_type[set_color_temp]
Would it be script_type.set_color_temp
yes, or script_type['set_color_temp']
Wouldn't the ' make it a string?
Huh wait
Set color temp contains the dict, not script type
you need to do set_color_temp[script_type]
and indeed without quotes
That would allow for example Day to be 222? So color_temp we are checking for in the condition would be 222
script_type['set_color_temp'] and script_type.set_color_temp do the same, but do not work with a variable
If the script_type is Day that would result in 222
Perfect.
Makes sense
The condition is still rendering false.
https://dpaste.org/AzhRK
All 7 are at 222. It should be true.
Check what it returns without the comparison
or check this in devtools
{% set script_type = 'Day' %}
{% set set_color_temp = { 'Day': 222, 'Night':370, '8pm': 370, 'After9pm': 370 } %}
{{ states.light | selectattr('entity_id', 'in', area_entities(area)) |
selectattr('attributes.color_temp', 'defined') |
selectattr('attributes.color_temp', 'eq', set_color_temp[script_type]) |
list | count }}
area: kitchen
script_type: Day
number_of_lights: 7
set_color_temp: '{ ''Day'': 222, ''Night'':370, ''8pm'': 370, ''After9pm'': 370 }'
color_temp_condition: []
BTW, you can also use yaml for your set_color_temp variable
So, make sure your template to count them works first 🙂
Weird dev tools worked it said 7
variables:
set_color_temp:
Day: 222
Night: 370
8pm: 370
After9pm: 370
Are you also turning the lights on?
You think that would fix it? Yep they are on this time lol.
Or are they static while testing this?
No, won't fix it, but might be easier to manage
It wouldn't render true if they were off because there's no color_temp
No, I meant they are on on all the time, you are not turning them on while running these tests
Oh yes they are staying on to test this.
And what if you use this (without the comparison for now)
color_temp: "{{ set_color_temp[script_type] }}"
color_temp_condition: >-
{{ expand(area_entities(area)) |
selectattr('attributes.color_temp', 'defined') |
selectattr('attributes.color_temp', 'eq', color_temp) |
list | count }}
BTW you could also add your scripts to an area instead of the split you are using now
I don't think I've ever seen a color represented as a 370
it's color temp
Petro https://dpaste.org/XKkjY
hue ranges from 0 to 360
HA uses mired
yeah, just seems wrong to me
to represent the color_temp
I changed you provided to condition1 to compare.
area: kitchen
script_type: Day
number_of_lights: 7
set_color_temp: '{ ''Day'': 222, ''Night'':370, ''8pm'': 370, ''After9pm'': 370 }'
color_temp_condition: 0
color_temp: ''
color_temp_condition1: 0
These are zha lights if it matters Petro.
okay, so the error is in getting the color_temp out of your dict
But it works in template editor with what you sent lol
why is that a string?
Around what?
set_color_temp: '{ ''Day'': 222, ''Night'':370, ''8pm'': 370, ''After9pm'': 370 }'
there
it's not a dict now, it's a string
which would also be resolved if you added it as yaml instead of json
I'd wager there's an erroneous pipe or carrot
Oh I see. Not sure how I didn't see it. Will try again.
The GUI probably did