#templates-archived

1 messages · Page 4 of 1

leaden cipher
#

Yea, clearly I have no idea what I'm doing. Got myself so confused by now, been at this 2 days.

leaden cipher
#

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.

floral shuttle
#

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?

marble jackal
#

Oh right, my bad.. was still early when I replied

floral shuttle
#

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}}

marble jackal
#

To avoid the unavailables you could also try to keep it on the current state in the state template

sterile nacelle
#

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 :/

sterile nacelle
#

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

inner mesa
#

regarding the test button, see the first pinned message

#

and that looks like 2 seconds...

sterile nacelle
#

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 🙂

inner mesa
#

exactly like that

#

I would do this, BTW: {{ states.switch.fr_table_lamp.last_changed < now() - timedelta(days=2) }}

sterile nacelle
#

that's alot more readable thanks

#

AND doesn't seem to work tho, to combine multiple checks

inner mesa
#

it does, just use "and"

#

almost nothing in HA is CAPS

sterile nacelle
#

xD

#

other languages it must be caps to work

#

like SQL

inner mesa
#

pretty much only that

sterile nacelle
#

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?

inner mesa
#

no

sterile nacelle
#

but there is no way to use states() to get last_changed right?

#

so i would have to use states. anyways?

inner mesa
#

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

sterile nacelle
#

{{ is_state('input_boolean.chore_vacuum_badevaerelse','on') and states.input_boolean.chore_vacuum_badevaerelse.last_changed < now() - timedelta(seconds=2) }}

inner mesa
#

yes

wicked parrot
#

Is there a way to hide modes with a climate entity?

obsidian lintel
#
{% 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?
mighty ledge
obsidian lintel
#

Wot a legend

marble jackal
mighty ledge
obsidian lintel
#

But no need, as recommended from petro, thomas cards are sick af

marble jackal
#

Yeah, no need for templates to show all lights which are on then

paper hazel
#

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') }}"
marble jackal
#

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

paper hazel
#

Hmmm... So no major impact to resources like CPU/RAM?

marble jackal
#

No, it basically does the same, check the current state and compare it to the wanted state

paper hazel
#

Cool! If the trace is the only major downside, I guess it cant hurt using them as they read easier to me

radiant spindle
#

Does someone knows why this is not working ```

  • conditions: "{{(states('sensor.lumi_lumi_weather_a372b807_temperature')|float) > (state_attr('weather.maison_accuweather', 'temperature')+5)}}"``` ?
hollow moth
desert plover
#

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?

radiant spindle
hollow moth
#

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 %}

young lake
#

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. 🤷‍♂️

inner mesa
#

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?

hollow moth
#

My sensor I'm trying to create is the h60_ one, the other one is the one I'm listening to

inner mesa
#

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 %}
desert plover
inner mesa
#

{{ ( states.sensor.valueNew ) | float < ( states.input_number.valueOld) | float }} is just incorrect syntax

silent vector
#

How would I setup a for loop to iterate through the list results checking that last updated is > 30 minutes?
https://dpaste.org/1GRAq

marble jackal
#

the input_booleans or the cameras?

silent vector
#

The input booleans.

marble jackal
#

you don't need to loop for that

silent vector
#

The list will list corresponding booleans. So there could be 2 booleans. 1 or 4. How would I do that without a loop?

marble jackal
#

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

silent vector
marble jackal
#

I've changed it

#

forgot the map() the first time

silent vector
#

Worked thank you!

scarlet berry
#

can someone help me out on chat with a noob template sensor?

silent barnBOT
#

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:

  1. What version of the Home Assistant are you running? (remember, last isn't a version)
  2. What exactly are you trying to do that won't work?
  3. Is the problem uniform or erratic?
  4. What's the exact error message?
  5. When did it arise?
  6. What exactly don't you "get"?
  7. Can you share sample code, ideally with line errors where the error occurs?
scarlet berry
#

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

marble jackal
#

Please don't do that

#

If you want to test bot messages, go to #botspam

scarlet berry
#

oh sorry

marble jackal
#

and please format your code as code

silent barnBOT
#

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).

marble jackal
#

there is an example for device trackers in the yaml there

scarlet berry
#

thank you for your assistance!

tepid mantle
#

GJ TheFes...

unreal merlin
#

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?

#

the t != 'None' is... well, quite awful

marble jackal
#

This will not work:

  1. t will never be the string None, so t != 'None' will always be true. It will also not be none, it will be [] if no sensors match the criteria. You should use t != []
  2. You are better of with an availability template in your sensor which checks if any of the source sensors is providing a numeric value
unreal merlin
#

yeah t='None': absolutely. On the availability template that would actually run a pretty similar set of filters (except for mapping/averaging)

marble jackal
#
  1. you should start your template with states.sensor instead of states to avoid it having to go through all state objects
unreal merlin
#

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

marble jackal
#

well, states is throttled to update only once every 10 seconds if I'm correct, states[domain] every second

#

periods could be different

unreal merlin
#

on availability_template: so this would essentially be looking if the result is a list with at least one item that's a float.

marble jackal
#

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 %}
unreal merlin
#

hmmm ohhh 🙂

marble jackal
#

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

unreal merlin
#

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 }}

marble jackal
#

yes, that is what I just placed above your post

unreal merlin
#

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

marble jackal
#
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 }}
unreal merlin
#

is there a |median alternative, or do I just build a min_max out of that?

marble jackal
#

there is no median filter

#

you can sort the values and take the middle one

unreal merlin
#

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

marble jackal
# unreal merlin 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')] }}
unreal merlin
#

oh that's a nice solution

#

thank yoU!

unreal merlin
#

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

marble jackal
#

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

unreal merlin
#

Why is that?

marble jackal
#

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

unreal merlin
#

and no way to set the entity_id from yaml?

marble jackal
#

if you don't add a name, and it will be based on the unique_id

unreal merlin
#

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

marble jackal
#

name is not required, basically only state

unreal merlin
#

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
marble jackal
#

the legacy template also has an option to provide availability using availability_template:

unreal merlin
#

oh that's availability_template!

#

any downsides using that then?

marble jackal
#

the new format supports state_class which the old one doesn't support

#

for long term statistics

#

and self referencing using this

unreal merlin
#

ewww 🙂 those are neat things

grim flicker
#

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

marble jackal
#

and other types, like select, number, button

unreal merlin
#

oic, thanks!

marble jackal
grim flicker
#

didnt know i could do this with a sensor. thanks

silent vector
marble jackal
#

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

silent vector
#

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

desert plover
marble jackal
silent vector
#

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.

marble jackal
#

@desert plover use states('sensor.cucumber')

#

{% set boolean_condition = expand(boolean_list) | selectattr('last_changed', '<', now() - timedelta(minutes=30)) | list | count == boolean_list | count %}

silent vector
#

Perfect that is what I was looking for. Sorry for the confusion.

desert plover
#

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?

marble jackal
#

How about input_number.set_value?

#

You can use a template to get the state of the sensor

#

And use that for value:

desert plover
#

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
inner mesa
#

you need to surround your template in quotes

desert plover
#

yeeeeaah tyyyyyyyyyyyyy

unreal merlin
#

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?

inner mesa
#

how did you define the namespace?

unreal merlin
#

Hey RobC! 🙂

#

{%- set ns = namespace(mapped=[], num=0) %}

#

before this for l in ns.mapped line, I can see there there's data in ns.mapped

#

[{'n': 'boot.mb', 'e': 2401},...]

inner mesa
#

this works fine:

{% set ns = namespace(foo=[]) %}
{% set ns.foo = ['foo', 'bar'] %}

{% for item in ns.foo %}
  {{ item }}
{% endfor %}
unreal merlin
#

yeah

paper hazel
#

I'm trying to understand how the "-" in templates changes them, e.g. '{% ... %}' vs '{%- ... -%}'. Any help on this will be appreciated

unreal merlin
#

RobC: can you selectattr in that?

inner mesa
#

{%- set ns = namespace(list="") %}

#

I concur with the error

unreal merlin
#

but the error calls out ns.mapped, not ns.list

inner mesa
#

yes

#

because you redefined the namespace to not include mapped

unreal merlin
#

bahhh

#

is that not adding a new ns variable, but redefining the whole ns?

inner mesa
#

you set the variable

#

it's exactly what you told it to be

marble jackal
#

Add list="" to the first time you define ns

unreal merlin
#

yeah it works like that

marble jackal
#

Or just use a different name for your namespace

unreal merlin
#

was it always like this?

marble jackal
#

You don't have to use ns

inner mesa
#

yes, otherwise it would be magic

unreal merlin
#

interesing - I thought this thing worked last week 😄

marble jackal
#

It's always been like this, if you overwrite a variable, the previous value will be gone

unreal merlin
#

I mean: this template actually ended up sending me notifications without erroring out

inner mesa
#

namespaces are no different from any data structure

marble jackal
unreal merlin
#

yeah, makes sense - better look for some other items like this in my code

#

thanks guys, this enlightenment is much appreciated

paper hazel
# marble jackal It differs in how whitespaces are handled

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?

inner mesa
#

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

paper hazel
#

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

marble jackal
#

Indeed, the HA template renderer also removes them

#

What do you want to achieve

paper hazel
#

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.

marble jackal
#

Correct

paper hazel
#

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

inner mesa
#

that's a lot of repetition 🙂

marble jackal
#

Why don't you use an input datetime for your snooze time input?

#

Instead of a separate one for hours and minutes

paper hazel
#

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.

paper hazel
paper hazel
marble jackal
#
{%- 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 %}
paper hazel
#

you gotta be kidding...

#

This just makes me realise once again I got a long road ahead of learning... Appreciate the help and insight 🙏

marble jackal
#

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

paper hazel
#

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...

marble jackal
#

ah, yeah, I replaced them with something like {% set h = 5 %} after that, as I don't have these input_numbers anyway

inner mesa
#

it's always 5 o'clock somewhere

paper hazel
#

This was an eye opener to me```
hour{{ 's' if h != 1 }}

paper hazel
silent barnBOT
paper hazel
#

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 %}

mighty ledge
#

@civic hedge you can't template in the frontend. You'd have to make a script and call the script instead.

civic hedge
civic hedge
#

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```
viral bolt
#

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>?

inner mesa
viral bolt
#

the Modbus part works fine, I need to use the template part so the relays state is based on binary_sensor state

inner mesa
#

by "button", do you mean in the frontend?

viral bolt
#

nope, i'm thinking on creating a template switch which when toggled toggles the relay and its state is based on binary_sensor

inner mesa
#

ok, so that's straightforward

#

did you try writing a template switch for that?

viral bolt
#

I think I've found an example on my config, I'll give it a shot

#

nope, it doesn't look to work

inner mesa
#

Ok

viral bolt
#

any clue what's wrong?

inner mesa
#

You provided no details

viral bolt
#

please see the pastebin URL above

inner mesa
#

How didn't it work?

#

Not gonna guess

viral bolt
#

when checking config I get an error

inner mesa
#

See, that detail

#

And of course the actual error

viral bolt
#

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 ?).

inner mesa
#

It told you what's wrong and even how to fix it

viral bolt
#

if I had understood the error code, I certainly would not have asked for help

inner mesa
#

The very first sentence there

#

Remove 'switch.'

#

Or use what it suggested

viral bolt
#

yep, i'm a bit blind this evening, thanks and sorry for bothering you

rare linden
#

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

inner mesa
#

You can't template keys like that

#

The easiest solution is to use a choose: to decide between two service calls

rare linden
#

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']

inner mesa
#

Yes, you need to surround the template in quotes

rare linden
#

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

inner mesa
#

Well, it needs quotes

#

Are you actually passing it in?

rare linden
#

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

inner mesa
#

Those fields do nothing

#

You have to call it with the parameters

#

They're just to guide humans

rare linden
#

i've just added them in as variables to test for the moment, thanks

woeful root
#
   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?
rare linden
#

try (states('sensor.verbrauch_schultz_KW')|float * 1000)|int

woeful root
#

awesome. thank you

rare linden
#

No problem

silent vector
#

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.

rare linden
#

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

silent vector
#

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.

rare linden
#

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

silent vector
#

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.

silent vector
marble jackal
#

That will not work for wait_for_trigger

#

In case it timed out wait.trigger is none will be true (corrected)

silent vector
#

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?

marble jackal
#

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

silent vector
#

Even when the trigger is in a wait for trigger and not the trigger section?

#

It has an id?

marble jackal
#

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

silent vector
#

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'

marble jackal
#

No

#

It's not a string, so don't check for 'none'

silent vector
#

It's just null?

marble jackal
#

wait.trigger is not none

silent vector
#

I see

#

That is what I needed.

versed delta
#

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) }}"
grim flicker
#

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'] }}
marble jackal
silent vector
# marble jackal `wait.trigger is not none`

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

versed delta
marble jackal
#

If no trigger then proceed indicates you actually want to check on wait.trigger is none

silent vector
#

Oops that was easy. Sorry.

marble jackal
charred dagger
marble jackal
#

That's indeed what I also should have said 😅

marble jackal
versed delta
#

This is what I get in the template editor

#

template:

  • sensor:
    • name: "PVH1"
      unit_of_measurement: "watts"
      state: "-373.0"
#

as a result

marble jackal
#

I assume after correcting that missing quote

versed delta
#

yes, although the sensor is still not visible as an entitiy

#

Ah a needed to reload entities

versed delta
#

How do I take the absolute value of of a custom sensor

inner mesa
#

|abs or abs(x)

#

Good links in the channel topic

charred haven
#

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

mighty ledge
charred haven
mighty ledge
#

well

inner mesa
#

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

mighty ledge
#

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

mighty ledge
#

states | will be throttled to at most 1 update per minute

