#templates-archived

1 messages · Page 60 of 1

marble jackal
#

then the light will report this back to HA, and the 16% is calculated back to the 0-255 scale, which will be 40.8 and rounded to 41

acoustic arch
#

sounds pretty logical! thx

spice current
#

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": ...}

mighty ledge
spice current
#

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",
...
},
...
}
},
...
}

mighty ledge
#

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 ^

spice current
#

isn't that the most basic thing every api should have? list me everything in an easily processable structure?

spice current
mighty ledge
#

Yeah, and you can get that from templates easily. But not in that format you want

mighty ledge
#

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

spice current
mighty ledge
#

Right, but that’s not your key

spice current
#

"<entity_id>": that looks like a key to me

mighty ledge
#

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.

spice current
#

what would be your suggestion then?

mighty ledge
#

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

spice current
#

Get a list of all entities, of all devices, in all integrations

mighty ledge
#

For what?

spice current
#

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

mighty ledge
#

Well first and foremost, yaml entities typically don’t report what integration they come from. So that’s already a no go

spice current
#

they would just go in a "Unknown" integration group then

mighty ledge
#

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

onyx notch
#

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?

inner mesa
#

but you can proably easily do exactly what you asked for with
{{ (now() - as_datetime(states('sensor.happyours_south_shore_last_rain'))).split(', ')[0] }}

onyx notch
#

'datetime.timedelta object' has no attribute 'split'

inner mesa
#

you could also do this:
{{ (now() - as_datetime(states('scene.new_scene'))).days ~ ' days' }}

onyx notch
#

This give me '2 Days' and should be 3
{{ (now() - as_datetime(states('sensor.happyours_south_shore_last_rain'))).days ~ ' days' }}

inner mesa
#

ok

onyx notch
#

After I install Relative Time Plus are the commands just available in the templates?

inner mesa
#

the instructions have examples....

onyx notch
#

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

plain magnetBOT
#

@midnight hollow I converted your message into a file since it's above 15 lines :+1:

midnight hollow
cerulean karma
#
    {%- 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)

acoustic arch
#

"{{ (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

marble jackal
#

BTW, you can do all those if statements outside you for loop

cerulean karma
#
       | 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

marble jackal
#
{%- 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 %}
fossil venture
marble jackal
# cerulean karma this is my recent code, but still only sorted by strint and not numeric
{%- 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 %}
cerulean karma
#

oh great, that works perfectly 🙂

#

and I thought I am near the solution 🙂

cerulean karma
#

when setting the state to this.state in a template, is there no update for last_updated?

lofty mason
#

last_updated is only if there is some change of state or attribute.

cerulean karma
#

ok thanks

#

and by change you also mean, it checks the values if they are same or not?

lofty mason
#

believe so

marble jackal
#

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

cerulean karma
#

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.

plain magnetBOT
#

@cerulean karma I converted your message into a file since it's above 15 lines :+1:

cerulean karma
#

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

inner mesa
#

those are the same thing

cerulean karma
#

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

rancid linden
#

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?

shadow gorge
#

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';
    }
  ]]]
