#templates-archived

1 messages Β· Page 24 of 1

marble jackal
#

HA usually removes the whitespace in the output, you rarely need to put this in yourself

upper basalt
maiden magnet
#

what?

mighty ledge
#

My reply was to hangingbsack

upper basalt
#

that was directed towards dan1002, a little mix-up here now

silent vector
#

I'm guessing I should just set a variable in the next service call.

What would I set it to and later on in the automation I would use the variable to compare against the last updated of an entity. Which time format is best for comparing the 2? The difference will only be a few minutes if that. I want to use it to understand what happened first the service call or the entity last updated.

marble jackal
#
    entity: light.groep_woonkamer
    secondary: >-
      {% set hum = (area_entities(area_id(entity)) | select('is_state_attr', 'device_class', 'humidity') | map('states') | select('is_number') | map('float') | list or [0]) | average | round(0) %}
      {% set temp = (area_entities(area_id(entity)) | select('is_state_attr', 'device_class', 'temperature') | map('states') | select('is_number') | map('float') | list or [0]) | average | round(1) %}
      {% set lux = (area_entities(area_id(entity)) | select('is_state_attr', 'device_class', 'illuminance') | map('states') | select('is_number') | map('float') | list or [0]) | average | round(1) %}
      {{ [ (temp ~ 'Β°C') if temp, (lux ~ ' lux') if lux, (hum ~ '%') if hum] | select() | join(' | ') }}
upper basalt
#

Probably because i have multiline secondary activated?

marble jackal
#

ah, that could indeed be it πŸ™‚

#

no, even with multiline secondary it works fine here

upper basalt
#

I see the issue :p The first value i have on "secondary information" is the name {{area_name(entity) | capitalize}}

#

{{area_name(entity) | capitalize}} {% set hum = area_entities(area_id(entity)) | select('is_state_attr', 'device_class', 'humidity') | map('states') | map('float') | list or [0] | average | round(0)%} {{ hum | average if hum else 'no data' }} %

dry narwhal
#

Tried and failed πŸ˜„

So, as I feared, I cannot use a list to directly search. So I would probably need to search per list item. So kind of search x in (search y in (search z in entity_id)) but that seems very "complicated" but I did not find a pretty solution in docs.

{{ ['-- - --'] + states.sensor|selectattr('entity_id', 'search', ("*Energy*Power".split("*") | select() | list) )|map(attribute='entity_id')|list }}```
marble jackal
#

you want to search for both Power and Energy?

dry narwhal
#

The search term will change depending on an input_text.

marble jackal
#

{{ ['-- - --'] + states.sensor|selectattr('entity_id', 'search', 'Power|Energy') )|map(attribute='entity_id')|list }}

dry narwhal
#

this is just a trial example

#

So the input_text will always be a (or multiple) words separated by *

#

Something like for key in ("*Energy*Power".split("*") | select() | list)?

marble jackal
#

so use join('|') instead of list to allow it to be used in combination with search

#

{{ ['-- - --'] + states.sensor | selectattr('entity_id', 'search', ("*Energy*Power".split("*") | select() | join('|')) ) | map(attribute='entity_id') | list }} this should work, not sure why you are concatinating these two lists here though

#

BTW this will fail, because you will not have any entities with uppercase characters in it

dry narwhal
marble jackal
#

This will probably return a list with sensors:

#

{{ states.sensor | selectattr('entity_id', 'search', ("*Energy*Power".split("*") | select() | join('|')) | lower ) | map(attribute='entity_id') | list }}

dry narwhal
#

The search however now results in an "or" and not an "and" search

marble jackal
#

but you can make it yourself easier to just use a pipe ( |) as seperator

dry narwhal
#

So it will return any sensor with "energy" or "power" in the name.

marble jackal
#

correct

#
{% set search_selection = 'Energy|Power' | lower %}
{{ states.sensor | selectattr('entity_id', 'search', search_selection) | map(attribute='entity_id') | list }}
dry narwhal
#

Sorry, used to auto-entities application, I did not explain.
I was trying to get every sensor that matches that wildcard expression. So the id of the entity must contain both/all search terms, not any

marble jackal
#

then just do two selections

dry narwhal
#

That's why I did the search in search above

marble jackal
#

ah wait, there are not always 2

dry narwhal
#

No, could be more. Or could even be without any *, so only one single string

#

Would it need to be a list after all and then a nested search?

marble jackal
inner mesa
#

That's some regex πŸͺ„

dry narwhal
#

Never in a million years

upper basalt
#

There should really be like a gallery of templates for people to use, and ppl could vote on good and helpful ones etc

sacred sparrow
#

is there a better way to do this:

          {{ iif(state_attr('media_player.living_room_tv_andriod_tv', 'app_name') == 'Netflix',
          states('media_player.living_room_tv_andriod_tv'),
          iff(states('media_player.living_room_tv_kd_75x8500e') == 'playing',
          states('media_player.living_room_tv_google_cast'), 'off'
          )) }}
inner mesa
#

Not really

sacred sparrow
#

I get the error 'UndefinedError: 'iff' is undefined'

full radish
#

I might just not figure out the right terms in my search but is there a way to enumerate state_attr without having its name.

sacred sparrow
#

of course haha

#

thank you

mighty ledge
#

{% for attr, value in states.sensor.xyz.attributes.items() %}

full radish
full radish
mighty ledge
#

you're doing something else wrong

#

do you have the closing {% endfor %}?

full radish
#
{% for attr,value in states.binary_sensor.car_trouble.attributes.items() %}
 {{ attr }}
{% endfor %}
#

Yup it seems if I use the same block and use a sensor and not binary_sensor then its fine. Also sadly I don't have any other Binary sensors with attributes so will need to have to fiddle.

inner mesa
#

exactly that works fine for me with one of my binary_sensor entities

mighty ledge
full radish
#

Ok! so I this is interesting it has to do with the name... I renamed the sensor to car. it was my VIN but tested if you use a sensor that starts with a number its truncating the first charater.

mighty ledge
#

you can't use the . notation when the object_id starts with a number

full radish
#

well I learned that the hard way...

mighty ledge
#

states['binary_sensor.000000'].attributes

#

would be the only way

full radish
#

Ok thanks I'll do it that way.

plain magnetBOT
#

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

uncut compass
#

the for loop is returning 0, where it should return 25

inner mesa
#

you need to use a namespace if you're planning modify a variable inside a for loop and access it outside

uncut compass
#

ah ok that I didn't find in my readings πŸ˜„

#

any documentation I can read on?

inner mesa
uncut compass
#

thanks a lot mate

inner mesa
sacred sparrow
#

Hi all, I am having trouble getting my head around a sensor I am trying to make for my TV.
My TV 'on' state shows fast with the Google cast integration (media_player.living_room_tv_google_cast) but it shows the 'off' state quicker with the sony Bravia integration (media_player.living_room_tv_kd_75x8500e)

#

so far I have

- binary_sensor:
    - name: "Living Room TV Information"
      state: ????
      attributes:
        Media: >
          {{ iif(state_attr('media_player.living_room_tv_andriod_tv', 'app_name') == 'Netflix',
          states('media_player.living_room_tv_andriod_tv'),
          iif(states('media_player.living_room_tv_kd_75x8500e') == 'playing',
          states('media_player.living_room_tv_google_cast'), 'off'
          )) }}
#

but I can't figure out how I would make the state show on/off using 2 different entities

inner mesa
#

or

sacred sparrow
#

I am guessing something like

#
          {{ iif(states('media_player.living_room_tv_kd_75x8500e') == 'off',
          'off', iif( not states('media_player.living_room_tv_google_cast') == 'off',
          'on', 'off'
          )) }}```
inner mesa
#

no, use "or"

floral steeple
#

hey all, I made a 10 min wind speed sensor using stats, but I noticed that if the wind is zero for more than 10 wind, then 10 min sensor goes unavailable. Why would it do that? Should it not be zero, also?

#

10 minute wind speed average sensor

- platform: statistics
  name: "Wind Speed 10 Minute Average"
  entity_id: sensor.windspeed
  state_characteristic: mean
  max_age:
    minutes: 10
  precision: 1
  sampling_size: 35
  unique_id: blah
inner mesa
#

Or you can do this:

{{ iif(['media_player.living_room_tv_kd_75x8500e', 'media_player.living_room_tv_google_cast']|map('states')|select('eq', 'off')|list|length > 0, 'off', 'on')}}
sacred sparrow
#

TypeError: object of type 'generator' has no len()

inner mesa
#

or just {{ iif(is_state('media_player.living_room_tv_kd_75x8500e', 'off') or is_state('media_player.living_room_tv_google_cast', 'off'), 'off', 'on') }}

#

fixed

sacred sparrow
#

the tricky part is media_player.living_room_tv_google_cast needs to be NOT off

#

as it doesn't have 'on'

#

just idle/playing/standby

inner mesa
#

so use the second version and adjust accordingly

#

you can use whatever test you want

#

point is that I don't think the nesting of iif() that you're doing is necessary, and makes it more complicated

sacred sparrow
#

hmm ok let me give that a go πŸ™‚

#

the OFF works as fast as the original entity by the ON is slower

barren umbra
#

or not is_state('media_player.living_room_tv_google_cast', 'playing') ???

sacred sparrow
#

that just stays "off"

barren umbra
#

So on is one of [idle|playing|standby] and off is 'off'?

sacred sparrow
#

yep

sacred sparrow
#

when I change it to:

or not is_state('media_player.living_room_tv_google_cast', 'off'),
'on', 'off') }}
#

on is fast - and off is slow to show

#

this is the part I cant get my head around how to merge the two together so it shows on and off as fast as the original entities

barren umbra
#

I think I understand now.
You have two integrations reporting from 1 tv and you want sensor state:
state == on if Google cast integration is on
state == off if Sony Bravia integration is off

sacred sparrow
#

exactly πŸ™‚

#

the Sony Bravia takes about 2-3 seconds to show the state as off compared to Google Cast - where its the opposite for the on state

barren umbra
#

they both have state off but the integrations' on states are diifferent with one having on and the other having [idle|playing|standby]

sacred sparrow
#

state == on if Google cast integration is playing/idle/buffering/paused
state == off if Sony Bravia integration is off

#

Sony Bravia integration is only 'playing' and 'off'

#

(i just went back through the state history of the entities to get all the states its been the last few days)

#

that why I thought this would be easier:
state == on if Google cast integration is NOT off
state == off if Sony Bravia integration is off

barren umbra
#

I don't think it's possible to evaluate the states in the manner you have visualized
state == off if Sony Bravia integration is off - no problem, but to go beyond that, as long as its state is off the sensor state can only be off. If you 'or' it with Google, doesn't matter what state Google says, the sensor will be still be off. Nor can you 'and' the two as the result will be delayed by the slower integration. And the same goes for if you try and check for 'on' first...
You would need logic to check whether Sony just changed from 'playing' to 'off' then state==off and conversely if Google just changed from 'off' to 'not off' then state==on. I cannot think of a logical way to achieve it...

sacred sparrow
#

ahh so its not just me - no wonder this one is making my head hurt just that little bit more haha

#

I really appreciate your help though

barren umbra
#

No problem! My head is starting to hurt too!

sacred sparrow
#

I wonder if a trigger sensor would help

barren umbra
#

I don't think so. But rather than a templated sensor, what about an input_boolean and an automation triggered by the two media_players?
First one to report on & boolean is turned on
First one to report off and boolean is turned off.
When the other media_player finally catches up, the automation will trigger again changing boolean from on to on or from off to off...no harm, no foul!