inner mesa
#

yes, as in the link above 🙂

mighty ledge
#

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

inner mesa
#

I practically killed somebody's Pi instance with states| once

mighty ledge
#

if you want dynamic entity sets based on wildcards using states, make an automation that sets a group

inner mesa
#

I was like: works great on my i5!

mighty ledge
#

Lol, yep

#

it was probably @floral shuttle

inner mesa
#

was taking like 30-45s or something like that

mighty ledge
#

He was the chief tester for the rate limiting IIRC

#

because all his systems have crazy templates

mighty ledge
#

bdraco made those changes specifically to counter act poorly optimized templates on slow machines

#

90's NBC FTW

marble jackal
mighty ledge
#

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.

charred haven
#

thank you @mighty ledge 🙏

mighty ledge
#

np

floral shuttle
queen viper
#

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()))}}

rare linden
#

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?

inner mesa
#

you can technically generate key/value pairs, but you have to template the whole data section and generate a dict

mighty ledge
#

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'.

queen viper
mighty ledge
marble jackal
#

Or use timestamps instead of datetimes and use timestamp_custom

mighty ledge
#

that won't necessarily work if the number of days is greater than 31

queen viper
marble jackal
#

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
mighty ledge
#

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

queen viper
# marble jackal Add `as_local`

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

mighty ledge
#

{{ (relative_time(states.input_datetime.andrades.state | as_datetime | as_local)) }}

queen viper
mighty ledge
#

it's a filter

#

or a method

#

method = some_method(...)

#

filter = ... | some_method

marble jackal
#

{{ relative_time(as_local(states.input_datetime.andrades.state | as_datetime )) }}

#

Btw you should use states('input_datetime.andrades')

mighty ledge
marble jackal
#

So many options 😅

mighty ledge
#

the least amoutn of () is always the best option when you can't use multiple lines IMO

queen viper
#

Yeah.. Hah.. I am most thankful.

#

I was close to just firing up a new app in appdaemon.... 😛

rare linden
#

is there a way to reference script fields?

inner mesa
#

they're Jinja variables

#

they serve no purpose other than to reference them 🙂

rare linden
#

i mean outside of the script though

inner mesa
#

unless you mean some other "script fields"

#

no

mighty ledge
#

why would you want that?

#

.xy

rare linden
#

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

mighty ledge
#

nooooooooooooooooooooooooooooooo where's the bot @arctic sorrel

#

just use anchors

rare linden
#

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

mighty ledge
#

yaml -> anchors

#
input_select:
  who_cooks:
    name: Who cooks today
    options: &options
      - Paulus
      - Anne Therese
  living_room_preset:
    options: *options
rare linden
#

ok, thanks

jolly ibex
#

Hi, Is it possible to add brightness control for modbus lights without using a template?

queen viper
#

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.

marble jackal
#

as_local just adds your local timezone, it doesn't do translations

queen viper
#

aaaaah... the doh's just keep doh'ing.

#

I suppose i could wrangle regexp_replace then... Thanks

arctic sorrel
marsh hull
#

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?

inner mesa
#

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

marsh hull
#

OK, so when the entity_id is not a variable, it is surrounded in quotes.

inner mesa
#

if you want a string, you put it in quotes. If you want a variable, you don't

marsh hull
#

What do you mean by, "...kill your device"?

inner mesa
#

it's going to sit there and spin in the loop as fast as possible

marsh hull
#

I could put a delay in my sequence, right?

inner mesa
#

just use one of the options that I suggested

#

you don't want a loop at all

charred dagger
#

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.

marsh hull
#

I my actual code, I have four conditions, any one of which should trigger the exit of the tight loop

inner mesa
#

you could add them all in a wait_for_trigger and it would be much better for HA

inner mesa
#

or a wait_template, if it's possible that it's already changed state and you just want to know that right away

marsh hull
#

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?

inner mesa
#

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

marsh hull
#

right, If I had varibles, there wouldn't be quotes around the b1

inner mesa
#

ok

marsh hull
#

but if I had actual entities it would be something like 'switch.b1'

inner mesa
#

yes

marsh hull
#

OK, thanks, that should keep me busy until dinner (and not longer, I hope 😉

inner mesa
#

you could further simplify that, but that's just an optimization

marsh hull
#

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")
    }}"
inner mesa
#

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")
    }}
silent vector
#

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 }}
unreal beacon
#

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

marble jackal
#

state_attr('sensor.foo', 'bar') > X