```
inner mesa
shadow gorge
#

ah ok 🙂

inner mesa
#

You need to use something like parseFloat()

slate fossil
#

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.
inner mesa
#

I would do the last one and use the state for okay/not okay and the attributes to indicate the state of individual things

slate fossil
#

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?

inner mesa
#

something like {{ "OK" if this.attributes.values()|reject('eq', 'OK')|list|length == 0 else "Not Okay" }}

full crescent
#

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...

inner mesa
#
{% set _nameMap = {'_rgb': [{'aliceblue': [240, 248, 255]}, {'antiquewhite': [250, 235, 215]}]} -%}
{{ _nameMap['_rgb'].0['aliceblue'] }}
#

you were also missing a ] in the _nameMap line

full crescent
#

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?

inner mesa
#

if you don't know...

#

how do you know?

#

what do you mean by "parse the number out"? what number?

full crescent
#

I will know the list nales and stuff and the name, not the number

marble jackal
#

why is it a dict in a list? are there more list items?

inner mesa
#

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

marble jackal
#

in yaml:

_nameMap:
  _rgb:
    - aliceblue:
        - 240
        - 248
        - 255
      antique_white:
        - 250
        - 235
        - 215
    - are there other list items here?
inner mesa
#

you mean the name could be in any of the items in the list?

full crescent
#

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)

marble jackal
#

what is there in those other list items then?

full crescent
marble jackal
#

yeah, okay, but I assume they are all in that first list item

full crescent
#

yes

marble jackal
#

So I don't think you need a list there

full crescent
#

Another function is to return a random color name, so that was why the list.

marble jackal
#

you can still do that without the list

full crescent
#

Working on a custom template...

#

ok, good

marble jackal
#

{{ {{ _nameMap['_rgb'].keys() | random }}

#

that will give a random color (without them being in a list item first

full crescent
#

noce That works

marble jackal
#
{% 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([]) }}
full crescent
#

OK. Taking this and building...

marble jackal
#

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([]) }}
slate fossil
#

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.' }}"
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.
inner mesa
#

that won't alert you if just one of those items is broken, though

slate fossil
#

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.

inner mesa
#

oh, nevermind. I misread it

slate fossil
#

Oh no. I mean, you're right. I just haven't gotten to that point with it yet.

inner mesa
#

actually, that logic looks wrong

#

I think you want select rather than reject

slate fossil
#

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.)

inner mesa
#

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"

slate fossil
#

It counts the icon and the friendly_name attributes as not OK.

inner mesa
#

oh, I see

#

nevermind, again 🙂

slate fossil
#

Better code would be to reject those I suppose but the 2 just made things shorter.

inner mesa
#

yeah, it's fine

fast violet
#

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 }}"

inner mesa
#

you can't template that field

fast violet
#

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

hard venture
#

smack self with clue-by-four after looking carefully at what he's trying to do v actually doing 🤦‍♂️

prisma locust
#

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

inner mesa
#

{{ (states('scene.new_scene')|as_datetime|as_local - now()).total_seconds()//60 ~ ' mins' }}

prisma locust
inner mesa
#

Yes

#

Take a moment to understand what it's doing

prisma locust
#

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

inner mesa
#

Use today_at() around the states() call

#

And then remove as_datetime|as_local

#

{{ (today_at('11:00') - now()).total_seconds()//60 ~ ' mins' }}

prisma locust
#

Hmm... -1390.0 mins sounds kinda wrong 😅

#

Could the problem be that the next bus comes past 12 right now?

inner mesa
#

It expects 24 hour time

prisma locust
#

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?

lucid thicket
#

@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 )) }}
floral shuttle
#

dont say I dont listen...

vagrant kiln
#

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

marble jackal
#

@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

prisma locust
#

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

marble jackal
#

you are only rouding 60

prisma locust
#

Ah okay the brackets did the tick. Thanks a lot :)

plain magnetBOT
#

@thorny snow I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

@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

thorny snow
#

@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

silent vector
#

Can you do a regex search with selectattr

#

selectattr('foo','search',regexstring)

mighty ledge
#

Yes

silent vector
#

My regex was bad

#

Ignore me lol

inland stag
#

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.

lucid thicket
inland stag
earnest cosmos
#

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

haughty breach
#

You don't need expand...

{{ states.light | rejectattr('entity_id', 'search', 'lys_ute_|shelly_|cam_') | map(attribute='entity_id') | list }}
rough delta
#

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.

marble jackal
#

If you only need the date you can add .date()

#

Then you can use the date key

silent vapor
#

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?

mighty ledge
#

you aren't using parenthesis where you need them

#

you should also use datetimes

silent vapor
#

Can you possibly help me with the correct syntax 🙏

mighty ledge
#
          {% 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

silent vapor
#

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) }}

mighty ledge
#

this instead

          {% set date = now().date() %}
          {{ date.replace(month=12, day=1) <= date or date <= date.replace(month=1, day=15) }}
silent vapor
#

Sorry, it does stay off

#

No error in the log

mighty ledge
#

of course it will

#

it's not december 1st yet

#

it's not december 1st anywhere in the world yet

silent vapor
#

🤷‍♂️ OMG... I'm staring blind here...

mighty ledge
#

🤣

#

you have a few days before it turns true 🙂

silent vapor
#

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!

balmy terrace
#

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".

lofty mason
#

maybe {{ is_state('sensor.laundry_shortcut_button_action', 'none' ) }} ?

balmy terrace
#
{{ 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

plain magnetBOT
#

@harsh coyote I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

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"

harsh coyote
#

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

inner mesa
#

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

harsh coyote
#

Hmm, ok, I'll dig into it. Thank you

#

Ok, weirdly, moving to is_state... convinces it to listen to everything 🤷‍♂️

mighty ledge
#

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 ^

harsh coyote
#

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.

lofty mason
#

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

harsh coyote
#

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

lofty mason
#

did one of your states change while you were typing it? maybe the heat turned off

harsh coyote
#

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 🙂

lofty mason
#

I find is_state also doesn't listen for entities after the short circuit.

harsh coyote
#

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.

mighty ledge
harsh coyote
#

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 🤷‍♂️

mighty ledge
#

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

harsh coyote
#

Ok, thank you

marble jackal
#

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

balmy terrace
#

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 .

marsh cairn
#

Only if there is an icon attribute. My media players don't have such attribute.

keen ingot
#

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'>)

lofty mason
#

Are you by chance sticking that yaml into the form for a helper template?

keen ingot
#

Yes indeed

#

Is that not the right way?

lofty mason
#

no that's not right.

keen ingot
#

oh my bad, I'm just starting out

lofty mason
#

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

keen ingot
#

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?

lofty mason
#

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"?

keen ingot
#

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

lofty mason
#

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.

keen ingot
#

hmm and that would simply be: {{ 1.32802 }} ?

lofty mason
#

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

keen ingot
#

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

lofty mason
#

what is "it", paste the full template

#

(that code looks fine in isolation)

keen ingot
#

{{ ((states('sensor.gasverbruik_dag') | float * states('sensor.tarief_gas_variabel')) + states('sensor.tarief_gas_vast')) | round(2) }}

lofty mason
#

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) }}
keen ingot
#

damn you're right

lofty mason
#

all states are always strings in HA

keen ingot
#

I'll remember that

lofty mason
#

(attributes can be numbers or other types)

keen ingot
#

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

inner mesa
#

|int is the ideal method to convert to an int 🙂

#

|float is the way to convert to a float

keen ingot
#

gotcha thanks

marble jackal
marble jackal
#

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

tribal cloak
#

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.

marble jackal
tribal cloak
#

done, thx

rich fjord
#

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)", "")}}
marble jackal
#
{{ (state_attr('media_player.hauptschlafzimmer','media_title') | replace("(Remaster)", ""))[:25] }}
rich fjord
#

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 ..."

inner mesa
#

Use |trim

rich fjord
inner mesa
#

There are more gems in the links in the channel topic 🙂

whole marsh
#

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

mighty ledge
#

add a home assistant start trigger

#

@whole marsh ^

whole marsh
#

so

  - trigger:
      - platform: time_pattern
        hours: /1
      - platform: homeassistant
        event: start
#

thanks!

mighty ledge
#

yep

whole marsh
#

that was only mildly infuriating lol. nothing in log, nothing anywhere

mighty ledge
#

well your time_pattern is on the hour, so it'll only trigger on the hour

whole marsh
#

that was the example in the docs (i mostly use NodeRed so I don't use automation stuff often)

onyx notch
#

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?

inner mesa
#

what is your actual goal?

#

to make separate sensors from each of those attributes?

onyx notch
#

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

inner mesa
#

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

onyx notch
#

I was trying to graph some of them on the front end and I had to manually template them to be useable

inner mesa
#

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"

onyx notch
#

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 %}"

inner mesa
#

display it how?

#

in a card in the UI?

onyx notch
#

In a front end lovelace card

inner mesa
#

lots of cards can display attributes dirctly

#

if you want to customize wording, you can use the markdown card, for instance

onyx notch
#

so to display the attribute with the entities card you have to drop to yaml editing?

inner mesa
#

seems that way

#

My entire UI config is in YAML, so 🤷

#
type: entities
entities:
  - type: attribute
    entity: light.test
    attribute: entity_id
mighty ledge
#

if the UI doesn't support fields, your only recourse is yaml

inner mesa
#

but it still live-updates the display with your changes

mighty ledge
#

Oh nice

#

(also a non-UI user)

onyx notch
#

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

mighty ledge
#

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

onyx notch
#

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?

inner mesa
#

Sure

#

You can have the state be whatever you want

onyx notch
#

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 }}

inner mesa
#

Yes

#

It's Jinja

spice sequoia
#

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)

onyx notch
#

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 }}"

lofty mason
inner mesa
spice sequoia
#

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..."

inner mesa
#

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

lofty mason
#

Then you can just set it to whatever arbitrary text string you want

#

But you can't like graph it then

onyx notch
inner mesa
#

a state is not an attribute

#

in that same line, you're reading a state

#

states are states

onyx notch
#

Got it, the media_player.tv_family has a state of on/off how is that evaluated? is that the sensor_state?

inner mesa
#

I don't know where you're getting "sensor_state" from

#

it's the same way you got the other state

onyx notch
#

or is there a media_player_state?

inner mesa
#

I think you're overthinking this

#

you wrote states('sensor.tp0_5_tv_family_hue_current_consumption')

spice sequoia
# lofty mason But you can't like graph it then

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

inner mesa
#

you don't need to try to invent somethign else for the other entity

spice sequoia
#

I guess also I can get history from the actual entity instead of the template sensor

lofty mason
onyx notch
spice sequoia
#

You’ve got me going the right path, let me play with it some more. Appreciate the input !

onyx notch
inner mesa
#

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

onyx notch
#

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' }}

inner mesa
#

the first one is preferred for reasons that I don't recall

spice sequoia
onyx notch
#

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 }}

inner mesa
#

yes

onyx notch
# inner mesa yes

In the switches template can I set an icon or colors based on the value_template result?

lofty mason
#

icon yes, color I don't think so.

marble jackal
#

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

onyx notch
#

can a static icon be set in the switches template?

inner mesa
#

yes

#

it's expecting a string or a template that outputs a string

onyx notch
#

So will my template_value above work since it's output is true?

inner mesa
#

if it's the state you expect, yes

#

I'm not commenting on the output of the template, just answering your earlier question

onyx notch
#

Like this:
{% (is_state('media_player.tv_family', 'on') or states('sensor.tp0_5_tv_family_hue_current_consumption') | int(default=0) > 120,) 'true' %}

inner mesa
#

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

onyx notch
#

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

inner mesa
#

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?

onyx notch
#

Trying to do an icon_template using the same logic as the value_template

#

don't understand the syntax of the icon_template

inner mesa
#

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

onyx notch
#

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

inner mesa
#

yeah, that's broken

#

do better than that example 🙂

#

in any case, point is, use the right logic to output what you want

onyx notch
#

my logic outputs True, can that be used to set the icon to mdi:television and mdi:television-off as the else?

marble jackal
#

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

inner mesa
#

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

onyx notch
#

LFG! thank you 🍻

sturdy yarrow
#

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?

inner mesa
#

{{ now().date().month == 12 and now().date().day == 1 }}

#

{{ (now().date()|string)[5:] == '12-01' }}

sturdy yarrow
#

Awesome, thank you 🙂

marble jackal
#

Option 3
{{ now().strftime('%m-%d') == '12-01' }}

acoustic arch
#

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:

upper basalt
#

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)}} 
marble jackal
marble jackal
upper basalt
# marble jackal No, you can't use templates in `tap_action`

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]]
plain magnetBOT
#

@shadow gorge I converted your message into a file since it's above 15 lines :+1:

upper basalt
#

and just do a +1 if you want tomorrow 😄

shadow gorge
upper basalt
#

gimme a sec, the +1 goes here: [now().weekday()+1]

shadow gorge
#

Thank you so much for the help, this is great for my weather forecast card!

hoary surge
#

how can i use boolean operators in template expressions?

marble jackal
#

@shadow gorge do you want them in English? Then you can just just now().strftime('%A')

marble jackal
shadow gorge
marble jackal
#
{{ (now() + timedelta(days=1)).strftime('%A') }}
{{ as_datetime('2023-12-25').strftime('%A') }}
shadow gorge
marble jackal
shadow gorge
#

TemplateSyntaxError: unexpected '}', expected ')'

marble jackal
shadow gorge
hoary surge
hoary surge
#

when i define a template switch: Where can i find it in the UI?

wheat junco
marble jackal
#

It's an entity, not a device. So in the automation GUI you won't find it under device trigger/condition/action

hoary surge
#

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. 🙂

mighty ledge
#

if you add anything via yaml, you have to find your entities via developer tools -> states or the entities list.

marble jackal
proud night
#

oh shoot. ok ill move it 🙂

light scroll
#

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?
inner mesa
#

add a unit_of_measurement

light scroll
blissful yarrow
#

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 }}"
inner mesa
#

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

cursive totem
#

Can anyone share with me an example of using the fire event action in developer tools?

inner mesa
#

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

cursive totem
#

I’m trying to learn how to use them (events) but I’m just not sure what the Event Data (YAML, optional) section does

inner mesa
#

Whatever you want to send with the event

#

Could be nothing, which is why it's optional

cursive totem
#

I got it

inner mesa
#

It's dependent on the event

cursive totem
#

Just figured it out

#

But I need to know what that event might do/ say when it’s fired natively

inner mesa
#

Then listen for it

cursive totem
#

In order to get the data to fire it as a test

inner mesa
#

And you will see

cursive totem
#

Guess I’ll have to try and find a way to force it to fire

inner mesa
#

Like I said, there are easier ways to cause events to be fired in many cases

cursive totem
#

Yea.. maybe restating the integration or something

inner mesa
#

Don't use that to generate state_changed, just change the state in devtools -> States, for instance

winged torrent
#

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 🙂

inner mesa
#

but I can't manage to get this to work:
🤷

#

please don't make us guess in what way it doesn't work

winged torrent
#

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.

winged torrent
#

ok, so my issue is that the "unique_id" field is not used for the sensor id.

still plank
#

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?

inner mesa
#

{{ area_entities('Family Room')|select('match', 'light.')|select('is_state', 'on')|list|length == 0 }}

slate fossil
#

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.

inner mesa
#

Nope

slate fossil
#

Would that be something worthy of doing of Feature Request? Would it be something that could theoretically be implemented?

marsh cairn
#

A usual binary template sensor with device class problem does that

slate fossil
#

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. 😕

jovial pilot
#

I figured out my template question - Home assistant reports states without capitalizing the first letter >.<

inner mesa
#

Generally, yes. devtools -> States

lofty mason
slate fossil
lofty mason
inner mesa
#

I stand corrected:

#

Nice!

slate fossil
#

I'm on the same page. 😆

fiery sage
#

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?

lucid thicket
slate fossil
# lofty mason And FYI, had you left it as a sensor, I believe you could have made it an `enum`...

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

mighty ledge
marble jackal
#

As far as I remember, attributes in template sensors only accept templates and strings

#

So a YAML formatted list won't work

slate fossil
#

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.

mighty ledge
slate fossil
#

What kind of update? I'm on 2023.11.6.

cursive totem
plain magnetBOT
#

@solid charm I converted your message into a file since it's above 15 lines :+1:

haughty breach
#

States are always strings.

solid charm
#

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
haughty breach
#

Attributes can be other datatypes.

solid charm
#

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 [

haughty breach
#

Put your array inside {{}}

solid charm
#

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}}
haughty breach
#

otherwise it's just a string

solid charm
#

Thats the sensor

#

Even if I return rates[0] its resolving as a string not a dict or list

marble jackal
#

@solid charm Are you using the legacy_templates: true option in your configuration?

acoustic arch
#

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

mighty ledge
#

Just add an input boolean and add it as a condition.

quick pelican
#

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...

mighty ledge
#

The only way is with a custom card, like card mod, custom button card, or base theming (which will be all entities)

marble jackal
#

mushroom template cards is also an option

quick pelican
#

the point is, that I already have a picture-elements card in use and don't want to change that...

marble jackal
#

then you can use card-mod

fluid fern
#

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') }}

mighty ledge
#

you can make a template binary_sensor

fluid fern
#

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

stuck sedge
#

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

inner mesa
#

templates don't have access to history

stuck sedge
#

ok, any other way?

#

with a helper or some such thing?

stuck sedge
#

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 :))

mighty ledge
tight tundra
#

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).

inner mesa
#

That's complaining about where you called it

#

Not the switch itself

tight tundra
#

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.

inner mesa
#

Yeah, probably needed quotes

acoustic arch
marble jackal
#

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

acoustic arch
#

ok so im going to set variabbles on a per attribute basis then

marble jackal
#
attributes:
  some_attribute: "{{ template }}"
  another_attribute: "{{ another template }}"
acoustic arch
#

thank you!

stable wagon
#

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"; ]]]

ember saffron
#

is there an easy way to get all entitiy written into a log or file of a domain? eg. switch?

acoustic arch
#
  {% 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(...?...)

marble jackal
#

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

acoustic arch
#

thx! i was putting the pipe at the wrong place then 🙂

#

you are gold. bedankt 🤗

ruby zephyr
#

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

marble jackal
#

@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

ruby zephyr
#

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'

mighty ledge
#

check the pins

marble jackal
#

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
mighty ledge
#

Didn't even look at the entity_id, good catch

#

also, float isn't even needed for that

marble jackal
#

@ruby zephyr it's option 2, the wrong entity_id. You switched the dot and undersccore. It's input_number. not input.number_

plain magnetBOT
#

@onyx hare I converted your message into a file since it's above 15 lines :+1:

onyx hare
marble jackal
#

Or just create a binary sensor group in the GUI (under helpers)

floral shuttle
#

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?

mighty ledge
#

we'd need to see what's in batteries

floral shuttle
#

sure. wait a sec

mighty ledge
#

only other possible spot for the issue would be w/ states[s]

floral shuttle
#
{%- 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 -%}```
mighty ledge
#

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

