#templates-archived
1 messages Β· Page 46 of 1
I checked there and non of my lights have the entity_id value for some reason
If it's on, last_changed is when it was turned on
Is there a option i need to select for them to show?
Huh, while thank you :))
Also last question for the last_changed how would i measure in a if command if its been on for longer then 10 minutes?
selectattr('last_changed', '<', now()- timedelta(minutes=10))
really love that notation/syntax, makes it so clear and fault tolerant. yet cant find the correct syntax using that in an automation condition replacing smthng like: {{(now() - trigger.from_state.last_changed).total_seconds() > states('input_number.presence_timer')|int(default=60)}}. the timedelta can be used like timedelta(seconds=states('input_number.presence_timer')|int(default=60)) but how to get that condition working..
this might be valid:```
{% set period = states('input_number.presence_timer')|int(default=60) %}
{{now() - timedelta(seconds=period) > trigger.from_state.last_changed}}
testing..
Does the "last triggered" attributes still work?
why wouldnt it?
what are you trying to do?
Im trying to turn off lights that have been on longer then 5 minutes
service: light.turn_off
data_template:
entity_id: |
{% for entity_id in states.light -%}
{%- if states.light[entity_id].state == "on" and states.light[entity_id].attributes.last_triggered is defined -%}
{%- set last_triggered = as_timestamp(states.light[entity_id].attributes.last_triggered) -%}
{%- if (now().timestamp() - last_triggered) > 300 -%}
{{ entity_id }},
{%- endif -%}
{%- endif -%}
{%- endfor %}
This is my code
But for some dumb reason non of the lights are turning off and its not workingπ
Any idea?
On why its not working?
Im thinking of just switching over to python/appdaemon but i still wanna learn templating so that's why im doing it on that
last_triggered is not an attribute of a light entity
π
Your looking for last_changed
And I already gave you the filter you should add to your template
Still no need for a loop
I did
I now get TemplateError: Invalid entity ID 'light.light.genio_led_strip_light'
That's because you are adding light. to your entity_id which it already has
But you are not listening to what I'm saying
Hmm?
{{ states.light | selectattr('state', 'eq', 'on') | selectattr('last_changed', '<', now()- timedelta(minutes=10)) | map(attribute='entity_id')|list }}
No need for a complicated for loop
The point for the loop is so i can put it in a automation as in
Instead of making a new script yk
You can just put the output of my template in a service call
And data_template has been depreciated for over 3 years, just use data
Wait so
Well
Im dumb xD
Wait so I didn't need to cycle through every light because entity_id accepts lists as well ;-;
oh wait fuck i just realised
i can't do that especially when i need the rooms they
are all in too lmao or what rooms the alexa is in with them
You can add a filter by area to TheFes' template. I hope you have a lot of conditions on that automation or people sitting in the rooms with lights are going to be unhappy. I have an automation for each room which is conditioned on occupation of the room and the light levels.
Ok course you could simply use the area directly in light.turn_off if any of the lights in that room are on.
yeah, and you dont even need to check if they are on....
okay okay so BASICALLY why i choose this option instead is because i want it to send a alexa actionable notification to the room that the light is on in asking the person if alexa can turn OFF the light and if it does then it turns it off if not keeps it on
for this usage i do
Ofc you have your goals I might not grasp. What I meant was that for turning off lights in a particular room, you donβt need to check if theyβre on. Simply issue the turn_off command to that room will turn them all off. It will only affect the light that was on, and if no light is on it wonβt hurt either
true true fair point
can even add the area to the service: service: light.toggle target: area_id: library π and compare that to the data template we had to use before the area coudnt be set as a target (long time ago....) {{expand(area_entities('library'))|selectattr('domain','eq','light') |map(attribute='entity_id')|list}}
I am trying to avoid asking other people and trying to figure it all out myself but i continously get stuck and run into errors and then spend hours on trynna figure it out and then get no where in the end
sure, but you need to start with answering #templates-archived message . you've come to the right place, and no issue at all asking. just help us help you
mmm thank you :)) and i will indeed try to help out in the community more :>
also if i may ask how do you check what attributes a entity has? i checked the states but it doesn't appear to be showing them all i was wondering if there was a way to get a list through the template editor?
? that is not what I meant.... I meant saying you need to start with explaining what you want to achieve. And not start with some technical solution that might not be the best solution for your requirement at all.
in attributes column in dev tools states,
ohhhh okay yep i'll try be a little bit more indept about what i want to achieve from now on :>
Right now i'm currently trying to figure out a way to try figure out what room a light is currently in
i tried attribute.room or area but it doesn't appear to be a attribute lmao
but you cant just try things. you need to follow the HA architecture π all explained in the docs....
btw, and this is an example of we needing to understand what you want: if all you want to do is show the 'on' lights in an area in your Dashboard view, you wouldnt need a template at all. You could simply use an auto-entities card in the dashboard and have that do the work for you...
just saying
okay okay so, what i am trying to get from the template is a list of alexa devices entity_id which are in rooms that have a light on in so i can use the alexa's entity id to activate a actionable notification.
- type: custom:auto-entities
card:
type: entities
title: Lights 'on' in Library
show_empty: false
filter:
include:
- domain: light
state: 'on'
area: Library
i decided to refer back to the for loop again xD
{% for light_entity in states.light %}
{% set light_room = states(light_entity.entity_id, 'attributes.room') %}
{% for alexa_entity in states.media_player %}
{% if states(alexa_entity.entity_id, 'attributes.area') == light_room %}
Light Entity: {{ light_entity.entity_id }}
Light Room: {{ light_room}}
Alexa Entity: {{ alexa_entity.entity_id }}
{% endif %}
{% endfor %}
{% endfor %}
but what i find i get with this is it loops back to me all the lights whom have the state "Unavailable " in it
the end goal of this entire automation is to hopefully be able to check which lights are on and if they've been on for longer then 15 minutes if so it sends an actionable notification to the local alexa relevant to that light that is on asking the people in that room if they want to turn the light off. If no response is heard or a yes response is heard then turn it off else if a no response is heard then leave it on
A light doesn't have a room attribute
yeah sorta realised that xD hoping it did but i guess not xD
Check in developer tools > states
is there any of way of detecting which room a light is in?
It's a function
area_name('light.some_light') will give you the area name of that entity
where's the documentation for that?
In the templating docs
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
2nd link
does anyone happen to know how you could possibly detect who send event as a condition?
thank youuu
@spring thicket I converted your message into a file since it's above 15 lines :+1:
- condition: template
value_template: >-
{{ trigger.event.context.user_id ==
states("media_player.brandon_s_bedroom_alexa")}}
This will never be true, the user id will never match the state of your Alexa entity.
Check the automation trace to see how a user_id in the context variable looks like
oh yeah i seen it lmao
would you happen to know anyway to check what device triggered the event?
Unless it's sent a part of the event (in the event data) I don't think you can
ahh damn thank youuu
If you have alexa media player installed you can use the sample there to get the last used player. This should normally be the one which triggered the automation. I use it to send tts to when something is called from them. I use different script data parameters so I know if the call came from Assist or Alexa or the dashboard
What do I have wrong with this? I am trying to use it in a markdown card.
{{ iif(is_state('sun.sun', 'above_horizon'), "Sunset is at" 'as_timestamp(states('sensor.sun_next_setting')) | timestamp_custom('%-I:%M %p')', "Sunrise is at" {{ as_timestamp(states('sensor.sun_next_rising')) | timestamp_custom('%-I:%M %p') }}.
I figured, I tried a bunch of different things and could not get it right
I have it working in multiple lines
It is part of a longer weather forecast string in a markdown card
This works, in the template editor:
{% if is_state('sun.sun', 'above_horizon') %} Sunset is at {{ as_timestamp(states('sensor.sun_next_setting')) | timestamp_custom('%-I:%M %p') }} {% else %} Sunrise is at {{ as_timestamp(states('sensor.sun_next_rising')) | timestamp_custom('%-I:%M %p') }}. {% endif %}
Then use that
No reason to use iif
especially if you don't understand string concatenation
Ok, thanks
hello, i'm writing automation that will do watchdog on several entities i.e triggered by state change from off to on for X munutes and turn it off. I cannot find syntax that will do action in a single line : instead of entity_id: switch.heater_kids_bathroom i want entity_id: {{ entity id that triggered me}}. I hope it's possible π
You need to surround the template in quotes. And it needs to be under data:
Or target:
There's example on that page
Hm.. so I've got an addon that gives the state of my dishwasher and I want to pull some of the states out to display in a template but Im kind of confused about something..
There is a state sensor.011090527032007221_active_program That in ha's Device and services shows the result as 'Eco50', but if I pull the state out via a template by calling that state, it shows up as Dishcare.Dishwasher.Program.Eco50
How the heck do I just get the "eco50" without the rest of the string? π (HA seems to doing this itself on the ui just fine)
Itβs an enum sensor
Check against that full string. Itβs used for translations
@limber haven ^
Ah, Im not sure what oyu mean by that
You have to use the whole value
Well, I'm not checking this against something for an automation, I just want it to display in the output as "Program Running : Eco50" not.. "Program Running: Dishcare.Dishwasher....."
Appologies if Im not understanding, Im very much struggling with templating π
The frontend should already translate it for you.
What does it show when you look at it in an entities card?
It looks correct in a Entities card, shows up as 'Eco50c' which is the result I want which is why Im quite confused π
Ok, so then you donβt need to template anything
Because itβs being translated for the front end
Well, I want this to be part of a title card is the thing, not an entitiy card so it wants it in a {{ .... }} format..
which is what is giving me the 'non-translation' string result rather than then actual translated result?
So {{ states('sensor.011090527032007221_active_program'}} returns the value Dishcare.Dishwasher....
Split the state on the . And grab the last item with [-1]
π Dishwasher Running - {{ states("sensor.011090527032007221_active_program").split(".")[-1] }} seems to work, thank you
Still confused why that was needed at all but... got there π
helo, i am running into an issue, i have some data that i send to home assistant via a webhook. and i want to filter out a perticular value. i want to filter out the 1st value of the orientaton array so i can compare this in an automation. can someone help me on how to do this. This is my template so far: message: "{{ (trigger.data.json | from_json).data.results[0].orientation }}"
this is the recieved code via webhook: json: {"hook": {"target": "https://webhook.site/5d76c3fd-0f55-4944-a338-0e326afc946e", "id": "camera-1", "event": "recognition", "filename": "camera-1_screenshots/23-05-08/14-23-40.241128.jpg"}, "data": {"camera_id": "camera-1", "filename": "camera-1_screenshots/23-05-08/14-23-40.241128.jpg", "timestamp": "2023-05-08T14:23:40.241128Z", "timestamp_local": "2023-05-08 14:23:40.241128+00:00", "results": [{"box": {"xmin": 317, "ymin": 247, "xmax": 362, "ymax": 261}, "plate": "p534sn", "region": {"code": "nl", "score": 0.519}, "score": 0.902, "candidates": [{"plate": "p523sn"}, {"plate": "p523sn"}, {"plate": "p523sn"}, {"plate": "vcg567"}], "dscore": 0.915, "vehicle": {"score": 0.769, "type": "Sedan", "box": {"xmin": 171, "ymin": 166, "xmax": 394, "ymax": 302}}, "model_make": [{"make": "Trabant", "model": "601", "score": 0.825}, {"make": "Trabant", "model": "P 601", "score": 0.1}, {"make": "Trabant", "model": "1.1", "score": 0.069}], "color": [{"color": "yellow", "score": 0.93}, {"color": "blue", "score": 0.01}, {"color": "brown", "score": 0.01}], "orientation": [{"orientation": "Rear", "score": 0.936}, {"orientation": "Unknown", "score": 0.032}, {"orientation": "Front", "score": 0.032}], "direction": 165, "source_url": "rtsp://gategate1:gategate1@192.168.178.102:554/stream2", "position_sec": 6577.5802705, "user_data": ""}]}}
The first score value?
No just the first orientation value. So in this case Rear
This software always places the correct value first in the array. So i want to collect this.
I always find using the Dev Tools a great help. Try
{% set json = json_str | from_json %}
{{json.data.results[0].orientation[0].orientation}}
My trick was to copy your json and set it to a variable json_str. That way you can drill down in the dev tool to find the right field and see what is going on as you do.
Also you might be able trigger.json directly as this should already be a mapped json string. So just
{{trigger.json.data.results[0].orientation[0].orientation}}
i have made it work with {{ (trigger.data.json | from_json).data.results[0].orientation[0].orientation in ['Front'] }} thanks for helping!
im having issues.. since this last update.. my esphomes dont work right works when HA loads up and then esphomes stop working for temperature.. but also my automations arent working when i use the imap... but here is the time errors.. i dunno whats wrong but its broke some of my stuff how do i fix it? TemplateError('ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%A %B %-d, %I:%M %p') }}' but no default was specified') while processing template 'Template<template=({{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%A %B %-d, %I:%M %p') }}) renders=34>' for attribute '_attr_native_value' in entity 'sensor.date_and_time' TemplateError('ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%I:%M %p') }}' but no default was specified') while processing template 'Template<template=({{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%I:%M %p') }}) renders=34>' for attribute '_attr_native_value' in entity 'sensor.display_time' TemplateError('ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%I') }}' but no default was specified') while processing template 'Template<template=({{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%I') }}) renders=34>' for attribute '_attr_native_value' in entity 'sensor.display_hour'
there are some more i just wasnt able to paste more
looks like sensor.date_time_iso isn't giving a valid state
But you could simply replace that with now().strftime('%A %B %-d, %I:%M %p') for example
how do fix that?.. i find this latest update.. is a bit flaky where automation may run but it does nothing... or my lights are reacking slow
so remove the timestamp custom then
Does sensor.date_time_iso give the current time?
ya 2023-07-09T10:33:00
I guess it's provided by this integration
I don't see any use for such sensors in templates, as you can use now() instead, like I've shown above
It used to be required to make templates update once per minute
Ah, right, I think I remember that change.
it's for translations. Pretty sure we've talked about this in this channel with other sensors/entities. States under the hood are untranslated. States in the UI are translated to the users language. Templates do not have access to the translated states.
Quick and simple but stupid question: I have a sensor called "sensor.peach" and would like to create a template that gives me it's name. Cant figure this out for the life of me....
{{ state_attr('sensor.peach','friendly_name') }} - if it has the attribute friendly_name
{{ states.sensor.aarlo_battery_level_family_room.name }}
that will fall back to friendly_name if it exists
Hey guys. I'm pretty new to this Home assistant stuff. I'm following a youtube video about how to install UI minimalist. But I have a problem for some reason is there anyone who is willing to help me?
<@&330946878646517761> can you guys help a rookie?
Do not do that
Thought if the ping function is not disabled for us we can use it lol
can you help me out. I have a small problem but can't find the solution
Pinging a whole group and not even asking a real question is kind of rude, no?
there was a real question I wanted to know if someone here is willing to help me out or not. So far it's a no.
It was not a real question: https://dontasktoask.com/
It can't really be answered because you didn't specify what you need help with.
Yeah good job you're nice!
I have an error saying that the Button-card template 'card_esh_welcome' is missing. BUT I believe I did everything right since I'm following a youtube video on it. What should I do?
Installed the button-card through HACS and added as a resource to the dashboard. Previously it showcased in the dashboard but after I started to config it not anymore
That's something one can work with but it's probably better suited for #integrations-archived or similar
it's from the UI Lovelace MInimalist template π but will post there as well
Hi, I created an image entity here that points a jpg snapstop/thumbnail from a camera:
#### Images
- image:
name: Bird Feeder Screenshot
url: http://homeassistant.local:8123/local/bird_feeder/blink_camera_still_image.jpg
despite the jpg file updating, the entity itself as above, does not update when the jpg updates. Do I have to add a refresh or reporting interval for this new entity?
thanks for help chatgpt code interpreter was quicker and solved it for me
you can provide a time_pattern trigger
or you can use this: https://www.home-assistant.io/integrations/folder_watcher/
it even has an example of watching for an image update
is it possible to convert the state values in the following template from string to float without "dissecting" it (ie using filters or something and without using a loop etc.)
{{states.sensor|selectattr('entity_id','contains','battery')|selectattr('state','match','^[0-9.,]*$')|list}}
like |map('float')?
those aren't actually state values, either
so |map(attribute='state')|map('float')
yeah that converts it to a number, but i want it to retreive the entity id for the given states. so i have
{{states.sensor|selectattr('entity_id','contains','battery')|selectattr('state','match','^[0-9.,]*$')|map(attribute='state')|map('float')|select('lessthan', 25)|list}} which returns [21.0, 0.0, 22.0] but i want to return the entity ids, associated with those value
You need a loop for that
bleh, okay. ty
Thanks Rob!
Hi, from this Sensors: {{ expand(area_entities('Bathroom')) | selectattr('domain', 'eq', 'sensor') | map(attribute='entity_id') | list }} Can I single out only humidity sensors for example?
it returns a list of sensor-entity_ids in the bathroom
I tend to change the name more often than I really want, so would be good to have automations/scripts read this runtime
Got it! Humidity_sensor: {{ expand(area_entities('Bathroom')) | selectattr('entity_id', 'search', 'humidity') | map(attribute='entity_id') | list }}
but.... when I now have the entity I need in a variable, how can I get the state using it? states(hum) didn't do it...
states takes a string, not an entity. maybe try either hum.state, or states(hum.entity_id)
hum is a variable holding the resulting list
From a list of all sensors in the room, single out only humidity sensors and read their values
So a list of states?
I suppose that would be it, yes
Replace the last entity_id with state
Nice! I wish this wasn't so cryptic... That worked nicely, thanks!
So how would this work if I add another humidity sensor in there? It won't show a mean value, I get that, but...?
lol, sorry! As I only have one, I never had to explicitly select one...
Ok. I have thought some more and think it would be useful if the above returned a named array, such as "{{{'humidity sensor 1': 55, 'humidity sensor 2': 76}}}". That way I could then look up the values where needed, making the script more adaptive. Would it be possible to do?
yes, in a for loop using a namespace
Something like this? {% set areas = ["Hallway", "Closet"] %} {% set ns = namespace(l = []) %} {% for area in areas -%} {% set ns.l = ns.l + expand(area_entities(area)) | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list %} {%- endfor %} {{ ns.l }}
But where (how) do I build the array?
not like this
Ok, please guide me then π
you need to build it in the for loop
but in your example you have a dict (mapping) not a list (array)
oh. I'll have to figure where I go wrong then...
what do you want as result
{
"Humidity Sensor 1": 45,
"Humidity SEnsor 2: 50
}
or
[
{
"name": "Humidity Sensor 1"
"state": 45
}.
{
"name": "Humidity Sensor 2"
"state": 50
}
]
I'd like a list like this: "{{{'humidity sensor 1': 55, 'humidity sensor 2': 76}}}"
Then I can look-up a value for a specific entity with "humidity[entity_name]"
the second one is easeier to work with
oh, and you want entity_ids
your not providing entity id's in your example
the example was merely to see if I had grasped the idea, and apparently I hadn't...
{% set areas = ["Badkamer", "Woonkamer"] %}
{% set ns = namespace(l = {}) %}
{% for i in (areas | map('area_entities') | sum(start=[]))
| select('search', '^sensor.')
| select('is_state_attr', 'device_class', 'humidity')
%}
{% if states(i) | is_number %}
{% set ns.l = dict(ns.l, **{i: states(i) | float}) %}
{% endif %}
{%- endfor %}
{{ ns.l }}
replace the areas wiht areas you have
That is excellent... I so wish I understood the mechanics of this better! Thank you so much!
This was harder than I thought... Trying to lookup the value like this {{ humidity_sensor_values[humidity_sensor_entity_id] }} yields an error "UndefinedError: dict object has no element ['sensor.bathroom_weather_1_humidity']"... What am I doing wrong please?
@pastel moon you're inputting a list, but the key is a single item
humidity_sensor_entity_id does not contain a single entity_id, but a list with one item
{{ humidity_sensor_values[humidity_sensor_entity_id | first] }} will probably work
I was trying to simplify for me to understand, this is how I'd like to use the template, if it makes sense: {% set sensor = 'sensor.humidity_2' %} {% set humidity_data = {'sensor.humidity_1': 115, 'sensor.humidity_2': 204} %} {{ humidity_data[sensor] }}
this did work actually π
yes, that will work, but above you had:
{% set sensor = ['sensor.humidity_2'] %}
{% set humidity_data = {'sensor.humidity_1': 115, 'sensor.humidity_2': 204} %}
{{ humidity_data[sensor] }}
so the variable you were checking on was a list
so im having some issues with a template that used to work, but now does not seem to give the correct 'answer'
so even though 'sensor.goodwe_battery_mode' is '2', it is returning 'Unknown'
Ah! Now I get it! Thanks for your help and patience! π
does it return Unknown or unknown if you check in developer tools > states
I'd wager that the sensor was changed to an enum sensor
'unknown'
that means it's the |float
provide a default for it |float(0)
actually, it's also missing )
which means it would have never worked
are you sure this worked in the past or did you just have this convo with chatgpt today?
maybe i typod it just then, but it used to work
and i just had this chat just now
so change the | float < 50 to | float(0) < 50 ?
just add (0) to float
I purposely left out the rest to not confuse you
before you had |float but you need |float(0)
hmm, not working as yet.. let me check
well, you're still missing the )
its working in the template thing in developer tools
i must have stuffed something else up in the view
post your configuration
hmm, so now im really confused.. if i put the template in the developer tools, it shows the right output
but, when i check the state of that sensor in my card on the dashboard, it shows 'unknown'
hold on a sec
so in my yaml, i have this...
goodwe_battery_mode_desc:
value_template: >
{% if is_state('sensor.goodwe_battery_mode', '1') or (is_state('sensor.goodwe_battery_mode', '2') and states('sensor.goodwe_pbattery1')|float(0) < 50) %}
Idle
{% elif is_state('sensor.goodwe_battery_mode', '2') %}
Discharging
{% elif is_state('sensor.goodwe_battery_mode', '3') %}
Charging
{% else %}
Unknown
{% endif %}
unit_of_measurement: ''
friendly_name: "Battery Mode Description"
I'd wager you placed it in your configuration incorrectly. That's why I asked you to post your configuration
can you paste your entire configuration in that file
you want the entire yaml?
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.
you want the entire sensors.yaml?
as i said, this used to work.. but i havent checked it in a loooong time
so i assume some changes in HA broke it?
The template is fine now
Nothing in HA broke anything
did you reload template entities after your last change?
legacy templates are frozen in time essentially
they will never be removed?
seeing that he doesn't have a unique_id, reloading would make the first one unknown, and it would create a second sensor.goodwe_battery_mode_desc_2
well, as you said, i had to change float to float(0).. so something changed
yes, that was required about a year ago
so, that did change but, not anytime recently
so if it hasn't been working for a year, then that would be why.
just restarted HA, nothing changed.. still 'unknown'
for the love of god, can you please post your full configuration
whatever file it's in. Also post configuration.yaml showing the includes
it would have been a lot better if you pasted it as YAML, as the bot message mentioned
@marble jackal just click 'veiw raw'
hmm i didnt see that option
oooh, colors
and that is indeed a quite recent change
remove all unit_of_measurement: ''
yes, but it's for all sensors, not just template
let me rephrase, remove unit_of_measurement: '' for all non-numerical sensors
So anything that returns a word, remove that
It was never required
it was never required
ok
ditto
i wonder how i ended up with it in there then.. oh well
maybe you added it for badges?
some people would make the unit_of_measurement: '' so that it had a specific badge display in the frontend if you used badges
those little round things at the top of views
the power monitoring thing in my config has been broken for a long time
and it wasnt really important, as my solar was also pretty much broken
but its fixed now, so im looking at the config for it etc again
so they all need to change right?
if they are converting a sensor, there is a chance at startup that the value is non-numerical, which will cause the float conversion to fail, and subsequently cause the template to fail
as in i have to specify a default precision for each
that's not a precision
oh, default value
that's the value when it can't convert the state to a number
yeah, it's a rather annoying thing
you can also just add an availabilty template too
and backspacing
was just about to mention that.. Well let me add then that the new format also supports state_class
ok, that config is updated.. i guess ill check all others now too
thanks for the help
I wonder if someone can help me, i am pulling my hair out on this and having very long and repetitive conversations with chatGPT :P. I am sure i am just missing something really silly!
I have created a utility meter help (sensor.hall_lights_cost). This seems to be doing the job i expect, and is currently reporting 29 Wh
i have a sensor that monitors my per unit cost (1kWh) (sensor.octopus_energy_electricity_xxx_xxx_current_rate). This is working as expected and is reporting 0.3863265 GBP/kWh
I have created the following custom sensor
hall_lights_daily_rolling_cost:
friendly_name: "Hall Lights Daily Rolling Cost"
unique_id: "hall_lights_daily_live_cost"
device_class: monetary
unit_of_measurement: 'GBP'
value_template: '{{ "%.5f" | format (float(((states.hall_lights_cost.state|float(0)) / 1000) * (states.sensor.octopus_energy_electricity_xxx_xxx_current_rate.state|float)) | round(5))}}'
chatgpt isn't good for HA. it's quite out of date, and will freely lie to you
however, that sensor is always reporting Β£0.000000
the maths all add up as when i do the maths manually, i get what i expect the value of the sensor to show
I'd suggest trying each bit of that in the developer tools template editor. see what it looks like
IE
29/1000 = 0.029 * 0.38632 = 0.01120
like make sure that float(((states.hall_lights_cost.state|float(0)) / 1000) has the value you think it does
not really sure how i test that in developer tools
Go to developer tools. Go the the template tab. try {{ float(((states.hall_lights_cost.state|float(0)) / 1000) }}
Result Type: string
float(((states.hall_lights_cost.state|float(0)) / 1000)
(((states.hall_lights_cost.state|float(0)) / 1000)
same results in the results area just without float there
you're putting the {{ }} round it?
Sorry just on a work call give me a second
(((states.hall_lights_cost.state|float(0)) / 1000)
That's missing the domain of the entity(sensor), an even better and more robust approach is to change that line to something like this:
states('sensor.hall_lights_cost') | float(0) / 1000
ok so
(((states.hall_lights_cost.state|float(0)) / 1000) = Does not work (TemplateSyntaxError: unexpected '}', expected ')')
states('sensor.hall_lights_cost') | float(0) / 1000 = Does work, and shows 0.029
what should this one be?
(states.sensor.octopus_energy_electricity_19l3741410_1013022116772_current_rate.state|float))
in fact, would you mind showing me what the whole line would be? Still a little confused
currently its:
'{{ "%.5f" | format (float(((states.hall_lights_cost.state|float(0)) / 1000) * (states.sensor.octopus_energy_electricity_19l3741410_1013022116772_current_rate.state|float)) | round(5))}}'
Please check how you can access states in a correct way here: https://www.home-assistant.io/docs/configuration/templating/
AI will make things up or mix them up. The official documentation is always the place to start.
Than your code should like this
'{{ "%.5f" | format(states('sensor.hall_lights_cost') |float(0) / 1000 * states('sensor.octopus_energy_electricity_19l3741410_1013022116772_current_rate')|float(0) | round(5))}}'
I just added the missing domain in and actually that did work! But you clearly know better so i will use yours π
hmmm
i actually got an error using yours in the config checker
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 60, column 7
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 64, column 52
Basically, when you have a problem with a template, build it up from elements π helps work out where the problem is.
It could be that some ( or ) is misplaced. Didn't check it, only adjusted the syntax to the correct format
the difference between both approaches of accessing the entity states is:
Avoid using
states.sensor.temperature.state, instead usestates('sensor.temperature'). It is strongly advised to use thestates(),is_state()state_attr()andis_state_attr()as much as possible, to avoid errors and error message when the entity isnβt ready yet (e.g., during Home Assistant startup).
'{{ "%.5f" | format((states("sensor.hall_lights_cost") | float(0) / 1000) * (states("sensor.octopus_energy_electricity_19l3741410_1013022116772_current_rate") | float | round(5))) }}'
think it was the single speech marks
this worked
thank you
hmm, so now i am looking at my energy dashboard stuff.. it seems some 'sensors' that i used to use, are now missing
namely the _accumulated ones
Its a bit annoying the energy dashboard does not include the cost of the individual devices. Can';t work out why they didnt add that?
Thank you for your help. I want to take your advice and have one others i need to change. Would you mind showing me what that should look like?
format (float(((states.sensor.electricity_daily_cost.state|float))
is it
format((states("sensor.electricity_daily_cost") | float))
Just not sure what i should do with that first float that i have missed off
good question π I dont fully understand it. im just re using someone elses
Hello,I know this is a big question.
I have a sensor that should contain 12 lists of triples (spending date, spending name, spending value) as attributes (for each month). Based on 6 triggers the list should be changed (It is a new year, it is a new month, adding new entry, remove last entry (of this month), monthly cost should be added).
I have created that sensor, but every time I restart home assistant the sensor attributes are emptied. So they only contain an empty list. Here is my code (of the first 2 months 3-12 are the same as 2).
Any help would be awesome thank you β€οΈ
https://dpaste.org/xJMPw
Are you using 2023.7? It does say it should store trigger sensors, one thing I would be tempted to try is changing the state (eg put a timestamp in it). to ensure the save is triggered
Yes I am using the latest version. Ok, i will try this, thank you
Why does this, if the sensor is unavailable/ unknown not equals to [] ?:
{% set previous = state_attr('sensor.legro_finance_list','monthly_tally_'~month_number) | default('[]',true) %}```
because that's a string
Probably because you have the default set to '[]' and you are not testing if it is defined.
"unavailable" and "unknown" are perfectly acceptable strings
does that attribute exist when the sensor is unavailable?
no, it vanishes with all data in it
thisa does not work either :/
``` does this cover all possible errors that could happen to the sensor?
I got into the world of templates today and I have a couple very basic questions.
- I have a motion sensor in a mushroom card, and it's reporting the State "Clear" (this is by default, I did nothing). But when I call the state of the binary_sensor in a template, the State is "off" instead. Why? How can I use the nice name?
- How can I call the last-change of a sensor in a template?
to your first question, this is changed only in the front end. The sensor is 'off' or 'on'. In frontned it is interpreted as clear, etc.
got it, so I guess it's the mushroom card doing that by default. I will use an IF to give the names to the values. Thanks.
I changed now the sensor to this:
https://dpaste.org/mhN6O
now the attributes dont disapear after a restart, but the data in all the attributes is lost.
I would even pay with paypal if someone could create or change this sensor so it works.
like 10 bucks or so? I am really sad and I dont know what else to do.
(I hope this is ok, to ask for a payment here, it is not my attention to discriminate the server rules)
{% set previous = state_attr('sensor.legro_finance_list','monthly_tally_'~month_number) or [] %}
You have to use state objects to get the last_changed. states.sensor.xyz.last_changed
keep in mind, it's a datetime object
my second reply was to chaos
First of all thank you for the help
Thanks, yeah I managed. I used this: {{ relative_time(states.binary_sensor.front_door_contact.last_changed) }}
Any idea why the relative time is not updating every second though?
Mushroom card does update every second, but my template does every 30s or so, and doesn't seem consistent.
the mushroom card does every second π¦ Is there no way to achieve the same behaviour?
it does not, it just appears as if it is
the value doesn't change, the display changes based on it's distance from it
i.e. no calculation is occuring
when you're using a template, it's running a calculation, so it's throttled based on the calculation
relative_time will update on the minute
I get that. I cannot simulate that display change right?
nope, not without JS
got it. Not the end of the world
many cards just start their own timer
The mushroom card probably has the end time and uses javascript on the browser to count down.
yeah, I understand.
I replaced everything and tried many other notations of my code, but sadly I cannot save my data after a home assistant restart (this also happens if I fast restart.) Does anyone have an idea why my data is lost?
There's probably an error somewhere, sadly, its so overly complicated that it'll take a while for someone to debug
When I need persisting values, I use MQTT
I am more than willing to reward you or someone else for the efforts via PayPal. Because I know how much time this is gonna take.
Use elif rather than else if
I suspect part of the problem is some of your triggers have empty to values which means they will be triggered on a reload and could be triggered before the value of the sensor is set. I don't have time to look further in your code, I am afraid, I do know that my template sensors with triggers attributes are restored so that would seem to be the most likely reason.
You do not check to see if any of the sensors you need are unavailable in or unknown, so you potentially have updates before read.
What Jane explains is likely to occur when one of the trigger entities is also a template sensor
So you are saying that when my trigger sensors are initiated they maybe trigger my finance sensor.
Which is not setup at that moment, so the "or []" part comes in an "resets"/ overwrite my attributes.
Do you know a way how I can overcome this problem?
Maybe I can create an availabe_template in the trigger sensors, that they only are available when my finance sensor is initiated?
Is the last trigger another template sensor?
It might already help if you add not_from: unavailable
I have three devices (climate.ac_<room> with <room> some room names). I would like a template which would be true if any of the devices are in any of the list of states ['off', 'fan_only']
Something like states('climate.ac_kids') in ['off','fan_only'] for three devices
You can use is_state as a test in the select() filter
aha, is_state can take a list of states! thanks
value_template: "{{ value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first }}"
This return me:
{'type': 5, 'name': 'ltr578 Ambient Light Sensor Non-wakeup', 'vendor': 'Lite-On', 'version': 256, 'accuracy': 3, 'values': [38.36375], 'lastValuesTime': 1689072491531, 'lastAccuracyTime': 1689056526374}
How to get values[0] from this?
wrap it in parenthesis and get the valeus: (...).values[0]
or create a variable if you also want extract more values
{% set data = value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first %}
{{ data.values[0] }}
with: "{{ (value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup')).values[0] }}" I have unknown π¦
without [0] i have empty
because you removed | list | first for some reason
you wrote:
value_template: "{{ value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first }}"
I said:
wrap it in parenthesis and get the valeus:(...).values[0]
then you decided to remove|list | first
no, i found issue, values is build-method
is possibel to execute quick rleoad from ha cli?
value_template: "{{ (value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first)['values'][0] }}" # good
# value_template: "{{ (value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first).values }}" # bad
that access method is identical
['values'] and .values is the same
unless it's a dictionary item
then it's a function and .values won't work
Hey guys. I'm controlling a ceiling fan's speeds. I control it by turning on 3 switches in a particular group for each speed. Switch 1 and 2 on is low. Switch 2 and 3 on is medium and all 3 on is high. I need to set a trigger for 1 and 2 on and each of the groups described above to act as triggers in an automation. I was told that I'd probably need a template for this, but I don't know how that template would look. Can anyone give me and example of a template that would group multiple entities in a particular state, to act as a trigger?
I have everything working on the fan speeds. My problem is that I have icons in my front end that don't correctly reflect the state when the speed is set by turning on the switches independently. If I turn on a speed by turning on a group of the switches, the icon shows correctly, but if I turn on the switches independently, then the icon doesn't show the state. I hope I'm explaining this where it makes sense.
what are the 3 entities?
If I could just make multiple switches together act as a trigger, I think that I could make it right.
to write the template, you have to be able to define what goes into making the final value. like is it the highest of the three? the lowest? the average? a sum?
fan speed 1, 2 and 3
can you write the entity_id's out please
fan.fan_speed_1, fan.fan_speed_2 and fan.fan_speed_3
such an odd way to do that
so what behavior do you want when you turn the fan on?
or do you just want a UI item to set high medium low, off
I want no matter how the switches get turned on or off, that whenever the correct set of switches is on or off, the icon will show the correct state.
what icon
Let me get a picture of my setup
@fringe sail Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
Everything works correctly, except when I turn the switches on independently. If I could set multiple switches as a single trigger, I'd have no problem. I just don'y know how to do that.
I just want to be able to see what the switches are doing independently. They aren't needed to make anything work.
Some rare times the device in the fan housing don't turn on every switch as it should and I can see exactly what isn't on with the independent switches.
that's not answering my question, what's making those buttons at the top
Each of those is an input boolean and I have an automation that turns on the correct set of switches for each speed.
Ok, that's what I was looking for
instead of input booleans, make template switches
seems like you really want an input_select
you could aslo do taht or template selects
either way, you need something that responds to the value of the 3 switches
If I were in your shoes, I'd make a template select. Remove all the automations and input_booleans
you'd have 1 template select for each room.
I'm sure that you're right, but I'm not that good at templates. That's why I went the way that I did.
Can you give an example of what you're saying?
Yes, but are you willing to change your UI?
I'm tring to figure out what you want
if you want the same UI, then you need to make a bunch of template switches
if you don't care about the current UI that you have, then you can go another route
Can you show an example of a template select?
it's a dropdown
it'll have a menu that pops open and has 4 options: off, low, medium, high
you can also keep your buttons and just have each button choose a differnet option
but that won't feed back to his buttons, which is his problem
I guess that I need an example of a template switch
Ok, so you want to go the template switch route
I guess...lol. Before I do that though, is there a way to make multiple switches together as a trigger?
another question: If you turn on just fan switch 2, is the fan still at low speed or does it not have a speed?
You keep wanting to make an automation and it just won't work. You have to go a separate route.
no 1 fan speed does anything. It must be at least 2 speeds to do anything
so please, lets focus on the solution, not what you want the solution to be
so, if fan speed 1 is off, turning on fan speed 2 does nothing?
Correct
ok, that makes this more complicated, but it can be worked through
switch:
- platform: template
switches:
fan_low:
value_template: "{{ is_state('fan.fan_speed_1', 'on') }}"
turn_on:
- service: fan.turn_on
entity_id: fan.fan_speed_1
turn_off:
- service: fan.turn_off
entity_id: fan.fan_speed_1
that replaces your low input boolean and the automation that pairs with it
it will be a switch entity.
when you turn it on, it runs the turn_on actions
when you turn it off, it runs the turn_off actions
the value_template determines the state of that switch
so no automations are needed, it just knows
if fan.fan_speed_1 is on, that switch will be on
now, for medium...
- platform: template
switches:
fan_medium:
value_template: "{{ is_state('fan.fan_speed_1', 'on') and is_state('fan.fan_speed_2', 'on') }}"
turn_on:
- service: fan.turn_on
entity_id:
- fan.fan_speed_1
- fan.fan_speed_2
turn_off:
- service: fan.turn_off
entity_id:
- fan.fan_speed_1
- fan.fan_speed_2
high...
- platform: template
switches:
fan_high:
value_template: "{{ is_state('fan.fan_speed_1', 'on') and is_state('fan.fan_speed_2', 'on') and is_state('fan.fan_speed_3', 'on') }}"
turn_on:
- service: fan.turn_on
entity_id:
- fan.fan_speed_1
- fan.fan_speed_2
- fan.fan_speed_3
turn_off:
- service: fan.turn_off
entity_id:
- fan.fan_speed_1
- fan.fan_speed_2
- fan.fan_speed_3
if you need a delay between the fan.turn_on for each fan... use this instead for turn on/ turn off
turn_on:
- service: fan.turn_on
entity_id: fan.fan_speed_1
- delay: "00:00:01"
- service: fan.turn_on
entity_id: fan.fan_speed_2
so...weird
it really is
Maybe I'm wrong, but it seems that low speed should be like this, because fan speed 1 and 2 need to be on for low speed. Is this correct?
switch:
- platform: template
switches:
fan_low:
value_template: "{{ is_state('fan.fan_speed_1', 'on') }}"
turn_on:
- service: fan.turn_on
entity_id: fan.fan_speed_1
entity_id: fan.fan_speed_2
turn_off:
- service: fan.turn_off
entity_id: fan.fan_speed_1
entity_id: fan.fan_speed_2
Sure, if that's what's needed for low
but, your'e listing it wrong
- service: fan.turn_on
entity_id:
- fan.fan_speed_1
- fan.fan_speed_2
Ok I've got it. I really appreciate this @mighty ledge !
you also need to change the value_template
value_template: "{{ is_state('fan.fan_speed_1', 'on') and is_state('fan.fan_speed_2', 'on') }}"
because the state of the switch will show as "on", when speed1 and speed2 are on
value_template derrives what the state of the switch will be, through a template
Yeah, I just saw that from your other examples. I would've never figured this out myself.
I'm gonna go try all of this out, much appreciation again.
just keep in mind that you'll need to change things for each switch
Absolutely, will do
also, when adding this to configuration.yaml, make sure you only have 1 switch section
e.g.
switch:
- platform: template
switches:
....
- platform: template
switches:
....
not
switch:
- platform: template
switches:
....
switch:
- platform: template
switches:
....
OK, so it goes in the switches.yaml and not the templates.yaml?
Yes
or just put them all under switches:
Ok, good deal
Could someone show me how i could regex this please?
{{ "%.2f" | format((states("sensor.daily_rolling_cost_pool_pump") | float(0) ) + (states("sensor.daily_rolling_cost_front_lights") | float ) + (states("sensor.daily_rolling_cost_porch_lights") | float) + (states("sensor.daily_rolling_cost_cinema_room_speakers") | float) + (states("sensor.daily_rolling_cost_cinema_room_lamp") | float) | round(5)) }}'
I have more sensors to add, and they all begin with "sensor.daily_rolling"
sorry i am not sure which links? The ones in the pinned posts?
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
the second one, in particular
anyway, here:
{{ "%.2f" | format(states.sensor|selectattr('object_id', 'match', 'daily_rolling')|map(attribute='state')|map('float')|sum|round(5)) }}
Will that add the value of the "state" up?
yes. that's this part: map(attribute='state')|map('float')|sum
yes, with rejectattr()
actually just checking. not sure i need to.
one second
Aamzing
it works
thank you so dam match!
Really appreciate that Rob.
hmmm
It worked in template developer tools
but in my yaml im getting
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 152, column 7
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 156, column 69
total_rolling_cost:
friendly_name: "Daily Rolling Cost Total"
unique_id: "daily_rolling_cost_total"
device_class: monetary
unit_of_measurement: 'GBP'
value_template: '{{ "%.2f" | format(states.sensor|selectattr('object_id', 'match', 'daily_rolling')|map(attribute='state')|map('float')|sum|round(5)) }}'
Think my quotes are wrong, so swapped them
"{{ '%.2f' | format(states.sensor|selectattr('object_id', 'match', 'daily_rolling')|map(attribute='state')|map('float')|sum|round(5)) }}"
yes, and you should fix your indentation. 2 spaces per level
they are, that was just a bad copy and paste
here is a question for.....
lets say i name that sensor above "sensor.daily_rolling_total"
whats that going to do?
on the basis the regex is looking for that
ill keep it simple and just not name it that
well it didnt?
match just starts at the beginning
ah, so it's not really match
that's "eq"
"search" searches anywhere (substring)
right, but it's not really regex's match function
search with "^xxxx" is probably the same as match
disregard this then
{{ "foobar" is match("foo") }}
{{ "foobar" is search("foo") }}
{{ "foobar" is match("bar") }}
{{ "foobar" is search("bar") }}
{{ "foobar" is search("^bar") }}
->
True
True
False
True
False
yeah it just doesn't do what re.match() does
which returns a list of things that match your regex exactly
<time to go to the code>
I didn't implement match, but I do reemmber talking with someone when they implemented regex_findall
which is close to match
Lol, missed the link. It looks great
lol thanks π
Does anyone see anything wrong with this? I've put this in my switches.yaml file, but I can't find any of these switches after saving the switches.yaml file.
- platform: template
switches:
dining_room_fan_low:
value_template: "{{ is_state('fan.dining_room_fan_speed_1', 'on') and is_state('fan.dining_room_fan_speed_2', 'on') }}"
turn_on:
- service: fan.turn_on
entity_id:
- fan.dining_room_fan_speed_1
- fan.dining_room_fan_speed_2
turn_off:
- service: fan.turn_off
entity_id:
- fan.dining_room_fan_speed_1
- fan.dining_room_fan_speed_2
How/where have you included it in to your config file?
In my switches.yaml file inside my config folder.
The most likely cause is the indentation of the include or the level.
They appear in developer tools -> states page
make sure switches.yaml is included in configuration.yaml
other than that, the code looks good
They don't appear in the developer tool states page either
did you restart after adding them and is switches.yaml included in configuration.yaml?
All of the other template sensors I've made appeared after I saved the yaml file, but not these switches.
Yeah, I restarted HA too
can you post how you're including them in configuraiton.yaml?
yes, just a moment
I need to see where you included it in configuration.yaml
hey guys i have an issue with the variable section of my Automation YAML that why i came to the template channel:
description:
designed to control the temperature of an air conditioning system in an intelligent manner. It takes into account various parameters such as the outside temperature, humidity, inside temperature, and desired temperature. The goal is to dynamically adjust the AC temperature to achieve and maintain the desired temperature while considering the current environmental conditions.
Code: https://dpaste.org/WBrVq (YAML) or https://dpaste.org/yACAr (Python Format, looks cleaner for comments)
issue: wrong temp output
what's the right output
If the room temperature is typically hot due to the outside temperature where I live, I should set the AC to a lower degree than my desired temperature. This will help the AC reach my desired temperature faster. As it gradually gets closer to my desired temperature, I can adjust the AC's temperature to be increasingly closer to my desired temperature.
right I get that, but I have no idea what it's outputting now and I have no idea what it should be outputting, and I have no idea what your inputs are
so.. how tf can anyone debug it without that info
right now its 34c outside and room is 29c when i got here my desired temp for the room 'inside' would be 25
well, not based on your code
inside - outside would be -6
you then make it positive
i would normally set the temp to be 20 or 19 to get the room down to 25 faster but if i leave the temp at 19 the room can get too cold which is not what i want and also not energy efficient
and then you say "if it's greater than or equal to 1, just set it to the desired"
so
so right now, you're just setting it to the desired temp
Never mind, I don't know when, but I evidently had taken "switch: !include switches.yaml" out of my configuration.yaml...π«
that's why I kept asking to see that π
so what you have should work now π
Exactly
i am worreid i might have over engineered this thing
so, your code is:
temp_difference: "{{ inside_temp - outside_temp }}
Gives -6
Then later on...
{% if temp_difference < 0 %}
{% set temp_difference = -temp_difference %}
Gives +6
then later on...
{% if temp_difference < 1 %}
{% else %}
{{ adjusted_desired_temp }}
{% endif %}
that's your current code path
so it's doing exactly what you asked
Can I make a unique ID for these switches in the switches.yaml? Otherwise I can't manage them from the UI.
if the temperature is wrong, then the issue is just in adjusted_desired_temp
Yes, just add unique_id: <something_unique_from_all_other_template_switches> at the same indentation level as value_template
I thought that might do it, but figured I'd be safe and ask.
so i had my presistant notification output the following:
outside_temp = 35.8
desired_temp = 23
adjusted_desired_temp = 23```
why don't you just test this in the template editor
with 1 template
instead of these 839489283492384 broken apart templates
well, if that's the case you should be able to pound this out pretty quick
with the template editor
so i set everything under one variable in the Template tab in developer tools?
Yep
so...
outside_temp: "{{ state_attr('weather.forecast_home', 'temperature') | float }}"
becomes
{% set outside_temp = state_attr('weather.forecast_home', 'temperature') | float %}
you can even just use fake numbers for testing
each template
e.g.
{% set var1 = 5 %}
{% set var2 = 6 %}
Then the template you're going to use would be something like
{{ var1 + var2 }}
and when you put it into your automation, you'd use...
var1: "{{ states(...) }}"
var2: "{{ states(...) }}"
var3: "{{ var1 + var2 }}"
damn couldn't they just use the same syntax
1 is yaml
the other is pure jinja
automations are yaml that allow jinja
regardless, your automation only needs 1 result so you can just do 1 huge template that outputs to ac_temp
there's no reason for you to separate it all
@mighty ledge thank you this chat has been very educational i'll go test things out and come back here to bother you again if needed
π
I'm not sure if this should be asked here, but I've got the 3 template switches working from earlier. I then set the 3 buttons in the front end to be the 3 template switches. When I turn on the low template switch, the low button turns on. When I turn on the medium template switch, the medium button turns on, but when I turn on the high template switch, all 3 of the buttons turn on. How can I stop this?
Hello guys, I'm looking for the template to scan a specific unifi wifi network in order to check if they're guests or no, but can't find it
is that information available in an entity somewhere?
I don't think so, I just got my unifi u6 lite for this purpose and installed the integration, although, the integration asks me which SSID I want to monitor the entities that appear are the individual devices
even if they're not in the network
despite petro's comments to the contrary (<#templates-archived message>), templates can only work with existing data
they aren't magic, and they don't really do anything on their own
I'm seeing this post, some people claim to be able to monitor the ssid
https://community.home-assistant.io/t/unifi-network-number-of-active-clients-on-guest-ssid/377074
doesn't that do what you want?
it's not "scanning", it's just finding all device_tracker entities that are home and have a specific essid in their attributes
that gives me something
I missed the attributes.essid part, I think is working now
What i doint wrong: 'sensor' is undefined:
description: ""
trigger:
- platform: state
entity_id:
- sensor.fully_kiosk_device_info_sensor_info_ambient_light
condition: []
action:
- service: number.set_value
data:
value: >-
{{ states(sensor.fully_kiosk_device_info_sensor_info_ambient_light)|int +1 }}
target:
entity_id: number.lenovo_tab_p11_screen_brightness
mode: single
i want set number.lenovo_tab_p11_screen_brightness to sensor.fully_kiosk_device_info_sensor_info_ambient_light when sensor.fully_kiosk_device_info_sensor_info_ambient_light was changed
Put quotes (') around your sensor entity
Well it's working but still on 0 when there is one device on the network
Sometimes integrations don't update the online status instantly
just notices there's a bug on unifi but the strange thing is I even restarted HA and the counter still at 0
You should look at the attribute in the entities
Look at the actual data. The template is just reading it
yes, the ssid appears on the device's attribute but the counter still at 0
Debug the template then
What it's doing is straightforward
There's only like 3 things it's looking for
for some reason the template just reads my IOT network I have 3 devices on it and it works well but when I move to another ssid it reads 0
You sob
Templates can do ANYthing
It won't work with my phone bc I'm using the GPS tracking method (no essid on the attributes), but I tried with other devices and seems to be working fine, that's my goal, to track guests so I think I'll be fine now
@mighty ledge , those switches did work, however I had to fall back to my automations. Maybe I'm doing something wrong, but I set the 3 buttons in the front end to be the 3 template switches. When I turn on the low template switch, the low button turns on. When I turn on the medium template switch, the medium button turns on, but when I turn on the high template switch, all 3 of the buttons turn on. I couldn't figure out how to stop that. The automations are way too complicated, but now that they're set up, they work 99% for what I want.
I have a WLED controller for an RGB+WW LED strip, and have been trying to get it to work properly with the Adaptive Lighting integration. Unfortunately the color temp of the strip I have is much warmer than whatever WLED or Adaptive Lighting is expecting, so it looks like garbage. I found a blueprint for using an RGBW light as a CT Light, which installs an automation to set the specified light based on color temp specified in an input_number.
I thought a template light might be the solution -- let Adaptive Lighting adjust that template light color, then feed the result of that into the input_number for that color correction automation. Does anyone know of an example doing something similar I could look at?
You probably have to turn on the 2 and turn off the remaining one for low and medium.
Just add them to the turn_on / turn_off sequences
I figured that too, but I couldn't figure out how to do it...lol
The turn on section is like an action section of an automation
I'll try that and let you know how it works out.
Same with the turn off section
I thought that if I turned off one of the other switches, then it wouldn't be on high anymore. It seems that I need the buttons to be just a representation of the switch states and not the actual switches.
Thatβs exactly what the value_template is
It does not cause the turn on / off actions
It just represents the state of the switch
The turn on / off actions are performed when you or a service call turns on or off the switch
Thatβs why high turns on when you turn in medium
Because all 3 switches are on, and all 3 being on means high is on
Since the buttons are the switches though, when high is turned on, it automatically turns on the other 2 buttons.
Yes that's right, but I don't see a way to stop that if the buttons are the switches themselves.
Then we need to adjust the value_template to check when the last switch is off
I feel like this is similar to launching a nuclear weapon
Can the buttons be the value templates instead? would that make a difference?
Thatβs what we are doing
Itβs no different, it just has a turn off sequence
Which you do want
Whatever you do, do NOT press the red button
Anyways, the value template should check is_state(β¦, "off") for the 3rd switch in each case
Because as I said before (unlike what rob thinks) templates can do anything
Hi There, is this the correct place to ask for help for an imap_content template? Im trying a very simple thing with the imap integration, adding the following into the "Template to create custom event data" field in the integration... but geting errors:
template:
- trigger:
- platform: event
event_type: "imap_content"
id: "custom_event"
sensor: - name: imap_content
state: "{{ trigger.event.data['subject'] }}"
- platform: event
This the debug log:
2023-07-12 10:48:24.085 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'trigger' is undefined when rendering 'template:
- trigger:
- platform: event
event_type: "imap_content"
id: "custom_event"
sensor: - name: imap_content
state: "{{ trigger.event.data['subject'] }}"'
2023-07-12 10:48:24.088 ERROR (MainThread) [homeassistant.components.imap.coordinator] Error rendering imap custom template (Template<template=(template:
- platform: event
- trigger:
- platform: event
event_type: "imap_content"
id: "custom_event"
sensor: - name: imap_content
state: "{{ trigger.event.data['subject'] }}") renders=1>) for msgid 6 failed with message: UndefinedError: 'trigger' is undefined
- platform: event
Template sensors for IMAP content should be set up in your configuration.yaml file (or a file properly !included for the template top-level key)... They do not go in the "Template to create custom event data" field within the IMAP integration configuration.
Thanks for letting me know! Whats that field for? Is it to filter the imap email count? E..g only count emails from a certain sender?
The IMAP Search field is for filtering things like Sender. My understanding of the template field is that it can be used to produce custom data inside the imap_event so it can be accessed by a content sensor... I think this is mainly for use pre-processing the body of emails, since there is a length limit to how much of the body will be passed in the event data.
OK got it. Thank you!
OK so getting there! Question: I have this line of text in an email "Quantity delivered -- 1 - TFTC". The email content both has a text and html version, so i only want to get the first text version. Im stuggling with initial understanding: {{ trigger.event.data["text"] | regex_findall_index("*Quantity delivered -- *([0-9]+) - TFTC") }} - can someone point me in the right direction?
(Ive got everything else working as expected FYI)
Where can I find the correct yaml format for template sensors, when including a yaml file in configuration.yaml like sensor: !include sensors.yaml
the template documentation page isnt clear which format im supposed to be using with this include, and the forums seem to be out of date, at least with what google is pulling up
The merge dir list one
FYI the documents are clear. If the field you want to include on says list, itβs merge dir list. If the field says mapping, you use merge dir named
Not sure what you are referring to, I am using the default auto generated configuration.yaml and sensors.yaml
Hence !include
Youβre asking how to include the template section.. right?
sensor section, but yes
Iβm sorry, Iβm not understanding your question.
You already have the include for sensor, you just said it
configuration.yaml:
sensor: !include sensors.yaml
sensors.yaml:
- platform: template
sensors:
outside_temperature:
name: "Outside Temperature"
unique_id: "outside_temperature"
unit_of_measurement: "{{ state_attr('weather.ecobee', 'temperature_unit') }}"
value_template: "{{ state_attr('weather.ecobee', 'temperature') }}"
Yes thatβs all correct
The format of sensors.yaml is wrong, as I get an error when restarting HA. I am trying to figure out what the correct format is, and I couldnt find the correct page for it
That format is correct
You must have incorrect spacing somewhere in your file
But what you posted without showing relation to other sensors, is correct
So that means your spacing is not correct in relation to other sensors in the file
Im getting an error related to name being an invalid value:
The system cannot restart because the configuration is not valid: Invalid config for [sensor.template]: [name] is an invalid option for [sensor.template]. Check: sensor.template->sensors->outside_temperature->name. (See ?, line ?).
Im pretty sure name is correct, but i also did friendly_name and it didnt like that either
Legacy docs say friendly_name
That probably will go to the wrong sensor section, scroll to bottom
This link
Hmm, another change I made in combination to friendly_name fixed it. Not sure why I need to use the legacy though
thatβs the route you decided to go
template: is the new method
Hence why your question was confusing
Legacy template sensors go in the sensor section
New template sensors go in the template section
Oh, I had no idea
Ty for your help, and that info on legacy template sensors. I got it working with the legacy way, but ill play around with the new way to do things
I have a simple question ( i think!?) I need to add two attribute values together from 2 different sensors to get one single value. ( sensor.fubar1.attribute1 + sensor.fubar2.attribute2 = SomeFubarValue)
I cant seem to do this with the input helper GUI. So I guess i have to make a template for each sensor attribute and then try to sum them with the input helpers. Is this the correct way to do this... it seems a bit over complicated to me.
You could probably just make a sensor that adds it together for you. Something like {{ state_attr('sensor.fubar1', 'attribute1') | float(0) + state_attr('sensor.fubar2', 'attribute2') | float(0) }} might do nicely
Of course! π thx mian! ill try that
value_template: "{{ (value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first)['values'][0] }}"
I have problem with this, sometimes this yaml key values don't exists, then I want to show last value. How can I do this?
How would you get a count of the distinct areas for entities that match a specific state? Basically trying to get a count of occupied rooms, with each room having multiple potential occupancy sensors. Have this so far: {{ states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'occupancy') | map(attribute='entity_id') | select('is_state', 'on') | list | count }}
You can only do that with s trigger based template sensor. You still seem to be using the legacy format though, which doesn't accept triggers
Add | map('area_name') | unique before the list
I think I found another solution for my problem, but thanks for reply. I use this sensor in automation so I can do this in this automation
Hello
I am making an automation to enter an order and send it on telegram via the bot.
I can send the quantities of products but I can't find how to display the unit of measure defined when creating the entity on home assistant.
This is my code now (it is working):
`service: notify.panda
data:
title: Commande MarchΓ©
message: >-
{{ states('input_number.courgette') | int }} courgettes
{{ states('input_number.tomates') | int }} tomates
{{ states('input_number.persil_plat') | int }} persil`
How can I display the unit of measure of each entities ?
Ok... I'm pulling my hair out over here!
My lights have a dimming function. And I'm using an if statement to see if brightness is a specific number. This works IF the light is on... If the light is off, attributes.brightness doesn't exist! So, the code errors and won't continue.
So then I got the brilliant idea to "test" if light is on FIRST before it checks brightness level... However, it still doesn't work because it still somehow hits the attributes.brightness even with the light off π¦
{% if states.light.in_wall_paddle_dimmer_500s_5.state == "on" %}
{% if states.light.in_wall_paddle_dimmer_500s_5.attributes.brightness == 51 %}
{% set a = a + ['light.in_wall_paddle_dimmer_500s_5'] %}
{% endif %}
{% endif %}
How would I fix this?
Well, N/M. It is working as expected. π
Apparently, I'm using Variables wrong π¦ But I don't know how it's wrong... π¦
@rocky crypt I converted your message into a file since it's above 15 lines :+1:
states('some.entity', with_unit=true)
You only want to turn off those two lights if the brightness is exactly 51?
{{ ['light.light_1', 'light.light_2'] | select('is_state_attr', 'brightness', 51) | list }}
Btw, if you would have used is_state_attr() or state_attr() instead of states.some.entity.attributes.brightness in the first place (as strongly adviced in the docs) you wouldn't have had these errors
thanks ! and to display the name of the entity ?
variable scope, you can't adjust lists outside namespace.
use set a = namespace(a=[]) and set a.a = a.a + [ ... ]
or do what thefes said
which doesn't need namespace
@TheFes On this one yes. But I have another one that is going to do two different actions... This is why I need the variable.
I think you miss understood his comment
Can't adjust lists outside of namespace... I don't quite understand that statement... π¦
{{ states('input_number.courgette') | int }} {{ state_attr('input_number.courgette', 'unit_of_measurement') }} de {{ states.input_number.courgette.name }}
and it works
Namespace is an object that allows you to modify its inner objects. Jinja does not allow you to modify dicts or lists outside namespace. Itβs just how it works
See my example
I guess I'm very confused now π¦ My whole set a and if statements appear to work in other automations. Just for the variable, section it's not working π¦ Maybe I'm not explainging myself correctly...
Here is my whole code:
https://dpaste.org/fhqu5
And that whole template can be replaced with that single line I posted
I'm OK with that because if the list is empty, it won't do anything anyways π
it will turn off the automation
Btw these actions will be performed microseconds after each other, so these lights won't be on for long
I still find it odd that you're only looking at 51 brightness
And brightness: 255 is not 20%
Oh. Yes.. I know.. Sorry.. Let me explain.. If the light is at 20%... before it turns them off, I want it to put them back to 100% then turn them off. This way if someone comes into the room and turns on the light, it'll be 100%
If I JUST turn them off, when someone comes back into the room to turn the light on, it'll still be at 20% π
what happens if it's at 19%?
Then it'll leave the light alone.
π I have another script that ran that made the lights 20% π
ok, seems odd
Seems like you're not using scene.create and scene.apply when you should be
It's for the Roomba. Per manual, it states it works best with light... So, when the vacuum starrts, I want it to turn the lights on, but only at 20%. When it's done, I want it to turn the lights off that it turned on.
yeah, scene.create and apply is what you really want to use
before the roomba runs, capture the scene, or turn the lights on and capture the scene. Then run the roomba with the lights at 20%, then when the roomba is done, apply the captured sceen and turn the lights off.
no need to even think about the actual percentages
But if someone comes into a room where roomba is, I want them to be able to turn the light to 100%.. Then I don't want roomba to turn that light back off because someone is in there...
ok, you can cancel events
all you need to know is if the vacuum is running and someone changes the light %
then you can cancel the scene.apply & turn off at the end
but what happens if they enter the room, turn on a light, then leave after turning off the light
you've got alot of problems you're going to run into regardless what route you go
Personally, I just run my roomba in the daytime when no one is home
That's true. That can happen.... And that is something that I am willing to "live" with.
For now, I think I'll stick with the variable way. I don't know much about scenes. So, I'll have to look into that another time... I appreciate the idea and thought for sure!
there's not much to know
you'd turn both lights on, use scene.create with the entities in question and a unique name. Then when you want to return to said state before turning off, you call scene.apply using that unique name
it stores all attributes of the entities when scene.create was called.
no templates needed.
And do you specify what items to capture?
Ok. I'll look into that. Because I'm still unable to get it to run even with the one liner variable... π¦ So, I have to be doing something wrong still...
it's very simple
I still wish I knew what I was missing though...
(with scene.create)
I'll look at scene.create. But, if someone could do me a favor an check out https://dpaste.org/uUEh6 What did I do wrong? light.turn_on is just reporting back as '{{ entity }}'
your template isn't wrapped in quotes
use multiline notation or wrap your template in quotes
Under variables?
look at where you're using {{ entities }}
and look at where you're using the longer template
notice the differences in the YAML
entity_id: has multiline notation... >- Correct?
yes
So, I'm confused. π¦
why
Oh sorry. Yes. Under variables. I have >- as well. I changed that and forgot to change it on dpaste.org. That's why I was confused π
read this
Right. Forgot the condition...
But it's not working. So, I still have something wrong...
If I put this line:
{{ ['light.in_wall_paddle_dimmer_500s', 'light.in_wall_paddle_dimmer_500s_5'] | select('is_state_atrr', 'brightness', 51) | list }}
In template (Settings/Develop Tools/Template), it errors and says "TemplateRuntimeError: No test named 'is_state_atrr'."
I would expect it to return my light.in_wall_paddle_dimmer_500s_5 (As this is the light at 51 brightness.
Am I wrong?
Typo: attr not atrr
THANKS! Yep! That was it π
Wow! All that because double R instead of double T π HAHA It's now working as expect...
@petro Thanks for the scene template idea. This will come in handy as well! I may end up switching it to this, but it drives me crazy when I think something should work and it doesn't. That was the main reason for me wanting to figure out the variable way..
Whoops, sorry for that. That's what you get from writing code on mobile
NO WORRIES! I appreciate the help! I do have another quick question. Is there a way to automatically do the select query on all device_class Lights? Without specifying each light ID?
Why doesn't this work?
now()-as_datetime(states('input_datetime.last_vacuum'))
The template editor complains can't subtract offset-naive and offset-aware datetimes I would like to do something like this to return a timedelta.
because as_datetime(states('input_datetime.last_vacuum')) does not have a TZ
you'll have to force it to be local or UTC
now() - states('input_datetime.last_vacuum') | as_datetime | as_local
I assumed you wanted local
aha. Thanks!
N/M my question. I figured it out π
There is no device_class light, there is a domain light though.
And yes, you can filter on all lights
Oh, should have scrolled to the bottom
Don't you just hate that
After a small break, I'm back at working on my energy pricing templates. I notice I'm just missing experience with these... Hoping someone here can help me in the right direction.
I have a list of figures, and I'd like to shuffle through them, so that I can compare the current (index 1) PLUS the 5th from then (index 6), to the next pair, etc.
Currently I have a template that simply sorts the list, and gets the lowest number:
state: >
{% set hour_threshold = states('input_number.dishwasher_hours_ahead') | int(0) - 5 %}
{% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
{% set items = state_attr('sensor.energyprices','raw_today') + state_attr('sensor.energyprices','raw_tomorrow') %}
{% set lowest = items | selectattr('start', '>', now()) | selectattr('start', '<=', time_threshold) | sort(attribute='value') | first %}
{% set lowest_price = lowest.value + states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
{% set cheapest_time = lowest.start %}
{{ cheapest_time }}
I think I have just what you need
https://github.com/TheFes/cheapest-energy-hours
THat looks like it indeed... BUT, one small thing (let's see if that works)... I am only interested in hour 1 and hour 1+4. In my case it's for the dishwasher. And hours 2,3 and 4 use negligble energy, but 1 and 5 use a lot.
Let me read through your docs and see how I can use it. Thanks for making it either way!
Advanced data selection settings - πββοΈ awesome!
π looks like enabling experimental mode for HACS crashed my server... Damn
Yeah, that was my plan b. Trying to see if I can still get into HAOS, but seems I can't get in through terminal, hard reset needed... π©
what error are you getting?
No error, system just crashed. but it's back up
There's a typo in one of your examples... The last one is missing a )
Let me check
But you should be able to do only hour 1 and 4, you can assign a weight of 0 to hours 2 and 3
I looked at my energy readings again, Seems this is what I need:
weight=[2,1,3,0,0]
That means 3rd hour weighs the most, first hour second most, and 2nd hour the 3rd most, with the last 2 being ignored, right?
And does it actually WEIGHT the prices? So for example if one hour usually uses twice as much power, should I actually make the number twice as high? Or is it simply a ranking
Yes
3,2,4,1,1
It does
You can use the template sensor to have them calculated based on an energy sensor
You can even do shorter periods, so readings per 15 minutes
Yeah I didn't realise it did more than ranking so I thought I can just check my graph π
This is an example of the output of the sensor for my washing machine
wasmachine_turbowash_60_1400:
data:
- 27
- 45
- 2
- 2
- 1
- 1
- 2
no_weight_points: 4
complete: true
Could it be that the code in the script is outdated? I'm getting syntax errors
Oops for the @
It ran today without issues for me
For the "example" lines it's asking for a string
Line 20: example: 120 Incorrect type. Expected "string".
Hmm, I noticed that as well now
But I have exactly that in my own config
https://github.com/TheFes/HA-configuration/blob/main/include/integrations/packages/energy_usage_plot.yaml
I should correct that though to something more appropriate
120 is not much of a description
Funny.
Ok, so I assume this will only work once my dishwasher has run again now that I've set it all up right?
Or can it look back historically?
So if I understood correctly... I have now installed the script, and created the sensor (which exists empty, which I guess means it works). I just keep it as it is, and I read out the values once my machine has done a wash?
If you've set an automation to start and stop the script it should work
Ah so it needs to be turned on right before the dishwasher runs, and then turned off right afterwards?
And turning it off is of course just changing the service call to turn_off
No it's supposed to turn off automatically based on a state change of an entity
Eg a binary sensor based on a power sensor checking if the device is active
Or a sensor provided by the device itself
Ah, that's what the off part is for. I haven't been able to find a sensor on my dishwasher that does that, and the power is measured by a smart socket
My washing machine is a smart one, so I use the sensor provided by it.
But for my dishwasher I have a template binary sensor which turns on when it's using power, and turns off when it stops doing that
Btw I've addressed the points you mentioned in a new version
https://github.com/TheFes/cheapest-energy-hours/releases/tag/v1.7.2
Cool!
This is the binary sensor I have for my dishwasher, however I currently only use that to send notifications when it's ready.
https://github.com/TheFes/HA-configuration/blob/main/include/template/binary_sensor/dishwasher_active.yaml
And I actually think I did find a sensor that will work. Thanks!
Let's see what happens next time I run it.
Looking forward to trying this script.
Okay, let me know if it doesn't work, I don't know if anyone besides me actually uses it π
And to be honest, I don't even have dynamic rates
Haha well I've been playing with this stuff for a while, learnt a lot. But also good to know when using someone else's stuff is a better idea and use my energy elsewher.e
But I'll let you know
Switch! Only today I got a code to share and "invite my friends" haha
Haha, I still have fixed rates from 2 years ago, they can't be beaten by dynamic rates yet
Looking for a full year average of course, summer rates are a lot cheaper then what I pay
Hi,
I have 8 motion sensor.
Now, i want to show list of sensor if state is unknown.
How to use template
Thanks
simple
{{ states.sensor|selectattr('state', 'eq, 'unknown')|map(attribute='entity_id')|list }}
did you try something?
thanks
But i want show list of motion only
ok
Hi, does anyone have experience of RGBW zigbee light bulbs being connected using a zigbee light switch, does it work?
#zigbee-archived would be a better place for that question
Anyone know if there's any way to get mdi icons inline with conditional template text?
E.g. {{"mdi:lock" if is_state('lock.frontdoor','locked')}}
Not embedded in the text like an emoji, if that's what you mean
You can use actual emojis
That's a bummer. Emojis aren't nearly as flexible/clean as MDI.
Seems like it's possible in the markdown card. Wonder if I could do some fiddling with mod-card to get it...
Oh, nice. I keep forgetting that you can insertt HTML
working on details, wondering if I should use: - > {{trigger.entity != 'device_tracker.synology_diskstation' and now() > today_at('23:00')}} as a template condition, - > {{ not trigger.entity == 'device_tracker.synology_diskstation' and now() > today_at('23:00')}} is there an order of operations issue here?
goal: this needs to be false when the trigger is that device, and its after 23 (which is the scheduled turn_off time, so I dont need a notification ...)
If it should be false after 23:00, you should use <
In both cases
The not only applies to the part before and, unless you use parenthesis
{{ not false and true }} # True
{{ not (false and false) }} # True
{{ not (false and true) }} # True
{{ not false and not false }} # True
thx, that was what I was looking for, I'll use
{{not (trigger.entity == 'device_tracker.synology_diskstation' and
now() > today_at('23:00')) }}``` which seems the most succinct translation of that sentence above
or trigger.entity != 'device_tracker.synology_diskstation and now() < today_at('23:00')
statements always work left to right with and
not (x == y) is identical to x != y
as both apply the __equals__ method on the object under the hood.
In that case he needs < instead of >
thx!
found another possible change. in the nex_alarm_timestamp sensor (remember Petro?) we use {% set days = timestamp|timestamp_custom('%d')|int - (now()+timedelta(days=1)).day +1 %} and this seems to be identical with the tiny bit clearer: {% set days = (timestamp|as_datetime()).day - (now()+timedelta(days=1)).day +1 %}. I like the fact they both use the .day . Would you agree on that?
@floral shuttle I'd just do:
{% set days = (timestamp | as_datetime - now()).days + 2 %}
not sure why you're doing all the +1 day stuff
{% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %}
{% if timestamp %}
{% set days = timestamp|timestamp_custom('%d')|int
- (now()+timedelta(days=1)).day +1 %}
{% set day_dict = {0:'Today,',1:'Tomorrow,',2:'The day after tomorrow,'} %}
{% set date = timestamp|timestamp_custom(' %A, %-d %B') %}
{% if days in day_dict %} {{day_dict[days] + date}}
{% else %}{{'Next' + date}}
{% endif %}
{% else %} Not set
{% endif %}```
easy time does that
-> Templates