sacred sparrow
#

its because the sensor has some attributes too

barren umbra
#

Ah, okay. So, create the boolean + automation and use the state of the boolean for your sensor state...

sacred sparrow
#

sounds like a good idea - I'll see what I come up with - thanks again

floral steeple
barren umbra
#

The sensor turns Unknown if no measurements are stored or if the source sensor is not updated within the time period

max_age time (optional)
Maximum age of source sensor measurements stored. Setting this to a time period will cause older values to be discarded. If omitted, the number of considered source sensor measurements is limited by sampling_size only. Set both parameters appropriately to create suited limits for your use case. The sensor value will become unknown if the source sensor is not updated within the time period. A statistics sensor requires sampling_size, max_age, or both to be defined.

age_coverage_ratio
Only when max_age is defined. Ratio (0.0-1.0) of the configured age of source sensor measurements considered (time period max_age) covered in-between the oldest and newest stored values. A low number can indicate an unwanted mismatch between the configured limits and the source sensor behavior. The value 1.0 represents at least two values covering the full time period. Value 0 is the result of only one measurement considered. The sensor turns Unknown if no measurements are stored.

#

I believe for stats, the source sensor would have to continue reporting 0 within the 10 minute window. I expect it's not doing that.

floral steeple
#

Hmm yeah, the docs are not clear on this. Wonder if I should report this as bug, but I figure I ask here first.

barren umbra
#

If there are no samples then it's unknown. Not a bug IMO...

floral steeple
#

But zero is a value for wind...

#

Interesting

barren umbra
#

But stats needs samples of the state, If the state is 0 and unchanged for 10 minutes then stats will go unknown. Same would be happen if the source reported 15 and remained 15 without additional updates for > 10 minutes...

floral steeple
#

Got it, makes sense, but what if it keeps reporting zero?

#

For more than 10 minutes

barren umbra
#

I would expect if your source kept reporting 0, still 0, still 0, still 0, still 0... the stat sensor would show 0

floral steeple
#

Exactly! But it's unknown.

barren umbra
#

Is the source sensor repeatedly reporting 0?

#

Stats uses logbook entries. If the logbook shows repeated 0's within the last 10 mins then I think we have a bug...

floral steeple
#

ok, we are good...there is no bug. I just check the history of the sensor....and despite the source reporting zero (via MQTT) on EVERY 16 second update, HASS discovery does not update untill the value is different

rose scroll
#

Yes, this is the expected behaviour for state objects.

floral steeple
#

ok, it all makes sense now.

#

thanks every one,

rose scroll
#

If it bothers you that the stats sensor goes to unknown when there are no recent updates, you could make a template sensor that takes the state of the statistic sensor when it is not unknown, else takes the state of the wind sensor.

barren umbra
#

If you want your frontend to show '0' when stats is unknown you'd have to template it...

#

or, not worry about it!!

floral steeple
#

that is a great idea beucase it shows up as some non numeric code message on my Fully Kiosk

#

so you'll know when there is no wind

#

its an eye sore

#

lol

barren umbra
#

Not a good time to be sailing either!

#

While raking leaves it can be a good thing...

floral steeple
#

lol ok, take care all

#

until next time....like tomorrow probably when I try to make this template sensor

barren umbra
#

That should be a lot easier than trying to wrap my head around onethreeseven's dual tv integration tug-of-war! πŸ˜΅β€πŸ’«

thorny snow
#

i got current mqtt sensor: https://dpaste.org/zGNqh and i want to create 2 new one but my mqtt incoming json are having same variable name PW0 and PW1, how can i distinguish them based on serial for instance ?

#

i want to create PW2 and PW3 using the second json (serial=703000368301)

native mirage
#

I'm just starting to fiddle around with templates and using "local" variables like this:
{% set max_ist_temp_diff = float(99) %}
For testing the template in the developer section of the HA webinterface: what would be the equivalent of printing that certain var and not just the result of the template?

marble jackal
#

{{ max_ist_temp_diff }}

#

BTW, no need to convert 99 to a float

native mirage
#

And I tried {% max_ist_temp_diff %} πŸ€¦β€β™‚οΈ

#

is there an automatic type conversion going on later when int and float meet?

nimble copper
#

I've created a last_motion template sensor that tracks which motion sensor was last turned on.

I'm trying to keep a history of the motion events in the attributes.

So that I can see what order the motion sensors are toggled in.

However, the this state doesn't seem to be working as I'd anticapted.

What's going wrong?

plain magnetBOT
marble jackal
silent vector
#

In my template sensor my attributes will have a state sensor value of 'active event's 'active notification' 'inactive'. What would be a clean way to know if there's more than 1 with either 'active event' or 'active notification'

https://dpaste.org/pMQbk

thorny snow
marble jackal
#

states(this.entity_id) will give the current state

thorny snow
#

can i add : value_template: "{{ value_json.pw0 if value_json.serial == "703000069723" }}"

mighty ledge
thorny snow
#

i want to have a mqtt sensor based on a json where the value is determined by the serial

#

{"serial":"703000368301","acv":0,"freq":0,"temp":0,"pw0":0,"pw1":0,"en0":2.7,"en1":2.3,"totalpwr":0,"totalen":5.0}'

mighty ledge
#

if your topic is an event stream, then you should be using a template sensor instead of a mqtt sensor

#

as mqtt can't handle event streams

thorny snow
#

it is an inverter sending power of my solar pannel

#

every 3mn

#

i ve 2 inverters with 2 different serial and they send these values

#

what is an event stream ?

mighty ledge
#
template:
- trigger:
  - platform: mqtt
    topic: aps/in
    variables:
      value_json: "{{ trigger.payload_json }}"
  sensor:
  - name: pw0
    unit_of_measurement: W
    state: >
      {% if value_json.serial == '703000069723' %}
        {{ value_json.pw0 }}
      {% else %}
        {{ this.state if this is defined and this.state is defined else 'unknown' }}
      {% endif %}
    state_class: total
    device_class: power
  - name: pw1
    unit_of_measurement: W
    state: >
      {% if value_json.serial == '703000368301' %}
        {{ value_json.pw1 }}
      {% else %}
        {{ this.state if this is defined and this.state is defined else 'unknown' }}
      {% endif %}
    state_class: total
    device_class: power
#

You have an event stream. Meaning your inverter doesn't send the states to different topics

thorny snow
#

thanks. so i can't use mqtt sensor as i tried, i ve to replace it by your template code, right ?

mighty ledge
#

no

#

you have to use a template sensor because you have an event stream

thorny snow
#

but previously it was working like that

#

today i added the second inverter, that's why i've issue

#

the new inverter is overring value of first one

mighty ledge
#

right, so it went from 1 entity to 2 entites on the same topic

#

changing it from a single device to mutliple devices

thorny snow
#

yes 2 entitees on same topic

mighty ledge
#

i.e.. changing it to an event stream

#

if you can separate the topics on the device, I would do that

#

however if you can't, you have to switch to a template sensor

thorny snow
#

:Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['sensor'][0]['state']. Got "{% if value_json.serial == '703000069723' }}\n {{ value_json.pw0 }}\n{% else %}\n {{ this.state if this is defined and this.state is defined else 'unknown' }}\n{% endif %}\n". (See /home/thoht/.homeassistant/configuration.yaml, line 838).

#

i got this error when adding the template code

mighty ledge
#

how are you adding that to configuration.yaml?

thorny snow
#

i put it on configuration.yaml

#

then i run : hass --script check_config

mighty ledge
#

you for some reason didn't copy what I wrote

#

copy/paste what I wrote, do not try to correct anything

thorny snow
#

i did a copy/paste

mighty ledge
#

no you didn't

thorny snow
#

let me try again

mighty ledge
#

You put an extra - in the wrong spot

thorny snow
#

yes because i got already a section here with a sensor

#

ok i ve commented my existing sensor

#

ERROR:homeassistant.config:Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['sensor'][0]['state']. Got "{% if value_json.serial == '703000069723' }}\n {{ value_json.pw0 }}\n{% else %}\n {{ this.state if this is defined and this.state is defined else 'unknown' }}\n{% endif %}\n". (See /home/thoht/.homeassistant/configuration.yaml, line 832).

#

now i got this error

mighty ledge
thorny snow
#

i did a raw copy/paste this time

mighty ledge
#

right but that error is old

thorny snow
mighty ledge
#

ok?

#

what errors are in your logs the template is correct

#

are you runing some custom error checker? if yes, don't do that

thorny snow
#

(venv_3.9.2) thoht@rpi3b-hass:~/.homeassistant$ date; hass --script check_config
Tue 10 Jan 13:46:47 CET 2023
Testing configuration at /home/thoht/.homeassistant
ERROR:homeassistant.config:Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['sensor'][0]['state']. Got "{% if value_json.serial == '703000069723' }}\n {{ value_json.pw0 }}\n{% else %}\n {{ this.state if this is defined and this.state is defined else 'unknown' }}\n{% endif %}\n". (See /home/thoht/.homeassistant/configuration.yaml, line 832).

#

i got same error, i put date before doing the check

mighty ledge
#

you need to run the normal config check and then restart templates normally for the normal error not some bullshit outside software

#

ah, ok, see problem

thorny snow
#

it is the native hass checker

thorny snow
mighty ledge
#

last }} should be %} for the first line under state

thorny snow
#

huh ?

#

{% if value_json.serial == '703000069723' }} ==> should be {% if value_json.serial == '703000069723' %} ?

mighty ledge
#

yes

thorny snow
#

i got now this err: ERROR:homeassistant.config:Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['sensor'][0]['state']. Got "{% if value_json.serial == '703000069723' }}\n {{ value_json.pw0 }}\n{% else %}\n {{ this.state if this is defined and this.state is defined else 'unknown' %}\n{% endif %}\n". (See /home/thoht/.homeassistant/configuration.yaml, line 832).

mighty ledge
#

there's 2 templates, both need to be corrected

thorny snow
#

i did on both

mighty ledge
#

also, that's the exact same error

thorny snow
mighty ledge
#

bro

thorny snow
#

maybe i should modify the begining also

#

