#templates-archived

1 messages · Page 141 of 1

fallow gulch
#

i'm running a stats sensor at the moment with max_age of 72 hours, and it's definitely not right

#

i think it's telling me what the rainfall amount was 72 hours ago

inner mesa
#

Seems unlikely

#

May need to increase the sampling size

fallow gulch
#

stepped it up from default to 100

#

no dice

inner mesa
#

You get one sensor update per day?

#

And look at the total attribute?

#

It shouldn’t be complicated

fallow gulch
#

no it constantly updates

#

it's cumulative rainfall for the past day, which resets at midnight

inner mesa
#

Well, it’s going to add up all the values in the sample range

fallow gulch
#

it might be easier to do this at the weewx end and just have it pass through the 72 hour cumulative value

bright quarry
#

what would a wait template look like that waits for a condition state of media_player.my_tv to on? i'm writing a script that turns the tv on and then waits for it to turn on before changing the input to an app.

inner mesa
thorny snow
#

Hi guys

#

which is the right syntax to create a yaml dictionary template?

#

I saw it somewhere but I can't remember

inner mesa
#

YAML and jinja can both use JSON formatting. Is that what you mean?

thorny snow
#

perhaps..

#

I'm gonna give it a go

#

thanks for the tip

#

look

#

maybe you have a better idea

#

I have this template

#

{% if is_state('sensor.tvaca_tv_channel_name') in ['rJeHak5zRg.Spotify','RN1MCdNq8t.Netflix','vbUQClczfR.Wuakitv','9Ur5IzDKqV.TizenYouTube','evKhCgZelL.AmazonIgnitionLauncher2','BTqpJutesE.Mitele','PzkKxRdFT6.TV3']%}
APP

#

so far so good

#

if channel name if any of those, I want to print the name of the app

#

if channel name is rJeHak5zRg.Spotify, print Spotify

inner mesa
#

Yeah, you should turn that into a dict

thorny snow
#

could you help me a,ittle bit?

#

🙂

#

I'm not sure

#

how to do it

inner mesa
thorny snow
#

thanks!

inner mesa
#

It’s a set of key: value pairs, and then you can index with dictname[key] to get the value

thorny snow
#

alright I got it thanks a lot

#

one little problem

#

when I try to create this dict

#

{Cuatro HD: 10}

#

yields an error due to the space between Cuatro and HD

#

how can I solve that?

inner mesa
#

If the name you want is always the part after the dot, then you just need to do state().split(‘.’)[1]

buoyant pine
#

{"Cuatro HD": 10}

thorny snow
#

is not always that... that's the problem

inner mesa
#

Yes, you need to quite the strings as in that example at the link

thorny snow
#

thanks you two

#

I have a problem with the index

#

I want to use a template

#

when inserting a value it does work

#

but when I do this: [{{states("sensor.tvaca_tv_channel_name")}}]

#

it yields: TemplateSyntaxError: expected token ':', got '}'

inner mesa
#

Remove the {{}}

thorny snow
#

that's it

#

thanks a lot

#

[] equals {{}} regarding indexing I assume then

inner mesa
#

No, {{}} is an ‘output’ statement for jinja

#

[] is always an index

thorny snow
#

now that you say that, it was really silly to put {{}} in there

inner mesa
#

Or a list structure 🙂

thorny snow
#

thanks again

slow vine
#

Is there a way to populate an input_select using a template? i.e. a dropdown list of all lights that are on etc...

inner mesa
#

Yes

#

Use a template like {{ states.light|selectattr(‘state’, ‘eq’, ‘on’)|map(attribute=‘entity_id’)|list }}

#

For the entity_id:

#

Or the options: or whatever they use

slow vine
#

ok, i'll try that.

#

Error loading /config/configuration.yaml: invalid key: "OrderedDict([('states.light|selectattr(‘state’', None), ('‘eq’', None), ('‘on’)|map(attribute=‘entity_id’)|list', None)])" in "/config/packages/input_select_test.yaml", line 4, column 0

#
  lights_on:
    name: Lights On
    options: {{ states.light|selectattr(‘state’, ‘eq’, ‘on’)|map(attribute=‘entity_id’)|list }}```
dreamy sinew
#

you didn't quote your template

inner mesa
#

Or you need to add >-

#

Oh, and you can’t do that

#

You have to call set_options

#

options list REQUIRED
List of options to choose from.

#

You can’t just do it at the definition. You would have to use an automaton to set the options when the state of a light changes

#

And at startup

slow vine
#

I'm working on that now. 🙂 thanks.

inner mesa
#

It’s a bit of a pain the ass. You need to trigger on the state_changed event and use a condition to filter on the domain of the trigger entity

slow vine
#

I'm trying this as an example, my goal is to have a dropdown of all esphome devices, I think I have the template for filtering that down by device attribute of the integration, but fisrt I need to have the general concept, and I think its working now as i expected...

slow vine
#

it seems like Integration is not a device attribute:{{ device_attr('dda0719e582d04a7b8d8e4ef5dccf2c7', 'manufacturer') }} returns the manufacturer but {{ device_attr('dda0719e582d04a7b8d8e4ef5dccf2c7', 'integration') }} returns 'none' 😦

inner mesa
#

There’s no easy way to do that without adding an attribute manually or using a name pattern

slow vine
#

I thought if the devices list includes the integration then it would be also an attribute. How does HA know what integration each device is part of?

inner mesa
#

Oh, I think you can get it out of ‘identifiers’

#

See link above

slow vine
#

the device i'm looking at just returns set() when I look att my zwave hub I get {('zwave_js', '3599338905-1')} I'm guessing its the way its setup internally.

inner mesa
#

it's however the integration fills out the device_info dict

slow vine
#

Thanks for your help, I'm getting somewhere but my computer is dying I'll charge it up later and look at this more tomorrow. 😄

#

and patience.

inner mesa
#

for integrations that do the right thing, this gets it:

#

{{ (device_attr('dd71fc3a10e4469198d9101ce0c18d05', 'identifiers')|first)[0] }}

floral shuttle
floral shuttle
#

got an mqtt sensor which value is 2021-11-04T20:04:26Z and set that to class timestamp with value_template {{value.split('Z')[0]}}. this throws the new error sensor.watermeter_startup_time provides state '2021-11-04 20:04:26', which is missing timezone information Can I fix that using another value_template?

mighty ledge
#

is that your timezone?

#

or UTC

floral shuttle
#

{{as_datetime(value).isoformat()}} gives 2021-11-04T20:04:26+00:00 and {{as_datetime(value)|as_local}} gives 2021-11-04 21:04:26+01:00 but missing the T

#
  • 1
mighty ledge
#

yes, so decide which one you want.

#

the isoformat adds the T

#

remove the isoformat from the first or add it to the second

#

however the new changes will want it to be a DT object, so i'd remove the isoformat

floral shuttle
#

{{as_datetime(value)}} then? resulting in 2021-11-04 20:04:26+00:00. but then its an hour off, so back to {{as_datetime(value)|as_local}} I guess.

#

dont get it though, because some short time ago, we had to assert all date times had the T, and forced us to use the .isoformat exactly for that? And now we are leaving that again?

mighty ledge
#

if it's your tz, then | as_datetime. If it's not, then | as_datetime | as_local

mighty ledge
#

You're in dev, remmeber? You're getting the changes before they go public

floral shuttle
#

yes I understand that its the same change. thing is I am not sure what the sensor provides. Utc or local..

mighty ledge
#

well, figure it out then apply the correct template

floral shuttle
#

most importantly, need to add the |as_datetime and worry about it being an hour off later 😉

floral shuttle
#

besides the dst sensor theres 1 more, on a sensor solar_noon_today. This is a template {{state_attr('sensor.astral_solar_noon','today')}} built on state sensor.astral_solar_noon=2021-11-24T12:28:40+01:00; yesterday=2021-11-23T12:28:22+01:00, today=2021-11-24T12:28:40+01:00, tomorrow=2021-11-25T12:28:57+01:00, device_class=timestamp, icon=mdi:weather-sunny, friendly_name=Astral Solar Noon, isnt that correct already?

#

returns: 2021-11-24 12:28:40+01:00

mighty ledge
#

if it's a string, no, if it's a datetime yes

floral shuttle
#

got it. did you already find a moment to check the DST sensor? oddly enough it does show a state (unlike the others that simply were unavailable completely) but it does throw the error

mighty ledge
#

all you have to do is remove the .isoformat, but no I did not fix it

valid mist
#

hi guys quick query please

#

i am trying to add a device tracker based on wifi name like so

  • platform: template
    sensors:
    alans_pixel_4_home:
    value_template: >-
    {% if states('sensor.alan_s_pixel_4_wifi_connection') == "wifi_name1" %}
    home
    {% else %}
    not_home
    {% endif %}
    friendly_name: 'Alans Pixel 4 Home (SSID = wifi_name1)'
    this is an example file but i have 4 wifi names in the house. Is it possible to enter 4 names?
    If so what is the correct format?
mighty ledge
valid mist
floral shuttle
#

but it still throws the error....

mighty ledge
#

xyz in ['a','b','c']

#

read it phonetically and it'll make sense.

valid mist
#

@mighty ledge so does this look correct?

  • platform: template
    sensors:
    alans_pixel_4_home:
    value_template: >-
    {% if states('sensor.alan_s_pixel_4_wifi_connection') [ 'wifi_name1', 'wifi_name2', 'wifi_name3', 'wifi_name4' ]" %}
    home
    {% else %}
    not_home
    {% endif %}
    friendly_name: 'Alans Pixel 4 Home (SSID [ 'wifi_name1', 'wifi_name2', 'wifi_name3', 'wifi_name4' ])'
mighty ledge
#

no, see previous response

#

you also have random quote it in

#

use the template editor to check things

mighty ledge
valid mist
#

I am using studio code

#
    sensors:
      alans_pixel_4_home:
        value_template: >-
          {% if states('sensor.alan_s_pixel_4_wifi_connection') [ 'wifi_name1', 'wifi_name2',  'wifi_name3', 'wifi_name4' ] %}
            home
          {% else %}
            not_home
          {% endif %}
        friendly_name: 'Alans Pixel 4 Home (SSID [ 'wifi_name1', 'wifi_name2', 'wifi_name3', 'wifi_name4' ])'```