onyx hare
mighty ledge
floral shuttle
#

please wait a sec. this is the main/only change in the template is it? {%- set ns.batt_low = ns.batt_low + [s] %}

mighty ledge
#

yes

floral shuttle
#

cool

mighty ledge
#

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

marble jackal
floral shuttle
#

right, didnt think of that, such a habit of adding those defaults

mighty ledge
#

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

floral shuttle
#

yes, youre right...

mighty ledge
#

thats how people end up w/ templates like this {{ states('sensor.abc') | float }}, where the float serves no purpose

floral shuttle
#

should I do is_number there, instead of filtering unknown/unavailable?

mighty ledge
#

if you want

floral shuttle
#

seems more focussed on being a number

mighty ledge
#

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 -%}
floral shuttle
#

yep, thanks!

#

we do still need the |selectattr('attributes.device_class','defined') ? Seem to recall Frenck saying that was now no longer required

mighty ledge
#

it might not be required anymore

#

lemme test real quick

floral shuttle
#

doesnt throw an error....

mighty ledge
#

i'd wager the null change for attributes made it so we don't need this anymore

floral shuttle
#

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

mighty ledge
marble jackal
#

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

floral shuttle
#

ill restart and see what happens there

marble jackal
#

But indeed it doesn't complain about state objects without the attribute anymore