{%

mighty ledge
#

you edited the wrong line

thorny snow
#

oh ?

mighty ledge
#

then you edited this {{ this.state if this is defined and this.state is defined else 'unknown' %}

#

so you just made it worse

#

instead of 2 broken lines, you now have 4

#

change what you did back, and edit the line I originally said yes to

#

if you're really unsure, I updated my post above

thorny snow
#

sorry, i guess my eyes are not in face today

#

Testing configuration at /home/thoht/.homeassistant
(venv_3.9.2) thoht@rpi3b-hass:~/.homeassistant$

#

good !

#

thanks @mighty ledge for your patience

mighty ledge
#

np

thorny snow
#

i ve to go to take kids at school then i'll check result, i'll be back in 1h, thanks again

mighty ledge
#

95% sure it should work

#

it'll be unkonwn until the topic updates

#

then it should be good from then on

silent vector
#

In my template sensor my attributes will have a state sensor value of 'active event' 'active notification' 'inactive'. What would be a clean way to know if there's more than 1 with either 'active event' or 'active notification'

https://dpaste.org/pMQbk

tepid onyx
silent seal
#

What issue?

#

Where/how are you using this?

tepid onyx
#

THe problem and code is outlined in the URL

#

what part doesn't make sense?

thorny snow
#

and i forced an update and still same

#

in devtools, sensor.pw0=unavailable

silent seal
# tepid onyx THe problem and code is outlined in the URL

Attempting to parse the below json using 2 fields. "id" and "type". Both are adding correctly to a yaml list as a variable in the automation. Using an if statement doesn't seems to recognise the wait.trigger.event.data.type list
What action are you using in the automation? Where is this data stored/coming from in the automation?

tepid onyx
#

data is coming from a kodi media centre that returns the json snippet. it's using service: kodi.call_method and service: kodi.call_method_result from the script... The issue appears with the code in the namespace section of the script with the if statement using wait.trigger.event.data.type

#

you'd have to create another sensor to get that data out of the sqllite or maria db from that time ago you wanted. then you can use the states(sensor) and compare it with the states(sensor.sql_value)

#

oop he went away

thorny snow
#

but my sensor value are reporting "unavailable"

mighty ledge
thorny snow
#

when grepping pw0, i got only this: Jan 10 14:55:10 rpi3b-hass hass[8534]: #033[32m2023-01-10 14:55:10.546 INFO (Recorder) [homeassistant.components.sensor.recorder] Compiling initial sum statistics for sensor.pw0_2, zero point set to 190.7#033[0m

#

it is 1h ago

mighty ledge
#

don't grep that

#

look for errors

#

manually

maiden magnet
#

Hi
How can i send a telegram notification with a variable text value? the name of the helper is "input_text.zustand"

service: telegram_bot.send_message
data:
  message: Hi, Scarriffle ist derzeit (variable) ```
thorny snow
#

when grepping ERROR, i see some error but on some other template sensor not related

#

nothing special in log at the end

mighty ledge
#

you can try adjusting your trigger to solve the problem

upper basalt
#

Is it normal for template + decluttering card to kill performance? One of my views is 70% jinja/templates (UI Mode) and sometimes really slow to load

thorny snow
mighty ledge
#

read up on what payload does and value_template

thorny snow
#

sounds complicated 😦

#

any clue to help me ?

thorny snow
#

Finaly, i removed the config you sent and i modified the mqtt sensor as below: mqtt:
sensor:

- name: "pw0"
  state_topic: "aps/in"
  unit_of_measurement: "W"
  value_template: >
    {% if value_json is defined and value_json.serial == '703000069723' %}
      {{ value_json.pw0 }}
    {% else %}
      {{ states('sensor.pw0') }}
    {% endif %}
  payload_available: "online"
  payload_not_available: "offline"
  unique_id: β€œpw0”
  state_class: total
  device_class: power
#

and it works !

#

πŸ˜„

tepid onyx
#

@silent seal http://pastie.org/p/0qw7nsA3KcywcmG7atW3QV was solved with:
data: method: Playlist.Add item: > {% set ns = namespace(items=[]) %} {% for plid in wait.trigger.event.data.plids %} {% set item_1 = wait.trigger.event.data.plids[loop.index-1] %} {% set item_2 = wait.trigger.event.data.pltype[loop.index-1] %} {% if item_2 == 'episode' %} {% set ns.items = ns.items + [ dict(episodeid=item_1) ] %} {% else %} {% set ns.items = ns.items + [ dict(movieid=item_1) ] %} {% endif %} {% endfor %} {{ ns.items }}
As there appears no zip() function for HA jinja...

mighty ledge
#

there isn't any

#

zip func

#

I have an open commit adding it that I never delivered 🀣

#

same for enumerate()

tepid onyx
#

πŸ™‚

thorny snow
#

i ve create 2 sensor and want now a new sensor which does the sum of the 2 existing sensor

#
  • platform: min_max
    name: totalen
    type: sum
    entity_ids:
    - sensor.totalen0
    - sensor.totalen1
#

this is my code in sensor section

#

i got value for totalen0 and totalen1 but NO VALUE for totalen... what did i do wrongly ?

inner mesa
#

what do you mean by "NO VALUE"?

#

literally that string?

thorny snow
plain magnetBOT
#

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

thorny snow
#

there is value on totalen0 and totalen1 ( 16000 and 0) but it totalen kept beeing "unvailable"

opaque creek
#

Heya! I'm using a code with this line:
{{int(states('sensor.multisensor_vinden_temp'))-1}}
But int makes the state remove ".X" so if the sensor above is 7.4 that code with just turn it 6.
How do I change the code for it to return 6.4?

inner mesa
thorny snow
mighty ledge
#

why don't you retain your MQTT data

thorny snow
mighty ledge
#

so that they aren't unavailable on restart

inner mesa
#

and the answer is probably that you need to provide defaults

thorny snow
#

petro how ?

mighty ledge
#

retain flag

#

in mqtt, should be covered in the docs

#

basically tells HA to keep the value it see's in the topic when you start up instead of waiting for a topic change

inner mesa
#

you also really need to provide a default. My guess is this:

If the source sensor provides an unknown state, it will be ignored in the calculation except for sum where it will set the state to unknown.

#

looks like you can't "fix" it with a default in that integration

thorny snow
inner mesa
#

needs to be set by whatever publishes the value

thorny snow
#

it is done by a raspbery which sends that: systemCmd = mosquitto_pub -h 192.168.1.53 -p 1883 -t aps/in -m '{"serial":"703000069723","acv":0,"freq":0,"temp":0,"pw0":0,"pw1":0,"en0":1032.5,"en1":641.2,"totalpwr":0,"totalen":0.0}'

#

ok flag --retain has to be added

inner mesa
#

-r,
--retain
If retain is given, the message will be retained as a "last known good" value on the broker. See mqtt(7) for more information. Note that zero length payloads are never retained. If you send a zero length payload retained message it will clear any retained message on the topic.

#

yes

thorny snow
#

this code is also not mine, it comes from a github project, i've to check with the owner

inner mesa
#

you can presumably just add it youself

thorny snow
#

it is a perl which call a compiled cgi

#

my $mosquittocmd = "/usr/lib/cgi-bin/ecu/sendMqtt.cgi $_";

#

the cgi is cpp compiled file

inner mesa
#

sheesh

thorny snow
#

oh there is the source

#

string systemCmd="mosquitto_pub -h " + mqtt_adr + " -p " + mqtt_port + " -t " + mqtt_out + " -m " + toMqtt ;

#

i guess i can modify it then recompile it

solemn frost
#

Perl and C++ CGI, dang. Is my calendar correct?

inner mesa
#

mmm, early 1990s...

thorny snow
#

OR i could trick the system by adding a bash alias like mosquitto_pub="mosquitto_pub -r"

#

renaming /usr/local/bin/mosquitto_pub by a shell script which call it in another path wih -r

#

my imagination will destroy everything 😦

inner mesa
#

you seem to have the tools, so knock yourself out

thorny snow
plush harbor
#

I've got my dryer plugged into a zigbee power monitoring plug socket and I am trying to create a sensor to see when it is on/off based on the power usage. The problem is that it does these short blips to 0 that I want it to ignore so I can't use do sensor.tumble_power == 0 or similar. I have been banging my head of this for ages but there is always some glitch. At the moment it's that if I restart HA it thinks that the tumble is on for 3 minutes before it corrects itself. Can someone have a look at my current sensor template? Thanks

{% set onNow = states.sensor.tumble_power.state | int > 0 -%}
{% set persisted = now() - states.sensor.tumble_power.last_changed >= timedelta( minutes=3 ) -%}
{{ onNow or ( not onNow and not persisted ) }}

obtuse zephyr
plush harbor
#

Yeah that would probably do it

sinful blade
#

hi

#

i am using {{ trigger.calendar_event.start }} in a data_template

#

and i dont know how to show only the time without date in the notification

rapid hawk
#

I am trying to figure out how to print individual device states. Reading through documentation at the moment.\

sinful blade
#

{{ trigger.calendar_event.start }} looks like this 2023-01-10T20:04:00+00:00

silent seal
inner mesa
#

yep, or the caveman: {{ states.automation.landscape_lights.attributes.last_triggered.time() }}

rapid hawk
#

That is what I am reading through actually.

silent seal
#

Yes, the specific part I linked you to tells you how to get the state πŸ˜‰

sinful blade
#

@silent seal Message malformed: template value should be a string for dictionary value @ data['action'][0]['data_template']

inner mesa
#

well, you're using data_template, which was deprecated years ago

#

not your problem, but still

#

and I'm 90% sure that you didn't follow rule #1 from that page

sinful blade
#

ok i will look at that... thanks @inner mesa @silent seal

rapid hawk
#

I can getsensor. to pop up possible options. For some reason state. doesn't pop up options but works if you know what to write. The sensors I see in sensor. is everything about the sensor except what it does.

inner mesa
#

it's states. and not state.

#

and it also isn't the start of an entity, so probably won't autocomplete to all possible domains

silent seal
#

And as per the section of docs I linked you to, you shouldn't use states. unless there's no other option πŸ˜‰

inner mesa
#

I do love the heck out of that autocomplete

#

it's really helpful

silent seal
#

Yup, I'm so glad it was added

gritty anchor
#

Hey, so I tried to turn the built in weather forecast into a few sensor values (so I can track them over time).
Now I'd like to pull the value and unit from the integration like this:

template:
  - sensor:
      - name: "Temp outside"
        unit_of_measurement: '{{ state_attr("weather.forecast_home", "temperature_unit") }}'
        state: '{{ state_attr("weather.forecast_home", "temperature") }}'

The value gets read properly but for the unit it just says {{ state_attr("weather.forecast_home", "temperature_unit") }} literally, what am I doing wrong?

silent seal
#

I don't think you can template that property

gritty anchor
#

What a tradegy

inner mesa
#

unit_of_measurement cannot be dynamic

silent seal
#

Well how often are you going to change the unit of temperature?

inner mesa
#

you never know when the US might change to metric

#

ok, I do know

#

never

gritty anchor
#

Ok. Then I'll put them by hand

silent seal
#

You can always find and replace on your template file(s) later to update it if you need to

gritty anchor
#

I just dislike hard coding stuff when there's a data source that provides that info dynamically

marble jackal
#

@gritty anchor You might be able to if you add it under attributes

#
template:
  - sensor:
      - name: "Temp outside"
        state: '{{ state_attr("weather.forecast_home", "temperature") }}'
        attributes:
          unit_of_measurement: '{{ state_attr("weather.forecast_home", "temperature_unit") }}'
rapid hawk
#

I think I figured this out now.

teal umbra
#

Is it possible to change the name from english Monday to Maandag directly in this template?

{% set event_datetime = strptime(event_time, '%Y-%m-%d %H:%M:%S') %}
{% if event_datetime.isocalendar()[1] == now().isocalendar()[1] %}
Deze week {{ event_datetime.strftime("%A om %H:%M uur") }}
{% else %}
Volgende week {{ event_datetime.strftime("%A om %H:%M uur") }}
{% endif %}```
marble jackal
#

Only by providing the translated days yourself

gritty anchor
marble jackal
# teal umbra Is it possible to change the name from english Monday to Maandag directly in thi...
{%- set days = ['maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag', 'zondag' ] %}
{% set event_time = state_attr('calendar.com', 'start_time') %}
{% set event_datetime = strptime(event_time, '%Y-%m-%d %H:%M:%S') %}
{% if event_datetime.isocalendar()[1] == now().isocalendar()[1] %}
Deze week {{ days[event_datetime.weekday()] }} om {{ event_datetime.strftime("%H:%M uur") }}
{% else %}
Volgende week {{ days[event_datetime.weekday()] }} om {{ event_datetime.strftime("%H:%M uur") }}
{% endif %}
leaden perch
#

I have created a template that shows the difference between two temperature entities. The problem is, on startup these entities are not yet available so the template generates a log error. From what I understand, availability_template can be used to get rid of this log error.
But I cannot figure it out.

- sensor:
  - name:                 Temperatuurverschil Sjors Kamer vs Buiten
    availability:         "{{ states('sensor.sjors_kamer_temperature')|int(-1) >= 0 and states('sensor.knmi_temperatuur')|int(-1) }}"
    state:                "{{ (states('sensor.sjors_kamer_temperature') | float - states('sensor.knmi_temperatuur') | float) | round(1, default=0) }}"
    unit_of_measurement:  'Β°C'```
#

This generates the following error: TemplateError('ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ (states('sensor.sjors_kamer_temperature') | float - states('sensor.knmi_temperatuur') | float) | round(1, default=0) }}' but no default was specified') while processing template 'Template("{{ (states('sensor.sjors_kamer_temperature') | float - states('sensor.knmi_temperatuur') | float) | round(1, default=0) }}")' for attribute '_attr_native_value' in entity 'sensor.temperatuurverschil_sjors_kamer_vs_buiten'

leaden perch
marble jackal
#

You forgot the >= 0 for the second sensor

#

But this is easier
availability: "{{ states('sensor.sjors_kamer_temperature') | is_number and states('sensor.knmi_temperatuur') | is_number }}"

leaden perch
#

Crap, I was that close!

gritty anchor
#
          - type: entities
            entities:
              - person.steve
              - person. ...

Is it possible to have an Entities card that lists all entities of a certain type?

gritty anchor
maiden magnet
#

Hey
The following Yaml code is incorrect (HA does not accept it) What's the problem?```service: input_text.set_value
data:
value: { state_attr("media_player.spotify_scarriffle", "media_title")}
target:
entity_id: input_text.songtitel

silent seal
#

Well you only have one opening { and one closing } but you need two of each, and you need to wrap that line with quotes

gritty anchor
marble jackal
#

No templates needed for what you asked πŸ™‚

inner mesa
#

Templates are magic and the solution to everything

sick ice
#
  - name: Coffee Machine Power Logic
    state: >
      {% if states('proximity.local') |int <= 5 %}
        {{6 <= now().hour < 17}}
      {% else%}
        False
      {% endif %}

This template works as a handy sensor for triggering a coffee machine automation on the hour and when we're nearby home.
How can I set this for 6:45 instead of 6 o'clock?

now().hour is very easy but how to combine it with now().minute without doing ugly unnecessary nesting of ifs is eluding me.

inner mesa
#

today_at('06:45') <= now() <= ...

sick ice
#

See, this is why I come here. So simple, just need to format it right...

#

And maybe I'm approaching this wront but I much prefer triggering an automation from a sensor state change, than at a specific time, because this way it still works through HA reboots and what not.

inner mesa
#

you could simplify that as {{ states('proximity.local')|int <= 5 and today_at('06:45') <= now() <= today_at('17:00') }}

sick ice
#

It doesn't look as impressive when it's just one line of code though! πŸ˜‰
Just kidding, much more concise. Have changed it to that.

#

Thank you.
Is there a difference in using && or and?

inner mesa
#

oops, some C crept in there

#

yes, one is wrong and the other is right

#

I fixed it

sick ice
#

multilingual coder problems? Not an issue for me πŸ˜‚

#

Obviously the goal here is to save energy by not powering the coffee machine when we're out of town, but turning it on when we're close enough so it's warm by the time we get home. Bloody luxurious right!?

inner mesa
#

I should actually do that. My espresso machine has a built-in timer, but I can control it via an integration (that I wrote!). I just toggle the days manually now

#

if I'm not at home at 6AM, chances are I'm not looking for coffee

silent vector
#

In my template sensor my attributes will have a state sensor value of 'active event' 'active notification' 'inactive'. What would be a clean way to know if there's more than 1 attribute state with either 'active event' or 'active notification'

https://dpaste.org/pMQbk

sick ice
inner mesa
silent vector
#

Does anyone know why I'm getting

Logger: homeassistant.helpers.script
Source: helpers/script.py:409
First occurred: 7:41:39 PM (4 occurrences)
Last logged: 7:41:43 PM

Error in 'condition' evaluation: In 'template' condition: TypeError: unhashable type: 'Wrapper'

https://dpaste.org/61A9X

inner mesa
#

looks like that's coming from a script, and a condition in it, rather than that template sensor

silent vector
#

Really? The template sensor isn't loading and I never saw that error before.

inner mesa
#

there's no condition in there

silent vector
#

Actually here's the error for why it's not loading πŸ€¦β€β™‚οΈ

#
Invalid config for [template]: template value should be a string for dictionary value @ data['sensor'][0]['attributes']['doorbell']. Got OrderedDict([('state', "{{ states('input_text.doorbell_notification_status') }}"), ('last_updated', '{{ states.input_text.doorbell_notification_status.last_updated }}'), ('event_id', "{{ states('input_text.doorbell_notification_status_id') }}")]) template value should be a string for dictionary value @ data['sensor'][0]['attributes']['outdoor_2']. Got OrderedDict([('state', "{{ states('input_text.outdoor_2_notification_status') }}"), ('last_updated', '{{ states.input_text.outdoor_2_notification_status.last_updated }}'), ('event_id', "{{ states('input_text.outdoor_2_notification_status_id') }}")]). (See /config/include/templates/Camera Notifications.yaml, line 0).
#

Aren't those all strings?

obtuse zephyr
#

Pretty sure your attributes can't be maps, it's specifically talking about the doorbell attribute needing to be a string

silent vector
#

Its talking about all of them but the attr state

barren umbra
silent vector
#

Passes

barren umbra
barren umbra
inner mesa
#

it's not being loaded because it doesn't like the format

barren umbra
#

I suppose the dev tools check is not checkiing everything required for HA to load the template...

inner mesa
#

it doesn't know anything about what the attributes section of a template sensor accepts

barren umbra
#

Dev Tools > Template should prove/disprove that...

silent vector
#

I thought an attribute could be a map

inner mesa
#

it can, but I don't know if the template sensor will like it

#

integrations can put whatever they want in there

#

attributes map (optional)
Defines templates for attributes of the sensor.

attribute: template template REQUIRED
The attribute and corresponding template.

#

it doesn't say "template or map"

#

but a template could output a map, I guess

silent vector
#

Interesting. What can I do to fix this? I have multiple template sensors with attributes where they reference each other or the state references the attributes

#

And they work

inner mesa
#

flatten it out

#
            vol.Optional(CONF_ATTRIBUTE_TEMPLATES, default={}): vol.Schema(
                {cv.string: cv.template}
            ),
silent vector
#

Can you translate that to English?

inner mesa
#

it's validating against a map of string: template items

#

that's for legacy templates, though

#

so like I said, you can probably maybe output a map

#

somethign like this:

      outdoor_2: >-
        {{
          {
            "state": states('input_text.outdoor_2_notification_status'),
            "last_updated": states.input_text.outdoor_2_notification_status.last_updated,
            "event_id": states('input_text.outdoor_2_notification_status_id')
          }
        }}
silent vector
#

Thank you I was just typing the single line less pretty version of that.

inner mesa
#

I don't have any of your entities, so I just get this in the template editor:

outdoor_2: >-
        {'state': 'unknown', 'last_updated': Undefined, 'event_id': 'unknown'}
#

but it looks promising

silent vector
#

Can I still reference it the way I was? this.attributes.outdoor_2.state?

inner mesa
#

try it and see

#

otherwise, flatten the structure

#

this works in the template editor:

        {% set data =
          {
            "state": states('input_text.test'),
            "last_updated": states.input_text.outdoor_2_notification_status.last_updated,
            "event_id": states('input_text.outdoor_2_notification_status_id')
          }
        %}

{{ data.state }}
silent vector
#

Template variable error: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'outdoor_2

#

when rendering '{% if this.attributes.outdoor_2.state == 'active event'

inner mesa
#

works 4 me

#
- sensor:

  - name: test
    state: "{{ states('button.water_heater_leak_detected_ping') }}"
    device_class: timestamp
    attributes:
      outdoor_2: >-
        {{
          {
            "state": states('input_text.test'),
            "last_updated": states('input_text.test'),
            "event_id": states('input_text.test')
          }
        }}
#

{{ states.sensor.test.attributes.outdoor_2.state }} -> foobar

silent vector
#

Are you able to try the template self referencing an attribute?

inner mesa
#

no, it hates that. I wouldn't really expect that to work

#

it hasn't created the attributes when it tries to evaluate the state

silent vector
#

I have that working in other templates just not with maps. The others are unavailable for a minute or something and then work

inner mesa
#

ok. I think you're in uncharted waters here

silent vector
#

Sounds scary

inner mesa
#

as you've found out, the difference is that the attributes that you're referencing aren't part of the templates

silent vector
#

I see.

barren umbra
#

I have state: templates referencing attributes of the entity but not attribute templates referencing other attributes of same entity.
Is that what's going on/the problem here?

inner mesa
#

I provided some template code that created the right data structure in the attributes, but the state then tries to reference those attributes that don't exist yet

hot blaze
#

Hi all, would someone be able to assist with a rest api call. I'm trying to read a value thats parsed from json but not 100% clear on how to work a state attribute to the sensor.

#

`

FortiGate latency to Google

  • platform: rest
    name: FortiGate-Google-Latency
    resource: !secret fgt-hass-latency
    method: GET
    scan_interval: 10
    headers:
    Authorization: !secret fgt-hass-api
    Content-Type: "application/json"
    value_template: '{{ value_json["results"].Google_Ping.wan1.latency | round(1) }}'
    unit_of_measurement: "ms"
    `
marble jackal
thorny snow
# thorny snow i mean "unavailable"

i finally figured out the issue. it was unvailable because the new sensor created, even if i chose exactly the same sensor name, HA added a 2 at the end, so totalen was a sensor not existing anymore and the good was totalen_2

#

how can i copy all data from totalen into totalen_2 ? i want to keep the history

thorny snow
#

(venv_3.9.2) thoht@rpi3b-hass:~/.homeassistant$ sqlite3 home-assistant_v2.db
SQLite version 3.36.0 2021-06-18 18:36:39
Enter ".help" for usage hints.
sqlite> insert into statistics (created, start, state, sum, metadata_id) select created, start, state, sum,
...> (select id from statistics_meta where statistic_id = 'sensor.totalensum_final')
...> from statistics where metadata_id = (select id from statistics_meta where statistic_id = 'sensor.totalen')
...> order by created asc;

#

and it works !

#

i did the same on statistics_short_term

#

==> it migrated all historical data from sensor.totalen into sensor.totalensum_final

silent vector
#

I tried adding is defined to force false rather than an error when the attributes haven't been loaded yet but that doesn't seem to stop this error.

#
Template variable error: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'outdoor_2' when rendering '{% if this.attributes.outdoor_2.state is defined and this.attributes.outdoor_2.state == 'active event' and this.attributes.doorbell.state == 'active notification' and (now() -
maiden magnet
#

Hey
I am trying to combine two text inputs but i dont know why its not working:

data:
  value: {{states(\"input_text.songtitel\")}} von {{states(\"input_text.interpret\")}}
target:
  entity_id: input_text.interpret_song
silent vector
#

Try

service: input_text.set_value
data:
  value: "{{ states('input_text.songtitel') + states('input_text.interpret') }}"
target:
  entity_id: input_text.interpret_song
tepid onyx
#

"{{ states('input_text.songtitel') ~ states('input_text.interpret') }}"

#

you don't need to escape the single quotes and ~ will ensure the concatenation in converted to text first

silent vector
hot blaze
#

Thanks Dan, will give it a go

silent vector
#

From there you parse it into a template sensor

#

You can add back unit of measurement I missed it when I copied your code

hot blaze
#

I think I understand what you're talking about, appreciate you responding, will have to try tomorrow. cheers mate

maiden magnet
silent vector
#

Try

service: input_text.set_value
data:
  value: "{{ states('input_text.songtitel') + 'by' + states('input_text.interpret') }}"
target:
  entity_id: input_text.interpret_song
#

You can also try ~ as was suggested instead of +

maiden magnet
#

thanks

eager reef
#

I want to group up same sensors (same model) to one binary_sensors smoke_detected.
I tried to filter the states by model like {{ states.sensor | selectattr('attributes.model', 'eq', 'HmIP-SWSD') | list }} but it runs into UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'model'.
I can access model on a given entity with state_attr. So I guess the problem is that not all states.sensors have this attribute?
How would I ignore those or is there an even better way to achieve this?

#

using the same on the the climate domain works:
{{ states.climate | selectattr('attributes.model', 'eq', 'HmIP-BWTH') | list }}

solemn frost
#

{{ states.sensor | selectattr('attributes.model', 'defined') | selectattr('attributes.model', 'eq', 'HmIP-SWSD') | list }}

solemn frost
#

By checking defined first, you filter it down to only the ones that have that attribute before doing the comparison so it won't error out trying to compare something that doesn't exist

median mason
#

hello, i want to create a template sensor from a sensor that has many attributes, I want to match a certain value and create the template sensor from there with more attributes. in the following example, I only have 2 attributes and I have to copy-paste almost the same thing over and over again. i will have atleast 6 attributes and for several machines.
my template sensor https://pastecode.io/s/emd40309
output of {{ states.sensor.proxmox_resources.attributes.data }} : https://pastecode.io/s/t0c1ihuf

how can i optimize the code, without writing the same thing over and over again?

native mirage
#

I tried iterating over a list of dictionaries without succes. My plan was to recreate the logic of the original author's code appended to my paste and placing each "custom entity" into a dictonary. For the two radiator thermostats I have for heating circuit 1 I went the stupid way duplicating the code, but for my underfloor heating with 8 "custom entities" I'd rather prefer to just iterate over them. Is that even possible with Jinja or is there a better approach to this?
https://dpaste.org/r2Qzh

#

@median mason Probably you are looking for a similar way of iterating about "things" like I do πŸ˜„

median mason
native mirage
#

Okay, than I might borrow some parts from it later πŸ™‚

median mason
median mason
native mirage
#

my plan was to create an a list containing n dicts within this values https://dpaste.org/wLFJX
than my script should just iter about every dict in this list until it spits out the final value.

native mirage
mighty ledge
#
value_template: "{{ state_attr('sensor.proxmox_resources', 'data') | selectattr('id', 'eq', 'qemu/101') | map(attribute='status') | list | first | default }}"
attribute_templates:
  name: "{{ state_attr('sensor.proxmox_resources', 'data') | selectattr('id', 'eq', 'qemu/101') | map(attribute='name') | list | first | default }}"
  id: "{{ state_attr('sensor.proxmox_resources', 'data') | selectattr('id', 'eq', 'qemu/101') | map(attribute='id') | list | first | default }}"
mighty ledge
#

you're also using namespace when you don't need to.

#

and you're casting floats all over the place when you don't need to

#

are you trying to replicate the code below? because the jinja wouldn't be far off from the code below...

plain magnetBOT
#

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

mighty ledge
#

yeah, stop using chatgpt

#

it's always wrong

median mason
#

at least value_template part is right. i also told it about the mistakes and gave it my errors from HA, it could explain why it was mistake, but couldnt write the right code

mighty ledge
#

but it's not

#

this would be optimized

#
{{ state_attr('sensor.proxmox_resources', 'data') | selectattr('id', 'eq', 'qemu/101') | map(attribute='status') | list | first | default("Not Found") }}
#

and it's using the states object, which you do not want to use

#

lastly, it's not outputting the information you want, it's outputting the entire dict

#

you want status

frank raven
#

Is there an easy way to select all lights which support HS (i.e. has "hs" in the supported_color_modes attribute)?

mighty ledge
frank raven
#

Oh, search. Thank you, that's awesome!

mighty ledge
#

np

mighty ledge
#

fixed πŸ˜›

frank raven
#

I took that as a discreet sign that you were able to type it all without testing :)

silent seal
#

Just thought I'd mention it as I'm always searching chat for template examples that solve my problems πŸ˜„

mighty ledge
# native mirage my plan was to create an a list containing n dicts within this values https://dp...
{% set devices = [
    ('climate.thermostat_badezimmer', 'sensor.bsb_lan_hk1_thermostat_badezimmer_raumtemperaturveranderung'),
    ('climate.thermostat_eike', 'sensor.bsb_lan_hk1_thermostat_eike_raumtemperaturveranderung'),
] %}
{% set max_set_temp = states('sensor.bsb_lan_hk1_thermostate_hochste_solltemperatur') | float(default=20) %}
{% set ns = namespace(max=[], diff=[]) %}
{% for climate, sensor in devices %}
  {% set desired = state_attr(climate, 'temperature') or 20 %}
  {% set actual = states(sensor) | float(default=20) %}
  {% set diff = actual - desired %}
  {% set ns.max = ns.max + [ diff ] %}
  {% if actual < desired %}
    {% set ns.diff = ns.diff + [ diff ] %}
  {% endif %}
{% endfor %}
{% if rooms > 0 %}
  {{ max_set_temp + ns.diff | average }}
{% else %}
  {{ max_set_temp + ns.max | max }}
{% endif %}
floral steeple
#

hey all, for the trend sensor/integration...is the gradient calculated using all stored values or the change from the last point to the second last point. thanks

mighty ledge
floral steeple
#

sorry, I was just playing the template of my trend sensor....hence I posted here....so its basically all max_samples. thank you

waxen meadow
#

Invalid config for [alarm_control_panel.manual]: [arming_time] is an invalid option for [alarm_control_panel.manual]. Check: alarm_control_panel.manual->disarmed->arming_time. (See ?, line ?).

obtuse zephyr
#

arming_time isn't valid for disarmed

waxen meadow
#

thx

tulip kindle
#

in a custom:mushroom-template-card, is it possible to specify icon_color as an hs_color [x, y] ?

waxen meadow
tulip kindle
tulip kindle
#

in re: my earlier question... why does the following template not work? or is this type of function not valid within a template?

#{{ homeassistant.util.color.color_rgb_to_hex('100', '100', '100') }}

I would think it should return this, but returns the name of the function instead

#646464

inner mesa
#

where did you get that?

#

Jinja has no mechanism for calling Python functions in HA

#

the links in the channel topic show what's supported

#

I see a way to convert non-base 10 to base 10 via int(base=xx), but not turning a base 10 number into base 16

#

ha! {{"#%02X%02X%02X"|format(50, 50, 50) }} -> #323232

tulip kindle
#

ah, so that function is not callable through a template. sorry, new to jinja, so i did not realize that. i figured i could put in any function that might return a string.

inner mesa
#

it's a big of a mixed bag - Jinja functions, filters, and tests need to be supported implemented by the Jinja package or the HA extensions, but Jinja uses Python objects, and (most) Python methods supported by those objects can be used directly in Jinja

#

you could also do this: {{"#%02X%02X%02X" % (100, 100, 100) }}

tulip kindle
#

ok that makes sense... however i was wanting to use this as a springboard to translate an variable time dependent hs_color value to hex, by first converting the hs_color value to rgb since there did not appear to be a direct hs to hex function. i'm probably overcomplicating it.

inner mesa
#

ok. I don't recall that being straightforward

tulip kindle
#

right on, thanks! πŸ™‚

floral steeple
#

Hey, I have a T & H sensor in our bathrooms that I'm measuring humidity so that when it goes high, the ventilation turns on automatically (i.e. shower/bath). I set up a trend sensor, but I keep getting false alarms because the sensor reports whenever there is change, and never fixed interval. Here's an example of when there is shower happening in the bathroom. You'd it would be easy to figure out the gradient, but still getting false alarms. https://ibb.co/7SgXWmn

#

here's my sensor:

#

HRV Auto-on with Upstairs Bathroom Shower

humidity_rising_upstairs_bathroom:
  friendly_name: "Upstairs Bathroom Humidity Increasing"
  entity_id: sensor.h5179_ec37_humidity
  sample_duration: 30
  max_samples: 3
  min_gradient: 0.25
  device_class: moisture
#

i mean is it matter of playing with the gradients, and sample duration time, etc? The sensor reports it seems every time there is a change

tame coyote
#

I'm trying to use ha voice stuff, how do i get only the temp rather then everything?

#

<template TemplateState(<state sensor.temperature_dht=79.2; unit_of_measurement=Β°F, device_class=temperature, friendly_name=Temperature DHT @ 2023-01-11T15:29:59.337434-08:00>)>

inner mesa
#

the state?

tame coyote
#

{{ states.sensor.temperature_dht }}

#

yes

#

just 79.2

inner mesa
#

{{ states('sensor.temperature_dht') }}

#

you were getting the state object

tame coyote
#

Thanks RobC

rose scroll
floral steeple
#

I've been playing with trend for weeks now...no success 😦

#

there's actually some humidity examples in the samples.

rose scroll
#

Yup it could work. It really depends on the behaviour of the sensor readings in HA and how you wish to use the readings in automations.

#

Subtle differences between the statistical mechanics of each...

floral steeple
#

derivative might work too!

#

wow so many options lol

#

I might actually try derivative, with a time window of 2 minutes

#

it does not take long for the humidity to shoot up

#

just to give you an idea, humidity when up by 23% in 5 minutes,

#

once a shower was started

#

sensor:

  • platform: derivative
    source: sensor.temperature
    name: humidity change per 5 min
    round: 1
    unit_time: min
    time_window: "00:05:00"
#

i'm just curious, what state value this shows? A number from 0 to 1?

rose scroll
#

It'll be a number indicating the rate of change. I.e. % change in humidity per min.

floral steeple
#

thanks very much @rose scroll!

sacred sparrow
#

Hi there, I am trying to make an automation condition that only passes if 'sensor.bed' has the state 'Out' thats been triggered in the last 5 minutes or below.
I am kind of stuck here:

restive depot
#

I want to set up an automation where it announces the time since a specific automation was triggered.

I have a little esp32 In a dreamcast VMU and when I press one of the buttons I want it to announce "it's been X minutes"

#

I already have this for a time button
Its {{ as_timestamp(states('sensor.date_time_iso')) |
timestamp_custom('%I:%M %p') }}

lofty mason
sacred sparrow
#

oh of course

#

thank you for that - here I was going to mess myself up with a template haha

sacred sparrow
#

does that look right to you?

inner mesa
#

Conditions are always AND, so no need for the first bit

sacred sparrow
#

ah of course. thank you

barren umbra
silent vector
#

Is there a time out variable for when a wait for trigger times out?

silent vector
barren umbra
silent vector
#

Nope I just want to know if it timed out, a variable to be consumed in a subsequent action.

plain magnetBOT
#

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

silent vector
#

Not sure what you're showing.
continue_on_timeout: true. Allows actions to continue, I have an action to be carried out with a condition. Either it's because of the trigger or because it timed out along with other criteria for either case. That's why I want to know if there's a variable that exists for when a timeout occurs.

plain magnetBOT
#

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

stable gate
#

Hello folks. Sorry if the question has been asked already, but can't find an answer with my google-fu.
Is it possible, inb a template, to get the value of a sensor not right now, but at a given point in the past. For example today at 2PM, or 7 days ago.
I know some mechanics (like history-graph, apexcharts, etc) are able to query this to HA and display the values, since they can draw graphs, or even display computed changes in values based on intervals of time.
But is it possible to do this in templates? I'd like to do this to be able to analyze trends. For example how much kWh was consumed last week vs the same week 1y ago or 1 month ago, and I have plenty of other ideas of cool stats that I could unlock if I knew how to do this

marble jackal
#

@silent vector there is no timeout for triggers, triggers are a single moment in time, an event.

silent vector
#

I would have thought since wait.completed exists something similar would for when a timeout occurs.

#

To be clear I'm talking about the action wait_for_trigger

marble jackal
#

ah, that was not clear

solemn frost
marble jackal
#

I was about to say that πŸ˜›

solemn frost
#

Too quick πŸ˜‰

marble jackal
#

wait.trigger is none is what I'd use

silent vector
#

Thank you.

#

I forgot about that variable.

marble jackal
#

that was already clear by now, and as he should use a template to check that, I think it's on topic πŸ™‚

barren umbra
#

I'm slow tonight...

#

Ity' sonly 5:35 am here!

marble jackal
#

time to go to bed then? Or are you already up again?

barren umbra
#

time to go to bed!!! 😴

floral steeple
#

@barren umbra thanks for inquiring the false triggers was that it was turning on when it shouldn't be turning on. The derivative method is working really well tested it out yesterday it is very clear when there is high humidity and it ignores the subtle changes that the sensors do when there is no high humidity levels., in which the trend sensor was not.

barren umbra
floral steeple
barren umbra
quiet lagoon
#

I want to add a bunch of sensor entities together in a template sensor. I am aware of the existing helper but these sensors update rather frequently so I am wanting to throttle the update of the new sensor so it doesn't update multiple times a second. What is the best method for adding sensor states together? "{{ ((states('sensor.circuit_1_power'))|float) + ((states('sensor.circuit_2_power'))|float) }}" seems like a cumbersome way to add all 16 sensors together. Any tips/shortcuts?

inner mesa
#

{{ ['sensor.x', 'sensor.y', 'sensor.z']|map('states')|map('float', 0)|sum }}

quiet lagoon
#

Awesome, thanks!

inner mesa
#

if they're all named after that pattern, you could also do it without needing to list all the sensors

#

{{ states.sensor|selectattr('object_id', 'search', 'circuit.*power')|map('states')|map('float', 0)|sum }}

quiet lagoon
#

I will have one oddball added on the end unfortunately. Is there a way to force only one decimal point at the end of the first template you provided? I seem to be screwing up the use of Round (1)

silent seal
#

You need to wrap the whole thing in brackets before | round(1)

#

Otherwise it will just round whatever is immediately to the left of it

inner mesa
#

what would cause this:
{{ states.sensor|selectattr('object_id', 'search', '.*battery_level.*')|map('states')|list }}
to give this error?
AttributeError: 'TemplateState' object has no attribute 'lower'

#

there are 20 sensor entities that match that pattern, and they all have...states. A couple of "unknown", but I don't know why it would cause that issue. In contrast, this gives me the list I expect: {{ states.sensor|selectattr('object_id', 'search', '.*battery_level.*')|map(attribute='state')|list }}
map('states') only works on entity_id strings?

quiet lagoon
#

Thanks @silent seal , I was using Round not round. 😩

hoary wing
#

Could anyone share me a template to list all domain.update within a group?

silent seal
#
{{ states.update | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}

Something like that would get all the update sensors which are on, you can remove the | selectattr('state', 'eq', 'on') part if you just want all of them

marble jackal
#

It doesn't work on the state object

inner mesa
#

ok, got it

#

seems like it should do something other than give an error like that πŸ™‚

#

I get what it's doing - expecting a string and trying to turn it into a useful entity_id

floral steeple
#

hey all, I have a question...how do I create a condition based on a numeric state that happened 10 minutes ago?

silent seal
#

The numeric state has a "for" option you can specify, but that requires it to be at that state for the period of time. Will it still be at that state, or will it keep changing?

solemn frost
#

If you can explain what the end goal is, it'll be easier to point you in the right direction

floral steeple
#

Yes sorry I will explain!

#

I have a temperature sensor in my freezer and a numeric trigger that if it goes above - 9Β° C for more than 30 minutes to send me a message that it is broken or hot. I also have a smart plug connected to this fridge which monitors power consumption. The problem is it has a defrost cycle so the freezer does normally go to high temperatures for brief periods of time and then the temperature drops down back to freezing cold. When the fridge is operating normally it uses less than 2 amps but when the internal heater is on it uses more than 2 amps.

#

The problem is that the amps happens almost immediately and then the temperature goes up later 10 minutes later

lofty mason
#

If it goes up and then comes back down quickly, why do you care about detecting the heater cycle at all? Isn't that covered by the 30 minute window?

floral steeple
#

it would take more than 1 hr for the food to go rotten....so this a simpler solution thanks

floral steeple
#

oh wow, I made the automation for my fridge with 9 choose options....or geeze...must be a better way to do this with some templating here

silent seal
#

If you share your whole automation I suspect folks can help

floral steeple
lofty mason
#

You don't really even need an automation at all. Just make a binary_sensor, "temp is high for > 1 hour". And then an alert integration with that boolean. done.

floral steeple
#

LOL i wish you told me that before

#

if my automation runs it will crash HA

silent seal
#

Also, you are combining many things that some folks would split into multiple automations into one

silent seal
#

Which is neither good nor bad, as long as you understand the automation, can debug it, and it works πŸ˜„

#

If you give two things the same trigger_id, you can just have the one condition and use the trigger data to get the friendly name of the device. E.g. your Fridge Compartment InkBird/Frezer (by the way, that should probably be Freezer), and Fridge Smart plug could be one condition/action:

      - conditions:
          - condition: trigger
            id: unavailable
        sequence:
          - service: notify.mobile_app_sony_xperia_zx1
            data:
              message: >-
                Warning! The {{ state_attr(trigger.entity_id, 'friendly_name') }} device has not reported for over
                30 minutes. Please check the device.
              title: InkBird Sensor is offline.
#

But, you can also just add those three entity ids to the same trigger of unavailable for 30 minutes:

  - platform: state
    entity_id:
      - sensor.ibs_th_0b50_temperature
      - sensor.smart_switch_7_electric_consumption_a_2
      - sensor.ibs_th_085d_temperature
    id: unavailable
    to:
      - unavailable
      - unknown
    for:
      hours: 0
      minutes: 30
      seconds: 0
#

A little template magic, a little automation magic, and you'll be off to a more streamlined start πŸ™‚

mighty ledge
#

uh, that whole automation seems overly complex

silent seal
#

I think it can be simplified a lot further, but thought I'd make some simple suggestions to start πŸ˜„

floral steeple
#

Ok, let me tackle this again. Some of your suggestions are great and I will implement them. It is overly complicated but it is also doing more than one thing it's doing freezer and fridge and starting timers and also tells me if switches are offline

silent seal
#

I wonder if the timer is really necessary

floral steeple
#

It's a good question whenever I deal with kind of important things like food in your fridge or hvac-related stuff I use those more robust timers

#

Especially if it's more than 30 minutes

#

It's not like I'm restarting home assistant every hour

mighty ledge
#

I like to use datetimes

#

No timer management

floral steeple
#

That's a really good idea

cursive totem
#

Hey, can someone help me with how i can get "current_temperature < temperature = true "

#

these are state attrubutes

#

hvac_modes:

  • 'off'
  • heat
    min_temp: 10
    max_temp: 30
    current_temperature: 19.5
    temperature: 20
    hvac_action: heating
    friendly_name: Lounge Rad
    supported_features: 1
obtuse zephyr
#

{{ state_attr('climate.thermo','current_temperature') | float < state_attr('climate.thermo','temperature') | float }}

#

(It's possible you may not need the | floats if that's how they're stored)

cursive totem
#

this is what i have now

#

{% set e = [ 'climate.serens_rad', 'climate.zacharys_rad', 'climate.master_bedroom_rad' ] %}
{{ e | map('state_attr', 'hvac_action') | select('eq', 'idle') | list | count != e | count }}

#

but hvac action is not reliable enouth

obtuse zephyr
#

That's entirely different... what are you trying to do exactly

#

or what problem are you solving

cursive totem
#

your code above works nice .. just need to tie it together

#

i need a trigger for an automation

#

when one of the TRV's in a zone calls for heat

#

or in this case goes cold

#

then ill grab the temp and add 5 degrees to the thermostat to call heating

obtuse zephyr
#

Can't say I completely follow why you wouldn't just let the setpoint itself control that

cursive totem
#

The call for heat is controlled by a thermostat in the hall .. often the hall in the center of the house is warm 22 degrees and the bedrooms on the sides are cold 17 degrees

mighty ledge
cursive totem
#

so i want to call an ectra 5 degrees when the bedrooms are cold then then they warm up ill lower the setpoint again to kill the call for heat

cursive totem
#

but float worked allso

#

what does float do / mean?

obtuse zephyr
#

It'll convert the type to a float (numeric) value. But those attributes are stored numerically, so it doesn't actually do anything here

cursive totem
#

right so state att sensor, value | convert to number < etc

#

in english

silent seal
#

| float(0) converts the thing into a float, and if it can't (e.g. it's "cat", it outputs a 0

cursive totem
#

pesky cats getting into my attrubutes

silent seal
#

But you also have |int(1) which converts to an integer (whole number, no decimal places), and defaults to say 1

#

The brackets and number are optional, but highly recommended

cursive totem
#

yes i seen int()

#

anyway .. does no one like my solution to my issue?

silent seal
#

it looks ok, but a little hard to read in Discord without formatting πŸ™‚

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.

cursive totem
#

I need to edit to to look at a formula attribute < attribute instead of just looking for a single attribute

#
{% set e = [ 'climate.serens_rad', 'climate.zacharys_rad', 'climate.master_bedroom_rad' ] %}
          {{ e | map('state_attr', 'hvac_action') | select('eq', 'idle') | list | count != e | count }}
#

Is what I have

#

But I need to get

#
{{ state_attr('climate.thermo','current_temperature') | float < state_attr('climate.thermo','temperature') | float }}

Into it instead

#

Will it work just replacing what’s there for state_attr?

spice current
#
light:
  - platform: template
    lights:
      fallback_light:
        value_template: "{{ states('light.primary_light') if states('light.primary_light') != 'unavailable' else states('light.fallback_light') }}"
        turn_on:
          service: light.turn_on
          entity_id: "{{ states.light.primary_light.entity_id if states.light.primary_light.state != 'unavailable' else states.light.fallback_light.entity_id }}"
        turn_off:
          service: light.turn_off
          entity_id: "{{ states.light.primary_light.entity_id if states.light.primary_light.state != 'unavailable' else states.light.fallback_light.entity_id }}"
        toggle:
          service: light.toggle
          entity_id: "{{ states.light.primary_light.entity_id if states.light.primary_light.state != 'unavailable' else states.light.fallback_light.entity_id }}"
``` can someone help me get this template working?
floral steeple
#

hey, im trying to understand the concept of a datetime helper for replacing a timer....so in the case of refrigerator temperature....I create a trigger when the temperature of above X, inject time now for 45 minutes, and if that time reaches, another trigger happens?

silent seal
#

Yes, you can use a time trigger and give it an entity πŸ™‚

floral steeple
#

thank you! Does the datetime helper survive if a restart of HA happens right around the time of a datetime?

#

what I mean is if the datetime happens when HA is restarting, would it still work as intended?

inner mesa
#

it will only trigger if HA is running when the time matches - there's "catch up" or fuzzy logic in there

#

that's why one typically adds a homeassistant "start" trigger to compensate

#

If home assistant just started and the condition check says that it's this time (maybe whack the seconds)...

sullen quest
#

afternoon all - is there anyway to "reset" a sensor to 0?

#

I created this sensor to monitor my modem traffic but would like to reset it to 0 at the start of the month

#
      unit_of_measurement: Gb
      state: "{{ (((states('sensor.m4r_packets_received') | float) + (states('sensor.m4r_packets_sent') | float)) * 4096 / 1000000000)| round(2)}}"
      unique_id:
inner mesa
#

that sensor doesn't accumulate anything

#

it just reflects a calculation of some other sensors - are they what you want to reset?

sullen quest
#

if I can yes

inner mesa
#

there's nothing you can do in the template for that

sullen quest
#

but those are created by the UPNP integration that reads it from my modem

#

thanks Rob

ornate shore
#

trying to pass the value of some templates into a service call from a button press, not sure what I'm doing wrong

#
  action: call-service
  service: ha_kia_hyundai.start_climate
  data:
    temperature: '{{states.input_number.telluride_temp|int}}'
    defrost: '{{is_state(''input_boolean.defrost'', ''on'')}}'
    heating: '{{is_state(''input_boolean.steering_wheel_heater'', ''on'')}}'
  target: {}```
inner mesa
#

you can't use templates there

#

Limitations
It is not possible to use templates for actions. But calling a script is a good alternative.

dull burrow
#

TIL smart cars allow you to control climate and even a steering wheel heater lmao

inner mesa
#

you also have some questionable templates there...

ornate shore
#

I'm sure I do. Okay i'll try a script.

ornate shore
#
data:
  temperature: '{{states('input_number.telluride_temp')|int}}'
  defrost: '{{is_state('input_boolean.defrost', 'on')}}'
  heating: '{{is_state('input_boolean.steering_wheel_heater', 'on')}}'```
#

this script doesn't run either, any assistance appreciated

inner mesa
#

you're using teh same type of quotes inside and outside your templtes

#

switch to " outside

ornate shore
#

Okay thanks!

barren umbra
# spice current ```yaml light: - platform: template lights: fallback_light: ...

It looks like you are self-referencing when the light_primary_light is 'unavailable'. Is that allowed?

light:

  • platform: template
    lights:
    fallback_light:
    value_template: "{{ states('light.primary_light') if states('light.primary_light') != 'unavailable' else states('light.fallback_light') }}"

The state of light.fallback (value_template) contains itself

barren umbra
serene crow
#

Hi everyone, I'm trying to create a template sensor for my standing desk (Sitting/Standing). The cover.desk have a state current_position. ```yaml

  • platform: template
    sensors:
    desk_position:
    friendly_name: "Desk Position"
    value_template: >-
    {% if (states.cover.desk.current_position.state) | float = 9 %}
    Sitting
    {% elif (states.cover.desk.current_position.state) | float = 70 %}
    Standing
    {% else %}
    Indetermined
    {% endif %}
serene crow
inner mesa
#

You test with ==

#

And it looks like you're trying to get an attribute?

serene crow
inner mesa
#

Yes, still wrong

serene crow
# inner mesa Yes, still wrong

I try to use "state_attr" ```yaml

  • platform: template
    sensors:
    desk_position:
    friendly_name: "Desk Position"
    value_template: >-
    {% if (state_attr('cover.desk', 'current_position')) | float == 9 %}
    Sitting
    {% if (state_attr('cover.desk', 'current_position')) | float == 70 %}
    Standing
    {% else %}
    Moving
    {% endif %}
inner mesa
#

Use is_state_attr from that link

serene crow
inner mesa
#

Beyond that, expand on wrong

serene crow
# inner mesa Beyond that, expand on wrong

Some progress, valide code but the sensor is "unavailable" ```yaml

  • platform: template
    sensors:
    desk_position:
    friendly_name: "Desk Position"
    value_template: >-
    {% if (states.cover.desk.current_position.state) | float == 9 %}
    Sitting
    {% elif (states.cover.desk.current_position.state) | float == 70 %}
    Standing
    {% else %}
    Moving
    {% endif %}
inner mesa
#

Still wrong

#

Please use is_state_attr

barren umbra
#

is_state_attr('device_tracker.paulus', 'battery', 40)

serene crow
#

Sorry wrong copy past

inner mesa
#

And re -read that whole section

serene crow
#

Thanks... testing

#

Working thanks a lot for your help ```yaml

  • platform: template
    sensors:
    desk_position:
    friendly_name: "Desk Position"
    value_template: >-
    {% if is_state_attr('cover.desk', 'current_position', 9) %}
    Sitting
    {% elif is_state_attr('cover.desk', 'current_position', 70) %}
    Standing
    {% else %}
    Moving
    {% endif %}
winged torrent
void idol
#

Hi there, general question about (rest) sensors, how do you check if a sensor has successfully updated? I have one setup to poll for my WAN IP every 120 secs, I just want to make sure the REST API calls are successful. Basically, I'm asking how to debug.

cursive totem
sullen quest
dawn salmon
#

I think there is a bug when I create 2 or more template sensors with one - platform: template field when I remove one sensor from its sensors: list it is not removed from home assistant. sensors must be created seperatedly so they get removed if I remove one sensor...

marble jackal
#

Can you remove it by going to the entity in the GUI, and then press delete under settings?

dawn salmon
#

no there is no delete button

#

it was configured in yaml.. but when removed the whole sensor all 3 it got removed created it again with 3 different - platform: template strings and all ok

plain sedge
#

Hi, can anyone help me parse some Json to get a value?

#

basically I'm after $.tracks.items[0].external_urls and then the spotify: entry

#

if I use json_attribute_path: "$.tracks.items[0].external_urls" and json_atttributes: -spotify I'm getting nothing 😦

#

json_attributes_path: "$.tracks.items[0].external_urls" json_attributes: - spotify

serene crow
serene crow
void idol
#

Maybe post the full code for the template sensor

floral shuttle
#

could this template be simplified to create a list of light entity_id' s out of the attribute lights of a Hue group?```
{% set ns = namespace(lights=[]) %}
{% for l in state_attr('light.terrace_outdoors_hue','lights')%}
{% set ns.lights = ns.lights + ['light.' + l|slugify ] %}
{% endfor %}

{{ns.lights}}```

marble jackal
#

{{ state_attr('light.terrace_outdoors_hue','lights') | map('slugify') | list }}

#

oh wait, you also add light

#

@floral shuttle this should work: {{ state_attr('light.terrace_outdoors_hue','lights') | map('slugify') | map('regex_replace', '^', 'light.') | list }}

floral shuttle
#

haha, thanks! not sure if that is simpler, it is shorter though πŸ˜‰ (had been looking for a way to slugify the initial output, but wasnt aware of map('slugify').

marble jackal
#

you can map() any filter to apply it on the individual items in a list

floral shuttle
#

Yes, but I think I tried it on the attribute lights..

marble jackal
#

Don't see any way to simplify it further though, als you need to slugify it, and need to add light., so those 2 steps are needed πŸ™‚

floral shuttle
#

yeah, wished Ha Hue integration would do it natively though.. just like with light groups

marble jackal
#

well, your Hue hub doesn't know the entity_ids

#

and theoretically you could name the lights differently in the Hue app, and in Home Assistant, so it might not even be possible to map them (and names are not always unique, so that is also a complicating factor)

floral shuttle
#

yep, all of that, I know... still, HA knows the entity_ids, and based on the unique_id's should be able to map those..even if the names were changed in the Hue app

plain magnetBOT
deep marsh
#

Hi! I have a question about attributes in a sensor. I created a custom template that loops through attribute blocks within a sensor. The number of attributes blocks can differ over time, so using a for statement can fail.

For instance see these attributes:

state_class: measurement
forcast: 
- price: 2888391
  electricity_price: 2888391
- price: 2869273
  electricity_price: 2869273
- price: 2860198
  electricity_price: 2860198

Within forecast I have three blocks with the same type of data. They all start with price. In above example there a three blocks, but sometimes there are only 2 blocks. So, if it do a for like "for i in range(3)" it will fail if there are only 2 occurrences of such a block. Is there a way to do a for until there are no attributes blocks available anymore, or determine up front how many attribute blocks are available within the sensor?

plain sedge
marble jackal
hallow mesa
#

Hi everyone, why doesnt this work?

  • sensor:
    • name: "Ingo procentuell skillnad"
      unique_id: ingo_procentuell_skillnad
      unit_of_measurement: "%"
      state: >-
      {{ ((states('sensor.ingo_mellanskillnad') | float) / (states('sensor.ingo_95') | float)) }}
marble jackal
#

@deep marsh ```jinja
{% set list = state_attr('sensor.bla', 'forecast') %}
{% for i in list %}
{% endfor %}

hallow mesa
#

i just get sensor value unavailable

marble jackal
#

does the template work in devtools > templates?

void idol
void idol
void idol
hallow mesa
#

Nope, get TemplateSyntaxError: expected token 'end of print statement', got 'x'

#

i have restarted several times

#
  • sensor:
    • name: "Ingo Mellanskillnad"
      unique_id: ingo_mellanskillnad
      unit_of_measurement: "kr"
      state: >-
      {{ states('sensor.ingo_95') | float - states('sensor.ingo_etanol') | float }}
#

that works without issues end the sensor gets a value

#

i then wanna use that value in a new sensor

void idol
#
/ (states('sensor.battery_energy_in') | float)) }} ```
plain sedge
#

- platform: rest resource_template: https://api.spotify.com/v1/search?q={{ states('sensor.media_artist_office')|default('')|replace(' ','%20') }}%2C%20{{ states('sensor.media_title_office') |default('')|replace(' ','%20') |regex_replace('\([0-9]+\)')}}&type=artist%2Ctrack&limit=1 headers: Authorization: > Bearer {{ state_attr('sensor.spotify_token','access_token') }} Content-Type: > application/json Accept: > application/json value_template: 'OK' value_template: '{{ value_json.tracks.items[0].external_urls.spotify }}' json_attributes_path: "$.tracks.items[0].external_urls" json_attributes: - spotify name: spotify_url scan_interval: 60

void idol
plain sedge
#

Maybe

void idol
#

You have value_template twice?

marble jackal
#

That is incorrect yaml, that will not work

void idol
hallow mesa
marble jackal
#

at least one of those sensors doesn't have a numeric state

void idol
#

the sensors aren't numbers

#

Or at least one isn't

#

Do them one at a time

#

See which one is unavailable

marble jackal
#

but you would also see that if you test it in devtools > template

hallow mesa
#

thats where i got the error

void idol
#

Do both those sensors have states as numbers?

#

At least one looks broken

hallow mesa
#

yep they both do

void idol
#

Sure?

marble jackal
#

try this in devtools:

{{ states('sensor.ingo_mellanskillnad') }}
{{ states('sensor.ingo_95') }}
hallow mesa
#

sensor.mellanskillnad 4.51

marble jackal
#

what does that return

hallow mesa
#

Resultattyp: string
unknown
19.65

marble jackal
#

okay, that's your answer

void idol
#

First one is stuffed

hallow mesa
#

so how to i change it from a string?

void idol
#

It says unknown

hallow mesa
#
  • sensor:
    • name: "Ingo Mellanskillnad"
      unique_id: ingo_mellanskillnad
      unit_of_measurement: "kr"
      state: >-
      {{ states('sensor.ingo_95') | float - states('sensor.ingo_etanol') | float }}
marble jackal
#

not, are you sure you did not make a typo in the entity_id

void idol
#

You need to fix that first

marble jackal
#

because that would give stat unknown

hallow mesa
#

this is what calculates the sensor mellanskillnad

marble jackal
#

check the actual entity_id in devtools > states

hallow mesa
#

in states i get the value 4.51

marble jackal
#

and please format your code

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.

hallow mesa
#

πŸ‘

#

is it possible to post a screenshot?

marble jackal
#

don't post images of code

hallow mesa
#

'''- sensor:
- name: "Ingo Mellanskillnad"
unique_id: ingo_mellanskillnad
unit_of_measurement: "kr"
state: >-
{{ states('sensor.ingo_95') | float - states('sensor.ingo_etanol') | float }}

  • sensor:
    • name: "Ingo procentuell skillnad"
      unique_id: ingo_procentuell_skillnad
      unit_of_measurement: "%"
      state: >-
      {{ states('sensor.ingo_mellanskillnad') | float - states('sensor.ingo_95') | float }}
marble jackal
#

backticks

#

copy them from the bot message if you want

hallow mesa
#
    - name: "Ingo Mellanskillnad"
      unique_id: ingo_mellanskillnad
      unit_of_measurement: "kr"
      state: >-
        {{ states('sensor.ingo_95') | float - states('sensor.ingo_etanol') | float }}        
        
- sensor:
    - name: "Ingo procentuell skillnad"
      unique_id: ingo_procentuell_skillnad
      unit_of_measurement: "%"
      state: >-
        {{ states('sensor.ingo_mellanskillnad') | float - states('sensor.ingo_95') | float }} 
marble jackal
#

you could have edited your previous post though

hallow mesa
#

devtools says that all sensors has values exept sensor.ingo_procentuell_skillnad

#

sorry bout that 😩

marble jackal
#

what is the entity id according to devtools > states

#

check that in the table in the lower part

hallow mesa
#

sensor.ingo_procentuell_skillnad

#

or what sensor do you mean?

marble jackal
#

'sensor.ingo_mellanskillnad'

hallow mesa
#

sensor.mellanskillnad

#

nevermind, ill show my self out. Thanks for all the help πŸ˜„

mighty ledge
#

@marble jackal you'll get a kick out of this

{% set entities = range(1, 25) | map('string') | map('reverse') | map('slice', 1, 'sensor.mgp_pun_ore_') | map('list') | map(attribute=0) | map('reverse') | map('join') | list %}
{% set values = entities | map('states') | select('is_number') | list %}
{% if entities | length == values | length %}
  {{ values | map('float') | average | round(3) }}
{% else %}
  {{ this.state if this is defined and this.state is defined else 0 }}
{% endif %}
#

doing backflips to avoid using namespace

#

(specifically the first line)

winged torrent
serene crow
mighty ledge
#

I can't think of another way to do it without adding some string appending function

#

I wonder if macros can be used as filters...

#

hmm

marble jackal
#

{% set entities = range(1, 25) | map('string') | map('regex_replace', '^', 'sensor.mgp_pun_ore_') | list %}

#

that seems to return the same list of entities

mighty ledge
#

yah, but that uses regex

#

I was just trying to do normal funcs

marble jackal
#

ah, slice was not in my list of normal functions yet πŸ˜›

mighty ledge
#

it was like a little challenge because I thought it should be doable

#

it's not on mine either

marble jackal
#

are there cases when this is not defined, or is that just to have it working in devtools?

mighty ledge
#

πŸ€·β€β™‚οΈ

#

better to be safe than sorry

#

I dislike it when people are like "Didn't work" so I always build explicitly safe things unless I"m 100% sure a case is not possible

marble jackal
#

true

plain sedge
#

any experts help me with this - if I use a standard rest template it all works, but I want three variables - and all I get is 401 invalid access token

plain magnetBOT
#

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

plain sedge
#

The token is correct - even if I replace it with a static token I get 401 😦

#

I am aware of the double .. in the last two sensors.

obtuse zephyr
#

What's the message of the 401? Have you tried issuing the request manually to see if the problem is actually in the above or if your token is actually incorrect or insufficient in some form?

mighty ledge
obtuse zephyr
#

Actually now that I look above... you said it does say "invalid access token". That's your answer... you're not correctly getting the token, or it's expired or something

plain sedge
#

I'll fix the bottom sensors and see what I get!

#

Ok, so now I get this which doesn't make sense as rest_command doesn't have an issue : homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.spotify_artist_rest. State max length is 255 characters.

mighty ledge
plain sedge
#

So how do I output less?

#

I've used JSONpathfinder to get the attributes

mighty ledge
#

value_template: "OK" on each sensor should work

#

but remember, you're yaml is already incorrect

#

you have too many sensor sections, you need to delete the last 2 sensors: lines

#

keep everything between

plain sedge
#

Yeah, I have fixed that. I'll try that - thanks for your help so far πŸ™‚

#

sensor: - name: spotify_url_rest value_template: 'OK' json_attributes_path: "$.tracks.items[0].external_urls" json_attributes: - spotify - name: spotify_track_rest value_template: 'OK' json_attributes_path: "$.tracks.items[0]" json_attributes: - name - name: spotify_artist_rest value_template: 'OK' json_attributes_path: "$.tracks.items[0].artists[0]" json_attributes: - name

#

Stil lsaying 255 chars is too long 😦

#

Ah ... it is saying that but it is also working. Very curious.

mighty ledge
#

are you sure that's not an old error message?

plain magnetBOT
#

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

mighty ledge
#

@tired sandal looks pretty good to me

#

you have some extra parenthesis in there but nothing overly done

tired sandal
#

@mighty ledge thanks, I've removed the time comparison since @marble jackal pointed out that forecast is always (more or less) gte now()

plain sedge
mighty ledge
#

just delete it

plain sedge
#

How - the option to delete isn't there....

mighty ledge
#

restart HA instead of reloading the rest integration

tacit sun
#

when setting up a statistics sensor... can I apply this template value to it so that it displays correctly on a lovelace gauge card?

value_template: >
        {% if states('sensor.master_bathroom_humidity_change_over_5m') in ['unknown', 'unavailable', 'None']  %}
          0
        {% else %}
          {{ states('sensor.master_bathroom_humidity_change_over_5m') }}
        {% endif %}
#

like:

- platform: statistics
  name: "Master Bathroom Humidity Change Over 5m"
  entity_id: sensor.master_bathroom_humidity
  state_characteristic: change
  max_age:
    minutes: 5
  sampling_size: 50
  precision: 1
  value_template: >
        {% if states('sensor.master_bathroom_humidity_change_over_5m') in ['unknown', 'unavailable', 'None']  %}
          0
        {% else %}
          {{ states('sensor.master_bathroom_humidity_change_over_5m') }}
        {% endif %}
mighty ledge
#

also your template would simply be {{ states('sensor.master_bathroom_humidity_change_over_5m') | float(0) }}

#

you can also do this to keep the last value

#
{% if states('sensor.master_bathroom_humidity_change_over_5m') | is_number %}
  {{ states('sensor.master_bathroom_humidity_change_over_5m') }}
{% else %}
  {{ this.state if this is defined and this.state is defined else 0 }}
{% endif %}
tacit sun
#

not sure I follow... (not good with templates)

#

when you say "keep the last value", could you please elaborate?

mighty ledge
#

I did, it's that template

#

the top template gives you 0 when the stats template is unavailable, the bottom template will give you the last value of the stats template instead of zero

tacit sun
#

the top template I understand (which is very nice, thanks!)
the bottom, I don't understand what the else is doing

#

is this the actual syntax, or sudo code?
{{ this.state if this is defined and this.state is defined else 0 }}

mighty ledge
#

that's the actual code

#

it only works in a template sensor

#

as this is only available in templates, scripts, or automations

tacit sun
#

right... so... in the example... "this" is referring to the template sensor in which: this.state is coded... effectively: myTemplateSensor.state

mighty ledge
#

it's referring to the state object in which the template resides

tacit sun
#

the sensor in question is a statistic sensor that is measuring the % change of the humidity sensor over 5 mins.
When there is no change over 5 mins, it goes unavailable

#

I don't know how to change that

mighty ledge
#

why don't you use the derivative sensor instead

tacit sun
#

mostly ignorance...

#

haha

mighty ledge
#

derivative is change over time

tacit sun
#

I saw that in my google searches today, but... not sure I comprehend what it is, how to use it... or... what benefits it has.

silent vector
#

How would I make this work for both 'eject' and 'Eject' currently it only checks the first word

{% set test = "eject" %}
{{ ('eject' or 'Eject') in test }}
mighty ledge
#

so if the change is high, then you know the humidity is rising

#

if the change is -high, then you know the humidity is falling

#

the number itself is guess work on how you want to trigger off it

mighty ledge
silent vector
#

Would you happen to know the syntax?

tacit sun
#

but... with derivative... when there is no change, it will just display 0 via built in functionality?

mighty ledge
#

test is search('eject', ignore_case=True)

#

or you could just search for ject and omit the E

silent vector
#

regex_search() got an unexpected keyword argument 'ignore_case'

mighty ledge
#

'ject' in test

inner mesa
#

or if you have different words, {{ test is search('foo|bar') }}

silent vector
#

That's possible. (This is not for home assistant) and I don't think anyone would approve of searching for 'ject' πŸ˜†

mighty ledge
mighty ledge
#

no change is 0

#

but it'll rarely be no change if you have a sensor that updates frequently as humidity sensors are not precise and they fluctuate alot

silent vector
#
{{ test is search('eject', 'ignore_case=True') }}

Worked

mighty ledge
#

no

#

that's not right

#

it's not a keyword

silent vector
#

But it worked? Lol

#

It changed to false

mighty ledge
#

because it resolved true

#
{{ 'Eject' is search('eject', True) }}
silent vector
#

You're saying use that? Or that's why it worked

mighty ledge
#

ignore_case= means using a keyword named ignore_case

#

I'm saying the ingore_case argument is not a keyword or i'ts not named ignore_case

#

so just supply the True

silent vector
#

Sounds good thank you.

#

And thank you robc

mighty ledge
#

it's not the correct keyword

#

so it would have been...

#
{{ test is search('eject', ignorecase=True) }}
#

no _

silent vector
#

So this one is good?

{{ test is search('eject', ignorecase=True) }}
mighty ledge
#

yep

#

any of the ones I posted are, just not the one with the _

silent vector
#

Awesome thanks.

cursive totem
#

Hi, can any one help me with a sensor that checks the attributes of 3 climate sensors to see if 'temperature' < 'current_temperature' on any of them?

sinful blade
#

can anyone tell me why this template doesent work in automation?
service: notify.client1 data: message: {{ trigger.calendar_event.start } | strftime('%d %b, %Y - %H:%M') }}

tacit sun
plain magnetBOT