#

it pastes crap in here

mighty ledge
#

You’re still missing what I told you to put in

mighty ledge
valid mist
#

yep i was typing the correct details in

valid mist
mighty ledge
#

no

#

but i'm guessing you still haven't added in in it

lethal spoke
#

Done. The improvement is noticable: there is much less delay as compared to storing/calling a Home Assistant scene, and there is way less Zigbee traffic flooding (simple on/off messages from a Home Assistant group are smaller than also needlesly sending the brightness/color temperature/transition time from a Home Assistant scene). I've made the group assignment dynamic (based on the state, domain, area, and an exclusion group). You can find the result here https://pastebin.com/QB7g4Xvb

valid mist
#

i have finished it

mighty ledge
mighty ledge
valid mist
# mighty ledge this

Sorry i have no idea what you mean i have tested in template and added the correct details.

#
    sensors:
      dale_iphone_home:
        value_template: >-
          {% if states('sensor.dales_iphone_pro_12_max_ssid') [ 'HMCustoms', 'HMCustoms_5GHZ', 'HM_Immigration_2.4GHZ', 'HM_Immigration_5GHZ' ] %}
            home
          {% else %}
            not_home
          {% endif %}
        friendly_name: 'Dale iPhone Home (SSID [ 'HMCustoms', 'HMCustoms_5GHZ', 'HM_Immigration_2.4GHZ', 'HM_Immigration_5GHZ' ])'```
mighty ledge
#

you're litterally missing the word in

#

i said this:

#
xyz in ['a','b','c']
#

you have

#
xyz ['a','b','c']
valid mist
#

ok

mighty ledge
#

not sure how else to spelli t out to you.

valid mist
#

🙂

#
    sensors:
      dale_iphone_home:
        value_template: >-
          {% if states('sensor.dales_iphone_pro_12_max_ssid') in [ 'HMCustoms', 'HMCustoms_5GHZ', 'HM_Immigration_2.4GHZ', 'HM_Immigration_5GHZ' ] %}
            home
          {% else %}
            not_home
          {% endif %}
        friendly_name: 'Dale iPhone Home (SSID [ 'HMCustoms', 'HMCustoms_5GHZ', 'HM_Immigration_2.4GHZ', 'HM_Immigration_5GHZ' ])'```
#

do i need it after friendly name as well?

mighty ledge
#

the freindly name isn't a template

valid mist
#

so does it look ok now 🙂

mighty ledge
#

so do whatever you want with it

floral shuttle
obsidian lintel
#

Hello, I need some help, is there a way I can pull string from a state attribute and use regex to filter out data which I need?

This will be the attribute (from google calendar):

Customer Name: John Doe
Venue: John Doe Place
Reason: Visitation

and this is the regex for it: /\bCustomer Name:\s+\K.*/gmi

How do I properly do this?

inner mesa
obsidian lintel
#

Hi @inner mesa.

Firstly, thank you for the prompt reply.

I see that the docs are really vague and there are not much examples, I have searched online but I am still quite unsure about what each function does exactly. Which one should i be using out of the 5 functions given?

inner mesa
#

You read the descriptions?

obsidian lintel
#

{{ state_attr('calendar.client_showroom_event', 'description') | regex_findall_index('\bCustomer Name:\s+\K.*') }}

#

Im assuming like this?

inner mesa
#

are you looking for the index or the data?

obsidian lintel
#

data

inner mesa
#

then you picked the "index" one

obsidian lintel
#

Thank you so much for clarifying

#

and helping me check 😄

inner mesa
#

Filter value | regex_findall(find='', ignorecase=False) will find all regex matches of the find expression in value and return the array of matches.

valid mist
obsidian lintel
#

{{ state_attr('calendar.client_showroom_event', 'description') | regex_findall('\bCustomer Name:\s+\K.*') }}

inner mesa
#

try it in devtools -> Templates

obsidian lintel
#

My regex value already searches for the data within :

For example, in Customer Name: John Doe, I will get John Doe

Am I creating redundancy? Is the findall_index able to get John Doe for me?

#

I will try it out

mighty ledge
inner mesa
#

{{ state_attr('calendar.client_showroom_event', 'description')|regex_findall('.*Name: (.*)\n')|first }}

young jacinth
inner mesa
#

returns the first item in the list

#

clear enough?

obsidian lintel
#

Extremely concise

#

I love you, it works :D!!!

bright plaza
#

I'm having some problems with the rest platform and then value_templates where I occasionally get 0 values

#

This is the value template where I've already tried to catch undefined values: value_template: "{% if state_attr('sensor.testnumber', 'number') is defined %} {{ (state_attr('sensor.testnumber', 'number')| float / 10**15) | round(2) }} {% endif %}"

#

But I'm still getting an entry in the state table with state 0.0 occasionally

#

I don't know if it's what's coming back from the rest api (I can't go back in time to find the json result as far as I know) or if it's related to the operations I'm doing to the state causing the 0.0 value

inner mesa
#

you don't have an "else"

bright plaza
#

oh I need one?

#

I assumed with no else it would not do anything if it isn't defined

inner mesa
#

well, it won't have a value sometimes if you don't

bright plaza
#

hmm, just getting my head round that

#

so if it's defined it does my code, if it isn't defined, it's defaulting to some 0 value rather than doing nothing?

#

I kind of assumed that with no else there it wouldn't do anything but maybe that's my issue - it does do something

inner mesa
#

I believe so. Some platforms support an "availability" field that can indicate that there's no value, but not this one

bright plaza
#

so, what should I put in my else block? I don't want a state recorded in this case

#

I end up with graphs with huge spike downs to 0 which aren't valid

inner mesa
#

your best bet may be to make a template sensor with your REST sensor as input, and use the availability template there to indicate when there's no value

bright plaza
#

This is in a template sensor

#

I tried to look into availability templates a week or two ago when I first saw it mentioned but have to confess I'm still a bit confused how to use them

inner mesa
#

rest platform

#

they're straightforward - an expression that returns true or false based on whether it should return a value

bright plaza
#

so I have a platform rest section that gets the data. Then a template sensor that processes that into the right sort of number. The graphing is off the template sensor

inner mesa
#

ok, then use an availability template

bright plaza
#

So I somehow need to incorporate availability into the template sensor bit

inner mesa
#

yes. you already seem to know when you don't want to return a value

bright plaza
#

even that's a bit of a stab in the dark

#

because I don't know what's being returned when this randomly happens

inner mesa
#

look at the history of your REST sensor

bright plaza
#

yep

#

So I can define a minimum allowed value which should catch anything

#

I've just re-read the PR for availability templates and the docs on templates where it mentions availability but I'm still struggling to understand how to use it and feeling a bit dense

inner mesa
#

it's just what I said above

#

an expression that returns true when your value_template should be evaluated and return, or false if it shouldn't

#

it's exactly what you're asking for

bright plaza
#

So I need something like {% if state_attr('sensor.testnumber', 'number') > 10 %} return true {% else %} return false {% end if %} or something like that?

mighty ledge
#

just return the whole statement for cases like that

#

{{ state_attr('sensor.testnumber', 'number') > 10 }}

bright plaza
#

oh I see

#

but, forgive the stupid question. If I'm testing the value of state_attr hasn't that value already been written to the db ?

#

I guess it has for the rest sensor but not my template sensor

inner mesa
#

you're deriving other entities from it

bright plaza
#

and it's the template one I actually use

#

I've put that in - will see if after some time that seems to fix the problem

#

Do I still need the if undefined bit on the value_template as well?

#

would the availability template test not work to cover undefined?

inner mesa
#

not if you build that into the availability template

bright plaza
#

I've just got state_attr(...) > 2 in the availability template section now. Generally I'd expect a number around 10 so 2 gives some margin

#

but if it's undefined the state_attr>2 would fail wouldn't it, making it unavailable?

inner mesa
#

TypeError: '>' not supported between instances of 'NoneType' and 'int'

bright plaza
#

Oh think I see

#

so I need something like state_attr() > 2 AND state_attr not undefined

#

Not sure how I do that in templating. I'm still a bit of an amateur

