#templates-archived
1 messages · Page 128 of 1
It looks like i am getting a comma separated list back but it only cleans the first room in the list then says cleaning complete.
I'm using a paper-button-row that has an icon and I'd like to add temperature from another entity. I saw that i can use jinja2 to pull the state of a thermometer i have in HA but I want to add the degree Fahrenheit at the end, how can I achieve that?
I am displaying the temperature with this: {{ states(''sensor.philip_sensor_temperature'') }} how can I add the units at the end?
a quote for the ages:Tinkerer — Today at 1:50 PM
Quotes... you're missing quotes
any way to get a name from an entity id?
trying to get the name of an entity from trigger.entity_id
trigger.name ?
Or trigger.to_state.name
I have a template that list all unavailable entities {{ states | selectattr("state", "in", ["unavailable"]) | map(attribute="name") | list | join(", ") }}
That works fine, but I'd like to show the name of the device - and only once - instead of the friendly name for every entity. Is that possible?
So you want the name and not the friendly_name (if it’s set)?
If so, why?
Oh, you want the name of the device that the entity comes from?
I don’t think that’s possible from a template.
Exactly so. Would be neat in the GUI. And ok, thanks anyway.
Devices were bolted on later and I don’t think they’re exposed in Jinja (yet?)
going nuts over this calculation. I'd want the end result to be an integer... Please help
{% set dim_light1 = ' | int / 2 | round(0)' if (states('sensor.period_of_day') in ['day', 'morning', 'evening']) else ' | int' %}
{% set d = (states('sensor.brightness_hallway') + dim_light1) %}
{{ d }}
ah, tried with int, which didn't work. will try
{% set d = (states('sensor.brightness_hallway')|float + dim_light1) %}
Oh, you’re trying to put a set of filters into a variable? Does that even work?
I would assume not
I am trying to divide the value returned from sensor.brightness_hallway pending the state of sensor.period_of_day...
the start value will differ so static values would not work
Right, but I doubt you can put filters (I.e., logic) into a variable like that
No, agreed. It does not seem to be interpreted as I need them.
You’d need some sort of eval() or similar
Ah? Jinja can do that??
Maybe? Don’t know
I would just repeat it with the proper filters based on the time of day. You’re not really saving much
You can use a variable for the state to shorten it
I have a template that is returning ['00:00:00', '00:50:00', '05:40:00', '09:00:00', '18:50:00', '22:40:00'] I want to know how to return each one seperately. i.e. using a for loop. Can this be done?
I am using https://github.com/nielsfaber/scheduler-component that is returning that array.
Yes, there’s an example in the default text in
-> Templates
Depends on what you want to do with each item
I looked at the example. I did not see what I need, I am getting those times from a state_attr I want to be able to know that eg state_attr('switch.schedule_ac_schedule', 'times',)[1] is 00:50:00 and that there are 6 times.
I tried:```
{% for i in state_attr('switch.schedule_ac_schedule', 'times') %}
{{ state_attr('switch.schedule_ac_schedule', 'times',)[i] }}
{% endfor %}
Again, depends on what you want to do with them
The loop in the example doesn’t use an index, it iterates through a list
Go back and look again
I want to be able to reference the actions that match the times. state_attr('switch.schedule_ac_schedule', 'actions',)
How do I use an index?
Sorry for being thick-headed I'll try to look again and figure it out.
that's what I meant about "what you want to do with it". If you want to match two lists based on indices, then looping on an index may be the best way to do it
How can I loop on an index? I'm trying to figure it out. I'm poking in the dark because I don't know what to do.
this matches up two lists:
{% for day in state_attr('weather.upstairs', 'forecast') -%}
{{ day.condition ~ state_attr('weather.downstairs', 'forecast')[loop.index-1].condition }}
{%- endfor %}
the general concept is iterate through one list and index into the other
thanks for reply, the update is every 60 second if there is a updated value
loop.index is what I needed, But even if I found it I would have been thrown off from the fact that the index starts at 1 but is index[0]....
I got tripped up by that first and then added the "-1"
Then you need at least 1440 samples.
ok, but i integrate the sensor before midnight, it will reset the next day at the same time. But since I would need a sensor that would give me a value for the previous day, I would not have solved anything like this, since the irrigation would start at 05:00 the sensor would have already reset, is that correct?
No. You're still not getting it. If you set the max age of the statistics sensor to 24 hours it can cross midnight. If you read the stats sensor at 5am it will give you the max value for a 24 time period to 5am the day before. Not to midnight.
ok thanks, now I understand! 😅
What exactly does the following line do... is default something user defined.. or is it some built in function in jinja?
{% set attributes = states.sensor.template_sidebar.attributes | default %}```
Default is a filter. They're a Jinja thing and well documented on the Jinja site.
Is it possible to make a group or template that show which doors have been open/closed instead of showing open/closed in the history log.
Any change to show or explain how? Tried for hours making this but don’t succeed.
Already have a group.doors.
{{ expand(state_attr('group.doors', 'entity_id'))|selectattr('state', 'eq', 'on')|map(attribute='name')|list }}
might need to adjust that state check
Already tried that but the thing is it won’t show a history on my card, instead it shows a colored bar…
And I can’t use this in a binary_sensor or add a device_class to the template.
right
that wasn't in the AC of your question
you might need to do a |join(', ') at the end to make it text
it might render then
Yeah sorry about that. It’s just strange that a simple thing like that isn’t possible. 🙂
Yep but that way it shows open/closed instead of the door name(s).
trying to use this for something in particular?
Yeah I made a single custom button card that shows the state of my doors and if all are open it shows all doors open. If I now use the more-info to view the history it shows just a colored bar instead of the usual history with which doors have been openende/closed (like a normal card with a single entity will do).
could do this to force it:
{{ ', '.join(doors) if doors|length > 0 else 'Closed' }}```
that way there's always something returned
so then you'll have an entity that will always have the names
group itself will be on if any of the doors are open
use the 2 together to inform
Thanks! Will give it a try in a template and see if this will show the history log instead of the colored bar.
you'll probably still get a colored bar but there should be text in there
Oh, that’s what I already have accomplished. 🙂
Maybe I just have to forget that nice history view. 😉
i mean, there are only 2 ways to render data there. Colored bars for states or graphs for numeric sensors
Can’t post a screenshot here I see but what I mean is a history log like a single entity that shows all the states from the entity, like frontdoor closed 10pm, opened 11pm, etc.
you'd need to look at the lines for the entities themselves
Yeah if I press the entity in the colored bar I can see it but really like that quick overview log from a single entity.
Maybe it something I can ask to implement…
i think if you want something more complex you're going to have to start looking at graphana
but #analytics-archived for more on that
Thanks for your time and patience, really appreciated! 👍🏻
np
is config code enclosed in [[[ ]]] brackets also templating or is that something else? not easy to google for [[[
Need more context
[[[ return entity === undefined ? 'rgba(255, 255, 255, 0.3)' : '#efefef'; ]]]```
as an example
Seems like #frontend-archived stuff
cool ty
I'm struggling a bit with rounding... If I only do {{states('sensor.somesensor') | round(1) }} it works as I expect it to do, but {{states('sensor.somesensor') |float/100| round(1) }} does not (all decimals show). I'm probably misunderstanding something, but I'm too stupid to figure out what.
try {{ (states('sensor.somesensor') |float / 100) | round(1) }}
you're rounding the 100 currently
Oh... thanks.
How can I find out what triggered an automation? I was told it could be done with templates?
Like, in the automation while it's running, or after the fact?
Right, should have mentioned that. While running
Any template in the actions of an automation will have access to the trigger variable. So you can do things like {% if trigger.entity_id == "light.bed_light" %} etc. https://www.home-assistant.io/docs/automation/templating/#available-trigger-data
Cool, would it be possible to determine if it was invoked by another script or manual even?
Ok, will do some testing. Thanks for the help! 🙂
I like using the system_log.write service for testing out this kind of thing. Then you can print variable contents to the log and see what you've got to work with.
but if an automation is "manually" triggered from the UI or via automation.trigger, there's no actual trigger and any references to trigger variables should fail
maybe you could detect that with {% if trigger not undefined %} or similar
Good advice, and the log service should prove useful, thanks again! 👍
Or work around it with the default filter.
default filter?
https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.default {{ some_variable_that_may_not_exist | default(43) }}
Thanks! Hadn't heard of that before, will check it out! 🙂
Sounds really useful, and a great jinja-resource page as well! Thanks a lot! 😄
It's the jinja resource. Usually first hit when you type "jinja3" into google too.
Also linked to from the pins in here.
Oh. You even updated it for 3.0. Nice.
Just now. Noticed the link you shared wasn't the same.
Hass is running on 3.0 since 21.6 apparently
also the bot message
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
goes to latest
Hi, very basic question. Trying to understand how to get attributes that are deeper than the root. e.g. {{state_attr('weather.home', 'temperature')}} works and gives me 27.1 which is easy as its only one value.
However {{state_attr('weather.home', 'forecast')}} give me a JSON blob like https://hastebin.com/rurasivuna.yaml how would i go about getting to the data for tomorrow like this https://ibb.co/4tXrwP9 instead of the full JSON blob? (the data is from accuweather)
I'm hoping for some help. I have a fan that really needs a quirk update. However, thats way beyond my skill set. So I'm trying to create a fan template as a bandaid. I've gotten presets working, but I'm failing to understand how to make the percentages work.
@sonic pelican posted a code wall, it is moved here --> https://paste.ubuntu.com/p/kpY6hRKV7V/
Oops. Thanks bot! Anyway, that's what I have. But when I slide the percentage input, nothing seems to happen.
n/m I think I may have figured it all out. https://community.home-assistant.io/t/king-of-fans-mr101z-missing-max-setting/267131/15?u=flyize
Can anyone tell me why this line works when I test it in the template developer tool
{{ float( states('sensor.stikkontakt_7_electric_consumed_kwh') ) }}
but when I add it to my script
service: input_number.set_value
target:
entity_id: input_number.vaskemaskin_kwh_forrige
data:
value: '{{ float( states('sensor.stikkontakt_7_electric_consumed_kwh') ) }}'
I get the error message
Failed to call service input_number.set_value. expected float for dictionary value @ data['value']. Got None
Your quotes are wrong. The second quote will close the first one, leaving a whole load of gibberish after it.
You need to mix quotes. Either use single outside and double inside, or vice versa.
So.. I have a list of lights i use in a template listed as states.light.name, I really don't want to have to go into the template to update it each time i add or remove a light.. I do have a group with all lights, is there a good way to use that as a source for the list?
yes, use expand()
cool I'll have a look at that
Thank you. Suddenly I understand a lot more. 😄
Is there any way to extract a previous state from the history (or otherwise) using templating?
The straightforward way is via the from_state of a trigger, but it’s pretty limited. You could also use the SQL sensor, I think
But that’s not straightforward
but the more important question is "what are you trying to accomplish?"
I have Tibber integration which gives me the hourly electricity rate. Whenever the rate changes I want to use the previous hour's rate to calculate costs on my various appliances.
Crossposting this groundbreaking template here by popular demand:
@mental coral Here's a template that looks up a friendly_name based on a user_id:
{{ states.person|selectattr('attributes.user_id', 'defined')|selectattr("attributes.user_id", "==", "xxx")|map(attribute="attributes.friendly_name")|list|first|default }}
Given how often somebody has asked that...
(now you just need to edit it to use code markup 😛 )
yeah, I guess that was lost in the copy/paste
its too bad comprehensions aren't a thing in jinja
users = {x.attributes['id']: x.attributes['friendly_name'] for x in states.person}
print(users.get(trigger.whatever)
I ♥️ comprehensions
No comprendo.
Mindblowing when I first saw them in python
I call them ‘turn 15 lines of code into a single line’ magic
haha
sometimes I go too far 🙂
map = [
self._get_key(k)
for k in self._entities[self._object_id][ENTITY_MAP][self._lm.model_name]
]
return {convert_key(k): convert_value(k, data[k]) for k in map if k in data}
have this gem that i'm kinda proud of
or this:
final_payloads.extend(
[
{"uri": uri, "devices": {"devices": cat_payloads[i : i + chunk_size]}}
for i in range(0, len(cat_payloads), chunk_size)
]
)
Hey all! Just a quick question I don't quite understand with the newer templating. I have created sensors for the purpose of taking a value from attribute from an entity. But not quite sure some sensors are shown as "Unavailable", but also will not change even when the data from the referenced entity changes.
Hmm... how do you do code formatting here? 🙂
@mighty crystal posted a code wall, it is moved here --> https://paste.ubuntu.com/p/zbbhvCwTcY/
Can a guru kindly point out what I have done incorrectly? Is it because those attributes were not ready at the time the template tries to populate the values?
We have gurus? 🤔
Hmmm.... wiser ones 🙂
Are you able to help? Thanks! 🙂
No, and don't tag me...
No worries mate!
Change sensor to sensors. Then remove all subsequent sensor lines and add a dash before each name.
The docs cover this btw
In the examples
Thanks for answering my question petro. I thought the "sensors" format is legacy config format? Do you mind pointing out to the doc with this particular one by any chance? I did try to search for a bit but couldn't find a reason why.
The sensors will populate, but behave differently depending on how many sensors I create, which is bizzare.
you are using the "new" format, which is now recommended, but the point is that it's expecting a list of sensors
the first example here shows multiple sensors in a list:
you can ignore the trigger: section if you don't need it, and just start with - sensor:
Thank you for taking the time to point out!! I did misunderstood the format.
something like this: https://pastebin.ubuntu.com/p/c9mshwvbQM/
Can template be used in packages?
Ohhh... that's probably what has let me to do it differently in the first place.
- led
the introduction of the new template style has brought all the package users out of the woodwork
May be I should stick to the 'old" style if I want to keep things neat in a package like what I do with climate?
all of mine are still the legacy format and I see no need to chagne
Thank you once again for your wisdom.
in my config file, if i have ```value_template: |>
{{ don't use me! }}
{{ use me! }}
aka, is this the right syntax for this
Check here, lots of great info. https://jinja.palletsprojects.com/en/3.0.x/templates/#comments
Hi everyone, im not quite sure where to start but guessing this would be the right channel. it's been quite a few years since i've actively used hass. I have a particle.io shield which controls 4 relays, which controls 4 water-sprinkler channels. I can successfully using curl turn on/off the 4 channels. however im struggeling with how hass has intended to implement this.
Ideally i would like to have the option to turn on/off the channels manually, which led me to Switch, and Template?
I would also like to have an automation, that based on rain report will turn on/off the channels with a timer.
To start with i thought i would just create something basic, like either a "channel 1 on" "channel 1 off" button, or a toggle switch.
I updated configuration.yaml with: https://pastebin.com/zLSHfA9x
I'm not looking for someone to do this for me, just asking for help on what things i should read up on and how to tie them together.
how to get in template value those two values :
The forecast is {{ state_attr('weather.home','???????') }}
{{ state_attr('weather.home','forecast')[0].condition}}
hello all i would like to use the icon of one entiy on other with template... i tried "icon_template: "{{ state_attr('cover.livingroom_cover1', 'icon') }}" but does not work
is there a way to limit an attribute output? i have an entry with date and time but only need the date
There's a way to extract what you need with a template
I have already read the attribute,{state_attr('garbage_sensor_3', 'start_time')} , but I don't know what to do next
"2021-06-24 00:00:00" is my output
i don´t need "00:00:00"
{{ state_attr('sensor.garbage_sensor_3', 'start_time').split(' ')[0] }}
your sensor entity name was incomplete, so I guessed
no it was not incomplete there is an variable with the real sensor name
ok
thanks that works
then you shouldn't have quoted it
i rewrite an blueprint to work for me, it was wrote from an other guy
ok. my point is that 'garbage_sensor_3' in state_attr('garbage_sensor_3', 'start_time') isn't referencing a variable
ok
ok now we have to wait until the event happens, it should be ready next week wednesday
- conditions:
- condition: template
value_template: '{{ trigger.entity_id == "sensor.v1_badkamer_switch_nr_1" }}'
how can i rewrite this to match ON state
im not familair with the syntax
so i have 2 switches hooked up to sensors. both have an ON and OFF state
i would like 4 conditions.
sw1 ON
sw1 OFF
sw2 ON
sw2 OFF
because then i can disable a motion sensor automation messing up with light on timer
(i think)
probably overthinking it
Automation 1:
2 state triggers
s1 to on
s2 to on
actions
start timer
turn on light
Automation 2
1 state trigger:
motion to on
condition: timer idle
actions: turn on light
(optional): restart timer
Automation 3:
1 state trigger: motion to off
condition: timer idle
action: turn off light
Automation 4:
event trigger: timer.finished
condition: motion off
action: turn off light
2 and 3 can be combined with choose in actions
all of this can be done without templates actually
Hi. I'm working on using templating for the first time. I'm still pretty new to HA. I'm very close, but trying to do a while statement that watches the device that was involved in the trigger. Can anyone help me understand what I need to change?
@nocturne nexus posted a code wall, it is moved here --> https://paste.ubuntu.com/p/8WdfR8Gb2C/
I think everything works great except line 22 to stop the repeating only while the triggered sensor is reporting wet.
*only when the triggered sensor stops reporting wet
hey templaters....
I want to create a sensor that shows how much my energy consumption is costing. I know its a sensor that is the multiplication of the power consumed (kWh) by the cost per kWh, but no idea where to start with making the template. any help would be great.
value_template "{{ ( states('sensor.your_kwh_sensor')|float * states('input_number.your_cost_per_kwh')|float )|round(2) }}"
thanks Tom, and the input_number, I am not 100% sure how to set that up, it has a min 0 and max 100 value as default, but unsure where I should be putting the $ value there...
in the UI anyway...
Does it not have a 'Unit of Measurement' field?
oh, thought that was for $/kWh
The template above is for $/kWh. If you use cents/kWh change it to this: value_template "{{ ( (states('sensor.your_kwh_sensor')|float * states('input_number.your_cost_per_kwh')|float ) / 100 )|round(2) }}"
You don't get charged between $1 and $100 per kWh !! You get charged something like 29c per kWh. So either change the min and max to 0-1 and enter the cost as 0.29 or leave it as is and change the unit of measurement to c/kWh. In both cases don't put a step size (it's optional) and change the type from slider to input field to allow you to type in a value.
right now I get it.... have hit input field though and nothing has changed...
Reload helpers?
perfect
lets give it a crack
hmmm, its returning 0.0
value_template "{{ ( states('sensor.kitchen_fridge_smartplug_energy_total')|float * states('input_number.energy_cost')|float )|round(2) }}"
Did you put a number in the input number?
The imgur URL? Yes 😆
fmd
haven't even had 3 tins tonight....
oh f me....
i just realised...
thats better
i thought you meant that the pic was showing i had entered the wrong settings
Delete the step size. You aren't going to get a price increase of exactly that value. Now put the input number entity in Lovelace and fill out the value there.
you beauty, all working now
Hi. I've been struggling for a few days to understand how to use a template. I've done a lot of reading, searching and can't figure it out. I'm probably missing some simple concept...
I'm trying to set a routine to warn of water leaks without typing in every leak sensor.
I think I have it working as desired except for line 22 isn't doing what I want it to do.
Maybe instead of saying, while that triggered water sensor is wet do xxxxxx, I should be saying while ANY water sensor is wet do xxxxxx? Is someone able to help me with what syntax I would use for that?
it all looks a bit over-complicated
rather than triggering on a state_changed event, just use a state trigger
then trigger.to_state.state, trigger.to_state.entity_id, trigger.to_state.name
have you looked into alert? https://www.home-assistant.io/integrations/alert/
that's what it's designed for
I have not seen the Alert function. I'll take a look. Thank you!!!
but to address your concern about line 22, the state key isn't under entity_id
you did it right earlier in the template: trigger.event.data.new_state.state
if you're using the state_changed event, which I wouldn't recommend.
Hello all, trying to learn to combine my entities for a Shelly1 that cycles my garage door, and a 433mhz magnetic reed switch that shows whether the door is closed full or not closed fully. Managed to get the following code and all seems to work well except, at first the icon was an exterior window, I changed it to mdi:garage, but it won't show it as open like my other garage door does. Anyone know how to do this? I'm assuming I need to somehow show a different icon for each state but I can't seem to find how to do that. Thanks
cover:
- platform: template
covers:
garage_door:
friendly_name: "Lower Garage Door"
unique_id: "2021061901"
value_template: "{{ is_state('binary_sensor.lower_garage_door', 'on') }}"
open_cover:
service: script.open_lower_garage_door
close_cover:
service: script.close_lower_garage_door
You can use the icon_template properly, or specify device_class: garage: https://www.home-assistant.io/integrations/cover/
So I was trying to do this through "Automation", but with the alert function, would that be done just through text editing a YAML file and not through the "Visual Editor"?
Yes
Got it. Thank you!
I guess I can't figure out how to do either one. I have read that page, but I'm new to all this and just can't seem to understand it. I made the code from a copy and paste and just edited my sensor name, all I know to do.
this is from my cover template:
icon_template: >-
{% if is_state('binary_sensor.garage_door_sensor', 'off') %}
mdi:garage-open
{% else %}
mdi:garage
{% endif %}
here's a link on the forum from a "home assistant garage door cover template" search: https://community.home-assistant.io/t/template-cover-for-garage-door/241763
petro mentions the device_class: garage option in the second post
Thanks! that looks like what i need and a good link.
So, I'm also wanting to have any water leak sensor trigger my water main valve to close (just trying to get the alert part working first). Am I understanding correctly that the "Alert" function cannot trigger a device action (closing the water valve)? So I'd still need my automation? But then would it make sense to have the automation also trigger the alert function?
Yes, you’d need an automation for that. No reason to manually implement the alert there, though
So setup a template of any leak sensor to trigger the automation that will call the valve to close and also call the alert function, right?
Or are you saying to just have the alert be totally separate and they would both just trigger off of the same criterial in two separate spaces?
The latter. You don’t call an alert
Ok. My head is still spinning a bit, but I think I'm starting to get it. I'll keep reading/experimenting. Thanks, sir.
np. alert encapsulates a lot of functionality, so if it does what you want, you can just use it
I essentially want a leak to trigger a valve to close, activate a few scenes to turn lights blue, send a leak alert to all of my mobile devices, play an alert on an alexa device every 10 seconds. I want the name of any triggered sensors to be listed in the app notification and spoken on the alexa device. Then once all leaks are cleared, I want to activate scenes to turn lights back to white, send a single leak cleared app notification and have alexa announce that the sensor name is now dry.
Would one alert and one single automation make sense for all of that, or would you suggest splitting it up more or something else entirely.
Oh, and the valve should open back up too once all sensors are back to dry
Seemed much simpler in my mind until I started to type it all out... 🙂
that's a bit much for me to work out
How about this: the alert function will not activate scenes, close valves, send TTS notices to alexa, right?
So I could maybe work though those in an automation and then just do the app notifications via alerts. That sound like I'm headed in the right direction?
yes
THx
So if, on an automation, I try to trigger on "State" it is asking for an entity ID. But I want my trigger to be any sensor switching to "on" that has a device class of moisture.
Is that possible to do? That is what a "template" is referred to as in HA, right?
yes, that would be a template. And the variables here can be used to determine what actually triggered it: https://www.home-assistant.io/docs/automation/templating/#template
So what would I fill in on the "entity" field of the trigger to have it look at all moisture sensors instead of a single entity or having to manually list each one individually? I feel like there is some simple thing I am missing/not grasping with this concept... And once I get that, I'll be on my way...
template triggers don't have an entity_id field
It's the entity field on the automation that I'm referring to.
the automation trigger
I get that, but if you're using a template trigger, it doesn't have one
I keep googling this thinking there has to be someone else that has already done what I'm trying to do and surprised I'm not finding anything.
you have to determine how you're identifying the entities that you want to monitor
I think, simply put, I want to create an automation trigger of any moisture sensor triggering.
going from off to on
device class of moisture
I keep seeing people listing every single sensor, but I want a way to have it use any of them with a certain device class
so if I add/remove one later the automation will still work.
Make sense?
{{ states|selectattr("attributes.device_class", "==", "moisture")|selectattr("state", "==", "on")|list|length > 0}}
that will trigger if any entity of device_class moisture is "on"
and a similar construct can be used to iterate through that list to generate a comma-separate list of entities, for instance with |join(', ')
Again, thank you! Is there some place that I might find real world examples of people with setups like this? I feel like I am just not searching for the right terminology or something... I hate bugging you with all of these questions, but really appreciate your patience!
the forum is usually the best place for examples. I didn't see any specific to your use case in a quick search, but it's not uncommon and I expect that there are some examples there
but for stuff like this it's best to study the templating docs (https://www.home-assistant.io/docs/configuration/templating/) and there are definitely lots of examples of that kind of template in the forum and here
{{ states|selectattr("attributes.device_class", "==", "moisture")|selectattr("state", "==", "on")|map(attribute="name")|join(', ') }}
Espresso Machine, Water Heater, Fridge, Master Vanity, Rachio v3 rain sensor, Upstairs Humidifier
Can you use templates in the snapshot_entities: part of a scene.create service call? I'm trying to use a light group there, so I don't have to constantly update my scripts whenever something changes to my setup (e.g. I get a new light). Just using the group there gives weird behaviour, where it gets and saves the average from all the lights in the group.
So when one light is blue and another is red, the scene contains two light that are set to purple :/
Expanding the light group with a template would work nicely, since then only the group configuration needs changing when a new light is bought, but it seems I can't get it to work properly
It’s part of data:, so it should work
You have to either output a comma-separated string of entities or a list
I currently have this {{expand(state_attr('light.bedroom', 'entity_id'))|map(attribute='entity_id')|list}}
which outputs
and it doesn't work?
nope
seems like a weird template, but the output looks okay. What does your actual call look like?
oh wait... I thought it needed quotes around the template, turns out it didn't 😅
it works now!
how do I return the current time in 12hr form? (6:02 PM)
Ok I have limited coding experience mostly LPC. But im trying to get an automation to fire with a random string from a list.
Like when x happens. Call service
Restful.service.random...
And in the rest web hook it want them URL to be one of about five. And I dont see a clear way to randomize these with a built in command
@uneven pendant You'd use a template. Use a list and the random filter.
hi,
i want to use a template in a time_pattern trigger. the automation should trigger every interval seconds.
- platform: time_pattern
seconds: '/{{ /interval }}'
i get an error here 😫 i can't get the syntax right
That’s not supported
You could use a template trigger that tests the time via now()
But. it only runs every minute
Or, you can use a fixed time trigger and a condition template to decide if the time is interesting
But in general, wanting to use a time_pattern trigger often indicates that you haven’t really thought through the problem and identified the actual triggering event that makes sense
It’s a trap that people accustomed to more transitional programming languages often fall into. For event based systems, looping/polling is rarely the best solution
iam building a blueprint for adapting lights over time based on sun position (i know adaptive lighting exist but i dont want to use it)
the idea is to let the lights adapt everytime they turn on and after a certain amount of time
the % sun position is calculated by sunset and sunrise
using sun.sun elevation attribute to trigger the automation may be a good idea
If you don’t plan to do anything unless the elevation changes, yes
the problem is that the sun.sun sensor only reports elevation changes every couple of minutes
another option would be to use a loop
Gack
gack? 
hi - does google home not support the command "stop" for covers within HA?
I have the blinds programmed for open, close, and stop and open and close work fine but google home says device is already stopped when I try to stop it
#cloud-archived or #integrations-archived depending on whether you’re using Nabu Casa
anyone know how to convert from color_temp to 565 RGB in a template?
I found how to go from RBG to 565 RGB, but lights don't always have rgb_color so templates die when lights use color_temp instead
I guess I'll just map some values and approximate
if i want to test a template from a script that recieves a data_template: value from an automation call, in the template tool.. how can i simulate the content of that data_template??
value_template: "{{ ( states('sensor.kitchen_fridge_smartplug_energy_total')|float * states('input_number.energy_cost')|float )|round(2) }}"
dishwasher_cost_total:
value_template: "{{ ( states('sensor.kitchen_dishwasher_smartplug_energy_total')|float * states('input_number.energy_cost')|float )|round(2) }}"
server_cost_total:
value_template: "{{ ( states('sensor.server_smartplug_energy_total')|float * states('input_number.energy_cost')|float )|round(2) }}"```
I would like to add these three sensors together into a 'total total' sensor - how do I add them in a template though? And is there a specific area in the docs this is mentioned? I could not find it in this area https://www.home-assistant.io/integrations/template/
or am I better off using a group?
Groups do not add up sensors. Al you need is value_template: "{{ states('sensor.fridge_cost_total')|float + states('sensor.dishwasher_cost_total')|float + states('sensor.server_cost_total')|float }}"
a simple plus, who would have thought
it could get even easier
{{ [states('sensor.fridge_cost_total'), states('sensor.dishwasher_cost_total'), states('sensor.server_cost_total')]|map('float')|sum|round(2) }}
Proof:
{{ ["4", "5.5", "10"]|map('float')|sum }}
-> 19.5
Could probably simplify further if you use a group
The values passed in are just variables, so you can do {% set foo=“bar” %}
sorry, mixed threads there, cleaned up my response
group example:
{{ expand(state_attr('group.my_group', 'entity_id'))|map('state')|map('float')|sum|round(2) }}
Is it possible to create a template title for the notify service call? Basically I want the title to return the name of the user that has activated the service-call. I couldn't find anything regarding that in the template docs or notify docs. Or if it's possible in the message that would be great too.
anything that's under data: can be templated
do you have an idea what the syntax might be? I tried {{user}} but that only works with markdown afaik
~share your service call
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
"user" is just a random variable name
the service call is part of a button-card tap_action
so I added that to the paste just to be safe
ok, then you really want #frontend-archived
well, it's the template engine right?
I want to use it for more than only the button-card
the frontend doesn't natively handle templates, so it's up to the individual card to do it, and they all do it differently or not at all
the custom button card does support templates there, for instance
but I don't think the default, built-in button card does
ah ok, gotcha
I have a brainfart! I can't for the love of it remember how I do a countdown template from an input_datetime'
Like hours and minutes left
Oh
Yeah I have an next alarm that is a datetime so I'm looking for "Wake you up in Xh"
you can just do datetime math
{{((states('input_datetime.morgon_alarm')|as_timestamp|int - now()|as_timestamp|int)/60)|int}}
This seems to do it for minutes
yep. you could also use strptime() to convert back into a datetime, assign the datetime difference to a variable, and do .hour(), .minute(), etc.
I suspect
working with datetime values is not fun
No it's rocket science to me, I'm not a programmer 🙂
that doesn't work anyway, so ignore
it always turns into an exercise in mashing on teh keyboard in the template devtool
Here is an example if someone looking for this {% if states('input_boolean.vackning') == 'on' %} {% set time = ((states('input_datetime.morgon_alarm')|as_timestamp|int - now()|as_timestamp|int)/60)|int %} {% set hours = ((time | int / 60) | string).split('.')[0] %} {% set minutes = time | int % 60 %} {% if hours == '0' %} Väcker dig om {{ minutes }} minuter {% else %} Väcker dig om {{hours}} timmar och {{minutes}} minuter {% endif %} {% else %} {% endif %}
good job! I look at that and think "there must be a better way..."
Yeah I know! It probably is, but I don't have the knowhow :/
Thanks! I'm off to bed, have a nice day/night
Is there a built in clamp/constrain/bounds function?
I don't think so. something like this works: {{ max(min_value, min(value, max_value)) }}
Tarras showed me this version which I thought was a neater solution: {{ ( [min_value, value, max_value]|sort )[1] }}
Nope it bounds between min_value and max_value
Once sorted the list will be in increasing order. Then the middle value is picked.
OH.. because it takes the middle item in [1]
That’s an interesting solution
did that PR for native types for input_datetime ever get merged?
no, got squashed
Paulus killed it because datetime isn't serializable
apparently that's bad for the recorder
I’ve been directed here, although looking at post history doesn’t seem like this is what I’m looking for….
I’m trying to create a script, or blueprint, or something that allows me to separate out a conditional on an entity state to either directly update brightens or set a zwave parameter for the brightness to be honored when it’s next turned on. A repeatable macro of sorts.
This is what I have in the Script, but I have so far been unable to templatize passing in the target entity (e.g. light). Several forum posts suggest this cannot be done, but @arctic sorrel said they do this successfully, so I’m hoping others have examples they would be willing to share.
https://paste.ubuntu.com/p/YCw34qTYRJ/
All I need is the ability to execute steps given a variable device and brightness values so that I can set my own rules from separate automations. I explicitly do not want to hardcode all of the potential permutations in one giant glob of unmaintainable scripting. Thanks for any help anyone can provide.
That seems like it should work if you put that sequence in a script and replace entity_id: light.bathroom_light with entity_id: "{{ entity }}" everywhere.
Then you can call that script with yaml service: script.set_brightness data: entity: light.bathroom_light
I think templating should work in target too, but if it doesn't you can probably use the legacy method ofyaml service: ... data: entity_id: like you do with zwave_js.refresh_value.
I did this, but when I tried to save, the UI stated that it was an invalid syntax for entity_id
Yes, templating works for target: as well
Ok. So the problem is in the condition. Maybe that doesn't support templates.
Try a template condition instead. yaml condition: template value_template: "{{ is_state(entity, 'off') }}"
Okay, that saved at least. Thank you.
So am I able to select entity and brightness in the UI when creating an Automation? I tried adding fields to the script, but it doesn't seem to be providing any sort of input for them.
Ah, looks like selectors were added recently. They haven't made it into the docs; I found the GH merge.
Success! Thank you @charred dagger, I really appreciate your direct help.
Keep getting errors - platform: mqtt
name: "BI Driveway Night Motion"
device_class: motion
state_topic: "Blueiris/Driveway Night"
payload_on: "on"
payload_off: "off"
value_template: "{{value_json.state}}"
off_delay: 30
'value_json' is undefined
sorry, unable to see the upload image so I cannot show the actual config and error
there's no formatting and you haven't said what kind of sensor that is, but yours doesn't look like the one here: https://community.home-assistant.io/t/blue-iris-integration-tutorial/71863
it says this:
binary_sensor:
- platform: mqtt
name: "FDC Motion"
state_topic: blue_iris/binary_sensor/fdc_motion/state
payload_on: "ON"
payload_off: "OFF"
device_class: motion
but that was a long time ago. so you need to look at what you're actually getting the from the topic, and make sure you're using the right topic
Am I limited to upload images on this board...I cannot find the upload button?
sorry, not sure how-to...anyway to drag and drop?
Thanks, let me sort out posting images.
use something like MQTT Explorer to see what's actually going on in your broker: http://mqtt-explorer.com/
then you're not flying blind about what's being published and what you should listen for
Are template switches being moved to the "modern" format now in place for sensors and binary_sensors, a la https://www.home-assistant.io/integrations/template/#configuration-variables
The switch page makes it seem like it's still the old style: https://www.home-assistant.io/integrations/switch.template/
Why does this always have state = off. I have tested in developer tools and see that I can get both true and false values ```binary_sensor:
- name: "hasp night mode"
state: >
"{{ is_state_attr('alarm_control_panel.area_1', 'arm_up_state', 'fully_armed') and
is_state('cover.scott_side', 'closed') and
is_state('cover.elizabeth_side', 'closed') }}"```
I think you don't need quotes after the >. Does that make a difference?
that did the trick! thank you thank you
I'm trying to write a template to calculate a "heat index". but I'm getting an error about non-int and floats: http://ix.io/3qNT
any ideas what I'm doing wrong?
a couple of things
first, this is just converting 100 to a float: {% set R = states('sensor.living_room_humidity') * 100 | float %}
{% set R = states('sensor.living_room_humidity')|float * 100 %}
that might be all, unless it doesn't like the giant multi-line expression at the end
ah ok
yes! that seems to have fixed it
thank you
same error with the round(1) I think
do i have to restart HA to load the modified template?
you can reload template entities from
-> Server Controls. And yes, the expression preceding |round(1) needs to have parens around it
you're currently rounding the last R
yeah
or just use a weather service or station that reports it natively (like my Weatherflow)
i'm calculating it based on a sensor in my office
i want to see how the Aircon temp/humidity affects my perception of temperature. and if Heat Index corelates
just for the fun of it
it would be cool if there was a "template sensor blueprint"
hmmm something still wrong with my formula. i'm getting -70751.6 😂
definitely not that cold in here
I'm not at all surprised that that monstrosity doesn't work 🙂
are relative humidity percentages stored internally as 0.50 or 50 for example?
ah
thanks
perfect, that fixed it
can i delete the history in the heat index sensor somehow? as it now has some -70000 entries
which messes up the chart
oh nice
so back in the paste, you can see the average temperature calculation: {{ ((bmp280 + sht3xd) / 2) | round(1) }}
every so often it returns 0 for some reason
one of those sensors is probably "unavailable" or similar sometimes
so how do i account for that in the formula?
you can give it a default with |default(xxx), but probably not what you want
any way to track why the sensor is unavailable at that moment?
you'll have to debug that with the integration that's providing that sensor
yes, I get it 🙂
that's an #integrations-archived question
I've multiple integrations that show up as "Devices" such as a Synology NAS. These devices may have some interesting attributes that I want to use in a template such as Model number or version. Is there a way to get this info through templates? I mean.. a device doesn't seem to be/have a entity I can address... Basically I'm looking for the parent of a entity
Nope, it’s not possible currently
Template question, I ran across some syntax that I do not understand: https://paste.ubuntu.com/p/3fSdmGvsZp/
I can't seem to find some documentation on it either.
Specifically the turn_on: &toggle_coffee and the turn_off: *toggle_coffee
Is the & and addressing definition and the * a pointer type reference?
(This is from the latest hassio podcast, was just looking at the show notes design here https://www.hackster.io/xbmcnut/hack-a-breville-espresso-machine-for-home-assistant-control-ec5213)
It really does appear that one references the other, I just can't find any docs about it.
ah I just wasn't googling the right term. My C programmer was making me search references
Anchors!!, thanks @brisk temple
Very cool.
I'm using the MQTT HVAC climate panel to control my split unit ACs, but there's a mode that's missing (side to side swing), anyway I can add that mode to the Climate panel?
hello. im looking for a template:
on each buttonpush i would like to increment input number. thats a call service ofcourse.
But how can cycle the steps? i would like to go to the lowest step after the highest step
its for a light. i would like to cycle the dimmersteps
so push once for 10 20 30 40 50 60 70 80 90 100 brightness. and then push for 10
its also a brightness_step but how to go to the beginning
Is it possible to force HA to record the state of an unchanged sensor template? I've done some looking around and found homeassistant.update_entity and maybe it does update, but it still doesn't record if the sensor is unchanged. For plotting purposes, it would be helpful to record the last value of a sensor just before it shifts to unavailable. I've found many threads of people looking for similar functionality and resorting to hacks like changing the value just a bit before a change (https://community.home-assistant.io/t/updating-template-sensor-on-attribute-change/106263/16). I wonder if there's an alternative!
It works, despite the bohica.net blogger introducing a typo (sensor -> sendsor) that hung me up for 10 minutes, in adapting this person's solution: https://community.home-assistant.io/t/update-record-of-sensor-template-every-5-min/37463/4
I'll have a look! Thx
Counter looks pretty good. It has a reset as well. I'll go mess with it this evening
Hi guys, I have sort of a dynamic "template within a template" but I can't figure out why it's returning a value of 0:
{{ state_attr('light.{{ states("input_text.lifx_device_lower") }}', 'brightness')|float }}
I'm trying to get the brightness state attribute of dynamically changing light names, which, as you can see, is dictated by the state of an input_text.lifx_device_lower. The input_text's state is currently "lightstrip", whose brightness value is 76, but this template returns 0. If I replace {{ states("input_text.lifx_device_lower") }} with the actual name of the light (lightstrip) it indeed returns 76.
not sure if i may tag you or not...
got this base automation running so far:
This base works:
longpress: HOLD mqqt --> toggles on/off
shortpress: TOGGLE mqtt --> this increments the counter
If counter >5 then reset to 1. SO i got 5 settings
but now for the actual brightness settings per counter value. I would like to add my own values to each value since not all lights are liniair in brightness it seems. I would like to add another choose action on TOGGLE:
A. Numaric value is always < > value. and not =
B State quotes the number and it doesnt work
any ideas?
It looks templatish to get it working
That’s not templating. That’s yaml. Look up yaml anchors
That’s not a template, that would be a script.
Can be done without templates
can it be done in ui/yaml?
if counter=1 then call service
if counter=2 then call service
etc?
Don’t nest templates in templates. A template itself is code and everything inside it doesn’t need more {{}}. Remove the nested {{}} and test your stuff in the template editor in dev tools
Yep, you don’t even need a counter. Input numbers have increase/decrease services
i know. But
A. i would like to add my own brightness values to eacht counter, since not all light are liniair
B. Reset to counter 1 after 5
so short presses: 1 2 3 4 5 1 2 etc
hold is off or toggle, dunno yet
Yeah just have a choose that sees if the input number is at the your max and if it is set it to your min
so all i need ( i think ) is a working choose action
thats where i break down
condition: numeric value?
condition: template?
numeric is above or below... not IS
state is a string?
So?
not a value...? doesnt it matter?
“1” is still “1”
guess not then haha
i couldnt get state to work. but ill try again in a super simple automation first
thx. at least i know it SHOULD work
back to the drawing board
hello i have a sensor for a window that sends an on off signal every time i open or close the window. now i want so craet a sensor that works like a switch. firs on of signal = sensor on second off and so on could anyone help me please i have no idea how that works
pls help me
you should make more sense first
a switch implies you can toggle it, a sensor only shows the state
sorry i want a sensor that shows open on the first impulse of another sensor and on the second impulse close and so one
and what is that other sensor? what states does it have?
Thanks!, was already answered above. My C progammer background was making me search for references as the term.
Try this: https://paste.ubuntu.com/p/D7h7HSCCq5/
i use thise for the tuya window sensor https://community.home-assistant.io/t/tuya-motion-sensor-is-not-supported-in-home-assistant/68109/89
thx i try thise
So thise is the sensor https://pastebin.ubuntu.com/p/pqHTdPk5bw/
this sensor https://pastebin.ubuntu.com/p/pqHTdPk5bw/
So substitute its entity id where I wrote binary_sensor.your_window_sensor_here
Questions about widgets should be made here #ios_and_mac-archived
Sorry, I must have missed clicked
what dit i do wron in the config https://pastebin.ubuntu.com/p/htjws5qP2g/
*did
ping_tuya_motion_sensor_master_bedroom is not an entity id. binary_sensor.ping_tuya_motion_sensor_master_bedroom is.
thx
Be aware that you may have to flip the state of the window toggle sensor initially (it might not be synchronised with the actual physical state of the window).
it always shows closed
is the config right ?
No. You are missing he dash before the trigger. Look at mine again. https://paste.ubuntu.com/p/D7h7HSCCq5/
You will also need a dash before sensor:
Above.
i copied your programm and it does not work..
"Does not work" is not very descriptive. Did you do a configuration check? Did it pass? Are there errors in the log?
i restarted the server an checked the config
And....
What switch? You have no switch only binary sensors
soory the sensor
Which sensor?
but the window sensor does not work
binary_sensor.ping_tuya_motion_sensor_master_bedroom this one works
the values are on and off
Is that the actual entity id? Look in developer tools / states menu
yes but i can rename it to something shorter
Looking at your forum post it should be binary_sensor.ping_tuya_motion_sensor_maeleigh_pir_bathroom
but the sensor platform is ping and we use state is this the problem ?
I don't understand the question.
sec i send the config
A binary ping sensor has on/off states which we can use. In fact I just read that the template can resolve to on/off or true/false so we could just use states() instead of is_state().
https://pastebin.ubuntu.com/p/QwZKRfp7DC/ thise is everything
This: state: "{{ is_state('sensor.window_toggle', 'off') }}" should be state: "{{ is_state('binary_sensor.window_toggle', 'off') }}"
My mistake.
Sorry.
You can also just use: state: "{{ states('binary_sensor.window_toggle') }}" if you want.
Slightly simpler.
it works thankeyou verry much
if i want so learn how that works where can i find that information
thanks
I am trying to take a device's state "[255, 214, 123]" and use it in a template like I have for another devices attribute: {%- set red=(state_attr('light.dining_light',"rgb_color")[0] * brightness)|int -%} and I am failing. When I do this: "{% set red=color_rbg.split(',')[0] %}" I get "[255"
Is the best way to "|replace" the stuff I don't want, or a better way to get the RGB out of [255, 214, 123]?
it's not clear what you got with state_attr('light.dining_light',"rgb_color")[0]
the attribute is most likely a list
you just said "I am failing"
yes, RGB, as a list
so what do you get with what I put above?
255
state_attr is all working for the dining light, yes, but that's an attribute... the state of this color sensor is [255, 214, 123]
I am just trying to do the same thing with a state instead of an attribute
ok, that wasn't clear at all 🙂
I am not sure how to word this
I can pull from an attribute correctly, but when I try to use the state of another device, I am not able to split it correctly
yeah, I don't see a convenient way to take a list-formatted-as-string and turn it into a real list without that string manipulation nonsense
my best bet I guess is to make the state into an RGB array
or attributes which I can work with
this gives you a list of strings: {{ "[255, 100, 10]"[1:-1].split(", ") }}
magic: {{ "[255, 100, 10]"[1:-1].split(", ")|map('int')|list }}
Hi all, I'm trying to migrate to the "new" recommended sensor template format and having some issues. I currently have something like this for each one:
- unique_id: washer_amps
name: "{{ state_attr('switch.washer','friendly_name') }} Current"
state: "{{ state_attr('switch.washer','current_a') }}"
unit_of_measurement: "A"
I expected the unique_id to be used as the entity_id by default, but that doesn't seem to be the case. Right now, the name fills in correctly, but the entity_id is coming out as "none_current", seemingly based on the name.
Is there any way to set the default entity_id in the template or do I just have to go through each one in the UI and override it there?
{% set red = (state_attr('light.dining_light', 'rgb_color') | from_json)[0] | int %}
that's the just "red", right?
yes. Updated
this does all and generates a list: #templates-archived message
not sure what they're actually looking for, but it's in there somewhere
that already works... what doesn't work is this: {% set color_rbg = states('sensor.global_rgb') %} The state is: [255, 214, 123]
yes
I am trying to use the RGB similar to the state_attr above
Thomas gave you a way to get just red, I gave you a way to convert to a list that you can index into, just like the attribute
@green karma unique_id is for making sure the entity id doesn't change if the name changes, even after a restart. It does not affect the initial entity_id in any way.
Can anybody tell me why this font size has no effect on my template widget from the android app?
<font size="7">{{ states('sensor.my_weather_station_temp')}} and {{ states('weather.home')}}</font>
and using the from_json trick: {{ states('sensor.global_rgb')|from_json|map('int')|list }}
You probably get the name none_current because switch.washer didn't exist yet when your sensor was created during the boot process.
{% set color_rbg = states('sensor.global_rgb') %}
{% set red = (color_rbg | from_json)[0] | int %}
there... thanks!
@charred dagger Ah I see. I'll just enter them in the UI then. Thanks for the help
That'd probably be the easiest way.
Anybody have a thought on this issue? Font size has no effect on the template widget, unless it's my code.
Sounds more like an issue for #android-archived, but I notice you're mixing ' and ", so you get:
the string '<font size="7">{{ states(' followed by the undefined variable sensor.my_weather_station_temp followed by the string ')}} and {{ states(' etc.
Oh I was just trying to format it for discord
There are no ' on either side in the real thing
Fixed it
I made a template to calculate a Heat Index - it mostly works but occasionally gets a spurious result causing the graph to have sharp lines in it. I had a similar problem with average temperature calculation which i fixed with a min-max entity. what can I do for this one? http://ix.io/3r2C https://imgur.com/rLCrmLe
You probably need to sanitise your template input data. Any filters like |float or |int will return 0 if the sensor state they are applied to is unknown. You can overcome this with an availability template.
If you link a pastebin copy of your template here we can help.
hi guys. Can someone please help me with templates/json?
I have a device that returns its state attribute as a number, but I want to display it as text.
gonna need more context
type: entities
entities:
- entity: vacuum.viaomi_s9_vacuum_robot_cleaner
type: custom:multiple-entity-row
name: RoboVac Viomi S9
show_state: false
entities:- attribute: fan_speed
name: Fan speed - attribute: battery_level
name: Battery
unit: '%' - attribute: vacuum.status
name: Status
- attribute: fan_speed
the last one "vacuum.status" returns an integer value. I want to be able to display a corresponding text value instead
what do you want it to say?
{'value': 0, 'description': 'Sleep'}
{'value': 1, 'description': 'Idle'}
{'value': 2, 'description': 'Paused'}
{'value': 3, 'description': 'Go Charging'}
{'value': 4, 'description': 'Charging'}
{'value': 5, 'description': 'Sweeping'}
{'value': 6, 'description': 'Sweeping and Mopping'}
{'value': 7, 'description': 'Mopping'}
Then you want a template sensor to transform the value
yeah, I tried, but got lost 🙂
I could not even get the original value to display
I tried to use it like that:
- attribute: template
value_template: "{{ state_attr('vacuum.viaomi_s9_vacuum_robot_cleaner', 'vacuum.status') }}"
That’s…not how that works
It very brief. I dont understant how to use the examples given
every time I try to do any data transform, I get told that I need to create a new entity just for that transformed value 😦
every time it happens, something twists inside me 🙂 Dont know why 🙂
If that does not work (untested) someone else will have to help. I'm off to bed.
that's pretty much what I was going to do
attribute names usually don't look like vacuum.status with a ".", so check on that
works fine with appropriate values in the template editor. 'vacuum.viaomi_s9_vacuum_robot_cleaner'->'vacuum.xiaomi_s9_vacuum_robot_cleaner'
the "vacuum.status" attribute is just a name that integration chose to use. Can be anything else
Sure, just atypical
it worked great, guys! Thanks you again 🙂
hi, i'm trying to make a template in an automation that select randomly an effect for the light, but it doesn't seems correct
here the yaml https://paste.ubuntu.com/p/RTsJnxNSmP/
that syntax is incorrect
- service: light.turn_on
target:
device_id: bc76ab1fc1dc1de6dd2238c28f1a57f7
data:
effect: "{{ (''Morning Sky'', ''Lightscape'', ''Vaporwave'' )|random }}"
it tells me this "Message malformed: invalid template (TemplateSyntaxError: expected token ')', got 'Morning') for dictionary value @ data['action'][0]['data']"
ok it was the ' '
{{ ['Morning Sky', 'Lightscape', 'Vaporwave']|random }}
a tuple won't work?
you need a list, not a tuple
ok, let me try this
also, the double single quotes are a dumb thing that the UI does, you don't need to replicate it
this works for me, BTW: {{ ('foo', 'bar', 'blah')|random }}
yeah, i through that if it does in that way it probably would be correct
odd
I amused myself for like 10s
might be something weird with the double quotes then
ok, it didn't changed
what issue do you have now?
probably the action is not correct to set the effect
i tried using the service to change the effect , maybe should i try to use device?
those appears in here https://imgur.com/a/oTHLY6o
you probably need to look in
-> States to see what it says in the attributes
can you manually set the effect using
-> Services?
wait, maybe now it works
one moment
yes, it goes
and maybe i found the problem
i tried to use before the device id of the lights with homekit and not the one i've made in configuration file
now it seems working!
thanks you for the assistance
Hi I am trying to integrate the UK transport API into HA. It provides a sensor with the next train information which I am able to create a card for. But there is an attribute to the sensor which has the next 25 trains information. is it possible to list the next three trains using the template. Sorry I'm a newbie and dont have a lot of experience
A section from their HA page https://pastebin.ubuntu.com/p/YTw3BkggQq/
Is there a way to determine an entity’s integration to use in a template?
Not typically
I don't understand the error I am getting with this template. ZeroDivisionError: float division by zero
{{ ((states('sensor.guest_room_heater_daily_energy') | float / states('sensor.tibber_daily_energy_total') | float) * 100) | round(2) }}
what's the value of states('sensor.tibber_daily_energy_total')?
Oh.... Unknown
That would certainly explain that....
indeed
Great work! 😉
I do what I can
Hi, guys! Need to verify this:
Invalid config for [plant]: expected int for dictionary value @ data['plant']['lavendel']['min_moisture']. Got '{{ states.input_number.planter_lavendel_fukt.state | int }}'
The state of the input number is: "12.0", and I would think I convert this to an integer using
min_moisture: "{{ states.input_number.planter_terrasse_fukt.state | int }}"
Where am I missing here?
~share the whole yaml definition
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
Here is my YAML: https://paste.ubuntu.com/p/WrXHwthGpZ/
I see no evidence in the docs that it supports templates
So that’s why then. I was assuming the same setup for a template would work all over in HA.
Only if the key is under data:, service:, or target:, or if the docs mention it
I have a pulse counter that measures waterflow, and I've successfully calibrated it to show it's state in liters/minute. Now I'm trying to use the utility meter integration to calculate a total for a day and a week, but they are way off and I think it's because the sensor is displaying 40 litres/minute with a sensor update rate of 10 seconds... Is there any way I can template this to be accurate? I'm thinking the template should increment the sensor value (40litres/min) every minute, then, the total should be accurate
The utility meter will not take any flow rate sensor. Only an accumulated use sensor (Litres). You need to use the Riemann sum integral sensor to convert your flow rate into total flow then use that in the utility meter. https://www.home-assistant.io/integrations/integration/
hi everyone 🙂 still on my vacuum integration.
I need to make 2 switches that take their state (on/off) from the vacuum entity attribute value (0 or 1) and if switched manually will send the command back to the vacuum.
Now, I kind of guess that I need to use a template switch. But do I need to make new binary sensor for each of the attributes I want to switch?
Say, I have 2 attribues that I want switches for:
- collect_dust
- repeat_vacuum
Do I create 2 binary sensors (collect_dust_state and repeat_vacuum_state) with the values of these attributes?
But I dont understand how to use the template switch. Like what do I put under
switch:- platform: template
switches:
??? switch name?
And do I create a script that sends the command to vacuum (toggle_vacuum_dust_collection and toggle_repeat_vacuum) and use it under turn on/turn off sections?
- platform: template
Which vacuum is this for?
So you are using a custom integration for this? The reason I ask is that there is no vacuum service to change these values.
yes, its a custom integration for all Mi devices.
ok, more specific question 🙂
If I have this script:
toggle_vacuum_bin_auto_empty:
alias: Toggle vacuum bin auto empty
sequence:
- service: xiaomi_miot.set_miot_property
data:
entity_id: vacuum.viaomi_s9_vacuum_robot_cleaner
did: 378451326
siid: 4
aiid: 41
value: 0
How do I set "value" to be the opposite value of binary_sensor.vacuum_auto_bin_empty?
*should be piid, not aiid
value: "{{ 0 if is_state('binary_sensor.vacuum_auto_bin_empty', 'on') else 1 }}"
too easy 🙂 I guess for the switch I should probably be using 2 different scripts - one for ON and one for OFF
Hi, I was wondering how to get the state of a specific day in the weather forcast for the weather entity
i want to make a template that gets the next days high, low, and condition
but it is a little confusing because I know that I can get the state of "forecast" but then it just gives me a bunch of days, i need to get the specific temperature from a specific day, how would that be done? please ping me if responding
Oh nevermind, i found it in a video
This seems to be exactly what I was looking for, will try it out, thanks!
Hello everyone. I’m trying to toggle my climate.office_ac entity by using the tap action in custom button card. Climate. Can’t be toggles which is where I’m stuck. I can’t seem to make a template to toggle the climate entity. Any help would be appreciated. Thanks.
Hi folks!
rebuild Frenks 2$ dorbell
https://frenck.dev/diy-smart-doorbell-for-just-2-dollar/
now I try to see on the UI when somone last rang - but I have my issues with the template.
I tryed
{{ relative_time(states.switch.doorbell_button.last_changed) }}
or
{{ state.switch.doorbell_button.last_changed }}
but its always empty in the template editor
...
nvm
binary_sensor.doorbell_button 🤦♂️
I have the following attributes in a rest sensor entity which returns a JSON. How do I extract the value of station_id: S114 ?
timestamp: '2021-06-28T11:00:00+08:00'
readings:
- station_id: S77
value: 0
- station_id: S109
value: 0
- station_id: S90
value: 0
- station_id: S114
value: 0
- station_id: S11
value: 0
- station_id: S50
Im stucked at {{ state_attr('sensor.myentity', 'readings') }} but unsure how to get the value based on the key value.
Add [0][‘station_id’] and so on
But the position may change. I do not want to use the index position.
Oh, I see
I want to get the value where station_id = S114
I understand
there's probably a better way, but this works:
{{ (data|selectattr("station_id", "eq", "S114")|list|first)['value'] }}
{{ data|selectattr("station_id", "eq", "S114")|map(attribute="value")|first }}
so... {{ state_attr('sensor.myentity', 'readings')|selectattr("station_id", "eq", "S114")|map(attribute="value")|first }}
Nice! That works. I am very new to Jinja and still trying to learn. The above codes is just 
I enjoy these problems far more than the DNS/can't boot issues we usually get in #330990055533576204 🙂
Hi... I have this script https://paste.ubuntu.com/p/SQXKrR9tPj/ which is triggered by an automation. I want to use variables for the value templates inside the choose block. This does not seem to work (is accepted by all checks), light goes out despite humidity is well above threshold. What am I doing wrong?
String is a keyword in jinja. Change that to something else
or make it Never mind. That won't help."string"
Lol yeah, that’s what I meant but it capitalized the s
On mobile 😕
Took me like 2 months to find the ` on the iOS keyboard
Lot's of secrets in that keyboard. I found them quickly because there's an é in my name...
Ah, yeah I did not. I’ve never used the accents until then
I think I accidentally found the accents then had an epiphany.
What I meant was that string: "template" may not be valid, but "string": "template" may be. But as I edited to, that won't work here.
I think what’s happening is that it doesn’t even attempt to replace existing variables from the variable dict when they conflict in the jinja namespace
I later realized that string is not reserved in yaml. There it's !!string.
Thanks, just in case I changed it to msg, though that part seemed to work. It's the above & below that did not. Those did not accept the value I fed them, demanded a float, and adding |float didn't work either. That's when I changed it into a value template, but perhaps missed out on the functionality I needed in the process... :S
I see.
- conditions:
- condition: template
value_template: "{{ threshold }}"``` From what I can tell `threshold` is 75, right?
So what you're saying here is "if 75, do this".
Later you also wait for 75 to occur before continuing.
You probably want {{ (humidity | int) < threshold }} or something.
Howdy 🙂
is there a way to list sensors per integration?
I'm trying to get a battery monitor in place for my sensors, and I'd love to grab Zigbee and Zwave, but unlikely that I care about stuff my latop / phone reports as battery level
That was my intention, but it seems it won't accept that statement as it didn't evaluate to true...
What does it say?
Nothing at all, it just don't do what I'd expect, never enters those conditions
But works well if written as numeric_state conditions
is there some one-pager on rejectattr options? I'd need to do something like rejectattr(state|float, 'le', 50)
trying to avoid running a loop on things I don't have to
This maybe will help a bit... https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.rejectattr
Thank you!
I mean what does it say when it won't accept the template. And what does that template evaluate to if you run in in developer-tools/template? https://my.home-assistant.io/redirect/developer_template/
I don't get an error. When running it in DevTools;
{% set threshold = 75 %}
value_template: "{{ threshold }}"
gives value_template: "75"
If I remove the quotes it wont pass ha core check: "ERROR:homeassistant.util.yaml.loader:invalid key: "OrderedDict([('threshold', None)])"
You can’t separate the template like that
value_template: >-
{% set threshold = 75 %}
{{ threshold }}
Aha, that was olny for test in devtools
Ok
Hi All!
I have a script that runs every 30 minute from an automation. The script checks if the tomatoes need watering, by comparing the humidity sensor in the soil against the wanted value for soil humidity.
Lavendel, measured: 10
Lavendel, target: 5
Lavendel, need water? True
Obviousely there is an error in the logics here. I test using a condition template to carry on it the test is TRUE
- condition: template
value_template: "{{ (states.sensor.planter_lavendel_fukt | int) < (states.input_number.planter_lavendel_fukt.state | int) }}"
What am I missing ?
{{ states('sensor.sensor_1')|int < states ('input_number.whatever')|int }}
Obviousely. Typo when pasting here
Typos happen during a paste?
Sure not, but while editing before hitting publish here 🙂
What are we supposed to evaluate?
I have this, then
Lavendel need water? {{ states('sensor.planter_tomater_fukt') | int < states('input_number.planter_lavendel_fukt') | int }}
Evaluate two numbers to see if the humidity sensor reports lower value than the wanted value set by th input__number
The only thing I noticed was the script not pausing as it should, thus turned the light off when it shouldn't...
Hi, not sure if it's the right place to ask the question. I'm new in ha and struggling with dynamic token storage and use. I've setup one REST sensor to download authentication token from extrenal service. It's working ok, sensor's state is set to retrieved value (the token). Now I would like to use that token in other REST sensors in "headers". How to do it propery?
Tried ```
(...)
headers:
(...)
X-Gizwits-User-token: states('sensor.hottub_login.state')
I don't see any evidence from the docs that templates can be used there
it's just a string, or a list of strings
Any idea how can I store token obtained from external API and use it in sensor?
If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.
What's the syntax for ANDing two states to get a true/false result?
{{ states('binary_sensor.porch_pir_sensor_occupancy') && states('light.porch_light_bulb') }}
?
states are strings, so ANDing those two things doesn't make sense
you want is_state('xxx', 'on') and such
that compares the state and returns a boolean, which can be ANDed
OK thanks.
{{ is_state('binary_sensor.porch_pir_sensor_occupancy', 'on') && is_state('light.porch_light_bulb', 'on') }}
Complains about &.
right, it's "and"
Jinja Template Designer Documentation
For more examples and samples, visit see this page
hello, I have a problem I setup a MQTT sensor in sensor.yaml with value_json.batt but in HA logs I have an error.. anyone have a suggestion?https://hastebin.com/lenariyuto.coffeescript
@humble grotto posted a code wall, it is moved here --> https://paste.ubuntu.com/p/BT7r2xMPVq/
Hey, I have an issue with template sensor not persisting the state after reboot. Anybody knows how can it be fixed?
Config as simple as the following:
https://paste.ubuntu.com/p/BT7r2xMPVq/
Hi... I asked yesterday for help with this script https://paste.ubuntu.com/p/XdKq7yhmqX/ Never understood why the conditions in the choose block don't work. I don't get any error or message, they are just not run. The commented-out alternative works fine... Please help 🙂
{{ threshold }} is curious NR star it’s always true as long as the value isn’t zero
So it’s of no use that I can see
Aha... But in that case shouldn't it enter the condition?
Might not, as it’s looking for a boolean and getting a number
Jinja may not treat zero as false and non-zero as true
You need a test of some sort
So that is what troubles it... That should be easily fixed to have it report true/false. Strange it accepts the number without complaining...
Yes, thanks! I will rewrite it to return a boolean instead! Been a headscratcher for some time... 😄
It’s not an error, it’s just not what it was looking for. Hard to say what the result would be
It’s just not clear what you were planning to do with it. But carry on..
What I try to do is for it to run the sequence when the humidity is over the threshold, and by that pausing shutting the light off
But now realize I forgot the compare with the sensor...
Then that’s the test
Exactly, thanks!
(how)? can I sort a group of sensors by state before iterating through them?
Check the pins, mb. There's a list of filters on the official Jinja docs.
I've got through a bunch of them, e.g. filtering the entity_ids and sorting them looks all ok, but sorting by state didn't have much I could get going on 😕
the base is a group with about 20 entities
Did you try the sort filter?
not all of them seem to be int, so I've got to do conversion too in order for |sort to work
Then you may need to map everything first so you have sensible values before you sort.
I was playing with something like {% for item in mydict|dictsort(false, 'value') %}
so like mapping the entity_id and the value too, so I can then sort it like a hashmap by value?
Could you describe in more detail what you're trying to do? I'm sure someone can help build a template for you once you do.
I've got a group with entity_ids that represent power (e.g. battery state of a certain sensor)
I've built a template sensor that tells me if anything is below X value
and what I'm trying to do is list all of those in ascending order as attributes that are below that value
so ideally what I need to do, is: 1) get entities from group 2) sort them by state 3) list them as a single attribute with something like comma separation, nothing fancy (e.g. to know what to replace asap)
something like: {% for s in state_attr('group.low_battery_zigbee_sensors', 'entity_id')|dictsort(false, 'value') %}
but that obviously doesnt work 😄
It does for ints and floats
Strings “” vrs “3$$;$4$:)8(“
Dicts and lists resolve false if they are empty
hi guys - could someone perhaps help explain the math for a template to me 🤦♂️
value_template: "{{(states('sensor.inverter_voltage_analog_a0') | float - 29.5) / 1024 * 3.3 *5|round (2) }}"
This is for a voltage sensor via tasmota (nodemcu) providing an analog value of +-896
The template value I get is: value_template: "13.978271484375"
Parenthesis around everything before the pipe round
the ()|round() mistake I run into every month 😄
so yeah I did - but that didn't sort on the way I expected it
reran that, e.g.: {% for s in state_attr('group.low_battery_zigbee_sensors', 'entity_id')|sort(attribute='state') %}
I think it's not actually sorting by the group member's entity_id's state.
I'm getting a sorted list back as 100, 100, 100, 91, 100, 66, 100 - while I'd expect 100, 100, 100, 100, 100, 91, 66...
well, that state_attr just gives you a bunch of entity_ids and not states
expand(state_attr('group.whatever', 'entity_id')|map(attribute='state')|list|sort might work
actually, this works:
{{ expand(entities)|map(attribute='state')|map('float')|sort }}
replace entities with your state_attr()
awe, that seems to do what it's supposed to, thanks!
so if I put that within a loop, is there a way to get my entity_id back?
for example:
{% for s in expand(state_attr('group.low_battery_zigbee_sensors', 'entity_id'))|map(attribute='state')|map('int')|sort
in this case {{ s }} is the actual state, and I'm looping through them in the right order
a |map(attribute'entity_id') (as a blind guess) seems to mix things up
what do you want your output to be?
ideally it's a list of [friendly_name: value, ] so I can easily spot sensors that are due battery replacement
something wife understands 😄
so the idea was to put this in a loop, and add them to a new list that I can put out as attributes to a template sensor
try this but the ordering could get weird because of strings
{% for state in expand(entities)|sort(attribute='state', reverse=True) -%}
{{ '{}: {}'.format(state.name, state.state) }}
{% endfor %}```
oh... that: {{ '{}: {}'.format(state.name, state.state) }} ... I've seen that in one example but couldn't make much sense out of it
yeah this looks close
but as you mentioned sort is a bit kooky, I've got like 96, 95, 94, 63, 44, 100, 100, 100, 100
let me see if I can tweak that to be something better
all I need is to throw off anything thats > 50 really
{% set ns = namespace(mapped = []) %}
{% for state in expand(entities) -%}
{% set ns.mapped = ns.mapped + [{'name': state.name, 'level': state.state|int}] %}
{% endfor %}
{%- for entity in ns.mapped|selectattr('level', 'gt', 50)|sort(attribute='level') -%}
{{ '{}: {}'.format(entity.name, entity.level) }}
{% endfor %}```
that'll do it
that swallows an error when I add my group instead of (entities), e.g. {% for state in expand(state_attr('group.low_battery_zigbee_sensors', 'entity_id')) -%} will fail
odd, what's the error?
can't see - returns blank, and any template under it stops processing
doing it in the template tester?
yep
let me clean that up
and the gt changed to lt to get all the 0s
{% for state in expand(state_attr('group.living_room', 'entity_id')) -%}
{% set ns.mapped = ns.mapped + [{'name': state.name, 'level': state.state|int}] %}
{% endfor %}
{%- for entity in ns.mapped|selectattr('level', 'lt', 50)|sort(attribute='level') -%}
{{ '{}: {}'.format(entity.name, entity.level) }}
{% endfor %}```
oh ok, I reset the template tester and it all seems to work now - not sure what swallowed it before
wow nice, now it's gonna take a bit of time for me to understand what exactly is happening there 😄
many thanks for your help!
the namespace thing is because you can't update something that lives outside of the loop from inside
yep, that's clear
the weird behavior with the ns.mapped = ns.mapped + [] is because .append() doesn't work
this ns.mapped + [{'name': state.name type mapping is the one that needs understanding
so that is actually adding new items to the [list]
so where does state.name and state.state come from?
its re-creating the list with the combination of the original + what you're adding
are those actual attributes of the entity_id, e.g. name is "friendly_name" and state is state (value)?
name and state are properties of the state object that comes out of the expand
oh ok, so what I should definitely read up on is expand
that's the magic that makes this work
also name will return the friendly name if its set or the entity_id if it isn't
oh cool
the selectattr there filters down the list to the ones you care about
there's a few things I think I can refactor by understanding what expand does
sort you already had
selectattr and rejectattr are cool - that I've been experimenting with in the past couple of days
'{}'.format(var) is a python trick for string manipulation
can you explain how the |map(attribute= vs map(int) work exactly?
that looked like we're pulling out an attribute and making it int (by mapping to int?)
map("<filter>") applies that filter to all items in the list
map(attribute="some_value") pulls the attribute "some_value" from all objects in a list and outputs a list of those values
can you map multiple attributes?
nope
i don't think so
I just looked it up
e.g. map(attribute="entity_id")|map(attribute... didn't work for me
would have saved us an extra loop
there's a request from 2016 and bunch of people recommending a loop
Hi, guys!
I need some help pointing me in the right direction for finding this error from the log.
It´s in a scipt, OK, but then searching for some % is hopeless.
Invalid config for [script]: invalid template (TemplateSyntaxError: unexpected '%') for dictionary value @ data['sequence'][1]['data_template']. Got None. (See ?, line ?).