mighty ledge
#

I'll have to see what was changed

#

that's a built in, so we must have overroad it

floral shuttle
mighty ledge
#

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

floral shuttle
#

those changes in the frontend need firm cache refreshes

mighty ledge
#

It's just like lovelace gen, where the frontend is loaded before everything else

floral shuttle
#

I see, if it sticks, I'll re-add those, I hate these warnings errors

mighty ledge
#

if you're using it in a markdown card, then definitely re-add those defaults

ruby zephyr
floral shuttle
plain magnetBOT
#

@waxen meadow I converted your message into a file since it's above 15 lines :+1:

waxen meadow
#

Hi someone help me with this template what am I doing wrong there?

mighty ledge
#
payload: >
  [...
  ]
#

i.e, add >, remove exterior quotes

waxen meadow
onyx notch
#

Jinja allows you to calculate, can I take the state of two temperature sensors, subtract them and display as a template sensor?

inner mesa
#

Yes, of course

#

Didn't you do exactly that earlier?

onyx notch
#

I did some evaluations, looking back through my devices for what I've done

inner mesa
#

It's no different

#

{{ states('sensor.one')|float - states('sensor.two')|float }}

onyx notch
#

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 ]]]

mighty ledge
#

why would state_with_unit work?

#

you just make that up?