inner mesa
#
{% set value = state_attr('input_number.away', 'doesnotexist') %}
{{ not value is none and value > 10 }
#

-> false

#
{% set value = state_attr('input_number.away', 'initial') %}
{{ not value is none and value > 10 }}
#

-> true

bright plaza
#

so I can do state_attr() > 2 and state_attr() not undefined ?

#

(and what's the difference between none and undefined?)

inner mesa
#

see my example

#

and feel free to test yourself in devtools -> Templates

bright plaza
#

will go test but not understanding that yet

inner mesa
#

understanding what?

#

I just tested until it worked

#

the error said "NoneType", so I used "none"

bright plaza
#

give me a sec to play

#

I get false for both

knotty lodge
#

I want to create a switch that's nothing more than a state flipper/indicator. Can I do that with just a template switch or do I have to create a binary sensor to "store" the on/off state?

inner mesa
#

that's an input_boolean

bright plaza
inner mesa
#

I have nothing to reply to you about

bright plaza
#

but I think I want {{ not state_attr('sensor.testnumber', 'number') is undefined and state_attr('sensor.testnumber', 'number') > 10 }}

inner mesa
#

that's not what I have

#

but if it works for you

#

I tested mine

bright plaza
#

so I cut and pasted your code above into the template editor and the second bit gives false for where you said gives true, so puzzled at that

inner mesa
#

if you don't have those entities, it will

bright plaza
#

ah stupid me thought it was something that would work as is :/

#

so I've removed all the if else endif bits and just got the template sensor being set from the state of the rest sensor. But added the availability template to hopefully return true only if the rest sensor state is not undefined and is > 2

#

hopefully that'll do what I need

#

Apologies for how slow I'm being. For some reason this bit of templating has been difficult for me to get my head around

#

I only get these issues with template sensors derived from rest platform sensors which get json data from an api and it's random and infrequent. So I can only assume something odd is happening with the result occasionally but I don't know what exactly because it isn't logged

knotty lodge
inner mesa
bright plaza
#

yeah, I have no idea either

#

it's hard to catch when you don't now what's wrong with it

#

it could be as simple as 0 values coming back from the rest api erroneously but at least my min value off 2 should stop that now

ancient swan
#

I've created a custom sensor to point to an attribute of another sensor. Check. There is another attribute, a temperature setpoint, that I want to create a template object for so that I can change the temp in my automation. What do I create this template as? Not a sensor--that's read-only.

#

I figured I'd have to go down this road since I can't get an automation to target a generic thermostat temperature. (Or maybe I'm doing that wrong.)

inner mesa
#

You need to use a service to change a setting

crude tartan
#

I am trying to convert this gree split heat cool unit from C to F as it only reports in C but this is showing status unaviable.```sensor:

  • name: "shedTemp"
    unit_of_measurement: '°F'
    state : >
    {{ ((float(states('climate.drumshed_heatcool', 'temperature')) * 9 / 5 ) + 32) | round(1) }}```
#

should it be "state_attr"?

ancient swan
floral shuttle
#

please help me once more with what I supposedshould be a regex template.trying to find all temperature sensors on my Hue bridge {{expand(integration_entities('Philips Hue 1')) |map(attribute='entity_id')|list}

slow vine
#

how can I use regex in an if statement in a template? I searched but It seems not possible.
The psuedo-code I want is like this:

{% for state in states.binary_sensor %}
  {%if state.entity_id <regex match> (.*_status$)|(.*status_\d\d*$) }}
    {{ state.entity_id }}
  {% endif %}
{% endfor %}```
Basically any binary_sensor that ends with `_sensor` optionally with `_`and any digits after. i.e. `garage_door_status` and `living_room_heater_status_11` etc...
slow vine
#

I saw that but I guess I used it wrong because it didn't work. I'll try again and post whats happening.

#

grrr. I had it right, with an extra ) and i just thought it was impossible. 😬

slow vine
#

I'm up to here:``` action:

  • service: input_select.set_options
    target:
    entity_id: input_select.esphome_devices
    data:
    options: >
    {{ states.binary_sensor | map(attribute='entity_id') | list | regex_findall('(.status$)|(.*status\d\d$)', ignorecase=True) }}
    {% set ns = namespace(all_entities="") %}
    {% for state in states.binary_sensor %}
    {% if state.entity_id|string is search('(.status$)|(.*status\d\d$)', ignorecase=True) %}
    {% set ns.all_entities = state.entity_id+", "+ns.all_entities %}
    {% endif %}
    {% endfor %}
    [{{ ns.all_entities }}]```
    Not sure why its not working. I get this error Error while executing automation automation.populate_esphome_devices: Invalid state encountered for entity ID: input_select.esphome_devices. State max length is 255 characters. I'm sure there is a better way to create this list but this is what I was able to come up with myself.
floral shuttle
silent vector
#

I'm trying to use a template sensor as a condition that If a different specific automation ran in the last 5 seconds it wouldn't run the automation.

I had this initially

"{{ ( as_timestamp(now()) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered')) |int(0) ) < 5 }}"

I saw the error about not having a default and I added

"{{ ( as_timestamp(now,0) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered')) |int(0) ) > 5 }}"

However I still get this erorr:

Template warning: 'as_timestamp' got invalid input '()' when rendering template '"{{ ( as_timestamp(()) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered')) |int(0) ) > 5 }}"' but no default was specified. Currently 'as_timestamp' will return 'None', however this template will fail to render in Home Assistant core 2022.1

I also don't even think the template sensor is working did I not set it up properly? It returns true or false but I wonder if the arrow is pointed in the wrong direction for what I want which is if automation.winter_daniels_thermostat ran more than 5 seconds ago then it should be true and It's a condition in an Automation to avoid another automation from running. That way if it's false then the Automation ran less than 5 seconds prior and it wouldn't run the other automation.

fossil venture
#

You missed the brackets to show that now() is a function. This "{{ ( as_timestamp(now(),0)... not this "{{ ( as_timestamp(now,0)...

silent vector
marble jackal
#

What is the result of {{ state_attr('automation.winter_daniels_thermostat', 'last_triggered') }} in devtools -> Templates

silent vector
#

Result type: string
2021-11-25 12:14:54.043455+00:00

marble jackal
#

Okay, so the attribute exists. I thought maybe that was the issue.. and does {{ as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered')) }} work as well?

silent vector
#

Result type: number
1637845500.0067

silent seal
#

That's a timestamp

silent vector
silent seal
#

For me, that works, I also tried it with {{ as_timestamp(state_attr('automation.anyone_arrives_home', 'last_triggered')) > as_timestamp(now() - timedelta(seconds=5)) }} and that works as well, though it doesn't have defaults as a fallback.

silent vector
#

I think it works the issue is that it will toss an error. Would your template require a default? And does the template mean if the automation ran more than 5 second ago it would be true?

silent seal
#

Mine means that if it ran more than 5 seconds ago it would return true, yes. I'm not a templates expert, just a developer (of very different things) who's happy poking at templates, so it's possible it could throw an error.

silent vector
#

I see. In 2 months I think it will reject the template unless I fix it. I might as well fix it now lol.

marble jackal
#

I tried {{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.eerste_verdieping_screens_naar_boven_bij_bui', 'last_triggered')) | int(0) ) > 5 }} and got no warnings..

#

It could be that the template is rendered before your automations are loaded, and that that causes the warning

#

Does the time of the warning match a reboot?

silent vector
#

I reloaded the template entities when I made the change. I just did another reload and so far it did not throw an error.

marble jackal
#

You could try {{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.eerste_verdieping_screens_naar_boven_bij_bui', 'last_triggered'),0) | int(0) ) > 5 }} but that would result in True if it is indeed the issue I suggested above.
You could put the whole thing in an if, or maybe use this {{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.eerste_verdieping_screens_naar_boven_bij_bui', 'last_triggered'),as_timestamp(now(),0)) | int(0) ) > 5 }}

#

This will result in False when state_attr('automation.eerste_verdieping_screens_naar_boven_bij_bui', 'last_triggered') is not a valid result to be used in as_timestamp

silent vector
#

The template works I just tested it and saw it switch to false. Here's the logs.

#

Template warning: 'as_timestamp' got invalid input 'None' when rendering template '{{ as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered')) }}' but no default was specified. Currently 'as_timestamp' will return 'None', however this template will fail to render in Home Assistant core 2022.1
Template warning: 'as_timestamp' got invalid input 'None' when rendering template '{{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered')) | float(0) > 5) }}' but no default was specified. Currently 'as_timestamp' will return 'None', however this template will fail to render in Home Assistant core 2022.1

marble jackal
#

Okay, the template I proposed will avoid these warnings (and errors after 2022.1)

#

The first warning confirms that the issue is caused by the template using the last_triggered attribute (which was the only option left anyway after you provided a default for the template using now())

#

And after you provide a default for both as_timestamp templates, there is no need for the | float(0) anymore

silent vector
#

I put this template in the developer tools: {{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered'),as_timestamp(now(),0)) | int(0) ) > 5 }} It's result type is boolean. Do i need the other template you showed then or this is good to put as a template sensor?

marble jackal
#

The result should be a boolean (either True or False) and also here you can remove the | int(0).
And I don't know what you want to do with this template, but you could use it for a template binary_sensor

silent vector
#

Don't I need int though? I need it because I care about the actual last time it was triggered I want to know if an automation was run in the last 5 seconds then this automation will not run.

marble jackal
#

Both timestamps are already numbers

inland stag
#

Hi everyone, is there a way to reference a value in JSON not by its position in the array, but by another key's value?
https://hastebin.com/xemigawuqe
value_json.dxsEntries[2].value works, but I would like to do something like this:
value_json.dxsEntries['dxsId'==33555202].value

marble jackal
#

With the | int(0) you will check for 6 seconds instead of 5 seconds, as 5.999999999999 | int(0) will result in 5 which is not > 5

#

and without the | int(0) 5.001 will be > 5

silent vector
#

It isn't important for the exact second I just don't want 2 automations to run simultaneously because of another. That's why I figured 5 seconds is good enough to keep them from interfering. It's a thermostat automation. If I don't use int how would it know what value I want?

marble jackal
#

both timestamps are numbers, so assuming as_timestamp(now()) equals 11.4 and as_timestamp(state_attr('automation.blabla', 'last_triggered')) equals 4.2 your template will do:
( 11.4 - 4.2 ) = 7.2 and then will check 7.2 > 5 which will result in the boolean True

#

There is no need to convert 7.2 to an integer

silent vector
#

How should I set it up without int? As in what would the template look like?

marble jackal
#

{{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered'),as_timestamp(now(),0)) ) > 5 }}

silent vector
#

Thank you I am going to test this and see if it throws an error still.

marble jackal
#

but if you want to run your other automation only when the 2nd automation is not running, you could also use a numeric_state condition:

  - condition: numeric_state
    entity_id: automation.winter_daniels_thermostat
    attribute: current
    below: 1
silent vector
#

What happens if it runs really quick? How long does 1 stay?

marble jackal
#

the attribute current will be 0 if it is not running, and 1 if it is running one time, it can run multiple times if you don't use mode: single

#

If you want to be sure some time is in between the two automations, you can also add - delay: 5 at the end, which will add a delay of 5 seconds (and will keep the automation running for that period)

silent vector
#

Sounds good thank you for the help. It worked and the latest error is just a repeat error. The template is completely different now from what the error is I am sure a restart will get rid of it.

buoyant pine
inland stag
#

I think I just found another solution

#

{{ (value_json.dxsEntries | selectattr('dxsId','eq',33556736) | list | first).value }}

buoyant pine
#

ah there ya go

#

i figured there was a better way lol

late island
#

heyho. I have this as a condition in an automation but its giving me false in the template developer tools of HA. What am I doing wrong?

        value_template: "{{ (state_attr('climate.comet_dect_1_schlafzimmer', 'preset_mode')) == comfort }}"```
inner mesa
#

You need to quote ‘comfort’

late island
#

All these little things.. Well gotta learn!

inner mesa
#

You also have an extra set of parens, but that’s not the problem

snow laurel
#

Hi all, Im trying to extract the number of days from a date string
with the template {{state_attr('sensor.grocy_chores', 'chores')[0]['last_tracked_time']}}
The original sensor reports: 2021-11-19T00:00:00+00:00

I want to know how many days its been since that date, so I wrote this template: {{ (now() - as_datetime(state_attr('sensor.grocy_chores', 'chores')[0]['last_tracked_time'])) }} which reports 6 days, 16:53:37.691303. I'd like to just get "6" and then I can make the unit "days". Should I just regex the first few numbers before the space? Is there a way to extract just the number with timestamp_custom?

inner mesa
#

{{ ((now().timestamp() - states.input_number.max_water_temp.last_changed.timestamp())/86400)|int }}

slow vine
#

Is there a filter to pass through an entity_id and get the owning devices device_id? i.e. sensor.living_room_temp | get_parent_id()

inner mesa
#

device_id(entity_id) returns the device ID for a given entity ID or device name. Can also be used as a filter.

snow laurel
#

Can I use timestamp with this format? state_attr('sensor.grocy_chores', 'chores')[0]['last_tracked_time']

inner mesa
#

if it results in a datetime, then you can do what I showed

#

It's a method on a datetime. You can probably also use |as_timestamp

#

or as_timestamp(xxx)

slow vine
#

What about getting the device name from device_id?

inner mesa
#

there's a section on this in the docs 🙂

#

I'm just researching it for you at this point

#

{{ device_attr(device_id('light.outside_back_porch_light'), 'name') }}

slow vine
#

I tried reading those pages, based on that i tried {{ state_attr('61dae1fb67a4148c6668277f3fbbd817', 'name') }} but it returns 'none'

#

ahh.

inner mesa
#

well, state_attr isn't querying the device attributes

slow vine
#

sometimes i want to bang my head!

#

I was on the right track just made a silly mistake. one that is obvious without knowing anything about templates etc... oh well...
Thanks again.

snow laurel
#

I want to shorten my code so that I dont have to keep writing the same entity each time.

Can I write:
{{ set name = "'sensor.grocy_chores', 'chores')[0]") }}

{{ state_attr(name + "['last_tracked_time']")}}
To extract just the last_tracked_time?

inner mesa
#

That first expression isn’t complete. You have to use a real expression there

#

You can’t just take a bunch of characters out of the second expression and put them in a variable. It needs to stand in its own

snow laurel
#

Ah okay. So then there's no way for me to do what I want to do right?

inner mesa
#

If you want to construct a string from a variable and some other stuff, fine.

#

But you have an extra set of quotes, a closing paren, and an array index in there

silent barnBOT
inner mesa
snow laurel
#

Apologies

#

Thought it would be short enough heh

mighty ledge
slow vine
#

I got it. Create an input_select with a list of device_names that have a light entity that is on. 🎉
Thanks @inner mesa for your time and help. I learned a lot of this confusing world of templates thanks to your patience and tutelage.

snow laurel
marble jackal
#

This template works fine:

{% set target_brightness = 150 %}
{{ 
  expand(states.light)  | rejectattr('attributes.brightness', 'eq', target_brightness)
                        | rejectattr('attributes.brightness', 'eq', undefined)
                        | map(attribute='entity_id') 
                        | list 

}}
``` But I would like to have some margin (eg 148 - 152 should be okay). But if I try `| rejectattr('attributes.brightness', 'gt', target_brightness - 2)` I get the error: `UndefinedError: 'mappingproxy object' has no attribute 'brightness'`
#

Oh never mind, it works if I keep the undefined check, and then do the filter on brightness afterwards

ruby pollen
#

Hi, I've a rainfall monitor, and for some reason, it now defaults to 0.3 at midnight. Also, whenever I reboot HA, it increases it by 0.3 incorrectly ...
https://hastebin.com/ebimeqewut

#

The sqlite data doesn't match either ....

#

So, what could be making it not be zero at midnight when there is no data referencing it until 10am and the first 'tip' wasn't until just gone 3pm?

#

Thanks

mighty ledge
slow vine
#

I am using expand to sort a list of entity_ids {{ expand(data.entities)|selectattr('entity_id')|map(attribute='entity_id')|list }} It works fine except I want to sort regardless of domain so light.bedroom should come after switch.attic I tried to research but everything I found the domain is part of the entity_id.
Any hints if there a way to do this?

ruby pollen
#

So, it sould be fine from tonight onwards

mighty ledge
#

Yeah it’s odd, they have to count the first value even if it crosses your configured time

#

Iirc someone complained it wasn’t a few years ago

ruby pollen
#

Definitely odd, but something I now know!

ruby pollen
#

Any idea why a reboot would cause it to increase. Read somewhere the change from unavailable might be the reason. Was hoping to have catered for that.

shadow root
#

ile "/usr/src/homeassistant/homeassistant/components/modbus/validators.py", line 236, in duplicate_modbus_validator
if hub[CONF_TYPE] == SERIAL:
KeyError: 'type'

#

this is the error in the log

#

modbus:

  • name: victron
    type: tcp
    host: 192.168.50.4 # use the IP address of your CCGX
    port: 502
    sensors:
    • name: "Battery Monitor State"
      scan_interval: 10
      slave: 245
      address: 1282
#

and this is part of my config.
The type is the same as in the example

inner mesa
shadow root
#

I am sorry, you are right

slow vine
inner mesa
#

You can sort on an attribute

#

attribute – When sorting objects or dicts, an attribute or key to sort by. Can use dot notation like "address.city". Can be a list of attributes like "age,name".

#

|sort(attribute=‘object_id’) should work

sudden citrus
#

can anyone tell me the difference between
value_template: {{ }}

  {{ }}```
and
```value_template: >-
  {{ }}```
mighty ledge
mighty ledge
mighty ledge
#

leading whitespace is spaces or carriage returns.

#

in almost all cases in home assistant configuration, the - is not needed with >- because templates by default remove leading and trailing whitespace.

sudden citrus
#

ah good to know, thanks 🙂

silent barnBOT
manic warren
#

Now maybe someone can help me with the challenge to survive the reboots:

When I initialize "binary_sensor.arut", I assign it certain attributes, e.g. last_time_home, mood. Currently I use a helper (input_datetime), that stores the data and survives the HA restarts. I cannot use "{{ state_attr('automation.set_last_time_home', 'last_triggered') }}, as I am using one automation with trigger_ids for all the people objects.

Question: is there a way, that I can assign the attribute to it's last value in database, so it survives the restarts

attribute_templates:
relationship: family
last_time_home: "{{states('input_datetime.last_time_at_home_arut')}}" ------------ so this should be last value for this attribute in database
mood: (should be the last value set)

This will allow to avoid creating a lot of helpers and store all the information in attributes that will survive the HA restarts.

Any help appreciated 🙂

silent barnBOT
manic warren
#

I trigger the service with a parameter 'who":
service: script.set_out_of_home_attribute
data:
who: arut

mighty ledge
# manic warren Now maybe someone can help me with the challenge to survive the reboots: When I...

No, that's not possible. If you want to survive restarts, the easiest way to store complex structures is to use MQTT and retain the messages. Otherwise you have to store the information in helper entities to survive restarts. You can use my setup to do that.
scripts: https://github.com/Petro31/home-assistant-config/blob/8264c25604e55a111cbe647062b173310f55a143/scripts/fake_mqtt_discovery.yaml
example startup: https://github.com/Petro31/home-assistant-config/blob/8264c25604e55a111cbe647062b173310f55a143/automation/doors.yaml#L1
example update states: https://github.com/Petro31/home-assistant-config/blob/8264c25604e55a111cbe647062b173310f55a143/automation/doors.yaml#L110

wispy lodge
#

can someone help me with this template?
I want "circle_power_casa" to show the status it has (above 0) with the aforementioned entity "power_casa"

silent barnBOT
wispy lodge
#

" if (variables.state | float === 0 {"

inner mesa
#

You’re confusing JavaScript, which you’re using in your card, with Jinja, which is used elsewhere and is the topic of this channel

wispy lodge
#

ok, sorry to be in the wrong place. But still, can you help me? I think it won't be difficult to solve, but my abilities are few

inner mesa
#

probably float(variables.state) === 0 {

wispy lodge
hollow canopy
#

hi! i want to convert an input_number that is a number of hours (can be decimal; i don't think i can use a datetime because i can have a duration greater than 24 hours and i want to express the duration in hours) in a HH:MM:SS format that i can input in a timer. i'm a bit lost as to how to implement that. i'll need to compute the number of hours, minutes and seconds from the float input_number, but i'm not sure how to do that within the realm of templates

#

are you able to help me, please? thank you!

inner mesa
#

it looks like you can just multiply the hours by 3600 and set the duration in seconds

#

{{ states('input_number.whatever')|float * 3600 }}

hollow canopy
#

mhhh, it says should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['duration'].

#

mh let me try anyway. ahhhhhhhhhhhhhhhhh states(...)

#

thank you for the pointer

inner mesa
hollow canopy
#

yep actually got the page opened already 🙂

inner mesa
#

surround it in quotes? don't use the UI?

hollow canopy
#

am i supposed to be able to just paste that template in place of the expected HH:MM:SS field? regardless of whether the resutl in seconds is accepted, this doesn't seem to do the trick

#

let me try to edit in yaml directly

#

i find it a bit confusing that some things can be edited via the UI and result in generated yaml (like automations), but some other things do NOT result in yaml (helpers)

inner mesa
#

no idea

hollow canopy
#

same when directly in yaml: Invalid config for [timer]: offset {{ states('input_number.fermentation_duration')|float * 3600 }} should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['timer']['fermentation']['duration']. Got "{{ states('input_number.fermentation_duration')|float * 3600 }}". (See /config/configuration.yaml, line 116).

#

so i guess the issue is that it doesn't accept seconds

#

so i'll need to prepare hours, minutes and hours, then output them as string?

#

hours = int(input_number.fermentation_duration) ; minutes = (input_number.fermentation_duration - hours) * 60 ; seconds = (minutes - int(minutes)) * 60 ; minutes = int(minutes) ; and somehow output this as a string: {{hours:minutes:seconds}}

#

(well, for the logic)

#

something like...

{
  "hours": states('input_number.fermentation_duration')|int,
  "minutes": (states('input_number.fermentation_duration')|float - hours) * 60,
  "seconds": (minutes - minutes|int) * 60
}
{{  hours:minutes|int:seconds|int }}

? except this is probably essentially wrong, but i'm a bit lost with this templating 😐

inner mesa
#

oh, you can only use a template in the data: block of a service call, not in the definition of the timer

#

A number works fine there, but it won't accept a template. Luckily, you can specify the duration in the timer.start service call

hollow canopy
#

mhhhh

#

i'm guessing you must be reading that in the documentation. where are you reading that, please? (i wanna know where i failed to read that myself :))

inner mesa
#

it says:

#

duration integer | time (optional, default: 0)
Initial duration in seconds or 00:00:00 when Home Assistant starts.

#

not "template"

#

and I know that you can always use templates in the data: block

hollow canopy
#

i see

#

alright, let me explore that way then

#

thank you!

#

nice, i think i got it to work. easier than i feared!

#

thank you! (well, still running a test right now)

#

veeeeeeeeeerrrrrry nice

#

thank you!!!

ebon yoke
#

i have an attribute that's currently a text string.. i want to convert this text string to a number.. there are five different strings which i want to give the numbers -2 to 2, so -2, -1, 0, 1 and 2

#

how can i do this in a template? and also, how can i trigger the update of this template every time the attribute changes?

inner mesa
#

the answer to the second part is to use a trigger in your template

#

for the first, I would use a dict

#
{% set map = {'foo1': -2, 'foo2': -1, 'foo3': 0, 'foo4': 1, 'foo5': 2} %}
{{ map['foo2'] }}
#

-> -1

ebon yoke
#

but how do i create a new template sensor for this?

inner mesa
#

yes, like that. and via the docs for a template sensor?

ebon yoke
#

i added that under sensor: and then - platform: template and then sensors:

#

but this confuses me

#

this seems to use the template integration..?

#

meaning:

template:
  - sensor:
#

but i have:

sensor:
  - platform: template
    sensors:
      template_name:
#

anyway.. my configuration barfed on the following:

sensor:
  - platform: template
    numeric_price_level:
      state: >
        {% set price_map = {'VERY_CHEAP': -2, 'CHEAP': -1, "NORMAL": 0, "EXPENSIVE": 1, "VERY_EXPENSIVE": 2} %}
        {{ price_map[state_attr('sensor.electricity_price', 'price_level')] }}
#

Invalid config for [sensor.template]: [state] is an invalid option for [sensor.template]. Check: sensor.template->sensors->numeric_price_level->state. (See ?, line ?).

#

ah, i see using sensor: is the old legacy format

inner mesa
#

there are two different ways to create a template sensor, and they're both documented there

#

you're mixing them up

ebon yoke
#

yeah, i managed to get it working now

past wigeon
#

I can from an index in a sensor, assign an alphanumerical value something like:

#

{{ ['-', 'Red', 'Orange', '-', 'Green', 'Blue', '-', 'White', 'User1', '-', 'Disco', '-', '-', 'Magenta', 'Cyan', 'Pattern', 'Rainbow', 'Ocean'][states.sensor.pool_status.attributes["lighting_zones"][0]["color"]|int] }}

#

How can I do the other way round? from a value in array, retrieve the index

#

{% set coloursDict = { '-': 0, 'Red' : 1, 'Orange': 2 , 'Yellow' : 3 , 'Green' : 4 , 'Blue' : 5, 'Purple' : 6 'White' : 7, 'User 1' : 8, 'User 2': 9, 'Disco': 10, 'Smooth': 11, 'Fade': 12, 'Magenta':13, 'Cyan':14, 'Pattern':15, 'Rainbow': 16, 'Ocean': 17 }
{{ coloursDict['Red'] }}

#

I think that will do

runic cipher
#

could use a little help, not sure if it exactly belongs here or not..

But I have a file, say it's called randomResponse.yaml, that has something like:

>-
  {{ [ "Yes", "Ok", "Aye" ] | random }}

I've included this in intent scripts with something like:

text: !include ../randomResponse.yaml

But now I want to do something a bit more complex... something like

text: >-
     !include ../randomResponse.yaml
     Some Generic Non Random Text Goes here
     This part is working, I just need the INCLUDE part

homeassistant.exceptions.TemplateError: TypeError: no loader for this environment specified

is the error i get when i use the jinja include syntax:

      {% include '../randomResponse.yaml' %}

I just can't figure out what to do

south dagger
#

Hello. Is this a bug that template sensors last_changed/last_updated are set on templates reloading? Was going to report, but not sure if this was not intentional.

mighty ledge
mighty ledge
manic onyx
#

hi everyone. I am trying to get cover state into another sensor. What am I doing wrong?
garage_status:
friendly_name: "Garage Door Status"
value_template: >-
{% if states.cover.mygarage == "open" %}
Open
{% elif is_state(cover.mygarage, "closed") %}
Closed
{% elif is_state(cover.mygarage, "opening" %}
Opening
{% elif is_state(cover.mygarage, "closing" %}
Closing
{% else %}
Unknown
{% endif %}

charred dagger
#

What's happening instead of what?

manic onyx
#

I just get the error

charred dagger
#

I'm guessing it's an error about cover.mygarage being undefined or something? It should be is_state("cover.mygarage", ... with quotes.

marble jackal
#

What are you trying to achieve anyway? The current state, but then with the first character in uppercase?

marble jackal
#

This will do that too:
{{ states("cover.mygarage")[0] | upper ~ states("cover.mygarage")[1:] }}

trail estuary
#

Is there a way to determine the max and min value of a temp sensor from a timerange? I would like to send a report of sorts, containing the max and min temp of the last month...

marble jackal
trail estuary
#

I didn't see how I can limit the range on that? How can I tell it to only look at data from the current month? I also see how I missed to include "current month" in my question.... 😊

#

History Stats (https://www.home-assistant.io/integrations/history_stats) has support for templating definitions of start and stop of the range like this:

start: '{{ now().replace(day=1).replace(hour=0).replace(minute=0).replace(second=0) }}'
end: '{{ now() }}'

but doesn't provide max/min....

inner mesa
#

I think you’d need to use an SQL sensor for that

trail estuary
#

OK. Is there a good space to ask for help with queries?

inner mesa
#

Not really. You can review the dev docs for the database schema, but SQL is well documented

trail estuary
#

The problem being I have no idea how to write a query... Well.... Thanks... 🙂

obsidian lintel
#

{% if is_state('light.lumi_lumi_light_aqcn02_66f8e802_level_light_color_on_off', 'on') %} -4px -4px 4px 0 rgba(255,255,255,.5),4px 4px 4px 0 rgba(0,0,0,.03); {% else %} -4px -4px 4px 0 rgba(50, 50, 50,.5),4px 4px 4px 0 rgba(0,0,0,.15); {% endif %}

#

How do I build it in a way where all the entities in the entities card will have lighting border when either one of them are turned on

silent barnBOT
inner mesa
obsidian lintel
#

awesome! Thanks @inner mesa

modest sparrow
#

I'd like to create a script for my alarm system. Whenever one of my listed entities is triggered while alarm in enabled, I would like to send a message containing the friendly names of sensors which were triggered in the last minute, searching all sensors with anyone of the following in the entity_id-name: tamper, contact, occupancy, motion. So it's a biggish project for me :-).

I guess my question is:

  1. How can I search for entity_id-names while looping through all sensors with {% for state in states.sensor | ? %}?
#

I hope to be able to work it out from there..

north locust
#

log messages , upcoming version requires defaults ... ?

mighty ledge
#

check the first pinned message

north locust
#

thnkx

granite tree
#

Goodevening everybody, I face a small issue with sensor templating. I have a wireless door sensor and I try to define the battery level attribute as a new sensor. So i've entered : " - platform: template
sensors:
door_battery_level:
friendly_name: "door battery level"
value_template: "{{ states.binary_sensor.sonoff_xxxxxxxx.attributes.battery_level }}" "

#

I get an error in the config check : - Integration error: templates - Integration 'templates' not found.
(latest version 2021.11.5)

#

I'm new with templates 😉

inner mesa
#

I’m guessing that you have templates: in your configuration.YAML (which should be template: with the new format) and you’re further confusing the legacy and new formats

granite tree
#

thanks, so i've placed "templates: !include templates.yaml" into my configuration.yaml, and into templates.yaml: "- sensor:

  • name: "door battery"
    unit_of_measurement: "V"
    state: "{{ states.binary_sensor.sonoff_1001429617.attributes.battery_level }}"
    "
#

but I still get " General Errors:
- Integration error: templates - Integration 'templates' not found." 😕

inner mesa
#

like I said...

#

I’m guessing that you have templates: in your configuration.YAML (which should be template: with the new format)

granite tree
#

indeed ... I feel stupid 😒

#

thanks, it's much much better 😉

austere relic
#

I'm using an actual example to set current timestamp to a datetime helper, and it does not save the time, just the date:

service: input_datetime.set_datetime target: entity_id: input_datetime.muffin_futter_timer_main data: timestamp: '{{ now().timestamp() }}'

result: has_date: true has_time: true editable: true year: 2021 month: 11 day: 29 hour: 0 minute: 0 second: 0

doc example: https://www.home-assistant.io/integrations/input_datetime/ (very last one)

mighty ledge
austere relic
mighty ledge
#

then you don't have has_time set to true

#

the code is very simple

#

it tries timestamp first and splits them up no matter what

#

date and time that is

#

then it checks if the item has date or time and populates it

austere relic
#

i do have has_time!

#

something seems broken

#

it's not a really hard example to follow either

mighty ledge
#

right, but something is wrong in your config and it doesn't have to do with what you've posted so far

austere relic
#

maybe I'm overseeing something, but I really think I don't

mighty ledge
#

are you using yaml or the helper UI?

austere relic
#

helper UI

mighty ledge
#

can you screenshot the helper?

inner mesa
#

worked fine for me

#
set_datetime:
  sequence:
    service: input_datetime.set_datetime
    data:
      entity_id: input_datetime.date_test
      timestamp: "{{ now().timestamp() }}"
#

I had it set up with only a date, changed it to both date&time, then set it with that

austere relic
mighty ledge
#

you have `timestamp: "{{ now() }}", I said:

then use datetime: "{{ now() }}"

#

timestamp is for timestamps

#

datetime is for datetimes

#

now() is a datetime

#

now().timestamp() is a timestamp

#

both should work, but you have to match it with the correct field. The example from the docs works for rob (and me).

#

what version are you on?

austere relic
#

up to date

mighty ledge
#

Then it should be working with what rob wrote or swapping timestamp: "{{ now().timestamp() }}" for datetime: "{{ now() }}"

#

or you could even do time: "{{ now().time() }}" and date: "{{ now().date() }}"

austere relic
#

I got it, it was actually the previous action (moving current helper data to an other) that killed the automation. The logs didn't show it until I restarted home assistant (probably because an integration has gone nuts with thousands of errors). And I though I'm going nuts 😄
Thanks for your help, sorry for the confusion.

ebon yoke
#

i have created a template sensor.. but i'm unable to use it in my automations

#

at least it doesn't trigger

#

i'm using the trigger type numeric state.. and i've checked if it's below 0

#

it's currently -2

buoyant pine
#

It needs to go from above 0 to below 0 to trigger

ebon yoke
#

but it went from -1 to -2

#

oh, ok, i think i know what you mean

#

how can i trigger on that, then?

buoyant pine
#

Trigger on what?

#

From -1 to -2?

ebon yoke
#

i want it to trigger whenever the sensor updates

buoyant pine
#

State trigger with only entity ID

#

(no to or from)

ebon yoke
#

so not numeric state?

buoyant pine
#

Nope

#

Might need to add a condition to prevent the automation from firing if a state attribute changes but not the state itself

ebon yoke
#

can i then use condition on the actions?

buoyant pine
#

"{{ trigger.to_state.state != trigger.from_state.state }}" is what I was talking about above

buoyant pine
ebon yoke
buoyant pine
#

Sure, but that won't do anything if it's exactly 0

ebon yoke
#

and it shouldn't

#

but as it's now it doesn't even react when it's -2

#

so i'm just wondering if there's something wrong with the template

#

if it's a string or something instead of a numeric value

buoyant pine
#

The state needs to change for it to trigger

ebon yoke
#

it did

#

it went from -1 to -2

buoyant pine
#

After updating that automation and reloading it?

ebon yoke
#

well, it seems to be working now.. i manually set the state and that triggered

buoyant pine
#

Unless you did that in the UI, then it'll reload itself

ebon yoke
#

i did that in the UI

bronze tide
#

good evening!

#

I want to get all my ESPHome devices with a status of 'unavailable' in HA in order to send a notification with the name of the device. I came up with the following template for testing. The problem is that despite a device gets listed the text '==> Message needs to be send' does not show up when I insert the code in the 'template' tab of the dev tools. What is it that I do not see? PS: the names of the sensors are like 'binary_sensor.l9_cam32_04_status' where the '9' and '04' might differ.

{%- set snd_msg = 0 -%}
{%- set e =  states.binary_sensor | selectattr("state", "in", ["unavailable", "unknown", "off"]) -%}
{%- for state in e -%}
{%- if state.entity_id.startswith("binary_sensor.l") -%}
{%- if state.entity_id.endswith("status") -%}
{%- set snd_msg = 0 %}- {{ state.entity_id }}
{%- endif -%}
{%- endif -%}
{%- endfor -%}
{%- if (snd_msg) -%}
===> Message needs to be send
{%- endif -%}
inner mesa
#

you need to use a namespace when modifying variables in a loop like that

#

random example:

#
            {% set ns=namespace(entities=[]) %}
            {% for i in states.switch if i.object_id.startswith('office') -%}
                {% set ns.entities = ns.entities + [i.entity_id] %}
            {%- endfor %}
            {{ ns.entities }}
quiet current
#

Hi, Is it someone that could help me to make a sensor to calculate the power (consumtion) kWh when an entity is "ON"? This is for a oven, I know the power when its "on". Not sure if this is the correct channel

floral shuttle
#

playing with things like {{expand(integration_entities('Browser Mod'))|selectattr('domain','eq','sensor') |map(attribute='entity_id')|list}} or even {{device_entities('324e8092823f3b08eb8bc9b576cc0a2e')}} I just can make the correct template connection.

#

in javascript we can use window.browser_mod.entity_id or even better, window.location.pathname, just to give you an idea what I am looking for

#

never thought of this, but guess we cant copy that js frontend info over to be used in Jinja backend somehow..?

silent seal
#

What is the end goal of this?

left badger
#

Do scenes support templates? I’m trying to use snapshot_entities with a template for states.light | select_attr(‘state’, ‘eq’, ‘on’) in order to snapshot the lights as they’re currently on, but it doesn’t seem to work. Is there a better way to accomplish this?

inner mesa
#

I assume you're using scene.create? It seems like it should, as long as you output a list. Your template syntax and functions are wrong, though

floral shuttle
hardy lava
#

Hi all 🙂 I am failing integration of a REST api.. is there someone who might can help 🙂 ?

#

Or is this the wrong channel?

keen oriole
#

how do I send a "list" as message body in a notification?
service: notify.mobile_app_tht_s20
data:
title: Zwave Failures
message: '{{ states.sensor.failed_zwave.state }}'
gives me an error: template value should be a string for dictionary value @ data['message']

keen oriole
#

Well.... figured it out... this will not work unless some sort of "message" is added in addition to the {{xxxxx}}

#

This works...believe it shoudl have worked without that text as well...: message: 'Failed Devices: {{ states.sensor.failed_zwave.state }}'

mighty ledge
#

which is why it wasn't working

obsidian lintel
#
entities:
  - switch.sonoff_s20_lamp
  - light.lumi_lumi_light_aqcn02_66f8e802_level_light_color_on_off
state_filter:
  - 'on'
card:
  type: markdown
  content: |
    The lights that are on are:
    {% for i in config.entities %}
      - {{ i.entity }}
    {%- endfor %}```
#

How do I make it such that I can pull out friendly name instead

mighty ledge
#

- {{ state_attr(i.entity, 'friendly_name') }}

#

is the entity a state object? If it comes from the config I would assume it's just the entity_id

inner mesa
#

oh, probably not. nevermidn

mighty ledge
#

🤷‍♂️

#

I'm guessing here

inner mesa
#

<deleted nonsense>

obsidian lintel
#

.name no work

#

Tried it xD

mighty ledge
#

don't use that card but it would make sense that it's the configuration

#

so it would work if you named each entity in the configuration of the card

#

but if it's just the entity_id, then you have to use state_attr

obsidian lintel
#

It works petro ur method

#

awesome

#

i did this at first

#
  • {{ state_attr({{i.entity}}, 'friendly_name') }}
#

LOL

inner mesa
#

templateception

mighty ledge
#

lol yep

#

every beginner/novice does it

#

at some point

obsidian lintel
#

I tried to big brain

#

Anyways

#

I got a new challenge

#

Might not be one for yall

silent barnBOT
obsidian lintel
#

U see the count

#

It does

#

1

1```
#

Instead

mighty ledge
#

yep

obsidian lintel
#

LOL

mighty ledge
#

jinja scope

obsidian lintel
#

Im guessing I got to make a sensor for it?

mighty ledge
#

no, use filters

obsidian lintel
#

May I have some demostration almighty petro?

mighty ledge
#

well, are you trying to put the number before the name?

#

oh wait, I see by your note

#

to count lights....

obsidian lintel
#

Yes petro

mighty ledge
#
{{ expand(config.entities | map(attribute='entity') | list) | selectattr('state','eq','on') | list | count }}
obsidian lintel
#

😅

mighty ledge
#

yep

#

config.entities | map(attribute='entity') | list makes a list of entity_ids

obsidian lintel
#

Where did you find that

mighty ledge
#

I made it

obsidian lintel
#

what does | actually do

#

Im still quite noob at jinja

mighty ledge
#

| is the filter applier

#

i dont' know the actual name of it

#

x | y means apply the y filter on x.

inner mesa
#

"pipe"

mighty ledge
#

yeah i know it's a pipe, but jinja has a name for it probably

obsidian lintel
#

Hey petro and rob

#

Thank you so much for your help

#

But i got more question xD

mighty ledge
#

so it is just pipe

mighty ledge
obsidian lintel
#

Let me think how I am going to ask it efficiently

obsidian lintel
#

Omg u can send gifs, you are a god

#

Anyways

#

{{ expand( domain | map(attribute='entity') | list) | selectattr('state','eq','on') | list | count }}

#

is there a way to do this?

#

So I wanna check all the lights that are on, all the switches that are on for example

mighty ledge
#

like all lights?

obsidian lintel
#

For every entity in my Home Assistant

#

Without the need to use a config.entities which uses a state-filter card

mighty ledge
#
{{ expand(states.light) | selectattr('state','eq','on') | list | count }}
obsidian lintel
#

How about filtering exactly 1 of my smart socket which controls a small table lamp, its in a switch domain. Is there anyway I can filter just that switch out?

#

together with all the light domain

mighty ledge
#

{{ expand(states.light, 'switch.xyz') | selectattr('state','eq','on') | list | count }}

inner mesa
#

I was going to suggest a regex, but that's better

obsidian lintel
#

Holy mother of all things Home Assistant

#

You are a living legend

mighty ledge
#

expand is the workhorse

#

it can do errything

obsidian lintel
#

Got it, gonna learn more about expand

#

Its so powerful

#

even Rob is mindblowned

#

Last question I promise petro

mighty ledge
#

Well you don't know it if you don't use it

obsidian lintel
#

eq

#

What does eq do?

mighty ledge
#

equals

#

you can also use '==' instead of 'eq', or 'equals'

#

not 100% sure about equals, but it sounds good

dreamy sinew
#

i tend to use "eq" because i use too many APIs 😛

mighty ledge
#

nope, equals doesn't work

obsidian lintel
#

Makes so much sense now

#

Thanks petro, Im reading up on expand

#

God like

mighty ledge
#

there's not much to read up on if you don't know python

#

the docs are lacking

#

you have to play around

obsidian lintel
#

I have python background, not too much as I do networks

dreamy sinew
#

expand() is HA specific so the HA docs are the only place you'll see any info on it

obsidian lintel
#

But thanks a lot

mighty ledge
#

but, you can mix and match states, states.domains, and entity_id's with commas and it should work with expand

inner mesa
#

I think the only issue with expand() is that can be slow and take a bunch of memory

dreamy sinew
#

or could go to the code in github. homeassistant/core/homeassistant/helpers/templates

obsidian lintel
#

I actually think that your example is powerful enough for me to do everything I want

mighty ledge
#

it's a generator so it's still quite fast

inner mesa
#

especially when used on states or a whole domain

#

doesn't it create a list?

dreamy sinew
#

nope, a genny

inner mesa
#

[<template TemplateState(<state switch.fr_table_lamp=off; friendly_name=FR Table Lamp @ 2021-11-30T07:54:31.218175-08:00>)>]

mighty ledge
#

if you use | list it'll be slower because it has to resolve the whole thing before it returns the results

#

where if you just keep it as a generator it'll only output what you as for as you ask for it

#

it's getting a bit deep but that's how generators work

dreamy sinew
#

huh, nope

inner mesa
#

it outputs a list for me

dreamy sinew
#
def expand(hass: HomeAssistant, *args: Any) -> Iterable[State]:
mighty ledge
#

well well then

#

so then it's just slow

#

haha

dreamy sinew
#
    return sorted(found.values(), key=lambda a: a.entity_id)
inner mesa
#

I remember because it was killing perf for someone on a Pi

mighty ledge
#

I could see it kill perf if you use states with it

#

or states.sensor

dreamy sinew
#

so values() should be a DictValues but i think sorted() turns it into a list

mighty ledge
#

yah | sort turns everything into a list in jinja

#

same with unique... i think

#

map, select, reject, selectattr, rejectattr are generators for sure

dreamy sinew
#

iirc DictValues() is a generator

obsidian lintel
#

{{ expand(states.light, 'switch.xyz') | selectattr('state','eq','on') | list | friendly_name }}

mighty ledge
#

nope

obsidian lintel
#

How do I list the friendly name for individual devices

#

xD

#

value = ?

mighty ledge
#
{{ expand(states.light, 'switch.xyz') | selectattr('state','eq','on') | map(attribute='name') | list }}
dreamy sinew
#

selectattr(...)|map(attribute='name')|list

#

oh, one of us is right

#

probably petro

mighty ledge
#

where's name on the state object?

#

under state or just name?

dreamy sinew
#

petro is right

mighty ledge
#

||it's just name||

#

I've been doing alot of HA work recently on my prod, so it's all fresh and memorized for now

obsidian lintel
#

petro

dreamy sinew
#

yeah i stepped back for a bit so i'm a tad rusty

obsidian lintel
#

its in a list

dreamy sinew
#

do you want them all as a string?

#

|join(', ')

#

use that instead of |list

obsidian lintel
#

Lemme try 😄

#

What if I want them

#

in a literally "list" format

mighty ledge
#

|join('\n - ')

obsidian lintel
#

Legendary

dreamy sinew
#

but you shouldn't need to do that

inner mesa
#

you usually don't need to do that, though

#

I tested it a few days ago

mighty ledge
#

he's in a markdown card

dreamy sinew
#

ah

obsidian lintel
#

And how would I go about filtering out a single entity which I dont want

#

it is my browser_mod light

inner mesa
#

rejectattr()

#

something like xxx|rejectattr('entity_id', 'eq', 'switch.something')|yyyy

obsidian lintel
#

- {{ expand(states.light, 'switch.sonoff_s20_lamp') | selectattr('state','eq','on') | rejectattr('name' 'eq' '00fb7000 90d1fd56' ) | map(attribute='name') | join('\n - ') }}

#

ah

#

I cant use the nam

#

name

inner mesa
#

you can

#

depends on what you want

obsidian lintel
#

I did that but it didnt reject it

#

Oh

#

my commas

#

Nope it still is showing

#

Oh damn it works now

#

😄

#

Legendary

#

This has been an extremely educational experience @inner mesa @mighty ledge @dreamy sinew

#

My outmost thanks to the 3 of you

#

Ive met all my agendas

inner mesa
#

you can add more with rejectattr('name', 'in', ['00fb7000 90d1fd56', 'xxx', 'yyy'] )

obsidian lintel
#

I see

#

expand works in an if statement right

#

so if count value is 0, it will just print a different line instead of

The number of ligths that are on now are:
0

and

The lights that are on are:

dreamy sinew
#

hah the edge cases are brutal

mighty ledge
#

lol thats great

#

not much you can do without getting complicated

obsidian lintel
#

Now I can finally add it into my UI

inner mesa
#

I think default() can be used for that. I posted an example in the last week or so

mighty ledge
#

before the join?

#

probably

#

with a | default(['None'])

#

and it'll have a listed None item

dreamy sinew
#

nope

#

doesn't work

mighty ledge
#

🤷‍♂️

inner mesa
#

that's what I was thinking of, but doesn't quite fit the issue here

dreamy sinew
#

here's my test that worked

inner mesa
#

it's the "True" part

dreamy sinew
#
{{ things|join('\n - ') if things else "Nothing to see here" }}```
obsidian lintel
#

Thanks for introducing expand, there wasn't much details on the template docs

inner mesa
#

or maybe it does. the point is that default('xxxx', True) will output xxxx if the input is an empty list

dreamy sinew
#

all my lights are off so it was an easy test

mighty ledge
#

yah that's what I was trying to avoid

#

ooo

#

this also works

dreamy sinew
#

ah learned something new

mighty ledge
#
{{ things|join('\n - ') or "Nothing to see here" }}
dreamy sinew
#

{{ states.light|selectattr('state', 'eq', 'on')|map(attribute='name')|join('\n - ')|default('Nothing to see here', True) }}

#

have to dump it to a list because a genny is truthy

mighty ledge
#

whats the ,True

#

what's that arg

inner mesa
mighty ledge
#

That's what I wish was in HA

dreamy sinew
#

i think its a test

mighty ledge
#

intellisense

dreamy sinew
#

slight tweak to remove casting to list

obsidian lintel
#

More questions

#

This is an add on for the browser_mod

#

So the issue is, well if I'm on my laptop versus my mobile device, the name for the browser_mod is different. How do I remove it entirely regardless of the device I use

obsidian lintel
#

But my mobile device is

#

a801 blah blah blah

#

Is there a way I can totally remove browser_mod light entities

inner mesa
#

Not just because they’re provided by the same integration. If there’s an attribute, yes. Or you can use a regex

obsidian lintel
#

Any Non Regex method?

#

There an attribute Type: browser_mod

#

Oh hmmm I'm gonna test something out

#

I guess instead of doing name eq deviceid

#

I can do type eq browser_mod?

inner mesa
#

Then that. rejectattr('attributes.Type', , 'eq', 'browser_mod')

obsidian lintel
#

I don't need eq

#

Oh yeah

#

I do

#

U edited before I asked hahaha

#

It doesn't work

dreamy sinew
#

you have to do the reject before the map()

inner mesa
#

And make sure that the attribute is really called 'Type' with the capital T

obsidian lintel
#
    selectattr('state','eq','on') | rejectattr('attributes.Type','eq','browser_mod'
    )
    | map(attribute='name') | join('\n - ') }}```
#

Nothing

#

Yeap aint working

obsidian lintel
inner mesa
#

"Type" would be unconventional

obsidian lintel
#

What would be better

inner mesa
#

whatever it actually is

#

no need to guess

obsidian lintel
#

well its a light entity but

#

its from browser_mod

inner mesa
#

does it have an attribute called "Type"?

obsidian lintel
#

Yup

#

Type: browser_mod

#

dude xD

mighty ledge
#

i usually make an attribute called source if I want that info

obsidian lintel
#

BRUH

#

Its in lower caps

#

it aint attributes.Type

inner mesa
#

sigh

obsidian lintel
#

its type

inner mesa
#

like I said

#

twice

obsidian lintel
#

XD

#

My bad, my auto caps was on

#

I didnt realised I sent Type

#

Once again @inner mesa Thank you so much for helping 😄

#

Thank you so much, this is the result 😄

#

Yall are freaking awesome

tired sandal
#

Hey folks.

#

Trying to use a template to respond to a temperature change from a thermostat.

#

According to the docs: The template variable this is also available when evaluating any trigger_variables declared in the configuration.

#

I've tried this.id, this.state.id, this.to_state.id, state.id, to_state.id and they all raise errors about invalid keys

#

Oh, I've also tried state('to_state.id)

#

what am I doing wrong?

mighty ledge
#

trigger variables are limited

#

to only jinja

#

no extras from HA

tired sandal
#

ok?

inner mesa
#

I also found that this. wasn't needed to access trigger_variables

#

but those are different from variables defined for the automation trigger

mighty ledge
#

that means you can't use them @tired sandal

tired sandal
#

@mighty ledge yeah, I got that.....

mighty ledge
#

you can only use built in jinja functionality

tired sandal
#

So, the thermostat (at least mine anyway) has a temperature attribute - i.e: climate.downstairs_thermostat.temperature. When that changes, I want to do something and I'm trying to figure out how to use that value in my action.

#

according to the docs, things like trigger.event should be available, if I'm understanding this correctly.

mighty ledge
#

make a state trigger and use the trigger passed through in your action, you don't need trigger variables

#

trigger variables have a very very very small niche use case, for MQTT topics pretty much

tired sandal
#

I'm not sure what you mean

#

I have a state trigger.

#
  trigger:
    - platform: state
      entity_id:
        - climate.upstairs_thermostat
        - climate.downstairs_thermostat
      attribute: temperature
mighty ledge
#

ok, that's a state trigger

tired sandal
#

yep

mighty ledge
#

to access that information, you'd use trigger.xyz

tired sandal
mighty ledge
#

yes

tired sandal
#

Dammit, you beat me to it.

arctic sorrel
#
{{ trigger.to_state.attributes.temperature }}
mighty ledge
#

yep

tired sandal
#

Oh, right. I think I was missing attributes

arctic sorrel
#

You wanted to click through to the state object page

tired sandal
#

I did.

arctic sorrel
#

And look at the entity in devtools -> States

mighty ledge
#

it also shows you everything in the traces

tired sandal
#

Also, validating the config throws an error for that.

arctic sorrel
#

Depends on what you did

tired sandal
#
Error loading /config/configuration.yaml: invalid key: "OrderedDict([('trigger.to_state.attributes.temperature', None)])"
in "/config/./config/automations.yaml", line 41, column 0
mighty ledge
#

you're probaly not useing quotes around your template

arctic sorrel
mighty ledge
#

or the field you're putting it in doesn't allow templates

tired sandal
#

Oh wait, you have to quote templates?

mighty ledge
#

single line templates require quotes

inner mesa
#

some reviewing of the templating page is in order

tired sandal
#

Ah

#

@inner mesa clearly.

inner mesa
#

there are big warning boxes and such for this stuff

tired sandal
#

Yep. I quoted my template, and it's happy now.

inner mesa
#

that one is #1 on the list of things to do

arctic sorrel
#

On the up side, the command line config check will tell you every time you get it badly wrong

tired sandal
arctic sorrel
#

Linked from the page you're on

tired sandal
#

Aha!

arctic sorrel
#

There are other links too

inner mesa
#

yeah, that page

mighty ledge
#

automation templating only covers the trigger objects that are passed through

tired sandal
#

Ah right.

mighty ledge
#

FYI, don't use the phrase trigger variables

arctic sorrel
#

Home Assistant will involve a lot of reading 😉

mighty ledge
#

cause it has it's own separate meaning

tired sandal
#

Ah right

inner mesa
#

"Important Template rules"

tired sandal
#

I think I looked at the examples that used multi-line templates, saw they weren't quoted and figured you didn't need them.

#

I guess you do for single line

mighty ledge
#

single line -> yes, multiline -> no

tired sandal
#

yeah

mighty ledge
#

those are part of yaml btw, not specific to templates

tired sandal
#

Ah. My yaml is a little rusty.

#

I try to avoid using it where possible.

mighty ledge
tired sandal
#

thanks i will

charred dagger
#

But what about card-mod where there's css in jinja in css in yaml?

#

Or auto-entities where there's json/yaml in jinja?

inner mesa
#

or custom button card, which has two completely different kinds of templates

#

and neither has any Jinja at all

mighty ledge
#

Nevermind, I’m an idiot

silver talon
#

hello there, how to make a template trigger, when trigger an entity specific attribute change (any to any)?

#

{{ is_state_attr('climate.tado_smart_thermostat', 'hvac_action', '????')}}

inner mesa
#

you don't need a template trigger for that, just a state trigger with an attribute

young jacinth
#

hi

#
{% set abfall = "in 7 Tagen: Restmüll &  Bioabfall" %}
{{ abfall|select('Restmüll','Wertstoff','Papier','Bioabfall') }}
#

i want to check abfall for the list and only print the matching items

#

i dont know if iam on the right way here....

charred dagger
#

Not too far off.

#

The select filter takes a list as input and lets through the items which passes a Test. The Test is the first argument of select(), and the other arguments are passed to the test together with each item in the list.

#

So first of all, you want to split abfall into a list of words - abfall.split().

#

I could tell you exactly how, or do you want to try it yourself?

#

In the end you'll get a generator object that you can turn back into a | list with a different filter.

#

Here's the way: || {{ abfall.split()|select("in", ['Restmüll','Wertstoff','Papier','Bioabfall']) | list }} ||

young jacinth
#

ouch, should have read the defintion of select

#

thanks alot!

trim leaf
#

Is it possible to create an array of entities that I can parse thru in a template?

#

feel like I am missing something obvious

charred dagger
#

{{ states }} is an array of entities.

#

Pretty much

trim leaf
#

right, but how do I set my own within the template?

#

not clear what that syntax is

charred dagger
#

I don't think I quite understand what you want to do.

trim leaf
#

I want to iterate thru a loop of specific entities I set

inner mesa
#

what do you want to do with them?

trim leaf
#

I have multiple temp sensors and corresponding input booleans indicating if we should honor that temp (if the room is occupied).

I want to iterate thru each of the sensors, check if the room is occupied, and if it is, use that temperature

#

I was trying to avoid a bunch of if/then logic, and do it all in a loop

#

Also, the input boolean should be set to on for at least 10 minutes before honoring the temp

inner mesa
#

first, I would set the input_boolean to on when it should count, and not leave that decision until later

trim leaf
#

okay thats fair, then I would iterate thru the input booleans instead, that works too

inner mesa
#

something like:

#
{% set temps = ['test', 'test2'] %}
{% set bools = ['test1', 'test2'] %}

{% set all_temps = states.input_number|selectattr('object_id', 'in', temps)|map(attribute="state")|list %}
{% set temp_bool = states.input_boolean|selectattr('object_id', 'in', bools)|map(attribute="state")|list %}
{% set ns = namespace(temps=[]) %}
{% for temp in temp_bool %}
  {% if temp == 'on' %}
    {% set ns.temps = ns.temps + [all_temps[loop.index-1]] %}
  {% endif %}
{% endfor %}

{{ ns.temps }}
#

with the appropriate changes for your entities, it will output a list of states of entities in the temps list whose corresponding entities in the bools list are 'on'

#

@trim leaf

trim leaf
#

Thanks @inner mesa few new concepts to me in that snippet. Let me play with it. Thanks!

trim leaf
#

@inner mesa could you explain what you are doing when you set all_temps or temp_bool?

I was trying to understand the filter(s) you used here and i just get back an empty list if I drop this into dev tools

{% set bools = ['input_boolean.living_room_occupied', 'input_boolean.master_bedroom_occupied'] %}
{{ states.input_boolean|selectattr('object_id', 'in', bools)|map(attribute="state")|list }}