#templates-archived
1 messages · Page 48 of 1
In configuration.yaml I typed as state of my select template Very Good Very Nice and the entity is now working but now where did the state information go?
not sure what you mean by "where did it go"
FYI select template entities support optimistic, so you can omit the state field all together when you set optimistic to True
pretty sure we explained it yesterday
@glacial matrix what's your timezone??
BST at the moment, (GMT) so i guess UTC.
well +1 hours for DST then right?
seems like the requirement should not be 'required', try just filling it out with a non-template
with optimistic on
What is optimistic
I was wonedering why the data for tomorrow ends at 21:30, but that doesn't explain it then
read the docs for that field, it'll explain the behavior
aarghh, this should be it: - platform: time at: - '20:20' - '20:25' - '20:30' condition: - > {{now().strftime('%w') == '5'}} compare to #templates-archived message ... how did I miss that 😬
And the data you posted is not the current data then? Because it contains the data from yesterday (19th)
wdym non-template
I deleted the state line but optimistic was true
But it says state is required in the logs
state: Item1, i.e. no template
I am using riemann sum integral to keep a running total of electricity cost, but if there is a period of time where no power is used (and the cost graph becomes flat) it changes to unavailable. The history graph still shows the total, is there anyway to make it show this total instead of unavailable whilst under the condition of no power being consumed?
Btw back to the list thing. Does ist make sense to create a Picture Elements Card Configuration and put service call buttons there, then make the service call buttons service call the template and a ready service call button to inform to the template that the list is finished?
(Then the template will service call the roborock vacuum cleaner a list of ids that come from other buttons)
because I want to clean a specific room and I can put my house plan there
I'd make input_booleans and have them on picture elements, then have a button that says "run" that calls a script. The script will look at all the booleans and then take action based on which ones are on.
yep, 1 service call, and it's easy to test
can the picture elements card configuration yaml create a list from the buttons then send as service call to the template something like this?
- 17
21
18
(order is not important, that ids are from specific buttons there)
No, you'd do that in your script
I don't know why you want each button to send a serivce, just have a start button that does it all
in the script from "run I mean"
you can even make a simple config for it
without input_boelans thing it'll be simpler
I mean how does it convert to input_boelans but not to the list
wait do you mean "calls a script" as calls the template?
you make a dictionary and select from the dictionary based on which input booleans are on. The dictionaries value for said input_boolean is the number associated with the room that Xiaomi likes
but how does the "run" button collect information from other buttons and send the booleans?
all in the template
there's nothing to send to the boolean
it gets from the booleans
the booleans just indicate that you're going to clean that room
does the template read the picture elements?
they are input_booleans
they will show up on your picture elements as an icon
you can click it, it will light up as "on"
you can use almost any of them
image, icon, etc
they all work the same way
look at the demo
They are entities, they are input_booleans.
Yes, you need to create input_booleans for each room
but what is the difference between a call service button that is calling a service to an entity and a button that is an entity?
Aren't they doing the same thing in the backround?
well, for 1, you have to set all that crap up
input_booleans don't need service calls
they are on or off, and you can click them and they turn on and off
isn't service call just a signal?
that's not a thing
you're really trying to go the really hard route
the input boolean route is VERY easy in comparison
and the template code is probably less than 5 lines
that's just madeup bullshit
there is no template.send_command
services are services
you can't make up a fake service
Well... you can, but it won't work
that too
but it needs to convert than the booelans to ids
How about this, how many rooms do you have?
11
wdym
... xiaomi allows numbers for rooms, not names
what's the number associated with the room name
Mutfak: 19
Yemek Masası: 18
Salon: 17
Kiler: 20
Koridor: 26
Küçük Banyo: 25
Yatak Odası: 22
Büyük Banyo: 16
Tarık'ın Odası: 27
Eymen'in Odası: 23
Balkon: 21
sorry for turkish names
I made copy paste
service: vacuum.send_command
data:
command: app_segment_clean
params:
- segments:
- INSERT ID(s)
- repeat: 1
target:
entity_id: vacuum.roborock_s6_maxv
This right here is a basic example template
using input booleans
doing exactly what you want
with a python script
turning that into a script would be easy, here's an example...
wait you can put python script to home assistant?
wait a minute the tap action is call service?
run_vacuum:
variables:
config:
input_boolean.room1: 19
input_boolean.room1: 18
input_boolean.room1: 17
rooms: >
{{ expand(config.keys() | list) | selectattr('state','eq','on') | map(attribute='entity_id') | list }}
segments: >
{{ config.items() | selectattr('0','in', rooms) | map(attribute='1') | list }}
sequence:
- service: vacuum.send_command
data:
command: app_segment_clean
params:
- segments: '{{ segments }}'
- repeats: 1
target:
entity_id: vacuum.roborock_s6_maxv
look at that, 2 template lines and 1 script
script.run_vacuum is your service call for the run button
now just make 11 input booleans and properly fill ou tthe conifg: section and you're done.
does this template go and read the input_booelans or get signals from input_booelans and read them?
wait I understood the yes as something else
please take 5 minutes to understand what an input_boolean is
true/false yes/no on/off 1/0?
on and off, yes
how does the input_booelan be in the script?
it's in there, in the template
I use trickery to do things there, but trust me, it gets the states of the input_booleans
why is it an entity in the button yaml in the demo?
is the entity in the template and still counted as entity?
I don't understand your question
You still have to create those entites listed in the template - putting them in the template doesn't create them
Yes, that is correct
then how does the entities/input_booelans information go to the python script
does the script read that
does it count as variable in the script?
do you understand how HA works?
@last lance I converted your message into a file since it's above 15 lines :+1:
idk
well, to me it seems like you're lacking basic knowledge of entities in home assistant
because I'm new to home assistant
and you're trying to come up with something complicated and you're unwilling to learn the baby steps
where are the baby steps?
creating a simple helper like an input_boolean, putting it in an elements card to see what it does and how it behaves
then, subsequently, using a template to get the state of the input_boolean
then, watching what happens to the template result when you click the input_boolean in the UI
do I need to create it in the configuration.yaml?
none of what I just said needs configuration.yaml
you can create helpers in the ui, you can create the picture elements in the ui, and you can test templates in the ui
you might need 2 browsers side by side to do the template testing portion when clicking the item in the picture elements
oh I found the "Helpers"
I just couldn't find out how to find the state of one specific entitiy
what I found was a list of states of some entities
okay I found it
{{ states('input_boolean.agu') }}
agu is the name of my input_boolean
it does exactly what I've expected
it says on or off
but that {{ states(entity.id) }} thing doesn't exist in the script you sent?
It is in the docs linked from the channel topic here, but Petro tackled it in other ways
so do I have to add other things than that script?
So, it does... sort of. Like I said, the template is doing fancy things. It's rather advanced, but it's a set it and forget it template. So you shouldn't have to worry about it until you become proficient
as for the script, you need to add your input_booleans to the config section of that script
but how does it take the state without jinja
e.g.
....
config:
input_boolean.agu: 15
it gets the state via expand
expand(config.keys() | list) makes a list of state objects. config.keys() | list is the list of input boolean entity_ids
yeah it was it the whole time
the rest is filtering down to input booleans that are on
I was trying to tell you that it does everything you want and it's easy to maintain
and should I use helpers in the picture eleements
yeah but I wanted to learn how it works so I don't have to always ask for a script
okay thank you a lot
np
So the data gets updated between 4 and 6pm, and it contains costs from about 7pm that day, to 21:30 / 22:30 the following day.
ah, so before 4 to 6 pm you don't even have all the data of today?
no i might only have data up to 9pm that day.
I'm happy for the template to calculate the above for 9pm to 9pm
So right now, i have this, and i wont get any more information until between 4 and 6 tomorrow.
@glacial matrix I converted your message into a file since it's above 15 lines :+1:
and that is the data from an attribute?
what is the entity_id and the attriubte key
hi,
I had state of sensor with format: 123456789.
I want reformat above number to 123,456,789
How to do that
Thanks
I'm using the following template to get the cheapest gas station nearby from the tankerkoenig integration.
|selectattr('entity_id', 'search', '_diesel$')
|rejectattr('entity_id', 'eq', 'sensor.template_diesel')
|selectattr('state', 'is_number')
|rejectattr('state', 'eq', 'unknown')
|map(attribute='entity_id')
|list) %}
{% set nameslist = nameslist|sort(attribute='state',reverse=false)|map(attribute='entity_id')|list %}
{{ states(nameslist[0]) }}```
If two (or more) gas stations are the same price, it sorts alphabetically.
Is it possible to sort the lowest price stations by distance (with reasonable effort)? The entities provide latitude and longitude in their attributes and can be seen on the map.
why do you want that? I recommend to let the front end handle that, or do you want to use it in a longer sentence?
can you try this?
{% set nameslist = expand(states.sensor
|selectattr('entity_id', 'search', '_diesel$')
|rejectattr('entity_id', 'eq', 'sensor.template_diesel')
|selectattr('state', 'is_number')
|rejectattr('state', 'eq', 'unknown')
|list) %}
{% set ns = namespace(list=[]) %}
{% for n in nameslist %}
{% set ns.list = ns.list + [dict(e=n.entity_id, s=n.state | float, d=distance(n.entity_id))] %}
{% endfor %}
{% set sorted = ns.list | sort(attribute='d,s', reverse=false) | map(attribute='e') | list %}
{{ sorted[0] if sorted else 'no stations found' }}
I have this template {{ (((states('sensor.dishwasher_w') | float < 2.7 ) and (states('sensor.dishwahser_a') | float < 0.1 )) or (states('sensor.dishwasher_w') | float < 0.1)) | default(false) } It started complain not having default value set so I added the last part. template shall eveluate to true or false so should be adequite, no?
no, it will still complain about missing defaults
I noticed... So what would I need to do please?
where are you using this?
In a trigger
value_template: "{{ (((states('sensor.dishwasher_w') | float < 2.7 ) and
(states('sensor.dishwahser_a') | float < 0.1 )) or
(states('sensor.dishwasher_w') | float < 0.1)) |
default(false) }}"
id: "dishwasher_off"
for: "00:05:00"```
because i want that number look nicely on front end
Thanks
{{
(states('sensor.dishwasher_w') | float < 2.7 and (states('sensor.dishwahser_a') | float < 0.1 or states('sensor.dishwasher_w') | float < 0.1))
if 'sensor_dishwasher_a' | has_value and 'sensor_dishwasher_w'| has_value
else false
}}
Is that the value the state of an entity? If you display it on your dashboard it should be converted according to your user settings
Thanks! Didn't know of the has_value!
you could also use states('sensor.dishwasher_a') | is_number
Very useful, thank you! 🙂
i have notifications send that state to Discord.
But it alway send with : Tiền tháng này Công tơ Mẹ-303 là 703747 VNĐ. +--> 13:53:34 Sun, 09-Apr
The number 703747 look not good 😄
so that's not what you said, you said you wanted to diplay it on the front end
but okay
so sorry,
So i want reformat that number when send to Discord.
How can i do
{% set value = 703747 %}
Tiền tháng này Công tơ Mẹ-303 là {{ "{:,}".format(value) }} VNĐ. +--> 13:53:34 Sun, 09-Apr
output: Tiền tháng này Công tơ Mẹ-303 là 703,747 VNĐ. +--> 13:53:34 Sun, 09-Apr
This seems to work. It indeed shows the closer one. Thank you very much!
Now I'm going to tinker around with that.
Never used two options for sort before, so I wondered if it would sort correctly
Good to hear it works
many thanks
@marble jackal Your macro is working brilliantly, thanks! In future I'm going to have to build my own array similar to the nordpool one for predicted solar production... Once I have my panels, but then I can still use the same macro.
Do you have any thoughts on how to implement a "deadline" in my timing? In my own script I had a time range within which I looked for the cheapest time (for example if I want my dishwasher to finish before 6pm), but I'm not sure how to do that with yours other than changing the input list of prices into a new entity.
Did you look at the documentation? You can provide a start and end for the datetime values which are used
ARRRG you're right sorry. Sometimes I forget to go back into the documentation when I've gotten my first part of the project to work
RTFM man! 😄
H all, I am trying to use the new image entity (template) where the picture changes every hour or so. After a back/forth with Frenck, he stated the template needed an update action, not the entity itself. Now I am struggling how to set this up with a trigger. This is what I have
template:
- trigger:
- platform: time_pattern
# This will update every quarter past
hours: 0
minutes: 15
image:
- name: MF_alert_today1
url: http://192.168.1.20:8123/local/pictures/meteo_france_alert_today.png
- image:
- name: MF_alert_today2
url: http://192.168.1.20:8123/local/pictures/meteo_france_alert_today.png
the first one is created but has no picture
the second one, outside of the trigger, is how the original setup is supposed to be and this indeed works
Why does the triggered 'image' not work?
the first one will update as soon as it's triggered
so not after the restart o fHA?
which is not every quarter past, it's only at 00:15 with your current trigger
no, only when it's triggered
it will restore it's state after a HA restart
thanks...will try to trigger it earlier, to not wait 5min from now and restart
you can add HA restart as a trigger though
what is your current trigger?
has_value below returns false, but if I use is_number it returns true... ```{{ states('sensor.washing_machine_a') }}
{{ states('sensor.washing_machine_w') }}
{{ states('sensor.washing_machine_a') | is_number }}
{{ states('sensor.washing_machine_w') | has_value }}
so
- trigger:
- platform: time_pattern
# This will update every quarter past
hours: 0
minutes: 51
?
yes
that's at 00:51 only
like I already mentioned before
/51
duh...
there you define that the hour must be 0
After some testing, I had to change the sorting from d,s to s,d. It showed the closest regardless of the price.
okay, that was indeed the part I was unsure of
I had to wait for some price changes
yes, that's because the input for has_value is an entity_id
you are now providing a state (so a string)
I'm not using states('sensor.foo') | has_value here, just 'sensor.foo' | has_value
you did, and that confused me a little... I thought it was to challenge me, sorry!
I will try as you did it then
no, that's also why the the filters are IS number and HAS value
the first one checks if a specific input IS something (a numeric value in this case)
the second one checks if the input HAS someting (a valid value for it's state in this case)
Got it. 🙂
From the docs it seems I can only set a time, not a datetime, and that if "tomorrow" is set to true, it defaults to tomorrow, correct?
So the only way I can set an end time today, would be to make my script enable or disable the "tomorrow" option.
Not sure if that makes sense, it confused me when I read it back.
if you want it to end at let's say 18:00 today, you should indeed not set include_tomorrow: true
Ok, so then what I think will make sense is that I have that selector change based on when my "desired" datetime is.
Should be doable with simple if statement
Is there an easy way in Jinja to check if a datetime is today or tomorrow?
The things seems to work , changed_at and updated_at show every 3 mins ( I changed it to /3), however, the image entity continues to show the picture that was there when the image entity was created ...changing the PNG does not do a thing. Frenck stated that I needed to re-render the image template and suggested a trigger for that....but to no avail so far. Any idea what os going wrong here?
He means output a template that generates the image string
you have a hardcoded image string with no template, therefor there's no tempalte to update, therfor nothing updates
just output the image url from the template itself and the trigger should handle the updates
that's what he means by "rerender"
do you know what a template is?
yes....
ok, do you know how to output with a template?
clearly not
very sorry, does not seem to be my day at all... ? pin ?
I wrote tens of template stuff, never used 'pin'
I know you've written 10's of template stuff, i've helped you with alot
anyways read the 2nd pin
I know you did and.... I am sorry to say that I donot see any pins with my messages, is not my day ...hot / tired
bloody hell....yeah....
if you're on mobile, it might require you to click aroudn up there
on mobile its hidden behind the people icon
sigh...thanks....
as_local(datetime).date() == now().date()
for today
having this template: {{states.geo_location |sort(attribute='state') |map(attribute='entity_id') |first}} and using that inside an auto entities give me the single strike just fine and clicking that shows all attributes of the entity_id. I also use it as an attribute on a template sensor as the image shows (btew note the entity_is attribute is not on the card)
however, I cant click that entity in a card for more-info )(as ifd it were the actual geo_location entity_id.. somehow I seem to not see how I should do that
note you are sorting on strings now. If there would be two strikes, this one 71.6 km away, and another one 9.2. km away, the one of 71.6 km away will be displayed on your auto entities card
this is what I would love to do in the entities card:
let me check that
a bit more than 2 😉
fine, but these are integers
states are strings
and you are sorting on states
and as your current output all has 2 digits before the . this will sort fine as strings
a yes, I see what you mean
but not if theres a strike at 10.2 km and then at 9.9 km
using this as template sensor {% from 'lightning.jinja' import strikes %} {{strikes().split(',')|reject('eq','') |map('states') |map('float',default=0) |sort|first}}
yes, but now you don't the entity_id available anymore
and if one of them is unavailable or unknown, you will get 0
TLDR: You can't do this in a 1 liner
the strikes could return a list of dictionaries as json, then use |from_json
you could also just use all " and then use |from_json too
at least taht's what I would do
lists of dictionaries are easy to manage with generators. They turn everything into 1 liners
that needs some more explanation for me.... Ive been able to manage this far, and now see there are even 2 strikes for the same distance.... {% from 'lightning.jinja' import strikes %} {% set distance = strikes().split(',')|reject('eq','') |map('states') |map('float',default=0) |sort|first %} {{states.geo_location|selectattr('state','eq',distance|string)|list }}
what does strikes() look like?
{%- macro strikes() -%}
{{- states.geo_location
|selectattr('attributes.source','defined')
|selectattr('attributes.source','eq','blitzortung')
|map(attribute='entity_id')
|join(',') -}}
{%- endmacro -%}```
change that to
{%- macro strikes() -%}
{%- set ns = namespace(items=[]) -%}
{%- for so in states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','blitzortung') -%}
{%- set ns.items = ns.items + [ {'entity_id': so.entity_id, 'state': so.state | float(None)} ] -%}
{%- endfor -%}
{{- ns.items | to_json -}}
{%- endmacro -%}
then
{% from 'lightning.jinja' import strikes %}
{{ strikes() | from_json | sort(attribute='state') | first }}
nice!
and... if you want to find multiple close ones...
{% from 'lightning.jinja' import strikes %}
{{ strikes() | from_json | groupby(attribute='state') | sort | first }}
I'm totally going to copy that
my use case is check if the nearest is within x km, create binary for that and use that as conditional in Dashboard to show Map.... also, I need to be able to have the entity_id singled out, so I can show its attributes.... let me fiddle about with this

as this is my first to_json/from_json I need to read up on that
not much to read up on
to_json takes the object and turns it into a string that looks like json
from_json takes a string and tries to turn it into an object, if it succeeds, you get the object
correct
if you want just the list and not the value
{% from 'lightning.jinja' import strikes %}
{{ strikes() | from_json | groupby(attribute='state') | sort | first | last }}
and how do I select the entity_id in {{ strikes() | from_json | sort(attribute='state')|first }}?
how would you do that with any object?
pretend it's a state object
how would you get the entity_id from a state object?
you mean like:```
{{ (strikes() | from_json | sort(attribute='state')|first).entity_id }}
or {{ strikes() | from_json | sort(attribute='state') | map(attribute='entity_id') | first }}
yep, either of those
really nice indeed! thx a bunch
only thing left: how to get that as a clickable entity in the dash.... believe we can only do that using the map and a template filter in auto-entities... not in an entities card
I mean, you can make a template sensor from it
yeah I have that, but that wont open a more-info with the attributes if the geo_location entity
Not sure I follow you
if you make a template sensor with all the attributes of the geo_location entity, then you essentially have a geo_location entity
just in the sensor domain
I could build that yes, but that seems a bit overdoing it. currently have: - unique_id: lightning_strike_nearest state: > {% from 'lightning.jinja' import strikes_object %} {{ (strikes_object() | from_json | sort(attribute='state')|first).state }} attributes: entity_id: > {% from 'lightning.jinja' import strikes_object %} {{ (strikes_object() | from_json | sort(attribute='state')|first).entity_id }}
I would have hoped to be able to click that entity_id , but, it isnt even shown 😉
If I click it in the Map
it nicely shows all attributes. So that map turns the template back into the entity_id.
for that, we need to use the template filter in auto-entities, and it takes care of it.
you probably only need the longitude and latitude attrubutes
I guess I don't understand what you mean by "click that" as it looks like the LS is the entity you'd click on.
Yes, that's all you need
for it to show up on a map
apparantly it already shows up on the map becasue of the entity_id in the entity_id attribute
at least, that's how I understand it from these screenshots
I'm not sure why that would work, but that could be the case.
so the config for this map is to show that template sensor?
no, just the template```
filter:
template: >
{% from 'lightning.jinja' import strikes_object %}
{{(strikes_object()
|from_json|sort(attribute='state')|first).entity_id}}
{{states.geo_location
|sort(attribute='state')
|map(attribute='entity_id')
|first}}```
and as alway, when testing the lightning stopped....
btw, the sensor turns unavailable so I need a guard, I do want it to remain available, but show no strikes, or none
ah okay, so the map card shows the geolocated entity
yes, and that is why I said we need Map/auto-entities/filter template and cant use an entities card with that template sensor entity.
okay, but it should display the more info dialog on your dashboard as well when you click it
do you have it in a browser mod popup maybe?
yes, but that holds nothing, not even the attribute (no, not in browser mod)
I think there is an issue with tap actions in auto-entities
my updates card also doesn't work
everything works fine here, I can tap/hold all auto-entities entities
you were just saying that you'd expect a more info dialog when clicking that entity in a auto-entities card and that it doesn't work
no, in a regular entities card ... but, there is nothing to show on that template sensor, other than a possible entity_id (which is hidden)
ah, yeah sure, in a regular entites card showing just that template sensor you won't get a map on a more-info card
unless you provide a longtitude and latitude attriubte
yes, I guess we would a new template entity entity for that 😉
now I hope you understand my previous comment on that then 😉
how do I check for that empty object? I tried {{strikes_object()|length }} but even when empty that equals to 2 ?? while {{strikes_object()}} is an empty list []
seems its counting the brackets too?
from_json 😉
hi, i'm trying to get the day of the week from my forecast weather :
`forecast:
- datetime: '2023-07-21T05:00:00+00:00'
cloud_coverage: 65
precipitation_probability: 88
...my code is :day_of_week: "{{ ['LUN.', 'MAR.', 'MER.', 'JEU.', 'VEN.', 'SAM.', 'DIM.'][state_attr('weather.home', 'forecast')[0].datetime.weekday()]}}"`
but it returns null. Any idea ?
check your errors in the logs
TemplateError('UndefinedError: 'str object' has no attribute 'weekday'') while processing template 'Template<template I should think more aboutr logs 🙂
Why not just add longtitude and lattitude to the existing one?
(state_attr('weather.home', 'forecast')[0].datetime | as_datetime).weekday()
so simple 🙂 thx
{% from 'lightning.jinja' import strikes_object %}
{% set strikes = strikes_object() | from_json %}
{% if strikes|length != 0 %}
{{ (strikes| sort(attribute='state')|first).state }}
{% else %} No strikes
{% endif %}```
Ya
or
{{ (strikes_object() | from_json | sort(attribute='state') | first | default({'state':'No strikes'})).state }}
you can also build no strikes into the strikes_object()
so first always works
btw, can confirm the attribute entity_id to be filtered out in the Frontend, changing that to entity helps make it show
Sorry missed that. Yes, that would probably make it show when used as an entity in maps too
How do I filter out just the time from my event when there are multiple listed? I'm assuming strftime but can only figure out how to do the first event. Perhaps a "for" type thing?
https://paste.debian.net/hidden/13f85cb9/
https://imgur.com/a/veIVdbj
change {{ event.start }} to {{ as_datetime(event.start).strftime('%H:%M' }}
or another time format (see https://strftime.org)
Error rendering data template: UndefinedError: 'str object' has no attribute 'strftime'
Ok, that works. Thanks.
I also made an assumption and added a ) after the %M'
One thing I didn't realize is even though it's called event.start, it has the ending time as well and it cut that out even though I'd like to keep it but I think I can figure that one out. Or at least will try for a bit.
Thanks for your help.
Hi again. I'm struggling with some template triggers. Whatever I try only the topmost works. The other two should do the same thing, right? https://dpaste.org/Wqnrt
Thing is, I need a template as there's more to it than this, but simplified to isolate the issue (or tried to)
the last one is just bad syntax
oh. I see, missing a pipe, corrected
in the last two, you need to remove the surrounding quotes
sorry, didn't evaluate the templates properly. In any case, your problem is that you've surrounded a multi-line template in quotes
Noooo? Speant a good amount of time on this tonight... I'll try again, this time without them...
Thanks Rob, it now works as I need it again... Wonder why I added them... I always run the ha core check though, but it won't fail on things like that...
it will just be evaluated like any other string
True. Anyways, thanks, on to the next challenge! 🙂
I have an array of objects in this format:
[{ "date":"2023-02-20T00:00:00.0000000Z" }]
I'd like to iterate through the array and reformat every date to simply show the day of the week (i.e: "Monday, Tuesday" etc.). Is there a way to do that using pure functions? Normally, I'd use map in JavaScript, but Jinja2 seems to treat that a little differently.
Ideally there'd be a way to pass some kind of arbitary transform function into the map filter to act on each object on the way through but that seemingly isn't possible (as far as I can tell, anyway)
Strftime might be able to help you too. I just learned about it for my use case. Try with a %A?
right but can you apply that as a filter to a list?
{{ data | strftime('%A') | list }}
TemplateAssertionError: No filter named 'strftime'.
Evidently not.
No, it's a python method, you can only use it like some_datetime.strftime('%A')
Bummer. Meantime - is there a native way to check in a template if a given date is between two other dates?
{% set end = (state_attr('calendar.trash_schedule', 'start_time') | as_datetime | as_local ).date() - timedelta(days=1) %}
{% set start = end - timedelta(days=6) %}
I want to check to see if a given date is between start and end
One thought I had was to write a loop to generate a list of dates manually, then use element in list to check. But there must be a better way, surely.
....I can just use < and >. Can't I.
🤦♂️
Probably, but it seems like I don't even need to do that.
{% set date = end_date - timedelta(days=3) %}
{{
date > start and date < end_date
}}
that returns true.
{% set date = end_date + timedelta(days=3) %}
{{
date > start and date < end_date
}}
that does not.
Going back, you could use a loop... Not pretty, but it works.
{% set ns = namespace(x=[]) %}
{% for i in data %}
{% set ns.x = ns.x + [{"date":(i["date"] | as_dateime).strftime("%A") }] %}
{% endfor %}
{% set data = ns.x %}
@tired sandal I converted your message into a file since it's above 15 lines :+1:
You can also do {{ start < date < end_date }}
is it possible to pad now().hour so I get the following?
00
01
02
03
...
12
13
14
...
22
23
'%02d'%now().hour
right, thanks for the answer
btw is there any way to force it to return time in other timezone
why is that not a feature yet 🗿
And it gets complicated with dst
nah don't have dst in that timezone
Because no one added it
on the subject, there wouldn't be a way to translate Swatch Internet Time to local time and vice versa?
There’s a way to do utc to local, that’s it
Ok. Nice beats are supported though, not many knowing about it 🙂
Hi, guys! I need to concatenate a string for a notification. This string should consist of which plants being watered at the moment. I was planning to build a template sensor like below, but my knowledge stopped when assembelling the new concatenated string.
I started with this; using the state for what valve is open, and was planning to use "If valve is open, then true, and use in contcatendated string.
template:
- sensor:
- name: "Irrigated now"
state: >
{% set lavendel = is_state('switch.vanning_k1_lavendel', 'on') %}
{% set tomatoes = is_state('switch.vanning_k5_tomater', 'on') %}
{% set herbes = is_state('switch.vanning_k6_herbes', 'on') %}
## put togheter the string based on what valves are open (ON)
My final string should look like: Now watering lavendel, tomatoes, herbes...
I would add all your sensors you want to monitor into a group (in Helpers). Then use something like:
{{expand('light.hall') | selectattr('state', 'eq', 'on') |
map(attribute='attributes.friendly_name')| join(', ') }}
replacing light.hall with your group name. It will use the friendly name of your switches, so you might need to use replace to strip out any extra text you don't want.
One time event
Now watering {% for x in ['switch.vanning_k1_lavendel','switch.vanning_k5_tomater','switch.vanning_k6_herbes'] | select('is_state', 'on')| list %}
{{- x.rsplit('_')[-1] }}{{', ' if not loop.last}}
{%- endfor %}.
My version
{% set w = states.switch
| selectattr('object_id', 'search', '^vanning_k')
| selectattr('state', 'eq', 'on')
| map(attribute='entity_id')
| map('regex_replace', 'switch.vanning_k.*_', '')
| list
%}
{% if w | count > 0 %}
Now watering {{ (w[:-1] | join(', ') ~ ' and ' ~ w[-1]) if w | count > 2 else w | join(' and ') }}
{% endif %}
Hi, I am simply trying to create a value in a template without any fractions (Android template Widget) . The value I get is a string in kWh and I want to display Wh as integer. I tried
Forecast:
{{states('sensor.energy_production_today') |float *1000 | int}} Wh<br>
Also different ways of using the round filter. However, what I noticed, as soon as I do the multiplication with 1000 I get some floatingpoint precision problem and whatever filter I apply after that, I can't get rid of it.
Example:
String:4.130
Float: 4.130
*1000: 4130.000000000005
Round(0): 4130.0000000005
Int: 4130.000000000005
So I run out of ideas what I am doing wrong here
If I do, I get an error message in the Widget
I don't get why and I see your point
So to be more specific, in an android template Widget the following results in a error message and prevents to save the Widget
{{states('sensor.energy_production_today') |(float *1000) | int}} Wh<br>
your parentheses are in the wrong place
{{(states('sensor.energy_production_today') |float *1000) | int}}
you added an unmatched closing paren
(float*1000) doesn't make any sesnse
Ahhh OK, I thought that (float * 1000) would force the result of that send down the filter
@inner mesa working now.... At least no error, need to wait to see if rounding works, as the PV system switched off a long time 😉
you can set the state of that sensor to whatever you want
I know, I am just on my mobile at almost 1 am... Writing templates on mobile is a bit of a challenge, I leave the testing for later on my laptop 😜 Thanks again
How would I create a template binary sensor for a automation that acts on a binary sensor trigger
this is the device (this outputs closed/opened)
{{ states('cover.z_wave_garage_door_controller') }}
if it only has 2 outputs, you don't really need an extra sensor do you?
It doesn't list on binary sensor list so I can't run a blueprint
I have a super basic template sensor that seems to have failed.
- name: Today or Tomorrow
state: >
{{iif(now() > today_at("17:30"),"Tomorrow","Today")}}
Then in an automation (or template page)
{% if is_state('sensor.today_or_tomorrow', "Today" ) %}
{% set n = 0 %}
{% else %}
{% set n = 1 %}
{% endif %}
If sensor.today_or_tomorrow = Today, I get an error if it's anything other than today (ie; tomorrow) I get a 1.
'An error'
Right, my bad
ValueError: Template error: int got invalid input 'None' when rendering template '{{ states('sensor.time_of_day_greeting') }} {{ states('sensor.today_or_tomorrow') }}'
{% if is_state('sensor.today_or_tomorrow', "Tomorrow" ) %}
{% set n = 0 %}
{% else %}
{% set n = 1 %}
{% endif %}
Oh wait. I think I got it.
It's this chunk. It doesn't like the [0] but [1] works. I'll have to look at the sensor again.
{{ state_attr('weather.redacted', 'forecast')[0].temperature|int }}
Ah
"temperature: null"
That'll do it.
Hi, I'm getting this warning on Logs
Logger: homeassistant.helpers.template
Source: helpers/template.py:735
First occurred: 10:44:38 AM (1 occurrences)
Last logged: 10:44:38 AM
Template variable warning: 'dict object' has no attribute 'ir_code_to_send' when rendering '{{ value_json.ir_code_to_send }}'
Where is this template sitting and how can I fix this warning?
Thanks!
Gosh, @marble jackal . Seems complicated, but I think I get the logics here. Thank you very much 🙂
Now watering lavendel, paviljong and tomater
I really loved the "and" put in there when more than one item and commas otherwise 🙂
Is there a way to have an automatinon trigger, if any door opens and have it fll that doorname as text into the notification action without 100 if clauses?
Example.: Front door opens -> Notification: "{Doorname} is open"
How do you identify doors?
binary sensor from an aqara door sensor @inner mesa
I'm asking about how you know which entities are doors
There is a device_class: door for binary_sensor, but I guess it can be dependent on the Zigbee integration and other factors if they identify as door or window
yea, they're identified as door
Easy solution:
List all door sensors in a state trigger and use trigger.to_state.name in your message
Yes, but you'll get one notification when it crosses your threshold (eg below 20 percent) per entity
@crimson sun I converted your message into a file since it's above 15 lines :+1:
Ah thats rather cool 😄
i just saw that this is the wrong channel for that, im going to post it into the #energy-archived channel, sorry guys^^"
Thinking of doing a macro to return this data, is there a more efficient way of getting the same functionality? https://dpaste.org/FG0YJ
I'm trying to avoid having same or similar definitions spread all over the place...
Macro is fine
Thanks 🙂
Hm. Macro turned out fine, but where do I put the import in scripts? Can it be put in the variables section somehow?
{{ light_data('hallway','brightness','day') }}```
2nd row is what feeds the parameter, but the first, do I need it more than once for each file?
or better yet, perhaps in configurations.yaml?
Each template
Hi All, I have a gas bottle sensor that converts weight into a percentage. How can set it so that 100% is the max?
state: > {{ (states('sensor.tasmota_hx711_weightraw') | float - 927) | float / 10000 * 100 }}
{{ ([(states('sensor.tasmota_hx711_weightraw') | float - 927) / 10000 * 100, 100]|sort)[0] }}
without going into that formula at all...
Thank you.. Sorry just learning all of this for the first time. At the moment i am testing with a 2 x 5kg weights that are simulating my "gas bottle" (which when finalise my weight station is 90kg in total when full).
Hi, can someone please help me to create a valid template to replace 2 words in a state name ?
This is working :
{{trigger.to_state.name|replace('Occupancy','')}}:{{as_timestamp(trigger.to_state.last_changed)|timestamp_custom('%X')}}
I want to replace not only the word "Occupancy" but also the word (EP1).
How can I use state_attr for retrieve of media player shuffling status. this isn't working:
'{{ state_attr("media_player.spotify_nr", "shuffle") }}'
Easiest is to add another replace filter
Yeah you’re right but I’m using this opportunity to learn something new. 🙂
That should work for a media player from the Spotify integration, but only when it's actually playing
regex_replace('Occupancy|EP1', '') should do it in one filter
I've implemented it on Spotify integration using automation
But sure what you mean with that
Thanks
it worked!
Hi all - I have a script that is giving me a weird result in return - am I allowed to paste it here for some support? It's fairly long...
@edgy flume 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.
Alrighty - so I have a script that's supposed to return "There is audio is being playing [ROOM] [SPEAKER NAME(S)] " but something very strange is happening in the output: "There is audio playing upstairs from: [, U, n, d, e, f, i, n, e, d, ,, , U, n, d, e, f, i, n, e, d, ,, , U, n, d, e, f, i, n, e, d, ] https://dpaste.org/FXpC6
you'll want to just use the states method in your test instead of selectattr
or is_state
selectattr('entity', 'is_state', 'playing') instead of that giant mess
{{ speakers | selectattr('location', 'in', ['upstairs']) | selectattr('entity', 'is_state', 'playing') | map('state_attr', 'friendly_name') | list }}
and because you don't have state objects, you can't map name
alternative would be to add them to your speakers variable, but this is a lot easier 🙂
well, personally, I'd approach it differently all together
I'd probably stick with this but a single persistent_notification
I would create a media_player group in the GUI, eg media_player.main_floor and then use:
{{ expand('media_player.main_floor') | selectattr('state', 'eq', 'playing') | map(attribute='name') | list }}```
I still don't fully utilize areas
missing a quote there
Huh, when did they add media player groups?
interesting
Thanks all I’m very new to this, will try it out and report back 🙂
Is it possible to set diffent device_class on different attributes in a template sensor? I have tried everything i can think of without success. Anyone know how to do it?
sensor:
- name: Time and temp
state: ok
attributes:
time: > ## I want this to be device_class timestamp
{{ states('sensor.date_time') }}
temperature: > ## I want this to be device_class temperature
{{ states('sensor.openweathermap_temperature' }}
No, my understanding is device class is defined at the Entity level, so you will need to set up two sensors rather than one. What are you trying to achieve?
You can store a timestamp and a number in attributes.
attributes can't have device classes.
attributes can store native types though
so numbers will be numbers, and datetimes will be datetimes
I have a couple of rest sensors that extract time and date from a API that i got help with here a couple of days ago. This works fine when i have a separate sensor for every time. I am trying to achieve to extract this from the json sensor i have and but it in one sensor with attributes.
- platform: rest
resource: http://ergast.com/api/f1/current/last/results.json
name: F1 - last race time
device_class: timestamp
scan_interval: 3600
value_template: >
{% set item = value_json.MRData.RaceTable.Races[0] %}
{{ (item.date ~ 'T' ~ item.time) | as_datetime | as_local }}
To minimize the amount of sensors and cals to the API
don't use the rest platform
use the rest integration
rest:
- resource: http://ergast.com/api/f1/current/last/results.json
scan_interval: 3600
sensor:
- name: F1 - last race time
device_class: timestamp
value_template: >
{% set item = value_json.MRData.RaceTable.Races[0] %}
{{ (item.date ~ 'T' ~ item.time) | as_datetime | as_local }}
- name: ...
device_class: timestamp
value_template: >
...
- name: ...
device_class: temperature
value_template: >
...
Yes, did that before but that creates one sensor for every time. What I am trying to achive is to have all in one sensor with attributes, but if I understand it right it´s not possible
if it is to minimize api calls, the approach above achieves that, becuase it does one call, and then creates all the sensors
Yea that´s right, it minimizes the amount a lot. Thanks!
hello, i need to control fan speed over modbus, i want to do it by slider. My problem is that i need to map values to percents, for example i need to send 5 to set 30%, and 8 to set 40% speed. How can i do this slider?
a template number
or an input_numer with an automation
does your modbus offer a sensor that provides the current slider setting? I.e. does it tell you that it's at 5 after you send 5 to it?
yes, this is read and write addresses
ok, then a template number is the best route to go
if you post the entities, I can help you with the yaml and the templates inside the yaml.
also post the service you'll be using the send the command
hello i need to control fan speed over
@bronze prawn I converted your message into a file since it's above 15 lines :+1:
@bronze prawn I converted your message into a file since it's above 15 lines :+1:
It's because you aren't providing defaults for |float
Actually I just looked at mqttexplorer and the issue is that my message is not being retained 😦
I am not sure what to say but my sensors/rainoffset is not there but sensors/rainhourlyoffset is. I'll have to check to see if weather station had a problem reporting and that value was unavailable
apologies please disregard. Deleting to avoid trouble to others
hey there,
I have a sensor which returns 1, 2, or some other numbers, tried to convert it to on/off but it seems I've missed something (the return value is fine without value_template):
- platform: snmp
name: "Holo Network Port"
unique_id: holo_network
host: 192.168.39.249
icon: mdi:lan
version: "2c"
community: "private"
baseoid: .1.3.6.1.2.1.2.2.1.8.7
value_template: >
{% if is_state('sensor.holo_network',1) %}on{% else %}off{% endif %}```
edit: value_template is always off
{{ 'on' if value | int(0) == 1 else 'off' }}
@marble jackal thank you
how do i access the time ago that a person changed zones? to be used as a condition: has this person been home for more than 5 minutes?
you don't need a template for that
in the past i've used (now() > states.sensor.device.last_changed + timedelta(minutes=3)) but that doesn't seem to work for zones.
i'll be calling it via node-red, so i do 😦
... don't i?
the very first example: https://www.home-assistant.io/docs/scripts/conditions/#state-condition
I'll take a look. Thanks RobC 🙂
It's not being used in an automation in home-assistant but the output is being judged via a node-red function. Do you/anyone know if it's accessible via a template? the condition is in node-red, not hass automations. got it figured... sigh. i had a typo as state.person.michael.last_changed instead of states.person.michael.last_changed
Maybe you folks could help me out over here. I'm attempting to use the HA camera proxy (https://www.home-assistant.io/integrations/proxy/) to grab a thumbnail from a camera and send it as a notification. The proxy requires a rotating token, so I need to send it in my automation, but its not working. This is my test in dev tools. I get the message. I can see the token in the message data, but no image.
service: notify.mobile_app_zac_s_phone data: message: "{{ state_attr('camera.camera_proxy_camera_side_lanai_door', 'access_token') }}" data: image: >- "https://hahalol.ui.nabu.casa/api/camera_proxy/camera.camera_proxy_camera_side_lanai_door?token={{ state_attr('camera.camera_proxy_camera_side_lanai_door', 'access_token') }}"
How do you get Jinja macros to load from custom_templates?
Yeah that's what I was reading, but I can't find that homeassitant entity to execute
What does that mean?
I feel like I'm missing something basic but googling it just turns up results of people just as confused as me
It goes in whatever template where you're using the macro
Import it, use it. As in the last example
homeassistant.reload_custom_templates
How do I do this ^
I've got the macro defined in a jinja file and I'm importing it into a template script
but it says it cant find the template file, and I can't figure out how to get it to load the file
service: scene.turn_on
target:
entity_id: |-
{% from 'scene.jinja' import set_scene %}
{{ set_scene('fluro') }}
Executed: July 25, 2023 at 5:12:14 AM
Error: Error rendering service target template: TemplateNotFound: scene.jinja
/docker/homeassistant/config/custom_templates$ cat scene.jinja
{% macro set_scene(name) %}
{% set state = states("sensor.last_alexa") %}
{% set device = state.replace('media_player.', '') %}
{% set arr = device.split('_') %}
{% if arr[1] == "s" %}
{% set room = arr[0] ~ arr[1] ~ arr[2] %}
{% else %}
{% set room = arr[0] %}
{% endif %}
{% set scene = "scene.fluro_in_" ~ room %}
{% if states(scene) is defined %}
{{ scene }}
{% endif %}
{% endmacro %}
I've tried random reload commands from the 'c' menu
Go to developer tools > services and call that service
Open your Home Assistant instance and show your service developer tools
ahh thank you
might be an idea to put that in those docs, because I found lots of people just as confused as me
I hate having to resort to bugging humans for help
docs are editable via the buttons at the bottom
I think I got the Jinja template call right, but I'm not sure
it's formatted differently in various places
Press M while on developer tools > services, you will be redirected to a page which provides my links
I would use that 🙂
trigger:
- platform: time
at: '19:00:00'
condition:
condition: template
value_template: "{{ next_scheduled_trash_day == (now().date() + timedelta(days=1) ) }}"
could i turn this into a calendar trigger?
no
I didn't think so, but figured it was worth a sanity check
Would it be more efficient to turn it into a template trigger instead?
i.e: 7pm the night before
So, I have the following:
- alias: 'Trash night reminder'
id: trash_night_reminder
variables:
next_scheduled_trash_day: "{{ (state_attr('calendar.trash_schedule', 'start_time') | as_datetime | as_local).date() }}"
next_trash_holiday: "{{ (states('sensor.next_trash_holiday') | as_datetime | as_local).date() }}"
holiday_data: "{{ state_attr('sensor.next_trash_holiday', 'data') }}"
trash_period_end: "{{ next_scheduled_trash_day - timedelta(days=1)}}"
trash_period_start: "{{ trash_period_end - timedelta(days=6)}}"
trigger:
- platform: time
at: '19:00:00'
condition:
condition: template
value_template: "{{ next_scheduled_trash_day == (now().date() + timedelta(days=1) ) }}"
I have an error in my logs that says: Error rendering variables: TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'
I'm presuming it's related to trash_period_end and my usage of timedelta somewhere in there...
I've tried pasting my code into the template debugger tab and it seems to work
{% set next = (state_attr('calendar.trash_schedule', 'start_time') | as_datetime | as_local).date() %}
{% set end = next - timedelta(days=1) %}
{% set start = end - timedelta(days=6) %}
{{ end }}
{{ start }}
{{ next == (now().date() + timedelta(days=1) ) }}
that returns
2023-07-24
2023-07-18
True
Hello, how do I make the following work? the \ is not escaping the quote for the ' mark in the final replace statement:
Is it really returning a list?
It looks like you're trying to parse a list represented as a string
What would the better way to do this be?
I am not entirely sure. This is only my second go at templates but yes, I think it is a list
I suggest putting {{ state_attr('sensor.minecraft_server_players_online', 'players_list') | join(', ') }} in
-> Templates
Hi All, How to i change the type of a mqtt entity to a number? I have two entities sensor.tasmota_hx711_weight which has device_class: weight and reports a number/graph in the front end, and sensor.tasmota_hx711_weightraw which does not have a device class and thus does not appear as a number.
I have an automation that was supposed to run this evening at 7pm but instead just threw
Error rendering variables: TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta' in the logs
unit_of_measurement is what determines if an entity is numeric or not.
@tired sandal I converted your message into a file since it's above 15 lines :+1:
what am I doing wrong?
It's something to do with how I'm using those timedelta expressions but they all work in the templates tab
you haven't said what's wrong
Excellent! Works great! Thanks!
was that to me?
@inner mesa ^
I looked in the traces and it didn't even run the first step.
I took the condition out, reloaded and press "Run" in the automations tab with the same result leading me to suspect it's something to do with those variables at the top
but I can't for the life of me see what's wrong with them
your problem is this: (now().date() + timedelta(days=1) )
oh?
what's wrong with that?
It works in the template page
also, if i take that out - it still doesn't work
From the error message it sounds pretty clear that it must be these lines? Those the only ones with a -
trash_period_end: '{{ next_scheduled_trash_day - timedelta(days=1)}}'
trash_period_start: '{{ trash_period_end - timedelta(days=6)}}'
ah maybe
I wonder do variables always coerce their result back to string? It seems to think that your LHS of that subtraction are strings.
Ah that could be what's going on...
maybe i need to convert trash_period_end and next_scheduled_trash_day back into dates before trying to use it with timedelta
I would try that
One more similar issue: - type: conditional conditions: - condition: template value_template: "{{ state_attr('sensor.minecraft_server_players_online', 'players_list') is not none }}" card: type: 'custom:button-card' template: card_generic variables: ulm_card_generic_name: Player List ulm_card_generic_icon: mdi:account-group entity: sensor.player_list
I am getting the error conditions are invalid
Yes
you could create a template binary_sensor with that and then use that entity in your card
sensors:
date_long:
friendly_name: "Day of week, Date and Year"
value_template: >
{% set year = ["2023"] %}
{% set months = ["Jan", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %}
{% set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %}
{{ {{ days[now().weekday()] {{ now().day }} months[now().month-1] {{now().year }} }} }}```
Trying to make a custom sensor that will display the Day, Date and Year like this for example: Tuesday 25 July 2023
But I get the error:
Cannot quick reload all YAML configurations because the configuration is not valid: Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token ':', got '{') for dictionary value @ data['sensors']['date_long']['value_template']. Got '{% set year = ["2023"] %} {% set months = ["Jan", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %} {% set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %} {{ {{ days[now().weekday()] {{ now().day }} months[now().month-1] {{now().year }} }} }}\n'. (See ?, line ?).
Uh I am honestly not sure...I modified this from elsewhere and tried to make it better but now have that error
Can I just remove all of those squiggly brackets?
no, you just need to have the right number in the right places
without really knowing what you're tyring to do....
Right...I am still rather new to templates so how can I fix it?
My aim is this
{{ days[now().weekday()] }} {{ now().day }} {{ months[now().month-1] }} {{ now().year }}
all of that is kinda unnecessary, really
use {{ now().strftime('xxxx') }} where xxxx is a format string comprised of things from https://strftime.org/
That worked, thanks!
Ah okay
So that would enable me to remove the set year etc definitions and just use the strftime stuff
So the template output line is all that is needed
yes
I will give that a go, thank you
the only reason that you would need to do what you had earlier is if you were trying to translate into a different language, for instance
Ah true
sensors:
date_long:
friendly_name: "Day of week, Date and Year"
value_template: >
{{ now().strftime('%A') }} {{ now().strftime('%-d') }} {{ now().strftime('%B') }} {{ now().strftime('%Y') }}```
Nice and short now
Very good
you can just put all that together
Remove all the { in between?
{{ now().strftime('%A %-d %B %Y') }}
Oh sweet even better
Great that works
The more you know
Seems like template newbies like me just add masses of unnecessary code everywhere lol
Not my first time doing that and not my last
first get it working, then optimize
Hi All, How to i change the type of a mqtt entity to a number? - Is this done with a template? I have two entities sensor.tasmota_hx711_weight which has device_class: weight and reports a number/graph in the front end, and sensor.tasmota_hx711_weightraw which does not have a device class and thus does not appear as a number. I would like sensor.tasmota_hx711_weightraw to be a devivce_class: weight
What do you mean by 'appear as a number'?
What im meaning is sensor.tasmota_hx711_weight shows as a graph when you click on it, whereas sensor.tasmota_hx711_weightraw shows as a "history line"?
Sorry didnt see the reply 🙂 so how do i acually add unit_of_measurement? It gets overwritten once MQTT updates the value again.
Hi,
I have this template
{{ states.sensor
|selectattr('object_id', 'search', 'lqi')
|selectattr('state', 'eq', 'unknown')
|map(attribute='entity_id')
|list }}
I want to list the state values of LQI sensors with a value less than or equal to 10.
How should I modify my template?
Thank you.
you have to use namespace when comparing numbers. Iterate the list and check each one after converting the state to a number. Then add it to a list inside your namespace object.
Hi, I seek assistance in order to understand fully the splitting of the config with "template: !include template.yaml"
quick confirmation please: is this the shortest to picking a random light out of my light group entities? {{expand('light.party_lights') |map(attribute='entity_id') |list|random}}
found an ancient listing in a script :```
service: light.turn_on
data:
entity_id: >
light.{{['frontdoor','dining_corner','symfonisk','kist','serre_chair',
'lounge_chair_long','home_theater','world_map']|random}}
yes
cool, thx for confirming
if the light group has an entity_id attribute, then you could make it shorter by using that
which it does
so...
{{ state_attr('light.party_lights', 'entity_id') | random }}
{{ state_attr('light.party_lights', 'entity_id') | random }}
hahaha
hehehe
you're the best. both of you 😉
but who's bester?

Walter Koenig. Obviously.
now for the best of the bestest: on creating a scene on the fly, can I use the entity_id light.pary_lights and have all lights stored in their current state, or would I need the template {{ state_attr('light.party_lights', 'entity_id') }}: - service: scene.create data: scene_id: before_party_mode snapshot_entities: - > {{ state_attr('light.party_lights', 'entity_id') }}
remove the - part and go with that
- service: scene.create
data:
scene_id: before_party_mode
snapshot_entities: >
{{ state_attr('light.party_lights', 'entity_id') }}
aarghh, I see I had this for my Hue group scenes: {% set select = states('input_select.hue_group')|slugify %} {% set group ='light.' + select %} {{group}} which only outputs the Hue group, and not the lights inside that (cant remember it didnt work btw, but thats besides the challenge).. had to turn it into this {% set select = states('input_select.hue_group')|slugify %} {% set hue_group ='light.' + select %} {% set names = state_attr(hue_group,'lights')|join('|') %} {{states.light|selectattr('name','match',names) |map(attribute='entity_id')|list}} to get the list of individual entitiy_id;s for the scene create.
(because Hue doesnt list entity_id's but names)
btw, need this after all, to reject powered-off lights {{expand('light.party_lights') |rejectattr('state','in',['unavailable','unknown']) |map(attribute='entity_id')|list}}
because:```
Logger: homeassistant.components.light.reproduce_state
Source: components/light/reproduce_state.py:122
Integration: Licht (documentation, issues)
First occurred: 14:44:11 (8 occurrences)
Last logged: 15:09:01
Invalid state specified for light.symfonisk: unavailable
Invalid state specified for light.home_theater: unavailable
{{ state_attr('light.party_lights', 'entity_id') | select('is_state', ['on', 'off']) | list }}
o right, that would be a smart way to prevent that rejector indeed! nice.
i have a threshold sensor on/off and i'd like to calculate duty cycle based on it (lets say in the last 24h), is this even possible with a template only?
Since the attribute returns a list of entity ids, you can also use has_value
{{ state_attr('light.party_lights', 'entity_id') | select('has_value') | list }}
that might do what you want
I really dislike has_value
I've stopped trying to get the has_value filter/function, I cant get it to be reliable when I think it is...
but that's a good use for it
i'm aware, and it does sound like a good idea, but i currently have no access to the machine, so web frontend only solutions are in my hand
although using your template does do what I need 😉 and its shorter
might be a first...
Entities always have a 'value' (state) 🙂
does_it_have_a_state_that_i_like_in_this_particular_instance()
yeah, but I only ever tried to use it eliminating in ['unknown','unavailable'] in its various forms
That’s all it should do
The original function got politicized to death and we ended up with has_value that looks at the entity_id
Thanks
I want to ask is there a way to change
|selecattr('state','eq','unknown')
By some comparison like
if states('entity') >=10
… no, that’s what I just explained to you.
You can't because states are always strings, and because of that you will be comparing the string "9" against "10" and "9" < "10" is false
applying filters to the incoming value before a test would be really great
better if it could be an expression
anything to avoid loops 🤮
Wasn't Petro working on that?
"thinking about it", as far as I recall. But hadn't come up with a good proposal
unfortunately you can't modify objects, and other syntax is weird. Something like selectattr('state'|float, 'gt', 5) doesn't make sense, so then you're down the road of trying to coerce the incoming value to match the comparison value or similar. And then you have a very limited use case
it would have to be a test, and I'm not sure how to get it through the politics
and I'd have to somehow pass tests to the test
it's all funky
unless I just make one that's for numbers only
that's probably the most common case and mistake
and ensuring that the types are properly comparable is probably only a good thing
Hello, I could use a little bit of nudge in the right direction.. I have the below...
- sensor:
- name: Lawn mower battery charging time
state: >
{% set x = states('sensor.time') %}
{% set t = 0 if states('switch.lawn_mower_charger') == 'off' else now().timestamp() - states.switch.lawn_mower_charger.last_changed.timestamp() %}
{{ t | timestamp_custom('%M minutes', false) }}
Questions:
- The above gets to 59 minutes and then once at 60, it flips back over to 00 minutes. To remedy this, I included %I for a 12-hour clock, but in a quick test, the output was "12" for the hour, while the minutes displayed correctly. How can I get it to continue counting and flip to "1 hour 00 minutes" once it gets to 60 minutes?
- Additionally, would I just use If/Elif/else statements to determine whether to output minutes or hours and minutes?
- Is there an easy way I can record the time it takes, maybe in minutes, so that I can perform a running average? For example, "On average it takes the lawn mower battery 47 minutes to charge". Currently once wattage for a smart plug gets low enough, I have an automation turn off the plug and send a notification that the battery is done charging and how long it took. However, when the plug turns off, the "Lawn mower battery charging time" goes back to "00 minutes" so I'm losing the value.
just make a duration sensor
- sensor:
- name: Lawn mower battery charging time
device_class: duration
state: >
{{ (now() - states.switch.lawn_mower_charger.last_changed).total_seconds() | int if is_states('switch.lawn_mower_charger', 'on') else 0 }}
unit_of_measurement: s
Thanks! That should give me some direction for my #1 and #2 above. For my #3, any idea what I'd need to use or look into?
that covers 1 2 and 3
as the display in the frontend will be HH:MM:SS
OH, did you edit question 3?
anyways, you can use that duration sensor to get an average
Yeah, sorry for the miscommunication. I did
or use it w/ min/ max statistics
The above didn't put it into HH:MM:SS.. it's in seconds. Furthermore, when I turn the switch from 'on' to 'off' it changes the charging time template back to 0. Not familiar with min/max function in HA; will have to look into that.
Apologies for what I'm sure is the obvious miss on my part, but how do I get it in a format other than "0"? And will min/max allow for averaging of all historical data prior to it flipping back to 0, while also ignoring 0?
it put's it in HH:MM:SS only in the frontend
under the hood it will be seconds
i.e. the states page
it's so your device can have a history, as well show a meaningful state in the UI.
Thanks for sharing! For some reason the "combine state for several sensor --> Arthimetric mean" is going back to zero immediately after turning the switch off. I'm guessing that's because the switch is off most of the time.. I think then this would apply to me "If you have spikes in your values (like 0 in my case?), it’s recommended to filter/equalize your values with a statistics sensor first." found here - https://www.home-assistant.io/integrations/min_max/
Do you agree with my assumption?
just use the statistics sensor set to max over the past 24 hours if you charge once a day
that will give you the most time it took
then average the past x days
Good stuff. Thank you
How do you convert 2023-07-26T19:35:28.947351Z to 07-26-2023 3:35:28 PM? Or / instead of - for the output
Thanks
Where did that come from?
is it a datetime object?
I don't think so. | to_datetime doesn't work
that's not a thing
|as_datetime is
this works fine for me: {{ "2023-07-26T19:35:28.947351Z"|as_datetime }}
then: https://strftime.org/
Is as_datetime a Jinja thing or ha filter
I wish Ansible had an equivalent or a native jinja way
so...you're not asking about a template in HA?
Not necessarily lol. Now it's more of a jinja question.
for whatever reason, I thought we were talking about HA 🙂
dan doesn't follow the rules
I only ask when it's quiet lol
Better jinja people here than the Ansible server
Okay - thank you - this actually really helped - now my script is working. I am however working on integrating the script into a sample automation. Here I have if a sensor detects presence, and the speaker in the room is not playing whatever is being played (if there is something being played elsewhere - it calls back to the script to see if there is a return) then office speaker join the rest of the group - wait 30s - stop music elsewhere. However, my office speaker does not seem to be joining the group. Any obvious flaws you (or anyone!) could point me to?
@edgy flume I converted your message into a file since it's above 15 lines :+1:
I founded solution for that:
{{ states.sensor
|selectattr('object_id', 'search', 'lqi')
|selectattr('state', '<=', '60')
|map(attribute='entity_id')
|list }}
the point was this:
{{ '6' <= '50' }} -> false
as was already pointed out here: #templates-archived message
so you didn't founded anything
Sorry,
I mean has found
What is a better(and working) way to do the following?
sensors:
player_list:
friendly_name: Players on Server
value_template: >-
{% if is_state_attr('sensor.minecraft_server_players_online', 'players_list') %}
{{ state_attr('sensor.eastern_edge_minecraft_server_players_online', 'players_list') | join(', ') }}
{% else %}
No Players Online
{% endif %}```
I currently have a template condition that looks like this:
- condition: template
value_template: >-
{{
(forecast | selectattr('temperature', 'le', freezing_temp)
| selectattr('condition', 'in', conditions)
| list
| length) > 1
}}
Is there a more elegant way to test if a list has a given length?
something like
['foobar'] | hasLength(1)
i thought about doing
forecast | selectattr('temperature', 'le', freezing_temp)
| selectattr('condition', 'in', conditions)
| list
| length
| first is defined
but I don't know if that's like to just cause more issues
You don't need the extra parentheses, but the way you did it is the way it's done
good to know, thanks
@tired sandal I converted your message into a file since it's above 15 lines :+1:
Ignore that - I just realized this is #templates-archived, I'll take my question to #automations-archived
You are specially rejecting the office speaker from the group
{{ (upstairs_playing + main_floor_playing + basement_playing) | reject('eq', 'media_player.office') | join(', ') }}
hello, I have a question. I am transferring from yaml mode to storage mode. I don't know how to use ui-button-template.yaml in storage mode.
it seems im blind, but based on the docs I was not able to find the allowed properties of a template sensor, can anyone guide a blind guy x_x
Sounds like something for #frontend-archived
What do you mean with priorities
a template sensor can have a attribute called: unit_of_measurement or device_class but not "fruit"
sorry it was missleading to say property instead of attribute
My guy, I'm not trying to lead you astray. There is no 1 liner or replacement that will work. You are comparing strings there. With strings a value of '9' is greater than '10', or '100'. That template will not work. You have to do what I said in my original message. There is no way around it.
hi, i want to get a list of all entity ids that have a specific device class like humidity from an area. i know we can do something like this to print out all entity ids that are assigned to this area, but cant get the filter right. can anybody help me out?
{{ area_devices('wohnzimmer') }}
{{ area_devices('wohnzimmer') | select('is_state_attr', 'device_class', 'humidity') | list }}
amazing thanks alot
i have 2 slides, i want to control it by only one and set value from this one on the both slides, how can i do this?
I only have one slide at my lakehouse
I have one in the garden for the kids
Whyyyyyy don't I get this... Why aren't all date/time "offset-aware"? What juggling would I need to compare these please?
TypeError: can't compare offset-naive and offset-aware datetimes```
Should I make timestamps of it and then compare? What would be the best way?
just add |as_local
|as_datetime|as_local is a typical idiom to generate a timezone-aware datetime
one of the few I didn't think of trying... thank you!
Thanks
How can I make sure value I am setting is a datetime please? - service: input_datetime.set_datetime target: entity_id: input_datetime.morning data: datetime: >- {% from 'pod_macros.jinja' import pod_calc_morning %} {% if pod_calc_morning() not in ['invalid'] %} {{ pod_calc_morning() }} {% endif %}
my if statement here did not do any good...
macro seems to return a string which this does not take as a valid input... How can I convert it?
Impossible to say without seeing the mysterious string
It looks like this 2023-07-28 06:01:00
I have tested the macro, and as a safeguard I set it to always return at least input_datetime.morning, so it shall always have a value at least, just not an accepted one...
Thanks, I think it changed to the next now "day", will fix the rest, perhaps good now. Thanks for the help
Thanks, I think I got it working for this use-case, but what about whitespaces?
if you'r not careful, the macro will return something like 2023-07-27 10:07:00.392705+02:00
so with whitespace in front of it, or empty lines
which will make it invalid input for something like as_datetime()
Ah, gotcha. I have taken care of that part. I thought you meant spaces in the string returned, ie the part that holds the info
I want to get alerts when a specific integration (Unifi Network) when a new device_tracker entity is added. I can see the number of such entities using {{states.device_tracker|count}} - do you all know - if I make a template sensor using this template, will it work? I'm concerned that this won't get automatically updated because it doesn't include a specific device or entity for automatic triggers. I wouldn't know what trigger to write, for example. (Cross post from #general-archived, new here. Thanks)
That template will be rendered every second if I'm not mistaken
thanks! i just discovered that i can listen to entity_registry_updated events
description: ""
trigger:
- platform: event
event_type: entity_registry_updated
event_data:
action: create
condition: []
action:
- service: notify.persistent_notification
data:
message: "New entity added: {{trigger.event.data.entity_id}}"
title: Entity registry updated
mode: queued
max: 10```
the same trigger could be used in a template sensor to limit the update churn.
that's a cool feature
Is there an easy way to subtract time. 02 - 4 = 10 rather than 02-4 = -2
Yeah that
Mistyped
I figured out the utc to est by the way. A bit of a challenge
This is a new one lol
Do you have an example of how that would work with just hours?
you can't, you need to use datetime objects
otherwise you have to build the logic yourself
Nevermind I do have the ability to use a datetime object
Doesn't this mean I need 2 datetime objects?
Yes
How do I get the second? If I only have 1 time reference and I need to go back 4 hours?
Lovely not supported by Ansible
{% set m = 2 %}
{% set result = ((m + 12) - 4) % 12 %}
{{ result or 12 }}
0 or 12
try it out in the template editor
Attempting to replicate lol
literally just do 0 or 12
Got it lol
How did thefes even know how to do all that math
I didn't even know what a % did until just now
how to write this template condition instead I think it will be much more easier for me:
choose:
- conditions:
- condition: trigger
id:
- any-light-toggle
- condition: state
entity_id: input_boolean.vacation_mode
state: "off"
conditions: "{{trigger.from_state.state == 'any-light-toggle' and states('input_boolean.vacation_mode == 'off'')'}}"
Or Im someone got wrong?
trigger.id
It's not conditions for a template
choose:
- conditions:
- condition: template
value_template: "{{ foo }}"
sequence: []
hey guys, im trying to do a sort of replacement for the ${name} / substitutions there is in ESP home. I want to chose a name for an entity e.g switch.person1_thingy and switch_person1_door and somewhere else just define the number of the person, so I dont have to change everything everytime.
As far as I can tell, this should be possible with a template to chose the correct entity, but I simply cannot catch a break. Any thoughts ?
so if I define a variable per the person number
variables: number: !input person_number
and then do a template for the entity id, that inserts the variable into it.
- service: switch.turn_on target: entity_id: "{{'switch.person'+number+'_thingy' }}"
Is this at all possible ?
entity_id: switch.person{{number ~ '_thingy'}}
or
entity_id: switch.person{{number}}_thingy
if your number is a float, you need to convert it to an int
number | int
holy ********** that worked... wth man... thank you so much... spent three hours trying this /
service: scene.turn_on
target:
entity_id: >
{% if is_state('input_select.luxafor_effects', '🔴') %}
{% set scene = "scene.luxafor_1_red" %}
{% elif is_state('input_select.luxafor_effects', '🟡' %}
{% set scene = "scene.luxafor_1_yellow" %}
{% else %}
{% set scene = "scene.luxafor_1_green" %}
{% endif %}
{{ scene }}
not working - is it because of the emoji?
or can you not use {% %} tags here
Missing a closing ) in the elif
I have a fan that has a speed percentage. I want graph that speed on a chart, so I think I need a sensor entity with that value. How can I extract that value from a fan in a template sensor?
first go to developer tools and look at what attributes are there in the fan entity. something like "percentage" or "speed" is probably one of them. then you can use a template with state_attr()
thank you, that's exactly what I needed to know
Sorry, it‘s possible very simple, but I don‘t seem to get behind it. How can I display the state icon from a binary sensor group which is defined as window. The group don‘t have a defined icon, only the option display as window. I tried {{ state_attr('binary_sensor.wohnzimmer_fenster', 'icon') }} , but that don‘t seem to work
@oak cairn I converted your message into a file since it's above 15 lines :+1:
the enties of my bulb are ...light.living_room_bulb
button.living_room_bulb_identify
select.living_room_bulb_start_up_behavior
number.living_room_bulb_start_up_color_temp
number.living_room_bulb_start_up_current_lev
sensor.ewelight_zb_cl01_|qi
sensor.ewelight_zb_cl01_rssi
If you want an easy way, create a light group (light.hall in the example) for your bulbs you want to count and use a template sensor value similar to:
If those are your only bulbs you can use
"{{ states.light | selectattr( 'state', 'eq', 'on') | list | count }}"
to count all of them. You also might want to consider using the modern formating for template sensors. See the Docs for more information.
template:
- sensor:
# ------------------------------------------------ Lights on Count
- name: Total Lights On
icon: "mdi:lightbulb-group-outline"
state: "{{ states.light | selectattr( 'state', 'eq', 'on') | list | count }}"
I can't help with the button card, you could set the icon colour in the template and set the icon differently depending on whats on.
did you found solution to create image from graph?
nop
this prop could be done via the api i guess but didnt look into it
that's shame
I just found this, so maybe via Grafana it's possible https://stackoverflow.com/questions/55377907/programatically-export-images-png-jpg-of-grafana-dashboard
i do not have my data in grafana :p
that's easy to add 🙂
When clicking on an entity and select history in the ui you can see what triggered or changed the device or entity. When a user changed it you can see it in the history too at the very end. Is there a way with templates to get the last state change and check which user triggered it? or atleast if it indeed was a user or the system itself. The reason i ask is, i have an AC which is fully automated. but when we intervene in this proces i want an automation to pick it up and put on a boolean called manual. after which all ac automations will not met the condition. I have everything setup like this but at the moment i let every automation put on an boolean so i know its the automation that did something and an automation to check the state of the ac. when the state changes it checks if the boolean is on and if not it means a person did something and then a manual boolean is turned on. I want this to be more acurate. So i am wondering on a state change if there is a way to check if a user made a service call or an automation did. i use things like states.sensor.deurbel_action.last_changed and i wonder if i can also get the user from something like this
You have to use the context object to get the user_id and corelate that with the person entity that has an attached user.
it also only works when inside the action section
{{ states.person | selectattr('attributes.user_id', 'eq', context.user_id) | list | first | default("No user") }}
so you can't use it in the condition section?
you can, but the code changes
iirc you need to use the triggers context object instead
trigger.context.user_id
ah right
we came across that some time ago, now I understand a bit more why
going off memory here
yeah
it's odd but makes sense
the context only gets passed to the action section for some reason
odd, but makes sense
yes
But IMO, the object should be passed directly after the trigger
the object exists, but it's not updated
so 🤷♂️
is it possible to get the device_id for a given entity_id (actually, i am tracking down a way to find out the integration that created an entity)
second link in the channel topic will be helpful for these questions
I don't have a straightforward answer to how to get back to the integration from an entity
this thread isn't promising: https://community.home-assistant.io/t/how-to-get-an-integration-name-for-an-entity/447635/5
{%
set device_id = ["light.primary_bathroom_shower",] | map("device_id") | list | first
%}
{%
set integration_name = device_attr(device_id, 'identifiers') | list | first | first
%}
{{integration_name}}
thanks RobC. i'll look at it. i was able to get the integration name for an entity that actually has a device. but some entities (i guess) don't have an associated device...
I was thinking about that, but I wasn't sure if that's always the case
and that, yeah
if you could get a list of integrations (which I don't think you can), then you could iterate over their entities looking for the one you want
thank you, this is much better:
{{ device_attr(entity_id, 'identifiers') | list | first | first }}
unfortunately it still doesn't work for the entity i'm trying to track down (a device_tracker entity that i happen to know comes from Unifi integration)
it does look like identifiers is defined that way, so that's a good way, as long as there's a device:
identifiers Set of (DOMAIN, identifier) tuples. Identifiers identify the device in the outside world. An example is a serial number.
this post shows how to enumerate (some/most) integrations: https://community.home-assistant.io/t/how-to-enumerate-entities-belonging-to-an-integration/343748/6
but it also seems to rely on entities having device_ids
basically, i'm trying to write an automation that does something automatically when an entity is added by a specific integration
