#templates-archived
1 messages · Page 76 of 1
nah i didnt read it.
Better just use commas between the strings (without spaces)
Like a,b,c,d,e,f,g
{{ states('input.text.blah').split(',')[now().weekday()] }}
I'm not quite sure what you are doing, but you probably want to start by looking at https://www.home-assistant.io/docs/configuration/templating/#time and https://docs.python.org/3.8/library/datetime.html#datetime.datetime. now().weekday() will return an integer where 0 is monday and 6 is sunday. now().isoweekday() starts monday at 1 and ends with sunday at 7
Automations. and this section from the docs. https://www.home-assistant.io/docs/configuration/templating/#tofrom-json-examples
thanks!
Hope this is ok, but I'm re-posting my question because it got converted and is difficult to read.
I'm trying to create a script that will set disable manual control of my lights, but not in certain areas based on other conditions. I have a template that returns the values correctly, but when I add it as a part of the script I get a message that says it's not a list that is being returned. I have attempted to follow the formats I've found in the docs and on the forums. Do I need to set a variable and return that? Or is there a cleaner way of doing this?
sequence:
- service: adaptive_lighting.set_manual_control
data:
manual_control: false
entity_id: "{{repeat.item}}"
for_each: >
{% for switch in expand(integration_entities('adaptive_lighting')) if state_attr(switch.entity_id, 'manual_control') != None %}
{% if not is_state_attr(switch.entity_id, 'manual_control', [])%}
{% if switch.entity_id != 'switch.adaptive_lighting_basement' or (is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off')) %}
{{ switch.entity_id }}
{% endif %}
{% endif %}
{% endfor %}```
I'm looking for some advice on how to handle a automation/template I'm hoping to add. I have all of our families calendars integrated into HA, but I don't want to have a big old calendar card on the dashboard because I'm not too fond of the extra stuff we don't need. What I'm wanting to do is run an automation each morning at 00:00 to get the calendar events for the day and put them into a list/array that can be access with a template on the front end. I have the automation part down, I just don't know where to store the data once I have it. I tried a template helper, but it doesn't allow for multiple values -- ideally I'd like a list output, ie: "Mom has 2 events today\n11:00am Pickup Kids\n1:00pm Lunch" and have only that information output on a dashboard/card -- any ideas on the best way to do this?
You can store a list in template attributes
{{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | list }}
you just gotta add the if statement for the guest mode and movie mode
That's pretty close to how I have it working for the general case!
{{ expand(integration_entities('adaptive_lighting'))|
selectattr('attributes.manual_control', 'defined')|
rejectattr('attributes.manual_control', 'eq', [])|
map(attribute='entity_id')|
list}}
But I wasn't able to figure out how to include the conditional logic.
your condition logic is only needed at the whole level
you can reject 'switch.adaptive_lighting_basement'
{% if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') %}
{{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | reject('eq', 'switch.adaptive_lighting_basement') | list }}
{% else %}
[]
{% endif %}
{% if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') %}
{{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | reject('eq', 'switch.adaptive_lighting_basement') | list }}
{% else %}
{{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | list }}
{% endif %}```
Ok so I can do this. I'll try it out. Is there a way to capture the output of {{}} statements?
like:
someList = {{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | list }}
{% if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') %}
{{ someList | reject(conditions) }}
{% endif %}```
{% set remove = ['switch.adaptive_lighting_basement'] if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') else [] %}
{{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | reject('in', remove) | list }}
oh dang that should be perfect, would like to have a true/false template of "xxx has events" and can just throw the rest of the info on the attributes, thank you!
Hi, im trying to check if now are between 2 date and they give me True but supposed to be false {% from 'easy_time.jinja' import month_day %} {{ month_day(9, 11) | as_datetime > now() or now() < month_day(9, 30) | as_datetime }}
Thank you, this feels a lot cleaner. I'm not sure I fully understand how the test being evaluated can also come with conditional logic in that final reject/in. The docs on jinja2/reject don't clearly lay it out. Is that what kwargs is doing?
reject is built in, the test in compares the current list you're 'iterating' to the other list and rejects things that are 'in' the list.
{% from 'easy_time.jinja' import month_day %}
{{ month_day(9, 11) | as_datetime < now() < month_day(9, 30) | as_datetime }}
the difference is the or ?
and you had the > going the wrong way
Oh ok ! thanks !
The in list we are providing has the conditional logic of looking at the booleans as well
{% set remove = ['switch.adaptive_lighting_basement'] if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') else [] %}``` so `remove` is also including the logic. I just didn't know we could do that based on what I had read so far.
Is this something that we can always do? Or are there certain builtins that work with it and others that don't?
an in-line if statement is <pass value> if <test> else <fail value>
so if your test is passing, you'll be rejecting ['switch.adaptive_lighting_basement'] entity_ids
otherwise you don't reject anything
Ok, I think I understand now. we are setting remove to either [with value] or [] at runtime, not passing remove as is written to the function
I think I was confused on exactly when the evaulation was happeing.
is there any good way do access historic data of an entity from a template? i've got all changes recorded, so i could access them via the API and put them into variables somewhere else in an automation, so i have a workaround if needed, but would be nice if i could jsut say "hey give me this entity state from a different date"
no
unfortunate. alright, will have to work my way around that limitation then
so I confess being ashamed to ask, but what unit of measurement (or device_class for that matter) should I give a lightning counting template sensor to show a graph...... I did have a fake unit before ( ↯), and took that out again, but now have the wrong display in the more info
or should I simply state 'strikes' and be done with it, the flash works but seems really too un HA like
tbh, I was surprised we dont have a device_class: count, or number/numeric, but maybe I am overthinking now
So doing a device_entities on the id 6c5687a52bab3a6380682cc904cd7f0b gives me:
['sensor.thinksmart_lr_wake','sensor.thinksmart_lr_stt','sensor.thinksmart_lr_intent','sensor.thinksmart_lr_tts','switch.thinksmart_lr_mic','sensor.thinksmart_lr_mic']
These are the sensors for one of my Stream Assist satellite devices. In a custom sensor device I have a sensor with attribute that matches one of these in the list:
'sensor.assistsat_viewlrthinksmart' attribute 'mic_device: sensor.thinksmart_lr_stt'
Each one of my satellite devices (eg sensor.assistsat_viewlrthinksmart) are in a group called group.viewassistsatellites .
What I'd like to do is have a template that searches that group for any member who's mic_device attribute matches the value from the device_id I receive back from the Assist response and return that member from group.viewassistsatellites
Challenging
state_class: measurement should suffice
{% for sat in expand('group.assist_satellites') %}
{{ sat }}
{% endfor %}```
produces:
```<template TemplateState(<state sensor.assistsat_audio_masterbath=; display_device=, browser_id=, view_timeout=, title=Annoucement, message=Washer is done, message_font_size=4vw, image=, timer=, alarm=, cycle_view=, type=audio_only, mode=normal, mic_device=binary_sensor.assistsatmasterbath_assist_in_progress, mediaplayer_device=media_player.assist_sat_master_bath_2, do_not_disturb=False, friendly_name=AssistSat_Audio_MasterBath @ 2024-05-22T07:33:42.510670-05:00>)>```
and a few more like this
In the loop I'd like to grab the value for mic_device, convert that entity to the device id then do an if statement that compared the devid variable I'm setting in the first line to that value. If true, it would return the 'sat' value name.
I think I can do the logic, but from the output above, how do I pull the mic_device value and the name (eg sensor.assistsat_audio_masterbath)?
{{ sat.entity_id }}
{{ sat.attributes.mic_device }}
{% set devid = "6c5687a52bab3a6380682cc904cd7f0b" %}
{% for sat in expand('group.assist_satellites') %}
{% if device_id(sat.attributes.mic_device) == devid %}
{{ sat.name }}
{% endif %}
{% endfor %}
Thanks for the help. Got it working like this
@willow wing I converted your message into a file since it's above 15 lines :+1:
@willow wing {{ states.climate | selectattr('entity_id', 'search', '_klimaanlage$') | selectattr('state', 'in', ['auto', 'heat', 'cool', 'dry']) | list | count > 0 }}
Hello everyone, I have a '3-way' type fan in my apartment. One is high, other is low. There are no such zigbee modules to handle this so I bought one for a curtain, so 'closing' is High, 'opening' is Low. However the position property of this curtain module in home assistant is messing things up. I do not know how it decides at what position the 'curtain' is, but once it goes to position closed, it stops, or if it arrives ad the fully open position 100, it also stops. However if you are already at position 100, and you start opening, it just keeps running (which I want).
Is there a way to just cut out the position property out of this template completely?
Thank you @marble jackal
you can find SonOff iFan04
unfortunately it is too big, it has to be put into a standard wall socket, or at least behind the button. Can i somehow override in home assistant the 'code' behind the ifan04?
it can put inside ceiling fan top cover and use normal switch for turnon power and control on HASS
you can find 'fan zigbee controller ' on aliexpress.com
I understand but I want to investigate a possible software side solution to this.
inovelli makes a really nice zigbee ceiling fan controller that is smaller than the ifan04
This is not possible. The cover position processing is hard coded. You're using the wrong kind of device for this. Either a relay or a fan controller (as others have suggested) is what you should be using.
how about cover position 'time'. It takes x seconds from position 0 to position 100. I can kind of manipulate it so it will take 30 minutes or so. The fan is an inbuild exhaust fan on the roof so it should not run that much.
I mean when we are talking about an actual curtain opening or something, what if the curtain is very long or short, there must be a way to callibrate this right? I can 'misuse' this function.
I may order one of those fan controllers but i'd love to make it work as is.
Maybe you can do it that way by stepping through the cover position at intervals. Tbh, I have never done it (nor would I want to lol) but for an exhaust fan on the roof? Just get a simple zigbee relay and flip on/off. This seems way over-complicated to me.
It has two neutral lines, one for high and one for low. I wanted to use two regular relay's but they wont fit in the junction box. 🫤
Hmmmm... Do you use both modes often-ish? I have an attic fan with 2 speeds and I just use it with a relay to set it on high to cool off the attic and then switch it off again.
instead of making 10x the same notification i would like to learn to make a more smart way. Is there a way to insert a variable into:
{{ state_attr('sensor.gas_station_euro95_lowest_price_1','brand') }}
say lowest_price_1 needs to be a a variable ranging from 1 to 10
possible?
not sure what you are trying to achieve here
what do you want as output from the template?
al list with all brand attributes of all those gas_station_euro95 sensors?
A script with input fields. So I choose one when calling the script and use that selection as variable inside a sensor
Then I can make a notification with the right sensor attributes
haha that would be too easy. I thought of it but I prefer low and high. The fan is connected to both Bathrooms and Kitchen. I was thinking of if humidity in bathroom gets too high then turn on the fan to prevent mold etc. Perhaps also in the kitchen together with an air quality meter, if too much 'smoke' from cooking is in the air, turn on to high etc.
what do you want to be able to select in those input fields? the brands? or those sensors?
I'm cooking atm. Back after dinner☺️
Thx
When I filter a bunch of devices example {% for plant in states.plant | insert here %} is there someway to filter based on when the last sensor connected to the device was updated?
something like this?
{{ states.sensor|sort(attribute='last_updated')|map(attribute='entity_id')|list|last }}
that gives me the entity_id of the sensor that was updated most recently
Thanks the last_updated seems to be what i need 🙂
Is there someway to filter so that i only get plants that have been updated the last day?
from midnight...
{% for plant in states.plant|sort(attribute='last_updated', reverse=True) | selectattr('last_updated', '>=', today_at()) %}
for last 24 hours...
{% for plant in states.plant|sort(attribute='last_updated', reverse=True) | selectattr('last_updated', '>=', now() - timedelta(days=1)) %}
Thanks that saved me alot of time 🙂
Hi, i have a automation for play a text with alexa_media_player depending on a brightness value of a light. Everything is working as expected. Now i want to convert the Automation into a blueprint. i read the example and could successfully convert it to a working blueprint. i have one thing left that i could not figure out by myself. i have a !input trigger_value witch take the value in %. As example 3%. now the created automation should only do the action when the brightness of the entity is 3%. But the attribute value of brightness is in decimal 8 (3% = 8). i want to add a way of conversion the 3% into decimal and compare it in the conditions with the value of the attribute brightness of the entity. i think i need to convert the !input trigger_value into a template variables first and then multiply with 2.55. after that i need so condition. i found examples in the docs but can't figure it out by myself
post what you have
maybe its just about making an input feeld with entities and and use that in the notification
i want something like:
condition:
( when !input alexa_trigger_device.brightness = !input alexa_trigger_value * 2.55)
condition: template
value_template: >
{{ trigger.to_state.attributes.brightness != trigger_value * 2.55 }}
so add trigger to variables. but why != should it not be ==?
if you wonly want it to fire at the value then ==
thx, i give it a try
@acoustic arch I converted your message into a file since it's above 15 lines :+1:
service: notify.mobile_app_mob_xx
data:
title: Gas
message: Gases
data:
tag: brandstof_prijzen
actions: >
[{%- for i in range(1, 11) %}
{%- set entity_id = 'sensor.gas_station_euro95_lowest_price_' ~ i %}
{%- set lat = state_attr(entity_id, 'latitude') %}
{%- set lon = state_attr(entity_id, 'longitude') %}
{%- set uri = 'https://www.google.com/maps/search/?api=1&query=' ~ lat ~ ',' ~ lon %}
{{ dict(action="URI", title=state_attr(entity_id, 'station_street'), uri=uri) }},
{%- endfor %}]
alias: stuur navigatie naar xx
enabled: true
thank you. and how can i call just one, for example 6 when using a variable as input?
{{state_attr('sensor.gas_station_euro95_lowest_price_[x]','station_street')}}```
like this-ish
but this doesnt work
cool. thats completely new syntax for me
{{state_attr('sensor.gas_station_euro95_lowest_price_' ~ x,'station_street')}}```
works
thx
Thx for your help. it is working now.
variables:
trigger_value: !input alexa_trigger_value
trigger: !input alexa_trigger_device
condition:
- condition: template
value_template: >
{{ trigger.to_state.attributes.brightness == ((trigger_value * 2.55) | round(0)) }}
i needed to add a round(0)
Hi all, i have a problem with coloring the tile card depending on an entities' state.
from documentation / forum posts, I put together this code:
type: tile
entity: sensor.ladenetz_aachen
card_mod:
style: |
.tile {
{% if states(config.entity)== 'Occupied' %}
--tile-color: var(--rgb-red-color);
{% elif states(config.entity) == 'Available' %}
--tile-color: var(--rgb-green-color);
{% else %}
--tile-color: var(--rgb-blue-color);
{% endif %}
}
however, nothing changes with the card_mod added. the tile card still looks blue (like default), but the state is Available.
am I doing something wrong?
are you sure your states are actually Occupied and Available? look in developer tools -> states page for the real untranslated states. @hidden cedar
unfortunately yes:
Available options: Available, Unavailable, Occupied, Unknown
also, if I change the 'else' to e.g. red, the card still stays in default style
{% else %}
--tile-color: var(--rgb-red-color);
{% endif %}
that's why I think it's a frontend problem and doesn't have to do with the exact state name
it's not a frontend problem
you're using card mod, it's a problem with your config in some form.
rule out your selector first, then try other things.
type: tile
entity: sensor.ladenetz_aachen
card_mod:
style: |
.tile {
--tile-color: var(--rgb-red-color);
}
if that doesn't change your card to red, then your selector for the style is wrong, your variable is wrong, or your css tag is wrong
if it does, then your jinja is wrong
@hidden cedar ^
thanks! it doesn't change the color
then it's not your code, it's your selector .tile, the field --tile-color or the variable --rgb-red-color
in the HA core log, no error is shown. In my browser console there is a green 'CARD-MOD 3.4.3 IS INSTALLED'; i would suppose everything is set up correctly.
there is no log what exactly the selectors are doing (e.g. undefined), right?
F12 may show you something, but it's unlikely. If you don't understand selectors, it's best to just search the forums for someone else who's done it already.
thank you for pointing me in the right direction!
that here does it:
style: |
ha-card {
--tile-color: red !important;
}
for some reason, the '!important' is necessary, otherwise the color doesn't change at all. could be that I overlooked it out while experimenting because I didn't think it was so important (literally :D)
thanks again
!important forces that to over-ride all other CSS for any elements which match that class.
https://www.w3schools.com/css/css_important.asp
thanks for the explaination!
@cyan pendant I converted your message into a file since it's above 15 lines :+1:
Even setting the state directly to on doesn't change the state in the UI element: https://fyi.cx/qqgAukh.png
you're sure that's the right sensor? I would have expected it named "Garage Door State" (unless you already renamed it and gave it an icon)
Do they have to be named the same?
The entity id looks correct
I did the trendy thing and asked chatgpt and it gave me the following:
template:
- binary_sensor:
- name: "Garage Door State"
unique_id: "garage_door_state"
state: >
{{ is_state('binary_sensor.garage_door_outer_contact', 'on') }}
and that also doesn't seem to work
It also suggested to reload the YAML, so I went to the dev tools section and reloaded everything under 'YAML configuration reloading'
And the binary sensor for the actual door contact updates correctly: https://fyi.cx/crSTnC6.png
not sure why it's not triggering for you but you're overly complicating that template
template:
- binary_sensor:
- name: garage_door_state
unique_id: garage_door_state
state: "{{ is_state('binary_sensor.garage_door_outer_contact', 'off') }}"
keep in mind, that what you're pasting needs to be put in configuration.yaml, not the UI
if you want to use the UI helpers, use just
{{ is_state('binary_sensor.garage_door_outer_contact', 'off') }}
templates are only the stuff between (and including) the {{ }}
I can't put that here? https://fyi.cx/y3wdBtX.png
no
That works. I've been using HA for a while, but mostly for just simple automations that are configurable within the UI itself. But I wanted to start setting up some more complex stuff, so this is a good starting point. Thank you again!
And thank you too, @lofty mason!
👋🏻 i have finally (using python/appdaemon) managed to parse my battery/solar provider's site to get hourly energy info:
{'date': '2024-05-24T15:00:00', 'index': 22, 'pv_generation': 0.23, 'pv_serving_loads': 0.23, 'battery_serving_loads': 2.55, 'grid_serving_loads': 0.29, 'total_loads': 3.07, 'pv_export_to_grid': 0.0, 'battery_export_to_grid': 0.0, 'total_export': 0.0, 'pv_charging_battery': 0.0, 'grid_charging_battery': 0.0, 'total_battery': 0.0}
what is the best way to store that on an hourly basis in HA? i'm thinking of creating sensors for each, class energy, type measurement, unit kwh. is there a way to only take "one value" each hour? in case the script timing is off?
Though this does beg the question, why are you copying the state of that binary sensor to another binary sensor?
Was just testing it out because I wanted to use it for something else
Triggered template sensor, using a time pattern trigger.
Hello...
I was sent here...
d_sellers1 — Today at 6:54 PM
@umbral ridge Try making one absolute value template entity and see if it is an issue with negative numbers. If that works, then the easy fix might be to wrap the bar-card with a decluttering-card and have it handle the absolute values so you don't have to make a ton of helper entities. I can look into that when I get home from work. templates can help with the helper entity.
Having issues with a bar card showing severity levels....it was suggested to make a helper to do absolute values as a test
Here is the bar card in it's current state...but I have no idea how to make a helper that shows absolute value
`type: custom:bar-card
entities:
- entity: device_tracker.andrew_mug_warmer
name: Andrew's Mug Warmer RSSI
severity: - value: -100
color: '#FF0000' - value: -80
color: '#FFA500' - value: -60
color: '#FFFF00' - value: -40
color: '#00FF00' - value: 0
color: '#0000FF'
attribute: rssi `
Any good examples/urls for me to look at? Thanks!
Do I still set the state in appdaemon, but then the triggered template sensor only updated at a set frequency?
Hi, i want to an display on my dashboard that shows how long its been between the previous and most recent trigger on an device if that makes sense. How would i do that? If its possible
You can set up a template to trigger when your device is triggered to save that time difference: https://community.home-assistant.io/t/how-to-calculate-time-between-the-two-most-recent-state-changes-for-binary-sensor/553945/3
You can also use SQL if you really want: https://www.home-assistant.io/integrations/sql/
{{ 14 * 1.609 | round(1) }} renders to 22.400000000000002.... is there anything sensible i can do about this? 😄
{{ (14 * 1.609) | round(1) }} ?
yeah jinja order of ops surprises me sometimes too
i dont think anything is broken, but just to learn:
{{states('sensor.power_highest_peak_time_tomorrow')}} gives me 2024-05-27T10:00:00+00:00
So hour 10.
but using the same entity in this format i get hour 12. So why does this convert +2, my local?
{{ as_timestamp(states('sensor.power_highest_peak_time_tomorrow'))|timestamp_custom ('%H') }}
as_timestamp has build-in local conversion?
timestamp_custom does use local is default
thx!
https://www.home-assistant.io/docs/configuration/templating/#time
Filter
timestamp_custom(format_string, local=True, default)converts an UNIX timestamp to its string representation based on a custom format, the use of a local timezone is the default. If that fails, returns the default value, or if omitted raises an error. Supports the standard Python time formatting options.
also in the docs!
{{ now() | as_datetime }}```
The first is UTC, The second local (+2)
So how can i template this if NOW is before of after this sensortime (true/false)?
im tempted to just convert them to as_timestamp and do A>B...
but this set me on the wrong foot.
the Fes made me this the other day and works.
{{ now() >= alarm - timedelta(minutes=30) if alarm else false }}```
the sensor is also in UTC time but he is comparing NOW and the sensor straight away
so there is some magic here which accounts for the local conversion.. but where does this happen
Datetimes have the timezone included
And timestamp is the UTC based UNIX timestamp
now() is already a datetime (with timezone data), which can be compared against another datetime
You can compare utc and local tz datetime objects and it works fine.
As long as the object has a tz, the calc will be correct when comparing timezones
Ok thank you both!
how can we select/reject entities from devices with a certain manufacturer? I have this {% set actueel = states.sensor |selectattr('entity_id','search','_actueel') |map(attribute='entity_id')|list%} {{actueel}} but need to reject 'manufacturer','Fibargroup'
could add a label and do {% set actueel = states.sensor |reject('in',label_entities('fibaro')) |selectattr('entity_id','search','_actueel') |map(attribute='entity_id') |list%} but do I have to?
{{ sat.attributes.display_device }}
{% endfor %}```
I have a group of devices that have some attributes that point to other devices. This is the output from the above:
sensor.tabletmaster_browser_path
sensor.thinksmart_lr_browser_path
sensor.tabletfullkiosk_browser_path
I would like to be able to use the above as an automation trigger for when any one of these changes. Is it possible to somehow pull those and determine if any have a state change?
and if the answer is yes, I would also like to know which triggered which would be sat.name I'm assuming
you'd need a template entity
Correct me if I'm wrong, but can I provide a list from a template for entity_id that would replicate this?
platform: state
entity_id:
- sensor.thinksmart_lr_browser_path
- sensor.fire7hd_browser_path
- sensor.tabletmaster_browser_path
Is the template entity you mentioned for determining which one of these changed?
I think this message is more relevant here. Can anyone tell what is wrong here? https://discord.com/channels/330944238910963714/1244645260387160115
What does it says if you put the template in
-> Templates?
My guess is that it created another entity called sensor.other_energy_consumed_2 or similar
no, there is only 1 entity, just checked again to make sure
Result type: string
sensor.
- platform: template sensors:
other_energy_consumed:
friendly_name: "Other Energy Consumed (kWh)" unit_of_measurement: kWh value_template: >
0.0
This template listens for the following state changed events:
• Entity: sensor.rcbo_fridge_freezer_energy_consumed
• Entity: sensor.rcbo_main_energy_consumed
• Entity: sensor.rebo_smarthome_energy_consumed
• Entity: sensor.rcbo_solar_energy
Looks fine, no?
The value shouldn't be 0.0 ofc
But it is
found it
silly issue in the defined values
was referencing the wrong entities 🤦♂️
so it was always going to the else statement
let me try it in the helper
You should switch to the new template format and add a unique_id
And do a config check
in dev tools i'm getting a value of: 385.57, which is fine. but still doesn't work in the helper
I added the unique id as well
Before saying the helper im getting this notification:
Sensor None has device class 'energy', state class 'total_increasing' unit 'kWh' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'sensor: - platform: template unique_id: "ca0f8dd3-1ad4-4ccb-85ba-045a3745c30a" sensors: other_energy_consumed: friendly_name: "Other Energy Consumed (kWh)" unit_of_measurement: kWh value_template: > 385.58' (<class 'str'>)```
And when I enter the helper, in the modal there is this info box on top:
This entity is no longer being provided by the template integration. If the entity is no longer in use, delete it in settings.
ahhh you pasted the yaml in the template UI form
Put just the template in there
not sure I get what you guys mean, sorry quite new to templating
You copied all the YAML into the template box
You know which part is the template?
Did you write that?
got it
works now. Thanks 🙂
coz the template stuff is already handled by the helper UI right.
I was thinking the other day about proposing a warning to the template selector. Would it be enough to just look for the string template: or platform: template in the input? Or would those strings ever be likely to appear in some valid template.
It could do what
-> Services does and parse what you type in the text box
I don't think it's necessary, though
You should know what the template part is. It could explain that there
if you see it from a dev perspective yes 🙂
for 'not so technical people' I feel there is a big gap between what the UI allows you to do to the endless possibilities of templating
if HA manages to bridge that gap, it would be the best thing ever done
It does that by trying to avoid non-technical people from having to write templates
yes, and it improve a lot since it started
In any case, I'm sure that box could be made more friendly for this case
i think a lot of people will have their template yaml in an included YAML file, so template: won't always be in the YAML they share
I would just add some explanatory text there that templates have {{}} or {%%}
would it be possible to somehow check if there is anything not between { and }
That's not necessarily wrong though
what would be a correct jinja template which isn't between curly brackets?
Can't it include extra characters? Like ${{ dollars }}.00
Like if you want the sensor value to be $100.00 from 100.
How can i get a vertical list? my sensor have a attribute that shows like below but my template shows it as x, y, z.
- y
- z```
{{ state_attr('sensor.node_proxmox_containers_running', 'lxc_on_list') |list|join(', ') }}
the top one is a list in yaml
your output is a comma separated string
you could do:
{% for container in state_attr('sensor.node_proxmox_containers_running', 'lxc_on_list') -%}
- {{ container }}
{% endfor -%}
The best way to bridge the gap and give non technical people more possibilities without having complex UI and avoid writing templates, is AI.
I can't image how impressive it could be if AI is added to generate and validate templates
Template triggers need to resolve false then true to trigger. You can’t make that happen with a list of entities. If you want reactions based on state changes in any entity in a group you need a template entity to do that.
Understood. I'm trying to avoid creating an automation per device and was hoping for an easy way to do this.
Could you thell me what the template entity would look like? not necessary to code it but to explain what I am trying to do with it?
You output the last updated or last changed to the state and use that as the trigger. Make an attribute that outputs the last changed entity id
You can add a second attr for state
What happens if two change at the same time? I know that this can/will happen. I understand that there may be milliseconds between them, but is the automation engine quick enough to fire on multiple changes to that template entity I'd create?
You’ll get both separate triggers
They won’t happen on the same microsecond
And if they do, you can choose the first or last
Or make it a list
Okay. Thanks for the tips. I'm not sure my brain will guide my hands to type this correctly so I may put it off for v2.
I really feel like this could be made simpler in some way. It's a common request, and leads people to want to use a state trigger with a template-generated list
Looking at what you said closer. I only need the first two things for my use, last update or changed and also which entity id.
This was part of my original question. How do I check which in the list I have has just changed?
Agreed
Group trigger
Can one of you tell me how to get "last updated or last changed" in template?
{% for sat in expand('group.assist_satellites') %}
{% set browserpath = sat.attributes.display_device %}
{{ browserpath }}
{{ states(browserpath) }}
{% endfor %}
Forgive me. I know this is far from correct. I can't figure out the syntax to get state.last_changed
Literally sat.last_changed
You have a state object, so follow the guidance at the link I posted
Just like you did with the attributes. Note that it's also in that list
Hmm.. So I may be misunderstanding but to recap, I have a group of custom sensor devices (group.assist_satellites). Each one of those has an attribute called 'display_device'. That attribute holds an entity_id of a different device. I am trying to get the last_changed for that device referenced by the group member. Convoluted.
sat.last_changed is actually the template device containing the reference to the device I'm interested in but not the actual device so it may go unchanged while the device I'm interested in chages. That's why I'm setting that variable browserpath . How do I get the last changed on that guy is what I'm after
states[browserpath].last_changed
I get this:
TemplateError: Invalid domain name ''
I can only go on what you've told me
{% set browserpath = 'sensor.aarlo_battery_level_family_room' %}
{{ states[browserpath].last_changed }}
-> 2024-05-26 23:58:26.355315+00:00
Understood. Apologies.
{% for sat in expand('group.assist_satellites') %}
{% set browserpath = sat.attributes.display_device %}
{{ browserpath }}
{% endfor %}
this produces this:
sensor.tabletmaster_browser_path
sensor.thinksmart_lr_browser_path
sensor.tabletfullkiosk_browser_path
{% for sat in expand('group.assist_satellites') %}
{% set browserpath = sat.attributes.display_device %}
{{ browserpath }}
{{ states[browserpath].last_changed }}
{% endfor %}
this produces the error I posted above
Not sure what to tell you. You can test this in
-> Templates
{{ states['sensor.tabletmaster_browser_path'].last_changed }}
just like I did
Alright. So manual entry like that gives me a time. I guess it doesn't like something about the way the attribute return value of that entity is formatted.
display_device: sensor.thinksmart_lr_browser_path
This is how that attribute shows up for one of the group members.
I can copy paste in your example above and it works fine. I cannot use the states[browserpath].last_changed though.
So this works:
{% for sat in expand('group.assist_satellites') %}
{% set browserpath = 'sensor.thinksmart_lr_browser_path' %}
{{ browserpath }}
{{ states[browserpath].last_changed }}
{% endfor %}
Am I doing something wrong in the way I am defining the variable in the version that doesn't work?
{% set browserpath = sat.attributes.display_device %}
I think this assignment is the problem
I'm going up and down with this and I can't figure out why that line breaks things, if it does break things. All seems well but I get that error
no idea
this works fine for me:
{% for sat in expand('group.downstairs_lights') %}
{% set browserpath = sat.entity_id %}
{{ browserpath }}
{{ states[browserpath].last_changed }}
{% endfor %}
my guess is that one of the entities doesn't have that attribute, or it's empty or something
What’s the error?
He has an item in his list that’s an empty string
if you are writing a template that incorporates a problem binary sensor using is_state would you use 'problem' or 'on' or even 'On'? if that makes sense
Depends on your definition of “problem”. Maybe check for unavailable or unknown.
i mean device_class problem
Binary sensor is always on or off in templates
got it
also if using configuration.yaml to write a binary sensor can you use delay_on: true?
oh i mean delay_on: 00:00:00
if thats even correct
Weird. I. Ohhhhhhh. I think I know what's happening now
Does the indentation of delay_on look right here? - binary_sensor: - name: Staff Entrance Light Left On All Night device_class: problem state: > {{ is_state('binary_sensor.staff_entrance_light_might_be_on', 'on') }} delay_on: 00:04:00
also can auto_off be used to automatically turn off at a given time. the doc says it "requires a trigger" but also says "how much time until" it turns off. If it could be triggered by a set time that would be cool
alternatively I could use an automation but it would be more elegent if i could write it into the templates especially since there will be quite a few
Im trying to understand what it means by requires a trigger.
ooo I just realised it makes no sense because it will turn off on its own anyway. Im trying to make an entity that stays on all day if a sensor state is on for 4 hours straight
Confirmed what the problem is. I use the same config for all satellites and some do not have video displays. That's the ones causing the error. So I guess I need to add an if in there to check if the browserpath variable is not null before trying to pull the last_changed. Apologies for the headache
{% for sat in expand('group.assist_satellites') %}
{% if sat.attributes.display_device != '' %}
{{ sat.name }}
{% set browserpath = sat.attributes.display_device %}
{{ browserpath }}
{{ states[browserpath].last_changed }}
{% endif %}
{% endfor %}
So adding in that check is what I needed. So now I can create the template sensor, set state to the last_changed value and store the sat.name as an attribute. I can then create an automation that triggers on the template sensor change and use the satellite name attribute to know which one needs attention.
Thanks for your patience. This should simplify things.
Hey, can i give them sensor an alias?
name: "Restabfall"
details_format: "upcoming"
date_template: '{{value.date.strftime("%d.%m.%Y")}}'
value_template: '{{value.types|join(", ")}}{% if value.daysTo == 0 %} Heute{% elif value.daysTo == 1 %} Morgen{% else %} in {{value.daysTo}} Tagen{% endif %}'
types:
- Restabfall```
alias and friendly_name are not working, i wanna set for example an "ä" in the name
consult the documents for that custom integration. We will have no idea unless we also use that custom integration.
I seek some help regarding the following:
Have a template file for capacity tarif sensors.
These sensors should update every 15 minutes to see if the new quarter consumption is higher than the one before.
what i'm experiencing is that on restart of HA or impelenting a new YAML file the sensors lose their value and are reset to 0.
Code: https://dpaste.org/4gJeU
add availability templates for the first two sensors. Then this line {% if is_number(states('sensor.max_kwartierpiek_dag_in_kw')) %} will actually do something
because currently sensor.max_kwartierpiek_dag_in_kw will either be 0 or it will have the state you expect
oh wait, sorry, I misread (as the names are simliar)
the sensor.elektriciteits_verbruik_15min is a utility meter which is resetted every 15 mins
you should let your trigger based template sensors refer to the current state in the else part, not to 0
Than it will still refer to something wrong, since the value is not numeric according to the if statement
The value of that sensor should always be numeric
as it restores state after restart
So in the else i just let it refer to it's own? I don't see the problem in the original code tho. Does the trigger gets activated on restart of the YAML config?
not sure
@mighty ledge do you know if time_pattern triggers are triggered after a restart?
No idea. I don't believe so.
They aren't
@hard vale can you try this? https://dpaste.org/xwVNL
Invalid config for 'template' at template.yaml, line 10: 'availablity' is an invalid option for 'template', check: sensor->0->availablity
When i set it to it's own value (in the else) the state is 'Unknown'
you pasted something incorrectly.
Indeed type in availability
the updated code is this: https://dpaste.org/YSDgi
still issues, one sensor is now not available (dag)
the other keeps at unknown (Maand)
timepattern one will be unknown until it gets a state
as for the one that's not available, verify the source entities are available.
Did a full restart for YAML
both sensors are now unknown
Wait 2 minutes
/15 minutes means it will only update the state on 0, 15, 30, 45, minute mark
If you want it to update on restart, you need to add that trigger.
@hard vale I converted your message into a file since it's above 15 lines :+1:
Yes already fixed that part. now i adjusted the timeframe so it updated every minute but it seems like it is now not setting the source value in the sensor. The sensor stays at: 'Unknown'. Link to latest code: https://dpaste.org/vUiyd
The original sensor where it should copy values from is updating good and correctly.
icon has the wrong indentation
You should see an error in your logs about the value being non-numerical
and it's because icon has the wrong indentation
Correct, i'm now testing with the template in development tools and it looks like 'this' is undefined.
when i put it to this it is giving me a value
{% set source = states('sensor.kwartierpiek_dag_in_kw') %} {% set current = states('sensor.max_kwartierpiek_dag_in_kw') %} {% if source | is_number and current | is_number %} {% if now().hour == 0 and now().minute < 15 %} {{ source }} {% else %} {{ [ source | float, current | float] | max }} {% endif %} {% else %} {{ current if current | is_number else source }} {% endif %}
This will be undefined in the template editor
this is a local reference to the template sensor itself. Before the first trigger this.state is undefined, and it does not work in the template editor
hmm i guess i found the issue
it has to do with the original sensor. it is giving me an 'uknown' state, even when removing the availability.
Pretty weard since i am able to receive values from this sensor in my faceplate
Hey, I could use some help with following template.
{{ integration_entities('mqtt') | map('device_id') | unique | list }}
I get a list of strings and 1 null value, which I want to remove from the list. Seems trivial, but for the life of.me I can't find out how to do so 😄
| reject("none")
put it between map and unique
you can put it after unique but you'll be using more memory every time it runs
I'm getting a syntax error and I can't see it. Can someone point it to me please: http://pastie.org/p/4aBEAEiDoS0ErD3M76144j
Unexpected } instead of )
you're looking at an old error
it definitely is
because your config is...
{% set value = states('sensor.electricity_current_demand') | int %}
but the error is
{% set value = (states('sensor.electricity_current_demand') | float %}
note the additional (
ahh yeah, I remember removing that one after pasting it
oh and you apparently changed float to int
perfect, thanks @mighty ledge
yep, it was a paste from another card
also, since I have you here, is it normal that I need to repeat the variable statement on every piece of the card that uses it?
{% set value = states('sensor.electricity_current_demand') | int %}
Yep, if they are in separate fields
why can't I set value once and then just use the variable in all the YAML?
ah ok, it's normal behaviour then
got it. Just a bit annoying. Liked it cleaner.
Variables are limited to their scope. Roughly speaking, if you set a variable in icon: then icon_color: will not be able to see it.
You could wrap a card in a custom:configuration-template-card. The custom:button-card is capable of applying variables throughout the card. You could also change the dashboard from Storage mode to YAML mode. You wouldn't be able to use the UI editor and would have to handle all the code manually but then you could use YAML headers and !includes.
How do I replace certain parts of a multi line string?
This for some ungodly reason converts the json data into yaml
If I leave out the template brackets it works fine
Please don't post images of YAML
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Just post the code like that
@zenith comet I converted your message into a file since it's above 15 lines :+1:
great so much more readable 😶
I was able to do what I wanted now because the webhook custom component has an alternaticve field for "jsonObj" which accepts whatever the template is turning the json string into
Guys Need help with something....
` ## Desktop Power Status
- platform: gpio
pin: D7 ## Power detect input pin (readback from Power Led)
name: "${upper_devicename} Desktop Power State"
id: ${devicename}_desktop_power_state
device_class: power
publish_initial_state: true
on_state: ## Binary Sensor Automation
if:
condition:
binary_sensor.is_on: ${devicename}_desktop_power_state
then:
- logger.log: "Desktop Is On!"
else:
- logger.log: "Desktop Is Off!"`
this the Binary Sensor
I want to measure On time In a day
I want to measure On time In a week
I want to measure On time In a year
Total power on time
data should be persistence
how to this any idea..
The big advantage is that it's copy/pastable
Try
json: >
{{
dict(
content=message_content,
embeds=[],
username=username,
attachments=[]
) | to_json
}}
Ask on the ESPHome discord
ESPHome is a system to control your ESP8266/ESP32, with a native integration for Home Assistant.
You can find their documentation here, and get help with ESPHome itself here in the #diy-archived channel (#integrations-archived for the Home Assistant side integration with it). They also have their own Discord server too.
@forest pagoda oh wait, use history stats for the daily sensor. Then use utility meters for weekly, yearly and all time
Hey all, I use this template sensor to check all motion sensors
{{ states | selectattr('attributes.device_class', 'eq', 'motion') | rejectattr('attributes.attribution', 'defined') | rejectattr('entity_id', 'contains', 'global') | selectattr('state', 'eq', 'on') | list | count}}
It occasionally gets stuck on 'on', normally reloading templates resolves it but it is still stuck. Any ideas?
I edited it to update it. All good now. Any ideas on how to optimise it though? Thanks
templates like that can't get stuck on unless it's from a trigger
also keep in mind that it's throttled to at most one update per minute
because you're just using the states object, not a sug broup of entities.
Hmm it certainly seems to be getting stuck on. What do you mean by 'unless from a trigger'?
If this isn't a trigger based template entity, it's not getting stuck on. Its being throttled to at most 1 update per minute.
because you're only using the states object
If you start with states.binary_sensor it will be updating a lot faster. It's throttled to once per second then
How do the template helper works? Does it pick the last output value as the state?
I could be able to use variables and other sensors in there right?
the template you use for the template helper determines the state. It has full access to all template methods, including getting other sensor states and the use of variables.
Hm, so i copied a template i made in the developer options but the helper is "Unavailable"
post the template
Ah nevermind. I picked "date" when i had another formatting 🙂
Can someone help me? I just want a card with my unchecked shoppinglist items. I dont want to delete all the checked items because the checked items are for me a reminder to check if I have them in stock. That whole list however, checked and unchecked itens, is to long. I now that i can use a servicecall to get the unchecked items. but how should I proceed? How do I just get a card with those items? thanks in advance!
Struggling again. I have this:
{% for sat in expand('group.assist_satellites') %}
{{ sat }}
{% endfor %}
which produces this:
<template TemplateState(<state sensor.assistsat_viewlr=; title=Annoucement, message=Dryer is done, image=, timer=, alarm=, cycle_view=, type=view_audio, mode=hold, mic_device=sensor.firehd_7_stt, mediaplayer_device=media_player.tabletfullkiosk, display_device=sensor.tabletfullkiosk_browser_path, browser_id=Tabletfullkiosk, view_timeout=20, message_font_size=4vw, do_not_disturb=False, friendly_name=AssistSat_ViewLR @ 2024-05-26T19:57:02.800807-05:00>)>
I want to actually print the display_device attribute. How do I do that?
{{ sat.attributes.display_device }}
ahh thanks.. was missing the attributes piece
I feel like we've been through that a few times now 🙂
You keep starting with the same thing
Hahah I guess it would be wise to do some sort of free cursus to learn how (python) objects and dicts are structured and can be accessed
I'm having trouble with a command_line switch. For some reason even though the value_template is rendering true, the switch shows as 'off' until I turn it on. What am I doing wrong here?
command_line.yaml
- switch:
name: Media VM
unique_id: media_vm
command_on: "ssh -i /config/ssh/id_rsa_vmhost -o StrictHostKeyChecking=accept-new user@vmhost.33h.lan sudo /usr/bin/virsh start media"
command_off: "ssh -i /config/ssh/id_rsa_vmhost -o StrictHostKeyChecking=accept-new user@vmhost.33h.lan sudo /usr/bin/virsh shutdown media"
value_template: >-
{% if is_state('binary_sensor.media_vm', 'on') %}
true
{% else %}
false
{% endif %}
Dang. Really sorry. It's time I take a vacation
Set command_state to :
Just blank?
No, :
command_state: ":"
Also, your value_template can just be {{ is_state('binary_sensor.media_vm', 'on') }}
That already returns a boolean
Yeah I’ve picked up on that whole troubleshooting today 🙂
I think this is a "templates" thing. I have a 120v car charger hooked up through a shelly current monitoring plug. I'm wanting to calculate roughly how many miles have been added the last charge cycle. I easily made a template that output miles as a function of kWh as reported by the Shelly, but I want this kWh number to reset any time the plug's power goes from 0W to >0W, so I have a persistant number of the last cycle's added range until I plug it in again
I don't appear to be able to manipulate the shelly "energy" sensor directly, and am not sure what triggers it to reset in the first place.
Use a Utility Meter helper if you want a energy entity you can reset at your own chosen interval.
Can I set a utility meter to reset with an automation?
yep, with a service call (utility_meter.reset)
ah, excellent.
@elder moon I converted your message into a file since it's above 15 lines :+1:
well for 1, fix the templates
they are overly verbose
All your time stuff is using really old style code and can be reduced.
hmmm it may be old style, i am pretty sure that i once found a solution to some problem on the HA forums years ago and been replicating from an automation to an automation ever since
im a 'stackoverflow' type of coder 😉
you mean copy/paster
not necessarily copy and paste, you would be surprised how many typos i just found and fixed in the template above
but generally speaking all the presence sensing templates in my home look like that (i have more than one presence sensor in each room, for example in bedrooms there are mmwave and pressure sensors on the bed, to minimize chance of vacuum starting making noise in the middle of someones nap)
{% set entities = [
'binary_sensor.baby_room_bed_presence_pressure',
'binary_sensor.private_office_presence_sensor_occupancy',
'binary_sensor.paulina_bed_occupancy',
'binary_sensor.michal_bed_occupancy',
'binary_sensor.master_bedroom_presence_sensor_presence',
'binary_sensor.baby_room_person_occupancy',
] %}
{{ entities | expand | selectattr('last_updated', '>=', now() - timedelta(minutes=15)) | selectattr('state', 'eq', 'off') | list | length == entities | length }}
might need to flop the >=
if you're loooking for things that haven't changed in over 15 minutes, then yes you do
if you don't like that code, change all your time comparisons
to
now() - states.binary_sensor.michal_bed_occupancy.last_updated >= timedelta(minutes=15)
expand -> expands the entity_ids into state objects so you can access attributes and properties
| selectattr('last_updated', '>=', now() - timedelta(minutes=15)) -> filters the list of entities to only things that have changed in the last 15 minutes
list | length == entities | length puzzles me
| selectattr('state', 'eq', 'off') -> filters the list to only things that are off
| list | length -> gets a count of everything after all the filters are applied
entities | length -> gets a count of everything before the filters are applied
| list | length == entities | length -> checks if the 2 are equal in count
i.e. it simulates x and x and x and x and x and x
aaaahhh i was not parsing it in right order in my head
really smooth templating!
hmm are you sure its "selectattr('last_updated', '>=', now() - timedelta(minutes=15))" not "selectattr('last_updated', '<=', now() - timedelta(minutes=15))"?
see this
your old template is taking the current time, subtracting the last changed, and checking to see if it's greater than 15 minutes.
now() - timedleta(minutes=15) will give us a datetime that's 15 minutes ago
i.e. you probably want <=
i.e. over 15 minutes ago
if that's not what you want, then reverse it
thanks!
sorry one more question, while the above works fine in template editor in developer tools, there's some syntax error when i put it in wait_template: >
i guess that's because we've got actually two templates here one with {{ }} and one with {% %} ?
how can i make it work in wait_template:
post what you're pasting, and post the resulting yaml
`action:
- wait_template: >
{% set entities = [
'binary_sensor.baby_room_bed_presence_pressure',
'binary_sensor.private_office_presence_sensor_occupancy',
'binary_sensor.paulina_bed_occupancy',
'binary_sensor.michal_bed_occupancy',
'binary_sensor.master_bedroom_presence_sensor_presence',
'binary_sensor.baby_room_person_occupancy',
] %}
{{ entities | expand | selectattr('last_updated', '>=', now() - timedelta(minutes=15)) | selectattr('state', 'eq', 'off') | list | length == entities | length }} - service: vacuum.set_fan_speed`
update: got it all working. It's wonderful.
you need to indent the template with 2 spaces
action:
- wait_template: >
{% set entities = [
'binary_sensor.baby_room_bed_presence_pressure',
'binary_sensor.private_office_presence_sensor_occupancy',
'binary_sensor.paulina_bed_occupancy',
'binary_sensor.michal_bed_occupancy',
'binary_sensor.master_bedroom_presence_sensor_presence',
'binary_sensor.baby_room_person_occupancy',
] %}
{{ entities | expand | selectattr('last_updated', '>=', now() - timedelta(minutes=15)) | selectattr('state', 'eq', 'off') | list | length == entities | length }}
- service: vacuum.set_fan_speed
BTW, I guess you want <=
assuming you want every room to be empty for at least 15 minutes before the vauum starts
hello
I have a vacuum that outputs json data as a sensor. Sometimes the json data has the battery level of the vacuum and sometimes it does not. I made a helper template to parse out the battery level:
{%set pos = (state_attr('vacuum.downstairs_vacuum_2','sensor')| base64_decode) | from_json %}
{% if pos.data.elec is defined %}
{{ pos.data.elec }}
{% endif %}
the vacuum battery level is pos.data.elec but sometimes there is no pos.data.elec and the template returns and empty string, which home assistant doesn't like because it is expecting an int for the battery level
Sensor sensor.downstairs_vacuum_battery has device class 'battery', state class 'measurement' unit '%' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: '' ()
What do you want it to be in that case?
the last known value
should I just save the previous state of the sensor? is that circular?
Is this a template sensor?
Use a trigger and reference the current value as 'this.state'
You have to write that YAML manually
If you're trying to do it in the UI
99% of my code is manual YAML and this is the one thing I tried to do in the UI and I was going insane because I couldn't fine the template sensor in my YAML and then remembered that I did it in the UI
anyway
how to I have a template sensor using a trigger?
is it an automation?
*do
when did this become a thing? new to me
Years ago
for your template, this may help:
{% set something = {} %}
{{ something.nothing|default('foo') }}
-> foo
you can use this.state in place of foo
can the default be the previous state of the template sensor that is
I see
but it has to be in yaml not UI
?
I can't use "this" in UI
I guess you don't need a trigger (anymore)
I suggest reading the page and trying it
nice
side question: when I make a template helper, where does home assistant write that down? I was going insane trying to find my template in my yaml files because I forgot I made it in the UI. Where is UI helper data stored?
okay.
if you want to mess with the the YAML, write the YAML yourself
almost everything that HA writes is in .storage
HA is still angry about the sensor
is it 'this.state' or this.state?
{{ pos.data.elec|default(this.state) }}```
it's a variable, not a string
{{ pos.data.elec|default(this.state) }}) renders=4>' for attribute '_attr_native_value' in entity 'None'
that's the only error
is that the full error?
depending on what parts of that structure actually exsist, you may need to do what you did earlier
{% set pos = {'data':{}} %}
{{ pos.data.elec|default('foo') }}
``` -> `foo`
FYI filters are applied left to right, you don't need the parenthesis there
if it's really none, then you may need to use default(this.state, True)
{% set pos = state_attr('vacuum.downstairs_vacuum_2','sensor') | base64_decode | from_json %}
I have removed the extraneous parens
the helper template sensor is unhappy. Renders Unavailable with {%set pos = state_attr('vacuum.downstairs_vacuum_2','sensor')| base64_decode | from_json %} {{ pos.data.elec|default(this.state,True) }}
You should test it in
-> Templates and debug
everything works in the template debug page, but how do I debug the this.state?
{{ pos.data.elec|default('Foo') }}``` outputs Foo or the battery percent as expected on the template debug page
logs are quiet so it seems to be working
not sure what I did wrong in the interim, but thanks for the help!
also it's good to know about the self-referencing
can you post the actual error?
It needs to have a valid value before you can start referencing it and expecting to get something useful
pos.data.elec|default is not immune to issues with the dictionary
{{ pos.data.elec|default(this.state) }}) renders=4>' for attribute '_attr_native_value' in entity 'None'```
that's the whole line in my logs
this is your actual error
'AttributeError: 'NoneType' object has no attribute 'lower''
which is why I was asking for the full error
so pos or data in pos.data are a None object
Or
state_attr('vacuum.downstairs_vacuum_2','sensor')
is returning None
should I do an if state_attr() is not None or something like that?
Now that you know about this.state and default(), you can use them with #templates-archived message
well, if sensor is a real attribute, it should not return None
go to developer tools -> states page and take a screenshot of your vacuum with attributes enabled.
Use Imgur to share the screenshot
The vacuum is integrated using Tuya Local so there could be weirdness in the data polling or something
{{ state_attr('vacuum.downstairs_vacuum_2','sensor') | base64_decode }} return in the template editor?
yah but just capture one of them
{"data":{"cleanArea":16,"cleanTime":740,"elec":69,"elecReal":69,"mode":"sweep","subMode":"smart","timeStamp":1717084361},"infoType":20001}
I think that None error might be a weird one
There were others
{% set pos = state_attr('vacuum.downstairs_vacuum_2','sensor')| base64_decode | from_json %}
{{ pos.data.elec if pos is not none and pos.data is defined and pos.data is not none and pos.data.elec is defined and pos.data.elec is not none else this.state | default(0) }}
that should init at 0, then always maintain a state
that's intense
well, if you don't know the data will always be there, you have to check at each .
pos will always be defined
data will not, you also don't know if data is null or not. So you have to check for both. Same goes for elec
not to bug but why isn't it enough to test for just pos.data.elec if that's all I'm looking for? data is null then there is no elec and I should just use this.state, ya?
This is where the JavaScript ? comes in handy
because you're asking for items in a nested dictionary
if the second nest fails, you get an error
| default only checks the last dictionary item
oh
| default only ensures data has elec nothing else before that
another way to do this with defaults would be....
{{ (pos.data | default({'data': {}})).elec | default(this.state | default(0)) }}
that exceeds my brains obfuscation parser
or
jeebus
{{ pos.get('data', {}).get('elec', this.state | default(0)) }}
what is {} doing?
that's a dictionary
so get data or return empty dict, get elec or return this.state and if the whole thing fails default(0)
or is it just if this.state fails default(0)
parens
isn't the {}.get() part actually calling a Python method?
nd if the
whole thing failsthis.state fails default(0)
anyway, not to further confuse things...
Yes, but it's an extension of the dictionary object in jinja
so it's both jinja and python
I think the Jinja one is slightly different because it's not exactly the same as the python built-in, I could be wrong on that though
I thought it was literally using the Python data structure and its methods, but I don't know for sure
it is
confirmed
hmm wtf is cycler
and joiner
what in the shit is that class
cycler is a counter though... nice
are you guys like black-belt level jinja/python people?
every jinja-related post of yours that I've seen on the forums is a pretty slick piece of code
well, i've been doing this for 8 years, rob somewhere between 4 and 8 years.
this being HA or jinja-fu?
so beginner level, then
right
jeebus
🤏
well, thanks for the help
np
{%- set x = cycler('a','b','c','d') %}
{%- for i in range(10) %}
{{- x.next() }}
{%- endfor %}
{%- for i in range(10) %}
{{- x.next() }}
{%- endfor %}
outputs
abcdabcdabcdabcdabcd
hmm, I'll have to think of a better use case than that 🙂
I cna't think of any
lol
well, right now I can't
you could use it in place of modulo
cycler(True, False, False, False) for every 4th item
e.g.
hey there! I'm trying to work with flightradar data to google sheets. I have it "working" but I have to run the same loop for each piece of data on multiple lines of code to output the values I want. I have a trial and error understanding of templates.
this works:
Craft: " {% set data = state_attr('sensor.flightradar24_current_in_area', 'flights') %}{% for flight in data %}{{ flight.aircraft_model }}{% endfor %}"
Flight Number: " {% set data = state_attr('sensor.flightradar24_current_in_area', 'flights') %}{% for flight in data %}{{ flight.flight_number }}{% endfor %}"
From: " {% set data = state_attr('sensor.flightradar24_current_in_area', 'flights') %}{% for flight in data %}{{ flight.airport_origin_city }}{% endfor %}"
but if there are 2 or more flights, I get a mess 😉
i tried cleaning up the loop, and it "works" in the dev template area
{% set data = state_attr('sensor.flightradar24_current_in_area', 'flights') %}
{% for flight in data %}
Flightid: "{{flight.id}}"
Craft: "{{ flight.aircraft_model }}"
Flight Number: "{{ flight.flight_number }}"
From: "{{ flight.airport_origin_city }}"
Altitude: "{{ flight.altitude }}"
{% endfor %}
BUT - I can't seem to jam this into the Data field of the automation
in fact, it'll often not even show the "Save" icon
I think I'm mentally mapping templates incorrectly
am i asking in the right place, and do I make any sense? 😉 Thanks!
hmm, can't paste in a screen grab...
you can't template yaml fields
you can output a dictionary to a yaml field, but you can't template something like this:
something: >
{% for i in range(8) %}
- x: {{ a }}
y: {{ b }}
{% endfor %}
you can only template something: if you output a list of dictionaries and something: has to support it.
k, so the "data" box only wants yaml...
I don't knwo what you mean by databox
on the automation page, in the Then Do secion, there's a data field that I can put yaml into, but not templates... unless they are inside the Label: "{{ value }}"?
You can't template those fields in that box
thanks for helping! I'm sorry i'm clueless 😉
you can if you output a dictionary
ok, will google dictionary and yaml
but a for loop would output a list
not a dictionary
so, i'll need more info from you
googling probably won't help because this is not normal
heh
I'm pretty yaml ignorant. is my approach that works above the "normal" way of jamming templates into yaml, or is what I'm doing clearly a dictionary thing I have to go understand?
everything you're saying is something you need to explain more
you keep saying data box, but there's 09287402850382094385 data boxes in HA
so, all I can say is what I've been saying
right, so you have to output a dictionary as your template result
i'm very happy to go watch videos or rerad blogs if you need me to get some basic background before bugging the discord!
you can't output yaml
k
there are no videos for this
this is high level templating
there are no docs for this
gotcha
i'm old too, so "dictionary" is the same as a perl hash? 😉 key-value pair set
yes
but you're outputting a list of dictionaries at the moment
well, you're attempting to output a list of dictionaries
data needs to be a dictionary
so you need to decide what to do when you have more than 1 flight.
i wish they'd limit to one flight at a time, but that proposal was rejected 😉
right- was hoping to write a line per flightid in the google sheet
I'm also messing with a display for the flight going over
this also uses the messy, loop per line of text approach
i'll go learn about dictionaries - thanks!
Is it possible to create a template sensor that can retain state over restarts so you can cover up for a binary sensor turning to unknown?
I think if it has a trigger
I think I mentioned that earlier 🙂
That + unique_id
From the docs:
The state, including attributes, of trigger-based sensors and binary sensors is restored when Home Assistant is restarted. The state of other trigger-based template entities is not restored.
Otherwise, you'd have to write to some other helper in the action and read it in the state
Pretty convoluted
Oh, I just read that as "you need to trigger an update"
Right
Guys, remind me what functionality the semicolon has in the template sentence syntax
nothing?
It performs a certain function, but I have forgotten which one. For example https://github.com/home-assistant/intents/pull/2201/files#diff-db001a0af745f39f18ad1244e5e3dd7cf7f01e82b4f512e8b9cc49bffdedb716R27
Definitely not templates
(A; B; C) = A B C or A C B or B A C or B C A or C A B or C B A
but indeed, this is not related to #templates-archived but it's more a #devs_voice-archived question
does ... | max(100) .... work in jinja in home assistant?
don't have an instance i can test it on rn
it does something, but probably not what you think
the first parameter of the max filter is a boolean to set case_senstive to False (=default) or True
100 is considered True, so this will set case_sensitive=true
Is there a way to get the current notifications in ha via template? I'm referring to the side bar "notifications"
Hi all, Is there a way to get the "time_since" filter to only output in days?
or, might there be another way to get nr of days that I'm not yet aware of 😄
{{ (now() - datetime_you_care_about).days }}
aaawesome! Much appreciated!
hmmm okay, is there any way to make it so that it goes to 100 and not above? so let's say i do 10* 12 the template output will be 100? or would i have to do some if statement shenanigans
[stuff, 100] | min
That's not a parameter of the filter, that's the input
{{ [100, value] | min }}
Or, when used as function
{{ min([100, value]) }}
But from the snippet you shared, you were using it as filter
(should be min not max if you want to cap it at 100 @marble jackal)
Ah right, he asked about max in his initial question
But indeed, to cap it at a maximum value, you need to use min
with value being?
i did this for now but might change it if u fully understand this lol
{% if omvormer_kW * 10 <= 100 %}
{{ name * 10 }}
{% else %}
100
{% endif %}
value being whatever your value is, so name * 10 in this case
Guys, can somebody give me a quick hand, I'm sure this has been solved before but I fail finding the solution.
I want to create a tempalte helper that substracts the value of one sensor from another, and track the result in a sensor. I have my total power consumption from directly from my smartmeter, and I have the sum of all my consumption trackers in a helper sensor. I want to track how much energy I consume that I am not aware of.
Ah, sometimes it just helps posting in here without anybody replying 🙈, I guess this should do the trick:
{{ states('sensor.smart_meter_active_power_plus')|float(2) + states('sensor.solar_power_total')|float(2) - states('sensor.smart_meter_active_power_minus')|float(2) - states('sensor.total_power_consumption')|float(2) }}
I hope I am not wrong about the formula, trying to take solar production into account. If anybody spots a problem, please let me know! 🙏
alright I already found a problem. If one entity goes unavailable I suddenly have a huge negative untracked value. How can I skip the value if one entity is unavailable?
Your template can have an availability_template, to go unavailable if either of those sensors go unavailable. Though if either of those sensors ever reset their consumption you're going to have a bad time as well.
can i create a template sensor with multiple attributes, all of which are getting a statistics?
Do you mean LTS?
yes
i would like to calculate an output factor for my solar panels but dont want to create a sensor for each
I'm pretty sure that LTS only include the state. Lots of attributes would make no sense as statistics
And you have to add attributes to enable LTS in the first place
And it applies to the state
hm i see, guess if thats the case i may use this as an excuse to not care about it and try doing nodered stuff for it
There's not much love for using attributes like that
I am trying to format a template sensor with a trigger, but i am not sure i understand the formatting
Why are you not sure?
so i have been using yaml files for sensors, so a normal template sensor would look like this
- platform: template sensors: ev_total_power: friendly_name: Total EV Charger Draw unit_of_measurement: "kW" value_template: >- {{ (float(states.sensor.tesla_east_ev_power.state) + float(states.sensor.tesla_west_ev_power.state)) | round(1) }}
i don't know how to start the sensor with a trigger, all the things i have tried have thrown errors
this is what i am trying to figure out
`template:
- trigger:
- platform: state
entity_id: sensor.east_ev_charger_daily
not_to:- unavailable
- unknown
sensor:
- name: 'East EV Charger Historical Max'
unit_of_measurement: 'kWh'
device_class: energy
state: >
{% set t_new = states('sensor.east_ev_charger_daily') | float(-99) %}
{{ [t_new, this.state | float(-99)] | max if trigger.platform != 'state' else t_new }}
attributes:
power_updated: "{{ now() | as_local }}" `
- platform: state
in a sensor.yaml file
it has to go there? Wasn't the whole point years ago to not have the config.yaml completely filled with stuff?
ok, that is different than a template sensor, that resides with sensors. i would just include it like anything else in the configuration.yaml?
They're both template sensors. You were using the legacy format and now you're using the modern format
Yes, same way
got it, so is there any value to migrating the old sensors? i have like 500
If you want the features of the new format
unique_id, for instance
It's not hard to do
You don't need to. Unlikely that the old format will go away
i am largely out of the modern development, what is the benefit of unique_id? sorry for the dumb questions
Let's you configure parts of the sensor in the UI, like the name
I suggest reading the docs that you clearly have to see the new stuff
ah ok, thats why template sensors show up weird that way
Since you're already using one, the trigger
I got it, is there a way to auto generate a unique_id like if you leave the field blank on the first startup or some other way?
No, but VSCode, for instance, has a UUID generator extension
HA never modifies your files
ok, i use VS code, so ill check that out.
unique_id is actually supported in the legacy format as well
state_class and of course triggers and actions are only supported in the modern format
How do I aggregate a daily sensor for a whole year? I have a sensor that gives me the daily produced energy from my solar panels and resets every day. I want to see how much energy was produced in total and then calculate how much money was saved
use a utility meter on that sensor
that's exactly what I need, thanks!
I'm having a bit of trouble with date/time in a template. I am trying to compare today's date to the date of the next NY Rangers game by using:
{{ now().date() | string == state_attr('sensor.team_tracker_rangers', 'date')[0:10] }}
This was working fine for a bit
When I go to look at the sensor, the attribute displays the date/time in my local time zone which is currently UTC-4 but when I use
{{ state_attr('sensor.team_tracker_rangers', 'date') }}
it returns the date/time in UTC. So when a game is supposed to start at 8PM local time, it shows tomorrow's date because four hours after 8PM is midnight.
So all this is to say that when it calls
now().date() it returns 2024-06-01
but when it calls
state_attr('sensor.team_tracker_rangers', 'date')[0:10] it returns 2024-06-02
because of the time zone difference.
How do I have it spit out the date/time in my local time instead of UTC?
What does state_attr('sensor.team_tracker_rangers', 'date') show in the template editor?
Right now it returns 2024-06-02T00:00Z
the next game is today at 20:00
If I look at it in the GUI, the Date attribute is displayed as June 1, 2024 at 8:00:00 PM
You can try this:
{{ (state_attr('sensor.team_tracker_rangers', 'date') | as_datetime | as_local).date() == today_at().date()}}
Nice! That appears to be working. It also fixes my bootleg way of pulling only the date to compare the strings. Thanks for the help
Hey all, is there a way I can exclude lights with a label id of don_t_count_as_light from this template? Thank you
{{ lights | count | default() }}```
{{
states.light
| selectattr('entity_id', 'in', label_entities('don_t_count_as_light'))
| rejectattr("attributes.entity_id", "defined")
| selectattr("state", "eq", "on")
| list
| count
}}
Thank you - however I think this includes lights with that label rather than excludes
states.light
| rejectattr('entity_id', 'in', label_entities('don_t_count_as_light'))
| rejectattr("attributes.entity_id", "defined")
| selectattr("state", "eq", "off")
| list
| count
}}```
This does the trick I think 😄 thanks a lot!
Yeah, that was to test you 😜
if:
- condition: template
value_template: |-
{% if target_display_device %}
true
{% else %}
false
{% endif %}
I am setting the variable target_display_device in part of my automation before this block. I want to test if this device has a value. I thought this would do it but I am getting a return as false (I think) as the code is not executing in the then portion. I want to know that this variable is not null/empty/none
for context this is how I am setting the variables:
variables:
target_satellite_device: |-
{% for sat in expand('group.assist_satellites') %}
{% if device_id(sat.attributes.mic_device) == trigger.device_id %}
{{ sat.name }}
{% endif %}
{% endfor %}
target_display_device: "{{ device_id (state_attr(target_satellite_device, 'display_device')) }}"
I do know that target_display_device is being set correctly as without the condition the service call does route to the correct device
I guess it only takes me posting to find the right answer. This appears to work:
{% if target_display_device is defined %}
That will always return true because it will always be defined
Put this in the template editor:
{% set target_display_device = None %}
{{ target_display_device is defined }}
Gotcha. Can you tell me what I should do instead?
It should equal None if that attribute or sensor or device isn’t found, so just test for != None
that didn't work. I will rethink this
What did it do that you didn’t want it to do?
I'm working on a project called View Assist. This ties a bunch of voice satellites together. Some of these devices have displays and some do not. I am trying to check if a device is configured to have a display and if it does it should then show something on the screen. If it doesn't it should just skip the display service call. I use the variable definition above on my automations and I thought I would be smart in checking if the target_display_device had a value in it and use that in the if statement
Looks like I am having problems setting those variables. They are all none. Back to the drawing board.
- name: "NAS Status"
icon: phu:nas-v2
delay_on:
seconds: 10
delay_off:
seconds: 10
state: "{{ states('sensor.server_smartplug_power')| float(0) >= 30 }}"```
whats the best way to make the on status stay on when HA is restarting?
Got it sorted and this was what I ended up needing. Thank you
Trigger based template sensor will retain its state across restarts
You can use a state trigger with
not_to:
- "unavailable"
- "unknown"
See the last example in the first section: https://www.home-assistant.io/docs/automation/trigger/#state-trigger
I'm trying to pull the media players located in the room in which I am located, ( To start rain sounds where I'm sleeping)
I have a sensor called 'sensor.where_is_maxi_sleeping' whose current value is "bedroom"
But when using
select('match', '^media_player.') | select('is_state','off') | unique | list }}```
I do not get the media players in the area called bedroom.
Any idea if this is supposed to work?
{{ [states('sensor.where_is_maxi_sleeping') | capitalize ] | map('area_entities') | sum(start=[]) |
select('match', '^media_player.') | select('is_state','off') | unique | list }}
This worked!
I was missing square brackets
Update on that code
How can I also check that they are unmuted
sum(start=[]) | select('match', '^media_player.universal') | selectattr('attributes.is_volume_muted', 'eq', false) |
select('is_state','playing') | unique | list }}```
Does not work and returns: UndefinedError: 'str object' has no attribute 'attributes'
right, you're just working on a list of entity_ids
How ca n I pull the corresponding objects?
you need to add |expand
At which position? 🙂
or, you can just use is_state_attr() there
Got more info on this?
yes, there's a whole page
I think it works as a test
indeed it does. example:
{{ area_entities('Downstairs Hallway')|select('search', 'aarlo')|select('is_state_attr', 'device_brand', 'Arlo')|select('is_state', 'armed_home')|list }}
Let me try that!
{{ area_entities('Office')|select('search', 'media_player')|select('is_state_attr', 'is_volume_muted', false)|select('is_state', 'playing')|list }}
worked! Thanks!
'media_player.universal')|select('is_state_attr', 'is_volume_muted',
false)|select('is_state', 'playing')|list }}``` Doesn't seem to work tho
Executed: June 1, 2024 at 9:05:51 PM
Result:
params:
domain: media_player
service: volume_up
service_data: {}
target:
entity_id: []
running_script: false
service: media_player.volume_up
metadata: {}
data: {}
target:
entity_id: >-
{{ area_entities(trigger.entity_id)|select('search',
'media_player.universal')|select('is_state_attr', 'is_volume_muted',
false)|select('is_state', 'playing')|list }
you appear to be passing an entity_id into area_entities()
Derp.. I need to use the area_id thing
Should this work?
'media_player.universal')|select('is_state_attr', 'is_volume_muted',
false)|select('is_state', 'playing')| list }}
Or I can't concatenate functions?
Worked, nnoice
not_to?
Yes, you want your template sensor to get updated on every state change except for when the sensor becomes unavailable or unknown which is what happens on restart. So your template sensor will update just like it does today except it won’t update on restart. Which is exactly what you asked for.
I mean - I didn't think not_to was a thing haha
in reference to the latest beta, i am struggling a bit to understand variables and wonder if someone could help
Hey, can someone tell me why i get here no values?
https://ibb.co/Pj0CVqq
@willow wing I converted your message into a file since it's above 15 lines :+1:
Did it already trigger?
@marble jackal i think this does when i reboot?
No, you have an hourly trigger, it triggers every hour on the hour
It should have triggered 28 minutes ago
ah okay, states are there, thank you
i have try template
{{ now() == today_at('08:01')}}
But it alway false
i have changed minutes
It's accurate to microsecronds...
Thanks
What are you trying to do with the comparison?
i want to use it as trigger to given time
Will a Time trigger not work for your use? Generally, when using now() in a template trigger it is best to use >= instead of == so you avoid the issue you showed earlier.
{{ now() >= today_at('08:01')}}
Thanks
I changed to
{{((now().hour == 6) and (now().minute == 30) and now().day == 1)}}
For some reason this template sensor keeps dropping to 0, but the source sensor doesn't. I presume it has something to do with the "availability:"... Is there a way to tell it to use the last sane value, instead of dropping to 0 when the availability renders false?
template.yaml
sensor:
- name: "Grid Consumption"
unique_id: grid_consumption
unit_of_measurement: "W"
device_class: power
availability: "{{ is_number(states('sensor.solaredge_m1_ac_power_2')) }}"
state: >-
{% set grid = states('sensor.solaredge_m1_ac_power_2') | float %}
{{ ((grid * -1) if (grid < 0) else 0) | round(0) }}
if the availablity renders false the sensor will report unavailable, not 0
that's the whole idea of the availability parameter
the sensor drops to 0 because you tell it to do that when the value is positive
BTW, you could also do
sensor:
- name: "Grid Consumption"
unique_id: grid_consumption
unit_of_measurement: "W"
device_class: power
availability: "{{ 'sensor.solaredge_m1_ac_power_2' | has_value }}"
state: "{{ [0, states('sensor.solaredge_m1_ac_power_2') | round(0)] | min | abs }}"
Hello,
I'm trying to make a template sensor that will calculate the rainfall/day so I know if I deactivate the irrigation system for the next day.
I've used the OpenWeatherMap rain value (mm/h), created an aritmetic mean of that and then multiply by 24.
The problem is that I'm not entirely sure what the result represents. My best guess is rolling average 24h of rainfall. Am I right?
Thanks.
Actually....I don't know what is the period the aritmetic mean is applied on 🫤
{% set o1 = states('sensor.average_precipitation_rate')|float %}
{%set o2 = 24 %}
{{ (o1 * o2) | round(3) }}
And sensor.average_precipitation_rate is median of openweathermap rain
what's creating sensor.average_precipitation_rate
use open weather map and that integration doesn't provide that
That sensor.average.... is a median of this : sensor.openweathermap_rain
Median is statiscally something different than an average
I've tried before aritmetic mean, but I reached 0mm of rain today so I realized that is no good either.
I've tried to plot the sensor.openweathermap_rain using statistical graph and that works perfectly. I just need to multiply it with 24 to get the value o want:
chart_type: bar
period: day
type: statistics-graph
entities:
- sensor.openweathermap_rain
stat_types: - mean
title: Daily rainfall
days_to_show: 7
Do you want rainfall in the past or the future?
In the past 24h
well that would be from midnight not past 24 hours
the stats integration can sum the past 24 hours of rainfall
or what petro is propossing indeed if you want 24h relative from now
it's a rolling 24 hours and it would be a sum
if you go average, it's going to be low because rainfall will likely be 0 at most times.
where as sum will add all the values together, then you can use a simple threshold
You mean history stats?
No, statistics
You can also just buy a rain sensor
which is 100% accurate
they are cheap(ish)
I got mine for like $70 but it was part of rainbirds setup. If you go with a non-proprietary sensor, they can be very cheap
I'm not interested in being 100% accurate. I just need to know if it's raining when the electric pump is starting (depending on raining direction there might be water on it)
And if the soil is too wet already, I don't want to add even more water.
right, you should really get a rain sensor then
they essentially have "soil" in them and the sensor reads that
If you need to do something that involves rain and electricity, you'll want a rain sensor (as petro said). Weather integrations that rely on the internet aren't always updated and there's a chance of it not even connecting sometimes. This is something I would not trust to the cloud.
Understood, thanks. I'll look into what sensor options do I have.
If you want to go the cheap DIY route: https://community.home-assistant.io/t/diy-zigbee-rain-gauge/255379
And to add to this, weather providers do machine learning estimates based on a certain grid size which can be multiple kilometers wide. So very local weather can be wrongly represented in that data
Any recommendations then of a rain sensor that can be integrated into Home assistant? 😁
It might be cheaper, but if I count the number of hours spent on that....to be honest I saw that DIY before posting here, but I thought it's too complicated.
Ah, gotcha. I have a Lacrosse View (which is cloud polling), but I think the Ecowitt line is all local.
Can't get this formatted correctly. If anyone can help.
Days until harvest: {{ ((as_timestamp(states('input_datetime.petunias')) + states('input_number.petunias') * 86400) - as_timestamp(now)) }}
The date Planted works.
I'm creating scene scripts using the scene services here :https://www.home-assistant.io/integrations/scene/#creating-scenes-on-the-fly, I need to template the entity name in the data, how would I do that? I can't seem to figure out the syntax.
data:
entities:
light.tv_back_light:
How would I make light.tv_back_light: a template (script field) like {{entity}}
Date Planted: {{ states('input_datetime.petunias').date() }}
Days until harvest: {{ (states('input_datetime.petunias') | as_datetime | as_local + timedelta(days=states('input_number.petunias') | int) - now()).days }}
Hi, guys I have a sensor outputting a time and date, how can I get just the time but, four hours earlier?
{{ states('sensor.ender_5_plus_print_eta') | as_datetime - timedelta(hours=4) }}
why "4 hours earlier"?
datetime! It's reporting the job will be finished at 1600 but when I check the device directly it's actually finishing at 1200
so, I'm not sure if it's a timezone issue ...
it's reporting your time in UTC
that is the correct time
I figured it was a timezone, but I thought -4 would be easier than figuring out how to change the tz?
No, you don't want to change it
you want to keep it the way it is, where are you trying ot use the time?
{{ states('sensor.ender_5_plus_print_eta') | as_datetime | as_local }}
damn, you make it look so easy
the beauty of experience
works perfectly, thanks petro!
Hi, any idea how to convert all options of a input_select into a yaml list with a yaml template?
input_select:
- Options:
- 1
- 2
- 3
into a yaml list
`- yaml_lst:
- 1
- 2
- 3`
aha, ok. thx
@inner mesa
I've tried:
`action:
- service: vacuum.send_command
target:
entity_id: vacuum.adoracion
data:
params:
- segments:
- {{ state_attr('input_select.reinigung_segmente', 'options') }}
repeat: 1
command: app_segment_clean`
But it replaces the yaml templete with a null:
`action:
- service: vacuum.send_command
target:
entity_id: vacuum.adoracion
data:
params:
- segments:
- null
repeat: 1
command: app_segment_clean`
What I'm doing wrong?
You likely need to template the entire value for params
Just segments
But you maybe right if the segments needs to be a string
Which some vacuums require
If I run it manually the segments are integers'
service: vacuum.send_command target: entity_id: vacuum.adoracion data: params: - segments: - 17 repeat: 1 command: app_segment_clean
That is the way I'm currently using it. But this approach only works for a fix set of segments. Which is why I want to replace it by a input_select, which allows me to add and remove options.
params:
- segments: "{{ state_attr('input_select.reinigung_segmente', 'options') }}"
repeat: 1
Almost there. It seams that it does not accept segments of strings. So I need to convert them to integers.
| map('int') | list
wohooo, its working. Thanks
@stoic sable It's an unfortunate side-effect of the python value coersion of templates.
Your template evaluates to 123,456.789 which is then re-parsed through python as 123, 456.789 or [123, 456.789].
The only way around it is to add something to the string which cannot be parsed as a number.
E.g. {{ "{:,} km".format(123456.789) }}
Tyvm for the clear explanation!!
Context for those playing along at home: <#general-archived message>
There is no filter or anything to bypass the coercion? It sounds like templates take the string and aggressively “try” to convert it into various types 🤷♂️ yeah pretty brutal. Is this a jinja2 thing or HA?
It's a HA thing, and there's nothing that can be done as far as I know.
It's actually very helpful for things like data in service calls but every now and then there is a problem like yours.
There are ways to bypass it, where are you using the template?
Primary value of a template card… I just want to display the number. I’ll space-prefix if I have to…
Is there any reason you’re not letting the ui format it for you?
And what do you mean “template card”?
Yeah I’ve noticed all the problems I expected, but didn’t have along the way - this explains why it “just worked”!
It always wants to add ".0" on the end 🙂
Sorry - paraphrasing. More precisely:
primary: {}```
I was also surprised I had no access to type() or str() functions within a template - is there a reason why not (?)
The mushroom template card ignores the display_precision. The generic mushroom card does apply it
Yes that’s where I’m going bas, to me it seems like you shouldn’t be using a template at all. Just a regular card that formats things for you in combination with a template sensor if needed
Yeah seems also more confient to me, let HA handle the precision globally for an entity
So why do you need to use the template card?
You do, but after the template outputs a value, HA tries to apply a type to the returned value.
So it doesn't matter what you do in the template, the resolver will apply a type after and you have no control over it.
Anyways, if you post your full mushroom template, I can offer a path of less resistance that will potentially do what you want.
Hey guys I've done some research but I can't seem to find an answer I have two power readings one input into an inverter and one output I'm trying to make a sensor value for efficiency as a percentage loss IE 100w input 80w output = 20% efficiency loss any ideas how I would go about this?
So the template always returns a string, and the resolver tries to do a decent job at typing it? I think the only odd part was that "1,000" was interpreted the same as "[1,000]" - any idea what the motivation was to infer the former as a list? Full template:
cards:
- type: custom:mushroom-template-card
primary: '{{ states("number.variables_rainwater_tank_max_storage_volume") }}'
OK - I've tried a custom:mushroom-entity-card (I can't control precision there either) - I don't want to use a number card because I don't want the slider; just a simple text number 🙂
Is there another more generic one you'd recommend?
The entity card, the precision is controlled by the entity in HA.
simply click on the entity, and set the precision
I don't see a way to set the precision on the entity (?)
if there isn't make a template sensor from the number
I just noticed that the entity in question is a volume, why is it a number entity?
it should be a sensor
anyways, to make a sensor from it, make a template helper using {{ states("number.variables_rainwater_tank_max_storage_volume") }} . Set the device_class or display as to volume and set your unit of measurement to the proper units. Then you can modify the precision there and use that in your UI.
As a sidebar, I highly doubt that the number entity is created by a normal integration, I'd reach out to the integration owner and ask why this isn't a sensor to begin with.
It's an integration with a lighting control system - it maps a variable in it, to a number in HA. I can change the integration no problem - what is a 'number' meant to be used for; is it for unitless values whereas this one (with some real world meaning, units etc.) maps more to a 'sensor'; even if it is just a variable?