#templates-archived
1 messages · Page 78 of 1
i have a powerplug that gives out Watts ofc and i want to expose it to Homekit
but since HK cant read Powerplugs
i tried to fake a sensor giving Lux
the Sensor is active but doesnt read out the real sensor
post what you tried
- platform: template
> sensors:
homekit_converted_sensor:
friendly_name: "MPower"
unit_of_measurement: "lx"
device_class: illuminance
value_template: "{{ state_attr('sensor.smart_switch_2309263180307151081348e1e9dbf36b_power','W') }}"
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
can you format it please
sure
just edit your previous comment
i can already see your template in th etemplate sensor is wrong
{{ states('sensor.smart_switch_2309263180307151081348e1e9dbf36b_power') }}
assuming your entity_id is actually sensor.smart_switch_2309263180307151081348e1e9dbf36b_power
why?
why what?
what is wrong about it?
your template? or the entity_id?
the template is wrong, just a misunderstanding of templates on your part. The entity_id isn't necessarily wrong, I'm just not sure if you provided the correct one to the template.
beginners typically don't know what entity_id's are, I'm not saying you do or don't. But you said you were a beginner.
sure iam 🙂
so the entity id i gave is the real sensor
i thought the template would pick this one to read out
the entity_id is the identifier for the existing information
the states function gets the state for the provided entity_id
you used the state_attr function, which gets attributes from a state object.
the state on an entity is not an attribute, so that's your miss understanding
you're assuming that state_attr(entity_id, 'w') will get the watts out
but the watts are the main state
so you just need the states function, i.e. {{ states('sensor.smart_switch_2309263180307151081348e1e9dbf36b_power') }}
so if you use the template I provided, it should work (Assuming that sensor.smart_switch_2309263180307151081348e1e9dbf36b_power is the correct entity_id)
omg
you should try the template in the template editor
developer tools -> template tab
it also has auto-complete for entity_id's
developer tools -> states shows you all entitys (and their states, entity_ids, and attributes)
np
ill get to work on that
hi, i'm trying to create a helper which copies the numerical state of a template i created from my climate sensor (because there isnt an entity for the value i need from it) but i'm struggling with what to create the helper template as as it keeps complaining about
Sensor None has device class 'temperature', state class 'measurement' unit '°C' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'value_template: "21.5"' (<class 'str'>)¬
any ideas ?
i'm using
value_template: "{{ states('sensor.mainhousetemp')|float }}"
or if i use the device directly even i get the same complaint about non-numeric value
value_template: "{{ state_attr('climate.heating', 'temperature') }}"
ok ignore me, figured it out
hmm ok so now i have the helper, the blueprint i have only is looking for number helpers, and doesnt see my template one. is there a way i can make a number helper = the other helper? would that need to be an automation in of itself?
yeah you need an automation for that
gotcha, i think i've made one and it looks like it is alll working now 🙂
does the switch template have any "magic" variables like this.action for the action (on/off) requested?
some templates have this kind of thing
Hi - anyone got any idea where HA stores the input from the template editor in Developer tools? I've got some bad templates which aren't in my config and I know HA reads the editor on boot and gives errors. I've cleared as many places as i can on my machines but still have some stragglers...it's very frustrating!
that question doesn't make sense to me. HA (core?) doesn't "read" anything from the frontend.
If the template in the editor is stored, it's cached locally in the client.
It does. Put a bad template in the editor and restart - look in your logs and voila - a startup error.
I've cleared all my caches and history on all machines that have ever accessed it.
can you show an example of whats your "bad" template, and what log message you get on restart?
Here's the log (this code doesn't exist anywhere on my config)
@thorny snow I converted your message into a file since it's above 15 lines :+1:
State-based and trigger-based template entities have the special template variable
thisavailable in their templates and actions.
from this page in the docs
so this.trigger.event would have the "on" payload if i tapped that template switch on?
this is the state object of the switch. The state object has no property called trigger
if you have a trigger-based template entity, it would have a variable called trigger populated with that data. But there is no such thing as a trigger-based template switch
so in my template i can say
turn_on:
service: script.turn_on
data:
target_entity: script.my_script
data:
intended_action: trigger.event
?
oh.
so i can't do what i want
wait haha i'm a dummy - the fact that i'm INSIDE turn_on is enough to know the intended action
nevermind
hi all - I'm seeing HA change text on me in the raw editor after I save, exit, and go back into raw editor. For example.
{{ states(''sensor.day_en'') }}, {{ states(''sensor.date_en'') }}```
is changed to:
``` name: |
{{ states(''sensor.day_en'') }}, {{ states(''sensor.date_en'') }}```
is this expected behavior?
It changed the > to |?
Both have the same result in this case, doesn't make a difference
interesting, it's strange that the raw editor is making unnecessary changes like that
it's part of the yaml -> json -> yaml serialization/deserialization
the whitespace character doesn't exist in json, so that info is lost
but I think it faithfully creates the correct output
It also adds these double single quotes, which are escaped single quotes
yeah I noticed that too
are the open {{ necessary in that block before "states"? can't it just be states('sensor.day_en....)
nvm - answered my own question
The {{ and }} are required, they are essential in Jinja templates
Hi everyone, I’m new to Home Assistant and I’m trying to learn by watching lots of tutorials but got stuck on a problem, trying to get current temp from any on my sensors with state_attr. I’m getting null or none when using {{ state_attr(‘sensor.aqara_temp_humidity_sensor_temperature’, ‘current_temperature’) }} and I’ve tried lots of things but nothing seems to work 🙁 What am I doing wrong 😑
please provide your full yaml in a log
- layout: name_state
name: |
⌂ {{ states('sensor.home_temperature') }}°F
this is mine, works fine
Yes using only states works for me too but not when using state_attr
your temperature sensor has an attribute of current_temperature? That seems odd. Did you look at what actual attributes exist on that sensor? (check developer-tools -> states)
why do you need to call on the attribute if the states works fine?
This is what I get
{'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>, 'unit_of_measurement': <UnitOfTemperature.CELSIUS: '°C'>, 'device_class': 'temperature', 'friendly_name': 'Sovrum Temp'}
I don’t know like I said in trying to learn and on the tutorials several videos shows this way and when I try to do the same thing it doesn’t work
you sound confused about the difference between states and attributes.
The state is the primary piece of information for a sensor. For a temperature entity, the state would be the temperature.
Attributes are like secondary information.
Ok. why do we use attributes then?
you can see them all in
-> States
and for this, it looks like you just did something like {{ states.sensor.xxxx }}, which isn't how you get a state
this is: #templates-archived message
Strange because that’s what I saw in that template video I was watching and he shows exactly that.
videos are often wrong. avoid whoever posted that one
they don't know what they're doing
if I want to pull state from weather, what should my code look like?
or you missed the .state at the end, but you should use what I pointed to anyway
I'm getting my internal temp and weather with this code:
- layout: icon|name_state
name: |
⌂ {{ states('sensor.home_temperature') }}°F
state: |
{{ state_attr('weather.home','temperature') }}°F
but for the life of me I'm struggling to pull state from weather. The docs say I can get it but no idea how
state like cloudy ?
That's just states('weather.home')
they show an example
first example: https://www.home-assistant.io/integrations/weather/#examples
{% set state = states(weather.home) %} ?
or do I have to pass the forecast variable too? hourly?
Using the state_attr for weather works just fine but not to get Temp from any of my aqara or hue sensors
the first example doesn't seem to have anything related to state (like cloudy), the second example has forecasting and has state but it's not entirely clear to me to pull just state and pass it onto a variable in yaml what I need to do
the state is just the state of the weather.xxx entity
you just posted an example of retrieving the state of an entity
you posted:
⌂ {{ states('sensor.home_temperature') }}°F
then did this:
{% set state = states(weather.home) %} ?
note the difference
I mean there's a couple differences 😉
but, you gave me a good place to start, I think I see it....maybe
I'll fix that statement for you:
using
state_attrworks just fine to get attributes from entities like the weather entity, but it doesn't work when you want the state of an entity
😉
still not getting it: {% set state = states('weather.home') %}
You're trying to get the weather state?
{% set state = states('weather.home') %}
yes, sorry I updated to weather.home but still nothing, I thought that returns the state
That's what you need.
yeah - I'm not sure why weather.home is returning nothing
{{ state_attr('weather.home','temperature') }}°F
returns temperature fine
where did i miss .state?
no he didn't
If you run that template through the template editor, what does it return?
then ignore their videos as they don't know what they're doing
so you are saying that dont look att youtube tutorials
Honestly, the forums are usually a better resource than Youtube videos are simply because a lot of videos are old and refer to old versions of HA. Same thing with ChatGPT assistance.
@frail dagger now I'm making some progress:
- layout: icon|name_state
name: |
⌂ {{ states('sensor.home_temperature') }}°F
state: |
{{ states('weather.home') }}
returns "sunny"
but:
{% set state = {{states('weather.home) }} %}
returns error:
TemplateSyntaxError: expected token ',', got 'weather'
wherever you saw this:
and for this, it looks like you just did something like {{ states.sensor.xxxx }}, which isn't how you get a state
sorry it actually returns:
TemplateSyntaxError: expected token ':', got '}'
when I fix that ` error
{{states('weather.home) }} you're missing a quote at the end. It should be {{ states('weather.home') }}
yeah I resolved that, then hit the second error
You are nesting templates
just saw that the videos i was watching are 2 years old 🙁
{% set state = states('weather.home') %}
Probably he want just
{{ states('weather.home) }}
That's my point. It's hard for content creators to keep up with how fast HA grows and changes. And they rarely pull their videos down... sooooo, you get stale info.
I think he wants to use the state variable though? I'm not sure 🤔
yeah I want to use variable to pass to an icon mapping
I think it's working but my mapping isn't working now. But, no errors which is promising
Post up what you have
probably best to just share the entire yaml at this point, I forget what this channel prefers for posting longer code
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
https://dpaste.org/Dne0e, I believe state is being passed on based on no errors and no default weather icon that used to come up, so I think I'm down to my path to my icons being wrong
Line 71 is wrong: {% set state = {% set state = states('weather.home') %} should be {% set state = states('weather.home') %}
I can't really validate the rest of it as I don't do frontend stuff.
But it looks good?
for my path, if I'm using a docker, the "./" is equivalent of location of my docker configuration folder right?
Yup. It translates to /config
super weird result - where my icon should be, it just reads "icon" in super small font
Post your yaml in #frontend-archived
I'm not good with frontend at all. lol
@frail dagger huge help. Beer on me 😉
Happy to help!
How is this possible
{{states('device_tracker.520d_xdrive')}} #Garage
{{is_state('device_tracker.520d_xdrive', 'zone.garage') }} #False
so the first line clearly says that car is parked in zone called 'Garage'
what is better approach for this
yeah, but Im confused? do I need some binary_sensor which will calculate is the car are in the zone or not?
and then just to observe that binary_sensor?
I'm not following you at all
you wrote a test to check if it was "zone.garage" when you already know that it's "Garage"
so here what I want, very simple.
Each night at 00.00 I want to check if my car is int he garage or not.
I created zone: zone.garage
Now I want to put condition template to check if the car (device_tracker.520d_xdrive) is in the garage or not. If not, notify me.
So my question is presumably that when device_tracker is in the some zone, in this example 'Garage' zone, its state will be 'Garage', the name of that zone right?
I dont need to check and compare if that device_tracker are really in the zone, just by string 'Garage'?
What if I want to rename zone in couple of weeks into 'New Garage'?
is that will break my automation?
You could just call the old one "Old Garage" 
Yes, but from perspective of maintanance I will need to edit my automation right?
I would like to use zone.garage if the device tracker is in or out that zone
Why not just put an entity state condition in your automation on zone.garage = 1?
Feels like you're over-complicating it.
{{states('zone.garage')}} returns zero, and
{{states('device_tracker.520d_xdrive')}} returns 'Garage'
how that is possible?
if device tracker returns 'Garage' that means that at elast 1 entity is in the zone?
what if the cars are people?
ok, so I cant use it because this device_tracker is basically BMW integration not human 🙂
I mean, I named my car... so, it's people to me.
Yup, I was wrong (I said it twice 🙂 )
I have attributes for location (longitude and latitude) position of the car, and based on that I created zone with radios of 10 meters
but apparently my automation is bad, because it's not matching want I want to be matched
maybe I can use zone trigger and some helper boolean to keep track if the car is in the zone
Post the automation.
how about something complicated like this:
{{is_state('device_tracker.520d_xdrive', slugify(state_attr('zone.garage','friendly_name')) ) }}
Try that again, the paste is returning a 500 error for some reason.
So, you're already using the value template, just use Garage instead of zone.garage.
No it doesn't. It's checking that the zone the device_tracker is in matches the slugified friendly name.
Then how it is possible to be false this statement?
https://i.imgur.com/9Azp0Gk.png
When I remove slugify method then it's true
What is setting the state of the device tracker? Is that the BMW integration doing that?
Yeah, probably because of slugify.
https://i.imgur.com/EZTwu96.png
I really don't know..
Slugify does make it lower case, but that was intentional, because that is what the state of a device tracker should be when it is in a zone
When it is in a zone the first letter is a capital one.
In the front end, yes. Not in the back end
At least normally. In your case, it also has a capital in the back end
nevermind, I think we fixed it now 🙂
Did you overwrite the state of the device tracker in dev tools and use a capital letter?
Is it just Home and Away that will cause device trackers to use a state that doesn’t match the frontend? (home and not_home)
coudl be
I didnt
Hey guys, I have a question. I have open weather in ha and I noticed something weird with forecasts. It seems to be pulling the Forcast data for like 4 hours ahead. Now I know the 3 hours of data is there when Iook at the sensor. But the weather.get_forcasts starts 4 hours ahead.
Yeah, looks like I was wrong. For user-created zones, the device tracker will use the zone’s friendly name as the state
My guess, the datetimes in the forecast are in UTC time, though probably is 4 hours ahead of your local time
What needs to be fixed?
You can compare timezone aware datetimes with each other if they are in a different timezone
How can I create template trigegr for my vacation mode automation, to triggers in to cases:
- When Im not in city zone anymore for 4 hours or more
- When Im on airport (witihin city zone) waiting for 2 and a hlaf hours to be boarded into a plane, then I suppose will have for my iphone device_tracker status 'unavailable'
woo this worked! I was printing states['sesnor.foo'] for debugging and it was showing just the sesnor attributes instead of the whole state object, so I thought I couldnt access last_changed from that
I need to figure out what time zones being sent and all that fun stuff
I think I just posted my message in the wrong group "integrations". So just to cover my bases I will try the templates group. I suck at yaml, it takes me months to figure this kind of stuff out. Mainly cause I get distracted and don't want to sit in front of the computer. I am or have been trying to figure out how to get a weather intigration working. To populate a cool weather card I found on HACS. I understand I am supposed to write a weather template where I as the user create the entities that pull in the data. What I am hoping is someone is willing to share a weather template that they are using so A. I can look at it and try to understand it. And B, I could possibly modify if I need to for my own use. I would really appreciate it if anyone is avalible to assist.
Alright, I have a sensor thats pulling from openweather. hour0_date: "{{ hourly['weather.openweathermap'].forecast[0].datetime }}" The openweathermap is sending me the time in UTC which is fine but I need to bring it back to my timezone. How can I accomplish this?
What's your goal here? You can use as_datetime to convert it to a datetime object (it most likely is a isoformat datetime string now) and then use as_local to convert it to your local timezone
Yea, end goal is to have that time in my timezone.
To do what with it?
I found a kodi plugin that pulls weather sensor data via the API from HA. So when its being read into Kodi its reading that time, which again is incorrect.
Now, granted within the Kodi plugin I can make it update based on the local time as well. However I thought it'd be a quick update to just do it within HA but its eluding me.
How does the plugin get the data? Do you only send the first list item or the entire forecast for the next days?
Why Im having an error: {{ (as_timestamp(states.binary_sensor.frontdoor_motion.last_changed | default(0)) - as_timestamp(states.binary_sensor.front_door.last_changed | default(0))) < 30 }}
ValueError: Template error: as_timestamp got invalid input '0' when rendering template '{{ (as_timestamp(states.binary_sensor.frontdoor_motion.last_changed | default(0)) - as_timestamp(states.binary_sensor.front_door.last_changed | default(0))) < 30 }}' but no default was specified
is this correct logic:
{% set current_time = now().time() %}
{% set start_time = strptime("09:00", "%H:%M").time() %}
{% set end_time = strptime("10:30", "%H:%M").time() %}
{{is_state('media_player.bedroom_tv','on') and (start_time <= current_time <= end_time)}}
is there any better approach?
you're not supplying the defaults correctly, please check the pins.
use today_at("9:00") <= now() <= today_at('10:30')
hey guys, I need to send a payload template of a clipboard (sensor.asclepius_activelink)
service: mqtt.publish
data:
qos: 0
retain: false
topic: homeassistant/button/TheGoat/launchurl/action
payload_template:
anyone know the template to grab the text value of said sensor?
payload_template: {{ states(‘sensor.aceplus_activelink’) }}
gee thanks!
What's the variable to capitalise all ?
{{'user' | capitalize }}
Ah thanks, I tried uppercase instead lol
Hey all, I'm trying to put together a template for sorting all my lights by floor and then area (with custom sorting) for use in auto-entities. Just checking in, in the off chance someone has already done something similar before
If not I may just hold off until auto-entities hopefully gets support for sorting by floor and secondary sort
@violet geyser I converted your message into a file since it's above 15 lines :+1:
You can get all the lights of a floor with:
{{ floor_areas('First Floor')|map('area_entities') | flatten
| select('match', 'light.') | list }}
Thanks. It doesn't seem to recognise flatten, however.
Thanks 🙂
Sorry, forgot that was custom...
Would it be possible to include multiple floors
I would have expected that you could start with a list, but no. You need to use a loop
{{ floors() | map('floor_areas') | sum(start=[]) | map('area_entities') | sum(start=[]) | select('match', 'light') | list }}
or...that
How can I use templates in the google assistant config for including entities that I labelled? Config should look like this:
google_assistant:
entity_config:
light.entitiy1:
expose: true
light.entitiy2: ...
You can't
You can't use templates in the Google Assistant YAML config
I don't think it's possible with Nabu Casa as well, there is no service call to expose entities
fair, albeit unfortunate. I'll just put it manually, will use the template dev tools to generate the list from a template that I can copy paste
hey, whats wrong with my syntex ?
service: input_number.set_value target: entity_id: input_number.screentime_hours_bank data: value: "{{ ((states("input_number.screentime_hours_bank") | float)*3600 - (state_attr("input_datetime.eithan_screentime_add" , "timestamp") | float))/3600 }}"
You're using the same quotes inside and outside your template
Use single quotes outside and double quotes inside, or the other way around
Or use the multi line notation to avoid quotes outside the template
thanks
@green summit I converted your message into a file since it's above 15 lines :+1:
@marble jackal I originally tagged you in this but didn't realize it was going to do that. But thats the way it returns. I just need 20 to be 16 lol
So, im trying to setup a dashboard and the addon im using isn't very mature yet but i do like some of the features. Is it possible to add An Icon, Sensor Name and Value, similar to how the standard dashboards show them, using a template.
As an example, I have some light sensors, and on the standard dashboard they show a sun icon, followed by the text "Light Sensor Light level", followed by the value "20 lx".
Is there a way for me to achive that exact same thing using templates?
seems like what you're calling "addons" are "cards"
No, I have a whole dashboard addon (HA Fusion) I am using, so doesnt have standard cards. It has some stuff but for the standard card style icon - text - value it doesnt seem to have anything. So was wondering if i could recreate that with template syntax
you can easily create a string with "Light Sensor Light level" followed by the value "20 lx" with the value being the state or attribute of an entity
It is possible to get the icon too or is that too far for templates?
if you find a unicode icon that you like, you can include that
you can't specify an mdi:xxx icon there and have it render
Ok cool, thanks
Hi, im trying to do the basic hourly forecast template sensor thing, but keep getting an error that my response_variable is undefined (UndefinedError: 'hourly' is undefined)
- trigger:
- platform: time_pattern
minutes: /15
action:
- service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.forecast_home
response_variable: hourly
sensor:
- name: "Forecast Home Hourly"
unique_id: hourly_weather
state: "{{ now() }}"
attributes:
forecast: "{{ hourly['weather.forecast_home'] }}"```
Where do you get that error? In developer tools?
I noticed in developer tools I can't test either and it was bugging me lol
developer tools and actual error log for my sensor
2024-06-15 18:24:09.623 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('UndefinedError: 'hourly' is undefined') while processing template 'Template<template=(template:
SO I dont think it works in dev but I have something similar let me compare
you have this in a template yaml?
uhh i could be putting in the wrong place since im not used to this
but I went Settings -> Devices & services > Helpers > Create Helper > Template > Template a sensor > paste in the state template box
Is it in your config file? For me I placed template: !include template.yaml in my config file and then in my template.yaml file I have exactly what you have but remove template:
If it only works in actual yaml i can try that
Yea I dont know about creating the helper template but I did it that way and it works. Only thing I'm trynna do is change the time lol
That seems to work, thanks! not sure what the difference is but ill take it
same, I wish I knew
I'm literally going through it now with that same template. Just can't seem to figure out how when I'm setting the attribute to subtract time from it.
Hmm, it seems to be in my local timezone already for me
otherwise you might mess around with these https://www.home-assistant.io/docs/configuration/templating/#time
oh wait you mean the attribute itself, yeah im not sure, im just passing the sensor to a dashboard card
yea I'm messing around with pulling this data via the API into a Kodi plugin.
Openweather sends it in UTC
Yes, you can’t create trigger-based template sensors in the UI, it’s yaml only
you happen to know if I can do what I'm trying to do or is that another nope
you are trying to convert all the UTC datetimes in the response to local datetimes?
I think I understand that you are trying to achieve but:
- I haven't used Kodi for maybe 10 years, but at that time you could simply point to online sources for the weather, no need to use Home Assistant for that
- In case you really want to use that plugin, that plugin should handle conversion from UTC to local time. Write up an issue for the author of the plugin
- In case you really want to use the plugin, you can maybe use another weather integration which might have local datetimes instead of UTC datetimes
- In case you really want to use the plugin and your current weather provider, I think you need to create a trigger based template weather which iterates over every item in the forecast and replaces the datetime string in each item with a local one. Seems like a lot of work for something which could be done a lot easier
Yes, I can update the plugin. I stated that previously. Sure, you can say use a plugin thats going to pull my local and not UTC time. All well and dandy. I'm simply asking for the Home Assistant way. I see plenty of people converting times and all that when looking around. None have seemed to work for me so far. If its simply Home Assistant can't do it because x y or z then fine. It just seems to me that if Home Assistant has all these abilities to modify time and format display that this shouldn't be such an issue that it seems to be.
you can do anything you want in a template. It's not an issue for home assistant.
I agree with TheFes, there are better ways to go about this. And I'm not great with namespaces, so there's probably some simplification that can be done. I've also been contemplating whether to post this or to teach you to fish, but here is something that works because I'm hanging up for the night: https://dpaste.org/6KUxh
This is a bit shorter, but indeed, I meant something like that
https://dpaste.org/oW0ju
Hm Having a bit of trouble with some templating, I'm trying to reduce the number of seperate automations I have for handling 'Door opens, turn on light in the room' so want to compact it all into 1 if possible. I've setup the sensors and lights so the follow the same scheme (binary_sensor.ROOM_door_contact & light.ROOM_lights) and wrote teh following automation to trigger but it keeps failing https://dpaste.org/ic9B0 with Error: In 'template' condition: ValueError: Template error: as_timestamp got invalid input '' when rendering template '{{ as_timestamp(now()) | round - as_timestamp(['light.' + trigger.entity_id.split('_')[0]].last_changed) | round > 10}}' but no default was specified
(it's supposed to check if the lights in that room have been off for 10 seconds, sort of as a debounce)
as_timestamp(states['light.' + trigger.entity_id.split('_')[0].split('.')[1]].last_changed)
You forgot states. and you forgot to remove binary_sensor.
Hmm..
@lyric jungle I converted your message into a file since it's above 15 lines :+1:
That doesnt seem to work either, get 'list object has no element 1' but I've been screwing around with it in templating and this ```{% set door = 'binary_sensor.kitchen_door_contact' %}
{{ door.split('.')[1].split('')[0] }} So I tried to convert that in the condition to be{{ as_timestamp(states['light.' + trigger.entity_id.split('.')[1].split('')[0]].last_changed) | round > 10}}returns the value of 'Kitchen' which.. is the correct word Im looking for to get added to the template but that produces the same error as before? Error: In 'template' condition: ValueError: Template error: as_timestamp got invalid input '' when rendering template '{{ as_timestamp(states['light.' + trigger.entity_id.split('.')[1].split('_')[0]].last_changed) | round > 10}}' but no default was specified ```
@lyric jungle I converted your message into a file since it's above 15 lines :+1:
You can't use templates in a tap action
Call a script and use the templates in the script
I think I got it 🙂 ```{{ as_timestamp(states['light.' + trigger.entity_id.split('.')[1].split('_')[0] + '_lights'].last_changed) > (as_timestamp(now()) < 10) }}
Ah right, I missed that _lights part before
(It should read the state of the lights, then turn them on if its been off for ten seconds, which.. should be good enough to stop debouncing)
Maybe an easier solution it to use a combination of areas and labels. Give each light which should be triggered by a motion sensor a specific label and make sure they are in the same area as the motion sensor
Then you don't need all this entity id matching
So for example a motion_triggered label
JHmm, I'll read up on that 🙂
Then you get something like this:
{% set area = area_id(trigger.entiy_id) %}
{% set light = area_entities(area) | select('in', label_entities('motion_triggered') | list | first %}
{{ now() - states[light].last_changed < timedelta(seconds=10) }}
This only works if there is only one light with that label in each area (like you have now with the entity_id matching)
It could be adjusted to work with more lights
Huh, I see! that does seem much simpler
Hello, I don't understand well template, I m tying to add a Open/Close helper when my car flap is 1/0 (close or open)
Is this correct ?
Template binary sensor
State template*
Close
{% elif states('sensor.dt5930_charge_flap_dc_status') == '0' %}
Open
{% else %}
Unknown
{% endif %}```
Does it work?
hi, I wonder how I can create my own demo for home assistant, without having connected hardware components to it?
A binary sensor will only ever be on or off, if you want it to show Open/Closed in the frontend you need to specify a device class of door, window, or cover. If you want the actual state to be Open/Close/Unknown you need to set it up as a sensor, not a binary sensor.
I didn't test it yet, it's late and my car is outdoor ^^'
Actually I ve choose the type door, I don't know if another type is better for a flap
It should always be On or Off (at least based on the history)
So if I want on or off what should I write ?
{{ is_state('sensor.dt5930_charge_flap_dc_status', '0') }}
That's all you need for the State template of a binary sensor helper to be 'on' when the flap status is '0'.
{{ is_state('sensor.dt5930_charge_flap_dc_status', '0') }} => it will set Open if 0 right ?
Yes
There's a demo integration
I am trying to convert a sensor that reports strings "Off" and "1" to "100" to an int
I tried the template
{{ states(''sensor.second_floor_odu_status'') | replace("Off", "0") | int }}
but the UI refused to accept the double braces, so I get this
Oh I can't post a screenshot here
Sensor None has device class 'power_factor', state class 'measurement' unit '%' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: '{ states(''sensor.second_floor_odu_status'') | replace("Off", "0") | int }' (<class 'str'>)
you need double braces, not single braces
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
It errors out in the UI if you use double braces.
I just used "combine the state of several sensors", and just used the one, and it seems to be working
it won't error if you're using double bracers, you're doing something wrong
double bracers are required for templates
If you're using hte UI to create a template sensor, this is all you should paste in the template box
{{ states('sensor.second_floor_odu_status') | replace('Off', '0') | int }}
and you can simplifiy it to
I did, and it is erroring and not allowing me to proceed. I cannot post the screenshot of it due to this channel not allowing me to.
{{ states('sensor.second_floor_odu_status') | int(0) }}
use imgur to post images
int(0) fixed it
Without that it was refusing to proceed, thanks
Now it's multiplying it by 100, probably because I set the measurement as a percent
That would do it
I added /100, will see if that fixes it
If you just want a value, fill out the UOM only.
Yeah I will if that doesn't work
Is there an easy way to get rid of the mean/average line on sensors?
I don't want the averaging or mean
I just want the actual reading
I'll ask in #frontend-archived
use a history graph not statistics graph
How do I change the graph type for when I click on a measurement on the overview?
The measurement overview is always the statistics graph and you can't change that
super
whats the best way to compare a current state to a change? do I have to use a helper to store the previous state? That feels inelegant? This doesnt work {{ (states.sensor.couch_person_count.state | int) == (states.sensor.couch_person_count.attributes.previous_value | int - 1) }}
i know... was trying to be illustrattive of the goal
I thought this would work: '{{ (trigger.from_state.state | int - trigger.to_state.state | int) == 1 }}'
the way to do it is to write an automation or a trigger-based template sensor and do that
ah
Hi, I hope this is the right place to ask a questions regarding template sensor:
I have a sensor, which shows the water-usage of my softner. At the moment it shows 500000 liter (several years, so the value is correct).
As I might want to change the system in the future and don't want to loose historical data I created a simple template-sensor, which just gets the value of my real sensor and integrated it in the energy-dashboard with the following code:
https://dpaste.org/m7x3b
It all works well, but as soon as I restart HA the STATISTICS of the template sensor gets as a one-time value the complete value (500000 liter) of the real sensor and not the 5 minute consumption. So I need to go to the statistics-dev-tool and modify the value.
What am I doing wrong?
Your if statement doesn't make sense. As you provided the default 0 for your float filter, it will always be a number
OK, so I can just remove the unnecessary if, but is this the cause of my problem with the statistics?
Your problem is the default for the float filter
You should use an availability template instead, but you can only do that in YAML, not when you create it in the GUI as a helper
ok, give me a sec 🙂
Wow, perfect. It just works 🙂
But can you explain me, why?
The available template will make your template sensor unavailable, while your default for the float filter made it 0
0 is treated as a reset, which was causing the spikes
Got it, once again: Thanks a lot!
i have a template for checking the forcast that is no longer working
%if state_attr('weather.pirateweather','forecast')[0].precipitation_probability < 51 %}
i can do a call service to get teh infromation but i need to pull out today which shoudl be [0] Can someone help me fix my template?
service: weather.get_forecast
data:
type: daily
target:
entity_id:
- weather.pirateweather
So you want the forecast from the service instead of from the deprecated attribute? Where do you want to use the service_call? In an automation/script? or template sensor?
i want to have my automoation check to see if it is going to rain
that is the goal, how i get tehre i don't partically care the template above is what worked last year and dosn't seem to work now
Okay do you check the template in the conditions part of the automation or in as condition in the actions part?
here is the automation https://pastebin.com/DUfEz5ur
figure sharing it is easier than trying to explain
If the latter you can do it all within the same automation, else if the automation is complex you best bet is to create a template sensor
It's a simple automation so we can rewrite it to handle everything within the automation. If you have a minute I can write something that should work
i like simpler
Oh I didn't mind to delete that from the copied over automation. But yeah that can be leaved out
wait which part is redant?
- condition: and
conditions:
and so i can learn and hopefully not bother with you in teh future, you are calling the service but how does the templeate get fille dout?
and ahh
for the redunant part
you set the response variable forecastwhere it stores the data from the service call, that variable is available in the actions part for all templates after the service call
can i paste that into the template editor to see what it spits out
Nope, it's not available in the template editor, but you can see the response data in the service part of the devtools
yea i got that far
it looks like it works, now i just need it to rain so teh automation will fail. unfortuanlly raid isn't looking good these days
thank you for the help
Scenario: Have a template entity in a trigger like this:
- platform: state not_to: entity_id: '{{ inputs[0].trigger_entity }}' id: 'StateTrigger' alias: '0'
That doesn't work, but this does:
- platform: event
event_type: state_changed
event_data:
entity_id: '{{ inputs[0].trigger_entity }}'
id: 'StateTrigger'
alias: '0'
entity_id does not support limited templates
99% sure I already mentioned this to you
You did
Is there another way to accomplish this with platform state so I don't get triggers on atribute changes?
Right now I'm using a condition in the action block to ignore them, but there still a lot of triggers when you open a cover.
Nope
Is there a way to conditionally disable triggers?
yep, using limited_templates you can disable/enable triggers
but, it's not live
limited templates are only resolved on automation load
which is why they are limited
enabled: "{{ whatever variable you want that resolves true/false }}"
Ok, that's straightforward
Hi Team, I need a little nudge (or maybe a big nudge) in the right direction here. I feel like I'm super close to figuring this out but just missing something simple.. I am trying to create an automation that will use the 'get_forecasts' service call so that I can get just the conditions for the upcoming days and turn those conditions into sensors. I'm including where I'm currently at (and stuck). https://pastebin.com/a1ARm7mb. Please guide me down the right path 🙂
At least your response variable is called daily and you are using the variable forecast later
Not sure what the condition in the actions is intended to do
I’m just trying to return the conditions, and nothing else
Remove alias and description.
And I guess the sensor states need an overhaul
Well, that's not really an automation. It looks like a template sensor to me. AFAIK, automations can't create sensors.
I missed "automation"
Probably just mixing up terms.
The thought behind the automation was bundling it all in due to the service 'get_forecasts' having to be called on a scheduled basis to continually update. Should those be broken up to where I am calling the 'get_forecasts' at a schedule time with an automation and then using a helper template to create the daily condition sensors?
Template sensors can have a service call action to retreive the data
Like in this example from the HA docs:
https://www.home-assistant.io/integrations/weather/#examples
So, adding to what @marsh cairn said... You don't want to do this with an automation. Just create a template sensor (in your configuration.yaml or in another file included in) and do it that way.
Can I get more specific or granular with the time intervals there? I don't need it checking every hour. I'd like to have it check once a day so that I can get the daily/nightly conditions for the upcoming days and populate them into a card.
I'm not understanding your question
your yaml only needs like 2 changes to make it into template sensors
your automation yaml
You can use a time trigger in a trigger template sensor that updates once a day
template:
- trigger:
- platform: time
at: "00:01:00"
action:
- service: weather.get_forecasts
data:
type: daily
target:
entity_id: weather.tomorrow_io_home_daily
response_variable: response
sensor:
- name: Day 1 Condition
unique_id: tomorrow_io_d1_condition
state: "{{ response['weather.tomorrow_io_home_daily'].forecast[1].condition }}"
- name: Day 2 Condition
unique_id: tomorrow_io_d2_condition
state: "{{ response['weather.tomorrow_io_home_daily'].forecast[2].condition }}"
Can you make event trigger do 'and' instead of 'or' for event_data?
`trigger:
- platform: event
event_type: zwave_js_value_notification
event_data:
device_id: !input 'switch'
command_class_name: 'Central Scene'`
triggers can't be 'and'
ok
Can I reference an input like this for a trigger entity_id: '!input input1[0].target.entity_id' Where the input name is input1?
Okay, I gave this a shot as a template. I don't have a template.yaml so I just put it in as a template helper. I restarted services with no luck. I feel like I'm missing something really simple here.
Hello. I'm trying to get the device name in a numeric_state trigger, e.g. {{ trigger.to_state.name }} too high for {{ trigger.for }}. However, this results in a error: "Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'"
It needs to go in configuration.yaml
You need to test it with a real trigger event, not the Run function.
You can use the States tool to temporarily set the state above or below your threshold for testing.
I had the threshold for the trigger set really low (for humidity sensor). Pretty this log came from that test, e.g. a real run
For context. This ☝️ is from a discussion in #automations-archived. The intention is that is should show if a sprinkler has been turned on today.
I don't think it will because of the and states.switch.sprinkler1.state == 'on' part.
yeah... I removed that.
thanks for adding context. 🙂
i have a white space issue. This works, but it gives me a blank line for every entitiy it skips:
| selectattr('attributes.device_class', 'eq', 'battery')
| rejectattr('state', 'equalto', 'unavailable')
| rejectattr('state', 'equalto', 'unknown')
| map(attribute='entity_id')
| list %}
{% for entity in battery_entities %}
{% set battery_level = states(entity) | int(default=100) %}
{% if battery_level < 25 %}
true
{% endif %}
{% endfor %}
false```
ugh, indent is right on my end
drat... didn't change it
ill read up some more
got it! thanks @silent seal great tip
{{ states.sensor
| selectattr('attributes.device_class', 'eq', 'battery')
| rejectattr('state', 'equalto', 'unavailable')
| rejectattr('state', 'equalto', 'unknown')
| map(attribute='state')
| map('int', 100)
| select('<', 25)
| list | length > 0 }}
there are other ways to optimize it
thanks! help me with map('int', 100)
that sets the scale?
I don't know what you mean "sets the scale"
anyways, more optimization (but not much)
{{ states.sensor
| map(attribute='entity_id')
| select('has_value')
| select('is_state_attr', 'device_class', 'battery')
| map('states')
| map('int', 100)
| select('<', 100)
| list | length > 0 }}
it would be better if you started without using states.sensor
I want to add a human readable uptime to my esphome devices, I already have an uptime sensor for raw seconds, and it's in the Diagnostic section, however no matter what I do, I cannot get a template sensor to show up there, it always shows up under "Sensors", even when entity_category is set to diagnostic
- platform: template
name: Human Uptime
icon: mdi:timer-outline
accuracy_decimals: 0
entity_category: diagnostic
lambda: |-
return id(uptime_raw).state;
It's best to ask on the ESPHome discord. But I would advise to use the start time of the device as uptime sensor, as it is static and won't have to write a new state to the database every second
New to templates, have a bit of a confusion. I'm trying to set up a VPD calculator using the template here https://community.home-assistant.io/t/calculating-vapor-pressure-deficit-or-vpd-in-kpa/162582, put in my sensor info and told it it was an atmospheric measurement sensor. But I'm getting an error I don't understand how to parse:
Sensor None has device class 'atmospheric_pressure', state class 'measurement' unit 'kPa' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'sensor: - platform: template sensors: vapor_deficit: friendly_name: 'vpd in kilo pascals' value_template: >- 1.77unit_of_measurement: 'kPa'' (<class 'str'>)
Looks like you pasted an entire YAML configuration in a GUI based template helper
uhhhh ... I don't have an option to open a yaml configuration in the UI here
only put this part in
{% set T = ((states('sensor.th16_si7021_temperature') | float) - 32) * 5/9 %}
{% set RH = states('sensor.th16_si7021_humidity')|float %}
{% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %}
{% set VPD = ((100-RH) / 100) * SVP %}
{{-VPD | round(2) -}}
oooooooh
okay, I get it. Thank you!
Added the sensor to my dashboard and it defaulted to mHg for unit of measurement. Curiosity is there any way that I can force it to default to mPa even though it's not an imperial measurement?
(working on plant stuff, and it'll be going into some docs to help other plant people who may want to do grow tent automation)
you can edit the enitity and choose a different unit of measurement
right, that's what I've been doing. I was just wondering if there was a way to pre-empt that for when it comes time for me to write up a guide
Hey Guys, i have a little error Invalid config for 'template' at templates/Team Tracker/1. Bundesliga.yaml, line 1: 'rest' is an invalid option for 'template' someone can assist me to fix this? here the code
resource: https://site.web.api.espn.com/apis/v2/sports/soccer/wc/standings
sensor:
- name: "World Cup"
unique_id: "World Cup"
value_template: "{{ now() }}"
json_attributes_path: "$['children'][0]['standings']"
json_attributes:
- entries
You placed a REST integration into the template integration. It is it's own thing.
yeah this i read out too, but no idea what exactly is to do :), maybe like this? https://github.com/theseal/SL-API-to-JSON-for-Home-Assistant-Restful-Sensor
yaml is not my world ^^
Your code has to go into the configuration.yaml directly and not into a template include. I guess that's what you are doing.
oh okay, i was trieing to move it in templates because i head its better
And then you likely have to check your indentation. But that might be me watching that on phone.
That's why I said it is not a template integration, but it's own.
okay, thank you 👍🏻
You were correct. It looks like the trigger just hadn't fired again. It ran successfully this morning. Thank you
Hello. Does anybody know how to deal with entities not being ready while starting up? Right now i have a sensor that throws up errros during startup since the entity referenced in its template is not ready for a while during startup.
i just tried this but no good:
- binary_sensor:
- name: Max Gusts Today Exceeded 30
device_class: problem
state: >
{{ states('sensor.weather_station_max_daily_gust') | float > 29.99 }}
availability: "{{ is_number(states('sensor.weather_station_max_daily_gust')) }}"```
I tried that based on an example in the docs
I used quotes like they did but not sure if thats right?
indentation is wrong
oh crap
I am testing it. Just ran into another problem during startup an integration is taking too long to start for some reason but will check back
Waiting on integrations to complete setup: {('alexa_media',
never had that happen before. its taking way too long
but it must be unrelated
Will HA eventually give up and move on to the next part of starting?
It just finally finished. And I got no value error so i thinks its working now I fixed the indentation! Thanks again Petro!
(Moved from automations at Tinkerer's request): Still having a bit of trouble with my sprinkler automation. Options 2-5 of my choose action work fine (I just added 5 this morning as a catch all because my yard isn't getting watered with choice 1 and it's been in the mid 90*s F for the last 1.5 weeks), however Option 1 isn't working at all. I got help with the template condition here, but I'm wondering if someone can take a look at the "final" YAML https://dpaste.org/XOhuz I built the automation on June 17th ahead of the time trigger.
The goal was to have a condition that made the 1st choose run every other day
When I test the template in Dev tools I get a string result of ' 0.0 '
at the start and end of the template you mean (I've never worked with templates before this)
?
OH I see that now.
"{{ .... }}"
so keep the double quotes and drop the single quote
outside that, it seems you're checking for every 1.5 days?
which doesn't really make sense
those aren't single quotes, those are backticks
it was to account for daylight savings
blind <--
it's meant to be a condition to have the automation choice 1 fire every other day when the time trigger is met
there was talk about how using "2" for the days would result in failure a small percentage of the year (daylight savings)
🫨
just change your time to be 3am
which only happens once a day every day
2am falls on DST which means it will be checked twice those days
or go 4am
to be safe
I run mine at 4:45am
ok. So the to do is: change the trigger to 3 or 4am (or just be fine with it not firing 2x/year) and remove the back ticks from the template?
that's what I'd do
cool, thank you petro, I'll give that a go!
value_template: "{{ (today_at().timestamp() // (60*60*24)) % 2 }}"
appreciate the help/patience
Just to be clear, the template should tick over to "2" at midnight correct?
it's showing 1 right now
oh as in on or off
it will change to 0 around midnight UTC
got it! Thank you.
are you GMT?
gmt -7
(truthfully I don't care what days this runs as long as it skips a day between runs)
sorry back
{% set offset = (now().utcoffset() - now().dst()).total_seconds() %}
{{ (now().timestamp() + offset) // (60*60*24)) % 2 }}
value_template: >
{% set offset = (now().utcoffset() - now().dst()).total_seconds() %}
{{ (now().timestamp() + offset) // (60*60*24)) % 2 }}
Your other option is to go with just the day of the year number
value_template: "{{ now().timetuple().tm_yday % 2 }}"
but you might get 2 sprinkler days in a row
between dec 31st and jan st
100% depends on leapyear or not
OK I'll give this a shot in a bit-- ironically I just had the pipe feeding my sprinklers break. I looked out back and water was shooting 10 ft in the air.
And you didn't setup a slip-n-slide? I'm disappointed in you.
oh there's still time haha
TemplateSyntaxError: unexpected ')'
add a paren at the beginning
thank you
I have a 2fer issue here. big one is I'm trying to add two integer numeric temps (a nominal temp + an offset) to get a max temp that I can pass to an automation to evaluate if the sensor temp is above the max temp. Images of my sensor configs are here https://imgur.com/a/AYmYrc4 and the state template for the max temp is {{ (states('input_number.day_temperature') + states('input_number.ac_offset')) | float(0) }}
The other issue is anyone know why I can't directly edit YAML on HA Container version for helpers?
it -looks- to my untrained eye like it's querying the sensors right, but pulling zero for both values (when it should be 73 and 3)
You need to convert the states to a float to add them. Now it tries to add two strings, fails and uses the default value of 0
ahhh. I saw somewhere how to do that ... give me a minute
You already did it. Just at the wrong place
{{ states('input_number.day_temperature')|float(0) + states('input_number.ac_offset')|float(0) }}
yeah, i'm just still learning HA's logic and syntax. It's a bit backwards from what I'm used to, like doing int(float)
Now we need to convert you to metric units and °C 
-I- can, it's just easier when talking to others local to me. Kind of like how I made a VPD sensor and even though I coded it in mPa, it keeps adding to the cards as inHg
unique_id: "gas_in_kwh"
device_class: energy
unit_of_measurement: kWh
state: >
{{states('sensor.gas_usage') | float(0) * 10.26 | float(0) | round(1)}}```
The state above gives data in the template editor, but the custom sensor outputs 'unknown'
To start, you're converting 10.26 to a float and then rounding it before using it in the calculation. You need to add parentheses
Second, every line after the first needs to be aligned with name:
Third, need to see the rest of the template sensor definition .
@inner mesa there all linedup in the code, just not on discord.
As for the other code, there is really nothing that is relevant to this part. There is sensor.gas_usage, which is a util meter in the UI that provides the data .
If you create a template helper, only put in the actual template, not the full YAML
the YAML is used when you create it in a yaml file
But if you want to use this on the energy dashboard, you should create it in YAML and add an availability template. Otherwise you will get spikes in the statistics on every restart of HA
I have this template sensor where state is time left when washing machine is running, 'Wash done' when it's done and blank state when door is open. Suggestions on how to prevent it showing "Wash done" if the door has been opened but then closed again? {% if is_state("sensor.vaskemaskin_washer_machine_state", "run") -%} 🌀 {{ time_until(states('sensor.vaskemaskin_washer_completion_time')| as_datetime) | replace('hours', 'timer') | replace('hour', 'time') | replace ('minutes', 'm') | replace ('minute', 'm') }} 🌀 {% elif is_state("binary_sensor.bad_vaskemaskin_dorsensor", "off") -%} 💦 Wash done 💦 {%- else -%} {%- endif %}
If you can’t determine the desired state by only using the current state of other sensors, then you’ll need a trigger-based template sensor. If you use a state trigger you’ll have access to a trigger.from_state variable, and you can also store information in the sensor attributes or look at the sensor’s own previous state (using this.state)
@visual gust I converted your message into a file since it's above 15 lines :+1:
You are not outputting anything here, only declaring a variable
Still not outputting anything
But I'm also not sure what you are trying to achieve
You already have a working sensor, you are just creating a new sensor with the same data
Okay, just do what they do then, you are declaring a variable hour but not outputting it
state: "{{ states('sensor.openweathermap_rain') }}"
Vs
value_template: >
{% set hour = states('sensor.openweathermap_rain')|float %}
Where are you placing this config?
I guess you are placing it in sensor.yaml but it doesn't belong there
You should place it directly in your configuration.yaml
Or create a separate template.yaml
This configuration is under the template integration
Which is still the wrong integration
That yaml belongs to the template integration, not the sensor one.
configuration.yaml
As TheFes said
sensor rain: !include rainmeter.yaml means you ar including a file under the sensor integration
the configuration for this trigger based template sensor is not working under the sensor integration
it's belonging to the template integration
so you can't put it in this rainmeter.yaml file
the only way to include mutliple integrations (sensor and template in this case) in one file is by using packages
To enable packages, add packages: !include_dir_named packages to your configuration.yaml so that it looks similar to this:
homeassistant:
...
packages: !include_dir_named packages
Important: The packages: line must be nested under homeassistant:!
For more information on packages, please refer to the packages docs: https://home-assistant.io/docs/configuration/packages/
Thanks!
no
That is a sensor, not a template
the statistics sensor does belong under the sensor: key as it is belonging to the sensor integration
All the HA documentation is written under the assumption that the YAML is placed directly in configuration.yaml. This means that the first line always contains the intengration. In this case sensor:
(you added template: yourself here)
Good thing: dog is already fed
Hopefully before someone feels insulted by that statement.
To make it more clear:
Your swearing and insulting is not appreciated.
It isn't even about anything HA related.
I think the main offense is the generalization. Be frustrated with the recall training of the dog instead (I have the same challenge)
unchecked_items: Ezekiel Bread, Salt, Eggs, Bread, Shredded Cheese, Chicken Wings
I have this shopping list. I am using Assist to remove items. I can do stuff like:
{{ trigger.slots.item | lower in state_attr(list_entity,'unchecked_items')|map('lower')|list}}
To check if the item is in the list. I want to remove the item if it is in the list, but I am not sure how to grab the value with the proper case. Removing from the list is case sensitive.
- service: todo.remove_item
data:
item: "{{ trigger.slots.item|title }}"
I can use this as I am adding with voice and using title case BUT if the user adds it manually there is no guarantee that the case will match
It's something like this:
{% if "eggs"|lower in (state_attr('todo.anylist_alexa_shopping_list','unchecked_items')|map('lower')|list) %}
true
{%- endif %}
But I don't know how to get the true value "Eggs" as the response.
Hope you guys don't mind me talking to myself 🙂
{%- for item in state_attr('todo.anylist_alexa_shopping_list','unchecked_items')|list -%}
{% if ("chicken wings"|lower) == (item|lower) %}
{{item}}
{%- endif -%}
{%- endfor -%}
So this works. Is this the best way though?
I feel like I provided a solution to this a while ago
I didn't look too closely at what you're doing there, but isn't that the same thing?
Hello, I am trying to figure out how to create a weather template that will give me entities and data to put in a weather card I found in HACS. Too say I'm not good with yaml is putting it mildly. I have installed the weather integration "tommorrow.io" and I had a person provide me with an initial template. I tried to compare it with a weather template I found in the HA community files. Honestly I'm not sure I understand if the template I have or the one I found works and what and if I am missing anything. Is there anyone that would be wiling to help me. I need a weather template that works with tommorrow.io integration. Any assistance or guidence would be appreciated.
Or just
{{ [ 'foo', 'bar', 'eggs' ] | select('search', 'EgGs', ignorecase=true) | list | first | default }}
result
"eggs"
Hi everyone, I’m having trouble accessing tomorrow’s weather forecast in Home Assistant. I’m using the weather.home entity with the met.no integration. The current weather data works fine, but I can’t seem to retrieve the forecast for tomorrow. Here’s what I’ve tried:
Current Weather (works fine):
{% set weather_condition = states('weather.home') %} {% set temperature = state_attr('weather.home', 'temperature') %}
Attempt to Fetch Tomorrow's Forecast (not working):
{% set forecasts = state_attr('weather.home', 'forecast') %} {% set tomorrow_forecast = forecasts[1] if forecasts and forecasts | length > 1 else None %} {% set tomorrow_temp = (tomorrow_forecast.temperature | int) if tomorrow_forecast and tomorrow_forecast.temperature else 'N/A' %}
This results in N/A for tomorrow's temperature. Any ideas on how to correctly fetch tomorrow’s weather data? Thanks!
you have to use the service weather.get_forecasts to retrieve forecast data
Thanks! can you show me an example maybe?
target:
entity_id:
- weather.home
data:
type: hourly
response_variable: response```
after that your forecast will be available in {{ response['weather.home'].forecast }}
is there a way to do it in a template?
Yes. Look at the first example here:
https://www.home-assistant.io/integrations/weather/#examples
i tried.. if i copy and paste i get this: "UndefinedError: 'hourly' is undefined"
You likely cannot just copy and paste it, but have to adjust it to your needs
if I'm not wrong you can't access the forecast attribute anymore from templates. You need to use the service
You probably pasted it to devtools>templates, which doesn't work as you don't have the response variable from the service call there
We really need a more elegant, combined solution for that
I’d love to see something Jupyter-notebook style, and we could choose each cell to be a template renderer, a device call, an event creation, or an event listener. And variables and template output would show below each cell
It is, and sorry. My mind is mush. I remember working on this a few months ago but did not remember I had posted this or that you had given a solution. I probably should search before posting. Apologies.
I have this:
{{ state_attr('sensor.viewassist_masterbedroom',"data") }}
which returns this:
{'list': 'todo.anylist_alexa_shopping_list'}
I want the value defined by list. How do I do that? I am planning to use this attribute to store a few different items. I thought this may be a handy way to temporarily pass data to the views.
You can use this to get the value of list
{{ state_attr('sensor.viewassist_masterbedroom',"data")['list'] }}
That's what I thought. I did try that and I get nothing. blank. It is probably how I am setting this value using set_state.py
Is there a way to return the type? I think this is being set as just a string
then something that you've said doesn't add up
you can test this yourself:
{% set test = {'list': 'todo.anylist_alexa_shopping_list'} %}
{{ test['list'] }}
Right. I am pretty sure the problem is in how I am setting the value:
service: python_script.set_state
data:
entity_id: "{{ target_satellite_device }}"
data: "{'list': 'todo.anylist_alexa_shopping_list'}"
I just tried without putting it in quotes and still does not provide a response. I have used this successfully to post a list but never a dictionary like this
using a python script to set a state in the state machine is just a bad idea
anyway, you know that you can confirm what attributes the entity has in
-> States
BTW, JSON requires double quotes for strings, so perhaps that's the issue
flip your quotes around
Yep. I know it's not a good solution. The problem is I have very little time to get up to speed to be able to write an integration. The goal for the project is to get something usable out there and people smarter than me might come in and do some clean up. I'm already seeing a bunch of folks helping with things so it's encouraging to think I might get some help with this. I think it's better to come out with a hacky solution that works rather than focus on finding a perfect one.
Tried this just now. The change is visible but no change in the output. Still blank
again, you can check what attributes the entity has
does it have what you expect?
my guess is that it just has a string that looks like a dict, but isn't a dict
you need to actually provide a dict in the attributes dict that you're providing in your python script
data: "{\"list\": \"todo.anylist_alexa_shopping_list\"}"
I think this is what you're telling me to check. I clicked on the entity name in dev states and it shows up at the top with all attributes. I had been looking in the column to the right with the attributes and it did not display those espace characters.
that's just a string
so it is a string and not an actual dictionary.
weird I am able to make a list without problem using the same script but not a dictionary. I guess it doesn't like the double quotes as the list is using single
https://community.home-assistant.io/t/propagating-all-variables-as-a-template-dictionary/624124/4
I'm not sure but this may be what I need to get it in the right format. I'm not certain I understand what the OP is trying to accomplish.
I don't entirely know what you're doing, but I just threw this together and it works fine:
entities = data.get('entity_id')
if not entities:
logger.error('No entity_id provided')
state = data.get('state')
if not state:
logger.error('No state provided')
foo_value = data.get('foo_value')
if not foo_value:
logger.error('No foo_value provided')
if isinstance(entities, str):
entities = [entities]
for entity in entities:
logger.info('entity_id: {} to: {}'.format(entity, state))
old_state = hass.states.get(entity)
new_value = {"foo": foo_value}
new_attributes={**old_state.attributes, **new_value}
hass.states.set(entity, state, attributes=new_attributes)
service: python_script.change_state
data:
entity_id: input_boolean.test1
state: "off"
foo_value:
foo: bar
blah: floop
{% set value = state_attr('input_boolean.test1', 'foo') %}
{{ value['foo']}}
-> bar
it creates or reassigns an existing key in the attributes of an entity to anything you pass in, including a dict
Thanks for the encouragement. I managed to do this:
service: python_script.set_state
data:
entity_id: "sensor.viewassist_masterbedroom"
data: "{% set data = {'allow_create': 'yes', 'entity_id': 'no', 'state': 'off'} %} {{ dict(data) }}"
and then:
state_attr('sensor.viewassist_masterbedroom',"data")['state'] }}
off
that's a far more complicated way of doing what I did in my service call above
I am already using a script. I tried using your service call example above but it did not work so I modified.
it's equivalent to:
service: python_script.set_state
data:
entity_id: "sensor.viewassist_masterbedroom"
data:
allow_create: yes
entity_id: no
state: 'off'
Let me double check. Maybe I did something odd
you're creating a dict, and then turning that dict into a dict 🙂
haha.. You know this is how I learn right? 🙂
service: python_script.set_state
data:
entity_id: sensor.viewassist_masterbedroom
data:
mystate: off
entity: todo.anylist_alexa_shopping_list
This works fine. I just am unfamiliar with syntax. I just don't know what I don't know. Again, thanks for your patience.
there are only two kinds of data structures in YAML
[1, 2, 3] is a list
foo:
foo: bar
``` is a dict
Well that makes it easy then. I'm glad I won't have the chance to mess this up any more than twice! haha
Soooo.. This gets me really close but not all the way. I need to convert:
{{ state_attr('sensor.viewassist_masterbedroom',"data")['entity'] }}
to javascript to use with button card. I can get this far:
list: '[[[ return hass.states[variables.var_assistsat_entity].attributes.data ]]]'
but not sure how to grab the value for entity. This returns [object Object] . I've tried adding ['entity'] after the attributes.data a few different ways but just get nondescript errors.
@bronze prawn The first entity that I found that has a nested attributes list is image_processing.demo_face. Right now, it has a state of Hans. These are the attributes: ```
faces:
- confidence: 98.34
name: Hans
age: 16
gender: male
entity_id: image_processing.demo_face
[...two more face examples but shortened here...]
total_faces: 4
device_class: face
friendly_name: Demo Face```
Using "[[[ return states['image_processing.demo_face'].attributes.faces[1].name ]]]" I was able to return Helena who is the second face (not shown in the code above.) Using 0 returns Hans.
Note: This entity is provided by the Demo integration.
@empty bone I converted your message into a file since it's above 15 lines :+1:
Oh, I didn't ask my question before hitting enter. My question was where do I place this yaml code for this view?
[[[ return hass.states[variables.var_assistsat_entity].attributes.data[0].list ]]]
I'm trying this to get to:
https://imgur.com/a/70970jC
but it's not working. Am I misunderstanding?
@bronze prawn That may go back to what RobC mentioned about the difference between a dict and a list. (I still don't completely understand the difference myself.) Notice the difference between your attributes and mine: https://i.imgur.com/f5zZpmP.png
ButtonCardJSTemplateError: TypeError: Cannot read properties of undefined (reading 'list') in 'return hass.states[variables.var_assistsat_entity].attributes.data.list'
I found another entity that might have a similar set-up as yours. "[[[ return states['sensor.persistence_tracker'].attributes.changes['light.all_lights']. This is a persistence tracker that I set-up in configuration.yaml. changes: light.all_lights: '2024-06-22T20:32:44.606108+00:00' light.office_lights: '2024-06-22T18:54:20.159015+00:00' [...shortened...]
[[[ return hass.states[variables.var_assistsat_entity].attributes.data['list'] ]]]
Is not allowed so I'm guessing also invalid
Are you trying to "load" the entire object or just a single value? You might need something like list[]: "[[[ return hass.states[variables.var_assistsat_entity].attributes.data['list'] ]]]" if you're trying to get everything into the list variable. Using list by itself (without the []) I think is the difference between defining a simple variable and a dict or list (again I don't know the difference.)
That's more of a #frontend-archived question. But, when editing your dashboard, Add Card button, scroll all the way to the bottom and select Manual and then paste that code. (This is assuming you have the custom:vertical-stack-in-card, card_mod, and the custom:weather-card all installed.) There you'll need to update the code with your respective entities.
I was hoping to pull just the value stored in list. By the way, it's not a list perse. It's a todo list entity just in case there was confusion. todo.alexa_shopping_list is the value that list holds that I'm trying to get.
Long story short, I'm trying to pull that value so that I can use it as the to do list entity for the todo list card so I don't have to build a view for every todo list a user might have.
Thank you for that tidbit of info. I knew my question was not going to fit in templates but it was part of my broader focus for building the weather template or trying to understand templates. Thank you for your direction.
Hi i was wondering if anyone could help me with this automation? I want to save the current state of input_select.acmode to current_state. Then perform an comparison of current_state and input_select.acmode. I am struggling to set current_state. Any pointers? Sorry if this is the wrong channel. Just redirect me thanks!
variables:
current_state: "{{states('input_select.acmode')}}"
value: "states('input_select.acmode')"
condition: template
value_template: "\"{{states('current_state') == states('input_select.acmode')}}\""
Is there a way to make a history stats based on the average of a entity's number of the last 2 hours? Or if not, simppy record what it was an hour ago, and what it was 2h ago?
Its not a linear graph i want to track though. Its a pirate weather entity of rain chance
Yes thats not really answering my question?
In all the examples in there you have to set a hour of the day. I want to track the last 2h.
Set start on start: "{{ now() - timedelta(hours - 2) }}"
Thanks Fes!
yes, that, or ```
end: "{{ now() }}"
duration:
hours: 2
thanks i got it. but how do i now make it track a numeric value and give me the average of the last 2h? what "state" (i suppose) should i put in there?
check out this other integration, this will probably help you achieve what you're looking for https://www.home-assistant.io/integrations/statistics/
thanks, thats looking great for my use case.
what happens if the entity behind a history stats or statistics becomes unavailable?
the statisticd or history stats also becomes unavailable? or shows 0?
anyone know why this sensor i made in configuration.yaml isnt working?
name: "Last 2 hours of rain"
entity_id: sensor.pirateweather_precip_probability_0h
state_characteristic: average_linear
max_age:
hours: 2``
the entity itself where it gets data from, is showing a percentage. now its 0%
the sensor i made shows "not available"
it started working when i added the percentile line to the template....but i can only fill in a number of 99? 100 is not allowed. what if the sensor reports 100 as percentage for 2 hours....?
Put on a swimming vest? 
How do i make a #automations-archived of that?
{{ (state_attr('media_player.living_room_speaker', 'source_list') | select('not in', ['Bluetooth', 'Line-in']) | list | random) }} it returns me an error
IndexError: Cannot choose from an empty sequence
TemplateRuntimeError: No test named 'not in'.
I got this using chatgpt: {% set sources = state_attr('media_player.system_speaker', 'source_list') | reject('eq', 'Bluetooth') | reject('eq', 'Line-in') | list %} {{ sources | random }}
How do I go abouts 'grouping` multiple lights to show as 1 using templates? For example: I have 4 lights in a group, and templates should report it is as 1 light
A template doesn't create groups. You could just use the group entity name (light._your_group_name).
I get that, I'm not trying to create a group, just wanting to print number of lights on
That's accruate. There isn't any 'not in' test. You could have gotten that just by reading the jinja2 docs though. All the tests are listed in the documentation.
so it will show, "1 light is on" instead of "4 lights are on". If I use groups it will always report as 4 lights on
At the moment I have this that shows amount of lights in a group:
{% set state= expand(states.light.living_room) | selectattr( 'state', 'eq', 'on') | list | count %} {% if state > 0 %} {{ state }} light on {% else %}Off {% endif %}
Ah, {{ expand('light._your_group_name') | selectattr("state", "eq", "on") | list | count }} will give you the number of lights on in a group.
Yup. That works.
could be even simpler
Yeh, but I don't think you got my initial post. The 4 light bulbs are part of same product, and each bulb is inside the living room group. This shows as 4 lights, I want it to show as 1 light on
{{ state_attr('light.xx', 'entity_id')|select('is_state', 'on')|list|count }}
Will that expand a light group though?
so 4 ceiling lights, should show as 1 light on
the entity_id attribute contains all the group members
Ahhhhh... gotcha... gonna steal that 🙂
might be a little less computationally expensive, but probably doesn't matter
That's what the group does already though. I have a light group (office lights) and only 4 out of the 12 lights are on. The group entity shows on. If you set All entities to true, then all lights in the group has to be on for it to show on.
Wouldn't you have to create a group within a group to do that? Example:
Hallway light group: 4 Ceiling lights, 1 Lamp
It will show as 2 lights on, not 5?
Nope. Just create 2 groups and if you have to, use All entities.
I do that in my office. I have the Office Lights group (with 12 lights) and a smaller Office Desk Lights that uses All entities set to true.
Ah, wasn't aware of All entities option, thanks! 🙂
No problem 
Hey folks - Was wondering if you could give me some quick help. I've been racking my brain trying to google for the right answer. I'm using the custom Hass-room-card and creating a template for the secondary property. The secondary property allows for templating.
I want to display the humidity with an icon. My yaml looks like this:
type: custom:room-card
name: Living Room
icon: mdi:sofa-outline
show_icon: true
show_name: true
secondary: |
{{states("sensor.first_floor_humidity")}} <ha-icon icon="mdi:water"></ha-icon>```
When the card renders the HTML is displayed and not rendered.
I'm missing something obvious. I was wondering if you could point me in the right direction.
Can someone please tell me how to get templated entity state/attribute value in scripts please. Tried different combination but nothing worked until now.
light_toggle:
fields:
entity_light:
selector:
entity:
domain: light
sequence:
- service: light.toggle
target:
entity_id: '{{ entity_light }}'
- service: tts.google_say
data:
entity_id: media_player.bedroom
message: "'{{ states['entity_light'].attributes.friendly_name }}' turned '{{ states['entity_light'].state }}'"
sequence:
- service: light.toggle
target:
entity_id: '{{ entity_light }}'
- service: tts.google_say
data:
entity_id: media_player.bedroom
message: |
{{state_attr(entity_light, 'friendly_name')}} turned {{states(entity_light)}}
Thats awesome @haughty breach You saved me. I never thought it would work without any quote. Even was searching internet until now. Have not got similar posts anywhere yet.
This resolved my issue. Thanks a lot
It's important to only use quotes where and when they are needed. Extraneous quotes can be just as bad as missing ones.
Help templating results from web service call
@haughty breach I respectfully disagree on avoiding quotes (in general). YAML will typecast some string values if they're not wrapped in quotes, which can lead to unexpected behavior
Though yes, if mixing single/double quotes, multi-line strings are a great alternative
it will not miss type cast
@random basin you might find this tool helpful: https://yaml-multiline.info/ There are multiple formats of multi-line strings for YAML. Yamlint can also be helpful, though I doubt there's a convenient way to integrate it with the home assistant UI.
unless it's a specific type, anytime there is a word, it will be a string
@mighty ledge there's a well-known example of this being an issue in the ansible world: file permissions. Specifying an octal number without wrapping it in quotes can sometimes convert it to base 10
but that has nothing to do with what we were even talking about...
nevermind the fact that there's a resolver after the fact for templates in home assistant
so the output result from your yaml may not match the result being found for the template resolver
this is why we have these rules pinned in this channel
I'm talking about general issues with unquoted inline YAML values. I acknowledge your point on Home Assistant -specific YAML though
well there's no reason to confuse the shit of people who don't know yaml
I wouldn't phrase it that way, but yeah, you have a point there as well.
I need some clarification, I'm trying to understand "templating" in HA. Is a template an automation? Or is an automation considered a template? Would a script be considered a template? And where do the templates reside in HA? or once created where would a user put them within HA?
A template is a template
it's all the information between template indicators
e.g. {{ ..... contents of your template .... }}
see the pins in this channel. One of the pins describes the difference between YAML and templates
Ok, so I saw the pin on how differentiate yaml from jinjia. So a person who creates an automation and then wants to "add a template" would go into the yaml code of the automation and add in the {{ ...template...}} portion to make it function? Is this correct? And it would get saved right back into the automations folder? The same goes for scripts?
Templates are only allowed in specific places
they can be used in specific areas of yaml
so your question doesn't make sense as they don't replace an automation or script
they suppliment automations and scripts
like a tattoo. You can't have a tattoo without skin to put the tattoo on. Well you can't have a template without the yaml to put it in.
You'd have to be pretty hardcore to get a tattoo of a template
And it should be correct. After rolling it out, it is read-only
curly braces around the BH
can someone show me an example of how a template condition appears in the UI of an automation (not YAML)? I've tried to get a template condition set 3 different ways with the help of people here (different templates), all of them test correctly in the development tools, but none of them actually work in the automation.
You should post the automation 🙂
Before anyone says anything, I know the automation is "extensive." Issue is still with choice 1 (always skips). Always defaults to choice 5.
"{{ (today_at().timestamp() // (60 * 60 * 24)) % 2 }}" << no spaces around the *'s
get rid of the quotes in the UI I think
Same. You don't need the quotes on line 31.
Well I think you want one pair of quotes when looking at it in YAML
It's weird, it's like it's doing some weird escaping thing.
Yeah, just before and after the braces, but I'm also looking at the // and scratching my head on that one.
So this: https://imgur.com/a/rI0qeIL
I'll give this a test and if it at least fires this time that will be an improvement
Thanks guys
You might need:
{{ ((today_at().timestamp() // (60 * 60 * 24)) % 2) == 1}}
I'm not sure if returning 1 is sufficiently truthy or not
it says it wants a boolean true to pass
what are you trying to achieve anyway, should it only run on even days since January 1st 1970?
I enter a description on my automations sometimes. Is it possible to fetch that data in a template?
I cant' find out if the description is an attribute (doesn't seem like it) or if there's some other way to use that data.
I'm trying to create a template sensor with triggers to show 3 states: Time left of washer, Wash done, Idle. If door has been opened after a wash and then closed, the state should be Idle. But ideally I want it to work even if HA restarts. Worst case it must show Idle after a restart and the door is closed, not Wash done. I can't get it to work properly. Help? 🙂 https://pastebin.com/QP32L0GA
no, that's not possible
Hi, I would like to create a template sensor for sensor.sun_next_dusk - 10mins. I am currently struggling to build the template - can anyone help please. Sorry new to all this!
the template will be:
{{ states('sensor.sun_next_dusk ') | as_datetime - timedelta(minutes=10) }}
wow, that was so quick, thanks! missed the timedeleta part
you can create a helper in the GUI and apply the state class timestamp
then you can use it for time triggers
do I need a unit of measurement
no
works, thansk so much Fes
I can't get my head around this. Can I change it to only show Wash done when sensor.vaskemaskin_washer_machine_state goes from run to stop and else show Idle?
you can make it a lot easier if you just add more triggers
what does sensor.vaskemaskin_washer_completion_time show when the washer is not acive?
and what does it show when it is active
When wash is done it's set to 3 hours later. I had a wash done 18:32 and it was then set to 21:15. Today at 08:43 it was set to 11:26 even though I haven't put on any wash.
When active it shows the time when wash is done
Don't understand why it suddenly set that at 08:43 today. I did nothing. Perhaps an update to Samsung servers.
Current state is 2024-06-25T09:26:14+00:00
So yes 🙂
Yes. I think it's mostly idle unless a new wash is put on. When that happens it would say something like 2024-06-25T12:26:14+00:00
okay, you just said it was 3 hours in the future when there is no wash active
or that only happens at the moment the wash finishes, and then it remains the same until a new wash is turned on
Yeah, that seems correct (except for that fluke this morning at 08:43 where it set the time to 11:26)
did you restart HA at 8:43?
My sensor.vaskemaskin_washer_machine_state has been 'stop' since 18:32 yesterday
so you want it to be idle after the washer is done, until the door is opened
No restart.
after the door is opened, you want it to be wash done
No. Wash done when washer is done until door is opened. Then Idle.
okay
The problem I've had is if the door is then closed again. Then it would show Wash done. I don't want that.
you can try this:
https://dpaste.org/Q2qNz
Will do. Thanks!
Maybe the wife can put on a wash 😆
Hm. I put it in and restarted and got Invalid config for 'template': expected str for dictionary value 'to', got None. The template sensor itself is unavailable.
sensor.vaskemaskin_washer_machine_state is stop, binary_sensor.bad_vaskemaskin_dorsensor is on, sensor.vaskemaskin_washer_completion_time is 2024-06-25T09:26:14+00:00
@distant plover no need to restart, just reload template entities
to: on on line 13 should have been to: "on"
Good tip on the reload template. I'll remember that. And "on" made it work. Thanks. 🙂 Will do some testing.
I'd like to do a clean up in my system and find any references to entities that doesn't exist any more in automations and scripts. I know how to write a template for listing all entities that do exist.
Can I somehow do it the other way around, like searching automations.yaml and scripts.yaml for non-existing entities (with a template)?
AFAIK, there is no way for a template to be able to parse files. But, you could use Spook (https://spook.boo/) to find things that are missing easily.
Thanks, I'll have a look there!
Ok, that's magic. Exactly what I needed. Thanks.
Spook is awesome.
I'm working on a template that looks at Calendar entries to check for label entries. The idea is that if a calendar entry has a location label assigned, and that location contrains the word "Office" the code should return a 1, otherwise it should return a zero. I'm looping through all calendar entries and labels to do this. I've been using AI, but it cannot figure out how to make it work. Perhaps I can get better luck with actual people? - Here is the code I have that does not work properly. My best guess is that Jinja2 sees 'result' as a global variable outside the loop and as a local variable inside the loop, but that's a guess.
@dark epoch I converted your message into a file since it's above 15 lines :+1:
that code just looks at a curated list of things. It doesn't look at any entities.
as for why that code is failing, you need to use namespace to store values that update within loops
e.g.
{% set ns = namespace(result=0) %}
...
{% set ns.result = 1 %}
...
The result is: {{ ns.result }}
Sorry, I copied the AI code example trying to fix it, this is the code looking at HASS:
{% set result = 0 %}
{% for entry in states.calendar %}
{% for label in entry.attributes.labels %}
{% if "Office" in label %}
{% if entry.attributes.due_today == true %}
{% set result = 1 %}
{% break %}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
But I will try the namespace fix now
same issue regarding the namespaces
entities do not store labels in attributes
and labels is no attribut... 🐌
If I put {{ label }} inside the second loop, it does return the correct label value
Is this an unstable way to access that label?
that's just not a way to access labels
no idea how that is working for you.
as it's not a thing that works.
The namespace fix actually got it to work, but I do want to fix the label access so it doesn't break with the next codefix
You're not accessing any lables though. Nor any entities. How are you planning on building your calendar entries?
he's accessing calendars in his second post
but he's also accessing a made up attribute
Here are the attributes I see in the States viewer for the calendar entry:
friendly_name: Scott to Work
message: Scott to work
all_day: false
start_time: 2024-06-25 06:09:21
end_time: 2024-06-25 07:09:21
location:
description:
due_today: true
overdue: true
all_tasks: Scott to work
priority: 1
labels: Andon Office Blue
what integration?
Todoist - the tasks automatically show up as calendar entries
since the tasks have far fewer details
It's a HA integration and not HACS if that is what you mean?
labels are set in Todoist
ah ok, so they are not HA labels, that's the confusion here
Oh! - yeah, I forgot HA created their own labels
that attribute is not normal, and don't associate that attribute with HA labels
if you add other calendars, that template will fail because that attribute doesn't exist
It doesn't seem to, here is the calendar entry right below that from the Holiday Integration:
message: Independence Day
all_day: true
start_time: 2024-07-04 00:00:00
end_time: 2024-07-05 00:00:00
location: United States, NV
description:
friendly_name: United States, NV
for labels in entry.attributes.labels seems wrong here, at least with that example you gave
{% set ns = namespace(result=false) %}
{% for entry in states.calendar if entry.attributes.labels is defined %}
{% for label in entry.attributes.labels %}
{% if "Office" in label %}
{% if entry.attributes.due_today == true %}
{% set ns.result = true %}
{% break %}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
that will work for only todoist calendars
there is only one string in that labels attribute, so for label in entry.attributes.labels will split that up in the individual characters
that's not necessarily true
the states table doesn't make lists of strings look nice
it's most likely a list at all times but the states table "pretties it"
could be
I really hate the states table's attributes parser
unless they copied it from the overview after clicking the entity_id. That will show it as a list
Yes, Todoist Labels come over as a list
friendly_name: Scott to Work
message: Scott to work
all_day: false
start_time: 2024-06-25 06:19:21
end_time: 2024-06-25 07:19:21
location:
description:
due_today: true
overdue: true
all_tasks: Scott to work
priority: 1
labels: Andon Office Blue, Andon Bar Blue
Here it is with two labels - This should return 1 if the code looks for "Office" and 1 if the code looks for "Bar"
FYI @marble jackal here's a screencap of a list with 1 item from a select entity
and here's one with multiple options
aka, hides the list with 1 option
So do I need to change this line: "for label in entry.attributes.labels"
yeah, I kinda assumed he copied from this:
I already fixed it for you
use this
I don't understand. I thought accessing entry.attributes.labels was the issue but it also shows in your code
Is it ok to use as long as I am filtering out undefined entries?
right, but look at the added if statement 😉
Ok, but I thought the whole issue was that this is a non-standard way to access that data. Did I misunderstand, or was that the confusion about Todoist Labels and HA Labels?
the confusion was about todoist labels and ha labels
Got it - Ok, thanks for the help!
This worked! It did need the extra “truthy”— thanks for the help!
message: The forecast is {{ states('weather.forecast_thuis') }}
{{ attributes('weather.') }}
Can i get attributes from a entity this way?
i dont know anything from templates XD
Attributes
temperature: 23.1
dew_point: 18.4
temperature_unit: °C
humidity: 74
cloud_coverage: 0.8
pressure: 1012.4
pressure_unit: mbar
wind_bearing: 81.8
wind_speed: 8.6
wind_speed_unit: km/h
visibility_unit: km
precipitation_unit: mm
attribution: Weather forecast from met.no, delivered by the Norwegian Meteorological Institute.
friendly_name: Forecast Thuis
supported_features: 3
ah works like this
"{{ state_attr('weather.forecast_thuis','temperature') }}"
Another question did some1 get it to work to send a todo-list as a notification?
I wanna use it as a grocery list, and when some1 enters the zone of the supermarket it needs to send that notification to the device of the user who entered
I've tested it a bit now and understand more of the template and I realize that the trigger to update time left only triggers when the state of sensor.vaskemaskin_washer_completion_time changes. How can I change it so it's updated every minute basically (since I want to see time_until and not what time it's done)? I don't want the state of the template sensor saying it's 59 minutes left and the next minute it's 'Wash done'. 🙂 https://dpaste.org/Rx37c
Don't need one minute interval but I want it to be updated according to time_until. {{time_until(states('sensor.vaskemaskin_washer_completion_time')| as_datetime)}} is now 30 minutes but {{states('sensor.vaskemaskin_complication')}} is 🌀 1 time 🌀.
use the todo service calls that gets your grocery lists. It's a responding service, so you'll have to treat it that. I.e. call the service, use the response in your notification.
add a time pattern trigger
Ok. But do I understand this correctly, if I don't have any triggers the state of a template sensor is 'live'? If you understand what I mean, hehe
sorry, i don't understand what you mean
typically, it's not a good idea to have a state constantly update based on time
If I have just this it will update constantly, wouldn't it? sensor: - name: Vaskemaskin complication unique_id: vaskemaskin_complication state: > 🌀 {{ time_until(states('sensor.vaskemaskin_washer_completion_time')| as_datetime) | replace('hours', 'timer') | replace('hour', 'time') | replace ('minutes', 'm') | replace ('minute', 'm') }} 🌀
it would update once a minute
again, you typically don't want that to happen
it will just flood your database with useless data
that's why things are left as a timestamp
and if you want a notification, then you perform the math in your notification
if you want the time displayed on the frontend, you keep it a timestamp sensor and display that in the frontend. It will countdown without state updates.
I see. All that makes sense. My issue is that I want to display it as a complication on my WearOS watch. And there I can only show the state of a sensor.
and you haven't put the completion_time on that?
I'd try that first instead of what you're doing.
The idea was to avoid having to calculate myself how much time is left by looking at two timestamps 😛
right, but there's no reason for that because the UI typically does that for you with timestamp sensors.
the whole point of timestamp sensors is to show a relative time that counts down or up in the UI without having state changes
It looks so cool though. 😆 https://imgur.com/a/YhpptHt
I really don't think you're understanding what I'm saying.
if you put the timestamp sensor there, it will show up as a relative time
Hold your horses. Must try! 😄
Well, it works like you said. But I can't tweak it to my exact preference. Like surrounding emoticons. And '40 m' instead of 'om 40 minutter'.
How do I hide | separator, to only show when the second line of code is present (light count)?
expand(states.light.kitchen) | selectattr( 'state', 'eq', 'on') | list | count
%} {% if state > 0 %} {{ state }} light {% else %} {% endif %}```
move it inside your if statement
Ah lovely, thanks
@tawny coral I converted your message into a file since it's above 15 lines :+1:
I've tried executing it normally but it still doesn't run "option 2" which is to turn on 1 ac and set the FTX to high
when i check the timeline it says "Choose: no action executed"
So the question then is, is this an incorrect template?
action:
- choose:
- conditions:
- condition: template
value_template: "{{ trigger.to_state.state | float > 23 }}"
sequence:
- type: turn_on
device_id: 71335c8dc91194f73296da6293294841
entity_id: 983f94b37c36bb0df51bfcf66a13c096
domain: switch
- service: switch.turn_on
data:
entity_id: switch.vsr300_man_high_mode
why not use trigger id's?
template should work though, I would advice to use numeric state triggers instead of device triggers
Is there a less-kludgey way to say:
(175 < state_attr('light.night_lights', 'rgb_color')[0] < 185) and
(5 < state_attr('light.night_lights', 'rgb_color')[1] < 15) and
(245 < state_attr('light.night_lights', 'rgb_color')[2])
}}```
A way to see if an RGB value is 'around' a certain set of values? Better yet, 'around' a certain color name?
@unborn acorn I converted your message into a file since it's above 15 lines :+1:
not really.
@unborn acorn assuming you mean you want to use target? value_template: "{{ target == 'Option 1' }}"
yes. thx that worked!
@unborn acorn I converted your message into a file since it's above 15 lines :+1:
trial and error {{ target_position }}
whatever you name the field is the variable that is used, if you use it. In your case, you named the field target_position, so that's the variable you use in your script.
Another question, is it possible to change color on an icon based on a helper variable or a sensors data?
With card mod, yes. #frontend-archived can help
thx
Any way to do element-wise addition of lists or tuples without looping? i.e.
(1,2) + (3,4) = (4,6)
Or maybe zip that i still haven’t gotten to making a pr for. Maybe in a few months…
You can still do a half-ass zip
for x in y:
set a, b = x
or for a, b in y
sorry, brain fart on that last response
yes zip
implementation is quick, testing would be a PITA
You can abuse dict():
{% set x = [(1,2),(3,4),(5,6)] %}
{% set d_x = dict(x) %}
{{ (d_x.keys()|sum, d_x.values()|sum) }}
Edit: Fixed making the dict twice