onyx notch
mighty ledge
#

that's a jinja template

#

custom button card is JS

#

you have to use the methods available in custom button card

inner mesa
#

that's a weird one. The docs make it look like it's part of the state object

onyx notch
#

In my sensor template I am using this, can the value be rounded and UOM displayed

  unit_of_measurement: °F
  device_class: temperature```
inner mesa
onyx notch
#

I though it was a cool function 🤷‍♂️

inner mesa
#

round is....round

onyx notch
#

In the Template sensor value template I added it as temperature') | float | round }}" but doesn't seems to be honoring it

inner mesa
#

need more than that little fragment

onyx notch
#
 unit_of_measurement: °F
 device_class: temperature```
inner mesa
#

you just rounded the second thing

#

you're missing parentheses

onyx notch
#

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) }}

waxen meadow
#

Hi i have question how im make rest sensor that it would be updated every 30 minutes? thx

glad geode
#

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?

spiral imp
#

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

inner mesa
#

use today_at('20:00')

stark current
#

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') }}
inner mesa
#

binary_sensor entities are only on or off, not true

stark current
#

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') }}
inner mesa
#

please format

plain magnetBOT
#

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.

inner mesa
#

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

stark current
#

I need the delay_on

inner mesa
#

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

stark current
#

no there are zero actions like delay_on or delay_off in the UI