unreal beacon
#
    Driving
{% else %}
     {{states("device_tracker.XXX")}}
{% endif %}```
#

this is what ive got so far

#

but it doesnt seem to work?

marble jackal
#

You have {{% and %}}, there should be one curly bracket there

unreal beacon
#

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?

marble jackal
#

And you should replace is_state_attr with state_attr

unreal beacon
#

haha!

#

got it

#

im not a total fool

marble jackal
#

is_state_attr expects a third argument, the state you are comparing it with

#

But can only be used for equal to

unreal beacon
#

right ok

marble jackal
#

But I'm not sure how the event data structure looks like. You can check that in the trace

silent vector
#

Can I also reject 'off' with a wildcard in the entity_id by saying 'off' not in trigger.event.data.entity_id

marble jackal
#

okay, that's matching what I suggested

#

ah, was just going to mention the quotes, but yes, that would work

silent vector
#

Perfect. Sometimes the solution is significantly easier than I thought.

marble jackal
#

BTW, in this trace you can also see that the trigger has a trigger.id 🙂

silent vector
#

Yes it does from our conversation yesterday lol.

unreal beacon
#

@marble jackal - quick question if i may, is there a way in what ive done to swap the "Driving" text to an MDI?

silent vector
#

Just tested it and it worked.

marble jackal
#
{% if atate_attr("device_tracker.XXX", "speed")| float > 10 %}
    🚗
{% else %}
    {{states("device_tracker.XXX")}}
{% endif %}
mighty ledge
#

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

marble jackal
#

Well, emoji is easy, just press windows key + . (on windows of course) and select one you like

unreal beacon
#

thanks

unreal beacon
mighty ledge
#

need to use something that injects html and resolves it

#

if you want the mdi icons

unreal beacon
#

yeah its not a big issue

#

text output is fine 🙂

mighty ledge
#

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.

unreal beacon
#

ill have a play 🙂

mighty ledge
#

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}`);
    ]]]
unreal merlin
#

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 🙂

mighty ledge
#

post them and me or @marble jackal can help you optimize them

mild valve
#

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 }}

mighty ledge
#

most likely a light group

#

when you use states.light you filter your selections down to things only in the light domain

mild valve
#

oh yeah, i have "all lights" group

mighty ledge
#

i.e. sensor.count_lights_on is not included in the template

mild valve
#

can I reject light group based on it's identity?

mighty ledge
#

so filter out the all lights light instead of sensor.count_lights_on

marble jackal
#

filter out entities with an entity_id attribute

#

it's in one of the pinned posts

mild valve
#

Yeah, got it working

unreal merlin
#

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)
mighty ledge
#

So even though it's heavy, it's only executing once per minute

unreal merlin
#

Yeap, which is fine for this purpose

mighty ledge
#

it's updating names and doing other crap that it doesn't need to do when you're just getting a count

unreal merlin
#

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?

marble jackal
#

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

unreal merlin
#

(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 }}
marble jackal
mighty ledge
#

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

unreal merlin
#

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 😕

mighty ledge
unreal merlin
#

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 🙂

mighty ledge
#

do you have any entities that come from yaml that do not have a device?

unreal merlin
#

like a template sensor?

mighty ledge
#

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

unreal merlin
#

the purpose of this is to find all zigbee sensors throwing themselves off network

#

they are all real devices

mighty ledge
#

oh really?

silent barnBOT
#

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.

mighty ledge
#

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

unreal merlin
#

sure, one sec

marble jackal
#

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

unreal merlin
#

oh hmmm would that be stg like integration_entities(zha)?

marble jackal
#

integration_entities('zha')

mighty ledge
#

yeah but htere's like 10 ways to integrate zha

unreal merlin
#

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)

mighty ledge
#

post the results of this

#
{{ device_attr('sensor.garazs_paramero_humidity', 'identifiers') }}
#

use the template tester

unreal merlin
#

{('zha', '14:b4:57:ff:fe:3c:68:0d')}

mighty ledge
#

developer tools -> template

#

clear, paste, profit

unreal merlin
#

😄

mighty ledge
#

ok, so it's zha

unreal merlin
#

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}}

mighty ledge
#

sorry, got sidetracked

#
{{ integration_entities('zha') | expand | selectattr('state','in', ['unknown', 'unavailable']) | map(attribute='entity_id') | map('device_id') | unique | list | count }}
unreal merlin
#

pfahhh

#

😄

mighty ledge
#

and for the names...

unreal merlin
#

map(device_id)|selectattr('name'...?

marble jackal
#

guess you meant zha instad of zwave_js

unreal merlin
#

yeah no worries there

mighty ledge
#
{% 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 }}
unreal merlin
#

oh interesting

#

any reason for not expand(integration_entities('zha')) but integration_entities('zha')|expand?

mighty ledge
#

it's the same

unreal merlin
#

this one looks better tho (follows pattern)

