#templates-archived
1 messages · Page 30 of 1
Hi dude, thanks for that, I tried to avoid loops but without looping how can you reference the script to light link ?
@tepid onyx Easiest would be to give the scripts the same object_id as the lights and add | map('replace', 'light.', 'script.')
But you could also create a dict to map the light to the right script
Hello you all
Maybe someone can help me with a small task. I want to create a sensor, that - depending on a condition - shows the values of one sensor or another. How can I do that?
to be concrete - I have two electric cars with two "State of charge" values. In my "custom:power-distribution-card" I can add a sensor for my car, so I see the State of Charge of my car, when the car is charging. Here I have to decide which sensor of which car I use. So I want to create a new sensor that always shows the state of charge of the car, that is currently charging. Like:
If car1 is currently charging, show SoC of car1, if car2 is currently charging, show SoC of car2. If no car is charing, show SoC of car that was charging last.
I think I can do that with a template, however i have no idea how to actually do it 😦
@thorny snow {{ [ 'sensor.car1', 'sensor.car2'] | map('states') | map('float', default=0) | max }}
trying to pass a variable to a script. Number works. But string not yet.
data:
set_brightness: "dim"```
fighting with the quotes. any suggestions?
value_template: "{{set_brightness == \"dim\"}}"```
??
Just do
condition: template
value_template: "{{ set_brightness == 'dim' }}"
ill try it out
got it!
also forgot to disable another condition in the script🤦🏼♂️
thank you
hi all, maybe someone knows if it's possible to make a condition from the current dashboard url or from switch dashboard your in.
Something similar to this
{% set dash = dashboard().current %}
{% if dash = bedroom %}
Your viewing the bedroom
{% else %}
Your viewing something else
{% endif %}
Yer...but that would mean renaming scripts and then updating $x hundred automations etc 😀 cheers though
Checkout #frontend-archived
hey! I have created a sensor that contains the (estimated) number of seconds until my heatpump's reservoir will be heated again. However showing a countdown in seconds for something that is often many hours in the future is not practical (although it is practical so have it as a number to perform calculations in automations). Is there a way of displaying that sensor as a sensibly formatted countdown while still have it be a time and not a string?
Do you want it to display "hh:mm:ss" updated per second? Or just something fuzzy like "in 4 hours"?
I don't know that having a sensor with "seconds remaining" is a great idea, I don't think you really need or want to have a state change every second, that sounds like a lot of slamming on your database. Better to just set the state to the time it will be done, and then you can calculate what you need based off that, or use the frontend to display the seconds remaining without forcing tons of state updates.
I am aware that working with datetimes in automations can occasionally be a bit confusing and daunting, but once you learn how it works and can get past that I think you'll find you don't really need a state with seconds remaining.
I was playing with the idea of a timedelta
which does seem to work
{% set secondsSinceLastChanged = as_timestamp(now()) - as_timestamp(states.sensor.temperatura_actual_acs.last_changed) %}
{{timedelta(seconds = ((states('sensor.temperatura_actual_acs') | int - (states('number.temperatura_objetivo_acs') | int - 5.5)) / 0.3333 * 3600 - secondsSinceLastChanged) | int)}}
however I see your point. In reality instead of the remaining time, I could have an "estimated hour"
same thing, much easier on the database because it would update far less often
The two options I can think of are if you have a timer entity, you can set the timer with the number of seconds until done when you calculate it, and then the frontend will show the time remaining in hh:mm:ss format.
Alternatively, if you have a sensor with the finishing time as the state, and set it to device_class timestamp, the frontend will display that sensor as a relative time like "In 33 minutes".
^ that sounds like the best idea
@lofty mason but how do I generate a sensor for a time in the future that doesn't recompute all the time?
Well I guess that's up to you, how you compute the future time, and how often you want to compute it. What are the inputs to the formula?
essentially I've estimated that the water cools about 1/3°C each hour. So if the water is at 48°C and i know that it will be heated again the moment it goes below 45°C, my estimation is (48 - 44.5) / 0.333, but for extra accuracy since the temperature sensor has a 0.5°C sensibility, I'm taking into account how many seconds ago the temperature last changed
if it last changed 30 minutes ago, I'm subtracting 30 minutes
I mean it's ok if the time in the future recomputes when the inputs change. I'm not saying you have to totally stop updates to the database, I was just suggesting that you don't need a "countdown" where you're causing state updates every second that are unneeded.
If it was mine I would probably just recompute a new finishing time every time the temperature sensor changed, that seems reasonable.
it does
I don't think I need to account for the time passed since it last changes. It might help with accuracy when first calculated, perhaps after a reboot, but from that point on since the value will be computed with every temperature change, it will be calculated with very little to no delay
If you have a temperature sensor on the heat pump why not use the temp it starts heating and the temp it stops heating. then notify when it gets there. If you really want to get a time till it stops heating a trend sensor would probably work
@tepid onyx I'm not sure I follow your reasoning. I want to have an estimation of when it will heat. Like, in 5h 23m
@tepid onyx I just learned that trend sensors exist
i like that, it could work, specially because my estimation of 0.333°C/hours depends on the current ambient temperature. The room where the reservoir is ~14°C. In summer it will be at 25°C, so the speed at which the reservoir looses heat will be different
is there a way of getting the current time similar to now() but that doesn't cause the template to update every minute?
Okay, then the alternative is either what you were doing already, or create a mapping
What do you mean? How often do you want it to update?
There is a sensor that computes its value using current time and the value of another sensor, but I only have to update it when that other sensor updates.
I could update with the same frecuency as the other sensor it relies on, the current time has no effect
Create a trigger based template sensor and use the state change of the other sensor as the trigger
could you elaborate on creating a mapping please
Not right now, I'm on mobile
@marble jackal that sounds promising. I've been using HA for years and I keep learning about features I didn't know existed all the time. Trigger sensors and the trend integration today, and the bayesssian integration a week ago
@lone birch I converted your message into a file since it's above 15 lines :+1:
@lone birch The new template sensor format falls under the template integration, where your old (legacy) template sensors fall under the template integration
The docs always assume that the code is directly placed in configuration.yaml, so the first line is the integration
Hi. I am trying to scrape my energy price from a website displaying the price in cents per kWh. For my energy dashboard I want the price to be in EUR/kWh. When I try to convert in EUR via value_template is goes wrong. Anyone seeing what is wrong in this code:
value_template: "{{ (value | replace(',', '.')) / 100 }}"
@jovial horizon You will still have a string after replacing the comma with a dot
You need to convert it to a float before you can divide it
Wow. Thanks, that worked.
value_template: "{{ (value | replace(',', '.') | float ) / 100 }}"
your pastie expired, so I could not see the actual scripts anymore, but I meant something like this:
{% set light_to_script = {
'light.tilewall01': 'script.foo',
'light.li11_hallway': 'script.petunia',
'light.li08_bedside_lamp_01': 'script.whale',
'light.li09_bedside_lamp_02': 'script.bar'
}
%}
{% set checklights = expand('group.alllights')
| rejectattr('entity_id', 'in', light_to_script)
| selectattr('state', 'eq', 'on')
| map(attribute='entity_id')
| list
%}
{{ light_to_script.items() | selectattr('0', 'in', checklights) | map(attribute='1') | list }}
Hi, i have been banging my head for a while so ill try asking 🙂
I have a mqtt sensor where i have a value template....
I receive a comma seperatted list all, good i can extract the value i need... However, i want to add the other values i receive as attributes, is this possible.
Question2: In the value template if i receive a specific value i would like to NOT update the current state....
Hi, I have a sensor that updates every minute and in that way spams the log. Is there a way to only update this sensor the moment that the sensor that it is based upon updates? This is the template sensor:
tesla_timechargingfinished:
friendly_name_template: "Tesla finishes charging at"
value_template: "{{ (now() + timedelta(hours=states('sensor.tesla_time_to_full_charge')|float)).strftime('%H:%M') }}"
At this moment, it also updates when it's not charging, because now() + time left to charge changes all the time, since time left to charge is 0 and now updates every minute.
You could create an input_datetime helper, and in an automation set that input_datetime anytime tesla_time_to_full_charge changes.
But I'm not aware of a way to restrict the update rate of templates, or to prevent now() from triggering minutely updates.
Or if the only issue is the logbook, just exclude this sensor from the logbook.
same advice as I gave earler today, create a trigger based template sensor with the state change of the source sensor as trigger
you'll have to use the new template sensor format then, the legacy format you are using now doesn't support triggers
template:
- trigger:
- platform: state
entity_id: sensor.tesla_time_to_full_charge
to: ~
sensor:
- unique_id: tesla_time_charging_finished_template_sensor
name: Tesla finishes charging at
state: "{{ (now() + timedelta(hours=states('sensor.tesla_time_to_full_charge')|float)).strftime('%H:%M') }}"
oh neat, I had no idea templates could have customized triggers 👍
meaning that I happen to be used "outdated" syntax and I should be grouping stuff by platform rather than by type?
@thorny snow I did it like this:
- trigger:
- platform: state
entity_id:
- sensor.temperatura_actual_acs
- number.temperatura_objetivo_acs
sensor:
- name: "Próximo arranque ACS"
unique_id: forecasted_next_acs_cycle
state: "{{now() + timedelta(seconds = ((states('sensor.temperatura_actual_acs') | int - (states('number.temperatura_objetivo_acs') | int - 5.5)) / 0.3333 * 3600))}}"
icon: "mdi:calendar-clock"
Not sure what you mean with platform
instead of having:
# configuration.yaml
sensor:
- platform: template
sensors:
sensor_name:
friendly_name: Fridge temperature
value_template: "{{stuff}}"
I should have
#configuration.yaml
template:
- sensor:
- name: Fridge temperature
state: "{{stuff}}"
That would be the new format, yes
I have homework then. A lot of stuff to move around
the old format does not allow (or I didn't see a way) of having a trigger on a sensor
That's true
all clarified. Since I missed the memo of formats changing, did anyone produce any migration guide? @inner mesa Seems simple enough tho
Maybe? It's pretty straightforward
yeah, don't worry
Could anyone take a look at my in development template sensor and see if I made any obvious rookie mistakes?
https://github.com/maxi1134/Home-Assistant-Config/blob/master/includes/template.yaml#L112
That link will take you to the template sensors line on my github
The goal of the sensor is to determine what I am up to
I don't know what you want folks to do with that monstrosity
Tell me if they see any blatant error that a non-coder like me might miss 😛
thanks Fes! I'll give it a shot
It worked but had to remove line: | rejectattr('entity_id', 'in', light_to_script)
Cheers
I have from 2 ESPHome devices power values (P1 and P2) and I want to divide the 2 values to create a new variable (P1 / P2 = Factor). Can this be done in a template?
I’m trying to create a humidifier ‘device’ based on different entities, not a generic hygrostat but an actual humidifier-device, I have ‘everything’ I need but as different entities (from localtuya) so anyone know how to do that, to create a ‘generic humidifier’?
I don't believe devices are creatable as an end user.
and why doesn't generic hygrostat suit that need?
Hi, I try to compare 2 values this way
condition: template
value_template: >-
{{ state_attr('climate.nest', 'target_temp_low')| float(0) }} = {{
states('input_number.temperature_confort')| float(0) -2 }}
😦 unable to make it friendly to read ...
but it seems it doesn't work ...
To format your text as code, enter three backticks on the first line, press Shift+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.
{{ state_attr('climate.nest', 'target_temp_low')| float(0) == states('input_number.temperature_confort')| float(0) - 2 }}
wow, ur so right
Hi guys, I'm stuck on something that is seemingly so simple, I'm trying to get my config file to add all the template files in the the folder templates. It's loading one, but one of them keeps giving me errors, here it is below
Invalid config for [template]: [masterbed_temperature] is an invalid option for [template]. Check: template->sensor->0->masterbed_temperature. (See /config/templates/temperatures.yaml, line 0).
That's the error
@cyan elm I converted your message into a file since it's above 15 lines :+1:
That's what the temperatures.yaml that its adding looks like
I've checked indentations a million times, if someone could help it would be greatly appreciated
What about this?
- sensor:
- name: masterbed_temperature
value_template: "{{ state_attr('climate.l1_100', 'current_temperature') }}"
unit_of_measurement: '°C'
friendly_name: 'Master Bedroom Temperature'
device_class: temperature
I'm looking at template examples but I don't see one where there's just a raw string instead of a name key. could be wrong though, not sure
is this being included under a template: key? Looks like you might be mixing up a bit of new format and legacy format.
Will give it a shot and let you know
Invalid config for [template]: [value_template] is an invalid option for [template]. Check: template->sensor->0->value_template. (See /config/templates/temperatures.yaml, line 0).
how is valid template invalid?
lol
value*
oh state instead of value template?
I see
- sensor:
- name: masterbed_temperature
state: "{{ state_attr('climate.l1_100', 'current_temperature') }}"
unit_of_measurement: '°C'
friendly_name: 'Master Bedroom Temperature'
device_class: temperature
Trying this
I don't think it accepts "friendly_name"
The interesting this is when I Had this in my config.yaml before I exported it to separate files
it was working a charm
that seems doubtful
- sensor:
- name: masterbed_temperature
state: "{{ state_attr('climate.l1_100', 'current_temperature') }}"
unit_of_measurement: '°C'
device_class: temperature
This worked, thanks!
Invalid config for [template]: expected dictionary for dictionary value @ data['sensors']. Got [OrderedDict([('name', 'masterbed_temperature'), ('state', "{{ state_attr('climate.l1_100', 'current_temperature') }}"), ('unit_of_measurement', '°C'), ('device_class', 'temperature')]), OrderedDict([('name', 'kitchenliving_temperature'), ('state', "{{ state_attr('climate.l1_102', 'current_temperature') }}"), ('unit_of_measurement', '°C'), ('device_class', 'temperature')]), OrderedDict([('name', 'toplounge_temperature'), ('state', "{{ state_attr('climate.l1_101', 'current_temperature') }}"), .... (See /config/templates/temperatures.yaml, line 0).
Sorry another question, when I put them all back, this is the error I get now
@cyan elm I converted your message into a file since it's above 15 lines :+1:
sensors is the legacy format, which you're mixing up
hello, im trying to template a nested variable, i believe thats what youd call it. im basically brand new to HA.
Ive got a helper, with some value in it that id like to access using a variable instead of referencing the helper directly.
the idea is that i would to perform an action using the value stored in one of 5 helpers. thus the variable reference.
the helpers are named color1 - color5 etc. its the color[n] bit that i cant seem to crack. i can explicitly call any of them and it works fine. the value of n (1-5) is stored in a local var called "result"
value: "{{ states('input_text.color[result]') }}" #returns an unknown value
value: "{{ states('input_text.color1') }}" # correctly returns the value stored in helper 1
i know its something simple, but given my limited exposure i cant spot the syntax hang up etc
{{ states('input_text.color' ~ result) }}
thx much i was just coming back to say that i arrived at value: "{{ states('input_text.color' ~ result) }} as well
Is there a way to avoid template loops (seeing them reported in the logs) in a template where in a binary sensor, I need to find many other binary sensors matching a certain substring. eg
{%- for sensor in states.binary_sensor -%}
{%- if 'motion_triggered_now_in' in sensor.entity_id and 'utility' not in sensor.entity_id -%}
I guess because this template 'listens' to all states.binary_sensor its classed as having a template loop. Is there some way to narrow that sensor watch to avoid loops, yet still having one binary sensor search for others.
@tribal cedar you don't need a for loop for that
{% set sensors = states.binary_sensor | selectattr('entity_id', 'search', 'motion_triggered_now') | rejectattr('entity_id', 'search', 'utility') | map(attribute='entity_id') | list %}
That will list all entity_id's which match the if statement
how to convert hex string 'fffb' to 16-bit signed integer -5
fffb -----> -5
{{ 'fffb' | int(base=16) }} returns something, but not -5
I'm trying to see if test has more than 1 light. but I get str object has no attribute 'light'
{% set test = 'light.front_door_outdoor_light','light.foo_light' %}
{{ test | selectattr('light') | list | length }}
{% set test = 'light.front_door_outdoor_light','light.foo_light' %}
{{ test | select('match', '^light') | list | length }}
How are you doing the highlighting?
python instead of jinja
How would I ignore white space in a string? When using startswith let's say foo.startswith('bar') but a user puts in bar it wouldn't match
Thanks! Will check this out 🙂
Awesome thank you
| map('trim') | list
t o trim whitespaces in list elements
or
| regex_replace('^(\\S+\\s+\\S+)\\s+.*$', '\\1')
to trim all whitespaces.
lots of ways
Using the commonly used light counter script which works fine.
{{ states.light
| rejectattr('attributes.entity_id', 'defined')
| selectattr('state', 'eq', 'on')
| list | count }}
However I have lights which are toggled on by switches. Given there are lots of 'switch.' based entities in home assistant is there a way of isolating the lights powered by switches and counting them?
Use Switch as X helpers to convert the switches to light entities. Then your existing template will work.
I've used helpers to group lights before but for a relative newbee. How do you convert switches to lights?
UPDATE FOUND IT
@halcyon fulcrum I converted your message into a file since it's above 15 lines :+1:
the state template is rendered before the attributes are created, so the state_attr() will result in none
the state template will then fail on the as_datetime(none)
and because of that your template will be unavailable
some other remarks, I don't know if self referencing using this works in the legacy format (which you ar using)
and you can simply use {{ days_since >= 3 }} . That will already return True or False. No need to build an if statement to achieve the same result
Would it be posibble to change the result of the following:
{{ state_attr(''media_player.hdmi_sync_box'', ''volume_level'') }}
This shows as an value of 0.00 (0.00 - 1), but i would like to show the result in percentage.
Such as 0.56 shows as 56%
"{{ (state_attr('media_player.hdmi_sync_box', 'volume_level')|float * 100) | int }}%"
Awesome, thank you!
Makes sense now. Thanks! So you think this would work if I used new formatting? I'm new to HA, could you point out what particularly makes my code legacy?
have a look at the docs, the new format is part of the template integration, and supports sensor, binary_sensor, number, button and more
the legacy template is mentioned at the bottom of that page
Thanks for that. It seems even with the much improved approach to find these sensors, HA is still reporting it as a template loop. I assume the fact that I mention states.binary_sensor at all, means it is still looping internally with the pipes | and is looping over itself, reporting it then as a template loop? I wonder is there a way around it.
Thanks!
I'm working on a Template condition in an automation.
I've got it triggering off of an event and I'm specifying the device_id: of the event I captured. For the condition, I want to look at Data: -> parms -> move_mode. I presume that my trigger condition would look at {{ tringger.event.data}}, but how do I specify all the way down to get to look at move_mode?
would {{trigger.event.event_data.parms.move_mode}} do the trick or just error out on me? I'm not sure I can test this in
| Template, can I?
answers the question: No
Can you post the full contents of the event you captured from the devtools?
if there's a further dictionary inside the event data, then yeah you'd just keep adding to the path to the final variable you're after
You probably at least have one too many 'event' items in there, but yes, seeing the actual event would help.
@hard venture I converted your message into a file since it's above 15 lines :+1:
hah, yeah, I see where I typed event.event - that was a typo on my part, not a copy/pasta
yeah in that case trigger.event.data.params.move_mode should be a usable variable in a condition or action
Thanks, @lofty mason . I presume I need to enclose it in {{ }}, correct?
Yes if you're writing a template.
OK. thought so, just wanted to confirm. That'll eliminate one error...
Question based on documentation found at https://www.home-assistant.io/integrations/cover.template/ . I have a Garage template sensor I created that takes an upper and lower tilt sensor into play on their status and creates the Garage Sensor based on their combined status. Based on the documentation and the value_template option it says open, closed, etc. but my Template sensor reports Open, Closed, etc. Do I need to lower case to comply or will HA convert it automatically?
I believe the states to use are "open" and "closed". If you see capitalization, that's probably just displaying the "human friendly" version. Do you just see those in the frontend display, or where are you seeing "Open" exactly?
I wrote this
@dense swan I converted your message into a file since it's above 15 lines :+1:
I wrote out Open, Opening, and Closed which HA would use for the cover.template's value_template to determine status
Not sure if should/need to change them to lowercaase to comply
Like when I look at states for sensor.garage, which the cover would use says the Open version not open like other states do
So not sure this would mess with the value_template's processing ability
didn't know if cover templates do a lc(value) to make it comply or do I have to
Its just tomato tomatoe but just asking
Guess this answers it:
2023-02-23 18:46:21.539 ERROR (MainThread) [homeassistant.components.template.cover] Received invalid cover is_on state: unknown for entity cover.garage_door. Expected: open, opening, closed, closing, true, false
Am I able to change the min/max/units settings on an input_number based on another value?
I tried this, but it'd seem I can't use templates in those fields directly:
# Input number for setting a custom height
input_number:
standing_desk_height:
name: Standing Desk Height
icon: mdi:human-male-height-variant
min: {{ states("number.upsy_desky_min_target_height") }}
max: {{ states("number.upsy_desky_max_target_height") }}
unit_of_measurement: {{ states("select.upsy_desky_height_units") }}
No, you cannot
If you use a template number you can template everything but the unit... because unit_of_measurement isn't a valid key for template number entities.
template:
number:
- name: Standing Desk Height
state: "{{this.state | default(0,1)}}"
optimistic: true
set_value:
- service: number.set_value
target:
entity_id: number.standing_desk_height
data:
value: "{{ value }}"
icon: mdi:human-male-height-variant
min: '{{ states("number.upsy_desky_min_target_height") }}'
max: '{{ states("number.upsy_desky_max_target_height") }}'
However, it is only restart tolerant if you use a standard input number or text to save the state value...
hi all, I have an issue with a template sensor where I changed the unit from Wh to kWh (by dividing the state by 1000). After Restarting HA the Value stays in Wh. Why?
- name: "Solar Forecast Watt Hours" unit_of_measurement: "kWh" device_class: energy state_class: measurement unique_id: solar_forecast_watt_hours #availability: "{{state_attr('sensor.solar_forecast_watt_hours_raw', 'watts')[state_attr('sensor.solar_forecast_watt_hours_raw', 'watts')|sort|select('le', now().strftime('%Y-%m-%d %H:%M:%S'))|list|last] |float |is_number }}" state: > {% set time_now = now().strftime('%Y-%m-%d %H:%M:%S') %} {% set tkey = state_attr('sensor.solar_forecast_watt_hours_raw', 'watt_hours') |sort|select('le', time_now)|list|last %} {{ state_attr('sensor.solar_forecast_watt_hours_raw', 'watt_hours')[tkey] /1000 | float }}
if I check the state in the dev tools it changes accordingly and everything seems to work
i mean in the dev tools - template editor tool...
is there a way to force the template sensor to take the updated state? (nevertheless, the sensor is updating the value, but does not divide it by 1000....)
are you sure there isn't a sensor.solar_forecast_watt_hours_2 now? Could be if you also added/changed the unique_id while making the changes
Trying to create a universal media player that uses source as a combination between a TV and an Apple TV. Basically i want to use the HDMI 1 and 4 (PC AND XBOX) from the TV but everything else from the Apple TV (HDMI 2). Is there a way to do this? So source list should be "Apple tv source + HDMI 1 and 4 from TV" and when i select the appropriate one it should switch to the corresponding input on the tv as well
I want to set the name of this custom button based on the value of the entity. when its empty, it should be "select room" and when it has some values (eg: kitchen, living_room etc) it should be "clean". but i dont get that. it shows the code itself.
- type: custom:button-card
entity: variable.deebot_kajer_beti_ronbot_queue
icon: mdi:play-pause
name: >-
{%- if is_state('variable.deebot_kajer_beti_ronbot_queue', "") -%}
Select rooms
{%- else -%}
Clean
{%- endif -%}
I tried giving the universal remote a custom source list like this source_list: input_select.lg_inputs but it does not seem to work...
is direct way to create a RFC 3339 format (ie. yyyy-mm-ddThh:mm:ss+offset) time sensor other than via strptime/format? I had this{{as_timestamp(now())|timestamp_local}} but it still contains the milliseconds.
if you have a timestamp, you can simply use | int
{{ (as_timestamp(now()) | int) | timestamp_local }}
2023-02-24T14:21:38+01:00
right! {{as_timestamp(now())|int|timestamp_local}}
o wait, you do something else
its correct though, never thought of |int ' ing that. thx!
would be a nice filter though 😉 {{now()|rfc_3339}}
I actually do the same, I've added some unneeded brackets
well, just tested the perfect output inside the platinum weather card, and it doesn work (invalid date, invalid date). Must be doing something wrong there.. https://github.com/Makin-Things/platinum-weather-card
so you created a template sensor which outputs that format, and then used that in the card config?
i pretty much always do INT/FLOAT(default=0), but now i have a sensor with verrry high numbers. Like 300k. When i graph this and an 0 is added i get an almost flat line due to the 0.
Should i remove the default and let it just make an error to remove the zero values?
You should probably add an availability template to make the template sensor unavailable when the source sensor(s) are not providing the right state
How could I select sensors which states are 'on' and use the list to pick their attribute values? I've tried some rejectattr and selectattr trickery but I don't fully understand how they work.
states.sensor|selectattr('state', 'eq', 'on')|map(attribute='attributes.whatever')
Otherwise, need more details on what 'pick' means and what you've tried
Plus, you probably mean binary_sensor
HI! surely I'm missing something in restoring a template sensor on reboot. I have a sensor that updates a few times a week and would like the status not to go unknown after reboot
- trigger:
- platform: state
entity_id:
- sensor.impedenza_francesco_raw
sensor:
- name: Impedenza Francesco
unique_id: impedenza_francesco
unit_of_measurement: 'ohm'
state_class: measurement
icon: mdi:omega
state: |
{% if states('sensor.impedenza_francesco_raw')|is_number %}
{{ states('sensor.impedenza_francesco_raw') }}
{% else %}
{{ this.state }}
{% endif %}
To format your text as code, enter three backticks on the first line, press Shift+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.
Change your trigger to this, and just refer to {{ trigger.to_state.state }} in the state template
- trigger:
- platform: state
entity_id: sensor.impedenza_francesco_raw
not_to:
- unavailable
- unknown
thanks, like this?
- trigger:
- platform: state
entity_id:
- sensor.impedenza_francesco_raw
not_to:
- unavailable
- unknown
sensor:
- name: Impedenza Francesco
unique_id: impedenza_francesco
unit_of_measurement: 'ohm'
state_class: measurement
icon: mdi:omega
state: "{{ trigger.to_state.state }}"
what does to_state mean? Where can I find documentation on this?
Third link in the topic
after home assistant restart it goes to unknown...
why is the previous value not loaded?
Did you restart to reload the configuration of this sensor?
You can do that from developer tools > YAML
Anyway, I guess it needs to be triggered again because the configuration changed
I'm doing some tests, now it seems to work. I think the problem was that I set the value through "set state" to try, but it seems that through this function the value is not saved in the db and when I restarted it gave me this problem. anyway, it looks ok
Yes, but I fixed it . I had selected an attribute so it didn’t read the state.. it’s working fine now
I've created these kind of template binary sensors and I would like to gather all the rooms together which needs cleaning. In other words the binary sensors which are true. I also would need to extract the room_id's from the attributes of the binary sensors to get my vacuum robot to understand which rooms are to be cleaned during that day.
- binary_sensor:
- name: "Living Room Cleaning"
state: "{{this.attributes.cleaning_need}}"
attributes:
room_id: "15"
timestamp: "{{1677059173.283542}}"
days_since: >
{% set today = now().date() %}
{% set last_cleaned = this.attributes.timestamp %}
{% set days_since = (today - as_datetime(last_cleaned).date()).days %}
{{ days_since }}
cleaning_need: >
{{this.attributes.days_since >= 3}}```
alright, so what I gave you should help
I'm getting an error with that at the moment
{{states('binary_sensor.living_room_cleaning') | selectattr('state', 'eq', 'on') | map(attribute='attributes.room_id') }}
<generator object sync_do_map at 0x7f3ee7e23bc0>
well, I guess it is not an error but something else
you started with a state, which is a string
I thought you might be further along that that
{{states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.room_id', 'defined')|map(attribute='attributes.room_id')|list }}
ah now I got it, thanks! Any tips how to get this filtering working only with specified sensors? Now it seems to collect every binary sensor it finds.
only ones with a 'room_id' attribute
but yes: {{expand(['binary_sensor.xxx', 'binary_sensor.yyy']) | selectattr('state', 'eq', 'on') | selectattr('attributes.room_id', 'defined')|map(attribute='attributes.room_id')|list }}
Ah, you have edited this code. Got some undefined values first. Thanks alot!
I'll also save this so I don't need to ask again if I need to build something like this again 🙂
I'm having trouble with a template.
This works:
{{ states.sensor.wabash_river_level_data.attributes["site"]["observed"]["datum"][0]["primary"]["#text"]}}
but documentation suggests NOT using states (and it doesn't seem to work in a sensor template in my configuration.yaml)
This doesn't:
{{state_attr('sensor.wabash_river_level_data','site').observed.datum.0.primary.#text}}
Not sure how to deal with the special character #.
Anyone have ideas on what I'm doing wrong?
you still need to use the ["#text"] format for that part
{{ state_attr('sensor.wabash_river_level_data','site').observed.datum.0.primary["#text"] }}
or you can just use [xxx] for all of them after the state_attr() call
TheFes was helping me yesterday to avoid a template loop but I can't seem to find a way to stop it. I have one binary sensor that needs to find binary sensors that match certain attributes. The fact that it loops or filters on states.binary_sensor seems to result in HA reporting it as a template loop. Is there some magic way out of this?
This is not my full template but it gives the jist of the fact that if I mention states.binary_sensor at all, its a loop. Can literally the word states.binary_sensor not be mentioned?
{{ states.binary_sensor | selectattr('entity_id', 'search', 'motion_triggered_now_in') | list | count }}
Thanks your suggestion worked perfectly. Thanks!
I'm on the beta, so maybe shouldn't ask here, but the openAI integration has a custom template now, and I tried it in the template section of dev tools, but it is giving me an error that 'areas' isn't defined.. anyone have a quick fix?
Well I may have spoken too soon. Works in the Developer Tools yaml window, but when I plug it into a sensor, I get an error.
- sensor:
- name: "WBRL"
state: "{{state_attr('sensor.wabash_river_level_data','site')["observed"]["datum"][0]["primary"]["#text"] | float }}"
state_class: measurement
unit_of_measurement: ft
I get the error :
bad indentation of a mapping entry (175:72)
174 | ...
175 | ... sh_river_level_data','site')["observed"]["datum"][0]["primary ...
------------------------------------------^
So I'm still missing something!
- name: "WBRL"
Looks like maybe it just wants you to tab your long line in the same as the one above it? 🤷 Not sure though!
Really need to see the YAML formatted as code
To format your text as code, enter three backticks on the first line, press Shift+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.
template:
- sensor:
- name: "WBRL"
state: "{{state_attr('sensor.wabash_river_level_data','site')["observed"]["datum"][0]["primary"]["#text"] | float }}"
state_class: measurement
unit_of_measurement: ft
And wabash_river_level_data is from above the template
# Wabash River Level
- platform: rest
name: Wabash River Level Data
resource: https://water.weather.gov/ahps2/hydrograph_to_xml.php?gage=lafi3&output=xml
value_template: "{{ now() }}"
json_attributes:
- site
- observed
- forecast
Use ' instead of " in your indexing within the state template
That did the trick. So many little nuances I need to learn. Thank you!
@grave solstice I converted your message into a file since it's above 15 lines :+1:
Whats the go to method do group all entities of a particular type now? I know it got changed a while back. I am using the below in an automation, however just want to have a simple on off switch on a dashboard and not sure how to go about it.
service: light.turn_off
target:
entity_id: >-
{{ states.light | map(attribute='entity_id') | reject('eq',
'light.wled_christmas_tree_master') | list }}
@tulip kindle I converted your message into a file since it's above 15 lines :+1:
sorry for bad post above.
how can I use hs_color in template for icon_color?
{% if states('sensor.plug03_current') > '0.2' %} hs_color(161,98) {% else %}
disabled {% endif %}```
How would i make a template that checks if a state atribute contains anything at all?
I want a template that returns true if the attribute "manual_controll" contains anything at all
at first i thought i could use a lenght filter or something but that is not a valid filter.
I feel like im missing something super obvious
{{ state_attr('switch.adaptive_lighting_bad', 'manual_control') | contains (*) }}
i thought maybe a "wild card" would work but no 😦
Is it defined, but just blank? Or doesn't exist at all?
@dry cobalt I converted your message into a file since it's above 15 lines :+1:
i am unsure what "defined" means in this context but im guessing this is "defined" ?
oh my god🤦♂️
i tried again, i must have made a typo or something when i tried it the first and second time..
Third times the charm
lenght worked
i appriciate the help ❤️
~~Still working on the above template; it now prints out which entity that is in manual controll, like this
{{ state_attr('switch.adaptive_lighting_bad', 'manual_control')[0] }}
{% else %}
none
{% endif %}```
in this case the output is " light.bad "
can i make the " light.bad " clickable in some way?~~
actually i have a better idea, a conditional button to turn off manual controll that shows up if the template outputs anything 😄
Hey all, has anyone ever seen a template render properly in the template editor, but incorrectly in an automation?
I have this template
{% set requested = states("sensor.zone1_requested") == 'True' %}
{{ 'switch.turn_on' if requested else 'switch.turn_off' }}
But it's rendering switch.turn_on in the editor and switch.turn_off when part of an automation
You could probably simplify that to switch.turn_{{ 'on' if states('sensor.zone_1_requeated') | bool(False) else 'off' }}
My guess is that 'True' is being evaluated differently in each case for some reason.
hi all, is there a way to create a stateless toggle button (on-off) to a switch with on off states?
You just want an input_button that will call the switch.toggle service?
hmm, maybe that is what I want....sorry, I posted in automations what my problem is
#automations-archived message
One possible way (probably not the best) is to check trigger.to_state.context.parent_id in a condition and if that's set, the state change was made by an automation.
oh, that is brilliant! that could work. what would the condition be equal to, not none or none?
value_template: '{{ trigger.to_state.context.parent_id == none }}'
You want it to be True when it's none
so, as you have it
(except w/ value_template not indented that far)
ah ha, ok let me try this, ok, I'll fix that indentation
STill hoping womone can point me in right direction? Or am i asking in wrong channel please show me the rigth one then 🙂 ❤️
If you're asking specifically about card configuration, thats a #frontend-archived thing, otherwise it's not clear what you're actually looking to achieve and where you're currently at
thank you very much @obtuse zephyr it worked perfectly with the condition you mentioned. I placed it as a global condition and although it does double fire at the same it time, it fails on the second time because the condition was not met.
Well i have configured a card it looks good... however i want to use the auto entities with that card so all my units will show up... i have come so far to understand i need to template that
hey gang... Just finished my streaming audio media_player build, and want to build a templated media_player around it, that can keep state, and resume playing after TTS
is this the right place to ask?
The template filter from auto-entities expects a list of entity_ids, not a complete card config
You can probably achieve what you want with auto-entities, but that is a #frontend-archived thing
Thanks for reply
I have another issue....
I got a Template Sensor with an attribute. I want to update that attribute from a script.... but in script i hace target and there asfaik i can only choose a entity_id....
There are no service calls to update sensors
Your only option is to create a trigger based template sensor and trigger on an event sent in the script
Hey can someone help me with the current Template? The rounding is not working 😭
template:
- sensor:
- name: "Füllstand (Volumen)"
unique_id: "ZisterneVolume"
unit_of_measurement: "L"
state: >
{% set volume = states('input_number.zisterne_volumen') | float %}
{% set height = states('input_number.zisterne_hohe') | float %}
{% set level = states('sensor.zisterne_ultraschallsensor') | float %}
{{ ((volume / height) * level | round(2)) }}```
I getting Values like 4.681,81818181818
Are you saying its impossible to update the data of a template sensor???
You are only rounding level
Use parenthesis
A state based template sensors is updated when the states of the source entity changes.
A trigger based template sensor is updated on the trigger(s).
If you want to update a template sensor from a script, you can send an event in your script, and use the event as trigger in a trigger based template sensor
Bit overdone on the parenthesis through, this will give the same result:
{{ (volume / height * level) | round(2) }}
So what your take ... I have a input _text value which a user can set an rttl tone.... I have a sensor.door with attribute ringtone...
Any smart ideas for me to proceed?
I have no clue what you want to achieve here. That sensor.door is a template sensor? What is the YAML code for the sensor
can i take week day in templates ?
@grave solstice I converted your message into a file since it's above 15 lines :+1:
Thanks a lot!!!
Wait, do you want that attribute to match the input text?
I've been looking around but am having trouble finding any good leads. I have a IR fan that receiving commands from a broadlink RM4, that part it working around 95%, and it's just missing a few commands here and there. My thinking was that I also have a energy meter on the fan, which gives me info on wattage i.e. fan level. Is there a way to combine the output from the power meter and the fan entity itself?
So far I've been able to create a template sensor that gives me the power level and I also have a Fan entity that is able to send commands. I want to mash these two together
Is it as simple as adding the template sensor into the percentage template instead?
Is it possible to transform the output of a Template Sensor in such a way that a unique numeric value can be passed based on the state of the attribute? For example, the Template below will return heating, idle, and cooling. I'd like to transform those attributes to something like 2, 1, and 0.
- name: "HVAC Status"
state: "{{ state_attr('climate.home_thermostat','hvac_action') }}"```
- sensor:
- name: "HVAC Status"
state: >
{% set mapping = { 'heating': 2, 'idle': 1, 'cooling': 0 } %}
{{ mapping[state_attr('climate.home_thermostat','hvac_action')] }}
So far I ve been able to create a
archhh... dont see it. I have 8 sensors with a state indicating the days left to an event. I want to template the next upcoming event (count days is lowest) , and then show the name. started with: {{states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')|list}} which gives me this list ['57', '114', '359', '182', '49', '80'] so doesnt even sort on the number, but still on the names. even with sort: {{states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')|list|sort}} returning ['114', '182', '359', '49', '57', '80']
now, that is not the most important thing here, I first need a template to find the lowest number, and then show the name
``` returns 114....
You'll need to add a | map('int') prior to | min otherwise you're sorting strings
a yes, that helps..{{states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')| map('int')|min}} results in 49, and ```{{states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')| map('int')|sort}}
How can I extract the total amount of minutes from a timestamp? The following template gives me the minutes in the hour (so the full time would be 5 hours and 24 minutes, and this template gives me just "24" as result instead of (5*60)+24 minutes=324. How can I get 324 as a result from this?
{{ (as_timestamp(state_attr('sun.sun', 'next_dawn')) - as_timestamp(now())) | timestamp_custom('%M') }}
Hi all, I would like to create a sensor template to sum all my MQTT sensor.*_energy entities. Note I also have sensor.solaredge_*_energy from the SolarEdge integration which I don't want in there. I only want the sensors from my MQTT integration. Is there a way to accomplish this?
Also, the time doesn't seem to be right, as it's two hours longer than it should be
First find the lowest one, then find the one matching that state
{% set lowest = states.sensor|selectattr('entity_id','search','verjaardag')|map(attribute='state')| map('int')|sort|first %}
{{states.sensor|selectattr('entity_id','search','verjaardag')|selectattr('state', 'eq', lowest|string)| map(attribute='entity_id')|join}}
ofc, that must be it. Shows empty though (and I cant find a typo....):
Holy shit! I didn't know there was an editor like that 🙂
|selectattr('state', 'eq', '49')| map(attribute='entity_id')|join}}
``` works though
so its not wanting a number but a string...
You need to change lowest to string
I've added the filter
Entity_id: {{states.sensor|selectattr('entity_id','search','verjaardag') |selectattr('state', 'eq', lowest|string)| map(attribute='entity_id')|join}}
check!
or maybe it is possible to have the value actually saved to be an integer? Seems logical
And then you don't need to mess around with it everywhere you want to use it
I was planning on adding it to a small markdown card:``` - type: markdown
content: >
## Volgende event:
{% set lowest = states.sensor|selectattr('entity_id','search','verjaardag')
|map(attribute='state')| map('int')|sort|first %}
{{states.sensor|selectattr('entity_id','search','verjaardag')
|selectattr('state', 'eq', lowest|string)| map(attribute='name')|join}}
{{states.sensor|selectattr('entity_id','search','verjaardag')
|selectattr('state', 'eq', lowest|string)| map(attribute='state')|join}} dagen
figured to set states.sensor|selectattr('entity_id','search','verjaardag') apart in a var, but it wont be merged correctly in he other templates
{% set events = states.sensor|selectattr('entity_id','search','verjaardag')|list %}
{% set lowest = events|map(attribute='state')| map('int')|sort|first %}
{{events|selectattr('state', 'eq', lowest|string)| map(attribute='entity_id')|join}}
That should work
and lowest will have your number of days, you don't have to refetch that
Found my solution thanks to messing around in the editor! I'll share it. Maybe you guys see newbie mistakes:
{%- for entity in states.sensor if (entity.entity_id.endswith("_energy")) %}
{%- if is_device_attr(entity.entity_id, 'manufacturer', 'TuYa') %}
{%- set tuya_energy.value = tuya_energy.value + entity.state|float %}
{%- endif %}
{%- endfor %}
{{ tuya_energy.value }}
quick fix
having this now:```
{% set lowest = states.sensor|selectattr('entity_id','search','verjaardag')
|map(attribute='state')| map('int')|sort|first %}
{% set events = states.sensor|selectattr('entity_id','search','verjaardag')|selectattr('state', 'eq', lowest|string)|list %}
Volgende event:
{{events| map(attribute='name')|join}}
{{events| map(attribute='state')|join}} dagen
I think this does it:```
{% set verjaardag = states.sensor|selectattr('entity_id','search','verjaardag')|list %}
{% set lowest = verjaardag
|map(attribute='state')| map('int')|sort|first %}
{% set events = verjaardag
|selectattr('state', 'eq', lowest|string)|list %}
Volgende event:
{{events| map(attribute='name')|join}}
{{events| map(attribute='state')|join}} dagen
I think this does it:```
{% set verjaardag = states.sensor|selectattr('entity_id','search','verjaardag')|list %}
{% set lowest = verjaardag
|map(attribute='state')| map('int')|sort|first %}
{% set event = verjaardag
|selectattr('state', 'eq', lowest|string)|list|first %}
Volgende event:
{{event.name}}
{{event.state}} dagen
better vars:```
{% set events = states.sensor|selectattr('entity_id','search','verjaardag')|list %}
{% set first = events
|map(attribute='state')| map('int')|sort|first %}
{% set event = events
|selectattr('state', 'eq', first|string)|list %}
Next event:
{{event| map(attribute='name')|join}}
{{event| map(attribute='state')|join}} days```
this might be a silly question. I defined a template sensor that performed some calculation based on other sensors, but when I first defined it I made a mistake and instead of a number I was generating a string containing a number. I've since then fixed it but the history graphs shows as a multicolored bar instead of as a chart, probably because it contained strings at some point. How can I fix it? Maybe by erasing the history?
nice!! this does it indeed:```
{% set events = states.sensor|selectattr('entity_id','search','verjaardag')|list %}
{% set first = events
|map(attribute='state')| map('int')|sort|first %}
{% set event = events
|selectattr('state', 'eq', first|string)|list|first %}
Next event:
{{event.name}} {{event.state}} days
``` didnt have the |first on the set event variable, so it errored at first... very nice indeed!
How can I get the start time from a calendar entry? I want to check if the start time is a specific hour of a day. It seems the best way is to use templates?
{{ (state_attr("calendar.xxx", "start_time")|as_datetime).hour == 12 }}
Thanks. Got it eventually
I want a color shifting icon for my template card. Is it possible to set icon-color in a template, to HS color value i.e.(hhh.hhh, sss.sss)?
(my device is a cheapo zigbee light strip for my tv backlight that returns HS color format via state_attr('light.lightstrip_tv_level_light_color_on_off','hs_color')
Hey, how can I create a template sensor that filters out everything except "01:00" from this issue "2023-02-27T07:08:02.506396+01:00"
Why do you want that?
Hey all, I'm having trouble figuring out what's going on with this template.
{% set sleeping = states('sensor.sleeping') %}
{{ sleeping }} # false, type boolean
{% set sleeping = states('sensor.sleeping') %}
{{ sleeping }} # False
{{ "yes" if sleeping else "no" }} # yes
It's like the type of sleeping is changing from boolean to string and the first letter is being capitalized depending on what the next line is
states are always strings
why does it report as a boolean in the first example?
it doesn't
it's just a string
always
if you want it to be evaluated as a boolean, you can do {{ bool(sleeping) }}
I can't paste a screenshot here but Home Assistant template editor is clearly stating that it's Result type: boolean which I just took as being correct
do we know what values evaluate to true or false for the bool() function?
speaking of which, what's the best way to search the docs?
how do i format a datetime string attribute (e.g. "2023-02-01 00:00:00-05:00") in a lovelace template? Looking to say something like "Feb 01, 2023" ideally
When I use bool in my template, it says bool is undefined
{% set sleeping = bool(states('sensor.sleeping')) %}
{{ ("2023-02-01 00:00:00-05:00"|as_datetime).strftime("%b") }} gives "Feb". Format as desired based on the link
thanks!
perhaps you're using a very old version of HA
{% set sleeping = bool('true') %} works fine for me
you'll need to break that habit if you plan to use the documentation
yeah, it looks like the documentation isn't versioned
it always represents the latest version
I'm running
{% for item in integration_entities('anniversaries') %}
{{ (state_attr(item, "next_date")|as_datetime).strftime("%b") }}
{%- endfor %}
and getting the error TypeError: float() argument must be a string or a real number, not 'datetime.datetime'
am i doing something obviously wrong?
remove "|as_datetime"
ok, now i'm getting UndefinedError: 'None' has no attribute 'strftime'
{% for item in integration_entities('anniversaries') %}
{{ state_attr(item, "next_date").strftime("%b") }}
{%- endfor %}
if i remove .strftime("%b"), i get the correct strings
oh, wait. i think there is a None entity in the results
seems like you're getting a "None" in there
i need an if check
the integration includes a calendar entity, not all sensors
so, i need to filter that out
that was it. thank you again!
That's new in 5.0. messed up my template as well
if you want to change brightness_pct, start with brightness_pct
"{{ state_attr('light.bedroom_dimmer', 'brightness_pct') + 10 }}"
Pop that in Dev Tools > Templates to test. That page will also indicate what type of data is outputted by the template.
That can't be the result of putting that in the template dev tool
Is your light currently on?
how can I examine the attributes to understand what they even are?
-> States
So...your light doesn't have a brightness_pct attribute? Check in Dev Tools > States.
Is this a Switch as X entity?
I doubt that will work if brightness_pct isn't provided by the entity.
Try it. But then again, if it provides brightness, why not just use that?
So...does your light provide the brightness attribute?
I'm gonna guess that if brightness_pct doesn't exist, then neither does brightness.
Hey I’m trying to get a sun rise entity to return “10:00” instead of “1 hour ago”. What am I doing wrong? https://dpaste.org/95wmo
You can't use templates in a device action
use "call service" instead, and just stop using device actions
light.turn_on
Hi, so is it
- "unknown"
- "unavailable"
Or
not_from:
- unknown
- unavailable
Does it matter? Thanks
because i want to compare this value with the current time
It doesn't matter
You don't need to remove that part for that, that part contains the timezone information.
If can perfectly compare it to the current time
Example:
{{ now() > as_datetime('2023-02-27T07:08:02.506396+01:00') }}
oh ok, thats nice
my goal is to turn of my lights when my pc does not recognise any action for 5 minutes. from my pc i have the time which shows me when there was the last action. Thats why i want to compare if the time is older than 5 minutes.
But now I have noticed, that this should also work like that, right?
entity_id:
- sensor.scarriffles_pc_zuletztaktiv
for:
hours: 0
minutes: 5
seconds: 0
In this case, I'm having an issue with a trigger based on an ESPHome button (stateless button)
- platform: state
entity_id:
- button.esphome_web_a85214_dyson_humidifier_power_on_off
id: Dyson Humidifier Changed
not_from:
- unknown
- unavailable
When it goes unavailable and comes back, it triggers.
Should the not_from take care of this?
Wonder if I should use a global condition in the automation, just after the triggers :
- condition: template
value_template: "{{ trigger.from_state.state not in ['unknown', 'unavailable'] }}"
Both should do the same
Interesting I just realized that if a button is stateless, this is checking the state. I'll have to try the global condition cause it's triggering from unavailable using not_from 😀
Does anyone have an idea about this?
I want to create two helper toggles that should show a random value from a static list but never the same value. Can anyone explain how to do this ?
The condition does the same, so it will also stop the automation if the previous state of the button was unavailable
😐
But the state of a button is de last time it was pressed
Yes, that should work as well
Can a state sent from a trigger automation (using events), be given a template value?
state:"{{state_attr('calendar.school','message')}}"
Is that valid?
Sorry, it's not clear to me what you are trying to do
I am trying to set a trigger template by using an automation.
Essentially, I want the state of a sensor to be the name of the calendar event.
you can use limited templates in an event trigger, but that template above is not a limited template:
Event trigger docs: https://www.home-assistant.io/docs/automation/trigger/#event-trigger
then use a template trigger
platform: template
value_template: "{{ states('sensor.your_sensor') == state_attr('calendar.school','message') }}"
or
platform: template
value_template: "{{ is_state('sensor.your_sensor', state_attr('calendar.school','message')) }}"
My issue is an issue that kind of affects both automations, and templates. I created a template trigger. (within templates.yaml) and am planning on update the sensor values by using an automation (so that I have more control over the frequency at which it updates).
So, within an automation, I am firing a custom event that will update the value of the template sensor with event data.
You mean you created a trigger based template sensor right?
Yes.
okay, you can use templates when firing an event
I wanted to pass the value of another sensor to the state of this sensor.
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
I wanted the state of this sensor to equal the value of the message attribute from calendar.
It's probably helpful if you post the template sensor and the event you ar using
Well seems you overcomplicated it a bit, but this will work with the following even fired from your automation/script
event: set_schooleventsched
event_data:
state: "{{state_attr('calendar.school','message')}}"
attributes:
state: "{{ 'something' }}"
That will set the sensor state to the message and all the attributes of the sensor to something
you also need to provide all data with every update now, as you didn't build in any failsafe for missing data
The main issue is... I have very specific criteria for when I want this to be updated. 😐
I do have a separate template sensor that correctly gets the correct times, etc...
However, it triggers every single minute.
And being that I have automations that activate whenever the state changes.... those automations fire way too frequently.
I would change the template sensor to this:
- trigger:
- platform: event
event_type: set_schooleventsched
sensor:
- name: SchoolTimes
state: "{{ trigger.event.data.message if trigger.event.data.message is defined else this.get('state', 'unknown') }}"
attributes:
school_date: "{{ trigger.event.data.school_date if trigger.event.school_date is defined else this.attributes.get('school_date', 'unknown') }}"
school_start: "{{ trigger.event.data.school_start if trigger.event.school_start is defined else this.attributes.get('school_start', 'unknown') }}"
school_end: "{{ trigger.event.data.school_end if trigger.event.school_end is defined else this.attributes.get('school_end', 'unknown') }}"
wait_for_bus_before: "{{ trigger.event.data.wait_for_bus_before if trigger.event.wait_for_bus_before is defined else this.attributes.get('wait_for_bus_before', 'unknown') }}"
wait_for_bus_after: "{{ trigger.event.data.wait_for_bus_after if trigger.event.wait_for_bus_after is defined else this.attributes.get('wait_for_bus_after', 'unknown') }}"
Then you can use the following event:
event: set_schooleventsched
event_data:
message: "{{ state_attr('calendar.school','message') }}"
school_date: '01-01-2023'
school_start: '10:30'
school_end: '12:30'
wait_for_bus_before: '10:00'
wait_for_bus_after: '10:45'
Hmmm 🤔
if you leave out one of the parts of the event, it will retain the current value (unless there is no current value, in that case it will use unknown)
Retaining is good... 🤔
My main issue(s) are...
- As soon as the calendar event starts... all of my times change. (As it goes on to the next event in the calendar, instead of seeing the current event through (and beyond) its completion.
And with my son, school times aren't static. 😐
He's in a special ed program.
So, having them remain dynamic is important.
And...
- I don't want the automations that use the sensor to be triggered, every single minute when the sensor updates (as a sensor updates counts as a sensor change. 😐
You can send the event any time you want
My old method was just using a template sensor.
(Which was less complicated)
But wreaked havoc on my automations. 😐
Because every single minute, they'd rapidly switch to unknown, and then switch to the correct value, which would cause my automations that used a state changed event to count that as a state change, and refire the automations (which involve sending messages to my speakers).
Hmmm 🤔
Is there a way to do this type of thing without having to resort to trigger based template sensor?
So that if the template already has a value, do nothing and leave it alone?
I wouldn't mind it running the check every single minute, as long as the state changed events do not register a state change because the value did not change.
What if the value needs to be updated?
Well, I'd want the template sensor to use conditions to retain the current value (if no change is needed) and to change the value if the value needs to be updated. 😐
So, essentially... it'd have to compare to the current value of the sensor (recursively), and if the new value equals the old value, do nothing... otherwise, update it to the new value.
🤔
Is it possible to do a recursive comparison like that?
Using a 'this'?
I don't think there is a lot of difference in resource usage to check in the conditions if the new values are different compared to the old ones, or to just send the event and update the sensor
Well... as it was stated... I "over-complicated" it. So, I was wondering if there was a less complicated way of doing it. 🤔
Ideally, I would like this sensor to set its times, once a day...
(Usually, at midnight... BUT be able to set its times in the event there are no times set (due to power outage, etc).
Hence the automation to check every hour, and then only update the value in the sensor if there isn't a valid value within the sensor.
you could do that with the sensor above
Excellent.
do one update at midnight, and check hourly on false values and update it if needed
And your suggested modifications make what change?
The automation will include all of the attributes, which will all change at the same time.
My automation wasn't quite finished yet.
I just wanted to make sure I had the syntax correct. 🙂
you were overcomplicating things with the attributes in the event
and also the usage of state instead of what the actual event data was
If you always send all the data, you don't really need the check if it's defined
Ah, I see what you are saying.
I just figured, since the state of that sensor was going to be the title of the calendar entry....
That I would just call it "state"
okay, but you were also using attributes.state
there is no need to use another attributes level in the event data
action:
- event: set_schooleventsched
event_data:
state: "{{state_attr('calendar.school','message')}}"
I haven't gotten that far yet. 😐
But
It is good to know that I don't need to include the attribute in there.
Cause I really wasn't sure how the syntax of that was going to go. 😐
So, you actually answered my next question. 🙂
So, thank you for that.
the point is that the trigger based template sensor will fail on the attributes if you don't provide all data
I want to create two helper toggles that should show a random value from a static list but never the same value. Can anyone explain how to do this ?
A toggle is on or off, it doesn't show a value
Sorry I meant the name of the toggle. Like "Clean <roomname_from _list> 0|1"
you can't template the name of a input_boolean/toggle helper
switch:
- platform: template
switches:
test_switch_1:
unique_id: 0086e6b1-265a-4cb4-b345-f2fc490cf90b
friendly_name: "{{ [ 'option 1', 'option 2', 'option 3', 'option 4'] | reject('eq', states.switch.test_switch_2.name | default) | list | random }}"
value_template: "{{ states('input_boolean.test_1') }}"
turn_on: &toggle1
- service: input_boolean.toggle
target:
entity_id: input_boolean.test_1
turn_off: *toggle1
test_switch_2:
unique_id: 52789344-d995-4294-8c03-4c472f7151df
friendly_name: "{{ [ 'option 1', 'option 2', 'option 3', 'option 4'] | reject('eq', states.switch.test_switch_2.name | default) | list | random }}"
value_template: "{{ states('input_boolean.test_2') }}"
turn_on: &toggle2
- service: input_boolean.toggle
target:
entity_id: input_boolean.test_2
turn_off: *toggle1
@plucky depot you could do something like this, which creates two swich entities with the templates used for the name. They are connected to two input_booleans
@marble jackal Thanks!, I will try that.
😐
My changes keep reverting to a non-working version now.
On the automation side of it.
It keeps tacking in an "attributes: null" into my event data.
It refuses to save.
Not sure what is going on now. 😐
you are using double quotes inside and outside your templates
Change them to single?
one of those yes
I guess you normally use double quotes inside, and single outside
I do the opposite
So, in the automation when I am passing the data, use single quotes there?
Or within the actual template.yaml file?
"{{'double quotes outside, single quotes inside' }}" or '{{ "single quotes outside, double quotes inside" }}'
NOT "{{ "double quotes outside, double quotes inside" }}" like you are doing now
you are actually mixing it
If you use the multi line notation you can do that (although I would still advice against it)
some_key: >
{{ 'this' + "that" }}
My confusion there was that in the documentation, I have always only seen double quotes used within those timestamps for the filters. 😐
So, I just figured it was the way it always had to be.
both can be used
"{{ "double quotes outside, double quotes inside" }}" this breaks it into 3 part
Part 1: "{{ "
Part 2: double quotes outside, double quotes inside
Part 3: " }}"
Makes sense...
@marble jackal sorry for all the questions but how do I make the template-switch names update once a week ? Do I need to create some automation or can I add a trigger somehow in the template ?
Do you need them to be static the rest of the week? Because the templates will be rendered again on each reboot
yes that's correct. I was planning to have template for my kids chores so that they get assigned a room to clean each week 🙂
Create 2 trigger based template sensors which update each Monday (or another day of choice) and select the new chore
refer to those for the switch name
template:
- trigger:
- platform: template
value_template: "{{ now().weekday() == 0 }}"
- platform: event
event_type: new_random_chores
sensor:
- unique_id: e891d4d0-ad9f-4c5f-9ed6-873622c58756
name: Chore Kid 1
state: "{{ [ 'option 1', 'option 2', 'option 3', 'option 4'] | reject('in', [states('sensor.chore_kid_2'), this.get('state')] | list | random }}"
- unique_id: 316d2eba-fcc2-4def-b6e5-86eaa847c0b7
name: Chore Kid 2
state: "{{ [ 'option 1', 'option 2', 'option 3', 'option 4'] | reject('in', [states('sensor.chore_kid_1'), this.get('state')] | list | random }}"
so set an initial state (or select new chores if you need) go to developer tools > event and send an event with type new_random_chores
Open your Home Assistant instance and show your event developer tools
and then the change the templates for the switches to friendly_name: "{{ states('sensor.chore_kid_1') }}"
Thanks for all the help @marble jackal 🙂
you could even reject the chore from last week if you want
so they don't get the same chore twice in a row
Ok, great
I've added it in the code above
You could also put the chores in a select helper
so you can easily add chores from the GUI
replace [ 'option 1', 'option 2', 'option 3', 'option 4'] with state_attr('input_select.chore_list', 'options') then
Got it working now. Thanks @marble jackal
I have succesfully extracted the hours from an attribute and converted to string for as_timestamp. However, it's giving me an error. This is working:
{% set tijdstipopkomst = (as_timestamp(t) |timestamp_custom('%H:%M')) %}
{% set time = "07:00" %}
{{ (((as_timestamp(strptime(time, "%H:%M"))) - as_timestamp( strptime( now().strftime("%H:%M"), "%H:%M") )) /3600) | float}}```
However, I would like to use {{ tijdstipopkomst }} as value for time. This results in ValueError: Template error: strptime got invalid input '{{ tijdstipopkomst }}'
Goal: To get the amount of hours in decimal since sunrise to use in a dynamically updating graph.
what are you trying to calculate here
and why are you coverting now() which is a datetime, to a string representation of the time, then back to a timestamp?
The hours since sunrise, in a decimal form (so 7 and a half hours shows up as 7.5 instead of 07:30). I can then use this in Apexcharts to dynamically set the start of my graph each day.
do you want the number of hours until the next rising?
No, I'm using the next rising as a substitute for last rising (as they differ only a couple of minutes and there is no last rising)
Well, this was the first way to finally get a working result, I'm really trying to understand all time additions/calculations but boy it's hard haha
I already thought so, but I don't have any ideas on how to make this easier 🙂
{% set t = state_attr('sun.sun', 'next_rising') | as_datetime - timedelta(days=1) %}
{{ (now() - t).total_seconds() / 3600 }}
Oh wow that is indeed a lot easier. Thanks a lot for this!
Hi all, I have a siren in HomeAssistant that only reports a binary_sensor.siren_alarm. It seems impossible to trigger the actual siren, even tho I manually changes the alarm to true and the 'sensor' to on.. Do I need to template it to a switch? Thx in advance
Hey, I have a template that works in the dev-tools template testing but shows unknown when I look it up under entities
Its a sensor but it shows unknown
@keen hawk I converted your message into a file since it's above 15 lines :+1:
You're not outputting anything in your 'if' path
this looks overly complicated
wondering is it would considered a bug, when using toggle_lights_area: alias: Toggle lights area mode: restart icon: mdi:autorenew sequence: service: light.toggle data: entity_id: > {{area_entities('library')}} and the unavailable lights throw an error
would have hoped the area_entities() to take care of that
I can imagine this will throw errors because there are other entities besides light entities in your library
sure, but the service selects only the lights to act upon
it only throws an error on 1 single unavailable light
does it? If I use light.toggle on a switch, I will get an error?
But why not just target the area?
didnt think of that...
service: light.toggle
target:
area_id: kitchen
even shorter
well library
somehow that wont go at all...hmm
via the UI that works. states the identical error though
the ambilights of my tv are unavailable, because the tv is off. the light is registered as entity though, but cant be toggled. same question: should that not be auto-ignored/rejected
@keen hawk can you try this?
{% set input = state_attr('sensor.daily_energy_price', 'ee') | selectattr('timestamp', '>', now().timestamp()) | list %}
{%- set ns = namespace(cheapest_time=0, cheapest_price=999.00) -%}
{%- for i in range(input | count - 2) -%}
{% set price = input[i:i + 1] | map(attribute='price') | average %}
{% if price < ns.cheapest_price %}
{% set ns.cheapest_price = price %}
{% set ns.cheapest_time = evening_night[i].timestamp %}
{% endif %}
{%- endfor -%}
{{ ns.cheapest_time | timestamp_custom('%Y-%m-%dT%H:00:00') }}
maybe, but that's more an integration thing then
you can filter them out using a template
yeah... I had that, but this would be so much more elegant
thanks for your reply. I don't know why, but it does not seem to be working. When the ESPHome device goes unavailable, and then comes back, it triggers the automation. Here's my automation:
http://pastie.org/p/1bYvfv6Kc5veykzayK6bSR
hmm, i just relized....I have have to put a not_to
its triggering from being available to not available
but not triggering from not_from
lol this is confusing
but I think that is the problem....not_to available, unknown
would this work?
entity_id:
- button.esphome_web_a85214_dyson_humidifier_power_on_off
id: Dyson Humidifier Changed
not_from:
- unavailable
- unknown
not_to:
- unavailable
- unknown
yes, that should work
just to be sure, I filed an issue, there something else being odd, in that we an use the Ui, but not a script using the same yaml..
I have 10 pictures to Level how to make template for water?
@raw jay I converted your message into a file since it's above 15 lines :+1:
anyone can help me?
That's not really related to templating. More of a networking issue
because of this:
No route to resource/endpoint
If the resource that it shows is correct, then it's not the template at fault
Is there a “friendly name” of a state you can call? So for a window sensor the state is on or off, but can you get it to display open or closed by calling on a specific attribute or something?
Nope
- platform: event
event_type: state_changed
event_data:
new_state:
state: grafitti_road
binary_sensor:
- name: grafitti_road
state: "on" ```
Is not trigegred by:
@grave solstice I converted your message into a file since it's above 15 lines :+1:
What have i missed
I don't see any templates here, this is something for #automations-archived
Hello every1. im struggling with the template tile on wear os. can some1 help? i just want to show a sensor value and im getting template error. im typing this: <b>{{sensor.shelly_em_geral_channel_1_power}}</b>
looks like "sensor" is undefined
🤔 it's an event trigger
you need to have a good look at the templating docs
that's not the way to get the state of an entity
try <b>{{states('sensor.shelly_em_geral_channel_1_power')}}</b>
i read the docs but it doesnt explain much. i was reading jinja2 docs now...
thanks. i will try. [EDIT] it worked 🙂
you won't find that in the jinja2 docs, as they are HA specific functions https://www.home-assistant.io/docs/configuration/templating/#states
oh i was looking at the companion apps docs bcause when we click on the '?' icons thats what it opens. thanks. ill take a look
Trying to setup a universal media player. But when overriding select_source with select_source: service: media_player.select_source target: > {% if state_attr('media_player.lg_c2', 'source') == 'Apple OTT' %} media_player.kontor {% else %} media_player.lg_c2 {% endif %} data: source: "{{ source }}"
I get the error dictionary update sequence element #0 has length 1; 2 is required
the template is fine, that's not causing this message
Ok. Guess i have to troubleshoot some other way then.
does that field accept templates?
Everything under data: and target: do
yeah, I realized that a few seconds after I typed it
then something else grabbed my attention
@marble jackal
I have 10 pictures to Level how to make template for water?
tank level
i need template only
❓
hello mr
Ok thanks
I’m still on vaca but I have a few forum posts that calculate the volume of a cylinder on its side
hey there... i'm new here in discord and in HA-community... i have a problem with template-sensor i want to create... what is the best way to get supported?
Hi, welcome. You can just start by asking the question you need help with, and likely someone will be able to answer.
ok, can i also post code-snippets here ?
i want to have a entity, that will display one of 3 states (string) in my dashboard... it should display the state of an smart-plus-sensor, where i plug-in two chargers for e-scooter. the 3 states should be "charging", "standby" and "off".
In the channel description is recommended to use paste sites for sharing code blocks, though a short few lines here doesn't hurt.
ok...
whats a part out of my config.yaml... but this doesn't work fine... i dont understand it... first: is this way the best? should i use config.yaml or sensor.yaml ?
@gist: my state is always goes "boom" 😄
Before putting it into yaml, go to developer tools -> template and try there, it's much faster for iterating.
in dev-tool it works fine... i don't understand that
ok, well that's a good start
you should cast those states to float and compare
you probably don't want string compare for the greater/less than comparisons either
left a comment there
Hello everyone. Would there be a reason why a service call works perfectly fine in the dev tools but the same code doesn't in a button in the lovelace UI? This is template related because the data sent is coming from input_select entities, with plain text both calls work fine.
@lofty mason you're right... it should be a compare of values
@manic niche are you sure the frontend card you're using supports template? most of the main cards do not support templates.
ohhh... i dont know
Oh I didn't read about that. I'll check. I should go through a script calling the service then I guess.
calling a script instead works like a charm. Thank @lofty mason
is it possible to define the color for timeline-view in HA for each state?
now it's likly very "random" colors...
I think you need a state_class to be a valid statistic?
should we repeat the main - trigger key for each trigger? tried to add the sensors below it, but cant get it right, please have a look?
first figured we can move the sensor: block under the same tab as platform: state, as those are the defining trigger id's but that wont work
you should be able to define multiple sensor under one trigger
template:
- trigger:
- platform: state
entity_id:
- binary_sensor.porch_buiten_sensor_motion
- binary_sensor.terrace_buiten_sensor_motion
- binary_sensor.parking_trash_buiten_sensor_motion
to: 'on'
sensor:
- unique_id: last_motion_outside_triggered
name: Last motion outside triggered
icon: mdi:motion-sensor
state: >
{{area_name(trigger.entity_id)}}
attributes: &attributes
history: >
{{(this.attributes.history|default(['Not yet set']))[-8:] + [ this.state ]}}
entity_id: >
{{trigger.entity_id}}
last_triggered: >
{{trigger.to_state.last_changed.isoformat()}}
- unique_id: last_motion_inside_triggered
name: Last motion inside triggered
icon: mdi:motion-sensor
state: >
{{area_name(trigger.entity_id)}}
attributes: *attributes
yes but this is not the case here, I need different sets of triggering entity_id's (have 4 of these )
this would have made most sense to me, but clearly not valid 😉
its not consistent with any of the other integrations, requiring to repeat the top key for each individual set if triggers
template:
- trigger: []
sensor: []
- sensor: []
- number: []
this is how the list looks
you are now indenting the sensor part
which breaks it
the sensor is now defined in your trigger
which makes in impossible to define multiple triggers for one sensor
template:
- trigger:
- platform: state
- platforme: event
sensor: []
this sensor will update on both triggers
Good morning everyone! Is there anyone around that is experienced with splitting the configuration.yaml file into other files?
Yes, but I don't see how that's related to the topic of this channel
I need some help while setting Template sensors within multiple files 🙂
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
That would be more suited in #general-archived I would say
Fair enough! Thanks @marble jackal !
Can I template an entity_id like this?
´´´
- service: scene.turn_on
entity_id: scene.kids_room_{{(states(''input_select.kids_scene_selector''}}
´´´
no
only if you put it under target or data
- service: scene.turn_on
target:
entity_id: scene.kidsroom{{ states('input_select.kids_scene_selector') }}
Thanks 🙂
Hi there. Could someone please help with this. My Energy tarif is as follows: From 0 - 200 kWh price is 0.08, from 200 - 300 price is 0.09 and from 300 onwards price is 0.13. Need to write up a template for cost calculation. I've written the following template:
template:
- sensor:
- name: Energy Price
unit_of_measurement: "AZN/kWh"
state: |
{% if states('sensor.home_energy_meter')|float(0) <= 200 %}
0.8
{% elif states('sensor.home_energy_meter')|float(0) > 200 and states('sensor.home_energy_meter')|float(0) <=300 %}
0.9
{%- else -%}
0.13
{%- endif %}
Will this work correctly? For example say I used 500 kWh this month. How would this be calculated? Will it apply price 0.13 AZN for those extra 200 kWh used on top of 300 only?
I've run it through the templates and it seems to work alright. Just not 100% sure about the math part of energy calculation.
right, I had not considered that indeed. by bad. sorry for that. So that does mean we have to create a - trigger key per set of triggers. ok. next challenge was a bit more complex. It turns out we can not use the this variable on a template trigger sensor last_changed? Ive been going back and forth to have the state of this sensor Not show a timestamp, but get the triggering entity And its timestamp in a set of historic attributes. The only reliable way seems to verbosely use the entity_id of the sensor itself:
before, I did this with the CC variable, but that was heavily reprimanded 😉 I also have an AD app doing this, but that is having some trouble if its own, so I figured why not build the trigger template to doing this
easiest would have been to set the time in the state (as the commented bit shows), but then the history graphs in more info run into space issues. Would be really nice if we could use this.attributes.last_triggered (it is a trigger template sensor after all) or at least this.last_changed (any entity has a last_changed, which is really what I am looking for here). no such thing, so I faked a last_triggered attribute, but even that I can not call using this.attributes.last_triggered
a sensor doesn't have a last_triggered attribute, so that only works for automations
I thought there is a trigger date in the trigger, but that doesn't seem to be the case
but I guess you could use trigger.to_state.last_changed
which you are already doing 🙂
BTW, why are the defaults for you history list items? While the standard history is a string
yes, but that changes the time in the history panel to read the to_state, and not the sensor, so it gets all confused
thats a c&P from when these were in fact lists... Ill remove those
You could build the whole history dynamically as a list though
o? that would be much better, can you give me a nudge please?
btw this is what I had before```
- unique_id: last_motion_sensor_triggered
name: Last motion sensor triggered
icon: mdi:motion-sensor
state: >
{{area_name(trigger.entity_id)}}
{{trigger.to_state.name.split(' sensor Motion')[0]}}
attributes: &attributes
history: >
{{ (this.attributes.history | default(['Not yet set']))[-8:] + [ this.state ] }}
entity_id: >
{{trigger.entity_id}}
last_triggered: >
{{trigger.to_state.last_changed.isoformat()}}```
hence the list in the default
I do something similar here https://github.com/TheFes/HA-configuration/blob/main/include/template/trigger/zone_history.yaml
last_arrival:
person: person.martijn
at: '2023-02-28T22:02:22.734480+01:00'
last_departure:
person: person.martijn
at: '2023-02-28T22:02:07.693854+01:00'
arrival_history:
- person: person.martijn
at: '2023-02-28T22:02:02.738222+01:00'
- person: person.marleen
at: '2023-02-28T18:57:36.099214+01:00'
- [ .. 8 more items here ]
departure_history:
- person: person.martijn
at: '2023-02-28T19:38:03.101676+01:00'
- person: person.marleen
at: '2023-02-28T18:34:10.960711+01:00'
- [ .. 8 more items here ]
icon: mdi:home
friendly_name: Home person history
I'm not completely sure now why do not only have the history
trying to rebuild it now
updated version (also on GitHub)
friendly_name: Home person history
arrival_history:
- who: Marleen
at: '2023-03-01T13:23:22.764623+01:00'
- who: Martijn
at: '2023-03-01T13:22:32.859332+01:00'
- [ .. 8 more items here ]
departure_history:
- who: Marleen
at: '2023-03-01T13:23:19.138472+01:00'
- who: Martijn
at: '2023-03-01T13:22:29.464805+01:00'
- [ .. 8 more items here ]
icon: mdi:home
this.state will not work here, as that will be the previous state
no it does not work unfortunately. thing what is making this complex, is that the history_1 should log the correct time for that entity, and thus gets propagated through the other history items. but it really is the last_changed of the actual sensor, all other formats change the timing in the history_item 1 to something being the last changed of that item, and not the sensor
let me quickly try something
so I am left with the only 100% correct template, the spelled out sensor entity_id
- trigger:
- platform: state
entity_id:
- input_boolean.test
- input_boolean.hide_header
to: "on"
sensor:
- name: Last input boolean triggered
unique_id: 563caa69-50be-4449-8aad-b56879913c4d
state: "{{ states[trigger.entity_id].last_changed.strftime('%X') }}"
icon: mdi:toggle-switch-variant
attributes:
history: >
{%- set what = states[trigger.entity_id].name %}
{%- set at = states[trigger.entity_id].last_changed.strftime('%X') %}
{%- set previous = this.attributes.history | default([]) %}
{%- set new = [dict(what = what, at = at)] %}
{{ new + previous[:4] }}
icon: mdi:toggle-switch-variant
friendly_name: Last input boolean triggered
history:
- what: hide_header
at: '12:48:40'
- what: test
at: '12:48:25'
you can also use where = area_name(trigger.entity_id) if you rather have the area
yes, I can see that working now, is cool. trying to format the layout to read Frontdoor: 14:01:20 and ditch the 'what' and 'at'
@floral shuttle just format the new like you want, i created a dict there, if you just want a string you can do that
{%- set where = area_name(trigger.entity_id) %}
{%- set at = as_local(states[trigger.entity_id].last_changed).strftime('%X') %}
{%- set previous = this.attributes.history | default([]) %}
{%- set new = [where ~ ': ' ~ at] %}
{{ new + previous[:4] }}
you beat me to it, I was testing {%- set what = states[trigger.entity_id].name %} {%- set at = states[trigger.entity_id].last_changed.strftime('%X') %} {%- set previous = this.attributes.history | default([]) %} {%- set new = [what + ': ' + at] %} {{ new + previous[:4] }} and had to walk around the house.. 😉
looks similar 🙂
it does show the ugly quotes though.
note there is also an hour issue.... bottom last_triggered is correct
ah, you need to use as_local
adjusted in my last version
don't think you can do anything about the quotes, it's a string
if you don't want those, you need to go back to your old version with the separate attributes.
yeah that would maybe be easiest. there always a compromise. you version has the state as top history item, which I had before in my configs too, I then though, hey, the state is not history, so lets change that. which then lead me into the timing trouble on those triggers..
also, Since we are not allowed to 'safe' too much history in the state machine, I wonder what would be best: 1 bigger attribute like yours, or 5 smalles ones with a single item..
we are allowed to do anything with the attributes of our own template sensors
if you want to create entities in a core integration you are limited in what you can put in the attributes
but you can also sort them the other way round if you do {{ previous[-4:] + new }}
oh wait, you wanted to omit the state from the history
the issue there is that you don't know what triggered that last state change
the time is in this.state
so if you don't want to include it in the history, and you already have a separate attribute to store the last area or name or whatever, you can also do that
@floral shuttle I converted your message into a file since it's above 15 lines :+1:
template:
- trigger:
- platform: state
entity_id:
- binary_sensor.hallway_door
- binary_sensor.garage_door
- binary_sensor.garage_corridor_door
- binary_sensor.front_door
- binary_sensor.back_door
- binary_sensor.corridor_door
- binary_sensor.stookhok_door
to: 'on'
sensor:
- unique_id: last_door_triggered
name: Last Door triggered
icon: mdi:motion-sensor
state: "{{ states[trigger.entity_id].last_changed.strftime('%X') }}"
attributes:
history: >
{%- set previous = this.attributes.history | default([]) %}
{%- set new = [this.attributes.last_area | default('nowhere') + ': ' + this.state] %}
{{ previous[-4:] + new }}
last_area: >
{{ area_name(trigger.entity_id) }}
oops. sorry.
the advantage of that is that I can &anchor the attributes in other sensors below that (and not have to spell out the entity per sensor)
that last template is nice too, it turns it all around a bit. using the state for the timestamp. will consider that in an additional sensor probably. thanks!
as said, on the moment of the trigger, this.state will be the current state (so before the new state is rendered, so basically the previous state)
so you can use it to generate the history, if you don't want the last update in the state, and in the history as well
have to carefully study this some more, because I was just editing the attributes last (previously history_1) to ```
last: >
{% set stamp = as_local(states[trigger.entity_id].last_changed).strftime('%X') %}
{% set id = state_attr(trigger.entity_id,'friendly_name').split(' door')[0] %}
{{ id + ': ' + stamp }}
Hi, is it possible to template a mqtt sensor?
mqtt:
sensor:
- name: myelectricaldata_year_2023
icon: mdi:flash
unit_of_measurement: 'kWh'
state_topic: "myelectricaldata/consumption/annual/2023/month/3"
I'd like to template 2023 and 3
any way to get the amount of entities in a device? like i have an intergration with a device and that device has 20 entities and sometimes more, how do i get that number?
count your device_entities https://rc.home-assistant.io/docs/configuration/templating/#devices
{{device_id('light.living')}}
{{device_entities(device_id('light.living'))|count}}```
Hello.
I am struggling with templates... Not sure what I'm doing to be fair atm. I have a temp.sensor showing lots of decimals to the value "5.08123841192373257681239" and I want to round it to show only 2 decimal places.
I have found a way how to round the number using this: {{ states('sensor.flexit_outdoor_air_temperature') | round(2)}}
But where do put this? I think I am supposed to enter it in a template in... configuration.yaml(?) not sure. And then how do I actually use it in the card on the dashboard?
I have tried alot of things but I cannot make sense of it. Thanks
iirc you can now use the UI to set the decimal places
go to the settings of the entity
Yeah ok. I cannot see a setting to set the decimal places
later today...2023.3
The problem with your template is that all states are strings
so you are trying to round a string, which doesn't work
oh wait, I think round already does the conversion
No I mean, in template editor in developer tools it shows correct rounded value
but if it is just for display purposes on your dashboard, I would suggest to wait for the 2023.3 release later today
Sorry, I am completely new to HA, I dont even know how to add a template and where to put it. But I have some coding experience so rounding the number was not that hard
add this to your configuration.yaml ```yaml
template:
- sensor:
- name: "Decimal Temperature"
unit_of_measurement: "°C"
state: >
{{ states('sensor.tempsensor') | round(2)}}```
- name: "Decimal Temperature"
Oh really, theres a new release today? 😄
if you convert it to an integer, there's not much left to round
oh yea my bad
float I guess
but like mentioned above, round already does the conversion to number
it's not needed
I would add either a default in the round filter, or an availability template
yeah I think I have it covered in what I mentioned earlier
{{ states('sensor.flexit_outdoor_air_temperature') | round(2)}}
this works
and you need to indent the template under state
template:
- sensor:
- name: "Decimal Temperature"
unit_of_measurement: "°C"
state: >
{{ states('sensor.tempsensor') | round(2) }}
availability: "{{ states('sensor.tempsensor') | is_number }}"
Btw, does it matter where i put it in config file? Like can I put it all the way down or like at the beginning?
you can try around in developer tools> template
btw
it doesn't matter where, but if you already have a template: key somewhere, you need to place it under that key
and only define template: once
Okay, I dont have a template key anywhere. Just started out trying to figure it out today
you can also put them in a seperate file like already exists for automations
but.. tomorrow this will not be needed, as you can round the current value in the GUI
or now already, if you install the beta
on the rounding in yaml: I deleted many many of those in my config yaml files, and only required a few precision settings in the new Frontend... that is a very fine and new feature in HA 2023.3!
it saves a lot of yaml, and hence the risk if typo's... 😉 no more trouble with default values etc etc
Btw, any need to restart Rpi or refresh something to make the template active?
if it is your first template entity you need to restart HA, after that you will have an option to reload them in devtools > yaml
and the code above will create a new sensor, which you can use in your dashboard
so you will have one rounded sensor, and one with all the decimals
Oh, okay. I see
which is another advantage of changing the precision on the actual sensor as of 2023.3
Yeah I guess. Do you know when the new version will be released?
somewhere today, when it's ready
always on the first Wednesday of the month
for a major release. and minor releases during the month
Okay, awesome. I am totally new to HA and Rpi, installed HA this weekend for the first time
Any easy way of converting this to a 'voice assistant' readable value? Current it says ex: 1 dollar dot 55. What can I do to make it show 1 dollar and 55 cents ?
{{ states('sensor.gasbuddy_average_gas_price') | int /100 }}
{% set value = states('sensor.gasbuddy_average_gas_price') | int / 100 %}
{% set d = value | int %}
{% set c = ((value - d) * 100) | int %}
{{ d ~ ' dollar' ~ ((' and ' ~ c ~ ' cent'~('s' if c > 1)) if c) }}
Thank you! Works perfectly
@cursive knoll I converted your message into a file since it's above 15 lines :+1:
hello how to add a picture to this template
- platform: template
sensors:
watertank_card:
value_template: >-
{% if states.sensor.watertank.state | float <10 %}
empty
{% elif states.sensor.watertank.state | float <20 %}
20
{% elif states.sensor.watertank.state | float <30 %}
30
{% elif states.sensor.watertank.state | float <40 %}
40
{% elif states.sensor.watertank.state | float <50 %}
50
this is my template is wrong
- platform: template
sensors:
binary_sensor.20:
value_template: >-
{% if states.binary_sensor.20.state | float <20 %}
20
state_image:
81: local/water/1.png
entities: []
type: picture-glance
entity: binary_sensor.20
Ok I have a new issue. I have a multi state value I want to convert to text with a template.
So the states can 1, 2, 3, 4, 5, 6 and 7 where they each represent a string value. How can this be done?
So far this is what I have:
- sensor:
- name: "OpMdSts"
state: >
{{ states('sensor.flexit_current_operating_mode')}}
- name: "OpMdSts"
I would do that with a dictionary lookup
Yeah, can I make a dictionary in the config file?
- sensor:
- name: "OpMdSts"
state: >
{% set map = {"1": "thing1", "2": "thing2"} %}
{{ map[states('sensor.flexit_current_operating_mode')] }}
Ahh, okay cool
So much to learn, never done yaml before. I have some xml experience but not much. And also almost never used javascript before, but I know some Python and Lua. Steep learning curve I guess. Thank you for helping me!
Check out the links in the channel topic for Jinja syntax. There's a lot of similarity to Python
Allright. Does the Jinja syntax to f.x. button-card addon? Would love to try out the more customizable cards. But so far I haven't tried them out much since I really didn't know what I was doing
are you talking about the custom button card?
"addons" are completely different things
if so, it uses Javascript, and has lots of examples in the documentation
An add-on is a Docker container with tweaks to allow it to be configured in the Supervisor UI. It is only available in the Supervised installs (#330990055533576204 and #330944238910963714) since if you've used any other install method you're able to install software already.
Yeah a bit confused about all the terminology I guess
Anyone? I will re-ask only once and then assume this does not exist (yet) 🙂
what specifically are you looking for? You can template lots of things in an MQTT sensor: https://www.home-assistant.io/integrations/sensor.mqtt/
you mean specifically in the state_topic?
Looks like "no"
This should be the easiest, most obvious thing ever, and I thought I had it working at one point, but it seems to be throwing an error now: {{ max[10,2] }} yields UndefinedError: function object has no element (10, 2). What does that mean and how do I fix the error?
🤦♂️ And, that's why it worked elsewhere, but not here.
Forest, meet trees...
I knew it was simple and obvious, I just wasn't seeing it.
Always check the punctuation
If a sensor has an attribute that returns this kind of array, how do I parse it to only return the value of "id"?
{'Value1': {'added_date': 1677245317, 'id': 60}, 'Value2': {'added_date': 1676604867, 'id': 89}, 'Value3': {'added_date': 1676407928, 'id': 14}}
I need that value to use in a service call
I think maybe state_attr('sensor.xxx', 'attribname').Value1.id
hi all, i'm mathematically challenged here. I'm trying to make a sensor that is based on the value of another sensor. The real sensor outputs a voltage from 0.00to 10.00 V, the new sensor should output a velocity based on this value, where 0.00 V = 0.00 m/s and 10 V = 30.00 m/s, a simple linear relationship
ok, I think I messed this up but here goes
- name: hvac_velocity
unique_id: 2c2ca0b1-9916-467f-99fa-6dbf395a43c7
state_class: measurement
unit_of_measurement: m/s
device_class: speed
state: >
{% set voltage= states("sensor.smart_implant_voltage_3") %}
{% set velocity= {{ (voltage / 10) * 30 }} %}
you didn't convert the state to a float, and you're nesting your template
and you didn't output anything
As TimO pointed out, this will do it:
{{ states("sensor.smart_implant_voltage_3")|float * 3 }}
thank you, all! this works
if I wanted 2 decimal places, is it this?
{{ states("sensor.smart_implant_voltage_3")|float * 3 | round(2) }}
that rounds "3"
{{ (states("sensor.smart_implant_voltage_3")|float(0) * 3) | round(2) }}
You saved me again, thank you
@humble void I converted your message into a file since it's above 15 lines :+1:
how is that related to a template?
maybe it's not...sorry not sure where to ask for help. All of my coding for this integration is in the configuration file. I'll figure it out...
The topic'area' contains multiple months, in the example '3' for this month, next month I want it to take 4 but I am not happy to update this every month for every year...so I take the 'no' ...thanks 🙂
perhaps this will be helpful: https://community.home-assistant.io/t/mqtt-topic-wildcard/389382
Helpful as I did not know this option but it does not return data, will need to dive into this a bit more...thanks !
I have a universal media player where i've said that the state (as an attribute) should be taken from my TV but it seems to take it from the apple tv anyhow. Anyone know why this could be?
not without you sharing the code
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Hi, I have got a power sensor that seems to be a string instead of a float. Is there a way to define it as float a the source?
{{ 'sensor.tasmota_mt681_power_cur' + 1 }} -> TypeError: can only concatenate str (not "int") to str
ALL states are strings
but you are not even getting the state, you are only providing a string with the entity_id
arg
{{ states('sensor.tasmota_mt681_power_cur') | float + 1 }}
^ to actually get the state ^ to convert it to a number
got itn thanks 🙂
so states('sensor.tasmota_mt681_power_cur') is even always a str?
yes
ok thanks
Sorry! Here you go! https://pastebin.com/vuXX5jGD
Howdy
i have a working template sensor, but i got hass errors, Error while processing template:
state is not an attribute of the media player, you need to use https://www.home-assistant.io/integrations/universal/#state_template
what is the actual error
and I think you have your comparisons mixed up
If i just wanted to inherit the state of the tv can i use {{ states('media_player.lg_c2') }}?
Hello, I have a list with strings in it, but I want to change them all to floats (so I can sum them). Is there a filter for that or do I have to do this via a for loop?
@half pendant yes
{% set my_list = ["1", "2", "3", "4"] %}
{{ my_list | map("float") | list }}
{%- set ns = namespace(data=[]) %}
{%for temp in sensor_temp_list%}
{% set ns.data = ns.data + [temp|float] %}
{%endfor%}
{{ns.data|average|round(2)}} ```
I have now this, but I have the feeling it should be simpler than that
ah, perfect thank you
@marble jackal http://pastie.org/p/0m0ePzdPytgIpNbbtJC0pu
maybe a conversion error between float and int ?
proably a typo in the entity_id, so the returned state is now unknown
and you didn't add defaults to your float filters, so it now fails on trying to convert unknown to a float
hi all, maybe a trivial topic: I have a template sensor where I want to read the water temperature only while a filtering pump started running (because before then the measurement does not accurately reflect the temperature of the water in the swimming pool, as the probe is attached to a pipe next to the pump). I currently have the following:
template: sensor: - name: pool_water_temperature state: >- {% if states('switch.ovalesublime_pool_relay_01_01') == 'on' %} {% set res = (states('sensor.ovalesublime_irrigation_ds18b20_2_temperature') | float) %} {% elif states('switch.pool_water_temperature') != 'unavailable' or states('switch.pool_water_temperature') != 'unknown' %} {% set res = states('switch.pool_water_temperature') %} {% else %} {% set res = 'unavaliable' %} {% endif %} {{ res }} state_class: measurement unit_of_measurement: "°C"
this works ok but there is a 5 min period while the temperature is still converging, as the water starts to circulate across the pipe. I would like to ignore those first 5 minutes as well. How can I tell from the template how long an entity is in a given state?
I know there is the ".last_changed" attribute but that doesn't seem to reflect the time in the "on" state
I'd assume the error is related to name: having it's value on the second line w/o a multiline indicator.
ah yes, probably that's it 🙂
maybe he fixed that already
When i run the following code in the template tester in HA UI it works as expected but when i put it in the state_template for universal remote i get unknown. Anyone know why?
{{ states('media_player.kontor') }}
{% else %}
{{ states('media_player.lg_c2') }}
{% endif %}```
I've just run the quick reload yaml from the ui and not restarted HA totally
With the history_stat, how can I count the amount of motion "on" for the past 5 minutes from now? https://paste.centos.org/view/raw/6dd911d0
Just use {{ now() - timedelta(minutes=5) }} for your start. And depending on what you mean by "amount", you currently have it set up for count, which is number of times in that state. There is also "time" which is amount of time in that state
I would like to start heating when I'm in the room for 5 minutes. Still have to figure out what numbers to use as threshold.
Instead of a simple: if motion detected start heating now. Which also triggers when I'm no longer than 2 minutes in the room.
One thing with motion detection.... will it be sensing motion for the entire 5 minutes you're in the room? You might only get a portion of that time as motion, even if you're still occupying it
No, its flips a lot between on/off, even when I'm in range. It clears after 30 seconds, then it waits for new motion, which occurs within 10 seconds or so. Which is why counting the amount is my best bet.
post the entire config
wondering if anyone can help me out with value templates and a JSON sensor? I've spent hour combing through docs and old forum posts, but can't figure this out. I have a JSON sensor which works well trying to get the temperature from a fireboard (wireless grill thermometer) in JSON format, but when I try to use a value_template to return just a single number, I got nothing.
Acatually a complete restart of HA fixed it. Maybe that quick reload isn't 100% yet? Or maybe i just missunderstood it
ok trying to post code but can't figure out discord formatting either
@unique briar I converted your message into a file since it's above 15 lines :+1:
Quick Reload does not necessarily reload everything, it only supports integrations that can reload YAML config on the fly
for the code I posted, I get the error: Template variable warning: 'list object' has no attribute 'temp' when rendering '{{value_json.temp}}'
but I get all the attributed correctly as expected: [{"temp":73.2,"degreetype":2,"channel":1,"created":"2023-03-01T21:55:35Z"}]
@unique briar I've really got no idea but you are fetching a file called temps.json in the resource field and then trying to send in a file called value_json.temp in your value_template field
Template variable error: 'temps' is undefined when rendering '{{temps.temp}}' when changing that. My assumption is that value_json.temp should get the value of the FIELD temp in the JSON that is returned, but i'm wondering if that's wrong.
your template should be {{ value_json.temp }} if "temp" is a key in the value_json dictionary, assuming it is a dictionary.
and, going to that resource, it is not a dict, it is a list
ah okay, so i'd need to grab the value based on index position in the list then?
that makes sense, since i'm seeing Template variable warning: 'list object' has no attribute 'temp' when rendering '{{ value_json['temp']}}' when i try it a different way
sensor:
- platform: rest
unique_id: fireboard
name: fireboard
resource: https://fireboard.io/api/v1/devices/a5b139fa-0d19-44b2-b6f1-d31fd8afeab4/temps.json
method: GET
headers:
Authorization: Token cc0da08db376820b638e1f10c6bee466019f45bc
scan_interval: 30
json_attributes_path: '$.0'
json_attributes:
- "degreetype"
- "temp"
- "channel"
- "created"
device_class: temperature
value_template: '{{value_json[0].temp}}'
what's fun there is that the list is seemingly returned in a different order every time
is it possible to sort the list before processing? do standard python methods for lists work here?
[{"channel":1,"created":"2023-03-02T14:05:53Z","temp":68.2,"degreetype":2}]
[{"temp":68.2,"created":"2023-03-02T14:06:03Z","degreetype":2,"channel":1}]
two logs seconds apart
if you just want the temperature, sure, you could make a template that grabs the correct temp
temperature is really all that I care about to be honest
timestamps should come in automatically, degreetype is just F so I can set that using unit_of_measurement and i'm only using the one channel
oh, that's what you meant by order
yeah, that doesn't matter
that's a dictionary
well a list with a dictionary inside it
this means list []
this means dictionary {}
a populated list is [4, 3, 5, 2, 1 ]
if that order changes, then you're SOL
you currently only have [{...}]
the first item is {...}
okay, what about something like "{{ value_json[0].temp}}"