#templates-archived
1 messages · Page 60 of 1
sounds pretty logical! thx
sorry, if i wasn't clear enough, i want both the id and the friendly name: so like { "entity_id": "friendly_name" } or { "entity_id": ..., "friendly_name": ...}
Theres no 1 liner that will make a new dictionary like that. You can use expand on the list of entities to get state objects which will contain both pieces of information
how is it so hard to get a informative list from the api
ideally i need a dict like ```json
{
"<integration_id>":
"name": "<integration_name>",
"devices": {
"<device_id>": {
"name": "<device_name",
"entities": {
"<entity_id>": "<friendly name",
...
},
...
}
},
...
}
Then you’ll need to use a few namespaces. But keep in mind, there can be multiple entities per device and that structure doesn’t support that. You’ll be overwriting entities
Is there a reason you need that structure? Seems like an odd requirement
@spice current ^
isn't that the most basic thing every api should have? list me everything in an easily processable structure?
it has a dict of entities so why would it overwrite?
Yeah, and you can get that from templates easily. But not in that format you want
Because your keys are identical. So each time you add the key, it’s going to overwrite the previous. You probably are missing a list in your structure
If you want entities in an integration, use integration_entities
If you want devices, you can iter the states object to get all device ids
If you want device entities, you can use device_entities
If you want your structure, you have to build that. Otherwise use built in methods I just described
the entity ids are unique tho? there can't be more than one "sensor.sensor1"?!
Right, but that’s not your key
"<entity_id>": that looks like a key to me
Regardless, if you want a custom structure, you have to build it
Also keep in mind, if you use all dictionaries, everything will go slower instead of lists because you won’t be able to use generators to filter down.
what would be your suggestion then?
Use the built in methods
Don’t hold yourself to an odd structure. Only access what you need, when you need it
What’s the end goal?
Like, full end goal
Get a list of all entities, of all devices, in all integrations
For what?
that is the end goal
to have a dict that many other tools and script can use and that i can even use myself. in a perfect world this would just be in the api and would not require hacky proxy php scripts
Well first and foremost, yaml entities typically don’t report what integration they come from. So that’s already a no go
they would just go in a "Unknown" integration group then
If you have access to the hass object, then you can just use its functions.
For templating, you have to use the built in methods.
Php scripts are most likely using what the frontend uses
Which would be websockets
Trying to format the output of a sensor which has a state of 2023-11-22T16:34:00+00:00
After searching I found some info that lead me to use:
{{ as_datetime(states('sensor.happyours_south_shore_last_rain')) - now() }}
Which outputs:
-3 days, 17:41:59.668721
How do I truncate it in the template to be just display 3 days?
this will give you lots of freedom: https://github.com/TheFes/relative-time-plus
but you can proably easily do exactly what you asked for with
{{ (now() - as_datetime(states('sensor.happyours_south_shore_last_rain'))).split(', ')[0] }}
'datetime.timedelta object' has no attribute 'split'
you could also do this:
{{ (now() - as_datetime(states('scene.new_scene'))).days ~ ' days' }}
This give me '2 Days' and should be 3
{{ (now() - as_datetime(states('sensor.happyours_south_shore_last_rain'))).days ~ ' days' }}
After I install Relative Time Plus are the commands just available in the templates?
the instructions have examples....
Ended up with this, and also got 2, 22nd to the 24th must be 2. LOL
{% from 'relative_time_plus.jinja' import relative_time_plus %}
{{ relative_time_plus(states('sensor.happyours_south_shore_last_rain'), parts=1 ) }}
Thank you
@midnight hollow I converted your message into a file since it's above 15 lines :+1:
Looks like the bot messed up the first line of my previous message and converted my message to a file. You can ignore this. I'll go post it in the community forum.
{%- if i.attributes.device_class == "power" -%}
{%- if i.attributes.unit_of_measurement == "W" -%}
{%- if i.state | is_number -%}
{{ i.entity_id + " - " + i.state}}
{%- endif%}
{%- endif%}
{%- endif%}
{% endfor %} ```
Hey, how can I sort this list by the i.state (value in W)
"{{ (lux_now - lux_min) / (lux_off - lux_min) * 100 }}"
this calculates the percentage of a value inbetween 2 values. But it can go past 100% and below 0%
How can i restrict this to 0 and 100?
with if/else, or is there some min() max() i dont know of
As states are strings, you need to first convert all states to numbers to sort them
BTW, you can do all those if statements outside you for loop
| selectattr('attributes.device_class', 'eq', 'power')
| selectattr('attributes.unit_of_measurement', 'eq', 'W')
| rejectattr('state','in',['unavailable','unknown','none'])
)
%}
{{ mylist|map(attribute='entity_id') |list}} ```
this is my recent code, but still only sorted by strint and not numeric
{%- for i in states.sensor | selectattr('state', 'is_number') | selectattr('attributes.device_class', 'eq', 'power') | selectattr('attributes.unit_of_measurement', 'eq', 'W') -%}
{{ i.entity_id + " - " + i.state}}
{% endfor %}
{{ ([0, (lux_now - lux_min) / (lux_off - lux_min) * 100, 100]|sort)[1] }}
{%- set ns = namespace(sort=[]) -%}
{%- for i in states.sensor | selectattr('state', 'is_number') | selectattr('attributes.device_class', 'eq', 'power') | selectattr('attributes.unit_of_measurement', 'eq', 'W') -%}
{%- set ns.sort = ns.sort + [ dict(entity=i.entity_id, state=i.state | float) ] %}
{% endfor %}
{%- for i in ns.sort | sort(attribute='state') %}
{{ i.entity }} - {{ i.state }}
{% endfor %}
when setting the state to this.state in a template, is there no update for last_updated?
last_updated is only if there is some change of state or attribute.
ok thanks
and by change you also mean, it checks the values if they are same or not?
believe so
If the state value changes, both last_updated and last_changed will be updated.
If the state value stays the same, and only an attribute value changes, only last_updated will change.
If nothing changes, both will remain as they were
ok thanks
I use the following template which seems to have a problem with the this.state usage. The template work fine but sometimes the value seems to be doubled.
@cerulean karma I converted your message into a file since it's above 15 lines :+1:
I think it is a problem with the this.state in the else
is it possible to not change/return anything in a valid way?
instead of returning this.state I would prefere to do nothing
those are the same thing
so returning this.state does never update a value or last_updated, right?
because the value stays the same
in my template here it could explain the double of the value if it updates last_updated
Hey, i am in need of some assistance with setting up my aircon damper controls, essentially i would like a slider that opens the zone dampers to the specified value, but will also need a way for it to show the current value on the slider if its sent via the aircon touchscreen.
I can call a service to open the damper via a button but dont see any way of building out a slider for it.
climate.living attribute airflow_max: dictates the damper open percentage.
Can anyone point me in the right direction?
Can anyone help me write this template properly so the values do not collide because they are both less or more than and so on..... Now for example, == 0 and <=50 is the same thing
icon: |
[[[
if (entity.state == "0"){
return 'mdi:volume-low';
} else if (entity.state <= "50"){
return 'mdi:volume-medium';
} else {
return 'mdi:volume-high';
}
]]]
```
That is JavaScript and belongs in #frontend-archived
ah ok 🙂
You need to use something like parseFloat()
I'm trying to figure out how to make a "Something is wrong" sensor. I know I can make a template sensor with a big IF statement to check the states/attributes that I want to keep an eye on. While this works, this will only give me an Okay/Not-Okay status.
- Should I be using triggers instead of an IF?
- How can I "store" an attribute to say what the problem is?
- Should I just put the IF in an attribute and make a list or string there? State )and icon) could just check the attribute at that point using
this.attributes.xxx.
I would do the last one and use the state for okay/not okay and the attributes to indicate the state of individual things
So, I should make an attribute for each thing it is checking (returning Okay/(something other than okay)? How could I easily get the state to check all the attributes without having to hard-code each one?
something like {{ "OK" if this.attributes.values()|reject('eq', 'OK')|list|length == 0 else "Not Okay" }}
Beating my head against the wall...
sample yaml:
{% set _nameMap = {'_rgb': [{'aliceblue': [240, 248, 255]}, {'antiquewhite': [250, 235, 215]}} -%}
How do I extract that rgb number list when I have the actual name, like 'aliceblue' or something. I can see it with
{{ _nameMap._rgb.0 }}
but not the name.
I have control of the json format if there is a better way to store that. The whole list is long, it's the entire name to rgb color map...
{% set _nameMap = {'_rgb': [{'aliceblue': [240, 248, 255]}, {'antiquewhite': [250, 235, 215]}]} -%}
{{ _nameMap['_rgb'].0['aliceblue'] }}
you were also missing a ] in the _nameMap line
Ya, I shortened the list, but the list I have has the syntax.
The problem is I don't know if it's 0 or number 129, Do I have to parse the number out first?
if you don't know...
how do you know?
what do you mean by "parse the number out"? what number?
I will know the list nales and stuff and the name, not the number
why is it a dict in a list? are there more list items?
I'm still not following how you plan to arrive at the "0" or "129" or whatever, if you say you don't know what it is
in yaml:
_nameMap:
_rgb:
- aliceblue:
- 240
- 248
- 255
antique_white:
- 250
- 235
- 215
- are there other list items here?
you mean the name could be in any of the items in the list?
ya. I'll have some form of json saving all the data, I can change that to whatever... (This may be my problem actually, open to changes)
what is there in those other list items then?
There are the enture color names list, like 100 or do names and rgb codes from here:
https://github.com/home-assistant/core/blob/dev/homeassistant/util/color.py
yeah, okay, but I assume they are all in that first list item
yes
So I don't think you need a list there
Another function is to return a random color name, so that was why the list.
you can still do that without the list
{{ {{ _nameMap['_rgb'].keys() | random }}
that will give a random color (without them being in a list item first
noce That works
{% set _nameMap = {'_rgb': {'aliceblue': [240, 248, 255], 'antiquewhite': [250, 235, 215]}} -%}
{% set color = 'antiquewhite' %}
{{ _nameMap['_rgb'][color] | default([]) }}
and while creating that, I see you actually had every color in a list item. I thought you had the whole dict in the first item, but you had each color in a separate list item
that could also work, but I think this is easier
with your previous setup (this can maybe be simplified, but this was the first I could come up with myself):
{% set _nameMap = {'_rgb': [{'aliceblue': [240, 248, 255]}, {'antiquewhite': [250, 235, 215]}]} -%}
{% set color = 'antiquewhite' %}
{% set color_dict = _nameMap['_rgb'] | select('contains', color) | first | default({}) %}
{{ color_dict.values() | first | default([]) }}
OK. Taking this and building...
hmm, that second approach doesn't work if there is also a color blue for example. It will retrun the rgb values for aliceblue then as that contains blue as well
either use the dict without the list, or use a named dict per list item
{% set _nameMap = {'_rgb': [{'color': 'aliceblue', 'value': [240, 248, 255]}, {'color': 'antiquewhite', 'value': [250, 235, 215]}]} -%}
{% set color = 'antiquewhite' %}
{{ _nameMap['_rgb'] | selectattr('color', 'eq', color) | map(attribute='value') | list | first | default([]) }}
RobC This is what I came up with for the "There's a Problem" sensor.
There are more attributes; just left them out of this post. I also had to change the length to 2 to account for the friendly_name and icon attributes. I made a simple state-change automation using this sensor. Right now it just turns on a light to red (off when states returns to OK). I'll probably add more to it such as TTS and phone notifications.```yaml
template:
- sensor:
- name: problem
unique_id: problem
device_class: enum
state: "{{ 'OK' if this.attributes.values() | reject('eq', 'OK') | list | length == 4 else 'Problem' }}"
icon: "{{ 'mdi:check' if this.attributes.values() | reject('eq', 'OK') | list | length == 4 else 'mdi:alert' }}"
attributes:
freezer: "{{ 'OK' if (states('sensor.kitchen_freezer_temperature') | float < 30) else 'Freezer too warm.' }}"
internet: "{{ 'OK' if states('binary_sensor.internet') else 'Internet is down.' }}"
- name: problem
NOTE: For the `state` and `icon` the number used is the number of attributes it is supposed to ignore. By setting the number to 4, the template will ignore the attributes for options, device_class, icon, and friendly_name.
that won't alert you if just one of those items is broken, though
Yeah. I thought about that. Figured I would have to expand the attribute's checks. Particularly if the device is unavailable... Maybe being able to expand the possibility of an OK, Warn, and Alert-type status. Alert for unavailable device but Warn for low battery.
oh, nevermind. I misread it
Oh no. I mean, you're right. I just haven't gotten to that point with it yet.
In this case, it is looking for attributes that are not OK. Set freezer state to 35*F in Dev Tools: icon: mdi:alert friendly_name: Problem Sensor freezer: Freezer too warm. refrigerator: OK internet: OK unraid: OKProblem state triggered and automation fired. (Temp sensor updated and cleared everything and returned all to OK.)
That line just doesn't make sense to me. Let's say they're all "OK". So you're rejecting all that are "OK", leaving none, then checking the count against 2, which will fail (because the length is now 0), so you'll report "Problem"
It counts the icon and the friendly_name attributes as not OK.
Better code would be to reject those I suppose but the 2 just made things shorter.
yeah, it's fine
hello. i have an automation (actually a few) that i would like to trigger on the state change of ANY members of a group of groups (old style groups, nested). i've come up with this template, which appears to work in the template dev tool, but it throws "is neither a valid entity id or a valid uuid" for the entity field: entity_id: "{{ expand('group.all_door_sensors') | map(attribute='entity_id') | list }}"
you can't template that field
well, that sucks
😄
also explains why i have been beating my head on the wall for a day trying to figure it out. thank you, @inner mesa
smack self with clue-by-four after looking carefully at what he's trying to do v actually doing 🤦♂️
hello guys,
i'm very bad at templates so i'm asking you guys. i have a sensor that holds the time of the next bus. i would like to make a template that tells me in how many minutes the next bus comes. so "basically" sensor.time - sensor.nextBus
{{ (states('scene.new_scene')|as_datetime|as_local - now()).total_seconds()//60 ~ ' mins' }}
okay... wait should scene.new_scene be replaced with the bus sensor?
I think I have a rough idea but I'm getting this Error: AttributeError: 'NoneType' object has no attribute 'tzinfo'. So is the Bus Sensor in a wrong time format? When I look at the sensor in the Dev Tool its in hh:mm
NoneType sounds like the object is empty but... Well its not
Use today_at() around the states() call
And then remove as_datetime|as_local
{{ (today_at('11:00') - now()).total_seconds()//60 ~ ' mins' }}
Hmm... -1390.0 mins sounds kinda wrong 😅
Could the problem be that the next bus comes past 12 right now?
It expects 24 hour time
okay, I see
Can show me how to display the raw value of the sensor if the calculated time is 0>?
or is converting the sensor to a different format that avoids this problem easer?
@rough delta
It depends on how you define “add a month”. Here’s what I came up with if the rule is: keep the day number the same or limit it to the max days in the next month. So adding a month to Jan 31 gets you Feb 28:
{% set date = as_datetime(states('input_datetime.trigger_date')) %}
{% set end_of_next_month = (date.replace(day=1)+timedelta(days=63)).replace(day=1)-timedelta(days=1) %}
{{ (date.replace(day=1) + timedelta(days=32)).replace(day=min(date.day, end_of_next_month.day )) }}
dont say I dont listen...
Ive moved all of those amazing options to card_mod... was a bit tricky but all in all, seems to ok. I've released a custom integration replacement to only set icon_color option now, and we can use that in customize And in jinja templates 🙂 they're too good to do away with... and even found a way to template the entity_pictures https://community.home-assistant.io/t/card-mod-add-css-styles-to-any-lovelace-card/120744/5412?u=mariusthvdb
Hey Guys, I created a template which is working perfectly fine, however it creates a log entry: "TemplateError('ValueError: Template error: int got invalid input 'unknown' when rendering template '{% set output..." Any ideas what I might be doing wrong here?
Code of the template:
{% set output = namespace(sensors=[]) %}
{%- for luftbefeuchter in states | selectattr('entity_id', 'search', '_luftbefeuchter_power') | rejectattr('entity_id', 'search', '_luftbefeuchter_power_outage_memory')-%}
{{ luftbefeuchter.state | int < 1 }}
{% if luftbefeuchter.state | int < 1 %}
{% set output.sensors = output.sensors + [luftbefeuchter.name|replace(' Luftbefeuchter Power','')] %}
{% endif %}
{%- endfor -%}
{{output.sensors | join(', ')}} sind aus
@vagrant kiln Your template is rendered when some of the source entities are not ready yet (eg after a reboot)
It then tries to convert "unknown" to an integer, which will fail
easiest is to add | selectattr('state', 'is_number') to the first line of your for loop
Hey,
does someone know why the number is not rounded when I put text after it?
{{ (today_at(state_attr('sensor.barenkrog_kiel_to_kiel_hbf', 'next')) - now()).total_seconds()//60 | round(0) }} Mins
It works without the "Mins" after it
you are only rouding 60
Ah okay the brackets did the tick. Thanks a lot :)
@thorny snow I converted your message into a file since it's above 15 lines :+1:
@thorny snow
{{ state_attr('sensor.xyz', 'products') | selectattr('id', 'eq', 1) | map(attribute='available_amount') | first | default }}
change sensor.xyz to whatever your entity_id is
@mighty ledge Thanks a lot for your answer and the mini masterclass in one line, it's a great example for me to understand how it works and the posssibilities ! thanks again
Yes
Hello - template noob here. How or even can I get a date range from a sensors state? It's a daily Kwh sensor that resets each day. I want to get the month total so I can calculate the total month cost so far.
You can do that by creating utility_meter that is fed by your daily kWh sensor. Try #integrations-archived if you need help with it.
Ah ha yea makes total sense. Thanks
How can I create and merge multiple lists, like this and merge them all to one list?
{{ expand(states.light, 'light.lys_ute_') | map(attribute='entity_id') | list }}
I found the expand command filters out the second clause light.lys_ute_ and I need to filter out more than one; light.lys_ute_ AND light.shelly_ AND light.cam_ and so on. Meaning I need to list all light.but not certain patterns of entity ID´s
You don't need expand...
{{ states.light | rejectattr('entity_id', 'search', 'lys_ute_|shelly_|cam_') | map(attribute='entity_id') | list }}
I want to use the following template in association with the input_datetime.set_datetime service.
{% set end_of_next_month = (date.replace(day=1)+timedelta(days=63)).replace(day=1)-timedelta(days=1) %}
{{ (date.replace(day=1) + timedelta(days=32)).replace(day=min(date.day, end_of_next_month.day )) }}
The template works fine in the 'Developer tools' 'Template editor', but not within the automation I'm using it in.
The Action code set I'm using is:
service: input_datetime.set_datetime
target:
entity_id: input_datetime.trigger_date
data:
date: >-
{% set date......}}
Is this the correct way to insert the template, or is the template not working because I should be using the timestamp method?
Ah... I was using the wrong method for the object type. Using datetime works a treat.
Hi, I just notices my last year working template now is not. it is a binary sensor:
kerst_seizoen: friendly_name: Kerst Seizoen (1 dec - 15 jan) value_template: > {% set today = states('sensor.date').split('-') %} {% set month = today[1]|int %} {% set day = today[2]|int %} {{ month == 12 and day >= 1 or month == 1 and day <= 15 }} winter_seizoen: friendly_name: Winter Seizoen (15 oktober - 15 maart) value_template: > {% set today = states('sensor.date').split('-') %} {% set month = today[1]|int %} {% set day = today[2]|int %} {{ month == 10 and day >= 15 or month == 3 and day <= 15 }}
What's wrong here?
Where do I need them? And why did they work well last year?
Can you possibly help me with the correct syntax 🙏
{% set date = now().date() %}
{{ date.replace(month=12, day=1) <= date <= date.replace(month=1, year=date.year+1, day=15) }}
although, that may not work
Like this: ?
kerst_seizoen: friendly_name: Kerst Seizoen (1 dec - 15 jan) value_template: > {% set date = now().date() %} {{ date.replace(month=12, day=1) <= date or date <= date.replace(month=1, day=15) }}
this instead
{% set date = now().date() %}
{{ date.replace(month=12, day=1) <= date or date <= date.replace(month=1, day=15) }}
of course it will
it's not december 1st yet
it's not december 1st anywhere in the world yet
🤷♂️ OMG... I'm staring blind here...
It works well now 🙂 changing the date... it's because I had 2 sensors and I was under the assumption that I was "playing" with the 2nd one...
Now my conditional cards all work well again, THANKS!!!!
I mentioned you on the HA forum, I know it's "not done", but that is my way to express my gratitude. Thanks!
Afternoon guys!
Simple question
{{ is_state('sensor.laundry_shortcut_button_action', none ) }}
{{ states('sensor.laundry_shortcut_button_action') }}
Result of the second template is 'none', but first one is 'false'.
Wondering how to make the first one "true".
maybe {{ is_state('sensor.laundry_shortcut_button_action', 'none' ) }} ?
{{ is_state('sensor.laundry_shortcut_button_action', '' ) }}
{{ states('sensor.laundry_shortcut_button_action') }}
that's the right one. it's just an empty string
thank you
@harsh coyote I converted your message into a file since it's above 15 lines :+1:
it short circuits the test and only listens for the things it needs to
based on the current states
is_state('input_boolean.xxx', 'on') is a bit more compact, BTW
my guess is that none of those first three entities are currently on, so there's no point looking at the other half of the 'and"
I would agree, except that master_bedroom_heat is one of the 'or' conditions, and is apparently not listening for it
That was the source of my question, sorry, I should have been clearer
yeah, I didn't pay close enough attention 🙂
so maybe that one is already on and it's just looking at the others? they key is going to be the current states
Hmm, ok, I'll dig into it. Thank you
Ok, weirdly, moving to is_state... convinces it to listen to everything 🤷♂️
it's not weird, it's because you're using or
if you have an if statement thats x or y or z or a and x is true, then jinja won't even look at y, z, or a. Making it only listen to x
if they are all false, it'll force the template to look at all 4.
that's just how code works btw
e.g.
both of those are off, it only see's the first because the 1st statement resolves true satisifying the or statement
if you break them up into separate lines, then it'll look at both
same logic, but the code has to execute a and b before it checks a or b. Therefore it will always be listening to both
@inner mesa ^
I understand how short circuiting works. Perhaps the confusion is that I would expect This template listens for the following state changed events to be talking about all things relevant to the template, not just the things that happen to be relevant right now, based on current state.
I guess it's smart enough to know that it doesn't care if master bedroom changes, because it won't affect the result. So it doesn't even wake up for it.
neat
Also, I'm not clear on how a list of states(...) == 'on' , chained together by or, and a list of is_state(... 'on') chained together by or would evaluate differently, but the latter reports that it is listening to all four states, while the former does not
did one of your states change while you were typing it? maybe the heat turned off
Not as far as I can tell, no, but I can't guarantee it
Anyway, I have it working, even if I'm a bit confused. Thanks for your help 🙂
I find is_state also doesn't listen for entities after the short circuit.
I guess the confusion is just that I wouldn't expect it to short circuit when describing the template as help text. Evalution, sure, but not in the 'here are the entities your template listens to' bit.
It won’t.
That’s the thing, you’re thinking of it in terms of templates, when it’s just what code does. The states function registers the entity id to the template, so it knows what to listen to for state changes. If the code doesn’t execute the states function, it doesn’t register it. Simple as that.
Fair enough, thanks for the explanation. Just my two cents, but this looks like help text to me, so I would expect it to be generic, maybe there's some way we could make it clearer 🤷♂️
It is generic, it displays what will update the template
If the code doesn’t register the entity_id, it won’t trigger updates
Again, you can’t think of it as “this is in the template, it will update it”. You have to think of how the code executes. It’s a language, this is a scenario where you’d need to know those finer details to understand what’s happening
Ok, thank you
as soon as your first part is false it will start listening for state changes of the 2nd part.
But as long as the first part remains true it doesn't care about the 2nd part, it's not relevant
Is there a temple for icon that just copies an entity icon?
For exemple ...
And template sensor that would have the same icon as a media player ... whenever the icon changes the temple would change too.
So I didn't have to choose an icon for each state .
Only if there is an icon attribute. My media players don't have such attribute.
I'm trying to calculate my natural gas fees. I have a smart meter which sends back the usage, and I already have a 'daily gas usage' entity that's working. Now I want to take that daily value and calculate my fees like this:
sensor:
- platform: template
sensors:
multiplied_sensor:
friendly_name: "Multiplied Sensor"
value_template: "{{ ((states('sensor.gasverbruik_dag') | float * 1.32802) + 0.79935) | round(2) }}"
(1.32802 and 0.79935 are the variable and fixed fees respectively.)
Unfortunately it's not working and I get the error:
Sensor None has device class 'monetary', state class 'total' unit '€' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'sensor: - platform: template sensors: multiplied_sensor: friendly_name: "Multiplied Sensor" value_template: "0.8"' (<class 'str'>)
Are you by chance sticking that yaml into the form for a helper template?
no that's not right.
oh my bad, I'm just starting out
the only part that should go in there is the {{ ... }} part
the rest of all that is for defining a template in your config.yaml
lifesaver! thanks a lot
Another question, I created a text helper where I enter the fees, but they don't become available when I want to use them in the template
Is there another, perhaps better, way to define the fees in some sort of variable?
I would have used a number instead of a text, but otherwise no that's probably the correct way to go about it.
why do you believe they "don't become available"?
The weird thing with number is that it doesn't give you the option to just set a number. There's a min/max which I don't need. And I fear accidentally changing it cause it also displays a range slider.
I'll try again, I think I may know now what I did wrong before
yes an input_number is intended to be somewhat dynamic, so it doesn't ask you to pick the value when you create it
you can set it in the UI at any time after it is created
you could also create a template sensor that just returns a fixed value if you wanted something a little more static.
hmm and that would simply be: {{ 1.32802 }} ?
an input number can also be mode: box if you don't like the slider, then you get a textbox
yes that ought to work
I don't want it to be editable at all. Except in the template settings.
Should I reference to the fee like so: states('sensor.tarief_gas_variabel')?
it stops working after I do that
{{ ((states('sensor.gasverbruik_dag') | float * states('sensor.tarief_gas_variabel')) + states('sensor.tarief_gas_vast')) | round(2) }}
the template is probably a string, so you'll need to convert it to float also
{{ ((states('sensor.gasverbruik_dag')|float * states('sensor.tarief_gas_variabel')|float) + states('sensor.tarief_gas_vast')|float) | round(2) }}
damn you're right
all states are always strings in HA
I'll remember that
(attributes can be numbers or other types)
is float the ideal method to convert it to an int?
I know in other programming languages you can do something like $number = (int) $input
and it gets stored as int
just curious
|int is the ideal method to convert to an int 🙂
|float is the way to convert to a float
gotcha thanks
JavaScript templates are for #frontend-archived . This channel is only for Jinja templates
JavaScript is only used on the frontend, hence it is also discussed in #frontend-archived
Jinja templates are used for template entities, and in automations, scripts etc, for more info there are some links in the topic description and pinned posts
Hi,
I had the following in my configuration.yaml for a test:
device_tracker:
- platform: ping
hosts:
dyson_hc_ping: 192.168.2.204
count: 2
scan_interval: 30
I've deleted that and rebooted twice and still the entity "dyson_hc_ping" appears in Devices&Services/Entities (as readonly).
How can I get rid of this as it was deleted from the yaml?? Makes no sense to me.
This is unrelated to this channel, try #integrations-archived or #beta if it is related to the 2023.12 beta changes for ping
done, thx
A quick question: How can I change the order of the [:25] and the replace function in my template? I want to first remove the "(Remaster)" from the song title and then, cut off any characters after 25.
{{state_attr('media_player.hauptschlafzimmer','media_title')[:25]|replace("(Remaster)", "")}}
{{ (state_attr('media_player.hauptschlafzimmer','media_title') | replace("(Remaster)", ""))[:25] }}
Thank you! Can I also trim any spaces from the end of the song title that has been cut down to 25 characters so that I will have "Cut song title..." Instead of "Cut song title ..."
Use |trim
Thanks that was easy. 🙂
There are more gems in the links in the channel topic 🙂
Hoping someone can help, trying to use the new weather.get_forecast with a template weather card. I understand I need to create a new template sensor with the forecast as an attribute. however I've tried using the example here https://www.home-assistant.io/integrations/template/#trigger-based-handling-of-service-response-data and the entity is blank. The state is "unknown" and there are no attributes. Here's my config (I have an include in my config.yaml): https://gist.fuzzymistborn.com/FuzzyMistborn/c13e27752d0a4a6a8044ba014675621f.git
when i do a test with the service call in the HA UI i get a response no problem
nevermind....updating now, was blank on startup
so
- trigger:
- platform: time_pattern
hours: /1
- platform: homeassistant
event: start
thanks!
yep
that was only mildly infuriating lol. nothing in log, nothing anywhere
well your time_pattern is on the hour, so it'll only trigger on the hour
that was the example in the docs (i mostly use NodeRed so I don't use automation stuff often)
Is there an easy way to template a sensor that has a number of sub attributes? I have sensor.tides_gulfport that has a state of High tide at 12:56 AM and bunch of attributes:attribution: Data provided by NOAA
next_tide_time: 12:56 AM
last_tide_time: 9:12 AM
next_tide_type: High
last_tide_type: Low
high_tide_level: 2.365
tide_factor: 14.7743247561542
low_tide_level: -0.428
friendly_name: Tides Gulfport
Can they create useable sensors with a wildcard or something?
Can they create useable sensors with a wildcard or something or are there 4-5 lines per attribut that need to be coded?
Or one parent entity with the sensors in it
Each sensor needs to be created separately, but usually don't need to surface all of them. Many parts of the system can access attributes directly
it's the whole "usable sensors" that I'm trying to unpack.
it sounds like you already have a sensor with a bunch of attributes, all perfectly usable
I was trying to graph some of them on the front end and I had to manually template them to be useable
Yeah, not everything can access attributes directly. For the history graph card, for instance, you would need to surface the attributes you care about as separate sensors
and no, there's no way to say "make all these attributes separate sensors"
How would I display sensor.tides_gulfport attribute next_tide_time without adding all of this:
tide_gulfport_next:
friendly_name: "Next tide"
entity_id: sensor.tides_gulfport
value_template: "{{ state_attr('sensor.tides_gulfport', 'next_tide_type') }} tide at {{ state_attr('sensor.tides_gulfport', 'next_tide_time') }}"
icon_template: "{% if is_state_attr('sensor.tides_gulfport', 'next_tide_type', 'High') %}mdi:waves{% else %}mdi:wave{% endif %}"
In a front end lovelace card
lots of cards can display attributes dirctly
if you want to customize wording, you can use the markdown card, for instance
so to display the attribute with the entities card you have to drop to yaml editing?
seems that way
My entire UI config is in YAML, so 🤷
type: entities
entities:
- type: attribute
entity: light.test
attribute: entity_id
if the UI doesn't support fields, your only recourse is yaml
but it still live-updates the display with your changes
I am fine dropping to yaml, I just struggle with the 'right' way and context with the official examples. They seem to fall short for noobs like myself
Spend time learning yaml
it's just a data format, once you learn the data behind the format, you can use the HA docs w/o needing examples
this is a step most people skip
I have command_line device setup to toggle the TV power or could use shell_command to control the power but want the button to display the current status, which could be the media player power state or the power usage from another device/sensor. Is that possible? Basically want to have a button that displays the status of the tv and will send the commands to control it based on the status https://pastebin.com/embed_js/mCs6J57c
Can that be done in a switch template?
Can the value_template be an or of two different devices?
like if either of these are true the TV is on
{{ is_state_attr('media_player.tv_family', 'sensor_state', 'on') }}
{{ states('sensor.tp0_5_tv_family_hue_current_consumption') | int(default=0) > 120 }}
I'm having some difficulty in configuring a template sensor to show a non-numerical text status when the device is showing "unknown" instead of a heart rate. With the current configuration, the last known measurement stays on while the device is charging. If i change the "N/A" to a numerical value, that will show - but considering I'm trying to keep track of an infrants HR, thought it best to show N/A when it's charging 🙂
name: "Owlet Heart Rate"
unit_of_measurement: "bpm"
state_class: measurement
state: "{{ states('sensor.owlet_baby_care_sock_heart_rate') if states('sensor.owlet_baby_care_sock_heart_rate')|is_number else 'N/A' }}"
(i want this to be a complication on my watch)
This seems to be working now, value_template: "{{ is_state_attr('media_player.tv_family', 'sensor_state', 'on') }}" would this logic work?
value_template: "{{ is_state_attr('media_player.tv_family', 'sensor_state', 'on') }} or {{ states('sensor.tp0_5_tv_family_hue_current_consumption') | int(default=0) > 120 }}"
I would maybe make an availability template, which makes the sensor unavailable when it is not valid. anything else will mess with like your history charts
you have to write a template, not two templates like that
I was getting there in searching for a solution.. only question - if sensor is unavailable, could i then set a custom status for the complication? ultimately just trying to get away from the circular showing "Unk..."
value_template: "{{ is_state_attr('media_player.tv_family', 'sensor_state', 'on') or states('sensor.tp0_5_tv_family_hue_current_consumption') | int(default=0) > 120 }}"
and that assumes that your media_player entity has an attribute called sensor_state, which seems odd
If you don't care about the numeric features, then you just need a template that doesn't have a unit of measurement.
Then you can just set it to whatever arbitrary text string you want
But you can't like graph it then
media_player.tv_family has state of on/off, is that the same as a sensor state?
a state is not an attribute
in that same line, you're reading a state
states are states
Got it, the media_player.tv_family has a state of on/off how is that evaluated? is that the sensor_state?
I don't know where you're getting "sensor_state" from
it's the same way you got the other state
or is there a media_player_state?
I think you're overthinking this
you wrote states('sensor.tp0_5_tv_family_hue_current_consumption')
Yeah thats a key function that’s needed for tracking. I was trying to figure out how to build a template sensor in the watch complication builder and wasn’t getting very far but maybe that’s the key since it won’t affect the history status
you don't need to try to invent somethign else for the other entity
I guess also I can get history from the actual entity instead of the template sensor
You can have two sensors, a numeric one with unavailable, and a text one that can just show the text of the number or "N/A" or whatever string you like.
Then you can have both.
I want to look at the media_player.tv_family state (on/off) or the value of sensor.tp0_5_tv_family_h* greater that 120 to determine if the TV is on,
You’ve got me going the right path, let me play with it some more. Appreciate the input !
How do I evaluate the media_player.tv_family state in the template logic?
I suggest re-reading this: https://www.home-assistant.io/docs/configuration/templating/#states
And again, you're comparing the state of another entity immediately after the first one. You already seem to know what to do
The answer is as simple as states('xxx') == 'on' or is_state('xxx', 'on')
You're trying you're make the first and second comparison different for some reason, when they're basically the same
Both of these seem to work, which is the right method or is flip a coin?
{{ is_state('media_player.tv_family', 'on' ) }}
{{ states('media_player.tv_family') == 'on' }}
the first one is preferred for reasons that I don't recall
yep, just dropping a hashtag on the measurement lines allowed N/A as a state for the complication. perfect, thanks again
So in the end it's:
{{ is_state('media_player.tv_family', 'on') or states('sensor.tp0_5_tv_family_hue_current_consumption') | int(default=0) > 120 }}
yes
In the switches template can I set an icon or colors based on the value_template result?
No, colors are not supported, only the standard state colors your theme uses
#frontend-archived can help with custom components which do support state based user defined colors
can a static icon be set in the switches template?
yes
it's expecting a string or a template that outputs a string
and https://www.home-assistant.io/integrations/switch.template/#considerations answers your earlier question about is_state
So will my template_value above work since it's output is true?
if it's the state you expect, yes
I'm not commenting on the output of the template, just answering your earlier question
Like this:
{% (is_state('media_player.tv_family', 'on') or states('sensor.tp0_5_tv_family_hue_current_consumption') | int(default=0) > 120,) 'true' %}
I don't know what you're tyring to do there
you didn't need to change what you already had
adding 'true' there is just a syntax error
and you have an extra comma
there's no reason to go beyond #templates-archived message
That returns 'True', looking at the icon_template example I don't understand how to use the value_template in the format in the icon template
I've lost track of what you're trying to do
you're correct that "True" is not an icon
what do you want there?
Trying to do an icon_template using the same logic as the value_template
don't understand the syntax of the icon_template
did you review this? https://www.home-assistant.io/integrations/switch.template/#change-the-icon
it's all just Jinja
all the same
in value_template, you just wanted a boolean value, so outputing the test result was enough. For the icon, you need a string that indicates the icon, so you need to output an appropraite string
in their example, it's looking at the state for cover.garage_door and comparing lookig for open in one part and on in the other
yeah, that's broken
do better than that example 🙂
in any case, point is, use the right logic to output what you want
my logic outputs True, can that be used to set the icon to mdi:television and mdi:television-off as the else?
You can use
{% if <template which ouputs true or false> %}
mdi:icon-when-true
{% else %}
mdi:icon-when-false
{% endif %}
Or is one line
{{ 'mdi:icon-when-true' if <template > else 'mdi:icon-when-false' }}
Don't include the < and >, replace that entire part with your template
I just opened a PR to fix that template example
And now I see where you were getting the whole "sensor_state" attribute thing. That was just some rando example for a fake device.
The idea is that you often use a template switch for a device or other thing that's non-standard and isn't already exposed with a normal switch. So you can accommodate the weirdness
LFG! thank you 🍻
Does anyone have a template I can use as a trigger to trigger at a given date every year? Example, trigger every 1st of December?
{{ now().date().month == 12 and now().date().day == 1 }}
{{ (now().date()|string)[5:] == '12-01' }}
Awesome, thank you 🙂
Option 3
{{ now().strftime('%m-%d') == '12-01' }}
I have a template sensor with 4 or 5 attributes going, because it doesnt fit in the state (max 254chars?)
Do i need to declare variables like {% set x = ...%} at every attribute? or only once on the first line in state:
Can I use templates in 'tap_action' calls?
I have a decluttering card mixed with mushroom-template and want to do something like this, but cant get it to work, any Ideas?*
tap_action:
action: navigate
navigation_path: /lovelace-rom/{{area_name(entity)}}
No, you can't use templates in tap_action
You need to define the attributes under attributes:
bummer, gotta find a smarter way of doing it then ,thanks 🙂 !
Edit: found a workaround, since i'm using decluttering-card i can just send the area-entity as an variable, and use this instead:
tap_action:
action: navigate
navigation_path: /lovelace-rom/[[variablename]]
@shadow gorge I converted your message into a file since it's above 15 lines :+1:
@shadow gorge `
Today is {{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}
Something like that?
https://community.home-assistant.io/t/weekday-and-month-sensor/45678/14
and just do a +1 if you want tomorrow 😄
oh cool. But is that the shortest way of rendering today?
where do you put the +1?
gimme a sec, the +1 goes here: [now().weekday()+1]
@shadow gorge
This thread is reeeaaally good for figuring this stuff out:
https://community.home-assistant.io/t/the-epic-time-conversion-and-manipulation-thread/85786/2
Thank you so much for the help, this is great for my weather forecast card!
how can i use boolean operators in template expressions?
@shadow gorge do you want them in English? Then you can just just now().strftime('%A')
What do you mean?
ah cool, perfect! How would you change that to show tomorrow or another day?
Like this?
{{ (now() + timedelta(days=1)).strftime('%A') }}
{{ as_datetime('2023-12-25').strftime('%A') }}
that last row did not work in the dev console, but the first row is perfect, thanks
2nd one should work now as well
still not for me... hmm
TemplateSyntaxError: unexpected '}', expected ')'
are you sure you have the updated version? Maybe my message wasn't updated yet
super wierd, I know I copied after you edited the post. Oh well, works now, thanks 🙂
sorry, i figured out: is_state(...) or is_state(...)
when i define a template switch: Where can i find it in the UI?
Devices & services / Entities / switch.xxx
It's an entity, not a device. So in the automation GUI you won't find it under device trigger/condition/action
ok, i could deal with it. It is a bit awkward to me that a template switch is not considered as a device, but anyway. i could do what I wanted to do. 🙂
nothing defined in yaml generates a device.
if you add anything via yaml, you have to find your entities via developer tools -> states or the entities list.
This is unrelated to templates, this is a question for #integrations-archived
oh shoot. ok ill move it 🙂
I feel like I have a really stupid question. I have a integration that pulls my bloodglucose value. This is in US measurement, and I need it in EU, so inside templates.yaml i put this code to convert it.
- name: blood_sugar_mmol
state: "{{ ((states.sensor.blood_sugar.state | int)/18) | round(1) }}"```
This gives me an entity that does what I want, but it shows the history as a timeline, and not a graph. Any tips to what I did wrong?
add a unit_of_measurement
I knew it was something silly i forgot. Worked perfectly. Thank you 🙂
I have a template sensor that records the temperature attribute coming from the accuweather integration. Due to the free API, it's only updated every few hours, and the template sensor reports 'Unavailable', and introduces gaps in the history graph. How could I fix this, can I tell the sensor that it's ok if it didn't get new values in more than an hour? I think it's 30 minutes that it reports unavailable now
sensor:
- platform: template
sensors:
outside_temperature:
unique_id: outside_temperature
friendly_name: "Outside temperature"
unit_of_measurement: "°C"
device_class: temperature
value_template: "{{state_attr('weather.home', 'temperature') | float }}"
You can add a trigger to tell it how often to update, but you'll need to switch to the modern template sensor format for that
Can anyone share with me an example of using the fire event action in developer tools?
As in why you might want to do it?
You can create your own event triggers in automations and test them by manually firing them, or fire any other event in the system manually if you want. There easier ways to fire events like state_changed by using other dev tools, so I've never actually fired an event from there
I’m trying to learn how to use them (events) but I’m just not sure what the Event Data (YAML, optional) section does
Whatever you want to send with the event
Could be nothing, which is why it's optional
I got it
It's dependent on the event
Just figured it out
But I need to know what that event might do/ say when it’s fired natively
Then listen for it
In order to get the data to fire it as a test
And you will see
Guess I’ll have to try and find a way to force it to fire
Like I said, there are easier ways to cause events to be fired in many cases
Yea.. maybe restating the integration or something
Don't use that to generate state_changed, just change the state in
-> States, for instance
Hello, I know I'm mixing old and modern format in my template.yaml, but I can't manage to get this to work:
- name: "T° Entrée"
unique_id: thermostat_entree_temperature
device_class: temperature
unit_of_measurement: "°C"
state: "{{ states.climate.entree.attributes.current_temperature }}"
- name: "T° Bureau"
unique_id: bureau_temperature
device_class: temperature
unit_of_measurement: "°C"
state: "{{ states.climate.bureau.attributes.current_temperature }}" ```
Any indication or help would be really nice, please 🙂
but I can't manage to get this to work:
🤷
please don't make us guess in what way it doesn't work
I'm sorry. only the first sensor shows up as an entity
ok, so it creates the second sensor, but the entity is "sensor.tdeg_bureau", that's why I didn't find it.
ok, so my issue is that the "unique_id" field is not used for the sensor id.
how can i create a condition to test whether all light entities in a given area are off? i don't want to create a light group really, is there a way with templates?
{{ area_entities('Family Room')|select('match', 'light.')|select('is_state', 'on')|list|length == 0 }}
A couple of days ago I created a "There is a problem sensor" #templates-archived message which works as intended. It has two states: OK and Problem with attributes for each items it checks.
When setting up an automation (via the UI) using the problem sensor, it only allows Unavailable and Unknown from the drop-down.
I can type in OK and Problem for the automation but I'm curious if it is possible to define the possible states in the template so the drop-down will show OK, Problem, Unavailable and Unknown.
Nope
Would that be something worthy of doing of Feature Request? Would it be something that could theoretically be implemented?
A usual binary template sensor with device class problem does that
Changed from template sensor to template binary sensor. Added problem device_class which gives an on/off state which the UI translates to OK/Problem. Now, the Automation UI's drop-down shows Any state (ignoring attributes, Unavailable, Unknown but does not show OK or Problem.
(A motion detector binary sensor shows Any state, Detected, Clear, Unavailable, and Unknown.)
Interestingly, a binary sensor helper created through the UI does show the OK/Problem states in the Automation UI but not the one that I put into configuration.yaml. 😕
I figured out my template question - Home assistant reports states without capitalizing the first letter >.<
Generally, yes.
-> States
I can't reproduce that. A template binary_sensor with problem class created in config.yaml is showing for me problem/ok as selectable options.
Saw your message and went investigating why it worked for you but not for me. Figured out the issue. My original template used state: "{{ 'OK' if this.attributes.values()|reject('eq', 'OK')|list|length == 3 else 'Problem' }}"Changed OK to off and Problem to on. Everything works now.
And FYI, had you left it as a sensor, I believe you could have made it an enum class, and given the list of possibilities as options in the attributes. and then those would show in the list.
I'm on the same page. 😆
the old mqtt weatherflow addon had a sensor for the last time it rained. The new built in integration does not. I'm figuring the way to fill this gap is with a template. I know I can find out the last time a sensor changed with states.sensor.st_00008500_precipitation_type.last_changed but how do I tell when it last changed to a specific value (in this case rain) not just any change?
That information only exists in the recorder database. So you can’t access it with a simple template. You can either write an SQL sensor to look it up, or you can create a template sensor or an automation that only changes or triggers when that attribute changes.
RobC - Took me a moment to get this to work, but it is working as you described. Changed template back to sensor (from binary_sensor) and device_class to enum (from problem.)
The options: threw me for a loop as far as where it is supposed to go and the syntax. It did not like being in the main part of the template and did not like being defined as a "dashed list". Ultimately, this is what worked for me: yaml attributes: options: "{{ ['OK', 'Problem'] }}"It does create an extra attribute that I had to account for in the template for determining the state (there are now 4 attributes used for the entity and 4 attributes to check for problems.)
In the end, I think this setup could allow me to define severities to the problems (low, med, high) and then the automation can handle the appropriate response (from sending a silent notification to my phone to broadcast TTS/alarm to all speaker devices, notify all phone devices, and turn all lights red...)
Original template (edited) #templates-archived message
You should have been able to do this
attributes:
options:
- OK
- Problem
As far as I remember, attributes in template sensors only accept templates and strings
So a YAML formatted list won't work
That's what I initially tried but the sensor wouldn't become available after reloading template entities. Tried deleting the entity and reloading; nope. Tried the options in quotes; nope. Just tried it again with no luck. Back to the version from above and sensor came back.
Yeah, it might need an update to templates the
What kind of update? I'm on 2023.11.6.
So i tried to add a switch entity for the broardlink integration as per the documents here https://www.home-assistant.io/integrations/broadlink#setting-up-custom-irrf-switches but i cannot get it to show, has any one had experiance with this?
@solid charm I converted your message into a file since it's above 15 lines :+1:
States are always strings.
Even state attributes?
Can I not make it a 'list' like this one:
rates:
- start: "2023-12-04T00:00:00+00:00"
end: "2023-12-04T00:30:00+00:00"
value_inc_vat: 0.183855
is_capped: false
- start: "2023-12-04T00:30:00+00:00"
end: "2023-12-04T01:00:00+00:00"
value_inc_vat: 0.202335
is_capped: false
Attributes can be other datatypes.
Yeah so mine is an attribute above
I'm using it like:
{{ state_attr('sensor.cheapest_upcoming_rates', 'slots') }}
but it evaluates as a string so ^ [0] gives [
Put your array inside {{}}
It is. Sec
- name: "Cheapest Upcoming Rates"
state: "Rates"
attributes:
slots: >
{% set rates = ((state_attr('event.octopus_energy_electricity_22l3614523_2600002745330_current_day_rates', 'rates') + state_attr('event.octopus_energy_electricity_22l3614523_2600002745330_next_day_rates', 'rates')) | sort(attribute='value_inc_vat') | list )[:6] | sort(attribute='value_inc_vat') %}
{{rates}}
otherwise it's just a string
Thats the sensor
Even if I return rates[0] its resolving as a string not a dict or list
@solid charm Are you using the legacy_templates: true option in your configuration?
morning all. I got a light which does auto-brightness based on lux outside. It runs /1 min. But sometimes we need to set it brighter manually by companion app or MQTT wall-button, so i would like some override fuction. Is turning the automation off/on the only way to temporarily stop the automation and do another automation to override? Or is there som smarter way?
im searching for a triggered-by-user thingy but it looks like it doesnt really exist
Just add an input boolean and add it as a condition.
FYI this isn't a template question, more an #automations-archived question.
hi all
is there a way to modify the color of the icon based on state? there's a lot of no-/knowledge out there, but I want able to figure out a solution yet....
the sensors are template-sensors...
The only way is with a custom card, like card mod, custom button card, or base theming (which will be all entities)
mushroom template cards is also an option
the point is, that I already have a picture-elements card in use and don't want to change that...
Does anyone have an idea how to make cover.garage_door just show open or closed as a sensor? I have the ratgdo and when I try to put it in an entity card it also gives up/down controls. I'm trying to just have it show open or closed. The ratgdo has a closed and open state. so far this is what I have and it shows closed {{ states('cover.ratgdov2_1494cb_door') }}
you can make a template binary_sensor
Ya thats what im kinda trying to do but trying to figure out the actual templating
I thing I got it if anyone in the future needs it - binary_sensor: - name: Garage Door State state: > {{ is_state('cover.ratgdov2_1494cb_door', 'open') }} device_class: opening
is there a way i can get the average (or max) for the last 15 minutes or so from climate-entity with a template sensor?
i use state_attr('climate.foo','temperature') to get the temp from it
templates don't have access to history
need to find the average difference between what a heater actually measure itself and what other temperature sensors in the room measures (so i can finetune the heater thermostat :))
Yeah, that looks good
thermostat_fan: value_template: "{{ is_state_attr('climate.thermostat', 'fan_mode', 'on') }}" friendly_name: Thermostat Fan turn_on: service: climate.set_fan_mode target: entity_id: climate.thermostat data: fan_mode: on turn_off: service: climate.set_fan_mode target: entity_id: climate.thermostat data: fan_mode: auto
Am I doing this template switch right? I keep getting an error "Failed to call service switch/turn_on. 'True'", but it's identical to the service call in devtools (which works).
Weird, cause I'm just calling it from a switch entity card in the dash for testing right now. The turn on service call is failing, but not turn off
My bad, i wasn't calling fan_mode as a string.
Yeah, probably needed quotes
for each attribute of a template sensor? Or just below attributes: so its available for all coming attributes? Studio code server is trowing errors when i do that
You can't template the attributes key itself, there is a FR open for that (or maybe a WTH)
you need to define a key first
ok so im going to set variabbles on a per attribute basis then
attributes:
some_attribute: "{{ template }}"
another_attribute: "{{ another template }}"
thank you!
I have to use JS as this is custom button card. can you give me a hint, why the icon won't change
color: | [[[ if (states['switch.shelly_eingangsbereich_aussen_aussensteckdose'].state == "on") return "red"; else return "lightGrey"; ]]]
is there an easy way to get all entitiy written into a log or file of a domain? eg. switch?
That's more for #frontend-archived
{% if is_state('binary_sensor.alle_raam_sensors', 'on') %} {{expand('binary_sensor.alle_raam_sensors')|selectattr('state','eq','on')|map(attribute='name')|list|join('<br>') }} {%
endif %}```
How can i skip one single entity by name from this list?
|reject(...?...)
depends on where you place the filter
| map(attriubte='name') | reject('eq', 'the name of the entity')
or
| rejectattr('name', 'eq', 'the name of your entity') | map(attribute='name')
the second one allows you to use enitty_id instead of name if you want
Hi everyone, i'm reporting here the conversation started in #automations-archived chanel: I want to define a default volume in my script when volume is not defined (not sent by another script). I want to retrieve this value from an input_number that will change depending the period of the day. As i said when i tried to put variables in my script, i can't save it in HA because of "Message malformed" error sent by HA. Here is what i tried to do (NB: I'm a yaml beginner):
https://dpaste.org/hmVrn/slim
@ruby zephyr your last one is close, but it needs to be a list item per action
you can't put it in one service call, the variables part is a separate action
I assume you are using the GUI to create the automation?
Firs create a variables action and create the variables
then use a service_call action to create the service call to set the volume
haaaa!!!!!!!! it's obvious!..... 😛 lol, ok, i will try that! thanks!
i got the error 'ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ states('input.number_volume_par_defaut')|float }}' but no default was specified'
In case of an input_number that would basically mean
- you didn't enter an initial value after you created it
- you have the wrong entity id
Didn't even look at the entity_id, good catch
also, float isn't even needed for that
@ruby zephyr it's option 2, the wrong entity_id. You switched the dot and undersccore. It's input_number. not input.number_
@onyx hare I converted your message into a file since it's above 15 lines :+1:
Oh hang on...it started working !
You could simplify that template to
{{ not (is_state('binary_sensor.bathroom_motion1', 'off') and is_state('binary_sensor.bathroom_motion2', 'off')) }}
Or just create a binary sensor group in the GUI (under helpers)
getting a raise TemplateError(err) from err homeassistant.exceptions.TemplateError: TemplateError: Invalid domain name '' at startup on this template: {%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {%- set ns = namespace(batt_low=[]) %} {%- for s in batteries().split(',') if states(s)|int(default=0) < alert_level %} {%- set ns.batt_low = ns.batt_low + [states[s].entity_id] %} {%- endfor %} {{ns.batt_low}})
it correctly outputs in the dev tools, it might be a frointend card template (card_mod) though. That dashboard is refreshed now, so it should be out of cache, but other than that, could there be some startup catch?
we'd need to see what's in batteries
sure. wait a sec
only other possible spot for the issue would be w/ states[s]
{%- macro batteries() -%}
{{- states.sensor
|rejectattr('state','in',['unknown','unavailable'])
|selectattr('attributes.device_class','defined')
|selectattr('attributes.device_class','eq','battery')
|map(attribute='entity_id')|join(',') -}}
{%- endmacro -%}```
which tbh, is rediculous that you're even doing that
{%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %}
{% from 'batteries.jinja' import batteries %}
{%- set ns = namespace(batt_low=[]) %}
{%- for s in batteries().split(',') if states(s)|int(default=0) < alert_level %}
{%- set ns.batt_low = ns.batt_low + [s] %}
{%- endfor %}
{{ns.batt_low}})
if that gets rid of the error, then you have a bad entity_id in your batteries macro
which doesn't make sense
Oh thanks...the setup though is with only sensor 1 turning the lights on, but both sensors 1+2 determining how long to keep the lights on.
also, the int defautls aren't needed based on your code
please wait a sec. this is the main/only change in the template is it? {%- set ns.batt_low = ns.batt_low + [s] %}
yes
cool
you were getting the state object and then the entity_id from it, which you already had
aka, unnecessary redundancy
you're filtering out unknown/unavailable states too and device_class battery
so your values will always be a number, meaning you can remove the int defaults
and input_number's restore state, so that doesn't need an int default either
Your current template will return on or off, mine will return true or false but in the end the result will be the same with your template or mine
right, didnt think of that, such a habit of adding those defaults
it's always good to know why you need the default, so that you can use or not use it. Don't just blindly add it
yes, youre right...
thats how people end up w/ templates like this {{ states('sensor.abc') | float }}, where the float serves no purpose
should I do is_number there, instead of filtering unknown/unavailable?
if you want
seems more focussed on being a number
i'd probably do
{%- macro batteries() -%}
{{- states.sensor
|selectattr('attributes.device_class','defined')
|selectattr('attributes.device_class','eq','battery')
|selectattr('state','is_number')
|map(attribute='entity_id')
|join(',') -}}
{%- endmacro -%}
yep, thanks!
we do still need the |selectattr('attributes.device_class','defined') ? Seem to recall Frenck saying that was now no longer required
doesnt throw an error....
i'd wager the null change for attributes made it so we don't need this anymore
yes! nice again!
another quick one related:```
{% set batteries =
expand(integration_entities('Ikea Trådfri'),integration_entities('hue'))
|selectattr('attributes.device_class','eq','battery') %}
{%- set alert_level = states('input_number.battery_alert_level')|int %}
{%- for b in batteries
if b.state|int < alert_level %}
> {{- b.name}}: *{{b.state}} %*
{% endfor %}```
works in the frontend on a Auto entities
no, this is not the case, something else was changed.
This still gives me 370 sensors
{{ states.sensor | rejectattr('attributes.device_class', 'defined') | list | count }}
So it's not that they're all defined now
ill restart and see what happens there
But indeed it doesn't complain about state objects without the attribute anymore
however...
if you're using that in the frontend, you may get that error while restarting and on the page that shows that
if you're using that in the backend, it will be fine
those changes in the frontend need firm cache refreshes
It's just like lovelace gen, where the frontend is loaded before everything else
I see, if it sticks, I'll re-add those, I hate these warnings errors
if you're using it in a markdown card, then definitely re-add those defaults
No way! I checked the variable name several times without seeing the error! .... Many thanks for the help!
Ill have a deeper look. the one I posted in the Hue/Ikea above uses as an auto-entities filter btw, not a Markdown, and is fine. the markdown I ll re-examine. For now, the error is no longer there
@waxen meadow I converted your message into a file since it's above 15 lines :+1:
Hi someone help me with this template what am I doing wrong there?
thx
Jinja allows you to calculate, can I take the state of two temperature sensors, subtract them and display as a template sensor?
I did some evaluations, looking back through my devices for what I've done
Should this work in a state template on a custom:button-card? .state works but state_with_unit doesn't?
[[[ return states['sensor.monitor_ac_main_diff'].state_with_unit ]]]
that's a jinja template
custom button card is JS
you have to use the methods available in custom button card
that's a weird one. The docs make it look like it's part of the state object
In my sensor template I am using this, can the value be rounded and UOM displayed
unit_of_measurement: °F
device_class: temperature```
but it's not documented here: https://www.home-assistant.io/docs/configuration/state_object/
I though it was a cool function 🤷♂️
round is....round
In the Template sensor value template I added it as temperature') | float | round }}" but doesn't seems to be honoring it
need more than that little fragment
unit_of_measurement: °F
device_class: temperature```
This seems to work in the Template editor {{ (states('sensor.monitor_ac_ds18b20_1_temperature') | float - states('sensor.monitor_ac_ds18b20_2_temperature') | float) | round(2) }}
Hi i have question how im make rest sensor that it would be updated every 30 minutes? thx
Hi all. Crosspost from #cloud-archived :
Hi all. For some time now I seem to have been unable to turn lights on to a certain level from the google home app. I'm certain that I used to be able to. Is there any way to get that back? It looks like my lights are reporting a brightness of null when they're off. The level_template in my template light evaluates to 0 when the light is off, but in the state it shows as null. Is that the problem? Any ideas how to solve it?
I am trying to figure out how to create a binary sensor that turns on at either sunset or 8PM (which ever is later) and turns off at 11PM. The sunset has a date assigned so I am not sure how manage comparing the two
use today_at('20:00')
I'm very confused about template sensors in the UI. In the state template code block for a binary sensor, would it look something like this? this isn'[t working and documentation is very unclear (to me).
- platform: template
sensors:
dining_table_delayed:
friendly_name: 'Dining Table Motion Delayed'
delay_on:
seconds: 5
value_template: >-
{{ is_state('binary_sensor.presence_fp2_office_desk', 'true') }}
binary_sensor entities are only on or off, not true
yes i fixed that..sorry was an old cut and paste
binary_sensor:
- platform: template
sensors:
dining_table_motion_delayed:
friendly_name: 'Dining Table Delayed Motion'
delay_on:
seconds: 5
value_template: >-
{{ is_state('binary_sensor.presence_fp2_dining_room_table', 'on') }}
please format
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
anyway, if you're adding the sensor to the UI, the template is just what's in value_template
or I'm not really following the question
you just fill in the fields
I need the delay_on
you don't copy and paste the YAML
is that not available in the UI?
If not, then you'll need to define the sensor in YAML. The UI is just for simple template sensors
no there are zero actions like delay_on or delay_off in the UI
then you can't use the UI for your sensor and need to define it in YAML
ugh
it's not intended for complex configurations
can't see how the UI is good for anything...but ok thx
a delay of 5 seconds is simple, IMHO
HA really needs to be easier to use...I know they've made progress, but it still has a very, very long ways to go. thanks
I have a Litter robot that is a vacuum in HA, I want to add it to an entity card with the 'press' option to start the cycle. Do just need to create a - platform: template, button in my button.yaml with a press service call to vacuum.litter_robot_litter_box?
you can call servivces directly from the buttons in the frontend boy changing the tap action
Would that have to be done in a button card? I have an existing type: entities card with the other robot info in it.
that can be done pretty much anywhere that allows tap_action
I think that is why I was going down the button template route, the entities. card doesn't maybe I just don't know how.
But if I button template it I can also expose it to the voice assistant and automations
then by all means, make a button template
I put this in my button.yaml and it didn't create Litter-Robot Cycle Start:
button:
litter_robot_cycle_start:
friendly_name: "Litter-Robot Cycle Start"
press:
service: vacuum.start
target:
entity_id: vacuum.litter_robot_litter_box```
does the `litter_robot_cycle_start` need to be `button.litter_robot_cycle_start`
where'd you get that yaml from?
buy looking at my switch templet configurations
You should instead look at the examples in the documentation page
apparently there arn't examples
template:
- button:
- name: ....
press:
regardless, you can still peice together the yaml off the documentation like I just did
rule #1 of HA yaml, don't make assumptions between integrations.
So in my switch.yaml I have it like this, is that wrong:
switches:
tv_master_toggle:
friendly_name:
value_template:
turn_on:
service:
target:
entity_id:
turn_off:
service:
target:
entity_id:
icon_template:```
that's for a switch
you're talking about a button
the 2 are not the same
that's what I mean by making assumptions
you're assuming the yaml will be the same, it will not
You would think by looking at the template documentation it's doing the same thing given there isn't a specific example for a button.
In the button template can I do icon_template?
No
you have to consult the documents
you can see what's shared between them
switch is very old, it has old yaml format
button is very new, it has new yaml format
all of HA yaml is like this, everywhere you go
you have to consult the documentation 100% of the time
there is no way around this. It's simply too much to memorize.
So I am confused, according to the doc it shows optional fields for a button is icon template.
because I asked and you said no
i siad you can't use icon_template
what's the name of that field?
it's icon.
so, no you can't use icon_template, but you can use icon because that's what the doc's state
HA is explicit, you cannot make assumptions and you have to think explicitly
Thank you, I misread icon template (optional) and ASSumed it was the same. After going back through the Template doc I see the links to the other types
Yes, half are new style and half are old style
we've been waiting for a volunteer to step up and convert them all to the new style
but it's a massive ammount of work, I don't expect it anytime soon
So when writing a template, is it going to be proper practice to check for unknown or unavailable for all of your template's state dependencies at the top of your template (as long as they are required and a default can't be used)? Or I guess you can also do this in the availability field if the template entity supports this
It seems kind of verbose to have to do for every state dependency that template uses, but I can't think of a way around that unless I'm missing something. I'd like to clean up a lot of my templates I've perhaps written a little haphazardly without proper error handling
Hi. Is there any specific reason why this wouldn't work:
- switch:
name: Doorbell Camera Panup
command_on: "/config/hascripts/amcrestcontrol.sh doorbellcamera.asus ptz panup {{states('input_number.camera_turn_speed')|int}}"
unique_id: doorbell_camera_panup
Maybe command_line platform does not understand {{states('input_number.camera_turn_speed')|int}} and implements it as argument, could this be the case?
I see nothing in the docs that say a template is supported there
got you, thanks. I'll try with shell command then, hope that works
worked with shell_command platform, thank you:)
@limber haven I converted your message into a file since it's above 15 lines :+1:
Basically Im not 100% how to get that 'if' statment to apply the flash if teh value of the sensor is over 100.
Apparently it is possible, https://community.home-assistant.io/t/mushroom-cards-card-mod-styling-config-guide/600472/62 - but.. I dunno, Im not sure why mine dodes not work 🙂
hey, i am currently trying to create a list of entities and would love to sort them, what is the syntax to sort them by the value?
`type: entities
entities:
- sensor.aral_...
- sensor.totalenergies_...
state_color: false
sort:
method: value`
it constantly tells me that sort isnt supported, however i see plenty of forum entries, so what do i do wrong?
that's a card, so #frontend-archived
I have an automation that is tracking the z-index of my garage door into an input_number based on zha_events. I'm trying to create a secondary binary sensor to represent if the garage door is open using a template helper that compares the input_number.garage_door_z to see if it is less than 500.
The template appears to work however, it does not dynamically change from closed to open when the z value changes.
This is what I have for my binary_sensor template code.
{{ is_number('input_number.garage_door_z') < 500 }}
where did that line come from? I thought that was just a proposal and not actually implemented
is_number will return True if the input can be parsed by Python’s float function and the parsed input is not inf or nan, in all other cases returns False
I see, I tried doing
{{ number('input_number.garage_door_z') < 500 }}
But the preview shows Unavailable as the computed state
@forest ferry I converted your message into a file since it's above 15 lines :+1:
yes, that's not a thing either
{{ states('input_number.garage_door_z')|float < 500 }}
{{ states('input_number.garage_door_z')|float < 500 }}
I suggest consulting the docs rather than trying random stuff 🙂
haha, thanks @inner mesa
😒 sorry forgot the 15 lines limit... Trying to get this one to keep the value unchanged when the main "if" is not met...
- trigger:
- platform: event
event_type: "imap_content"
binary_sensor:
- name: gmail imap hydroqc am peak period
unique_id: gmail_imap_hydroqc_am_peak_period
state: >-
{% if '9 h, en matin' in trigger.event.data["text"] %}
true
{% else %}
{{ states('binary_sensor.gmail_imap_hydroqc_am_peak_period')}}
{% endif %}
use this.state
I suspect events are ephemeral, but I'm not a huge of needing to have these axis helpers and an automation to update the values.
Is it possible to have a template sensor that reads the value from the most recent zha_event for a given device_ieee and attribute_name?
events have entities now
but yes, you can create trigger-based template sensors
I've never used them, but there they are
It works with "sensor"
state: >-
{% if '9 h, en matin' in trigger.event.data["text"] %}
1
{% else %}
{{ this.state }}
{% endif %}
but not "binary_sensor"
that's curious
So if I don't see an event entity for the device in question, then I need to go with a trigger based template?
forget it , a typo.
I don't know what you're trying to do. It's an option
I'm trying to simplify how I track the z-index of a sensor on the garage door.
Right now I have:
- A
binary_sensor.garage_door_sensorthe raises azha_eventforx_axis,y_axis, andz_axisvalues - A number helper
input_number.garage_door_z - An automation that is triggered by
zha_eventsfor thebinary_sensor.garage_door_sensorand captures the value of thez_axisevent, storing it in that number helper - A binary template sensor
binary_sensor.garage_door_positionthat compares the input number to be< 500to determine if the garage door is open. (What you just helped me solve)
This works. I now know if the garage door is open.
I'm just hoping to simplify the implementation, and have the binary template sensor binary_sensor.garage_door_position dynamically read the latest zha_event for this device & attribute so that steps 1,2, and 3 above are not necessary at all.
it seems like you could implement that completely with in a template binary_sensor
Use an event trigger and set the state based on whether the z_axis value is less than 500
one step
I know this is not right, but I'm a stuck
template:
trigger:
- platform: event
event_type: zha_event
event_data:
device_ieee: 91:6d:a3:b3:01:02:fb:17
sensor:
- name: Garage Door Z
unique_id: garage_door_z
state: "{{ this.trigger.event.data.args.value > 500 }}"
Can any one explain why this < is not true?
{{ states("sensor.dining_hallway_motion_illuminance_lux") }} // = 8
{{ 51 if states("sensor.dining_hallway_motion_illuminance_lux") < "39" else 64 }} // = 64
I have tried not using quotes for the less than comparision, but it complains about not being able to compare int and str, so the state is for whatever reason a string
Oh yeah, I just remembered having to do that once before. That worked perfect, thanks 🙂
There used to be a way to make an automation that would be able to be triggered at some time after sunset but now it seems that there is only a fixed time and sunset but no option to change it to 30 minutes after sunset or after next dusk. I don't know what I'm doing so I enlisted the help of ChatGPT and Bard but cant come up with a working solution 😦 this is what I have tried:
- sensor:
- name: "adjusted_sunset"
# state: "{{ as_timestamp(states('sensor.sun_next_setting')) - (30 * 60) | timestamp_custom('%I:%M %p') }}"
state: "{{ as_timestamp(states('sensor.sun_next_setting')) - timedelta(hours=2, minutes=30) | timestamp_custom('%I:%M %p') }}"
icon: "mdi:calendar-clock"
they have failed miserably. Can anyone help? seems simple enough but I'm lost
I'm able to set an offset on the sunset trigger
platform: sun
event: sunset
offset: "-00:30:00"
Why use the sun elevation trigger or condition rather than a time offset from sunset or sunrise? Because the elevation more consistently relates to the light level than a fixed time offset. An hour before sunset is very different light levels on the longest day than the shortest day, for example.
hmmm .. I guess that would work ..basically I have an automation for the kitchen lights that turns the overhead light on if presence is discovered and the light level is below a point but I want to also add in that about 2 and a half hours after sunset, have only the kitchen sink light turn on instead of the overhead light .. I'm fairly new to home assistant .. maybe there is a better way to get this done .. I was hoping to have a different setup like the sensor so I could have the original and the adjusted .. but using an offset like this, to me, seems like it would permanently change the sunset event to whatever I change the offset too .. or am I misreading and that can be added to an automation and not to your configuration.yaml
lol I guess I could just set a fixed time like 8pm instead of a variable time that adjusts to seasons... and I guess I could adjust the "switching time (between overhead and sink light)" using the months
the more I think about it, if I do set it for a fixed time like 8pm, I guess I wouldn't have to set it up for different months because in the summer, at 8pm, it's light out and the automation wouldn't trigger because of the lux sensor but in the winter time it would trigger. ... thanks for the help and causing me to look harder into the issue 🙂 lol
I have external and internal temp data going back >1yr. I created a heating degree day sensor which will calculate this each day going forwards, but is there a way of running the calculation on the historic data I have so that the history is complete?
Hi all, hoping I can get some help with a configuration.yaml issue which appears to function fine but in the Home Assistant Core logs I’m seeing errors, can’t see how to attach pictures so am pasting in text form below
Configuration.yaml template below:
friendly_name: "X3800 Volume Level"
value_template: "{{ '{:.1%}'.format(state_attr('media_player.denon_avc_x3800h', 'volume_level')) }}"
device_x4700h_volume_level:
friendly_name: "X4700H Volume Level"
value_template: "{{ '{:.1%}'.format(state_attr('media_player.denon_avc_x4700h', 'volume_level')) }}"
Is giving below errors in the log file:
2023-12-07 07:26:37.893 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template("{{ '{:.1%}'.format(state_attr('media_player.denon_avc_x4700h', 'volume_level')) }}")
It indicates that the attribute's value is somehow None
is it possible to create an own update domain entity?
the volume level will not be available when the player is off, you can default it to 0
there is no such thing a s a template update entity
@marble jackal , thanks for responding, I see now, I’m unsure what to change to have a default value of 0 ?, is the template line/code ?
value_template: "{{ '{:.1%}'.format(state_attr('media_player.denon_avc_x4700h', 'volume_level') | float(0)) }}"
that should work
Awesome, will give that a go, thanks a bunch @marble jackal
is it somehow possible to remove an entity with the attribute "restored: true"? It is somehow stored but its annoying because a new entity with the same name as "_2"
When you go to the entity in HA, will it not let you delete it?
It must still be managed by whatever integration created it if so
Or are you not even able to find the entity? You can search by attributes in the state tab in dev tools
it seems that for imap we are not there yet
Yeah event is a new entity type and I've come across a ton of entities that should probably be converted. Could be worthy of a github issue
Did you forget to paste code?
Discovered this is a bug in the latest release of HA, thanks for asking
Wondering of someone can steer me in the right direction, I'm trying to make a stacked statistics graph where it shows 24h of data that is the stats over 30 days
right now if I want to show stats graph with 30 days of data, the X axis is 30 days instead of 24h
Hey, someone knows what here is the problem?
TemplateError('ValueError: Template error: as_timestamp got invalid input 'None' when rendering template '{{ as_timestamp(state_attr('sensor.backup_state', 'next_backup')) | timestamp_custom('%d.%m.%Y - %H:%M Uhr') }}' but no default was specified') while processing template 'Template<template=({{ as_timestamp(state_attr('sensor.backup_state', 'next_backup')) | timestamp_custom('%d.%m.%Y - %H:%M Uhr') }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.next_backup_format'
Here is the Template code:
- name: "Last Backup Format"
state: >
{{ as_timestamp(state_attr('sensor.backup_state', 'last_uploaded')) | timestamp_custom('%d.%m.%Y - %H:%M Uhr') }}- name: "Next Backup Format"
state: >
{{ as_timestamp(state_attr('sensor.backup_state', 'next_backup')) | timestamp_custom('%d.%m.%Y - %H:%M Uhr') }}
- name: "Next Backup Format"
You're missing a default value, check the pins
ah okay, nerver before wor with them, like this? how i can add these?
what are pins?
ahh okay thanks
Man, that breaking default change was in 2022.2 and we are still getting hits about it today
im no programmer, is new land
so i must be called, right?
{{ as_timestamp(state_attr('sensor.backup_state', 'last_uploaded')) | timestamp_custom('%d.%m.%Y - %H:%M Uhr', default = 0) }}
like this? sorry my programming knowledge is bad
{{ as_timestamp(state_attr('sensor.backup_state', 'last_uploaded', default = 0)) | timestamp_custom('%d.%m.%Y - %H:%M Uhr') }}
nope, you put it in state_attr(), needs to go in as_timestamp().
no plan sorry
delete 1 of the doulbe )
and move it back to after uploaded')
you can test all of this in the template editor
{{ as_timestamp(state_attr('sensor.backup_state', 'last_uploaded') default = 0) | timestamp_custom('%d.%m.%Y - %H:%M Uhr') }}
like this?
ah okay i understand, thank you
It is an entity, created in yank, but even when I remove the rows it still shows under states. I guess because of this I get the _2 extensions
Integration or automations are not used with the entities
Hm, so I have a bit of templating that takes the current time, and works out how many hours /minutes it is till 2am. But I want to inject the result of that into a 'select.' box that only takes h:mm in 15 minute intervials. Is there a way to convert this code so it will take the result and round it up to the nearest 15min segment? ```
{% set t = now().replace(hour=2, minute=5, second=0, microsecond=0) %}
{{ ((t + timedelta(days=1) if now() > t else t) - now()).total_seconds() |
timestamp_custom('%-H:%-M', false) }}```
I.e. if its 8 hours 49 minutes till 2am, give a result of 8:50
(most of this is copy/paste if Im honest, Im not even 100% how this code works out its 2am, but it does :D)
{% set interval = timedelta(minutes=15) %}
{% set target = today_at('2:05') %}
{% set t = now() %}
{% set target = target if today_at() < t < target else target + timedelta(days=1) %}
{% set count = (target - t) // interval %}
{{ count * interval }}
if you want it to round...
{% set interval = timedelta(minutes=15) %}
{% set target = today_at('2:05') %}
{% set t = now() %}
{% set target = target if today_at() < t < target else target + timedelta(days=1) %}
{% set count = ((target - t) / interval) | round %}
{{ count * interval }}
if you want it to always round up...
{% set interval = timedelta(minutes=15) %}
{% set target = today_at('2:05') %}
{% set t = now() %}
{% set target = target if today_at() < t < target else target + timedelta(days=1) %}
{% set count = ((target - t) / interval) | round(0, 'ceil') %}
{{ count * interval }}
Yeha i'd never have worked this out on my own 😄
Hm, okay that works but returns 8:30:00, but need to strip the seconds off it.. and using timestamp_custom seems to make it crap out
change the last line to
{{ (count * interval).total_seconds() | timestamp_custom("%H:%M", false) }}
Ah conver it to total seconds..
Was trying string editing which.. apparently wont work with timedelta
Hm.... so the code works, but not if I put it inside a select.select_option, just throws an 'unknown' error.. also wont let me set the data: to data_tempate: either
post the full yaml please
data:
option: >
{% set interval = timedelta(minutes=15) %}
{% set target = today_at('2:05') %}
{% set t = now() %}
{% set target = target if today_at() < t < target else target + timedelta(days=1) %}
{% set count = ((target - t) / interval) | round %}
{{ (count * interval).total_seconds() | timestamp_custom("%H:%M", false) }}
target:
entity_id: select.011090527032007221_bsh_common_option_startinrelative```
Actually it looks like the selector is only 30min intervals, which is a obvious fix on that code but still does not work, just says 'unknown error'
that looks fine, what's the error in the logs?
Hm... I thinkt he problem is it might not like the leading 0 either lol..
change %H to %I
If I just put in a raw string, 08:00 errors, 8:00 doesnt, good lord this thing is picky
Well it thew a green checkmark 😄
progress?
Yeha, I think thats working 🙂 Just need ot figure out how to implement this now in the automation/UI but thats a lot easier 🙂
Thank you haha, I dont think I've ever got that
'Hi there! I need a hint how I could do the following. I would like to store the consumption of a meter on each last day of the month and show that in a list. So I can see how much was used in which month. I just have no good idea how I could do that. Maybe someone could point me into the right direction...
doesn't the energy dashboard show that just fine?
Hi! 🙂 Yes, but then I need to go through each month, one by one. What I would like to have, is a real list that is automatically generated and carried over every month. Maybe for each of the last 12 month in one list. And best with the amount that I used...
Quick question.
Should this
{{ states.climate|selectattr('entity_id', 'search', 'bedroom')|map(attribute='temperature')|float }}
not return the same as
{{ states.climate.eq3_master_bedroom_climate.attributes.temperature|float }}
?
I do get only one entity_id from {{ states.climate|selectattr('entity_id', 'search', 'bedroom')|map(attribute='entity_id')|list }}, so the entity found is unique. I don't quite get why the above won't work as expected.
The first returns a generator
If you wanted to get the first, you'd need to add |list|first
Or you can do |map('float')|list to get a list all the temperature for everything that matches as a float
You also need | map(attribute='attributes.temperature')
That, too
Did the template engine change in the last release? Some of my blueprints are now freaking out:
{% set json_text = {"0": "#FEC4FF","10": "#D977DF","20": "#9545BC","30": "#4B379C","40": "#31B8DB","50": "#31DB8B","60": "#6ED228","70": "#FFFF28","80": "#F87E27","90": "#CF3927","100": "#A12527"} %}
{{ json_text | from_json }}
This is now throwing an error and my blueprints int he previous verison used this code fine
Thank you both 🙂
For others: If you want to just get the value (instead of a list) so you can perform mathematical comparison/calculations:
{{ states.climate|selectattr('entity_id', 'search', 'bedroom')|map(attribute='attributes.temperature')|map('float')|first }}
There should be no need for from_json there
It does work if the variable is a string
{% set json_text = '{"0": "#FEC4FF","10": "#D977DF","20": "#9545BC","30": "#4B379C","40": "#31B8DB","50": "#31DB8B","60": "#6ED228","70": "#FFFF28","80": "#F87E27","90": "#CF3927","100": "#A12527"}' %}
{{ json_text | from_json }}
But in your case it was already a dictionary
I was not able to figure out how to send the response to the service call to the template but I did manage to do a workaround by saving the response in an automation to a helper text entity. https://community.home-assistant.io/t/displaying-todo-list-on-template-to-display-on-android-widget/652210
@gilded saffron I converted your message into a file since it's above 15 lines :+1:
this pops up as two entities but not combined into a single device in the mqtt integration
Everything in the device map should be the same if you want them to map to the same device. You’ve assigned a different device name to each one.
The MQTT integration supports device discovery, but you need to use that in your yaml. That yaml is outdated, assuming you're on an older version, you'll have to verify that you can even assign a device in the version you're using.
Update to the latest version and I can help you make those appear in a single device.
Also, this is not a #templates-archived question, this is an #integrations-archived question
Yea i did notice that of sorts... but the other logic seems to be off as well... i think today i'll dig into it indepth more
can you post the full blueprint? And the error that's "blowing up"?
im using 12.2023. i assume its just the - platform: mqtt part that makes it legacy
- platform: mqtt was removed many releases ago
@gilded saffron I converted your message into a file since it's above 15 lines :+1:
You need to move it to the MQTT section
if that's the case, then you still need to have the section it's in
- sensor:
- unique_id: ...
well it's a list, so
sensor:
- unique_id: ...
Hello, Guys, im checking the last days my protokoll errors, someone can assit me to correct my template?
ValueError: Sensor sensor.wohnzimmer_comet_dect_battery_level has device class 'battery', state class 'None' unit '%' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: '80%' (<class 'str'>)
Template:
- name: "Küche Comet DECT Battery Level"
unit_of_measurement: "%"
device_class: battery
state: >
{{ state_attr('climate.kuche_comet_dect', 'battery_level' ) }}%
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
And the answer is to remove the trailing %. It's a pretty clear error messasge
alright, thank you
Hello, how would a template look like which tells me when sensor.motion was last turned on/sensed motion?
{{ states.binary_sensor.motion.last_changed }} also changes time when it no longer senses motion. I need this in a compariosn which sensor sensed motion last.
make a trigger-based template sensor
trigger when it turns on, use {{ now() }} for the state
can you elaborate on that a bit more pls
I can point you to the docs and you can try it: https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-images-numbers-selects-and-sensors
if you already have template sensors, you can reload
i already go one binary sensor
then just reload template entities
- binary_sensor:
trigger:
- type: motion
platform: device
entity_id: binary_sensor.example
domain: binary_sensor
sensor:
- name: example_latest_motion
state: '{{ now }}'
no, but there's alot wrong there too
in regards to the yaml, not the template
sensor should be binary_sensor, and the first binary_sensor: with the dash should be gone and trigger should have the dash
binary_sensor was my fault, fixed above
so if i have multiple binary sensors, i only have one -binary_sensor: ?
zero binary sensors
i had one so far and it worked
- trigger:
- type: motion
platform: device
entity_id: binary_sensor.example
domain: binary_sensor
sensor:
- name: bewegungssensor_example_latest_motion
state: '{{ now() }}'
like that?
Invalid config for 'template': required key 'device_id' not provided
What are those entity and device id with these ID numbers instead of names?
What is the best way to determine the direction of movement between two rooms (that´s what my intention with the above is). Set the occupancy timeout very short and do the above to compare the two corresponding binary sensors?
Is there a better way to check for midnight than this? {% if {{ [now().hour,now().minute] == [0,0] }} %}
maybe {% if now() == today_at() %} ?
I doubt that the latter would ever be true because it counts microseconds
Yeah thought of that. Especially as the template only updates every minute at most.
the first is better, but don't nest your templates
Ha. Well spotted. Copy paste error from the template editor
I do wonder if it is guaranteed to execute once per minute. Maybe due to cpu load or scheduling delay it might be evaluated at 23.59.9999 and 00.01.0001, which is "roughly" once per minute, but not during that minute.
Yeah could definitely be a problem. I'm not using the second version.
It's for a template that rejects zero values during the day but resets to zero at midnight, https://community.home-assistant.io/t/issues-in-energy-dashboard-with-accumulated-solar-production-values/652460/5 feel free to jump in if you have a better idea. Outlier filter integration might work but I've had issues with filter sensors in the past.
I've found a blueprint which changes the brightness of a lamp using a dimmer knob. It uses light.turn_on brightness_step_pct to increment the brightness. I would like to change the hue of the lamp instead but there's no way to increment the hue only to set it. That means I need to access the current hue but I don't know how to do that. First line old code, second line my try. Any tips?
brightness_step_pct: '{{ step_percent * steps }}'
color_temp_kelvin: '{{ state_attr(press_light, 'color_temp_kelvin') + (press_step_percent * steps) }}'
while parsing a block mapping in "<unicode string>", line 138, column 13: color_temp_kelvin: '{{ state_att ... ^ expected <block end>, but found '<scalar>' in "<unicode string>", line 138, column 61: ... n: '{{ state_attr(press_light, 'color_temp_kelvin') + (press_ste ... ^
Idk about how templates fit into this but ideally what you'd do for like a utility meter or odometer or other long-increasing counter is store the counter value at local midnight and then always return the subtraction of that value. Probably a more involved service or helper for that
It's a daily PV energy meter. It resets at midnight.
It’s always like .001 microseconds after the second. And it is guaranteed once per minute.
Basically there’s 2 throttles and everything else is registered for an update.
Throttle 1 is on the domain, throttled to at most one update per second. And on the states object, throttled at most once update per minute. Nothing else has a throttle.
Basically how it works is: If any states type of function is called (too many to list), the entity_id that's being used is registered to the template engine for updates. If any time function is called (today_at, relative_time, now, utcnow), a boolean flag is flipped that causes an on the minute update to be registered to the template. If states object is used, a throttle is imposted for at most 1 update per minute. If states.domain is used, a throttle is imposed for at most 1 update per second.
@fossil venture ^
It would be nice if we had a time function that omitted microseconds and seconds. I've had a need for this many times. Maybe something like this_minute(), where you could compare it to today_at
Your error is coming from your interior and exterior quotes. Your color_temp_kelvin has ' exterior quotes and ' interior, making the yaml thin that your template is just: '{{ state_attr(press_light, '. You need to use " exterior quotes and ' interior or vice versa.
{% if now().replace(microsecond=0) == today_at() %} would work too
Without if
also without the s
Thanks! I'm getting a new error related to !input. press_light is an entity input. Can't I use !input in this context? I've also tried it without parentheses and by assigning it to a variable first. How would I go about debugging this? The dev tools template menu doesn't seem to work well with blueprints
color_temp_kelvin: '{{ state_attr((!input press_light), "color_temp_kelvin") - (press_step_percent * steps) }}'
Message malformed: template value should be a string for dictionary value @ data['action'][1]['choose'][3]['sequence'][0]['repeat']['sequence'][0]['data_template']
It’s always like .001 microseconds after the second. And it is guaranteed once per minute.
Basically there’s 2 throttles and everything else is registered for an update.
Throttle 1 is on the domain, throttled to at most one update per second. And on the states object, throttled at most once update per minute. Nothing else has a throttle.
Basically how it works is: If any states type of function is called (too many to list), the entity_id that's being used is registered to the template engine for updates. If any time function is called (today_at, relative_time, now, utcnow), a boolean flag is flipped that causes an on the minute update to be registered to the template. If states object is used, a throttle is imposted for at most 1 update per minute. If states.domain is used, a throttle is imposed for at most 1 update per second.
You probably need to assign it to a variable first outside of the template, such as https://www.home-assistant.io/docs/scripts/#variables
Then you can use the variable in your template
Thanks, I've tried that before and couldn't get it to work. I now managed to implement it in pyscript. I'm a bit confused why the built in automation is so much more difficult to use (I have very little experience with either) 😕 https://pastebin.com/nHLme7Ee https://pastebin.com/NtYNW0Uj
I use PyScript for my more complex automations and where I need multiple instances. I don't use blueprints, so was just guessing
struggling with a wait template. Has one one got any idea where I'm going wrong please?
wait_template: >
{{ (state_attr('switch.adaptive_lighting_living_room', 'brightness_pct')) | int =
(state_attr('light.living_room_light_main', 'brightness')) | int }}
continue_on_timeout: true
You didn't say what was wrong ( 😡) but you at least need == instead of =
sorry, it was throwing an error not being able to interperate the =, I'll try the == as suggested. Many thanks
I have a sensor values that resets on an interval (daily, weekly etc), but I want to convert them into an always increasing total for all time. Any thoughts on the best ay to accomplish this in HA?
Hi.
Is it possible to create a binary sensor from a other binary sensor state?
I have a sensor stating "on/off", but the opening sensor is not updating correctly.
So i need to make my own open/closed binary sensor based on the on/off sensor.
Not sure if this is possible.. or weise.. never done it before
Yes it is possible with a template.
https://www.home-assistant.io/integrations/template/