mighty ledge
#

there are issues with it as afilter, but i believe those issues were fixed

marble jackal
#

isn't there a bug with the filter making it only work in the template editor, but not in sensor entities?

mighty ledge
#

flip it then

marble jackal
#

could be it's fixed 🙂

unreal merlin
#

awesome, thank you!

mighty ledge
#

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

marble jackal
#

uhm, you mean in .storage?

mighty ledge
#

yes

marble jackal
#

yeah, I can access it

mighty ledge
#

can you tell me the field that contains the user set name

#

of the device

#

the key itself

marble jackal
#

it seems to be name_by_user

#

but if not set that will be null

mighty ledge
#

oh ffs, i tried everything

unreal merlin
#

that in core.device_registry?

mighty ledge
#

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 }}
unreal merlin
#

so device_attr(device, 'name_by_user') is available then awesome

mighty ledge
#

yes

#

change the last line to {{ ns.names | sort }} to sort it

unreal merlin
#

would that apply to all other attributes in device registry?

#

device_attr(device, 'connections') for example

mighty ledge
#

device_attr gets any attribute that's in the device registry for that devicde

#

yep

#

try it

unreal merlin
#

oh ffs if I had known that a week ago 😄

#

several new worlds opened up just now

#

need a drink

mighty ledge
#

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 }}
unreal merlin
#

oh that is for the "identify" stuff ?

#

or any ZHA entities that end up being a button?

mighty ledge
#

well, it's for firmware updates

unreal merlin
#

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 mindblown

#

/config/devices/device/{id}

unreal merlin
#

I feel like that when wife looks at me after spending some time with templates 😄

mighty ledge
#

well, that's because it drains your energy when you use it

#

can you post one of your devices from the conf.device_entry?

unreal merlin
#

well, I've learned a lot today folks, many thanks for all your help both!

#

yeah sure, one sec

marble jackal
#

don't make hassbot angry 😛

mighty ledge
#

I'm wondering if it contains the entity registry information

unreal merlin
#

I don't seem to have a conf.device_entry

mighty ledge
#

if not, then it seems like we might need a new func/macro

#

conf.device_entries?

unreal merlin
#

./core.device_registry?

marble jackal
mighty ledge
#

ya that one

marble jackal
#

heres one

mighty ledge
#

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

unreal merlin
mighty ledge
#

but we'd need a new func/filter for that

unreal merlin
#

is there a way to add multiple integration_entities?

#

e.g. integration_entities('zha', 'androidtv') (which fails)

marble jackal
mighty ledge
#

expand(integration_entities('zha'), integration_entities('androidtv')) is the only way

unreal merlin
#

works for me

mighty ledge
#

( I diddn't try it, assuming it works)

marble jackal
#

+ should also work, as it provides a list

#

also didn't try

mighty ledge
#

ya, only use the + as a last resort tho

marble jackal
#

oh, why is that?

mighty ledge
#

when you use + you iterate through the second list, then the whole list

#

with expand

marble jackal
#

ah, while using expand you mean

mighty ledge
#

if you use the, you'd iterate the first list, then the second

#

yeah

unreal merlin
mighty ledge
#

nice

mighty ledge
marble jackal
#

(integration_entities(x) + integration_entities(y)) | expand would not have that issue?

mighty ledge
inner mesa
#

that's one where I might start with states|...

#

since it's static

mighty ledge
#

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

inner mesa
#

depends on what you want out of it

mighty ledge
#

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

inner mesa
#

right. my comment above was assuming that the integration entities was static and didn't need updates

mighty ledge
#

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

unreal merlin
#

is there a way to rate limit template sensors to 1/minute without using the legacy syntax?

mighty ledge
#

you could just add {% set x = states %}

unreal merlin
#

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) }}
mighty ledge
#

but why would you want to rate limit it?

unreal merlin
#

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

mighty ledge
#

it's stil not that computation heavy

unreal merlin
#

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

mighty ledge
#

I really don't think you need to rate limit it

#

you're looking at what, 5 temp sensors at most in each area?

unreal merlin
#

2-4 depending on the room

mighty ledge
#

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

unreal merlin
#

yeap, not more than that

mighty ledge
#

it's akin to adding 1 + 1 + 1 + 1

unreal merlin
#

in the second template it can go up to 10

mighty ledge
#

doesn't matter, still small

#

states.sensor one though, that one is big

unreal merlin
#

but that's quite strictly |selected not to bring up more than needed

mighty ledge
#

so your area ones:

unreal merlin
#

yeah

mighty ledge
#
          {{ 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

unreal merlin
#

correct

mighty ledge
#

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) }}
unreal merlin
#