inner mesa
#

then you can't use the UI for your sensor and need to define it in YAML

stark current
#

ugh

inner mesa
#

it's not intended for complex configurations

stark current
#

can't see how the UI is good for anything...but ok thx

inner mesa
#

simple things

#

that's kind of an extreme position 🤷

stark current
#

a delay of 5 seconds is simple, IMHO

inner mesa
#

apparently not

#

anyway, opinions and such

stark current
#

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

onyx notch
#

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?

mighty ledge
#

you can call servivces directly from the buttons in the frontend boy changing the tap action

onyx notch
#

Would that have to be done in a button card? I have an existing type: entities card with the other robot info in it.

mighty ledge
#

that can be done pretty much anywhere that allows tap_action

onyx notch
#

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.

mighty ledge
#

entities card allows tap actions for the button

onyx notch
#

But if I button template it I can also expose it to the voice assistant and automations

mighty ledge
#

then by all means, make a button template

onyx notch
#

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`
mighty ledge
#

where'd you get that yaml from?

onyx notch
#

buy looking at my switch templet configurations

mighty ledge
#

You should instead look at the examples in the documentation page

plain magnetBOT
mighty ledge
#

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.

onyx notch
#

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:```
mighty ledge
#

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

onyx notch
#

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?

mighty ledge
#

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.

onyx notch
#

