#templates-archived
1 messages · Page 70 of 1
Hi! I'm trying to use the markdown card to use jinja2 code that lists all battery entities with the device_class battery and show the ones below 25%. Has anyone done this before and might give some pointers in the right direction? I know I can use battery state card, but I would like a clean text-based list of entities.
Can you post the jinja that you've tried?
message: Helen Adams Keller was an American author, disability rights advocate, political activist and lecturer. Born in West Tuscumbia, Alabama, she lost her sight and her hearing after a bout of illness when she was 19 months old. She then communicated primarily using home signs until the age of seven, when she met her first teacher and life-long companion Anne Sullivan. Sullivan taught Keller language, including reading and writing. After an education at both specialist and mainstream schools, Keller attended Radcliffe College of Harvard University and became the first deafblind person in the United States to earn a Bachelor of Arts degree.
I've got a large blob of text. Sometimes on these searches I get a lot like this but others not as much. Is there an easy way to limit to just the first two or three sentences? if not, is there an easy way to limit by number of characters and then add the ... to the end?
split the message by periods to get number of sentences
or [:255] for everything before the 255th character
{{ "large text" | truncate }}
that will limit it to 255 characters (including ... at the end) and split on the last full word
is there a way to get the device_id of the device that triggered an automation?
Trying to do something like:
value_template: "{{ trigger.device_id == 'xxxx' }}"
what is your trigger?
but I expect "{{ device_id(trigger.entity_id) == 'xxxx' }}" will work
It's a motion sensor. First time trying to work out a more custom automation (rather than just using a blueprint).
Aiming to get this flow:
https://i.imgur.com/x1ffbIm.png
Ill try what you mentioned 👍
Ah, worked it out, so, entity_id seems to be only available on some platforms, switched to using state from device and seems to be working now. Thanks for your help
That's why I asked what the trigger was
How do i get this condition to work? It should pass, but it doesnt.. and is there a simpler way to find an item in an array?
alias: Jafaris alert
description: ""
trigger:
- platform: time_pattern
minutes: "10"
condition:
- condition: template
value_template: |
{%- for post in (state_attr('sensor.jafaris', 'schedule') | list) -%}
{{ post.place == 'Ed' }}
{%- endfor -%}
action: []
mode: single
Solved with this as value_template, if anyone needs something similar.. {{ (state_attr('sensor.jafaris', 'schedule') | selectattr('place', 'match', 'Ed') | map(attribute='place') | list)[0] == 'Ed' }}
sorry, didn't see your question. You can make that a bit shorter with some safety built in
{{ state_attr('sensor.jafaris', 'schedule') | map(attribute='place') | select('match', 'Ed') | first | default == 'Ed' }}
basically it gets the first item if it exists and compares it to ed, if it doesn't exist, it'll fail the condition
also, it removes the need for () and other things you had
it worked
If I add a template sensor based on some other sensors, should the results be available immediately or do I need to wait for more data? I'm trying to calculate energy usage for last 24h, yesterday, last week, ... Or is there a better way of doing that? I need it as a value so I can later use it in estimating the cost.
I dont know if this is best for here or #automations-archived but, trying to set some variables based on some conditions and then use them in a service call but I cant seem to get it working, i have a feeling the variables aren't being set but cant work out what I am doing wrong.
I am switching between yaml and the UI editor as I am new to this, so trying to learn the yaml by seeing what the UI is doing and then tweaking it.
variable scope does not work outside the action list it's in
you have to template the entire variable at the same level where you use it
meaning anything in an if-then action section will not work outside the if-then action section
gotcha, so based on that im probably better just doing the end action in multiple places, than setting a variable and using it later
or just template the whole variable
brightness: "{{ iff(today_at('12:00') < now() < today_at('18:00'), 2, 100) }}"
oh wait, you have more logic
yeah, if the trigger was a door sensor, i want always 100%, but i like your idea, thats far cleaner
brightness: >
{% if today_at('12:00') < now() < today_at('18:00') %}
2
{% elif trigger.id == 'DOOR_SENSOR' %}
100
{% else %}
100
{% endif %}
Thanks, will try this
My main aim is to learn as much of this as I can, i work as a software developer so i just need some exposure and i should start understanding it.
So yes cheeky for sure 🙂
variables:
settings: >
{% if today_at('12:00') < now() < today_at('18:00') %}
{'brightness': 2}
{% elif trigger.id == 'DOOR_SENSOR' %}
{'brightness': 100, 'delay': 300}
{% else %}
{'brightness': 100, 'delay': 60}
{% endif %}
Then later..
- service: light.turn_on
data: "{{ settings }}"
target:
device_id:
- 8a5ed3da4078996d696c1669aef7a6e0
- b49e5722c65191ff0d1d4886404a6d9a
if you want to learn complex templating, just look at my repo
I avoid yaml when I can and use templates as much as possible to reduce overhead
Thanks I will defo take a look. Its one of those things, I can read it and undestrand it, but the moment I try to write something from scratch, im a bit lost. So I will definitely take a look as it will just add to the understanding
it's python with extra flavor
but also less flavor
jinja is weird
take a look at the pins
- "You can do anything in templates"
- "Jinja uses various delimiters in the template strings.
{% %}..." - "you need to use a namespace if you're planning modify a variable..."
- "I see a lot of folks ask for how to know, of a group, who was th..."
- "To count lights which are on, and exclude light groups, note tha..."
- "Jinja (Template) Built-ins jinja.palletsprojects.com/en..."
- "Distinguishing Yaml from Jinja (templates) community.ho..."
- "Confused about the 2022.2 breaking
defaultchange? c..." - "Understanding types to parse JSON community.home-assist..."
- "@689168555861737485 Here's a template that looks up a friendly..."
Hi, you can help me to convert timestamp ?
I use a multiscrap sensor, but he doen't work :/
actual timestamp : 1709920796 and lastsee : 1709916039
- unique_id: see_last
value_template: "{{ (states('value_json.lastsee') | as_datetime | as_local).isoformat() }}"
I don't understand how to get the date in correct form, thanks
value_template: "{{ value_json.lastsee | as_datetime | as_local }}"
wow, realy good, thanks 👏🏽
result : 2024-03-08 17:40:39+01:00
Many thanks, is it possible to remove the +....
it won't be the correct time if you do
add device_class: timestamp
and it'll show up in the UI as your formatted time
e.g.
value_template: "{{ value_json.lastsee | as_datetime | as_local }}"
device_class: timestamp
with devise_class the result is 2024-03-08T16:40:39+00:00
i would like to have just : 2024-03-08 17:40:39
Look at the entity in the UI
don't look at the states page
e.g.
Oh ! really
Yes
I use integration for ipmi. It gives me a button to turn the computer on and off. Pressing the button causes the computer to switch on after about a minute. Until then, the status of the button is Off, this means that I can press it to send the on/off commands to ipmi. Which can result in the computer stopping turning on.... I would like my button to be able to be pressed again only one minute after it was pressed. How do I achieve this?
Make a script with mode single. The script will turn on the switch then delay 1 minute. Next make a template switch that’s turn on function is the script. Its turn off is the turn off of the switch in the script. The value template is state of the switch in the script
trying to create a sensor to measure how long my car is driven each week
- platform: history_stats name: Fiat Connected entity_id: binary_sensor.fiat_connection state: "on" type: time start: “{{ as_timestamp( now().replace(hour=0, minute=0, second=0) ) - as_timestamp(now().weekday() * 86400 )}}” end: “{{ now() }}”
but the log complains "start must be a datetime or a timestamp: could not convert string to float"
Replace those fancy quotes with normal double quotes
You could simplify that template to
"{{ today_at() - timedelta(days=now().weekday()) }}"
thanks - let me try that. I'm not sure where those fancy quotes came from though 🙂
That worked - thanks TheFes
Any idea how I could efficiently take a list of numbers get the 2 highest numbers, if the difference between them is >= 15 for example try the next 2 highest until the difference between the 2 highest is <= 15 then output the highest number?
Here a way:
{%- set numbers = [11,27,26,30,46] -%}
{%- for number in numbers | sort(reverse=True) -%}
{%- if loop.nextitem is defined and (number - loop.nextitem) <= 15 -%}
{{- number -}}
{%- break -%}
{%- endif -%}
{%- endfor -%}
I was so close lol I just started down the nextitem and reverse sort path
Just was not sure how to stop the loop
Thank you!
You bet
In a template sensor you can do this.attributes.yourvar can you do the same in an automation for a variable with a yaml dictionary so keys with jinja can reference other key values in the same dictionary.
I don't follow your question
https://www.home-assistant.io/integrations/switch.template/
Hello, I have a switch to toggle my AC using a universal IR remote, but the current switch code can't know if the ac is on or off, so I hooked an energy meter to the AC, how can I add this condition to the switch? like if the current is over 3 amps say that it is on and vise versa?
switches:
dining_room_ac_switch:
value_template: "{{ states('sensor.ac_current') | float > 3 }}"
turn_on:
service: script.dining_room_ac_on20
turn_off:
service: script.dining_room_ac_off
friendly_name: "Dining Room AC"
``` would this work?
Looks ok
If sensor.ac_current exists in your HA. ChatGPT makes up stuff sometimes.
yes it's making it up, i'll just have to replace it
It seems it's not possible to do
variables:
random:
foo: 'xyz'
adam: "{{ this.random.foo }}"
If you have some power measuring, it is usually called something with power and the unit of measurement is W
hey there, looking for a little help with https://www.home-assistant.io/integrations/fan.mqtt/
i have commands working, but no matter what i try, state is still optimistic and not using the state i want
mqtt:
- fan:
- name: Fan
unique_id: fan0
command_topic: "fan/on/set"
state_topic: "fan/on/state"
state_value_template: "{{ states.input_text.current_fan.state }}"
i tried w/ and w/o the state_value_template but that didn't make a difference
just seeing two lightning bolts for the entity controls, instead of it actually showing the fan as on or off 😦
Not possible
That's what I thought
How does it work in a template sensor though?
It’s a state object in the template sensor
Variables are not part of the state object
@mellow hound I converted your message into a file since it's above 15 lines :+1:
There's an example in the docs https://www.home-assistant.io/integrations/weather/#examples
Hello here, when I am creating a sensor template, do I still need to put the code into the configuration.yaml? I have troubles recreating the one saving temperatures from the weather forecast: https://community.home-assistant.io/t/outside-temperature-add-to-history/452230/15
I put the code into the configuration.yaml file, but cannot find any new entity. Also how does the name of entity works? Is it created from the name attribute, so if the name would be "Outside temperature" the entity would be called sensor.outside_temperature?
ok, nevermind, seems like restart of the system did fix it
Heya. Is there some home assistant template that makes a string commandline save like escaping & | ' and "
Also see this if you’re escaping inside a template: https://jinja.palletsprojects.com/en/3.0.x/templates/#escaping
Next alarm trigger not working anymore
Remaining Charging Time for PV Battery
hey
how can i store the data from a "get" request, for example from "get.items", in an entity
Not sure I understand the question, but an input helper or a template sensor are the two main ways to store data
Hey, I am looking for some guidance. I have contact sensors on my doors upstairs and I want to make a sensor that updates for when the vacuum cleans rooms based on when the doors are open.
@summer arch I converted your message into a file since it's above 15 lines :+1:
I think I have done it right but what I am confused on is what if the door is not open? I want to leave the value as it
what does the door have to do with cleaning a room?
Well if the doors closed... how does the vacuum get in...
first thing I notice is the quotes around your output
remove those
and what if the door is opened like 2 minutes after the vacuum started, it will still clean the room
{% else %}
{{ this.state }}
{% endif %}
you can define both sensors under the same trigger
Vacuum is triggered to clean when no ones home so I am less concerned. But since it is triggered when no one is home, we have no way of opening the doors. We often close doors to keep the dog out hence wanting metrics on when and why
I thought you required the quotes (maybe '' ?) to make the output functional in the sensor state
check the pins
quotes are needed for specific situations with yaml
they are not needed for jinja
- "You can do anything in templates"
- "Jinja uses various delimiters in the template strings.
{% %}..." - "you need to use a namespace if you're planning modify a variable..."
- "I see a lot of folks ask for how to know, of a group, who was th..."
- "To count lights which are on, and exclude light groups, note tha..."
- "Jinja (Template) Built-ins jinja.palletsprojects.com/en..."
- "Distinguishing Yaml from Jinja (templates) community.ho..."
- "Confused about the 2022.2 breaking
defaultchange? c..." - "Understanding types to parse JSON community.home-assist..."
- "@689168555861737485 Here's a template that looks up a friendly..."
"Distinguishing Yaml from Jinja (templates) community.ho..."
- trigger:
- platform: state
entity_id: vacuum.upstairs_vacuum
to: cleaning
for:
minutes: 1
sensor:
- unique_id: upstairs_vacuum_last_clean
name: "Upstairs Vacuum Last Clean"
state: "{{ trigger.to_state.last_changed }}"
device_class: timestamp
icon: mdi:broom
- unique_id: bedroom_last_cleaned
name: "Bedroom Last Cleaned"
state: |
{% if states('binary_sensor.bedroom_door_sensor_contact') and states('binary_sensor.spare_room_door_sensor_contact') %}
{{ trigger.to_state.last_changed }}
{% else %}
{{ this.state }}
{% endif %}
Do both doors have to be open for the vacuum to be able to clean the bedroom?
Yeah, housed in the spare bedroom so if the spare bedroom isn't open, no where else gets cleaned
that makes sense 🙂
@summer arch I converted your message into a file since it's above 15 lines :+1:
Ok so remiving quotes in the multiline states?
this.state if door not open
last clean uses trigger last changed not now
think that covered all the suggestions?
Late at night so won't get to test it now
as you base it on the same trigger, I would just use trigger_to_state.last_changed as input for all sensors
Is a template sensor the best way to convert the text output of a binary sensor?
Example: My door sensors gives "opened" or "closed", but the blueprint I am using expects "on" or "off"
a binary_sensor is already on/off
it's just displayed differently depending on the class
hm ok maybe something else is broken then
So in the backend that's already translated then, it's just on the UI I see opened/closed
the other way around, but yes
Hey,
I'm outputting a string, and the only option to separate it, as a list, is by using 'double space':
value_template: |
{%-set value = value.split(" ")-%}
{%for x in value%}
- {{x}}
{%-endfor-%}
Unfortunately, there's a final 'double space' at the end of the string - creating a blank:
- text...
- text...
-
Any idea of a solution?
what kind of value template is this? if it expects a list, this should be enough {{ value.split(" ") }}
I don't know of any value_template field that accepts anything other than a string, bool, float, or int
It's from multiscrape.
For some reason the attr comes as a list, but without the value_template it stays as a string when {{state_attr('sensor...', 'attr')}}.
Wait, in the template it comes as a list - but in a card it comes as a string. 
if the result of that is the state of your entity, it will always be a string
states are always strings
I'm using the attr; in a Markdown Card.
how does the attribute look in devtools > states?
Without the value_template, it comes as:
17:30 Gaziantep FK Besiktas SPORT TV1 18:00 Belenenses Leixões SPORT TV+ 19:30 SD Amorebieta Leganés ELEVEN SPORTS 4 19:45 Lazio Udinese SPORT TV2 20:00 Almería Sevilla ELEVEN SPORTS 2 20:00 Chelsea Newcastle ELEVEN SPORTS 1 20:15 AVS SAD Feirense SPORT TV3 20:15 Gil Vicente Desp. Chaves SPORT TV1
yeah, so split that using the template I gave
If I do:
[
"",
"17:30 Gaziantep FK Besiktas SPORT TV1",
" 18:00 Belenenses Leixões SPORT TV+",
" 19:30 SD Amorebieta Leganés ELEVEN SPORTS 4",
" 19:45 Lazio Udinese SPORT TV2",
" 20:00 Almería Sevilla ELEVEN SPORTS 2",
" 20:00 Chelsea Newcastle ELEVEN SPORTS 1",
" 20:15 AVS SAD Feirense SPORT TV3",
" 20:15 Gil Vicente Desp. Chaves SPORT TV1",
""
]
where do you see this output?
In devtools > template; if I check the devtools > state:
friendly_name: Football Game
list: , 17:30 Gaziantep FK Besiktas SPORT TV1, 18:00 Belenenses Leixões SPORT TV+, 19:30 SD Amorebieta Leganés ELEVEN SPORTS 4, 19:45 Lazio Udinese SPORT TV2, 20:00 Almería Sevilla ELEVEN SPORTS 2, 20:00 Chelsea Newcastle ELEVEN SPORTS 1, 20:15 AVS SAD Feirense SPORT TV3, 20:15 Gil Vicente Desp. Chaves SPORT TV1,
okay, so it is a perfectly fine list
this is just how a list is outputted if you use a template
for your markdown card you could use:
{% for item in state_attr('sensor.your_scrape_sensor', 'list') %}
- {{ item }}
{% endfor %}
oh, and you might want to change the template for your attribute to {{ value.split(" ") | select() | list }} to remove the empty ones
figured it out - it was two-fold: 1) i was getting a string for target entity id in the state_value_template. needed to wrap that in a "States()" call. 2) MQTT seems to prefer all-caps ON/OFF string state topic payloads, so i also added an |upper filter to the template.
final:
mqtt:
- fan:
- name: Fan
unique_id: fan0
command_topic: "fan/on/set"
state_topic: "fan/on/state"
state_value_template: "{{ states(states.input_text.current_fan.state)|upper }}"
payload_on: "ON"
payload_off: "OFF"
Hi Guys, i'm struggling with this template for some times, the result is always Unavaible, somebody can help me Please :
`{% set today = as_timestamp(now().date()) %}
{% set garbage_dates = state_attr('calendar.chalet_service', 'events') %}
{% set prochains_dates_ordures = garbage_dates | selectattr('summary', 'eq', 'Ordures') | selectattr('all_day', 'eq', True) | map(attribute='start_time') | map('as_timestamp') | select('>=', today) | list %}
{% set prochain_date_ordures = prochains_dates_ordures | first %}
{% set jours_jusqua_ordures = ((prochain_date_ordures - today) / 86400) | int if prochain_date_ordures is not none else None %}
{% set prochains_dates_recyclage_compost = garbage_dates | selectattr('summary', 'eq', 'Recyclage et compost') | selectattr('all_day', 'eq', True) | map(attribute='start_time') | map('as_timestamp') | select('>=', today) | list %}
{% set prochain_date_recyclage_compost = prochains_dates_recyclage_compost | first %}
{% set jours_jusqua_recyclage_compost = ((prochain_date_recyclage_compost - today) / 86400) | int if prochain_date_recyclage_compost is not none else None %}
{% if prochains_dates_ordures | length == 0 and prochains_dates_recyclage_compost | length == 0 %}
Aucun événement de collecte d'ordures à venir.
{% else %}
{% if jours_jusqua_ordures == 0 %}
C'est le jour des ordures.
{% elif jours_jusqua_ordures == 1 %}
Demain, c'est le jour des ordures.
{% elif jours_jusqua_recyclage_compost == 0 %}
C'est le jour du recyclage et du compost.
{% elif jours_jusqua_recyclage_compost == 1 %}
Demain, c'est le jour du recyclage et du compost.
{% else %}
{% if jours_jusqua_ordures is not none %}
Prochaine collecte des ordures dans {{ jours_jusqua_ordures }} jours.
{% endif %}
{% if jours_jusqua_recyclage_compost is not none %}
Prochaine collecte du recyclage et du compost dans {{ jours_jusqua_recyclage_compost }} jours.
{% endif %}
{% endif %}
{% endif %}`
@waxen meadow I converted your message into a file since it's above 15 lines :+1:
@waxen meadow I converted your message into a file since it's above 15 lines :+1:
Hey guys. I have an Ecobee thermostat and I can see when it's heating in HA. How would I write a template sensor that would tell me
how long the heat ran?
Likely you want a binary template sensor that tells you if the hvac_action attribute is heating, paired with a history_stats sensor that counts the time that sensor was on.
Your problem is the second line. The events attribute was phased out last year. You need to take a look at the current Calendar integration docs, especially the calendar.get_events service call.
In the future please follow server guidelines and use a code share site for anything over 15 lines.
but how would be the code? idk how to write attribuetes
hey!
I'm currently using a sensor I created to monitor my boiler time on
- platform: history_stats
name: Boiler On
entity_id: input_select.switcher_boiler_status
state: "On"
type: time
start: "{{ now().replace(hour=0, minute=0, second=0) }}"
end: "{{ now() }}"
However even when the Boiler is off it's showing the last time it was on and for how long.. also how can I convert it to minutes instead of hours? Thanks!
It will always use hours, if you add a unique id in your config you can simply change the unit of measurement
Okay, so I will keep the hours; but how can I fix that it won't show the time on if status of Boiler is Off?
That's not how that sensor works
It shows how long it has been On today, regardless of it's current state
Is there a way to hide it / reset the sensor time if state of boiler equals to Off?
loving the new state_translated() templates. however, is it a bug, or just not yet implemented that 'unknown' is not translated?
cause now I need to do this on my entities: {% if is_state(config.entity,'unknown') %} Uit {% else %} {{state_translated(config.entity)}} {% endif %} in a template-entity-row..
which is correct in itself, as Ive turned_off the switch. just wondering why it doesnt say 'Onbekend'.
feels buggy because this {{states('binary_sensor.achterdeur_buiten_sensor_motion')| state_translated}} even errors with
I've already seen that before, that unavailable and unknown are not translated, so it's known. Not sure if it's intended
so what do you want to measure? the time that it is On since the last time it has been turned On?
@floral shuttle In the first example you are using state_translated on the state, you should use it on the entity_id
{{ 'binary_sensor.achterdeur_buiten_sensor_motion' | state_translated }}
That's what causes the error on the filter
The error even points to what was done wrong TemplateError: Invalid entity ID 'unkonwn'
I'd remove that from the issue because all it's going to do is make the code owner overlook the issue.
If you want the data to persist through a HA restart you’ll need a trigger-based template sensor. You’ll need to create it in YAML following these docs. Your sensor will need a state and so if you only want to define attributes you can just set something like state: 'ok' Attributes are simply added as a separate fields:
attributes:
my_attribute: "{{ template_goes_here }}"
but with normal quotes instead of these fancy ones
Thanks. That whole post was garbage 😅
Yeah exactly, to monitor how long the Boiler is On only when it's on.
then you should use the time it turned On as the start parameter, not midnight
start: "{{ now().replace(hour=0, minute=0, second=0) }}"
to now().replace(input_select.boiler) equals to On ?
I did just now, sorry for that, I had missed this tag somehow
no, that's not working
You need to understand what {{ now().replace(hour=0, minute=o, second0) }} is doing. It takes the current time and replaces the hours, minutes and seconds with 0 so it returns midnight
BTW, a PR I created was just merged to replace that template with {{ today_at() }} in the History Stats docs
I guess this will work:
- platform: history_stats
name: Boiler On
entity_id: input_select.switcher_boiler_status
state: "On"
type: time
start: "{{ states.input_select.switcher_boiler_status.last_changed }}"
end: "{{ now() }}"
It will show the time it has been set to On since the last time the entity changed its state
It will reset if you restart HA though
might want it to be today_at("00:00")
but it's a step in the right direction for sure
In which part of it?
yeah, I actually did consider that
might have been more clear what it does
Wondering if something changed in the configuration yaml in regards to calculating totals..
I have a sum of a sensor using this code:
- name: "Solar totaal"
unique_id: "solar_totaal"
unit_of_measurement: "W"
state: >
{{ states ('sensor.solaredge_ac_power') | float(0) | round(0)
+ states (' sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w_filterspikes' ) | float(0) | round(0) }}
but that seems to have stopped working somewhere recently.. that second/last line is not added as a sum to the solar_totaal sensor that's created in the configuration.yaml here. Am I doing something deprecated here?
' sensor
space
also, you don't even need a template for this, just make a sensor group with 'sum' as your group option.
oh slap my bum and call me sally.. let me see if that fixes it 
no the space doesn't seem to make a difference. Let me check that sensor group option
doing a few others with subtract as well, let me see if you can do some math in those
- sensor:
- name: "Stroomverbruik in huis"
unique_id: "stroomverbruik_huis"
unit_of_measurement: "W"
state: >
{{ states ('sensor.solaredge_ac_power') | float(0) | round(0)
+ states ('sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w_filterspikes' ) | float(0) | round(0)
- states ('sensor.smartmeter_power_production') | float(0) | round(0)
+ states ('sensor.smartmeter_power_consumption') | float(0) | round(0) }}
another one I use.. it's basically to add up the total of the solar inverters, subtract the total production and/or consumption value as reported by my smart meter to get the actual in-house power usage of all appliances .. so that uses a combination of add and subtract
yes, all that kind of stuff needs templates still
hmm think I found the culprit
sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w_filterspikes <-- this one
refers to a spike filter method, as the zwave kwh meter tends to be a bit weird with its values sometimes when it reconnect..
Which is this formula:
# Aeotec power filter (get rid of nonsense spikes)
- platform: filter
name: "sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w_filterspikes"
entity_id: sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w
filters:
- filter: outlier
window_size: 4
radius: 10.0
and although that works fine as a sensor still and it has values, it seems it's not being recognised in the configuration.yaml template to use as such
if I change the non-working sensor template to the original 'sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w' it works
not a big issue tbh
but it used to work
(also yes, the spike filter comes before the other template functions)
Hello guys need some help please: been using this template to get a time but after the sun2 integration update it now supplied a timestamp like this (2024-03-13T06:25:16+00:00) and not just a time. so my previouse template is no longer working but have no clue what i need to change.
'{{ (as_timestamp(states.sensor.sun_next_rising) + (states("input_number.sunrise_offset") | int) * 60) | timestamp_custom("%H:%M") }}'
any help is appreciated thanks!
that template would have never ever worked
as_timestamp(states.sensor.sun_next_rising) has never been correct syntax
the rest seems fine
but, this is easier now anyways.
well easy is relative
{{ states('sensor.sun_next_rising') | as_datetime | as_local + timedelta(minutes = states('input_number.sunrise_offset') | float) }}
I'd change your sensor to a device_class: timestamp too. Then the UI will translate the time to whatever your system has set up.
and you'll be able to use the sensor in automations
if you keep it HH:MM, you won't have those luxuries
And maybe consider using sun elevation for whatever you're doing
Kinda seems like you're trying to fix a light level issue
dunno how but it was working lol
You either changed something, or it never worked the way you think it did
states.sensor.sun_next_rising from when HA first introduced templates always returned state objects, not states. So as_timestamp would always return 0 (beyond 3 years ago) or an error (starting around 3 years ago).
it definetly worked
been working for years
putting the new template in though isnt working though i guess how its in config has changed too
" sunrise_with_offset:
friendly_name: 'Sunrise Time'
value_template: '{{ states('sensor.sun_next_rising') | as_datetime | as_local + timedelta(minutes = states('input_number.sunrise_offset') | float) }}'"
does sensor.sun_next_rising exist?
yes if i past just the template into dev template it works
must be my formatting in the config file that it doesnt like
value_template: "{{ states('sensor.sun_next_rising') | as_datetime | as_local + timedelta(minutes = states('input_number.sunrise_offset') | float) }}"
ive done it as a helper template now and its working how can i set it to only show HH:mm dont need the date please
make it device_class: timestamp
and it will translate the unreadable state in your frontend when you use it
no formatting required, it uses what you set in your settings
i dont see timestamp as an option in template helper
its an hour ahead for some reason none of my other time based stuff is an hour ahead
time zoen is all set ok
ok looks like my old sensor was an hour behind hahaha
ah no i see issue used a + not a - im an idiot
thanks for help looks like its all good now
Is this the best method to report unavailable state as off? https://community.home-assistant.io/t/show-unavailable-as-off/462706/8
Evening all. I just tried to add the following to configuration.yaml, but the added sensor says "not available". whats wrong here?
- binary_sensor:
- name: "Car Parking Spot Helper"
delay_off:
seconds: 15
state: >
{{ states('binary_sensor.car_parking_spot_car_occupancy')|float > 0 }}```
Hi all, I was trying to list and sort all my utility meters that start with sensor.week_energy. But the sort is done by string value , instead I need it by numeric value. For example the value 3.17 kW/h would be sorted before 13.65 kW/h , because the 3 string is greater than the 1 string.
How should I change this code?
| sort(reverse=true, attribute='state')%}
{{state.name[20:]}}: {{state.state | float(default=0.0) | round(2) }} kW/h{% endfor %}```
Thanks!
A state of a binary sensor can never be converted to a float. It is a boolean and is by definition non-numeric
how would i then put it?
What do you want to achieve?
basically want this binary sensor to be a exact copy of binary_sensor.car_parking_spot_car_occupancy
just goes off 15s later when the actual binary sensor turns off.
remove the | float > 0 then
thank youuuu ❤️
You need to create a new list using a namespace and a for loop and convert the states to numbers. Then sort that new list and output the names and states
I've tried creating a template binary_sensor based on 2 door sensors:
{{ is_state('binary_sensor.living_room_door_contact', 'open') or is_state('binary_sensor.utility_room_door_contact', 'open') }}
I want it to show as open whenever any of the 2 doors is open, to show my cat has free access to its food.
But it's not reacting as expected. Rn one door is open but the sensor shows closed. What did I do wrong?
I did it via UI. Choosing "Show as door".
Just create a binary sensor group, you can do that in the GUI under helpers
No templates required
Your template isn't working because the state of a binary sensor is on or off
Not open or closed. It's translated on your Dashboard based on the state class
Check in developer tools > states what the actual state is
ahh, got confused with that
yeaah, I was playing around there but got confused. Thanks
never used the group helper
I see I can choose whether to use All or Any
nice, thanks
Hello! Im trying to make a template that counts how many people are on the bed. i have the sensor set up using esp home and sensor.bedsensor_hx711_value value ranges from <150lbs no one on the bed >150lbs 1 person >200lbs 2 people. I not very good at templating and could not find someone doing something simular on google or the forms. Could someone help me please? thank you!
@quasi frost I converted your message into a file since it's above 15 lines :+1:
and i added now the 2 new devices "Labor" and "Garage", but they dont work
found the problem
instead of notify.alexa_abstellkammer i need to use notify.alexa_media_abstellkammer 🙂
Hey there. I am having a strange problem that I can't figure out... I have a BASIC script and it is failing..
set_power_cost:
alias: Automation - Set Cost of Power
squence:
- service: input_number.set_value
target:
entity_id: input_number.utility_cost_aps
data:
value: 0.5
Any idea why it wouldn't work? The error I'm getting is:
2024-03-13 03:11:04.144 ERROR (MainThread) [homeassistant.components.script] Script with alias 'Automation - Set Cost of Power' could not be validated and has been disabled: extra keys not allowed @ data['squence']. Got [{'service': 'input_number.set_value', 'target': {'entity_id': 'input_number.utility_cost_aps'}, 'data': {'value': 0.5}}]
Oops!
Haha!
SEQUENCE 🙂
Wow!
Well, thanks! ROFL 🙂
Was a great chat!

@rocky crypt I converted your message into a file since it's above 15 lines :+1:
state_class is not supported in a legacy-type template sensor, also measurement contains a typo
Got it. Ok. Thanks. I guess I'll just use the customize function then.
You could also create the sensor from the GUI
That uses interally the new template configuration
Got it. Thank you. Is HA going away from YAML configuration and trying to make everything GUI? Is that why it's supported in GUI, but not YAML?
Not particularly, it's also supported in yaml as part of the template integration which is not the same as the legacy template sensor in your example
And a sidenote don't use the states object directly, but use the states function to extract the state.
value_template: "{{states('sensor.forecast_temp')}}"
Ok. Perfect! Thank you for your help!
@fickle sand Thanks again! I converted it to the template integration and it worked perfectly! One other question. You said to access the states function instead of the states object directly.. Is there a reason? I did change it as you recommeneded, but just trying to learn from my mistakes 😉
Anyone please? thanks
why do you want to get rid of unavailable
you can't use the switch if it's unavailable
that will misslead you
if it's a binary sensor, a template sensor is the best route. But for anything that's controllable, you don't want to do that.
Hey there. Another quick question. I was using Legacy Templates and trying to convert them to template integration.. I see there is template integration for sensors, binary sensors, numbers, and weather... Is there still not a template integration for covers? Does anyone know if there ever will be?
Right, but that's the legacy way so to speek isn't it? That's how I was doing sensors before... Just using sensor: then platform template... The template integration sensor goes under template... Maybe I'm wording this wrong....
So, for template integration way... I would have expected to see:
template:
- cover:
- name: "My Cover Name"
hmm that I am not sure.
Does that makes sense? Am I wording that correctly? So, it seems as if "covers" are still stuck in legacy mode...
I see what you're saying, I don't know what is the right answer.
As far as I know "legacy mode" is only applicable to sensor and binary_sensor. No other domains have deprecation warnings.
Ok. Well, at least I feel better and not thinking I'm going crazy haha 🙂
Got it... Well, maybe it's in the works to convert the others? who knows... 🙂
I see on the template page, it says:
Sensors, binary (on/off) sensors, buttons, images, numbers and selects are covered on this page. For other types, please see the specific pages...
And weather is listed as a separate page, HOWEVER, if you scroll down, weather is actually in the "newer" template way... So very strange...
Hmm. And then it says:
Button, image, number, and select template entities are defined in your YAML configuration files under the template: key and cannot be configured via the UI.
However, this is also not true... So, I guess the documentation is out-dated? You CAN create new buttons and numbers via UI...
Buttons, at least, are not quite the same
In a template button, you provide an action for 'press', while in a button helper you just create the entity and then I guess you need an automation to actually have it do something
I rarely use the UI outside of helping folks here, so 🤷
Gotcha. That's how I am as well. I prefer to configure everything in YAML. 🙂
A template button is like creating an input button and an automation in one go
It actually is a bit of a strange oddling within the template integration as it doesn't require any templates 🙂
Hey there. Question regarding Climate template...
On a normal thermostate, you have the options "Heat/Cool", "Heat", "Cool", and "Off"... When creating a template, I only see the option to add "Heat".. Am I missing something?
"entity_id for heater switch, must be a toggle device. Becomes air conditioning switch when ac_mode is set to true."... So, can I link AC_Mode to a entity_id to toggle True/False?
Yeah, I guess it's using 'template' as 'you define everything'. Others like a template switch are similar in 'optimistic mode'. Should be like 'generic thermostat', perhaps
This is what I tried...
climate:
- platform: generic_thermostat
name: Virtual T-Stat
heater: switch.tstat_heat_switch
target_sensor: sensor.virtual_tstat_temp
ac_mode: >
{% if states('switch.tstat_cool_switch') -%}
{{ true }}
{%- else -%}
{{ false }}
{%- endif %}
min_temp: 50
max_temp: 100
And doesn't like it 😦
nvalid config for 'generic_thermostat' from integration 'climate' at configuration.yaml, line 363: invalid boolean value {% if states('switch.tstat_cool_switch') -%}
{{ true }}
{%- else -%}
{{ false }}
{%- endif %} for dictionary value 'ac_mode', got "{% if states('switch.tstat_cool_switch') -%}\n {{ true }}\n{%- else -%}\n {{ false }}\n{%- endif %}\n"
So, looks like it has to be hard coded to "true", but then how do you turn on/off AC?
You passing true and false as variables without having a value..
Ok, I hard coded it to true, now it only has cool.. No Heat...
It seems you can't have both cool and heat like a normal t-stat... 😦
Needs ac_mode to be on when the switch is on?
Yes.
But again, there is no way to have the traditional buttons in HA for cool/heat... It's only cool OR heat it looks like...
This seems odd to me... Considering my ecobee t-stat has all 4 options/buttons... Auto, Cool, Heat, Power.... But generic looks like you can only have two!
Per documentation:
Currently the generic_thermostat climate platform supports ‘heat’, ‘cool’ and ‘off’ HVAC modes. You can force your generic_thermostat to avoid starting by setting HVAC mode to ‘off’.
However, I think they are using the word "and" wrong. Should be "or" 🙂 I can live without the "auto", but I really needed heat and cool...
One Generic Thermostat entity can only control one switch. If you need to activate two switches, one for a heater and one for an air conditioner, you will need two Generic Thermostat entities.
Ugh. Wonder why that would be???!!! Hmm....
is ac_mode set?
Yes. I tried setting ac_mode: true... This forced it to be an AC thermostat. No heat mode.
right, it can only be one or the other
That's why I thought ac_mode: should be a template... Not a hard coded true/false... This way it could change automatically from heat to ac...
I don't think it is even templateable
nothing is templateable in that
generic thermostat serves 1 purpose
it's not a template thermostat
it controls a switch based on a temperature
it's not for a nice UI to merge a bunch of things together
if you want that, you have to use the custom integration template climate or whatever it's called
Gotcha... So, I need a template thermostat and that doesn't exist 😦 So, how does the ecobee plug in create it then I wonder?
integrations can create entities
Hmm. I may have found a simple solution, but then the device shows in the UI, but only the title of the device haha 🙂 ... Interesting...
I decided to try:
homeassistant:
allowlist_external_dirs:
- /config/automation
customize:
climate.virtual_t_stat:
hvac_modes: off, heat, cool, heat_cool
As these are the exact settings my ecobee has...
The device isn't adjustable in the UI... It shows in HomeKit correctly though! HAHA
Now the question is, can is customize templateable?
Can I use if statements in it for values?
Hello there, I have a template that returns me a list of sensors. Some of the names of the sensors contains underscore that sends bonkers the markdown parser of telegram. Is there a way to escape (replace _ with \_) the output string of a template?
*The alarm is triggered!* Cause: {{open_sensors}}?
No it can't
just make a template climate using the custom integration, you're wasting your time otherwise because things won't work. Your virtual climate device will cause issues with your actual device because it's designed to turn on and off the configured switch
I am unfamilure with how to create a custom integration 😦
you've never used HACS before?
No.
Well, get installing https://hacs.xyz
ROFL 🙂
if:
- condition: template
value_template: '{{zone}} == 2'
then:
- service: denonavr.get_command
metadata: {}
data:
entity_id: media_player.marantz_sr6012_2
command: zone2
else:
- service: media_player.turn_on
metadata: {}
data:
entity_id: media_player.marantz_sr6012
I must be missing some really annoying syntactical thing, but I can't seem to get this to evaluate to true
It's a template variable
fields:
zone:
selector:
number:
min: 1
max: 2
step: 1
name: zone
default: 1
required: false
then you need "{{ zone == 2 }}"
{{ }} outputs, {% %} is logic, {# #} is a comment
your == 2 was just hanging out in no man's land
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
Hey there. I am looking for a way to have an automation trigger if a file hasn't been modified in a specific length of time. The data may not change in the file, so using "platform: file" isn't working. Because the data stayed the same, so HA doesn't show that it has been updated even thought the Date Modified of the actual file is updated...
Not sure if I need a template or not do this, that's why I'm asking in here instead of in #automations-archived.
how about the folder watcher integration
Well, I found this: https://community.home-assistant.io/t/shell-command-sensor-for-last-modified-date-of-files/402567/2, but this gives errors on restart 😦
2024-03-13 13:21:13.041 ERROR (MainThread) [homeassistant.components.sensor] Error while setting up command_line platform for sensor
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 350, in _async_setup_platform
await asyncio.shield(awaitable)
File "/usr/src/homeassistant/homeassistant/components/command_line/sensor.py", line 66, in async_setup_platform
name: str = sensor_config[CONF_NAME]
~~~~~~~~~~~~~^^^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable
Hmm. I was unaware of that integration. I can try that 🙂 Thank you!
Hey! I am trying to get this time remaining to show as XX:XX. What do i need to change in this return code:
{% if int(rem_h) > 0.9 %} {{ rem_h }} hour(s) and {{ rem_m }} minute(s) {% else %} {{ rem_m }} minute(s) {% endif %}
Full code here:
{% set rem_m = (as_timestamp(states.sensor.washer_washer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-M', false) %}
{% if int(rem_h) > 0.9 %} {{ rem_h }} hour(s) and {{ rem_m }} minute(s) {% else %} {{ rem_m }} minute(s) {% endif %}```
Its also showing 43 minutes remaining even though the washer is off
what is the state of sensor.washer_washer_completion_time?
and how does it compare to the current time?
Um it shows a date and time
Idk why
currently says 2024-03-13T23:50:32+00:00
Smart things shows the washer as off
is that 43 minutes ago for you?
Maybe. Not really sure when the washer ended
doesn't matter
is it 43 minutes ago for you?
literally that time vs. the clock on your wall 🙂
in other words, is the template working and the time there is not what you expect?
Its an hour off since daylight savings
so its technically behind
Take that back. The time it shows was the time it ended the cycle
So yes the time would have been correct but it's not updating the time within the states on dev tools
So the entity isn't updating since the washer turns off
And it's continuing to count down
If I have a yaml dictionary in a automation.
foo:
bar: 'mary'
eve: ''
adam: ''
Is it possible without a jinja loop to get the values from the dict and select != '' and print the first one?
Well just tested it out, it's not showing anything.
I also noticed that I get an error on Logs related to this template -
Error fetching Boiler On data: Parsing error: start must be a datetime or a timestamp: could not convert string to float: ''
Template variable warning: 'None' has no attribute 'last_changed' when rendering '{{ states.input_select.switcher_boiler_status.last_changed }}'
also a warning right under that error
You know this is for work and not an automation, don't lie
xxx.items() | rejectattr('1', 'in', ['']) | first
This time it's actually home assistant lol
Trying to setup an automation to control a humidifier/dehumidifier and break the logic up using yaml dicts to keep it clean vs a big jinja variable
Hm the automation doesn't like rendering that. I don't think it likes items()
action_calculation:
humidifier: ''
dehumidifier: turn_on_dehumidifier
emergency_stop: ''
This is the variable I'm trying to get what isn't '' from
Hm but it's a yaml dict does that matter?
wtf is a yaml dict
a dict is a dict
you can't use yaml in jinja if that's what you're asking... post your full code
Are you sure that entity_id is correct?
Do you mean the input_select one?
input_select.switcher_boiler_status
That's from the dev tools ^
@silent vector I converted your message into a file since it's above 15 lines :+1:
Oops
ok in a separate variable all you need to do is use the template
{{ action_calculation.items() | rejectattr('1', 'in', ['']) | first }}
Yeah I did and I'm getting
Error rendering variables: ValueError: too many values to unpack (expected 2)
Error rendering variables: ValueError: not enough values to unpack (expected 2, got 0)
Which is weird
you're doing something wrong, I do this all the time
post the full template, not your abbreviated stuff.
and when you run the automation?
Oh I have a different error downstream from the var lol. It's confusing sometimes how automation errors show in the logs. I'm getting a split error somewhere else. Let me fix that.
@mighty ledge I know you wanted me to post everything so here it is. I tagged you to make it easier to find later:)
Currently I am trying to fix the issue by creating a sensors.yaml with he following code:
- sensor:
- name: 'Washer Remaining Time'
state: >-
{% set rem_h = (as_timestamp(states.sensor.washer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-H', false) %}
{% set rem_m = (as_timestamp(states.sensor.washer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-M', false) %}
{% if int(rem_h) > 0.9 %} {{ rem_h }}hr {{ rem_m }}m {% else %} {{ rem_m }}m {% endif %}
- name: 'Dryer Remaining Time'
state: >-
{% set rem_h = (as_timestamp(states.sensor.dryer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-H', false) %}
{% set rem_m = (as_timestamp(states.sensor.dryer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-M', false) %}
{% if int(rem_h) > 0.9 %} {{ rem_h }}hr {{ rem_m }}m {% else %} {{ rem_m }}m {% endif %}```
It doesn't seem to work within the config.yaml or if I create a seperate sensor.yaml file
The current format of sensor.washer_washer_completion_time is 2024-03-14T17:25:01+00:00.
If you were complaining about minutes being 1 instead of 01, then you should remove the minus here: (%-M)
%M is zero padded, %-M is not
This is actually very helpful information to be noticed by others that can answer your question 🎉
I am sure petro or others can help you with it.
I will mention some small things now, because I have to leave in a minute.
This is part of the template integration and should not be posted directly under sensors or in sensor.yaml, that will not work unfortunately.
If you want written style relative time you can check the easy_time or relative-time-plus macro's
Ok, so do you still want that format hr m s? Or do you want an actual clock? HH:MM:SS?
I realistically just need hour and minutes remaining
Ah ok. That makes sense
template:
- sensor:
- name: 'Washer Remaining Time'
availability: >
{% set end = states('sensor.washer_completion_time') | as_datetime %}
{{ end and end > now() }}
state: >
{% set end = states('sensor.washer_completion_time') | as_datetime | as_local %}
{% set current = now().replace(microsecond=0) %}
{% set sec = (end - current).seconds %}
{% set h = sec // 3600 %}
{% set m = (sec // 60) % 60 %}
{{ h ~ 'hr ' ~ m ~ 'm' if h else m ~ 'm' }}
sorry got pulled away again
anyways, that will be unavailable when the end time is older than the current time
if you wanted a real duration sensor, I can also provide that. But it will be HH:MM:SS format
but the template would be easier to understand
which is...
That would be fine with me. I mainly just need to to show 0 when its done and place a 0 in front of the minutes when needed
I don't think you need to remove the microseconds, .seconds already returns an integer
I do it always for timedeltas if you plan to output the result
just a habbit at this point
template:
- sensor:
- name: 'Washer Remaining Time'
availability: >
{% set end = states('sensor.washer_completion_time') | as_datetime %}
{{ end and end > now() }}
device_class: duration
unit_of_measurement: s
state: >
{% set end = states('sensor.washer_completion_time') | as_datetime | as_local %}
{% set current = now().replace(microsecond=0) %}
{{ (end - current).total_seconds() }}
anyways, that will also be graphable (history) and it will show up as HH:MM:SS in the UI wherever you put it
Once I get back to my PC I will test this. Thank you so much
based on a timestamp sensor for my next-alarm, what is the cleanest way to create a binary for alarm on for tomorrow? thing is, the timestamp sensor returns 0 if no alarm is set, and then the .day returns funny things...
so now I re-enter another binary {% set next = states('sensor.next_alarm_timestamp')|as_datetime() %} {% set gezet = is_state('binary_sensor.wekker_gezet','on') %} {{gezet and (now()+timedelta(days=1)).day == next.day}}
that check for 2 booleans {{is_state('input_boolean.alarmclock_wd_enabled','on') or is_state('input_boolean.alarmclock_we_enabled','on')}}
if that is on, it is safe to test for the .day equality
otherwise it would do this...
{% set next = states('sensor.next_alarm_timestamp') | as_datetime %}
{{ next is datetime and (next.date() - now().date()).days == 1 }}
that returns a typeerror
Sorry, accidentally added parenthesis after next. Fixed
yes, that works!
now I need t understand why 😉
is that first test still essential? this wrks too {% set next = states('sensor.next_alarm_timestamp') | as_datetime %} {{ (next.date() - now().date()).days == 1 }} and next will always be a datetime?
just tested that in all conditions (booleans on/on, on/off, off/on, off/off) ...
next.date() will not work when you don't have an alarm set
the template then returns False, which is correct, but not because next is datetime would fail. that always returns true, also when no alarm is set
next is datetime will return false when the state of the sensor is not a datetime string
Eg when it is unavailable
ok, Ill add it as extra safeguard
need to check if my base sensor timestamp itself isnt doing that already... but it wont harm to be safe
much cleaner anyway, thx!
Even nicer… was just about to paste the timestamp sensor when my keyboard on the Mac started acting up
Weird, can’t type anymore at all on the device
This helps a lot!
This worked. Thank you! However it will still count down even if I just turn the washer on and off and don't start a cycle. Is there a way to fix that?
You washer would have to give that information out
- name: Assist_Last_Called
state: "{% set sensor_states = namespace(last_sensor='', last_changed=None) %}{% for entity_id in ['sensor.thinksmart_lr_stt','sensor.firehd_7_stt' ] %}
{% set state_obj = states[entity_id] %}
{% if state_obj.state == 'start' and (sensor_states.last_changed is none or state_obj.last_changed > sensor_states.last_changed %}
{% set sensor_states.last_sensor = entity_id %}
{% set sensor_states.last_changed = state_obj.last_changed %}
{% endif %}
{% endfor %}
{{ sensor_states.last_sensor if sensor_states.last_sensor else 'None' }}"
Can someone tell me how to format this correctly? Do I need to do
state:| or something to get a multiline valid yaml?
I guess I could string it all together but that is maybe more of a mess than this.
Hmm okay. I will look more into the integration. Thank you for your help
- name: Assist_Last_Called
state: >
"{% set sensor_states = namespace(last_sensor='', last_changed=None) %}
{% for entity_id in ['sensor.thinksmart_lr_stt','sensor.firehd_7_stt' ] %}
{% set state_obj = states[entity_id] %}
{% if state_obj.state == 'start' and (sensor_states.last_changed is none or state_obj.last_changed > sensor_states.last_changed %}
{% set sensor_states.last_sensor = entity_id %}
{% set sensor_states.last_changed = state_obj.last_changed %}
{% endif %}
{% endfor %}
{{ sensor_states.last_sensor if sensor_states.last_sensor else 'None' }}"
Second attempt. Still not working
2 timer entities?
Remove the surrounding quotes
oh
{% set sensors = expand(['sensor.thinksmart_lr_stt','sensor.firehd_7_stt' ])|selectattr('state', 'eq', 'start') %}
could probably do more with stuff like that
Man I thought I was doing good by including them! One day I'll catch on
Truth be told I'm going by an example I was provided but I will look at what you provided for sure. Thank you
that'll give you a list of those things that have that status
and its already in object form
i'm kinda anal about avoiding loops when i can though
if it works, it works
Hmm. So I removed the quotes and I'm still not seeing the new entity. Am I doing something else wrong?
you can't string compare a date to none
hmm. Okay. Please bear with me. This works fine in dev tools template and just trying to figure out how to make it a sensor so I can determine which assist device last called for some custom stuff I'm doing.
{{ sensor.entity_id if sensor else 'None' }}```
something like that might work
might need to drop the |first
Getting a No aggregated item, sequence was empty. when trying
with or without |first
🙂
too much regex for me
Empty list then when I call it I get:
[<template TemplateState(<state sensor.thinksmart_lr_stt=start; engine=stt.home_assistant_cloud, metadata=language=en-US, format=AudioFormats.WAV, codec=AudioCodecs.PCM, bit_rate=AudioBitRates.BITRATE_16, sample_rate=AudioSampleRates.SAMPLERATE_16000, channel=AudioChannels.CHANNEL_MONO, icon=mdi:numeric-2, friendly_name=ThinkSmart-LR STT @ 2024-03-14T18:17:25.613942-05:00>)>]
ok, there's only one object there
And that's what I was hoping for
Understood and thanks for the help. Please share your idea when you have time.
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|list|length > 1 else 'None'}}
i think that'll do it
@bronze prawn
couple of ninja edits
TemplateSyntaxError: Encountered unknown tag 'sensor'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
That's with the edits.
lol more condensed with a fix
changed again
oops, one more change
it doesn't like those previous forms of pulling an attribute because of how its pulling things
Good news bad news. Good news: It shows 'None' with no errors. Bad news, it never changes but the other code I was using before does (your example) change so this one is just not noticing the change
change |attribute() to |attr()
weird
At some point I'm going to be back to the same question as to how to add this into the template sensor.
```it looks like this?
{% set sensors = expand(['sensor.thinksmart_lr_stt','sensor.firehd_7_stt'])|selectattr('state', 'eq', 'start')|rejectattr('last_changed', 'eq', None) %}
{{ sensors|max(attribute="last_changed")|attr('entity_id')
it shouldn't be throwing that because if the list is empty it wouldn't get there
unless you dropped the if check
Alright. So maybe I got things goofy in the copy/paste but this is what I have based on me piecing everything together:
{% set sensors = expand(['sensor.thinksmart_lr_stt','sensor.firehd_7_stt'])|selectattr('state', 'eq', 'start')|rejectattr('last_changed', 'eq', None) %}
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|list|length > 1 else 'None'}}
This is back to not changing from None
you dropped the >=
No aggregated item, sequence was empty.
Alright. I don't want to try your patience. I added the >= back in and that's what I'm getting when calling the mic
so weird
because this works:
{{ foo|max if foo|list|length >=1 else "bar" }}```
-> bar
oh
figured it out
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|length >= 1 else 'None'}}```
had to put the |list earlier
Bingo!
putting it all together:
state: >-
{%- set sensors = expand(['sensor.thinksmart_lr_stt','sensor.firehd_7_stt'])|selectattr('state', 'eq', 'start')|rejectattr('last_changed', 'eq', None)|list -%}
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|length >= 1 else 'None'}}```
Giving it a shot now
That did it. Thanks so much. This is one of the missing pieces I need to do more with my Echo Show replacement project.
haha good luck!
Hi,
can somebody help me fix/finish my simple template? I receive an error (TypeError: '>' not supported between instances of 'NoneType' and 'datetime.datetime') in HA: {{ state_attr('serge_s_apple_watch', 'away') > now() - timedelta(minutes=30) }}
I'm just trying to conditionalize if the watch has been away for more than 30 mins
Seems like there's no such attribute
Your entity is missing it's domain... it should likely be sensor.serge_s_apple_watch but you haven't provided enough information.
Hey @dreamy sinew Is there a way to modify the template so that it keeps the value of the last called mic and only change it when a new mic makes a call? Right now it will only show the value when 'ok nabu' is said but as soon as you say anything else like 'turn on the living room light' the value goes back to 'None' which doesn't provide much. Apologies.
hmm, that's a lot harder
might need a 2nd entity
maybe an input text and an automation to set it when the sensor.Assist_Last_Called is updated but not when its none
Gotcha. Will check that out later. Running on fumes right now.
yep! 100% a copy/paste error. I fixed that obvious problem (thank you) but I still get a similar error {{ state_attr('device_tracker.serge_s_apple_watch', 'away') > now() - timedelta(minutes=30) }}
As Rob stated above, away is not a common attribute, so that is the next most likely source of your issue. Can you clarify where you are trying to use this template? For example, are you trying to trigger an automation when the watch is away for >30 minutes or are you setting up a Template sensor....?
finally made it back.... here's the timestamp sensor controlling all. based on 2 booleans, and 2 input datetime (weekday and weekend)
Finally got this automation working and this code does work. How would I get it to just show the value other than using a list index? In your example it would show just turn_on_dehumidifier and not the key 'dehumidifier' as well.
Map the second value
1 refers to the value, 0 would be the key
Ah that's what I thought.
Hi, trying to retain my attributes over a restart. Understood that a trigger based sensor will keep it, so I am copying it. But it turns the array to a string, and I am stuck. Anyone with some tip on how to move along. (it is nordpool data).
`template:
- trigger:
- platform: time
at: "11:17:00"
sensor: - name: nordpool_idag_recal_ts3
state: 0
attributes:
raw_today: "{{ state_attr('sensor.nordpool_recalculate_new6', 'raw_today') }}"`
- platform: time
I can not pull a specific position in the array
Looks identical, but is treated as a string
[{'start': datetime.datetime(2024, 3, 15, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 2, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 2, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 3, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 3, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 4, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 4, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 5, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 5, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 6, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 6, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 7, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.418}]
exactly as I thought, it has datetime objects which can't be serialized
you need to convert each datetime into a string in order for it to treat it as a list, this will also affect the code and the behavior of whats displaying the information
What do these values represent and what are you trying to do with them?
It is energy prices for each hour
and what are you doing with those prices?
I collect them from the nordpool intergration, do a python script for calculation of additional costs
Then i am using it for energy usage optimization
e.g. which hours to turn things on when it's the cheapest?
Yes
ok, well I have a few recommendations then.
Works well, untill i do a restart before next days prices are available
- you can use https://github.com/TheFes/cheapest-energy-hours instead of your python script to do all the math to get cheapest hours, then only store the cheapest hour range via a template that has a trigger.
I could compensate in other ways, just forllowin this track for now
- Continue using whatever you derrived, but do the same thing. Run the calculation when you get the data, only store the result in a trigger template sensor.
tried alternative 2. it does not retain the data written from the python script over a restart...
don't use the python script to set a state
use it to do the calculation
then have a trigger based template entity store the value
i.e. fire an event from your python script that has the data, then use a trigger based template enttiy that triggers off the event and uses the data
or just use thefes's macro in a trigger based template entity.
Thanks for your time and help. I will certainy take a look at TheFes and also see if I can change somethng in my logic. The fun of HA this 🙂
this is how you trigger an event:
hass.bus.fire("hello_world_event", {"wow": "from a Python script!"})
then your trigger
trigger:
- platform: event
event_type: hello_world_event
accessing data in templates
trigger.event.data
why do you need yesterday's data?
it would be nice if the Nordpool or Entso-e integrations would add the response service calls. That would make it easier to create a sensor with all the data you need, including yesterday's data
I am doing a period from 18-07
okay, you can use a trigger based template sensor at eg 17:00 to determine the best time in that period
as it is trigger based template sensor it will not change until 17:00 the next day
here is an example using the macro https://github.com/TheFes/cheapest-energy-hours/blob/main/documentation/6a-dishwasher_overnight.md
I am doing graphs and price limits, all works but with a restart I loose proper function till Norpool updates around 13:30...
well, if you're interested in 18:00 - 07:00 you're data loss will be at midnight
You are right I will be able to compensate for this and be as good as before my latest journey to make things harder for myself
I'm struggling trying to return the name of an attribute that matches a value.
Entity: [<template TemplateState(<state plant.pothos_golden=problem; species=Epipremnum aureum 'Golden Pothos', moisture_status=ok, temperature_status=ok, conductivity_status=Low, illuminance_status=ok, humidity_status=None, dli_status=ok, species_original=epipremnum aureum 'golden pothos', device_class=plant, friendly_name=Pothos Golden @ 2024-03-15T11:53:42.565631-05:00>)>]
In this case, I would like to return the attribute name "conductivity_status". This should work, but I guess the plant domain doesnt have the same attributes as the sensor domain.
{% for key, value in a.items() if value.text == "Low" %}
{{ key }}
{% endfor %}```
On mobile but
if key == 'conductivity_status'
Or if you want to find low, if value == 'Low'
any one of those keys can be "Low", I'm trying to return the name of whatever status low
ahh
I guess there's no .text suffix
No, it’s not suffix
I'm having a hard time coming up with the actual word for it, you're right
What you’re asking there is to get the text key from value but value isn’t a dictionary
that was it, if value == "Low". I can't believe it was that simple
Over thinking it 😉
Now to figure out how to use multiple keys
if value in ["Low", "High"] ?
sweet, again simple
Hi Guys, i would like to create a setup panel for the lights, I'll explain better with an example, I have 10 lights, I would like to create booleans to use in an automation that only turns on the lights that are "on" in the booleans, this is something that can be done for you? I don't want to create groups but a real control panel where I decide which individual lights to turn on.
What's the difference between.. (I know the example's malformed, just assume I got it right)
states.plant.pothos_golden.attributes
and
states('plant.pothos_golden').attributes ?
The first one will give you all the attributes from the state object, the second will give you an error
I"m trying to utilize a variable + concat to turn
variables:
triggering_entity: "{{ trigger.entity_id }}"```
into
```sensor: >
{% for key, value in 'states.'~triggering_entity~'.items()' if value in ["Low", "High"] %} {{
key.split('_')[0] }} {% endfor %}```
I have a working example in a different automation, but that automation is only outputting a string, it's not trying to use the concatted string as an entity
states[triggering_entity].attributes.items()
with square braces specifically?
Yes
Are the lights that will be controlled by the "panel" fixed, or do you expect that you will be adding or subtracting other lights? The best way to make templating easy in cases like this is to make sure you have a consistent naming convention for all the input booleans and lights involved.
in fact I would like to leave myself the possibility of adding new lights..
what do you mean with "consistent naming convention for all the input booleans and lights involved"
call input boolean and lights the same way?
If you're going to add entities, you would be better served putting them in a group. That would reduce the places you have to edit... especially if you use a card like Auto Entities or one that accepts templates. HAving the names the same is easiest, but the names do not need to be the same as long as the way they are different follows a pattern.
looking for an example for templating an action..
{% for key, value in states[plantid.entity_id].attributes.items() if value
in ["Low", "High"] %}{% if loop.first %}{{plantid.attributes.friendly_name}} needs: {%endif%}
{{ key.split('_')[0] }}{% endfor %}
{% endfor %}```
does pretty much what I want.
Pothos Manjula needs: conductivity
Pothos Marble needs: moisture
Pothos Golden needs: conductivity
Basically for every plant returned by the above, I want to run the action
```yaml
action:
- service: notify.wife
data:
title: I'm dying! :warning::radioactive::skull_crossbones:
message: >
{{state_attr(plantid.entity_id,"friendly_name") }} :herb: needs: {{
sensor }}
sorry, power went out
I'm mainly interested in a dynamic action that applies to all plant entities, even ones added later will just automagically be included
right, see the link
so you're suggesting the automation call a script, and the script handle the template actions
you can do that right in the automation action
the action of an automation is a script
this is similar to what I've already tried:
action:
- repeat:
for_each: "{{ plant_list }}"
sequence: []
variables:
plant_list: "{{states.plant|map(attribute="entity_id")|list}}"
fails when saving, with error `template value should be string for dictionary value @data['action'][1]
aha
You're not actually doing anything in the sequence, but I don't think that's invalid, just useless
agreed, I"m just trying to verify syntax before adding the sequence
understood
It's a trick I've learned from years of being an idiot. Don't change too much, you may not know what you did that broke it
I'm not sure that you can just stick the variables section out there like that
maybe you can, but I can't find the documentation to support it
oh, you're using the same quotes inside and out
at least that, maybe other stuff, too
quotes, that was it
this script validates and works fine for me:
repeat_test:
sequence:
- variables:
plant_list: "{{states.alarm_control_panel|map(attribute='entity_id')|list}}"
- repeat:
for_each: "{{ plant_list }}"
sequence:
- service: persistent_notification.create
data:
message: "{{ repeat.item }}"
good news is I may have figured a way to handle an individual run immediatly on state change as well as an aggregate reminder of all problem sensors with a single for loop
are you using plants.yaml ? or have them all separate?
Hey all, I'm having trouble creating a binary_sensor using a motion sensor that updates a "time" value whenever it's triggered. I'm using some old sensors via rtl_433 and the time value is the only thing that updates in MQTT when triggered.
and what is the question?
Is there anyway to have the payload_on when the time updates then switch to payload off after a second or so
Can I tell you what I did wrong?
],
"received_at": "2024-03-16T05:46:16.004320157Z",
"uplink_message": {
"session_key_id": "AY5DIq6NZbVG/u2dR1N4mQ==",
"f_port": 2,
"f_cnt": 164,
"frm_payload": "AAAAAAAAAAAAAAAAnu93QBSuq0HS3HpEAJltQg==",
"decoded_payload": {
"batteryVoltage": 3.874000072479248,
"humidity2": 59.3994140625,
"pressure2": 1003.4503173828125,
"temperature2": 21.459999084472656
},
mqtt:
sensor:
- name: Balcon-Sensor-Temp5
state_topic: "v3/my-sensor01@ttn/devices/eui-70b3d57ed0065ebe/up"
unit_of_measurement: "°C"
value_template: "{{ value_json [uplink_message.decoded_payload].temperature2'}}"
I think it depends value_template: "{{ value_json [uplink_message.decoded_payload].temperature2'}}"
I also tried it like in this video
That doesn't work either
@haughty galleon I converted your message into a file since it's above 15 lines :+1:
The proper format is either value_json.key1.key2.key3 or value_json['key1']['key2']['key3'] or a even a mix of the two value_json['key1'].key2['key3']
The square brackets are especially useful when you want to use a variable
{% set var = 'key1' %}
{{ value_json[var] }}
The mqtt sensor yaml code you shared looks correct, but it’s not possible to tell for sure without the entire json string. Are you sure uplink_message is the first level of the json object (and also not a member of a list)? Share the JSON on dpaste.org
@haughty galleon I converted your message into a file since it's above 15 lines :+1:
now I get an output
how can I create a template that contains all the friendly names for a list of entities where state is "on"?
my problem is that the entities are not of same type, but they are binary_sensors, sensors, switch
@spark vortex This might work for you. Included a couple of examples on how to exclude some entities. yaml {{ states | selectattr ('domain', 'in', ['light','binary_sensor','switch']) | rejectattr ('entity_id', 'in', integration_entities('group')) | rejectattr ('entity_id', 'eq', 'light.all_lights_on') | rejectattr ('entity_id', 'search', '_screen') | sort(attribute = 'entity_id') | map(attribute = 'name' ) | list }}
but I don't want to check all entities in these domains, but just some of them
excluding is hard, can I just include what I need?
I mean, I have more than 100 entities, I just need to check less than 10, so it is easy to add than exclude
I created an old stype group, becase I can add different type of entities in the same group and then used this "{{ expand('group.elettro_on') | selectattr('state', 'eq', 'on')| map(attribute='name') | list | join(', ') }}"
I am not happy to use the old style group, but I guess there is nothing better to use
Are you wanting to hard-code the list of entities into the template?
I'd prefer to not hard-code it, that is why I am using the group that is easier to add/remove entities
What about the group don't you like because that seems to work pretty well using the code you provided?
it works, I am just usign old style group, is it still ok or it will be removed soon?
You can do the same with a GUI created binary sensor group
with helpers?
Yes
it supports different type of entities in the same group?
it seems not
group: elettro_on: name: elettro on entities: - binary_sensor.caffe_state - switch.tv_letto_switch - switch.tv_cucina_switch - switch.tv_salone_switch - switch.tv_gabry_switch - binary_sensor.piano_cottura_state - binary_sensor.thermostat_state - sensor.ac_cucina_state - sensor.ac_salone_state - sensor.ac_camera_da_letto_state
this is my group, if I can do the same with not old stype syntax, I would be happy 🙂
{{ state_attr('calendar.persoonlijk', 'start_time') }} gives null if calender is not set but it gives true if check is defined.
How can i make a check that does not break my state_attr('calendar.persoonlijk', 'start_time') code
Ah, you indeed can't combine multiple domains in the modern groups
What do you want it to return instead of null?
this doesnt seem to work like i expect it to work, it stops at midnight, am i reading the documentation wrong or is this a bug?
- platform: history_stats name: in bed entity_id: binary_sensor.test_still_target state: "on" type: time start: "{{ today_at('20:30') }}" duration: hours: 17
@spark vortex TheFes I wonder if you could use something like this: ```yaml
elettro_on:
name: elettro on
entities:
- binary_sensor.binary_sensor_entities_group_from_UI
- switch.switch_entities_group_from_UI
- sensor.sensor_entities_group_from_UI
yeah, but in my template I will get the group name and not the entry name (it is inside the inner group)
Nope, expand also expands group members if these are groups themselves, until it reaches the final single entities
Turtles all the way down
Yes, it is the correct entity_id.
What can I do to prevent this error & warning?
Hello.. I need some help on a sensor, which is supposed to calculate the weighted average of the several marks from school.. the retrieve or the marks is working, but it seems that total_notes and total_coefficients are reset at each loop when they shall sum up at each loop..
Any clue on what is wrong in my code?
Here is is:
https://dpaste.org/4A3cQ
yes, you need to use a namespace for variables changed inside the loop to be reflected out side it
here's a random example: #templates-archived message
This will prevent the error
{{ states.input_select.switcher_boiler_status.last_changed | default(now(), true) }}
Great, it works!! Thanks a lot @inner mesa !!! 👏
@distant abyss I was using plants.yaml, but removed it in favor of the Plant Monitor integration + OpenPlantBook
What am I doing wrong here? Any and all help appreciated.
"{{ int([states.light.nursery_1,
states.light.nursery_2,
states.light.nursery_3,
states.light.nursery_4]
| selectattr('state', 'eq', 'on')
| list | count) == 1
}}""
seems to work as expected in dev tester, but always evaluates false when entered in config
What does this have to do with templates?
Uh shoot, wrong thread. Sorry.
I need a pointer because I cant seem to get my head around jitsi2. I want to iterate over elements of a calendar. I'm in the developer tools and tried {% for calevent in calendar.xxxxx %} but it complains that calendar is undefined. How do I refer to the calendar I want to access?
I am missing something obvious, that much is certain. Somehow, I cannot use calendar. inside the developer tools despite it being suggested to me when I type calendar. (it opens a dialog with suggestions including the calendar I'm looking for).
I'm still working on my project. I'm wondering if I can create a group with my custom sensors and somehow use a template that searches the members in the group for one of them that has state of 'assisting' . Is that something easy to do with templates?
@merry furnace I converted your message into a file since it's above 15 lines :+1:
Are you using this in the GUI template helper section? If so, remove the quotes around the template. It also seems you have 2 double quotes are the end
And you might want to use
{{ [ 'light.nursery_1', 'light.nursery_2', 'light.nursery_3', 'light.nursery_4'] | select('is_state', 'on') | list | count == 1 }}
No I'm using it in an automation yaml file
I'd past the whole part in, but I think I remember that pasting too much code in the discord here is frowned upon 😉
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.
Use one of those
You could also create a light group out of the 4 lights and check if the group is on
BTW, I now noticed you were responding to my reply to someone else
https://dpaste.org/6eiZT
This is the heating automation part I created to increase / decrease an integer, so later I can use that integer to turn pumps and heating on or off.
I'm not sure I understand what you are trying to achieve. You have several climate entities. But what are you trying to achieve by comparing them with each other?
The comparison is between the temperature sensor of them and the thermostat setting. Based on that I now if that device would like to get heat.
I then want to increase the value of the number higher if heat is needed and lower based on devices that do not need heat. I should however push the number higher with the total number of thermostats and decrease only by one.
The way I have written this now however looks like it should be done differently and more efficiently probably.
Why do you have these numbers in your entity_id's?
The are coming from fibaro
Thanks!
But it's now showing me a full timestamp instead of number of hours / minutes it's on
Time On: 2024-03-17 04:50:16.637077+00:00
Current: 0W
Yes, you should use it in the history stats sensor
We started here
#templates-archived message
Ok so by all I now understand,
{% for event in calendar.xxx %}
should actually work. Just how can I prevent the dev tools from telling me that calendar is undefined? It does the same for sensor and any other element type I can think of.
it seems I can access something with {{ states("calendar.xxx") }} but that only reutrns off, I still fail to find the structure of a calendar object
Only the current or next calendar event is shown in the entity itself
For all events in a certain period you need to use the list_events service call
my point is it already fails at calendar
I don't understand how to retrieve a list of entries, like with which syntax.
Hey guys,
Can someone tell me why my template (which is working) still throws
errors in logs that my power_sum variable is undefined
all inputs to my variable power_sum should default to 0 on any error if I understand float(0)
https://dpaste.org/8BUsf#L12
"Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined"
I know but even if I take the 04:50:16 out of it, it's incorrect.. the boiler was on for 1 hour and 25 minutes.
That's not what history stats will do
4:50:16 is the time (UTC) it was last changed
Not the time since the last change
@clear mist I converted your message into a file since it's above 15 lines :+1:
Try:
if states(entity) | bool(false)
or
if is_state(entity, 'on')
States are strings, and Jinja will use both "on" and "off" as True
I have been reading the documentation since you posted that yesterday, can't get it to work... might need your help here 😦
Good morning, i use a window sensor to check the status of a lock. But the displayed status is wrong. If the lock ich locked, it shows me open, because the windows sensor is at this moment not active. But at this moment the status should be locked. How can i invert the displayed status?
Ah, that was 100% it - thanks so much, you're a lifesaver!
i tried to add a template sensor to my configuration.yaml
- platform: template
sensors:
garage_tor_schloss_invertiert:
value_template: "{{ is_state('binary_sensor.garage_sensor_tor_schloss_contact', 'off') }}"
friendly_name: 'Garage Tor Schloss Invert'
but when i try to add device_class: lock, i got a error message during checking the configuration.yaml
I guess you will need to change the template sensor to a template binary sensor
device_class: lock is not available for the sensor domain
ah got it, so how can i change the template sensor to a binary sensor?
binary_sensor:
- platform: template
sensors:
garage_tor_schloss_invertiert:
value_template: "{{ is_state('binary_sensor.garage_sensor_tor_schloss_contact', 'off') }}"
friendly_name: 'Garage Tor Schloss Invert'
If you put it directly in configuration.yaml else you can add what you have into binary_sensor.yaml
Or create it in the GUI and it will be build in the (new) format
ok, i tried:
- binary_sensor:
- platform: template
sensors:
garage_tor_schloss_invertiert:
value_template: "{{ is_state('binary_sensor.garage_sensor_tor_schloss_contact', 'off') }}"
friendly_name: 'Garage Tor Schloss Invert'
device_class: lock
then i recive: Invalid config for 'sensor' at configuration.yaml, line 166: required key 'platform' not provided
The hyphen(-) before binary_sensor is not needed
- platform: history_stats
name: Boiler On
entity_id: input_select.switcher_boiler_status
state: "On"
type: time
start: "{{ states.input_select.switcher_boiler_status.last_changed | default(now(), true) }}"
end: "{{ now() }}"
Using this sensor on the 'Current' part of this card:
http://pastie.org/p/1wgurLyTU1CPJe4pawEHam
What should I modify to show time preferred by the number of minutes and not the number of hours since the state changed to On, I have read the documentation a few times but I'm stuck.
then i got errors, it should be placed at the right position in the cinf...yaml
figured the right position out, its working now 🙂 Thank youuuu!
if you add a unique_id you can change it to minutes in the setting of the entity
- platform: history_stats
name: Boiler On
unique_id: dc81f153-e9fc-4521-823c-24dcd23b968e
entity_id: input_select.switcher_boiler_status
state: "On"
type: time
start: "{{ states.input_select.switcher_boiler_status.last_changed | default(now(), true) }}"
end: "{{ now() }}"
Like that?
yes
How can i change the colour of a state depending of the staus?
Thanks, managed to change it to minutes now.
Why do I have to add unique_id to be able to access those settings? and what do I need to do with the start line to let it show the minutes its state is On and not the timestamp?
Do you mean to change the color of the icon? This can either be done by themed state color variables or in some card that supports templating for the icon_color both are more related to #frontend-archived
only entities with a unique_id can be changed in the GUI settings
and you don't need to do anything with the start line to do that, the state of this history stats sensor will be the numer of minutes it's On
oh got it
so why is it showing now
Time On: 0.000259015162785848
and the Boiler state is Off at the moment
I also changed the entity settings to Display Precision to 0 (so it won't show big numbers like those and just the minute)
because there is a minor difference between the start and end now()
Display precision is only applied in the frontend, not in the dev-tools/states tab
- platform: history_stats
name: Boiler On
unique_id: dc81f153-e9fc-4521-823c-24dcd23b968e
entity_id: input_select.switcher_boiler_status
state: "On"
type: time
start: "{{ states.input_select.switcher_boiler_status.last_changed | default(now().replace(microsecond=0), true) }}"
end: "{{ now().replace(microsecond=0) }}"
this will probably resolve that
The number I pasted is from the frontend = my card
what kind of card is that, unless you use a template to show it, it should use the set precision in the entity
But what can I change in the template to show 0 or null when state is not On which means the Boiler is Off and obivously there is no time on when device is off
It should do that with the version I pasted above
@sonic sand I converted your message into a file since it's above 15 lines :+1:
Except from some custom card that doesn't support display precision
I used mushroom-template-card
That should support it
no, he uses a template
use this to use the precision set:
secondary: Current: {{states("sensor.boiler_power", with_unit=true) }}
it will also automatically use the unit of measurement
so should I remove the change you've done to the start&end few minutes ago or keep it?
Oh right, it depends on the template states() extracts the raw state right, unless the variable rounded=true or with_unit=truei s set
you can
I think it's best to leave it as is
but if you only want it to show on that card, you could just create a template which shows the time it has been on
it should already do that
Okay I will give it a shot
IIRC history stats shows duration sensors
not necessarily, I will show it in various cards through my dashboard.
okay
anyway, this should also work:
secondary: >
{% set entity = 'light.booglamp' %}
{% set last_change = states[entity].last_changed %}
{% set minutes = ((now() - last_change).total_seconds() / 60) | round(0) if is_state(entity, 'On') else 0 %}
Current: {{ minutes }} minutes
@mighty ledge got time for a q? 🙂
just post it, anyone can help
Ay its posted earlier without response 🙂 I can copy paste
repost:
Can someone tell me why my template (which is working) still throws
errors in logs that my power_sum variable is undefined
all inputs to my variable power_sum should default to 0 on any error if I understand float(0)
https://dpaste.org/8BUsf#L12
"Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined"
basically got a working sensor that always shows values, no errors in UI/graph view yet my logs are spammed with errors
thats it unfortunately, i get nothing more than that .__.
just am oment
need to reactivate it and wait for an error, was spitting out to many faults so i disabled it
From older timestamps (while i wait)
2024-03-18 10:59:10.970 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'power_sum' is undefined when rendering '{{ power_sum }}'
2024-03-18 10:59:10.971 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
Internet crashed; sorry
It's still showing me the long number we had before
I don't see how those errors can occur with what you posted
there has to be an error before that
outside that, I wouldn't even use a tempalte sensor for this, I'd just make a sensor helper group with sum selected
i'd then have a second template sensor that outputs 'Error' 'Idle', etc
afraid not , i ctrl-f my log and there is nothing else related to my power2 sensor oother than repeats of the lines i posted thats why im confused
2024-03-18 11:06:52.648 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 11:06:52.648 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 11:06:52.649 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 11:06:52.649 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 11:06:52.649 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Running template script
2024-03-18 11:06:52.650 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Executing step setting variables
2024-03-18 11:07:00.162 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Running template script
2024-03-18 11:07:00.162 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Executing step call service
2024-03-18 11:07:25.768 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 11:07:25.769 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 11:07:25.769 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 11:07:25.770 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
heres a longer snippet
I understand but its secondary information and i'd rather not have unneccesary amount of entities if I can group data like this, i rather like that option
just wasn't expecting all the errors even across reboots
and now that I re-enabled it it's spamming errors again
2024-03-18 13:09:17.655 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 13:09:17.655 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 13:09:17.656 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 13:09:17.656 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 13:09:17.663 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Running template script
2024-03-18 13:09:17.663 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Executing step setting variables
2024-03-18 13:09:24.781 ERROR (MainThread) [moonraker_api.websockets.websocketclient] Websocket connection error: Cannot connect to host 192.168.1.86:4409 ssl:default [Connect call failed ('192.168.1.86', 4409)]
2024-03-18 13:09:50.657 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 13:09:50.657 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 13:09:50.658 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 13:09:50.658 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 13:09:50.659 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Running template script
guess I could report it as a bug on github since neither you nor I see any errors in my template
how fast are these updating?
on state change from 3 different entities from the same devices (a shelly 3PM)
so 30s i think?
yeah, just use a sensor group and a separate template sensor
it appears to be updating too fast
ah ofc.. 3 updates every 30s when shelly updates the 3 entities ..
or yoru script has an error in it and it failed the first time and now it's stuck
ill try just using a single entity on the state
not sure what you are using now
@sonic sand I converted your message into a file since it's above 15 lines :+1:
Thanks for help
I'd like to create a group that contains all of the microphones tied to assist. these show up as sensor types. I added a helper with these but it seems to have made them into a combined sensor instead of a group.
Can I group sensors together so that I can expand them and use them in templates or am I thinking about this the wrong way?
use oldschool group, yaml only
you can also use expand on a GUI created sensor helper group
ah yes
I"m assuming these won't be numeric
yeah, but someone else in the ass the other week, fresh in my mind
would be nice if we had a sensor group that just output the timestamp of the last entity update
auto made it into a timestamp sensor
No. They will not be numeric. hold strings. Will configure in yaml. Thanks
if i have a sensor like nordpool, with attributes that is prices etc, can i make another sensor that monitors a specific attribute in the nordpool sensor for state changes? like when new price comes in the attribute changes
The nordpool sensor has a tomorrow_valid attribute that indicates that the new prices are available
@Bas ok, can i make a trigger somehow that triggers on that changes from false to true, or whatever the state is ? 🙂
Yep you could do that
I am using the trigger directly in an automation, but it should also work similar in a trigger sensor
trigger:
- platform: state
entity_id:
- sensor.nordpool
attribute: tomorrow_valid
for:
hours: 0
minutes: 0
seconds: 0
from: false
to: true
thanks 🙂 gonna try it out .. have had trigger at 15:00 so far each day and sure that works but it keeps working on old data from when i get the data until 15:00 🙂
well just used the boiler device, and it's showing 0 mins on the card (#templates-archived message).
in devtools it is showing 0.0 in state.
is it still On?
Maybe it's better to create a template sensor using this template:
{% set entity = 'light.booglamp' %}
{% set last_change = states[entity].last_changed %}
{{ ((now() - last_change).total_seconds() / 60) | round(0) if is_state(entity, 'On') else 0 }}
You can paste this as the template in a GUI tempalte helper
I'm back asking questions but hopefully I'm almost done. @petro helped me last week in creating a sensor that shows the last used assist microphone device (sensor.assist_last_called).
The final piece will need to take that sensor value (sensor.assist_last_called). , and compare it to a list of Assist satellite devices (group.assist_satellites) that has an attribute (mic_device) that contains the same name stored in sensor.assist_last_called and reutnr the matching entity name from the list of satellite devices.
I THINK what I need to do is something like:
expand(['group.assist_satellites'])|selectattr('mic_device', 'eq', sensor.assist_last_called)
Does that make sense?
{{ expand(['group.assist_satellites'])|selectattr('mic_device', 'eq', sensor.assist_last_called) |list}}
Tried this but I am getting a 'sensor' is undefined . Not sure how to pull that variable value for the comapre
if the output of sensor.assist_last_called is an enitty_id, get it's state with the states() method
tried this:
{{ expand(['group.assist_satellites'])|selectattr('mic_device', 'eq', states(sensor.assist_last_called)) |list}}
erorr is 'sensor' is undefined. I guess that's not what you mean. The value of sensor.assist_last_called is a text string that returns a value like 'sensor.thinksmart_lr_stt'
surround the entity_id in quotes
quotes
you're treating it as a variable
im too slow
Someday I might get this straight!
So now I am getting back :
[]sensor.thinksmart_lr_stt
Not sure why I'm seeing the empty set (square brackets) but more importantly I'm getting back the value storage in snesnor.assist_last_called OR the value of the mic_device attribute from the group.assist_satellites member entity. What I'm needing is the the group.assist_satellite member entity name. Not sure if I'm making sense but it's not returning what I need.
I suspect that 'mic_device' needs to be 'attributes.mic_device'
Hey @marble jackal, thanks for the response. The double quote was a copy-paste error. Doesn't appear in my actual instance. I've tested this as working in the GUI template helper section, but it doesn't work when added to my configuration.yaml
It always evaluates false in config
[<template TemplateState(<state sensor.assistsat_viewlrthinksmart=; title=, message=, image=, timer=, alarm=, cycle_view=, mode=normal, mic_device=sensor.thinksmart_lr_stt, mediaplayer_device=media_player.thinksmart_lr, view_timeout=20, message_font_size=3vw, friendly_name=AssistSat_ViewLRThinksmart @ 2024-03-18T10:28:36.587060-05:00>)>]sensor.thinksmart_lr_stt
So this is what is returned. I'm only interested in getting the 'sensor.assistsat_viewlrthinksmart' portion. Can you tell me how to grab that?
This is what I'm working with
poste how you have it in you configuration.yaml
{{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='entity_id') | list }}
Thank you both VERY much. I think this is the last piece in the puzzle
I'll push my luck and ask how I might also pull attribute 'mediaplayer_device' ? It's not as easy as modifying that map call to mediaplayer_device
I got it. attributes.mediaplayer_device
how do i get all words from a sentence except the 1st word.
found it split(first_word, 1)[1].strip()
service: browser_mod.navigate
data:
path: /dashboard-tablet/weather
target:
device_id: "{{ device_id('sensor.tabletfullkiosk_browser_path') }}"
Example ^^^^
I'm needing to get a device_id for rather than the entity_id from an altered version of what you gave me:
{{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list }}
Is it easy to modify this to provide device_id? I see the function call but I'm not sure how to format it.
Is that display_device an entity_id?
Sorry. Yes, it is storing an entity_id
Is there a way to "mutex" a trigger-based template sensor? I have one which triggers on (among other things) 2 binary sensors that may change state at "exactly the same time" (they have the same device as source), and somehow it is not able to perform an "increment" action on one of the output sensors. I guess this is due to the async way HA is written, and the trigger on one of the 2 BSs not being done (but being in an await call) while the other starts executing/calculating. But I really need to trigger on both binary sensors.
So can I add a mutex, or does anyone have an idea how to work around this issue?
it's impossible for both entities to change state at exactly the same time
there will be two separate events no mater what
if you want to trigger on both changing to the same state, add both as triggers and use a condition that theyr'e both in the desired state
right, which is why I put it in quotes. But from what I can see the 2 triggers are close enough for the template to trigger quickly after another, resulting in 2 calculating being simultaneously executed.
{{ device_id ("expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list") }}```
I tried this but I got back a bunch more than expected:
[<template TemplateState(<state sensor.assistsat_viewlrthinksmart=; title=, message=, image=, timer=, alarm=, cycle_view=, mode=normal, mic_device=sensor.thinksmart_lr_stt, mediaplayer_device=media_player.thinksmart_lr, display_device=sensor.thinksmart_lr_browser_path, view_timeout=20, message_font_size=3vw, friendly_name=AssistSat_ViewLRThinksmart @ 2024-03-18T13:58:52.049367-05:00>)>]sensor.thinksmart_lr_stt
It throws an error without
this part is wrong:
"expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list"
TypeError: unhashable type: 'list'
then add |first
get rid of quotes and pipe to first after list?
think about what you're doig
🙂 Got it. Thanks!
well, you can use a condition as I described to only proceed if both have changed to the new state
And what if I need to be able to distinguish all 4 different combinations of 2 binary states?
do it in the action: section with a choose
device_id can be used as a filter, so you can also do
{{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | map('device_id') | list | first }}
Thanks, I'll have a try (hadnt looked at choose yet), though while reading through its documentation, I am not sure whether it will solve my problem of the template being calculated twice at the same time.
ok
How to check if an attribute is defined?
Another option: {{ ("My sample sentence").partition(" ")[2]}}
@clear mist I converted your message into a file since it's above 15 lines :+1:
@clear mist #frontend-archived
ah, sorry, wasn't sure where it sat - thanks!
Hi, sure I can clarify: For this device tracker, Home and Away are used to determine if the device is Home or not. I can verify this by watching the state of the device tracker. In the automation UI, I can conditionalize the device state to Home, Away, Unavailable, Unknown, so I know the state of Away is correct. What I'm trying to do is conditionalize an automation so that it only runs if my watch has been away for 30 + mins {{ state_attr('device_tracker.serge_s_apple_watch', 'away') > now() - timedelta(minutes=30) }}. Right now it's welcoming me home even if I take the dog out for 5 mins.
The actual state of a device tracker is home, not_home, or the name of the zone it is in. Home and Away are "friendly" frontend representations of the state.
None of that has anything to do with the state_attr() function you are trying to use because the state is not an attribute.
I understand what you're saying and I was suspicious that I was using state_attr() incorrectly. Do you know which function I'm supposed to use?
Rest value_tempate for Signal Messenger
What are you using as your trigger?
when the watch changes to home
if the watch has been gone 30 mins, then run the automation
{{ now() - trigger.from_state.last_changed >= timedelta(minutes=30)}}
wow, so simple. Thank you so much
Hi! I have a sensor with attributes that I can see on the state card if I expand the Attributes-drawer. However I can't seem to access them with state_attr('sensor.sensorname', 'attributename') - it gives me None. Any hints on what to do?
the GUI will doe cahnges to the attribute (eg capitalize the first letter, change underscores to spaces)
check in devtools > states what the actual attribute key is
Thank you! ⭐
Hi. I have a two way-valve that controls the water source for my vegetables watering. If there is water in the cistern, it is used and otherwise I use water from the tap (I use a pressure based sensor to measure the water level in the cistern). The valve is controlled with a Shelly Uni which provides 2 switches in HA. If I turn
switch A on switch B off -> the valve uses water from the cistern
switch A off switch B on -> the valve uses water from the tap
The switches turn off after 30 seconds automatically.
What I am looking for:
a new (virtual) "Master" switch, that stores its own state and sets the state of A and B when being switched. I was able to create a template sensor, that triggers the actions, but it does not keep its state. Can anybody point me in the right direction?
Nevermind - I think I found it. I can use an input helper for that.
Hey, I would like to calculate the real energy cost of charging my EV because I have a mix of grid energy and solar energy.
I have done that per charging cycle but its not very accurate.
I do (speudo code) consumption_of_charging_cycle * energy_cost / 100 * (100 * grid_energy / (grid_energy + solar_production - grid_feed))
Is there a way to better track this as a template?
why don't you just add this to the energy panel
because this gives me the overall price if my grid.
I want to have a dedicated price for charging the EV only
right, that's an option
(not included my home consumption)
I don't think energy can do that?
individual devices can't do that?
No they don't track costs
thats my problem 😄
Problem is, I want to have it soon ... not to say, today or tomorrow 😂
I mean, my method works, but it just takes the integral values of the energy consumptions.
If there are clouds or the sun goes down its looses accuracy, because it only takes the energys kWh values, whan everything is done. (no real time tracking)
Its even harder for me to do this on a daily bases.
Next step: I want to see the "real" costs on a daily basis and not "per charging cycle".
If I use my approach, then the values are completely messed.
I guess maybe what you want is a sensor that is the instantaneous cost of your charging electricity, and then riemann sum it while the car is charging?
something like this maybe?
This is exactly what I do to determine the costs for individual devices. Depending on the update frequency it can be quite precise