anything I can add to those template sensors that allow me to get out of states.sensor?

mighty ledge
#

that's throttled to 1 update per second at most

unreal merlin
#

(out of already existing values)

mighty ledge
#

well, it's out of your entire sensor domain

#

personally

unreal merlin
#

the first one is called area_fsz_this_that, and the second one is area_group_this_that

mighty ledge
#

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

mighty ledge
#

yes

unreal merlin
#

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 🙂

unreal merlin
#

hmm expand is not a valid filter 🙂

marble jackal
#

okay, so not fixed yet

lost locust
#

is it possible to get a function inside a selectattr? like I want an attr that contains today's isodayofweek

marble jackal
#

yes

inner mesa
#

I have a PR out for that

unreal merlin
marble jackal
#

selectattr('attributes.foo', 'eq', now().isoweekday())

lost locust
#

can I add on to that at all?

marble jackal
#

What do you mean?

lost locust
#

selectattr('entity_id','match','input_boolean.(0[0-9|1[0-2])' + now().isoweekday())

mighty ledge
inner mesa
mighty ledge
lost locust
#

sick. thanks so much 😄

mighty ledge
inner mesa
#

No, sorry

mighty ledge
#

I was thinking "how tf you pull that off"

inner mesa
#

Took too long to write my message

#

magnets. It's always magnets

inner mesa
#

if we only knew how they worked...

mighty ledge
#

gif for everything

lost locust
#

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)

mighty ledge
#

oof, you have to create them tho

#

that seems like alot of work

#

unless you use yaml

lost locust
#

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

inner mesa
#

the kids?

lost locust
#

yes, but also yes.

unreal merlin
inner mesa
#

expand() just works

#

I was referring to this:

hmm expand is not a valid filter 🙂

#

which my PR fixes

unreal merlin
#

oh yeah man my bad - please disregard 😄

gusty pulsar
#

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.

inner mesa
#

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

gusty pulsar
#

That sounds good, I'll give it a try now - Thanks again RobC

tepid onyx
#

how to write this as a template:
- condition: state state: not_home for: minutes: 30 entity_id: device_tracker.iphone

marble jackal
#

Why do you want it as a template?

tepid onyx
#

because i've forgotten how to do it... 🙂

marble jackal
#

{{ is_state('device_tracker.iphone', 'not_home') and now() - states.device_tracker.iphone.last_changed > timedelta(minutes=30) }}

inner mesa
marble jackal
#

Added, thanks

floral shuttle
inner mesa
#

I know how people just copy and paste things around here 🙂

tepid onyx
#

thanks mate, i was trying to used as_timestamp on the device_tracker
how long has timedelta been around

inner mesa
#

years?

tepid onyx
#

oh

inner mesa
#

maybe 2 years

marble jackal
#

Long, but I haven't used it for this until recently

tepid onyx
#

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 }}"

marble jackal
#

Im used (now() - states.some.entity.last_updates).total_seconds() / 60 > 30 before that

#

Until @floral shuttle showed me this version

tepid onyx
#

much cleaner

mighty ledge
waxen meadow
#

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.

mighty ledge
#

Also on template reload

floral shuttle
#

yep, that's a known trio here too 😉

waxen meadow
#
  • 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() }}"
floral shuttle
#
  - trigger:
      - platform: time_pattern
        hours: 0
        minutes: 0
      - platform: homeassistant
        event: start
      - platform: event
        event_type: event_template_reloaded
mighty ledge
tepid onyx
#

hour to 11

floral shuttle
#

loads of the time/day sensors use that, no need to update each minute

#

or, when absolutely required: - platform: time_pattern hours: '/6'

waxen meadow
#

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

mighty ledge
#

Post your full config for it, looks correct otherwise

inner mesa
#

it may not like the 07 padding

mighty ledge
#

That shouldn’t matter, it’s still an int

waxen meadow
#

without 0 before 7 working

mighty ledge
#

Well, doesn’t matter in python,

waxen meadow
#

👍

#

I have EU time, and if I have USA time how would it distinguish between morning and evening?

mighty ledge
#

It’s based on the location set in your configuration

waxen meadow
#

I thought

#

and where would I write AM?

pure creek
#

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) }}'
pure creek
tepid onyx
pure creek
#

@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

tepid onyx
#

if you wanna do graphing definietelt checkout influxdb and grafana addons if you haven't already

rare linden
marble jackal
#

You are now checking for that as a string, not for the variable

rare linden
#

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

marble jackal
#

It is not triggering? Or is it not performing the action?

#

And how are you testing this?

rare linden
#

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.

marble jackal
#

With trigger variables you really need a trigger 🙂

rare linden
#

no i was letting it trigger normally

marble jackal
#