So I am confused, according to the doc it shows optional fields for a button is icon template.

mighty ledge
#

right, so then you can use it

#

not sure why that's confusing

onyx notch
#

because I asked and you said no

mighty ledge
#

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

onyx notch
#

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

mighty ledge
#

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

atomic blade
#

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

ember cloud
#

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?

inner mesa
#

I see nothing in the docs that say a template is supported there

ember cloud
ember cloud
plain magnetBOT
#

@limber haven I converted your message into a file since it's above 15 lines :+1:

limber haven
#

Basically Im not 100% how to get that 'if' statment to apply the flash if teh value of the sensor is over 100.

potent ridge
#

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?

inner mesa
hardy laurel
#

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 }}
inner mesa
#

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

hardy laurel
#

I see, I tried doing

{{ number('input_number.garage_door_z') < 500 }}

But the preview shows Unavailable as the computed state

plain magnetBOT
#

@forest ferry I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

{{ states('input_number.garage_door_z')|float < 500 }}

hardy laurel
#
{{ states('input_number.garage_door_z')|float < 500 }}
inner mesa
#

I suggest consulting the docs rather than trying random stuff 🙂

hardy laurel
#

haha, thanks @inner mesa

forest ferry
#

😒 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 %}
inner mesa
#

use this.state

hardy laurel
#

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?

inner mesa
#

events have entities now

#

but yes, you can create trigger-based template sensors

#

I've never used them, but there they are

forest ferry
# inner mesa use `this.state`

It works with "sensor"

    state: >-
      {% if '9 h, en matin' in trigger.event.data["text"] %}
        1
      {% else %}   
        {{ this.state }}  
      {% endif %}
#

but not "binary_sensor"

inner mesa
#

that's curious

hardy laurel
#

So if I don't see an event entity for the device in question, then I need to go with a trigger based template?

forest ferry
#

forget it , a typo.

inner mesa
hardy laurel
#

I'm trying to simplify how I track the z-index of a sensor on the garage door.

Right now I have:

  1. A binary_sensor.garage_door_sensor the raises a zha_event for x_axis, y_axis, and z_axis values
  2. A number helper input_number.garage_door_z
  3. An automation that is triggered by zha_events for the binary_sensor.garage_door_sensor and captures the value of the z_axis event, storing it in that number helper
  4. A binary template sensor binary_sensor.garage_door_position that compares the input number to be < 500 to 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.

inner mesa
#

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

hardy laurel
#

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 }}"
zealous sparrow
#

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

inner mesa
#

All states are strings

#

Add |float

zealous sparrow
#

Oh yeah, I just remembered having to do that once before. That worked perfect, thanks 🙂

timid vigil
#

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

zealous sparrow
#

I'm able to set an offset on the sunset trigger

platform: sun
event: sunset
offset: "-00:30:00"
plain magnetBOT
#

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.

timid vigil
#

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

timid vigil
#

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

unkempt flame
#

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?

dense hamlet
#

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')) }}")
fickle sand
#

It indicates that the attribute's value is somehow None

ember saffron
#

is it possible to create an own update domain entity?

marble jackal
marble jackal
dense hamlet
#

@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 ?

marble jackal
#
value_template: "{{ '{:.1%}'.format(state_attr('media_player.denon_avc_x4700h', 'volume_level') | float(0)) }}"
#

that should work

dense hamlet
#

Awesome, will give that a go, thanks a bunch @marble jackal

ember saffron
#

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"

atomic blade
#

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

wanton sapphire
atomic blade
#

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

atomic blade
#

Did you forget to paste code?

steady vortex
harsh briar
#

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

willow wing
#

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') }}
mighty ledge
willow wing
willow wing
#

what are pins?

mighty ledge
#

discord pins

willow wing
#

ahh okay thanks

mighty ledge
#

Man, that breaking default change was in 2022.2 and we are still getting hits about it today

willow wing
#

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) }}

mighty ledge
#

default goes in as_timestamp

willow wing
#

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') }}

mighty ledge
#

nope, you put it in state_attr(), needs to go in as_timestamp().

willow wing
#

no plan sorry

mighty ledge
#

delete 1 of the doulbe )

#

and move it back to after uploaded')

#

you can test all of this in the template editor

willow wing
#

{{ as_timestamp(state_attr('sensor.backup_state', 'last_uploaded') default = 0) | timestamp_custom('%d.%m.%Y - %H:%M Uhr') }}

#

like this?

mighty ledge
#

you still need the comma

#

before default

willow wing
#

ah okay i understand, thank you

ember saffron
#

Integration or automations are not used with the entities

limber haven
#

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)

mighty ledge
#

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 }}
limber haven
#

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

