#templates-archived
1 messages · Page 141 of 1
You get one sensor update per day?
And look at the total attribute?
It shouldn’t be complicated
no it constantly updates
it's cumulative rainfall for the past day, which resets at midnight
Well, it’s going to add up all the values in the sample range
it might be easier to do this at the weewx end and just have it pass through the 72 hour cumulative value
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.
Just like in the docs: https://www.home-assistant.io/docs/scripts/#wait-template
Hi guys
which is the right syntax to create a yaml dictionary template?
I saw it somewhere but I can't remember
YAML and jinja can both use JSON formatting. Is that what you mean?
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
Yeah, you should turn that into a dict
First example here: https://www.w3resource.com/JSON/structures.php
thanks!
It’s a set of key: value pairs, and then you can index with dictname[key] to get the value
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?
If the name you want is always the part after the dot, then you just need to do state().split(‘.’)[1]
{"Cuatro HD": 10}
is not always that... that's the problem
Yes, you need to quite the strings as in that example at the link
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 '}'
Remove the {{}}
now that you say that, it was really silly to put {{}} in there
Or a list structure 🙂
thanks again
Is there a way to populate an input_select using a template? i.e. a dropdown list of all lights that are on etc...
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
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 }}```
you didn't quote your template
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
I'm working on that now. 🙂 thanks.
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
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...
it seems like Integration is not a device attribute:{{ device_attr('dda0719e582d04a7b8d8e4ef5dccf2c7', 'manufacturer') }} returns the manufacturer but {{ device_attr('dda0719e582d04a7b8d8e4ef5dccf2c7', 'integration') }} returns 'none' 😦
There’s no easy way to do that without adding an attribute manually or using a name pattern
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?
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.
it's however the integration fills out the device_info dict
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.
for integrations that do the right thing, this gets it:
{{ (device_attr('dd71fc3a10e4469198d9101ce0c18d05', 'identifiers')|first)[0] }}
bordering a crosspost on the auto-entities repo, I am in need of some serious templating magic. please have a look at https://github.com/thomasloven/lovelace-auto-entities/issues/232 Ive tried all known techniques to me..
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?
{{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
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
{{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?
right, this is why i asked
if it's your tz, then | as_datetime. If it's not, then | as_datetime | as_local
This is the change to datetimes in states that you're getting that other warning about
You're in dev, remmeber? You're getting the changes before they go public
yes I understand that its the same change. thing is I am not sure what the sensor provides. Utc or local..
well, figure it out then apply the correct template
most importantly, need to add the |as_datetime and worry about it being an hour off later 😉
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
if it's a string, no, if it's a datetime yes
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
all you have to do is remove the .isoformat, but no I did not fix it
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?
in [ 'name1', 'name2', … etc ]
So is it square brackets after == [ 'name1', 'name2', … etc ]?
thats exactly what I had already done:``` {{([ns.spring,ns.fall]|min)}}
.isoformat()```
but it still throws the error....
no, in replaces ==
xyz in ['a','b','c']
read it phonetically and it'll make sense.
@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' ])'
no, see previous response
you also have random quote it in
use the template editor to check things
that doesn't look like the new versioin
template editior ???
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
Open your home assistant and use the template editor to test out templates
You’re still missing what I told you to put in
can you see the link?
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
i have finished it
Yes, and exactly like I said above about 4 3 times now.....
this
this
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' ])'```
you're litterally missing the word in
i said this:
xyz in ['a','b','c']
you have
xyz ['a','b','c']
ok
not sure how else to spelli t out to you.
🙂
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?
the freindly name isn't a template
so does it look ok now 🙂
so do whatever you want with it
Really? Wait, let me check and get back
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?
Take a look at this: https://www.home-assistant.io/docs/configuration/templating/#regular-expressions
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?
You read the descriptions?
{{ state_attr('calendar.client_showroom_event', 'description') | regex_findall_index('\bCustomer Name:\s+\K.*') }}
Im assuming like this?
are you looking for the index or the data?
data
then you picked the "index" one
Filter value | regex_findall(find='', ignorecase=False) will find all regex matches of the find expression in value and return the array of matches.
Thank you for your help
{{ state_attr('calendar.client_showroom_event', 'description') | regex_findall('\bCustomer Name:\s+\K.*') }}
try it in
-> Templates
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
np
I would just do this:
{{ state_attr('calendar.client_showroom_event', 'description')|regex_findall('.*Name: (.*)\n')|first }}
hi, i got a sensor.abfall that has changing attributes
https://imgur.com/a/6PZVLfR
how can i print the second attribute?
What does |first do?
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
you don't have an "else"
well, it won't have a value sometimes if you don't
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
I believe so. Some platforms support an "availability" field that can indicate that there's no value, but not this one
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
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
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
rest platform
they're straightforward - an expression that returns true or false based on whether it should return a value
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
ok, then use an availability template
So I somehow need to incorporate availability into the template sensor bit
yes. you already seem to know when you don't want to return a value
even that's a bit of a stab in the dark
because I don't know what's being returned when this randomly happens
look at the history of your REST sensor
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
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
So I need something like {% if state_attr('sensor.testnumber', 'number') > 10 %} return true {% else %} return false {% end if %} or something like that?
just return the whole statement for cases like that
{{ state_attr('sensor.testnumber', 'number') > 10 }}
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
you're deriving other entities from it
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?
not if you build that into the availability template
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?
TypeError: '>' not supported between instances of 'NoneType' and 'int'
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
{% 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
so I can do state_attr() > 2 and state_attr() not undefined ?
(and what's the difference between none and undefined?)
will go test but not understanding that yet
understanding what?
I just tested until it worked
the error said "NoneType", so I used "none"
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?
that's an input_boolean
not sure if that's in reply to Neo or me
I have nothing to reply to you about
but I think I want {{ not state_attr('sensor.testnumber', 'number') is undefined and state_attr('sensor.testnumber', 'number') > 10 }}
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
if you don't have those entities, it will
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
Thanks! I think that put me in the right direction....
I still doubt that ‘undefined’ is what you want, but 🤷♂️
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
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.)
You need to use a service to change a setting
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"?
Ah.
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}
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...
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. 😬
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 errorError 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.
like this outcome, but then without the for loop...{% for s in expand(integration_entities('Philips Hue 1')) %} {% if 'temperature' in s.entity_id %} {{ s.entity_id }} {% endif %} {% endfor %}
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.
You missed the brackets to show that now() is a function. This "{{ ( as_timestamp(now(),0)... not this "{{ ( as_timestamp(now,0)...
Still getting this:
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
What is the result of {{ state_attr('automation.winter_daniels_thermostat', 'last_triggered') }} in
-> Templates
Result type: string
2021-11-25 12:14:54.043455+00:00
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?
Result type: number
1637845500.0067
That's a timestamp
Yes I understand. I'm trying to fix an error. I attached it above.
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.
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?
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.
I see. In 2 months I think it will reject the template unless I fix it. I might as well fix it now lol.
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?
I reloaded the template entities when I made the change. I just did another reload and so far it did not throw an error.
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
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
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
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?
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
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.
Both timestamps are already numbers
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
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
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?
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
How should I set it up without int? As in what would the template look like?
{{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered'),as_timestamp(now(),0)) ) > 5 }}
Thank you I am going to test this and see if it throws an error still.
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
What happens if it runs really quick? How long does 1 stay?
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)
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.
assuming that 33555202 only appears once:
{% set val = value_json['dxsEntries'] %}
{% for x in val if x['dxsId'] == 33555202 %}
{{ x['value'] }}
{% endfor %}
I think I just found another solution
{{ (value_json.dxsEntries | selectattr('dxsId','eq',33556736) | list | first).value }}
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 }}"```
You need to quote ‘comfort’
All these little things.. Well gotta learn!
You also have an extra set of parens, but that’s not the problem
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?
{{ ((now().timestamp() - states.input_number.max_water_temp.last_changed.timestamp())/86400)|int }}
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()
device_id(entity_id) returns the device ID for a given entity ID or device name. Can also be used as a filter.
Can I use timestamp with this format? state_attr('sensor.grocy_chores', 'chores')[0]['last_tracked_time']
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)
What about getting the device name from device_id?
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') }}
I tried reading those pages, based on that i tried {{ state_attr('61dae1fb67a4148c6668277f3fbbd817', 'name') }} but it returns 'none'
ahh.
well, state_attr isn't querying the device attributes
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.
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?
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
Ah okay. So then there's no way for me to do what I want to do right?
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
@snow laurel posted a code wall, it is moved here --> https://hastebin.com/ebozadoyec
Not possible
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.
thank you!
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
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
If the state is off as it crosses midnight, the count will be 1
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?
Thanks @mighty ledge you were spot on, the database has an off dating back a few days.
So, it sould be fine from tonight onwards
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
Definitely odd, but something I now know!
Use object_id
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.
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
- name: "Battery Monitor State"
and this is part of my config.
The type is the same as in the example
Sounds like #integrations-archived
I am sorry, you are right
I looked at https://github.com/home-assistant/core/blob/c2df4f56a3eb7ff54fa25ccc73174331b2527b57/homeassistant/helpers/template.py#L488 and I think it might not be possible, object_id is right but expand I think is hard-coded only for the whole entity_id and there is not really a way to sort using expand and ignore the domain.
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
can anyone tell me the difference between
value_template: {{ }}
{{ }}```
and
```value_template: >-
{{ }}```
first one is wrong syntax, however it's trying to be a single line yaml field that has a template. It needs to be
value_template: "{{ }}"
second one is a multiline yaml field with a template, > indicating the next few lines are part of this field.
The third one is a multiline template indicating that the next few lines are part of this field. But it's going to remove any leading whitespace
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.
look at this post I made a while back, covers the basics https://community.home-assistant.io/t/psa-template-and-yaml/348967
ah good to know, thanks 🙂
@manic warren posted a code wall, it is moved here --> https://hastebin.com/tugeruxiyu
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 🙂
@manic warren posted a code wall, it is moved here --> https://hastebin.com/iwedokuqok
@manic warren posted a code wall, it is moved here --> https://hastebin.com/sosevolixi
I trigger the service with a parameter 'who":
service: script.set_out_of_home_attribute
data:
who: arut
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
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"
@wispy lodge posted a code wall, it is moved here --> https://hastebin.com/xahunojuvi
You’re confusing JavaScript, which you’re using in your card, with Jinja, which is used elsewhere and is the topic of this channel
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
I'm not very familiar with Javascript. Try in #frontend-archived
probably float(variables.state) === 0 {
I'll try it on Frontend. Thanks for the help anyway my friend.
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!
it looks like you can just multiply the hours by 3600 and set the duration in seconds
{{ states('input_number.whatever')|float * 3600 }}
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
lots of good info here: https://www.home-assistant.io/docs/configuration/templating/#states
surround it in quotes? don't use the UI?
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)
no idea
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 😐
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
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 :))
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
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!!!
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?
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
something like this: https://dpaste.org/TLtf ?
but how do i create a new template sensor for this?
yes, like that. and via the docs for a template sensor?
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
there are two different ways to create a template sensor, and they're both documented there
you're mixing them up
yeah, i managed to get it working now
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
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
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.
everything in HA works this way, you restart and you get a new state, therefore it just changed
you can't concatenate !include with anything else. Everything needs to be in the include.
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 %}
What's happening instead of what?
I just get the error
I'm guessing it's an error about cover.mygarage being undefined or something? It should be is_state("cover.mygarage", ... with quotes.
What are you trying to achieve anyway? The current state, but then with the first character in uppercase?
This will do that too:
{{ states("cover.mygarage")[0] | upper ~ states("cover.mygarage")[1:] }}
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...
A statistics sensor? https://www.home-assistant.io/integrations/statistics/
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....
I think you’d need to use an SQL sensor for that
OK. Is there a good space to ask for help with queries?
Not really. You can review the dev docs for the database schema, but SQL is well documented
The problem being I have no idea how to write a query... Well.... Thanks... 🙂
{% 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
@obsidian lintel posted a code wall, it is moved here --> https://hastebin.com/olahogokef
You’ll get more help in #frontend-archived
awesome! Thanks @inner mesa
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:
- 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..
i need to set some defaults for a template i have , don't quite understand what to default ?
https://pastebin.ubuntu.com/p/HtxGSqbZR7/
log messages , upcoming version requires defaults ... ?
check the first pinned message
thnkx
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 😉
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
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." 😕
like I said...
I’m guessing that you have templates: in your configuration.YAML (which should be template: with the new format)
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)
then use datetime: "{{ now() }}"
also does not save the time
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
i do have has_time!
something seems broken
it's not a really hard example to follow either
right, but something is wrong in your config and it doesn't have to do with what you've posted so far
maybe I'm overseeing something, but I really think I don't
are you using yaml or the helper UI?
helper UI
can you screenshot the helper?
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
dev tool state: https://www.imgpaste.net/image/KJ02uX
helper config: https://www.imgpaste.net/image/KJ0czb
automation: https://www.imgpaste.net/image/KJ0Dd2
you didn't change the field name
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?
up to date
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() }}"
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.
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
It needs to go from above 0 to below 0 to trigger
but it went from -1 to -2
oh, ok, i think i know what you mean
how can i trigger on that, then?
i want it to trigger whenever the sensor updates
so not numeric state?
Nope
Might need to add a condition to prevent the automation from firing if a state attribute changes but not the state itself
can i then use condition on the actions?
"{{ trigger.to_state.state != trigger.from_state.state }}" is what I was talking about above
Condition for what?
i guess this is now something that fits better in #automations-archived , but here it is: https://dpaste.org/csfN
Sure, but that won't do anything if it's exactly 0
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
The state needs to change for it to trigger
After updating that automation and reloading it?
well, it seems to be working now.. i manually set the state and that triggered
Unless you did that in the UI, then it'll reload itself
i did that in the UI
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 -%}
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 }}
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
asked in frontend, but got no response so please allow once more here. I would like a Jinja template that (having installed Browser-mod too) gives me a path for any browser I use, without having to hard-code the browser-id like I do now in https://gist.github.com/Mariusthvdb/9069c8c4dcad6324035a679244bbfdf1#file-custom_header_template-yaml-L9
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..?
What is the end goal of this?
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?
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
assuming you replied to me? What I like to achieve is to have the current View name in my header bar. I have that now in the browser I hardcoded the Browsermod id in. I want it to be browser independent however. see https://community.home-assistant.io/t/card-mod-super-charge-your-themes/212176/910
Hi all 🙂 I am failing integration of a REST api.. is there someone who might can help 🙂 ?
Or is this the wrong channel?
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']
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 }}'
messages need to return strings, not other types
which is why it wasn't working
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
- {{ 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
oh, probably not. nevermidn
<deleted nonsense>
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
It works petro ur method
awesome
i did this at first
- {{ state_attr({{i.entity}}, 'friendly_name') }}
LOL
templateception
I tried to big brain
Anyways
I got a new challenge
Might not be one for yall
@obsidian lintel posted a code wall, it is moved here --> https://hastebin.com/ofetutinoh
yep
LOL
jinja scope
Im guessing I got to make a sensor for it?
no, use filters
May I have some demostration almighty petro?
well, are you trying to put the number before the name?
oh wait, I see by your note
to count lights....
Yes petro
{{ expand(config.entities | map(attribute='entity') | list) | selectattr('state','eq','on') | list | count }}
😅
Where did you find that
I made it
| is the filter applier
i dont' know the actual name of it
x | y means apply the y filter on x.
"pipe"
yeah i know it's a pipe, but jinja has a name for it probably
jjust ask your questions
Let me think how I am going to ask it efficiently
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
like all lights?
For every entity in my Home Assistant
Without the need to use a config.entities which uses a state-filter card
{{ expand(states.light) | selectattr('state','eq','on') | list | count }}
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
{{ expand(states.light, 'switch.xyz') | selectattr('state','eq','on') | list | count }}
I was going to suggest a regex, but that's better
Got it, gonna learn more about expand
Its so powerful
even Rob is mindblowned
Last question I promise petro
Well you don't know it if you don't use it
equals
you can also use '==' instead of 'eq', or 'equals'
not 100% sure about equals, but it sounds good
i tend to use "eq" because i use too many APIs 😛
nope, equals doesn't work
there's not much to read up on if you don't know python
the docs are lacking
you have to play around
I have python background, not too much as I do networks
expand() is HA specific so the HA docs are the only place you'll see any info on it
But thanks a lot
but, you can mix and match states, states.domains, and entity_id's with commas and it should work with expand
I think the only issue with expand() is that can be slow and take a bunch of memory
or could go to the code in github. homeassistant/core/homeassistant/helpers/templates
I actually think that your example is powerful enough for me to do everything I want
it's a generator so it's still quite fast
nope, a genny
[<template TemplateState(<state switch.fr_table_lamp=off; friendly_name=FR Table Lamp @ 2021-11-30T07:54:31.218175-08:00>)>]
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
huh, nope
it outputs a list for me
def expand(hass: HomeAssistant, *args: Any) -> Iterable[State]:
return sorted(found.values(), key=lambda a: a.entity_id)
I remember because it was killing perf for someone on a Pi
so values() should be a DictValues but i think sorted() turns it into a list
yah | sort turns everything into a list in jinja
same with unique... i think
map, select, reject, selectattr, rejectattr are generators for sure
iirc DictValues() is a generator
{{ expand(states.light, 'switch.xyz') | selectattr('state','eq','on') | list | friendly_name }}
nope
{{ expand(states.light, 'switch.xyz') | selectattr('state','eq','on') | map(attribute='name') | list }}
petro is right
||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
petro
yeah i stepped back for a bit so i'm a tad rusty
its in a list
|join('\n - ')
Legendary
but you shouldn't need to do that
he's in a markdown card
ah
And how would I go about filtering out a single entity which I dont want
it is my browser_mod light
rejectattr()
something like xxx|rejectattr('entity_id', 'eq', 'switch.something')|yyyy
- {{ 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
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
you can add more with rejectattr('name', 'in', ['00fb7000 90d1fd56', 'xxx', 'yyy'] )
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:
hah the edge cases are brutal
Now I can finally add it into my UI
I think default() can be used for that. I posted an example in the last week or so
before the join?
probably
with a | default(['None'])
and it'll have a listed None item
🤷♂️
here's my test that worked
it's the "True" part
{{ things|join('\n - ') if things else "Nothing to see here" }}```
Thanks for introducing expand, there wasn't much details on the template docs
or maybe it does. the point is that default('xxxx', True) will output xxxx if the input is an empty list
all my lights are off so it was an easy test
ah learned something new
{{ things|join('\n - ') or "Nothing to see here" }}
{{ 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
That's what I wish was in HA
i think its a test
intellisense
ah
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
My laptop browser is 00f blah blah blah
But my mobile device is
a801 blah blah blah
Is there a way I can totally remove browser_mod light entities
Not just because they’re provided by the same integration. If there’s an attribute, yes. Or you can use a regex
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?
Then that. rejectattr('attributes.Type', , 'eq', 'browser_mod')
I don't need eq
Oh yeah
I do
U edited before I asked hahaha
It doesn't work
you have to do the reject before the map()
And make sure that the attribute is really called 'Type' with the capital T
selectattr('state','eq','on') | rejectattr('attributes.Type','eq','browser_mod'
)
| map(attribute='name') | join('\n - ') }}```
Nothing
Yeap aint working
This is an interim solution but I need a permanent one
What would be better
does it have an attribute called "Type"?
i usually make an attribute called source if I want that info
sigh
its type
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
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?
ok?
I also found that this. wasn't needed to access trigger_variables
but those are different from variables defined for the automation trigger
that means you can't use them @tired sandal
@mighty ledge yeah, I got that.....
you can only use built in jinja functionality
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.
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
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
ok, that's a state trigger
yep
to access that information, you'd use trigger.xyz
@mighty ledge like this? https://www.home-assistant.io/docs/automation/templating/#state
yes
Dammit, you beat me to it.
{{ trigger.to_state.attributes.temperature }}
yep
Oh, right. I think I was missing attributes
You wanted to click through to the state object page
I did.
And look at the entity in
-> States
it also shows you everything in the traces
Also, validating the config throws an error for that.
Depends on what you did
Error loading /config/configuration.yaml: invalid key: "OrderedDict([('trigger.to_state.attributes.temperature', None)])"
in "/config/./config/automations.yaml", line 41, column 0
you're probaly not useing quotes around your template

or the field you're putting it in doesn't allow templates
Oh wait, you have to quote templates?
single line templates require quotes
some reviewing of the templating page is in order
there are big warning boxes and such for this stuff
Yep. I quoted my template, and it's happy now.
that one is #1 on the list of things to do
On the up side, the command line config check will tell you every time you get it badly wrong
@inner mesa I'm looking at this: https://www.home-assistant.io/docs/automation/templating/ and other than the examples, I'm not seeing anything about quoting.
Aha!
There are other links too
yeah, that page
automation templating only covers the trigger objects that are passed through
Ah right.
FYI, don't use the phrase trigger variables
Home Assistant will involve a lot of reading 😉
cause it has it's own separate meaning
Ah right
"Important Template rules"
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
single line -> yes, multiline -> no
yeah
those are part of yaml btw, not specific to templates
Distinguishing Yaml from Jinja (templates) https://community.home-assistant.io/t/psa-template-and-yaml/348967
thanks i will
Jinja (Template) Built-ins https://jinja.palletsprojects.com/en/3.0.x/templates/#list-of-builtin-filters
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?
or custom button card, which has two completely different kinds of templates
and neither has any Jinja at all
What do you mean, you want more pinned messages?
Nevermind, I’m an idiot
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', '????')}}
you don't need a template trigger for that, just a state trigger with an attribute
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....
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().
Then you want to select from that list the words that are in a different list of words. https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.select https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-tests.in
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 }} ||
Is it possible to create an array of entities that I can parse thru in a template?
feel like I am missing something obvious
I don't think I quite understand what you want to do.
I want to iterate thru a loop of specific entities I set
what do you want to do with them?
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
first, I would set the input_boolean to on when it should count, and not leave that decision until later
okay thats fair, then I would iterate thru the input booleans instead, that works too
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
Thanks @inner mesa few new concepts to me in that snippet. Let me play with it. Thanks!
@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 }}