And this trigger should work fine

rare linden
#

it's just not triggering instantly for some reason, it seems delayed / intermittent

marble jackal
#

What does the trace show

rare linden
#

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

marble jackal
#

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

rare linden
#

they should be i did that over the weekend added anything that was missing but will recheck the lights

marble jackal
#

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?

rare linden
#

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

silent vector
#

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 }}
rare linden
#

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

marble jackal
silent vector
#

I changed it to eq I forgot to make the change in what I posted

marble jackal
#

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

silent vector
#

Tried that too.

marble jackal
#

It might be good if you actually mention that when posting the question 😛

#

oh, and you need to use attributes.color_temp

silent vector
#

'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

marble jackal
#

correct

#

you need to check for that

#

I would also probably turn your selection around, first select on area entities, then select on domain

silent vector
#

What would the difference be?

marble jackal
#

{{ 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

silent vector
#

It also not actually evaluating as expected. It saying true when the color_temp of the lights is 370

marble jackal
#

My version above?

marble jackal
silent barnBOT
#

Please use a code share site to share code or logs, for example:

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.

silent vector
#

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

marble jackal
#

Well, your version is throttled, so updates are delayed

rare linden
marble jackal
silent vector
#

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

rare linden
#

living_room seems to work fine it's all the other areas that dont

marble jackal
#

It would be nice to have a trace of one which did not work then

marble jackal
rare linden
silent vector
#

Awesome thank you.

marble jackal
#

So your template is working fine

#

What happens if you use the above service call in developer tools > services

rare linden
#

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

silent vector
#

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()

https://dpaste.org/4nYn6

rare linden
#

ah bedroom sensor is missing

#

time for a litre of espresso me thinks

marble jackal
#

You are trying to count this integer again

silent vector
#

I thought so too but I kept getting {}

marble jackal
#
  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

silent vector
#

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

marble jackal
#

you changed the number_of_lights template than after you posted the link

silent vector
#

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.

marble jackal
#

I normally just added something like - delay: 0

marble jackal
#

And not:

number_of_lights:
  - light.closet_1
  - light.closet_2
silent vector
#

Yes it does I removed | length and then | count

#

I needed to keep | length

marble jackal
#

length and count do exactly the same

silent vector
#

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

marble jackal
#

yes, or script_type['set_color_temp']

silent vector
#

Wouldn't the ' make it a string?

marble jackal
#

Huh wait

#

Set color temp contains the dict, not script type

#

you need to do set_color_temp[script_type]

#

and indeed without quotes

silent vector
#

That would allow for example Day to be 222? So color_temp we are checking for in the condition would be 222

marble jackal
#

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

silent vector
#

Perfect.

#

Makes sense

marble jackal
#

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 }}
silent vector
#
area: kitchen
script_type: Day
number_of_lights: 7
set_color_temp: '{ ''Day'': 222, ''Night'':370, ''8pm'': 370, ''After9pm'': 370 }'
color_temp_condition: []
marble jackal
#

BTW, you can also use yaml for your set_color_temp variable

marble jackal
silent vector
#

Weird dev tools worked it said 7

marble jackal
#
variables:
  set_color_temp:
    Day: 222
    Night: 370
    8pm: 370
    After9pm: 370
#

Are you also turning the lights on?

silent vector
#

You think that would fix it? Yep they are on this time lol.

marble jackal
#

Or are they static while testing this?

#

No, won't fix it, but might be easier to manage

silent vector
#

It wouldn't render true if they were off because there's no color_temp

marble jackal
#

No, I meant they are on on all the time, you are not turning them on while running these tests

silent vector
#

Oh yes they are staying on to test this.

marble jackal
#

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

mighty ledge
#

I don't think I've ever seen a color represented as a 370

marble jackal
#

it's color temp

mighty ledge
#

that seems fishy to me.

#

color temp ranges from 2700 to 6500

silent vector
mighty ledge
#

hue ranges from 0 to 360

marble jackal
#

HA uses mired

mighty ledge
#

yeah, just seems wrong to me

marble jackal
#

to represent the color_temp

silent vector
#

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.

mighty ledge
#

no, i'm sure it's some HA bs

#

we always choose odd units

marble jackal
#

okay, so the error is in getting the color_temp out of your dict

silent vector
#

But it works in template editor with what you sent lol

mighty ledge
#

why is that a string?

marble jackal
#

yes, I see that now as well

#

there should be no quotes around that

silent vector
#

Around what?

marble jackal
#

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

mighty ledge
#

I'd wager there's an erroneous pipe or carrot

silent vector
#

Oh I see. Not sure how I didn't see it. Will try again.

marble jackal
#

The GUI probably did