mighty ledge
#

change the last line to

#
{{ (count * interval).total_seconds() | timestamp_custom("%H:%M", false) }}
limber haven
#

Ah conver it to total seconds..

#

Was trying string editing which.. apparently wont work with timedelta

mighty ledge
#

yeah, you could have done it that way too

#
{{ ((count * interval) | string)[:-3] }}
limber haven
#

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

mighty ledge
#

post the full yaml please

limber haven
#
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'

mighty ledge
limber haven
#

Hm... I thinkt he problem is it might not like the leading 0 either lol..

mighty ledge
#

change %H to %I

limber haven
#

If I just put in a raw string, 08:00 errors, 8:00 doesnt, good lord this thing is picky

mighty ledge
#

sorry, not %i

#

%-H

limber haven
#

Well it thew a green checkmark 😄

mighty ledge
#

progress?

limber haven
#

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

azure drum
#

'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...

marble jackal
#

doesn't the energy dashboard show that just fine?

azure drum
#

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...

dry narwhal
#

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.

inner mesa
#

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

marble jackal
#

You also need | map(attribute='attributes.temperature')

inner mesa
#

That, too

hearty verge
#

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

dry narwhal
#

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 }}
marble jackal
#

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

dusty stone
plain magnetBOT
#

@gilded saffron I converted your message into a file since it's above 15 lines :+1:

gilded saffron
lucid thicket
mighty ledge
#

Update to the latest version and I can help you make those appear in a single device.

hearty verge
mighty ledge
gilded saffron
mighty ledge
plain magnetBOT
#

@gilded saffron I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

You need to move it to the MQTT section

gilded saffron
#

ah i see

#

oh wait it is

#

its under mqtt: !include_dir_merge_list mqtt/

mighty ledge
#

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: ...
willow wing
#

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' ) }}%

mighty ledge
#

pleas learn to format your code

#

this is like the 8th time you've done this

plain magnetBOT
#

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.

inner mesa
#

And the answer is to remove the trailing %. It's a pretty clear error messasge

willow wing
#

alright, thank you

thorny cargo
#

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.

inner mesa
#

make a trigger-based template sensor

#

trigger when it turns on, use {{ now() }} for the state

thorny cargo
#

can you elaborate on that a bit more pls

thorny cargo
#

think i got it, thx!

#

do i need to restart ha after editing my configuration.yaml?

mighty ledge
#

if you already have template sensors, you can reload

thorny cargo
#

i already go one binary sensor

mighty ledge
#

then just reload template entities

thorny cargo
#
    - binary_sensor:
        trigger:
          - type: motion
            platform: device
            entity_id: binary_sensor.example
            domain: binary_sensor
        sensor:
          - name: example_latest_motion
            state: '{{ now }}'
mighty ledge
#

now()

#

like rob said

thorny cargo
#

thx

#

Identation etc. correct?

mighty ledge
#

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

inner mesa
#

binary_sensor was my fault, fixed above

mighty ledge
#

oh yeah duh, keep sensor

#

the rest still stands

thorny cargo
#

so if i have multiple binary sensors, i only have one -binary_sensor: ?

inner mesa
#

zero binary sensors

thorny cargo
#

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?

fossil venture
#

Is there a better way to check for midnight than this? {% if {{ [now().hour,now().minute] == [0,0] }} %}

#

maybe {% if now() == today_at() %} ?

inner mesa
#

I doubt that the latter would ever be true because it counts microseconds

fossil venture
#

Yeah thought of that. Especially as the template only updates every minute at most.

inner mesa
#

the first is better, but don't nest your templates

fossil venture
#

Ha. Well spotted. Copy paste error from the template editor

lofty mason
#

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.

fossil venture
#

Yeah could definitely be a problem. I'm not using the second version.

torpid comet
#

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 ... ^

untold hawk
fossil venture
#

It's a daily PV energy meter. It resets at midnight.

mighty ledge
#

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

mighty ledge
mighty ledge
marble jackal
#

Without if

floral shuttle
#

also without the s

torpid comet
# mighty ledge Your error is coming from your interior and exterior quotes. Your color_temp_ke...

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']

leaden lodge
#

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.

inner mesa
#

Then you can use the variable in your template

torpid comet
inner mesa
#

I use PyScript for my more complex automations and where I need multiple instances. I don't use blueprints, so was just guessing

dapper spindle
#

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

inner mesa
#

You didn't say what was wrong ( 😡) but you at least need == instead of =

dapper spindle
#

sorry, it was throwing an error not being able to interperate the =, I'll try the == as suggested. Many thanks

sudden fractal
#

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?

neon lodge
#

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