#templates-archived
1 messages Β· Page 24 of 1
the mushroom-template multiline-secondary card didnt that line
what?
My reply was to hangingbsack
that was directed towards dan1002, a little mix-up here now
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.
just tried it out myself, works fine without
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(' | ') }}
Probably because i have multiline secondary activated?
ah, that could indeed be it π
no, even with multiline secondary it works fine here
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' }} %
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 }}```
you want to search for both Power and Energy?
The search term will change depending on an input_text.
{{ ['-- - --'] + states.sensor|selectattr('entity_id', 'search', 'Power|Energy') )|map(attribute='entity_id')|list }}
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)?
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
Sorry, we can ignore the first list. That is because it will be part of an automation that populates a dropdown.
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 }}
You, sir, are correct ^^
The search however now results in an "or" and not an "and" search
but you can make it yourself easier to just use a pipe ( |) as seperator
So it will return any sensor with "energy" or "power" in the name.
correct
{% set search_selection = 'Energy|Power' | lower %}
{{ states.sensor | selectattr('entity_id', 'search', search_selection) | map(attribute='entity_id') | list }}
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
then just do two selections
That's why I did the search in search above
ah wait, there are not always 2
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?
{% set search = '*Energy*Power' %}
{% set search = ('^(?=.*' ~ search.split('*') | select | join(')(?=.*') ~ ').*$') | lower %}
{{ states.sensor | map(attribute='entity_id') | select('match', search) | list }}
That's some regex πͺ
There should really be like a gallery of templates for people to use, and ppl could vote on good and helpful ones etc
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'
)) }}
Not really
I get the error 'UndefinedError: 'iff' is undefined'
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.
It's iif
enumerate the attributes?
{% for attr, value in states.sensor.xyz.attributes.items() %}
Ok so that's what I thought it should be but this is the issue I get..
TemplateSyntaxError: expected token 'end of statement block'
Not sure if this is an issue with binary_sensor. vs regular sensor...
{% 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.
exactly that works fine for me with one of my binary_sensor entities
entities:
{%- for state in states %}
{{ state.entity_id }}:
{%- for attr, value in state.attributes.items() %}
- {{ attr }}: {{ value }}
{%- endfor %}
{%- endfor %}
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.
you can't use the . notation when the object_id starts with a number
well I learned that the hard way...
Ok thanks I'll do it that way.
@uncut compass I converted your message into a file since it's above 15 lines :+1:
the for loop is returning 0, where it should return 25
you need to use a namespace if you're planning modify a variable inside a for loop and access it outside
this was like you, yesterday: #templates-archived message
thanks a lot mate
explained in "Scoping Behavior" in https://jinja.palletsprojects.com/en/3.1.x/templates/
worked now, thanks again!
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
or
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'
)) }}```
no, use "or"
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
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')}}
TypeError: object of type 'generator' has no len()
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
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
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
hmm ok let me give that a go π
the OFF works as fast as the original entity by the ON is slower
or not is_state('media_player.living_room_tv_google_cast', 'playing') ???
that just stays "off"
So on is one of [idle|playing|standby] and off is 'off'?
yep
for media_player.living_room_tv_google_cast
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
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
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
they both have state off but the integrations' on states are diifferent with one having on and the other having [idle|playing|standby]
none actually have on - on is playing
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
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...
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
No problem! My head is starting to hurt too!
I wonder if a trigger sensor would help
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!
its because the sensor has some attributes too
Ah, okay. So, create the boolean + automation and use the state of the boolean for your sensor state...
sounds like a good idea - I'll see what I come up with - thanks again
hey all, so just wondering if this expected activity for the statistics sensor...thanks
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.
Hmm yeah, the docs are not clear on this. Wonder if I should report this as bug, but I figure I ask here first.
If there are no samples then it's unknown. Not a bug IMO...
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...
Got it, makes sense, but what if it keeps reporting zero?
For more than 10 minutes
I would expect if your source kept reporting 0, still 0, still 0, still 0, still 0... the stat sensor would show 0
Exactly! But it's unknown.
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...
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
Yes, this is the expected behaviour for state objects.
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.
If you want your frontend to show '0' when stats is unknown you'd have to template it...
or, not worry about it!!
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
Not a good time to be sailing either!
While raking leaves it can be a good thing...
lol ok, take care all
until next time....like tomorrow probably when I try to make this template sensor
That should be a lot easier than trying to wrap my head around onethreeseven's dual tv integration tug-of-war! π΅βπ«
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 ?
this is the 2 different json coming to mqtt: https://dpaste.org/wXWJw
i want to create PW2 and PW3 using the second json (serial=703000368301)
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?
And I tried {% max_ist_temp_diff %} π€¦ββοΈ
is there an automatic type conversion going on later when int and float meet?
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?
@nimble copper I converted your message into a file since it's above 15 lines :+1:
int and float can be compared with each other (or summed or multiplied or whatever)
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'
How can i create 2 mqtt sensor from json which sent same variable name (pw0 & pw1) but with a serial variable different for both ? Current MQTT sensor : https://dpaste.org/zGNqh JSON: https://dpaste.org/wXWJw
this.state is always the previous state, so something changes causing your template sensor to be rendered again, at that point this.state is the state before the template is rendered again
states(this.entity_id) will give the current state
can i add : value_template: "{{ value_json.pw0 if value_json.serial == "703000069723" }}"
you'll have to elaborate on your question as well as post your json that's in your topic
it is in reference of #templates-archived message
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}'
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
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 ?
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
thanks. so i can't use mqtt sensor as i tried, i ve to replace it by your template code, right ?
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
right, so it went from 1 entity to 2 entites on the same topic
changing it from a single device to mutliple devices
yes 2 entitees on same topic
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
: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
this is the code i put: https://dpaste.org/RfamW
how are you adding that to configuration.yaml?
you for some reason didn't copy what I wrote
copy/paste what I wrote, do not try to correct anything
i did a copy/paste
no you didn't
let me try again
You put an extra - in the wrong spot
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
this is the code: https://dpaste.org/prYxs
that's not possible if you have the correct dashes
i did a raw copy/paste this time
right but that error is old
this is the code screenshot: https://imgur.com/a/U7m4dKh
ok?
what errors are in your logs the template is correct
are you runing some custom error checker? if yes, don't do that
(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
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
it is the native hass checker
great !
last }} should be %} for the first line under state
huh ?
{% if value_json.serial == '703000069723' }} ==> should be {% if value_json.serial == '703000069723' %} ?
yes
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).
there's 2 templates, both need to be corrected
i did on both
also, that's the exact same error
this is the code: https://dpaste.org/Pv0eB
bro
you edited the wrong line
oh ?
you said this
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
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
np
i ve to go to take kids at school then i'll check result, i'll be back in 1h, thanks again
95% sure it should work
it'll be unkonwn until the topic updates
then it should be good from then on
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'
Hello I'm having an issue with http://pastie.org/p/0qw7nsA3KcywcmG7atW3QV i'd appreciate any hints. Thanks
it says the entitee is not numeric on the dashboard
and i forced an update and still same
in devtools, sensor.pw0=unavailable
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?
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
@mighty ledge i did listen on MQTT and messages are coming well: https://imgur.com/a/vXHi0YA
but my sensor value are reporting "unavailable"
check for errors in your logs
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
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) ```
when grepping ERROR, i see some error but on some other template sensor not related
nothing special in log at the end
then it's most likely related to your trigger
you can try adjusting your trigger to solve the problem
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
how do i can adjust the trigger ?
take a look at the MQTT trigger docs that I linked
read up on what payload does and value_template
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 !
π
@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...
there isn't any
zip func
I have an open commit adding it that I never delivered π€£
same for enumerate()
π
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 ?
i mean "unavailable"
@thorny snow I converted your message into a file since it's above 15 lines :+1:
there is value on totalen0 and totalen1 ( 16000 and 0) but it totalen kept beeing "unvailable"
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?
what if you put {{ states('sensor.totalen0') is number}} {{ states('sensor.totalen1') is number }} in
-> Templates?
i can't test anymore, i restarted HASS and my inverters are now in SLEEP mode, not sending value anymore -SUN left- so all values are now unknown until next polling tomorrow when sun will come
why don't you retain your MQTT data
before restarting i tested this on devtools: https://imgur.com/a/kSRCQ3O
so that they aren't unavailable on restart
and the answer is probably that you need to provide defaults
petro how ?
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
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
so i just have to add "retain: true" on my mqtt sensor, that's it ?
needs to be set by whatever publishes the value
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
-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
this code is also not mine, it comes from a github project, i've to check with the owner
you can presumably just add it youself
it is a perl which call a compiled cgi
my $mosquittocmd = "/usr/lib/cgi-bin/ecu/sendMqtt.cgi $_";
the cgi is cpp compiled file
sheesh
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
Perl and C++ CGI, dang. Is my calendar correct?
mmm, early 1990s...
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 π¦
you seem to have the tools, so knock yourself out
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 ) }}
What if you left it based on state but used delay_off (https://www.home-assistant.io/integrations/template/#delay_off) for a certain time?
Yeah that would probably do it
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
I am trying to figure out how to print individual device states. Reading through documentation at the moment.\
{{ trigger.calendar_event.start }} looks like this 2023-01-10T20:04:00+00:00
Something like {{ trigger.calendar_event.start } | strftime('%X') }} π
yep, or the caveman: {{ states.automation.landscape_lights.attributes.last_triggered.time() }}
That is what I am reading through actually.
Yes, the specific part I linked you to tells you how to get the state π
@silent seal Message malformed: template value should be a string for dictionary value @ data['action'][0]['data_template']
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
ok i will look at that... thanks @inner mesa @silent seal
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.
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
And as per the section of docs I linked you to, you shouldn't use states. unless there's no other option π
Yup, I'm so glad it was added
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?
I don't think you can template that property
What a tradegy
unit_of_measurement cannot be dynamic
Well how often are you going to change the unit of temperature?
Ok. Then I'll put them by hand
You can always find and replace on your template file(s) later to update it if you need to
I just dislike hard coding stuff when there's a data source that provides that info dynamically
@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") }}'
I think I figured this out now.
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 %}```
Only by providing the translated days yourself
Let me try after I figure out how to make an entities card that shows all persons π
{%- 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 %}
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'
- On startup, the new template sensor itself works fine
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 }}"
Crap, I was that close!
works like a charm π Thx
Thanks!
- type: entities
entities:
- person.steve
- person. ...
Is it possible to have an Entities card that lists all entities of a certain type?
That seems to work
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
Well you only have one opening { and one closing } but you need two of each, and you need to wrap that line with quotes
Use this: https://github.com/thomasloven/lovelace-auto-entities
For more help on that, please ask in #frontend-archived
Sorry. I thought that was a question of templating. But thank you very much π
No templates needed for what you asked π
Templates are magic and the solution to everything
- 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.
today_at('06:45') <= now() <= ...
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.
you could simplify that as {{ states('proximity.local')|int <= 5 and today_at('06:45') <= now() <= today_at('17:00') }}
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?
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!?
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
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'
easy enough to have it use different times for work/non work days too. wifi connected coffee machine or a dumb machine made smart? I wish mine had smart functions, just on a smart plug for now.
the way you wrote that template, I would guess {{ this.attributes.values()|select('in', ['active event', 'active notification'])|list|length > 1 }}
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'
looks like that's coming from a script, and a condition in it, rather than that template sensor
Really? The template sensor isn't loading and I never saw that error before.
there's no condition in there
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?
Pretty sure your attributes can't be maps, it's specifically talking about the doorbell attribute needing to be a string
Its talking about all of them but the attr state
so HA check configuaration fails then?
Passes
that was my thought as well
I presume you've plunked the state: template into Dev Tools?
but he says the template sensor is not present in HA...
it's not being loaded because it doesn't like the format
I suppose the dev tools check is not checkiing everything required for HA to load the template...
it doesn't know anything about what the attributes section of a template sensor accepts
Dev Tools > Template should prove/disprove that...
I thought an attribute could be a map
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
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
flatten it out
vol.Optional(CONF_ATTRIBUTE_TEMPLATES, default={}): vol.Schema(
{cv.string: cv.template}
),
Can you translate that to English?
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')
}
}}
Thank you I was just typing the single line less pretty version of that.
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
Can I still reference it the way I was? this.attributes.outdoor_2.state?
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 }}
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'
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
Are you able to try the template self referencing an attribute?
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
I have that working in other templates just not with maps. The others are unavailable for a minute or something and then work
ok. I think you're in uncharted waters here
as you've found out, the difference is that the attributes that you're referencing aren't part of the templates
I see.
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?
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
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"
`
You'll probably be looking for coffee, but elsewhere
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
(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
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() -
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
Try
service: input_text.set_value
data:
value: "{{ states('input_text.songtitel') + states('input_text.interpret') }}"
target:
entity_id: input_text.interpret_song
"{{ 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
# 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"
attributes:
- Google_Ping
Thanks Dan, will give it a go
From there you parse it into a template sensor
You can add back unit of measurement I missed it when I copied your code
I think I understand what you're talking about, appreciate you responding, will have to try tomorrow. cheers mate
but i want a "by" between the title and the artist
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 +
thanks
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 }}
{{ states.sensor | selectattr('attributes.model', 'defined') | selectattr('attributes.model', 'eq', 'HmIP-SWSD') | list }}
Ah! that did the trick.
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
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?
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 π
mine actually works. just wanted to know how can i reduce my code π
Okay, than I might borrow some parts from it later π
sure no problem π
you want an entity with attributes?
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.
Result should be: https://dpaste.org/5CQoY Translated from the German forum post of the original author https://forum.fhem.de/index.php/topic,60900.msg755975.html#msg755975
The dicts would be manually set up in the template.
Your code is very non-pythonic/jinjaish. It's very verbose and can be optimized.
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 }}"
There are a ton of errors in that. What are you trying to do? All your is_state if statements will fail
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...
@median mason I converted your message into a file since it's above 15 lines :+1:
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
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
Is there an easy way to select all lights which support HS (i.e. has "hs" in the supported_color_modes attribute)?
{{ states.light | selectattr('attributes.supported_color_modes', 'defined') | selectattr('attributes.supported_color_modes', 'search', 'hs') | map(attribute='entity_id') | list }}
Oh, search. Thank you, that's awesome!
np
attriubte π
fixed π
I took that as a discreet sign that you were able to type it all without testing :)
Just thought I'd mention it as I'm always searching chat for template examples that solve my problems π
right
{% 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 %}
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
wrong channel, but if you read the docs, you'd find out that it's based on max_samples which you can set
sorry, I was just playing the template of my trend sensor....hence I posted here....so its basically all max_samples. thank you
https://pastebin.com/5SLp6kex someone help me where is problem?
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 ?).
arming_time integer (optional)
State specific setting for arming_time (all states except disarmed and triggered)
arming_time isn't valid for disarmed
thx
in a custom:mushroom-template-card, is it possible to specify icon_color as an hs_color [x, y] ?
no official, but try card_mod from hacs
thanks! π
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
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
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.
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) }}
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.
ok. I don't recall that being straightforward
right on, thanks! π
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
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>)>
the state?
Thanks RobC
Yes basically you have to tune the max samples and the duration you specify. Another method is to specify that the sensor needs to be above the threshold for a certain time when you use it in automations. That would help to smooth out some false positives.
@rose scroll I think I found a solution. I could use the change feature in the statistic sensor. May what will it report?
I've been playing with trend for weeks now...no success π¦
there's actually some humidity examples in the samples.
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.
There is also this https://www.home-assistant.io/integrations/derivative/
Subtle differences between the statistical mechanics of each...
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?
It'll be a number indicating the rate of change. I.e. % change in humidity per min.
thanks very much @rose scroll!
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:
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') }}
How about && of two conditions:
- sensor.bed is state 'Out'
- NOT( sensor.bed is state 'Out' for 5m )
oh of course
thank you for that - here I was going to mess myself up with a template haha
conditions:
- condition: state
entity_id: sensor.bed
state: Out
- condition: not
conditions:
- condition: state
entity_id: sensor.bed
state: Out
for:
hours: 0
minutes: 5
seconds: 0```
does that look right to you?
Conditions are always AND, so no need for the first bit
ah of course. thank you
I need one of those! (entity_id: sensor.bed...)
Is there a time out variable for when a wait for trigger times out?
auto_off: ??
Not sure what you mean? That's not a variable in an automation. That's a template trigger.
Do you mean a variable containing the time remaining when it triggered before the timeout: expires?
- wait_for_trigger:
- platform: event
event_type: alexa_actionable_notification
timeout: "00:00:15"
Nope I just want to know if it timed out, a variable to be consumed in a subsequent action.
@barren umbra I converted your message into a file since it's above 15 lines :+1:
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.
@barren umbra I converted your message into a file since it's above 15 lines :+1:
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
@silent vector there is no timeout for triggers, triggers are a single moment in time, an event.
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
ah, that was not clear
https://www.home-assistant.io/docs/scripts#wait-variable
Looks like you should be able to check wait.trigger == none
I was about to say that π
Too quick π
wait.trigger is none is what I'd use
This should have been in #automations-archived...
that was already clear by now, and as he should use a template to check that, I think it's on topic π
time to go to bed then? Or are you already up again?
time to go to bed!!! π΄
@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.
I think we last discussed wind speed! I don't recall interjecting on the humidity thing...
Oh sorry I thought you were referring to my humidity sensor using trend versus derivative. The discussion is above I must have got mixed up, there's too many awesome helpers here!
No worries! It can get confusing!
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?
{{ ['sensor.x', 'sensor.y', 'sensor.z']|map('states')|map('float', 0)|sum }}
Awesome, thanks!
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 }}
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)
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
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?
Thanks @silent seal , I was using Round not round. π©
Could anyone share me a template to list all domain.update within a group?
{{ 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
You need to map to entity_id first before you can use map('states')
It doesn't work on the state object
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
hey all, I have a question...how do I create a condition based on a numeric state that happened 10 minutes ago?
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?
If you can explain what the end goal is, it'll be easier to point you in the right direction
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
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?
this is a good point, I can just increase the window to 1 hr
it would take more than 1 hr for the food to go rotten....so this a simpler solution thanks
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
If you share your whole automation I suspect folks can help
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.
Also, you are combining many things that some folks would split into multiple automations into one
probably yes
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 π
uh, that whole automation seems overly complex
I think it can be simplified a lot further, but thought I'd make some simple suggestions to start π
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
I wonder if the timer is really necessary
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
That's a really good idea
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
{{ 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)
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
That's entirely different... what are you trying to do exactly
or what problem are you solving
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
Can't say I completely follow why you wouldn't just let the setpoint itself control that
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
attributes will always be typed, even restored. datetimes are the only exception
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
thanks yes this works {{ state_attr('climate.serens_rad','current_temperature') < state_attr('climate.serens_rad','temperature')}}
but float worked allso
what does float do / mean?
It'll convert the type to a float (numeric) value. But those attributes are stored numerically, so it doesn't actually do anything here
| float(0) converts the thing into a float, and if it can't (e.g. it's "cat", it outputs a 0
pesky cats getting into my attrubutes
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
it looks ok, but a little hard to read in Discord without formatting π
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.
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?
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?
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?
Yes, you can use a time trigger and give it an entity π
There's an example here: #automations-archived message
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?
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)...
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:
that sensor doesn't accumulate anything
it just reflects a calculation of some other sensors - are they what you want to reset?
if I can yes
that would be a question for the #integrations-archived channel about that integration
there's nothing you can do in the template for that
but those are created by the UPNP integration that reads it from my modem
thanks Rob
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: {}```
you can't use templates there
Limitations
It is not possible to use templates for actions. But calling a script is a good alternative.
TIL smart cars allow you to control climate and even a steering wheel heater lmao
you also have some questionable templates there...
I'm sure I do. Okay i'll try a script.
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
you're using teh same type of quotes inside and outside your templtes
switch to " outside
Okay thanks!
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
value_template: "{{ states('light.primary_light') if states('light.primary_light') != 'unavailable' else 'off' seems more appropriate to me...
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 %}
I got an error , I suppose it not the way to get the value of this state.
You right for the == but still invalid
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 %}
Use is_state_attr from that link
the documentation look what I'm trying to do : state_attr('device_tracker.paulus', 'battery') will return the value of the attribute or None if it doesnβt exist.
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 %}
is_state_attr('device_tracker.paulus', 'battery', 40)
Sorry wrong copy past
And re -read that whole section
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 %}
Now I'm curious, what kind of standing desk can you connect to HA?
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.
Have this sensor feed a helper utility meter
Yip got that sorted earlier π thanks
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...
Can you remove it by going to the entity in the GUI, and then press delete under settings?
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
Hi, can anyone help me parse some Json to get a value?
JSON is here https://pastebin.com/JtjrzHaw
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
Itβs an IKEA standing desk : https://www.ikea.com/ca/en/p/idasen-desk-brown-dark-gray-s99281039/#content. Iβm using an ESP32 with ESPHome and ESPHome component for Ikea Idasen desk control https://github.com/j5lien/esphome-idasen-desk-controller.
Iβm working on an NodeRed automation to change my desk position after 90 minutes of usage of my computer. The automation will wait for certain events : the end of a zoom call or ideally Iβm going to the restroom π
I don't see any issue there, maybe check your indentation, yaml sucks
Maybe post the full code for the template sensor
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}}```
{{ 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 }}
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').
you can map() any filter to apply it on the individual items in a list
Yes, but I think I tried it on the attribute lights..
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 π
yeah, wished Ha Hue integration would do it natively though.. just like with light groups
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)
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
@deep marsh I converted your message into a file since it's above 15 lines :+1:
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?
I have sorted it - believe it or not if you put scan_interval: at more than 300s it just doesn't work.
just use the attribute itself instead of a set range
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)) }}
- name: "Ingo procentuell skillnad"
@deep marsh ```jinja
{% set list = state_attr('sensor.bla', 'forecast') %}
{% for i in list %}
{% endfor %}
i just get sensor value unavailable
does the template work in devtools > templates?
Works for me when I replace it with sensors that are in my HA. Maybe your indentation is bad?
Really? Is that documented anywhere? Seems strange
Try restarting HA if reloading just template entities alone didn't work.
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 }}
- name: "Ingo Mellanskillnad"
that works without issues end the sensor gets a value
i then wanna use that value in a new sensor
/ (states('sensor.battery_energy_in') | float)) }} ```
Nope ... it simply doesn't return anything if you up the scan_interval. Had to set it to 60 and hope they don't think I am spamming them!
- 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
Maybe something to report on the forum or github then...sounds like a bug
Maybe
You have value_template twice?
That is incorrect yaml, that will not work
I just checked, I have a REST sensor where the scan_interval is set to 1800 because I'm limited to 50 API hits a day...and it works fine
Ok, some changes and now i get this error:
ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ states('sensor.ingo_mellanskillnad') | float - states('sensor.ingo_95') | float }}' but no default was specified
at least one of those sensors doesn't have a numeric state
the sensors aren't numbers
Or at least one isn't
Do them one at a time
See which one is unavailable
but you would also see that if you test it in devtools > template
thats where i got the error
yep they both do
Sure?
try this in devtools:
{{ states('sensor.ingo_mellanskillnad') }}
{{ states('sensor.ingo_95') }}
sensor.mellanskillnad 4.51
what does that return
Resultattyp: string
unknown
19.65
okay, that's your answer
First one is stuffed
so how to i change it from a string?
It says unknown
- sensor:
- name: "Ingo Mellanskillnad"
unique_id: ingo_mellanskillnad
unit_of_measurement: "kr"
state: >-
{{ states('sensor.ingo_95') | float - states('sensor.ingo_etanol') | float }}
- name: "Ingo Mellanskillnad"
not, are you sure you did not make a typo in the entity_id
You need to fix that first
because that would give stat unknown
this is what calculates the sensor mellanskillnad
check the actual entity_id in devtools > states
in states i get the value 4.51
and please format your code
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.
don't post images of code
'''- 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 }}
- name: "Ingo procentuell skillnad"
- 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 }}
you could have edited your previous post though
devtools says that all sensors has values exept sensor.ingo_procentuell_skillnad
sorry bout that π©
what is the entity id according to devtools > states
check that in the table in the lower part
'sensor.ingo_mellanskillnad'
sensor.mellanskillnad
nevermind, ill show my self out. Thanks for all the help π
@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)
That's really nice, thanks for sharing.
I will post on GitHub my setup when the automation is "finalized"
wow
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
{% set entities = range(1, 25) | map('string') | map('regex_replace', '^', 'sensor.mgp_pun_ore_') | list %}
that seems to return the same list of entities
ah, slice was not in my list of normal functions yet π
it was like a little challenge because I thought it should be doable
it's not on mine either
are there cases when this is not defined, or is that just to have it working in devtools?
π€·ββοΈ
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
true
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 sedge I converted your message into a file since it's above 15 lines :+1:
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.
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?
first and foremost, you should only have 1 sensor section
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
I'd agree but the restful command using the same headers is working.
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.
you're outputting to much to the state
So how do I output less?
here is the JSON : https://pastebin.com/JtjrzHaw
I've used JSONpathfinder to get the attributes
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
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.
are you sure that's not an old error message?
@tired sandal I converted your message into a file since it's above 15 lines :+1:
@tired sandal looks pretty good to me
you have some extra parenthesis in there but nothing overly done
@mighty ledge thanks, I've removed the time comparison since @marble jackal pointed out that forecast is always (more or less) gte now()
Yeah - bad news is that HA has created spotify_artist_rest_2 etc. now - any way to get rid?
just delete it
How - the option to delete isn't there....
restart HA instead of reloading the rest integration
good point. thank you :)
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 %}
no, you'd need to make a template sensor that uses the stats sensor
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 %}
not sure I follow... (not good with templates)
when you say "keep the last value", could you please elaborate?
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
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 }}
that's the actual code
it only works in a template sensor
as this is only available in templates, scripts, or automations
right... so... in the example... "this" is referring to the template sensor in which: this.state is coded... effectively: myTemplateSensor.state
it's referring to the state object in which the template resides
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
why don't you use the derivative sensor instead
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.
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 }}
it's exactly the same as what you had before, it gives the change over time
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
search using regex is the only way
Would you happen to know the syntax?
but... with derivative... when there is no change, it will just display 0 via built in functionality?
test is search('eject', ignore_case=True)
or you could just search for ject and omit the E
regex_search() got an unexpected keyword argument 'ignore_case'
'ject' in test
or if you have different words, {{ test is search('foo|bar') }}
That's possible. (This is not for home assistant) and I don't think anyone would approve of searching for 'ject' π
might just be a non keyword arg
yah
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
{{ test is search('eject', 'ignore_case=True') }}
Worked
You're saying use that? Or that's why it worked
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
it's not the correct keyword
so it would have been...
{{ test is search('eject', ignorecase=True) }}
no _
So this one is good?
{{ test is search('eject', ignorecase=True) }}
Awesome thanks.
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?
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') }}
Thanks for that info, I appreciate you explaining it. Sorry if I was an ass.
@tacit sun I converted your message into a file since it's above 15 lines :+1: