#templates-archived
1 messages · Page 163 of 1
So I'm trying to stop the error from happening by checking the list isn't empty before running the average.
{{ expand(area_entities('kitchen')) | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'temperature') | map(attribute='state') | select('is_number') | map('float') | average | round(1) }}
I think you need to do that in two steps: yaml {% set values = expand(...) ... | map('float') %} {{ iif(values | length, values | average | round(1), 'unknown' }}
Ah ok! That makes sense. Thank you.
Actually, that will just give you the same error.
Yeah I've just noticed that.
{% set values = expand(area_entities('kitchen')) | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'tempserature') | map(attribute='state') | select('is_number') | map('float') | list %}
{{ iif(values | length, values | average | round(1), 'unknown') }}
iif evaluates both arguments regardless, so you need a full if: {% if values | length %} {{ values | average | round(1) }} {% else %} unknown {% endif %}
You could also add an availability template using something like:
{{ expand(area_entities('kitchen'))
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'temperature')
| map(attribute='state')
| select('is_number')
| list
| count > 0
}}
how do I take 1 minute away from {{ as_timestamp(now()) }} ?
Not sure this is the location but it's a best guess. How do I make a binary sensor that acts like a coin toss? True and false presenting heads and tails (not necessarily respectively).
I'm thinking something like
is_int(Time.Milliseconds /2)
However that's nonsense in yaml
Subtract a timedelta
You want it to be random? What's the goal?
Look at the random integration though: https://www.home-assistant.io/integrations/random/
Perfect
Thank you
that is cool, never new that existed .... now got to find a nice reason to use it 😉 somehow feel my mockupancy config could benefit from this.
Hey!
I'm reading breaking changes and noticed tat "Defining manually configured MQTT entities directly under the respective platform keys (e.g., fan, light, sensor, etc.) is deprecated, and support will be removed in Home Assistant Core 2022.9."
Does the same also applies/ will be applied to Template?
@novel crystal posted a code wall, it is moved here --> https://hastebin.com/kemevumuyi
lol, ty BOT
how? Im new to templates
Check the docs. They detail timedelta and working with dates and times.
Hi!
I want to pull the data from the hour that is current hour from the weather forcast. More specifically I want to get the precipitation. I just can't figure out how to do it
For some reason the met.no integration's hourly forcast does not show precipitation as of right now as an attribute but the forcast attribute contains the precipitation for current hour
Here's the data https://pastebin.com/iKtktQLa
So If I would like to select precipitation from 12:00. How can I do that?
No, the template lights/covers/switches etc still remain under the respective domains
Oh, had a look at your link as well now
You should have a look at the new format, that is totally different as what you are trying to put in now
It should be something like:
template:
- binary_sensor:
- name: is DST
state: "{{ now().timetuple().tm_isdst > 0 }}"
Furthermore, these templites reside under the template integration, and not under the sensor integration, so you can't place them in your sensors.yaml
Is there a clean way to check after a certain time if the target_sensor value is equal to the value sent in the command? Such as whether the sensor mode is equal to active if the command sent in the previous action was active or the temperature is equal to 65 if the temperature sent was 65. If not after 5 seconds then resend the command (in the event the API timed out and never processed the command). Then recheck and if it still isnt equal send a notification (presumably API Issue).
https://www.toptal.com/developers/hastebin/buguwimuso.less
template trigger in wait_for_trigger
or a wait_template
depends on how fast the API responds.
both are covered in the script section of the documentation
yes I have it (during testing) inside my templates.yaml.
tyvm for your answer
And then what would the template be to see if it equals what was sent in the rest command?
https://www.home-assistant.io/docs/scripts for the syntax
you'd look at the sensor
you update the entity, and then check the sensor
And see if the target_sensor == service_data?
what's the state of the sensor that you're updating
It's going to be either on/off or a number (temperature). 2 different templates sensors.
ok, and you want to look at your temperature sensor, right?
basically, you want to check whatever the state is going to be
you know how to do that, you've done it before
I was overthinking it. It's simply is the state equal to the variable temperature or mode if it was a mode change.
{{ as_timestamp(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) }}
doesnt seem to work
timedeltas are not an integer and as_timestamps are
don't use as_timestamp, change it to as_datetime
that attr should already be a datetime, so you probably don't even need that.
Lastly, if you're on 2022.6, you can use the offset calendar triggers so you don't even need a template if you're trying to make a notification automation.
Oh thanks - I am using this as trigger in a bigger automation
{{ as_timestamp(now()) > as_timestamp(state_attr('calendar.gmail','start_time')) and is_state('calendar.gmail', 'on') }}
this didnt work:
{{ as_timestamp(now()) > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
but this alone does
{{ as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) }}
Then just use the new calendar trigger with a 1 minute offset
with a condition that checks to see if the calendar is on
Yes, that would work, but look what you're doing in the previous one that doesn't work. You're using as_timestamp again... those aren't integers and as_timestamp is
hmm I tried both
{{ now() > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
&
{{ as_datetime(now()) > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
still cant get it to work
Now is a datetime
Triggers have to resolve false then resolve true for it to trigger
If you’re restarting and you’re past the time, it won’t trigger
I meant just in developers > templates
I'm trying to get it work there before taking it to the automation
Now() is local timezone, what’s the timezone on your cal? If it’s local you need to add as_local as well
What error does
> templates give?
for: {{ as_datetime(now()) > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
TypeError: float() argument must be a string or a number, not 'datetime.datetime'
so i tried: {{ now() > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
Dude, remove the as_datetime on now and add as_local on the as_datetime(state_attr
{{ as_local(now()) > as_local(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
gets me: AttributeError: 'str' object has no attribute 'tzinfo'
oh lord haha
and keep as_datetime on the start_time attribute
Now does not need to change
but add as_local as well
Like, read what I’m writing
It’s very frustrating to help a person who is not reading what you’re writing
as_local(as_datetime(state_attr()))
or, maybe more readable: state_attr() | as_datetime | as_local
I really appreciate the help - I am sorry it is frustrating you but I am just trying to wrap my head around it
{{ now() > as_local(as_datetime(state_attr('calendar.gmail','start_time'))) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
does that work in
>templates?
How can I get the precipitation from the current hour from a weather sensor? The [0] is usually 1-3 hours in the past
What does the sensor show in developer tools?
I’m using my phone at the moment but it’s the regular weather.home_hourly so the forecasts have a datetime attribute. I’m guessing I somehow can loop trough the forecasts, select the one that matches current hour and then use that precipitation state.
The data looks like this https://pastebin.com/iKtktQLa
{%- set w = 'weather.climacell_hourly' %}
{%- set h = today_at(now().hour ~ ':00') %}
{%- for f in state_attr(w, 'forecast') %}
{{ f.precipitation if as_datetime(f.datetime) == h }}
{%- endfor %}
Change the weather entity in de first line
Could be done easier if I knew how to convert a datetime in local time to utc 🙂
On a side note I used to use the regular home_hourly until I realized how inaccurate it was in comparison to AccuWeather or openweathermap at least for me it was inaccurate by a few degrees and sometimes more. Openweathermap also let's you get an hourly forecast if you want to know hour by hour vs 3 hours. Openweathermap also updates more frequently than the regular one.
Thanks for trying to help guys! I’ll have a look at it
@tidal heart Better version
{%- set w = 'weather.climacell_hourly' -%}
{% set u = utcnow().strftime('%Y-%m-%dT%H:00:00+00:00') %}
{{ state_attr(w, 'forecast') | selectattr('datetime', 'eq', u) | map(attribute='precipitation') | join }}
Updating to 2022.6.0 😄
Not needed anymore with the last version
I have been so frustrated that the weather sensor in general seem to just skip the precipitation and precipitation_chance in the "current" attributes (not in the forcast list)
Trying now, can it be so that if it returns 0 it actually does not show at all?
Or wait utcnow() is the right timezone for me
now() seem to work though!
You need utcnow() here, because the timestamps in the weather forecast are in utc
- condition: cloudy
precipitation: 0
precipitation_probability: 16.7
temperature: 13
datetime: '2022-06-02T13:00:00+00:00'
wind_bearing: 260.4
wind_speed: 23
This is the part of the current hour, and precipitation is 0 here. So 0 seems to be correct
Wait what! This gives me 0.0 and if I change the mapped attribute to datetime it's the right hour as well
{%- set w = 'weather.home_hourly' -%}
{% set u = now().strftime('%Y-%m-%dT%H:00:00+00:00') %}
{{ state_attr(w, 'forecast') | selectattr('datetime', 'eq', u) | map(attribute='precipitation') | join }}
Damn, how do you make the formatting so nicely here on discord? Mine looks like shait
Nice!
{{ now() }}
{{ now().strftime('%Y-%m-%dT%H:00:00+00:00') }}
{{ utcnow().strftime('%Y-%m-%dT%H:00:00+00:00') }}
result:
2022-06-02 15:23:00.008942+02:00
2022-06-02T15:00:00+00:00
2022-06-02T13:00:00+00:00
at least for me, as I'm on GMT+2
Yeah I'm as well
okay
then with now() you wil get this part
- condition: cloudy
precipitation: 0
precipitation_probability: 1.5
temperature: 13.4
datetime: '2022-06-02T15:00:00+00:00'
wind_bearing: 266.3
wind_speed: 26.3
which is also 0, so it seems to be correct as well, but that will not always be the case of course
That time there is not the right time, because it is in utc
Hold on now... so you mean that if I use now() it might not get the right data in the template? Like it could go for the next hour or what?
If I tried utcnow() it renders nothing
Our current time is 15:27 which is 13:27 utc
so currently you need the block with the datatime of '2022-06-02T13:00:00+00:00'
Oh my! So you mean that everytime I'm looking at those forecasts it's actually not in my timezone!? (at least the attributes I guess the UI sorts it out)
The last part +00:00 shows in which timezone it is
Ah!
if that shows no offset, it is in utc time
Now I get it! And when I try your code it renders nothing because this met.no does not actually have information on the current hour
... and then there's daylight savings time... as you can imagine programming this stuff is an absolute joy.
ah, climacell does
What country are you in?
Netherlands
Ah ok, the met.no is close for me as I'm in Sweden
Is there a way to like store the last hours info so I can access that as a "current" hour sensor? Like when 15 switch to 16 it stores the 15's info?
It does the same thing for the current day on the main sensor as well. I guess it kinda makes sense as they are forcasts but for some reason it does not use precipitation at all in the current attributes
I mean on the current day it would be nice with a "X% chance of rain"
You could make a trigger based template sensor which updates it on a time pattern (10 seconds before the whole hour for example) and stores the whole forecast attribute in an own attribute
Sounds good as long as I'm not rebooting/reloading at the wrong time 😄
correct 🙂
Thanks a lot for teaching me this! I was about to give up on it haha
The timezone trolled me bad
👍
Can I add an hour to your initial code to pull the hour after current hour?
Also I'm not sure if the weather forcasts switch to the next hour on for example 15:59:59 or if it can vary a couple of minutes
yes, but that will basically the first item in the list
{{ state_attr('weather.entity', 'forecast')[0].precipitation }}
btw how to handle state triggers from MQTT button? I got the command to work but not how to catch the button state. It will just carry the date/time
A button doesn't have a state like on and off. The state is the last time it was pressed.
hi i nearly have what i want as a message but can't figure how to end it message: 'http://192.168.3.250:8200/MediaItems/{{trigger.json.message}} .mp3'
basically have the url and .mp3 after it and that needs to be part of the url
Agree, but how to get hold of it?
use a trigger based template and template all you need? like:```
template:
- trigger:
- platform: event
event_type: hue_event
event_data:
id: alarm_button_button
sensor: - unique_id: alarm_button_last_event
<<: &alarm_config
state: >
{{trigger.event.data.type}}
attributes:
last_triggered: >
{{trigger.event.time_fired.isoformat()}}
- platform: event
obv use an mqtt_event
For my lights i use the following template, how to do the same for a button a catch the trigger?````
- platform: mqtt
name: "Garage Roof"
schema: template
state_topic: "pt:j1/mt:evt/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:8_0"
command_topic: "pt:j1/mt:cmd/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:8_0"
command_on_template: '{"corid":"","props":{},"serv":"out_lvl_switch","type":"cmd.binary.set","uid":"1d5a45b0-d2bd-11ec-901b-194ce6613fff","val":true,"val_t":"bool"}'
command_off_template: '{"corid":"","props":{},"serv":"out_lvl_switch","type":"cmd.binary.set","uid":"1d5a45b0-d2bd-11ec-901b-194ce6613fff","val":false,"val_t":"bool"}'
state_template: "{{ 'on' if value_json.val == true else 'off' }}"
equalent to the state_topic and state_template
what exactly do you want to catch? As Fes says, the state of a button is merely the last_changed
if you want a template triggered on that state change, use that in the trigger based template, and create a sensor, with any state template you are looking for: https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-numbers-selects-and-sensors
I want to catch the trigger aka state date/time. When the fysical button is pushed the MQTT payload is sent. I want to read that to HA so i can trigger my nodered event.
When pushing the button it works, so the command payload is fine.
hi all, I'm currently trying my first template sensor, as I want to get some entity attributes as sensor, which I could implement accordingly. from the dev git of this integration I got {{ states.sensor.2minersinfo_miner_address.attributes['unpaid'] }}
as this is my first template I'm not 100% sure if the include in my configuration.yaml is working as expected too ``template:
- binary_sensor: !include_dir_merge_list templates/binary_sensor/
- sensor: !include_dir_merge_list templates/sensors/
- trigger: !include_dir_merge_list templates/trigger/ ``
after the restart I get the following error Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'minersinfo_ETH_Wallet') for dictionary value @ data['sensor'][0]['state']. Got "{{ states.sensor.2minersinfo_ETH_Wallet.attributes['unpaid'] }}". (See /config/configuration.yaml, line 29).
so arent you in fact talking about a regular mqtt sensor? that sensor picks up the payload, and changes state. You can then trigger based on that state change?
Yes i guess you are correct, the sensor might be right. But the then i cant trigger the sensor in HA, i will be forced to the fysical button.
Of course i could create a local button that changes the sensor locally
I was hoping that the MQTT button could be used both locally in HA so as the fysical button.
you could write that trigger based template and use both the state change of the physical button (regular mqtt sensor) and a virtual button. Just start with the first, see if it works, and then add the virtual button
you issue is with the name starting with a 2, see the docs on how to handle those https://next.home-assistant.io/docs/configuration/templating/#entity_id-that-begins-with-a-number
you mean the name of the sensor? no the name of the sensor is - name: "Unpaid ETH Balance"
entity_id starts with 2
but the integration itself startes with 2 (2miners)
try:{{ states.sensor['2minersinfo_miner_address'].attributes.unpaid }}
(cant test myself because dont have the entity)
tried it .. currently restarting 😦 everytime these restarts 😦
just reload templates....hit c key, type template and click the reload Template entities in the quickbar
but, before doing that, enter the test template in dev tools template https://my.home-assistant.io/redirect/developer_template/
"nothing found"
really sorry but I have to go.. again try in the dev template page, and maybe even {{ state_attr('sensor["2minersinfo_miner_address"]','unpaid')}} though again, I can not test myself
ok will play around with that thank you
this works locally:{{ states.automation["2v12_alarm"].attributes.last_triggered}} so if 'unpaid' is a regular attribute in your sensor, that format should work
i'm trying to build a string and failing its basically url, number, extension with the number being a variable so url/number is ok but the extension is separate so the link fails
got it htank you so much (and also found the reload tempalte button xD)
Can a mono stabile mqtt switch be created?
Are trigger.to and trigger.from available in trigger based template sensors
Just asking because they're not super easy to debug..
hi would anyone be able to help with what i thought was a simple template ?
Hello everyone
show us what you've got
did you try? 😉
I am struggling with a simple template for an automation:
condition: template
value_template: {{(now().day|int % ((states('input_select.watering_repeat'))|int) == 0)}}
and I am getting this:
Invalid condition configuration
template value should be a string for dictionary value @ data['value_template']
what's wrong with the above ?
input_select.watering_repeat contains numbers, from 1 to 7
Hi guys
you need to set defaults on the |int , see the Pinned posted in the header here (this is besides any logical check, and purely syntax)
will now, couldnt before :p
That's a bug documented in the pinned message
I get this in that template, because I dont have the entities: ValueError: Template error: int got invalid input 'unknown' when rendering template '{{(now().day|int % ((states('input_select.watering_repeat'))|int) == 0)}}' but no default was specified
the template is working fine in the devtools
as RobC said, see: https://github.com/home-assistant/frontend/issues/12282
@floral shuttle and @inner mesa : thank you, I'll check this
I want to create a weather template entity and in the forecast_entity field it needs to be an array.. how can I set a custom array?
you should really search the commmunity for that, there are many examples and suggestions available, did you have a look?
works fine in dev tools but, something like this wont recursively update, will it?
{%set alldistance = 20 %}
{%set alldistance = distance+alldistance %}
{{alldistance + distance}}```
uh in a template sensor
what part of that is recursion?
you're just referencing the current status of a sensor in the definition of the sensor?
yeah, idk, im not sure if its going to see the status change and try and update it again
how do i change media_content_id: "http://192.168.3.250:8200/MediaItems/{{trigger.json.message}}" to media_content_id: "http://192.168.3.250:8200/MediaItems/{{trigger.json.message}}"+.mp3 ??
I see
it seems easy to add mystring ((trigger.json.message)) but adding a third part has me totally stuck
you've only included part of the definition, but I would expect it to be based on the value of another sensor, and the template sensor will only update when that other sensor updates
It's not inherently a problem to reference the current value of a sensor, and in fact that was made easier via this in the last HA release. It will be a problem if you then trigger an update to the sensor based on updating the sensor
ok, ill try to take this one step at a time. this template sensor doesnt appear to be triggering. what did i do wrong?
platform: state
entity_id: sensor.lexus
attribute: Trip Distance(miles)
to: '0'
- sensor:
- name: Old Day Distance
state: >
{{trigger.from_state.attributes[Trip Distance(miles)]|float+(states('sensor.old_day_distance'))) }}
sensor doesnt even show up with an unknown value
Hey! Could someone help me out here. I have this template here. Show me what I want to see, a simple time!
state: "{{ state_attr('sun.sun', 'next_rising') | as_datetime | as_local - timedelta(minutes = 45) }}"
But it turns out like this: 2022-06-03 03:33:26.128445+02:00
What do I need to add in the code to just show me the time in hours : minutes ? 😛
your syntax is incorrect
template:
- trigger:
platform: state
entity_id: sensor.lexus
attribute: Trip Distance(miles)
to: '0'
sensor:
- name: Old Day Distance
state: >
{{trigger.from_state.attributes['Trip Distance(miles)']|float+(states('sensor.old_day_distance'))) }}
(note that I removed the extra "-" and you need to have it all nested under template: (or in an included file), which you didn't show)
Always:
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
- HAOS & Supervised use
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
also, you need to quote the attribute name
{{ (state_attr('sun.sun', 'next_rising') | as_datetime | as_local - timedelta(minutes = 45)).strftime('%H:%M') }}
Thanks a lot 🙂
Hi i want to template a message https://paste.debian.net/1242862/ trouble is i can't quite get the right result can anyone help me please or am i beyond hope
what is the value of trigger.json_message?
60149
the idea is to finish up with server/file .mp3 all the file names are numbers since its minidlna that serves them
actually it kinda does , in an unexpected way see the filename should be 60149.mp3 so i wanted to concatanate the 60149 and .mp3 together along with the server path. serverpath and filename not a bother but i was getting url .mp3 so the extension wasn't part of the url. however i just tested something minidlna doesn't care 60149 and 60149.mp3 are the same as far as its concerned
lol
so i have just spent all afternoon trying to add an extension that isn't actually needed to make it work
it must be possible to template it with the extension i have done it before for a rest sensor
that i basically created 3 variables a , b, c and just assigned to d = a + b + c
Thanks on both fronts.
Is it possible to have multiple triggers for a template sensor and then use trigger ids with it? Not sure how that would be formatted if it works, don't really see much of anything about template triggers in the docs
something like
platform: state
entity_id: sensor.lexus
attribute: Trip Distance(miles)
to: '0'
id: update
trigger:
platform: time
at: '00:00:00'
id: reset
sensor:
- name: Old Day Distance
state: >
{{trigger.from_state.attributes['Trip Distance(miles)']|float+
(states('sensor.old_day_distance')|float(0)}}```
or would i just make 2 different templalte sensors for that
You make a list of triggers. It's exactly like an automation
i changed how im doing this. i think this works better since template sensors dont store over restarts
https://www.toptal.com/developers/hastebin/wiqikuvomi.yaml
if theres something like an input number that doesnt allow manual adjustments, that would be cool to avoid an accident
Mqtt sensors
A template number?
Or that
Template numbers remember their state after a reboot?
Hmm, I guess not:
The state, including attributes, of trigger-based sensors and binary sensors is restored when Home Assistant is restarted. The state of other trigger-based template entities is not restored.
What would a template be to pull all of this in as attributes? It's a rest sensor. Here's the api documentation too, scroll to the bottom for what a response is. I thought if it was application/json it would be read in automatically. It isn't doing that as I got an error it exceeded 255 characters meaning it attempted to pull it into the state.
https://dpaste.org/SOtzr
https://docs.developer.sleep.me/docs/
Would this work?
{{ value_json | list }}
where do you plan to put that?
What's your rest sensor's full config? Are you using json_attributes? https://www.home-assistant.io/integrations/sensor.rest
I would do it as the examples here show: https://www.home-assistant.io/integrations/sensor.rest/#fetch-multiple-json-attributes-and-present-them-as-values
but you may be able to provide json_attributes_path to have them all pulled in without specifying each top-level key
Hi all, new user here. how do I create a lovelace template ? can someone point me in the right direction, I have installed lovelace gen, I'm trying to follow these instructions to track house chores https://github.com/Burningstone91/smart-home-setup#household-tasks
that's better asked in #frontend-archived
ok sorry and thanks
- platform: rest
name: Left DockPro
resource: 'https://api.developer.sleep.me/v1/devices/<DEVICE_ID>'
scan_interval: 30
headers:
Authorization: !secret sleepme_api
Content-Type: application/json
Try following the example Rob posted above to generate the attributes from the JSON output.
Alright I'll do that, thank you.
I worked out a template that adds circuit 1+2 for my AC. I have 1 day and 1 mon total increasing values. I tried to add state_class: total_increasing to my sensors. However home assistant says platform:template state_class isn't valid any way I can resolve this
I am trying to get my AC to show up in my energy dashboard.
I already added device_class: energy
Invalid config for [sensor.template]: [state_class] is an invalid optopn for [sensor.template]
you need to use the new format: https://www.home-assistant.io/integrations/template/#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors
to save hours of fustration how would I convert the attached sensor
Please give it a try
I still get state_class is invalid for [template]
I have spent hours in fustration please help
is this even remotely right
There are clear differences between that and the very first example
well you said rewrite in some modern form
so I guessed at it
I have literally NO idea what I am doing wrong
alright
here's the example:
template:
- sensor:
- name: "Average temperature"
unit_of_measurement: "°C"
state: >
{% set bedroom = states('sensor.bedroom_temperature') | float %}
{% set kitchen = states('sensor.kitchen_temperature') | float %}
{{ ((bedroom + kitchen) / 2) | round(1, default=0) }}
here's what you did:
template:
sensors:
name: "Air_Conditioner_Day"
# state_class: total_increasing
device_class: energy
friendly_name: "Air Conditioner Day"
unit_of_measurement: "kWh"
state: >
{{ ( (float(states('sensor.air_conditioner_2_16_1d')) + float(states('sensor.air_condition_1_15_1d')) )) }}
name: "Air Conditioner"
device_class: energy
# state_class: measurement
unit_of_measurement: "wh"
state: >
{{ ( (float(states('sensor.air_conditioner_2_16_1min')) + float(states('sensor.air_condition_1_15_1min')) )) }}
you have "sensors:" where the example has "- sensor:"
you have "name:" where the example has "- name: xxx"
Despite appearances, I am generally happy to help. But I do look for some effort to match examples that are very close to what you want
rebooting to see if its right
the sensor does not appear in developer tools
I guess I have to delete friendly_name
and rebot
now they exist again but have unknown values
ok they came back
i have a template sensor that gets confused after midnight , it uses today_at('00:00'). i dont really understand why this happens, or h ow i can tell it not to get confused
{%set time = (strptime(pretime, "%d-%b-%Y %H:%M:%S.%f"))%}
{% set triptime= state_attr('sensor.lexus', 'Trip Time(Since journey start)(s)')|float%}
{%set offset = (((as_timestamp(time))-as_timestamp(today_at('00:00'))-triptime-(triptime/20))/3600)|round(2)%}
{{'+'~offset if offset > 0 else offset}}```
works fine in dev tools template
the sensor is showing 19.71 which is what it would be showing at about midnight, likely 11:59
the template is showing -4.29 which is right
do i just have to add somet hing extraneous in there that gets it to pay attention t o time like now()? why doesnt today_at() update at midnight, since, yknow, today changes at midnight
is there something that updates less frequently than every minute, like every hour?
Hi guys
I have this forecast data attribute whithin a sensor, it's an array:
I'd like get this array, select only the values whose date is the same as today or after today, and then, whithin every datetime, replace 22:00 with 00:00
how can I do that?
Hi
I Am trying to setup a template with a trigger but it seem that i miss some thing I am on 2022.6.1 in my configuration.yaml is the following
template:
- trigger:
- platform: time_pattern
minutes: "/2"
sensor: - name: "Estimate Inverter Runtime left"
state: "{{ ((states('sensor.rct_ac_output_rating_active_power') | float * (((states('sensor.sunsynk_soc') | float) - 20) / 100) )/ states('sensor.inverter_load_avg') | float ) | round(2)}} "
- platform: time_pattern
but this do not trigger every 2 min. Without the trigger this sensor update about every second and i want to limit this
If I look at the logbook this sensor update vary between 6 min to 9 min update inverval
Any suggestion what I am doing wrong?
What is your goal here? Normally all values in the forecast are today or later, otherwise it won't be much of a forecast
Note that these timestamps are in utc, so you are probably in GMT +2, so these timestamps are at midnight local time
Exactly what you seem to want :)
Struggling to make a template sensor out of this or any template for that matter than can read these state attributes they are json_attr from a rest sensor
https://www.toptal.com/developers/hastebin/efelicoyih.yaml
{{ state_attr('sensor.foo', 'about').firmware_version }}
That was fast and it worked thank you.
I have an automation to notify when a new iOS release is out via an RSS feed using feedparser. It uses a template sensor that get's the information that I'm looking for looking like this https://www.toptal.com/developers/hastebin/aliwifucuc.kotlin
Everytime I reload the template entities it triggers though, what can I do to prevent that? Automation is looking at the state so I guess it gets unavailable or something. Heres the automation https://www.toptal.com/developers/hastebin/ubodopazug.less
It does not trigger on reboot, only on reloading template entitites
look at your automation trace and see what the state is before it.
Can I somehow stop an automation from triggering when state has been unknown anytime in the last 1 min?
It seems it moves from correct state to unknown and then back to that first state.
A second automation that disables and enables the first?
Just reading the words of the question. Not considering any A/B-problem.
It's probably not the best solution for whatever you actually need.
A template binary sensor which turns on when the sensor state is unknown with a delay_off of one minute
🤷♂️ I think the simplest solution is to just use not_from, it was specifically added to filter out state transitions on startup
I tried:
platform: state
entity_id:
- sensor.apple_ios_latest
not_from:
- unknown
not_to:
- unknown
But that did not work
are you sure your sensor is 'unknown'?
Or indeed not_from in combination with for
you have to look at the from_state in the trace after a reload
I'd wager it's unavailable based on your code.
not unknown
Good question, as this notifies my phone I got two notifications simulations, one with the old state and one with unknown
Also tried a
condition: not
conditions:
- condition: state
entity_id: sensor.apple_ios_latest
state: unknown
99% sure templates go unavailable during reload. I'ts been a long time since I reloaded though.
This is still triggering it. I can't see what the state it changes to in the history tab, it's so small I can't select it and the logbook actually don't register any change at all.
platform: state
entity_id:
- sensor.apple_ios_latest
not_from:
- "unknown"
- "unavailable"
- "null"
not_to:
- "unknown"
- "unavailable"
- "null"
for:
seconds: 5
did you reload the automation?
null isn't a valid option btw, you won't get that either.
Yeah
it's going to be unavailable or unknown, and drop the for
platform: state
entity_id:
- sensor.apple_ios_latest
not_from:
- "unknown"
- "unavailable"
not_to:
- "unknown"
- "unavailable"
you can look in your history what the state is as well
I can't select them small breaks in the history tab
Ah, you can't type it
either way, you should still be able to see 5 seconds of state in 5 minutes, if you aren't then it's a smaller window than 5 seconds and the for: is your problem
Yeah they are to small
then use the trigger I posted above
Already tried it, still goes trough
reloads and to circle back for the 10th time, what does the trace show
it will literally show you what the before and after state is
Let it trigger on every state change and write trigger.to_state.state to a persistent notification
you don't even need to do that, just look at the trigger trace data
it'll be on his last trace
👍🏼
Click on the trigger, then click on changed variables
Step details?
null
in quotes?
Without
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
@tidal heart posted a code wall, it is moved here --> https://hastebin.com/mifuqijeco
Ah, the whole state is missing
so
add:
to conditions:
- condition: template
value_template: "{{ trigger.to_state is not none and trigger.from_state is not none }}"
I always use iif for such checks
I wouldn't use iff for checking none
when checking for none, you want to use is, not ==
TBH, I thought HA got rid of all those trigger events
I still have them in all my automations, but it's because I was too lazy to remove them.
So, I won't be removing them I guess
Hehe nah it seem to be a good idea to stick with them
They must only be suppressed at startup
Thanks a bunch for the help! Learned to dig deeper into trace tab and that I can use trigger.to_state
{% set test = none %}
{{ test is not none }}
{{ iif(test) }}
both return False here
yes, but that's because if test will return false, however if test is 0, which is valid, it will also return false.
if 0 -> false
if none -> false
if '' -> false
if you want to check for none, you have to use if is none
Yeah okay, or []
right, same with {}
basically any "empty" object
will be false
for the built in objects
int, float, str, dict, list, etc
granted, those variables won't be thte built in objects so I guess you could use it
Yes, but in there is actually a from_state it will return True. So I agree you are not only checking for none
If you really want to know if something is none you can not use it
well i think iff(x is none) would work
but that's just extra steps
when you could do x is none
it depends on what you want to catch. I use if x when don't want empty objects or none, and i use if x is none when explicitly looking for none
python isn't strongly typed, so in reality if you use x alot inside a method and you assign random objects to it, you'd want to explicitly search for none.
That's just me, you're welcome to handle it however you want. I like to make my stuff strongly typed, and always check for none to avoid exceptions.
I'll keep it in mind! Thanks for the advice
@marble jackal you are the right man for the job for sure. how can I make a list with all my light that is turned on but exclude from this list some lights that have certain names (I want to exclude some groups of lights that I've made) because at the end i want to count all the lights that are turned on (but only the lights not the groups too)
No need to tag me, other people here can help you as well
And there is a pinned post which explains how to get a list of lights which are on and are not a group
Hello fellow coder... I have a "I dont see it problem" here... damned. I need to add the matching "default=0" to the following line: value_template: 'Noch {{ ((as_timestamp(states("sensor.octoprint_estimated_finish_time",0)) | int /60/60) - (as_timestamp(now()) | int /60/60)) | round(0)}} Stunden'
your parenthesis are wrong for states("...")
you have the ,0 inside the wrong parenthesis
the 0 should be for the as_timestamp(
as_timestamp(arg1, default)
arg1 is your states()
WAAAAAAH
yes!
Thank you!
So, this is they ...? 'Noch {{ ((as_timestamp(states("sensor.octoprint_estimated_finish_time"),0) | int /60/60) - (as_timestamp(now(),0) | int /60/60)) | round(0)}} Stunden'
sure, seems a bit verbose but it should work
cool
you could always just do this
Noch {{ ((as_timestamp(states("sensor.octoprint_estimated_finish_time"), 0) - as_timestamp(now())) / 3600) | round(0) }}
I'm trying to figure out how to make an heavy rain alert using an hourly forecast. I'm trying to pull if there will be more than 10 precipitation between two hours the current day and what datetime it will start.
that array is the stock info from the weather integration. As you can see, according to the data, every day starts at 22:00. What happens is, when I set the weather card in Lovelace, the day won't start until 22:00, so in lovelace until 22:00, Tuesday's forecast shows up as Wedensday's forecast. At 22:00 it does what it's supposed to but at 00:00 it's crapped again, Wednesday's forecast shows up as Thrusday's forecast. I want to create a weather template correcting that error
No, every day starts at midnight in your local timezone
Which is 22:00 UTC time
nope
I'm telling you the problem is that. I have already built the new array and it's working as expected, but I built it using Node Red
I want to know how to achieve the same using YAML
And I'm telling you the timestamps are in UTC. As your were using pastebin.pl, I assume your are in Poland, which is GMT +2
So 22:00 + 2 hours is midnight
You mean I should set a +2 instead of replacing the 22:00?
This is what I got so far. Checking for two hours precipitation at the time might be to hard. Not sure how I can pull the precipitation from the same hour as what have been selected here. https://www.toptal.com/developers/hastebin/
No, I am telling you that these timestamps in the array are at midnight in your local time
just use utc to check the time instead of your local time, that's what he's saying
+00:00 at the end means that the timestamp is in UTC
I do know however doing what I did has worked. Why?
even though that might be midnight in myu local time
for some reason when I set the card
the card doesn't interpret it as it should..
time is hard when you dont understand it
^^
you have to convert time depending on that timezone it's in for comparisions
Oh this again... time zone's trolled me bad yesterday
the integration is Spanish and I'm from Spain
oh I got it now
UTC is UNIVERSAL TIME COORDINATE
I see I see
so what time is it where you live?
15:04
it's 9:04 here
is it the same time?
Yes, it's the same time. However we are in different timezones.
UTC is agnostic of what timezone you're in
it's the same for everyone
in the world
Where UTC is 15:00
GMT +2 is 17:00
yeah I gort it
that's exactly it
then it's supposedly right, at 22:00 it's midnight here as TheFes suggested
in python, whenever you see +00:00 at the end of your timestamp, it's UTC
why isn't the card doing a good job then?
what card
weather card
is this the basic weather card or what?
basic
is your timezone set in HA?
ok, so what's wrong on the weather card then?
also keep in mind that your browser will come into play
forecast info from today
- condition: rainy
precipitation_probability: 100
temperature: 20
templow: 12
datetime: '2022-06-03T22:00:00+00:00'
wind_speed: 10
wind_bearing: 315```
lovelace card sets this values as tomorrow's forecast
at 22:00 local time, it does shows this values as today's forecast
well that is tomorrow
that is today sir
no it's not
06-03
and converted into local time, its 6-4
oh my
😉
xD
lol
Your not alone m8, had that kind of a problem yesterday as well
thanks for your time petro and TheFes, I appreciate
np
How can I get more than datetime to follow along in the result here? I don't get a hang on them loops at all. I want to output the datetime and precipitation not just the modified datetime https://www.toptal.com/developers/hastebin/moxahuxaga.kotlin
Can I somehow get the object number to use to pull all the information from whatever is in the same object as my | first
Hi, I dont really know the right syntax:
data:
entitiy_id: >
{% set entities = states.input_boolean |selectattr('object_id', 'search',
'is_lovelace_allgemein')|selectattr('state', 'eq',
'on')|map(attribute='entity_id')|remove input_boolean.this_explicit_entity_id|list %}
{{entities}}
so I have 2 problems:
- This whole template doesnt run with "service: input_boolean.turn_off"
- how do I remove 1 exactly entry in that template list
{% set date = utcnow().date() %}
...
{%- if i.precipitation <= 10 and date == (i.datetime | as_datetime).date() %}
is anyone able to tell me why this is showing as "true"
{{ as_timestamp(state_attr('calendar.kls_sync','start_time')) | timestamp_custom('%A %B %-d, %Y')
!=
as_timestamp(now()) | timestamp_custom('%B %-d, %Y') }}
Even though:
calendar.kls_sync = June 6, 2022
now = June 3, 2022
basically I just want to show it as true if start_time is today
because your formats are different
they'll never be the same
so that will always be true
{{ states.input_boolean | selectattr('object_id', 'search', 'is_lovelace_allgemein') | selectattr('state','eq','on') | rejectattr('entity_id', 'eq', 'input_boolean.this_explicit_entity_id') | map(attribute='entity_id') | list }}
thank you
use the same format
'%A %B %-d, %Y' format is not the same as '%B %-d, %Y'
{{ as_timestamp(state_attr('calendar.kls_sync','start_time'))
| timestamp_custom('%D')
!=
as_timestamp(now())
| timestamp_custom('%D') }}
Same format now but still getting True
because %D isn't valid
I also tried
{{ as_timestamp(state_attr('calendar.kls_sync','start_time'))
| timestamp_custom('%d/%m/%y')
!=
as_timestamp(now())
| timestamp_custom('%d/%m/%y') }}
ok, and what does each one say?
I'm guessing you didn't read the conversation that occured directly before this one and you're start time is in UTC
06/06/22
03/06/22
np
Trying another path: https://www.toptal.com/developers/hastebin/zesaxezitu.lua
Looks like this now: https://www.toptal.com/developers/hastebin/efuyeyojox.yaml
trying to get the | first here only get's me the condition of every object. [0] renders errors. How can I move from here? 😄
what are you trying to do, get the next time it rains?
If it today will rain more than 10mm, when does it start and how much will it rain
Ideally I would like it to check if there will be more than 10mm rain over two hour periods but that seems much harder
{% set forecast = state_attr('weather.dark_sky', 'forecast') %}
{% set midnight = today_at().astimezone(utcnow().tzinfo) %}
{% set tomorrow = midnight + timedelta(days=1) %}
{% set next_rain = forecast | selectattr('datetime', '>', midnight.isoformat()) | selectattr('datetime', '<', tomorrow.isoformat()) | rejectattr('precipitation', 'eq', none) | selectattr('precipitation', '>', 10) | list | first | default(none) %}
{% if next_rain is not none %}
{{ next_rain.datetime }}: {{ next_rain.precipitation }}
{% endif %}
@tidal heart
Wow!
I need to try an understand the flow here
Thank you for taking the time to help!
Hey friends: I'm looking to output the instigator of a state change in an automation... who did it. Am I RTFMing correctly?
https://www.home-assistant.io/docs/automation/templating/#available-this-data suggests that this gives me access to context of the trigger...
https://data.home-assistant.io/docs/context/
suggests that i need to use user_id ...
so put the two together and i need to output {{ this.user_id }} in my template to output the instigator?
part 2: if that's indeed just a user-id... there a way to translate that to a name?
You need context.user_id and that is indeed only an id
i guess i gotta figure out how to translate to a name now.
thank you! oh man.
figures that it's not even a hass article.... leave it to ludeeus
oh man that works great. thank you TheFes 🙂
Notify Discord of Door/Window Open/Closed has been Disabled by Michael
Is there a filter to sum up the states of a given entities? like:
{{ states.number
| rejectattr("state","in",["unavailable","unknown"])
| sum(attribute="state") }}
( this fails because state = string and expects int )
Or should I do that with a for loop?
Use map(attribute='state')|map('float')|sum
yeah, literally called sum 🤣
you sir didn't read the wholesome post 😛
heck, what did I miss? Passing templates to notify service is deprecated and will be removed in 2021.12. Automations and scripts handle templates automatically
is it complaining about things like: service: notify.system data: message: > {% set message = state_attr('persistent_notification.httplogin','message') %} {{now().timestamp()|timestamp_custom('%d %b: %X')}}: {{message}} Track offending ip on http://www.ip-tracker.org/locator/ip-lookup.php?ip={{message.split('from ')[1]}} title: > {% set title = state_attr('persistent_notification.httplogin','title') %} Ha Rpi4:{{title}} ?
Maybe if you call it via
-> services
It's saying that the service itself doesn't render templates
I'm still using them, no error here. Must be specific to whatever nofity.system is sending to
The data: block of a service call handles it for the service
I mean, all my notifications are using templates.... but they are in the scripts and automations, so I just dont get the message here
At Rob: yeah, so my example above would be correct according to that wouldnt it?
-> Services doesn't render templates, so it passes them straight to the service. Then the service itself either just sees the text or actually renders them
it might have been this text message selector: intercom_message: name: Intercom message options: - Komen jullie allemaal aan tafel, het eten is klaar! - Wie laat George even uit, hij heeft er echt zin in. - Alles staat klaar voor de volgende aflevering van 2 voor 12 - > {{states('input_text.message')}}
I may have fluked that into an error by pressing the Send button before the template was actually displayed
let me test once again
hmm, cant make it happen again, though interesting errors are logged when sending an empty message via the input_text
also, its really odd,because those messages are all used in tts.cloud_say services, and not in a notify service.... so it must have been something else I figure
making this really an integration issue I now notice... sorry for the wrong #
hi everyone. A simple one - how do I output current date with timezone?
{{ now().date() ~ ' ' ~ now().tzinfo }}
How would I add is_state_attr to this?
Result from this is 67, how would I say is_state_attr 67 for example.
"{{ state_attr('sensor.left_dockpro', 'control').set_temperature_f }}"
Try:
{{ is_state_attr('sensor.left_dockpro', 'control.set_temperature_f','67') }}
Worked, thank you.
Is there any way to check the last_changed from an entity_id in a variable?
Like this:
{{ states. ~ var ~ .last_changed }}
var contains an entity_id but it doesn't work ( expected name or number )
{{ states[ var ].last_changed }}
Yes! Thank you!
I was so far, only I had an extra '.'
{{ states.[ var ].last_changed }}
Hi guys!
Is there a way to define the order of execution of templated attributes assigned to one entity?
just updated to 2022.06 and getting this now in the startup log:
TemplateError('ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ 'True' if states('sensor.washer_current') | float > 0.041 else 'False' }}' but no default was specified') while processing template 'Template("{{ 'True' if states('sensor.washer_current') | float > 0.041 else 'False' }}")' for attribute '_state' in entity 'binary_sensor.washer_running'
guessing it's related to the breaking change for templates. I've read it but don't understand the issue. can someone help? Here's the template: {{ 'True' if states('sensor.washer_current') | float > 0.041 else 'False' }}
{{ states('weather.home') == 'sunny' }}
or
{{ states('weather.wetter_von_accuweather') == 'sunny' }}
I am using two weather services for my arena, because sometimes only one states "sunny", while the other says "cloudy".
How can I logically connect those two in a template, so that the entire template is "true" if only one of the two is "true"?
Hello
{%- for state in states.light -%}
how is it possible to remove the Browser Mod lights?
how can I get the integration from "state" ?
i got it:
{{ true if states('weather.home') == 'sunny' or states('weather.wetter_von_accuweather') == 'sunny' }}
🙂
Your sensor.washer_current was not ready when the template was rendered, and therefore the float filter got an invalid input.
You can resolve that by providing a default for the float filter float(default=0) or simplyfloat(0) or by providing an availability template in your template sensor config like {{ states('sensor.washer_current') | is_number }} ensuring the value template will only be rendered when the source sensor is providing a valid result
{{ 'sunny' in [ states('weather.home'), states('weather.wetter_von_accuweather') ] }} or {{ is_state('weather.home', 'sunny') or is_state('weather.wetter_von_accuweather', 'sunny') }} would work
Or what you already had without the true if part. That is not needed if you are already providing statements resulting in true or false
{{ states('weather.home') == 'sunny' or states('weather.wetter_von_accuweather') == 'sunny' }}
ahhh, that makes sense, thank you. figured it was something simple
hello all, I have a question for template-experts 😉
I have this:
- platform: mqtt
name: Helium
state_topic: "helium/86acb131-b25d-48b1-920c-e920e67c1997/rx"
value_template: '{{ value_json["decoded"]["payload"]}}'
The data I get is this:
{'BatV': 3.001, 'Ext_sensor': 'Temperature Sensor', 'Hum_SHT': '43.1', 'TempC_DS': '327.67', 'TempC_SHT': '25.44'}
I need the 3 sensors inside HomeAssistant: BatV, Hum_SHT' and TempC_SHT, how can I do that?
Hi all, can anyone tell me how I can display the state of a switch without the ability to turn it on or off? I have an automation that controls an HRV fan, I'd like to display whether the fan is running without the user being able to turn it on or off.
A template binary_sensor
thanks, i'll look into that!
very basic example from the docs: https://www.home-assistant.io/integrations/template/#change-the-icon-when-a-state-changes
worked perfectly!
With an input select, is it possible to get it to turn a switch on based on the state of the input select without building an automation? i have an input_select with three options: on, off and auto. if the input_select is on, i'd like to turn a switch on. if the input_select is off, i'd like to turn the switch off. if the input_select is auto, i'd like to control the switch from automation.
Hi all!
Is there a filter which can calculate any kind of checksum on a string? Goal would be to store the output in another attribute.
can i do a for each in an automation like, for each entity whos id contains trip, do x?
the documentation examples only cover pre-defined lists of entities
if (
(state.entity_id.startswith("sensor.trip_") if 'yesterday' not in state.entity_id and "Device Time" in state.attributes)
) -%}
{%- if loop.first -%}{% elif loop.last -%} {% else -%} {% endif -%}
{{state.entity_id}} {% if state.name.startswith('trip_1')%} {%else%} {%endif%}
{% endfor%}```
i wanna use this in a for each in an automation
This repeat form accepts a list of items to iterate over. The list of items can be a pre-defined list, or a list created by a template.
do i just put a template in there?
like i just go
{%-for state in states
if (
(state.entity_id.startswith("sensor.trip_") if 'yesterday' not in state.entity_id and "Device Time" in state.attributes)
) -%}
{%- if loop.first -%}{% elif loop.last -%} {% else -%} {% endif -%}
{{state.entity_id}} {% if state.name.startswith('trip_1')%} {%else%} {%endif%}
{% endfor%}```
figiured it out i think, not sure if it works, but its valid lol
my list is outputting as a string, not a list..
how do i convert the result, which is a string, into a list...
the result is a string
sensor.trip_2```
i cant slice because it's a foreach
and even adding {{', ' if not loop.last}} doesnt work
I don't understand the logic there, but you need to use a namespace and add each item to a list
like:
{%- if loop.first -%}{% elif loop.last -%} {% else -%} {% endif -%}
🤷
ive never used namespace before 😅
ok
im sure thats simple, but i dont understand it lol
tbh i copied the code from a random post on the forum
excellent
lol
im looking into namespace and im not really understanding how to use it to return a list...any examples would be super helpful, i learn best when i see someone else do things
Why are you adding all these empty if statements? Lijkt Rob also pointed out above
Furthermore it looks like you also don't need to use a loop here
to this p oint i copied the code from the forums...
i've reduced the useless garbage
{%for state in states if state.entity_id.startswith('sensor.trip_') if 'yesterday' not in state.entity_id and "Device Time" in state.attributes%}
{{state.entity_id}}
{%endfor%}```
but i dont understand how to do this really at all, moreso without a loop
Does this work?
{{ states | selectattr('entity_id', 'match', '^sensor.trip_') | rejectattr('entity_id', 'search', 'yesterday') | selectattr('attributes.Device Time', 'defined') | map(attribute='entity_id') | list }}
except that it adds entities with 'device time' that dont contain 'trip' in the entity_id
I've added that now
yeah that works. thanks. now ill try to understand whats new to me here so i can do it my own next time
appreciate the patience, most of this is new to me, just learning as i go along..
@orchid oxide
states get all state objects
selectattr('entity_id', 'match', '^sensor.trip_') select only those objects for which the entity id matches the regex for begins with sensor.trip_
rejectattr('entity_id', 'search', 'yesterday') reject those objects for which the entity id contains the word yesterday
selectattr('attributes.Device Time', 'defined') selects those objects which have the attribute Device Time defined
map(attribute='entity_id') take the entity id out of the selected state objects
list create a list from these entity ids
oh wow, thanks for the in depth explaination. really appreciate it
im a little on clear on the proper syntax for a template in 'for each' in an automation ive tried a number of things, but its coming back with none rather than the list
for_each: >-
{{ states | selectattr ('entity_id', 'match', '^sensor.trip_') | rejectattr('entity_id',
'search', 'yesterday') | selectattr('attributes.Device Time', 'defined') |
map(attribute='entity_id') | list }}
sequence:```
i tried - {{ states... too, comes back none
If that template works in
> templates, it should work in the for_each as well
ill try to pull it up in a persistant notification, maybe im just calling it imporperly
.share your whole script/automation
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
i figured it out. i was using 'repeat.item' instead of repeat.item
so it works now, ty for the help
👍🏼
Can anybody tell me whether there is a filter available to create a checksum like MD5 on a string? I found a filter called hash, but this does not seem to be part of HA.
does not exist
Hi everyone. Can someone please suggest a way to display the largest water use times for a day? I have a sensor that increments for each liter use. I use it to increment the utility sensors for hour, day etc. But I want to know not the largest use hour (that I have already) but also when the largest use started, ended and how much water was used
With an input_select, is it possible to get it to turn a switch on based on the state of the input select without building an automation? I have an input_select with three options: on, off and auto. If the input_select is on, i'd like to turn a switch on. If the input_select is off, I'd like to turn the switch off. If the input_select is auto, I'd like to control the switch from automation. Maybe the best solution would be a dummy template switch that gets it's state from the input_select and then has an action to control the physical switch?
Hey i hope someone can help me, have been trying for a while but something about my syntax seems to be off
I am trying to access a url inside a still_image_url section but i need the info from a diffrent sensor
still_image_url: http://xxx.xxx.xxx.xxx/server/files/gcodes/.thumbs/{{ states((‘sensor.3d_printer_current_print’)) }}-400x300.pngthe sensor i am using for this looks like this:
friendly_name: "Current Print"
value_template: ‘{{ states.sensor.3d_printer_current_print.attributes[“print_stats”][“filename”][:-6]}}’```
the :-6 should remove the last six charakter since they are not needed
probably is something silly but i cant seem to figure it out
You have some fancy quotes there..
You can create a template select. An input_select won't do anything out of itself without an automation
Oh, that sounds interesting. I didn't know there was such a thing.
Is there an example anywhere? I'm having a hard time googling it, since the term "select" is fairly generic.
Something like:
template:
- select:
- name: Some name
state: "{{ option }}"
options:
- petunia
- whale
select_option:
- if: "{{ option == 'petunia' }}"
then:
- do something
else:
- do something else
But then using the right indentation 😅
Oh great, that looks really useful. Most of the examples in the template page seem to be sensors, this one would be good to add.
Okay so i got further, i am getting the correct value into my sensor, but my url ends up being
http://xxx.xxx.xxx.xxx/server/files/gcodes/.thumbs/shelly + door hinge-400×300.pngbut when i type that into the browser i gethttp://xxx.xxx.xxx.xxx/server/files/gcodes/.thumbs/shelly%20+%20door%20hinge-400%C3%97300.pngBut what i want is http://xxx.xxx.xxx.xxx/server/files/gcodes/.thumbs/shelly%20+%20door%20hinge-400x300.png
i assume %20 is spacebar, can i somehow turn all spaces into %20 in a template?
| replace(' ','%20')
thanks....it would have worked without...the probem was the "400×300.png"
...you see the x? its not a regular x 🤣
but thank you for the help, will still replace the spaces
well thanks to whoever wrote this damn blogpost from where i copied this...
So I've tried to create the template, but I'm getting an error when I restart Home Assistant.
template:
- select:
- name: "HRV Mode"
state: "{{ option }}"
options:
- On
- Off
- Auto
select_option:
- if: "{{ option == 'On' }}"
then:
- service: switch.turn_on
entity_id: switch.shelly1_3c6105e37612
Invalid config for [template]: template value should be a string for dictionary value @ data['select'][0]['options']. Got [True, False, 'Auto']. (See /config/configuration.yaml, line 75).
you should always check your config files with the developer options yaml checker instead of restarting or atleast i would highly recommend that
I did, that part passes but when I restart I get that error in the log.
oh really? interessting then i have said nothing 😄
So I guess the syntax is right
Hmm, guess you should use options: {{ [ 'yes', 'no', 'maybe' ] }}
Okay I'll try that
And you know you don't need to reboot right? You can reload template entities in
> YAML
Even when they're in configuration.yaml? I thought any time entries were changed in configuration.yaml, you had to restart.
Where they are doesn't matter. Everything starts from configuration.yaml
Oh amazing, I didn't know that.
This seems to work well now, but I notice when I reload the template entities it starts in an unknown state. Is there a way for it to remember it's previous state?
- select:
- name: "HRV Mode"
state: "{{ option }}"
options: "{{ [ 'On', 'Off', 'Auto' ] }}"
select_option:
- if: "{{ option == 'On' }}"
then:
- service: switch.turn_on
entity_id: switch.shelly1_3c6105e37612
- if: "{{ option == 'Off' }}"
then:
- service: switch.turn_off
entity_id: switch.shelly1_3c6105e37612
optimistic: true maybe?
I tried that, but it doesn't look like that works. When I reloaded it immediately went to unknown. This error shows in the log, which I guess is because the variable isn't defined when the template is loaded. Template variable warning: 'option' is undefined when rendering '{{ option }}'
@wicked rune posted a code wall, it is moved here --> https://hastebin.com/tozazutepu
with all of these efforts preventing the unkown's in the template configs, what would be the advantage over a single input_select and a small automation? they are very robust, and are restored, so never turn unknown..
I guess I was trying to avoid the automation to prevent a condition where the switch gets stuck in an on state. Maybe I'm overthinking it. I do have other automations that run if the selector is set to Auto.
The template select seems to work well except for the initial state.
yeah, maybe. though my question was an honest one. I always try to follow the new HA core options, and havent come to terms yet with many of these new template integrations... 😉 so was hoping for a direct and positive answer tbh. Without all the hassle of setting defaults and preventing the consequences of the broader templating quirks, these formats seem very attractive. Getting to silence the logs, makes them more complicated, and then the 'advantage' over the ancient techniques become less obvious
in this particular one what does the variable {{option}} template? is that a single option in the possible options?, yes it is: https://www.home-assistant.io/integrations/template/#select_option. until it isnt selected yet, and we need to set a default? just asking
yeah, you can see the template i'm trying here: https://hastebin.com/tozazutepu. and yes, i'd like the default to be the previous state.
or rather, i'd like the start up value to be the previous state.
so you dont have an action for the option Auto yet? not sure if that would work, but you could test that ofc. Still, if you have anther automations for the option Auto, why not add:{% if trigger.to_state.state in ['on','off'] %} service.turn_{{trigger.to_state.state}}
I meant to have an Auto in the template select that would turn the switch off initially. Then any automations I built would only run under the condition that Auto is selected.
right, I see. well, as I have made abundantly clear above, I am no expert on the template select at all, so not the best person to advise you there. Seems a bit contrived tbh. if possible, keep things simple. as possible.
I also never used it myself, but if the state doesn't restore I would also suggest to go for the input_select and an automation
My concern with the automations is that they can terminate before being executed completely. In my automation, I want to run the HRV so many minutes per hour if the selector is Auto. So in my automation, at the top of the hour I turn the HRV on, then wait X minutes, then turn it off. So what happens if I reload the automations before they're complete (during the wait period?). The HRV doesn't end up getting turned off. So I thought with the template select, I'd be able to have the switch automatically turned off when the template loads.
Use a time pattern trigger with the state of the input_select as a condition
You mean separate the automations between on and off?
Or add triggers on automation reload and home assistant start
What you also could do instead of an input_select and automation is an input_select and a template select
Set the input_select to the same state as the template select in the actions, and use the state of the input_select for the state of the template select
Hmmm, yes I can see how that could work. Ideally I'd only have the automations trigger if the input_select is Auto. I'm having enough trouble with Auto already because I have a few different conditions there. I want to run the HRV a certain number of minutes per hour, but then if the bathroom humidity gets above a certain value I also want it to run until the humidity drops. So even those two conditions can create conflicts.
Ah, no that won't work. The input_select changes the state of the template select, but the template select actions don't run.
I guess I just need to figure out how to do this with input_select and automations, and maybe have an automation that turns the switch off when it loads initially.
@manic tartan posted a code wall, it is moved here --> https://hastebin.com/kodawocuve
Can you help with the above problem. Don't get it (template newbie). What am I doing wrong :-)?
It works perfectly as a template, but not in the automation.
[Rule #6](#rules message): Please do not post codewalls (text longer than 15 lines) - use sites such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
Please take the time now to review all of the rules and references in #rules.
Thanks, sure 'else' fixed. Why it works in HA GUI in template section? I understand the message (MaxLengthExceeded), but what characters counts?
It seems event_type string is too long, but why?
Because the template editor doesn't care how long it is
I'm just reading the error message
It's quite clear
Many things have a maximum length
OK, so how to evaluate this within 64 characters :-)? The limit is for jinja2 syntax (300 characters), not the result itself?
The string that results is too long
Oh, the real problem is that it just sees the whole template as the event string and isn't evaluating it at all
You would have to use an if/then or choose: to conditionally fire a different event
Thanks. Will try this, but it so long syntax works like a charm for service:, and why not for events: ...
I don't think custom events are used very often, and it takes somebody that cares
action:
- service: >
{% if is_state('input_boolean.livingroom_music_mode', 'off') %}
input_boolean.turn_on
{% else %}
input_boolean.turn_off
{% endif %}
data:
entity_id: input_boolean.livingroom_music_mode
this works fine, and it is 175 character long
Because it supports templates
ok, so event don't? OK
You're welcome to file a feature request on the forum
Thanks for help.
I was wondering whether there is a jinja filter available which can provide a simple check sum on a string like sha or md5 . I saw a filter called hash, but this was outside the HA scope.
I thought that there are people on the channel which can offer a solution rather than a simple "no". And as one one person responded and my problem still exists .... I hope you understand.
So now two people told me 'no' and as you mentioned my problem will continue to exist.... What a solution!
you asked how to implement your solution, you never mentioned what your problem is. IE: why you want a checksum on a string in the firstplace.
Take a step back, and detail your actual problem. What is the actual problem at the higher level that has resulted in your checksum approach. The solution to your problem might be a lot simpler than needing a checksum if the problem is solved a slightly different approach than the one you are currently on.
I want to have a short representation of a string ( made of a sorted list containing device names) which might be longer than an ordinary state can hold to compare it later on.
templates are probably not the best for that, in node-red you could implement a basic substitution approach in a function node for something like that
Hello, I'm struggling to get the right mix of value_templates to get the first 'power' value from my json (in this case 530.44). Is it possible to retrieve this without an iterator?
The value of states.sensor.shelly_em.state is ...
[{'power': 530.44, 'reactive': -406.79, 'voltage': 245.44, 'is_valid': True, 'total': 20020.7, 'total_returned': 0}, {'power': 0, 'reactive': 0, 'voltage': 245.44, 'is_valid': True, 'total': 0, 'total_returned': 0}]
like {{ value_json[0].power }}?
I've been trying to work it in the Developer Templates page using something like {{ states.sensor.shelly_em[0].power }} but it claims "object has no element 0"
your answer shortcuts where I'm heading anyway.. so thanks! I'll give that a go.
ahh i see
Is that really the state?
it was someone down a few layers, but not quite far enough
value_template: "{{ value_json.data.device_status.emeters[0].power }}" is what i'm needing
thank you. you got me where i needed to be
this template works but is there a way to condense it:
https://www.toptal.com/developers/hastebin/cofaqavosi.java
its very long at the moment
{% set ns = namespace(count = 0) %}
{% set start = states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_appointments_event_`) | map(attribute='attributes.start') | list %}
{% for item in start %}
{% if as_datetime(item).date() == now().date() %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count > 0 and is_state_attr('sensor.ical_work_appointments_event_0','summary',"Busy") }}
I would have never been able to figure that out! Thank you - I’ll give it a go
Is there a way I can set a input.number to the number of how many events come back as true? I want to do a text to speech to say “you have x events today”
I’m guessing setting the count as input.number
Well, you don't need to set an input number, the ns.count is what you're looking for if I understand you correctly
It would be for a seperate automation:
I currently have that for another calendar but want to change it for the one listed first
is it possible to use this.entity_id inside a config template card which has been nested in an auto entities card
or some other way to pull the attribute state of this.entity_id
Using this.entity_id within the card, same way you would to call any other state, doesn't work. Soon as I put this.entity_id in a template the whole thing just renders blank
I changed the name of the entity but I am getting an error - Do you see anything wrong after I've changed the entity?:
{% set ns = namespace(count = 0) %}
{% set start = states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_appointments_event_`) | map(attribute='attributes.start') | list %}
{% for item in start %}
{% if as_datetime(item).date() == now().date() %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count > 0 and is_state_attr('sensor.ical_work_appointments_event_0','summary',"Busy") }}
Developer tools > templates says:
TemplateSyntaxError: expected token ',', got 'attributes'
you have a funky quote:
'^sensor.ical_work_appointments_event_)`
ah If I change that I get:
TypeError: float() argument must be a string or a number, not 'datetime.datetime'
javascript question. how do i get hh:mm from a timestamp? using the config taemplate card ive got
${(Date.parse(states[this._config.entity].attributes['Device Time']))} which returns a timestamp 1654457964877. I'd like to extract hh:mm from this
All your config template card questions should be in #frontend-archived . This channel is for Jinja
ok, thanks
I changed from as_datetime to the below and it's showing up as FALSE when its meant to be true:
{% set ns = namespace(count = 0) %}
{% set start = states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_calendar_event_') | map(attribute='attributes.start') | list %}
{% for item in start %}
{% if as_timestamp(state_attr('sensor.ical_work_calendar_event_0','start')) == as_timestamp(now()) | timestamp_custom('%d/%m/%y') %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count > 0 and is_state_attr('sensor.ical_work_calendar_event_0','summary',"Busy") }}
This works though but its long:
https://www.toptal.com/developers/hastebin/ugizekubix.java
This doesn't work because you only applied the custom timestamp on now() and not on the start time of the calendar events
hi everyone. I am using template sensor and want to set the state value to be a value of another state's attribute, which is integer. But I also want to set the attribute of that new sensor to be a text explaining what that attribute is.
This is what I have and it works fine, but sets the verbal state. I want state value to remain the integer
verbose_vacuum_state: friendly_name: "Verbose Vacuum State" value_template: > {% set index = state_attr('vacuum.viomi_v18_04fb_robot_cleaner', 'vacuum.status')|int %} {{ ('Sleep', 'Idle', 'Paused', 'Go Charging', 'Charging', 'Sweeping', 'Sweeping and Mopping', 'Mopping')[index] }}
Is that json_attributes_template?
reading the docs. Looks like I am using old config 🙂
so its "state" and "attributes"?
You are, but this works in legacy template sensor format as well
thank you!
verbose_vacuum_state:
friendly_name: "Verbose Vacuum State"
value_template: >
{{ state_attr('vacuum.viomi_v18_04fb_robot_cleaner', 'vacuum.status') }}
attribute_templates:
verbose_state: >
{% set index = state_attr('vacuum.viomi_v18_04fb_robot_cleaner', 'vacuum.status')|int %}
{{ ('Sleep', 'Idle', 'Paused', 'Go Charging', 'Charging', 'Sweeping', 'Sweeping and Mopping', 'Mopping')[index] }}
did not like that attributes part
Invalid config for [sensor.template]: [attributes] is an invalid option for [sensor.template]. Check: sensor.template->sensors->verbose_vacuum_state->attributes. (See ?, line ?).
this still gives me "false"
{% set ns = namespace(count = 0) %}
{% set start = states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_calendarevent') | map(attribute='attributes.start') | list %}
{% for item in start %}
{% if as_timestamp(state_attr('sensor.ical_work_calendar_event_0','start')) | timestamp_custom('%d/%m/%y') == as_timestamp(now()) | timestamp_custom('%d/%m/%y') %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count > 0 and is_state_attr('sensor.ical_work_calendar_event_0','summary',"Busy") }}
rewrote it under the template > sensor instead of sensor > template
Sorry, it's attribute_templates in the legacy format
Looks like the is an underscore missing in the set start part, between calendar and event
looks like that did the trick!
will {{ ns.count > 0 and is_state_attr('sensor.ical_work_calendar_event_0','summary',"Busy") }} also check for event_1 and event_2 etc?
because that needs to count up as well
It doesn't in your original template
Oh wait, it does in the last version you posted
Try this:
{% set ns = namespace(count = 0) %}
{% for item in states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_calendar_event') %}
{% if item.attributes.start.date() == now().date() and item.attributes.summary == 'Busy' %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count > 0 }}
TemplateSyntaxError: unexpected ')'
Fixed.
TypeError: float() argument must be a string or a number, not 'datetime.datetime'
Stop tagging me please, I'm in the channel
Sorry about that
And please check if the updated version works
It says "true" so looks like its working 🙂
👍🏼
is there a way of using that code to give me a number of how many events are today that have "busy"? for TTS?
Why not simply create a template binary sensor using the template you have now instead setting an input boolean in an automation?
You can set the number of events in an attribute as well, so you can use that in your tts
oh thats a good idea - I didnt think of that!
thank you 🙂 let me work on that
number_of_appointments:
friendly_name: Number of Appointments
availability_template: "{{ not is_state('calendar.ical_work_calendar', 'unavailable') }}"
value_template: >-
{% set ns = namespace(count = 0) %}
{% for item in states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_calendar_event') %}
{% if item.attributes.start.date() == now().date() and item.attributes.summary == 'Busy' %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count }}
Legacy template format, but looks fine
works a treat - legacy how?
ahh I see
Thanks for the support!
Here the long story which I did not publish so far as I had no feedback on lenghty explanations of any of my problems. In the "fully blown up solution" I want to have an automation which checks every x minutes whether a certain type of device is unavailable and sends out notifications. The code for finding the device is up and working. I do want to have the automation to send notifications only if there are still devices unavailable. I do not want a message telling me every x minutes that devices foo and bar are not available. So somehow I need a mechanism which tells me whether a change occurred.
Looking at the States tab of DevTools I noticed that last_changed might hold the solution to my problem, but can it be that the solution is to use a state trigger in the automation mentioning just the entity id like in https://www.home-assistant.io/docs/automation/trigger/#state-trigger ???
Edit: So far it works! I should mention that the sensor the automation is screening is a template sensor which is setup with a time trigger.
I would suggest to create a template binary sensor which is on if there are such devices unavailable and use that binary sensor for the alert integration
make a template sensor that's main state outputs a string representation unavailable sensors. Then, as an attribute, list them out as entity id's. Make your trigger based on the state change of the template sensor and use the attribute in the notification.
Unfortunately, there is no checksum func in templates, that would make a hash of your template sensors that's unique. Would be really great for this situation.
You could just have the main state as a counter that updates when the count changes
I found out that there is a simple way to use a state trigger in the automation while having the sensor with an attribute updated by a time trigger. A bit of googling was necessary after I had the right words to search for. A pity that there is no "cookbook" around!
There are plenty of cookbooks https://www.home-assistant.io/examples/
I did not have this URL on my list. Thanks!
FYI, it's the first link when you google search home assistant cookbook
You are right. The idea of having a solution made me focus on the solution and nothing else. I also thought that I would find some menu entry of the HA web site like in ESPHome where I spent more time reading the docs. The bare text "Examples" didn't trigger anything in me as a lot of examples within the HA docs are simple and often too simple. Maybe time for a change at the HA website to call the the Examples rather Cookbook???
There used to be a cookbook section
But that looks a lot like the examples page 😎
It was renamed examples
because more people looked for examples opposed to cookbook
I hope it stays "cookbook" on the ESPHome site as I as a none native speaker of English relate "Cookbook" with solutions who are beyond simple examples which are found in the docs where a function is explained.
Everytime at startup i get some errors because the sensor and/or attribute is not yet available. Is there anything i can do/add to avoid this? I get the following errors: Error while processing template, TemplateError('UndefinedError: 'None' has no attribute 'split'') while processing template and Template variable error: 'None' has no attribute 'split' when rendering. Thx in advance for any help. https://paste.ubuntu.com/p/QdkxDHBtpH/
Yes, add availability templates to your template sensors
Or defaults to your templates
{% set variable1 = state_attr('sensor.backup_state', 'size_in_google_drive') or "0 GB" %}
{% if variable1.split(' ')[1] == 'MB' %}
{{(variable1.split(' ')[0] | float(default=0)/1024 )| round(1)}}
{% else %}
{{(variable1.split(' ')[0])}}
{% endif %}
or you could probably remove the redundancy
{% set value, units = (state_attr('sensor.backup_state', 'size_in_google_drive') or "0 GB").split(' ') %}
{% if units == 'MB' %}
{{ (value | float / 1024) | round(1) }}
{% else %}
{{ value }}
{% endif %}
you shouldn't ever use states.xxx.xxx unless you know what you're doing. state_attr was built so you don't need all these checks
Thats the problem sometimes, not know what i'm doing. 🙂
Greatly appreciate your help Petro!
Just try it out for a few days, some safety was removed and you might get an error with the float. Otherwise you can do an availability template like thefes said
Will sure do, for know the errors seems gone after restart!
Thanks Petro and TheFes for the support!
TIL that you can use or in combination with set
you can use or anywhere
and and
or with set is VERY goofy
it depends on what the first and second value is
Ah, I was just about to ask what foofy means
If the first is falsy it takes the second?
No, it's more complicated than that
{% set items = [ 0, 1, '', 'x', False, True, {}, {'x':1}, [], [0], none ] %}
{%- for i in items %}
{{ i }}
{%- for j in items %}
{{ i }} or {{ j }}: {{ i or j }}
{%- endfor %}
{%- endfor %}
run that
specifically look at the interactions with none
has a mind of it's own in some cases
I'll have a look at that when I'm not on mobile
Is there a way to do < or > or == to in a statement like this
{% if is_state_attr('sensor.blue_bin', 'days', <12) %}
Ah thank you!
is there a template to apply inverted values to a sensor?
like for instance if there were a sensor going from 1 to 100 would it be possible to have it show 100 when the value was 1
and vice-versa, as well as for every subsequent value? basically inverting the curve
hey friends, i ran a across this yaml that helps track heating and cooling times over the day
part is a template, other part is sensor. should i be trying to convert the sensor in to a template sensor?
https://www.codepile.net/pile/dbPWj8Zx
{{ 100 - states('sensor.your_sensor') | float }}
That will onder invert 0 to 100 though
with |float
on a template with state: state: > {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='state') |map('float')|sum)|round(2,none)}} my sustem seems to sometimes choke, and throw 0 for this sensor, which messes with the energy panel, because on the next state change it jumps back, with a then huge total increase...
what would be the best way to set availability on this, not being total 0? To prevent it from being included in the energy panel calculations, Do I repeat the template
like: {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='state') |map('float')|sum)|round(2,none) != 0}} ? Dont think it can be done with the this variable?
cause that wouldn have been elegant: availability: > {{this.state != 0}} ... although it seems to work, no error, and a value is calculated..
I would not check on the sum being 0 because of one of them is unavailable you will also see a decrease.
I would suggest this:
{{ expand('group.switches_total_device_energy') | selectattr('state','is_number') | list | count == expand('group.switches_total_device_energy') | list | count }}
my check on 0 is for the total value (energy) not for the individual items. if only 1 would be 0, the total would still never be 0. so the full check != 0 would be the (system error) check to do?
I wouldn't expect that to ever be true, since states are strings
But if some of them are unavailable that could cause a drop in the total value and will mess up your energy panel
Rob: thats a good point... I'd need {{this.state|int(default=0) != 0}} in that case
yes, thats why I reject those in the state template?
That's not what I mean. Let's assume there are 5 values there, all being 5. That's a total of 25
coming to think of that: I could aslo do {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable','0.0']) |map(attribute='state') |map('float')|sum)|round(2,none)}} maybe 😉 simply reject the total sensors with a 0 value
If one of them becomes unavailable your total is 20, which is lower than 25
The energy dashboard will then assume it has been reset, so it was 0 at one point which was missed by HA, and it's now 20 again
So for the energy dashboard the value will be 45 (25 + 20)
That's why you don't want it to drop below a previous reading
And you want to make sure all source sensors are available
you're right. we need all sensors there, and they all should be total_increasing... so, if it glitches on a single sensor, the rejectattr will catch that. And if the complete sensor is messed up, the availability template catches it? the count being equal, ensures that if a single sensor would turn 0, and be rejected because of that, the availability is false
Why would a sensor be messed up in the first place?
Seems to me like that's your real problem
yeah, well they sometimes simply are. eg when the MQTT source has a hiccup
If there is a single sensor glitching, it will be excluded from your state template, causing the state template to decrease, but still it will still be above 0
and you're right that should be guarded, but unfortunately we can not add an availabiltiy template to the mqtt sensors
but then you're template would catch that wouldn't it?
Yes, because it checks if all members of the group are providing a number for their state
exactly, so thats why I said I will combine them. Or, that was what I meant there #templates-archived message
thanks !
number check could also be: {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable','0.0']) |selectattr('state','is_number') |map(attribute='state') |map('float')|sum)|round(2,none)}} probably... let's test
Hey, could anyone help me with this? ```
Error rendering icon template for sensor.times_of_the_day: TypeError: '<' not supported between instances of 'str' and 'datetime.datetime'
@vagrant monolith posted a code wall, it is moved here --> https://hastebin.com/pobimetite
You're comparing the string returned by the attribute.today with a date time.
What are you trying to do? There's likely a better way than updating every single minute.
Your image doesn't load, but I guess you're answering the wrong question
What is your goal, not "how are you trying to solve your problem", but what do you want/need to do with this data?
You can parse a string to a time, but I really suspect you've taken a wrong turn there, this seems very inefficient
i have a sensor that outputs a currency amount, so i have it rounding to the 2 decimals, but when the number is x.x0 (ex 2.20), it will trim the zero. can i stop this?
I am trying to create a template that sum 4 sensors, 4 ACs kwh from emporia sensors, where do I add a template?
With a template sensor
I have a draft, I just don't know where I add the code... which file does it go, or is it on the interface?
Sensor, binary sensor, button, number and select template entities are defined in your YAML configuration files, directly under the template: key and cannot be configured via the UI.
configuration.yaml
thanks
I was able to add to the configuration.yaml. I see the entity created, but unavailable. Would anybody be able to check my syntax please? https://www.codepile.net/pile/JvOy39zj
hey all, struggling with an automation script for setting a input_datetime. I'm trying to just add an hour to now for my lovelace to pick up and show once the automation runs for when it will turn off. I have this now but I see errors in the logs
The last 3 have sensor.sensor
service: input_datetime.set_datetime
target:
entity_id: input_datetime.attic_fan_turn_off_time
data:
datetime: '{{ now() + timedelta( hours=1 ) }}'
What...errors...
sensor.attic_fan_turn_off_timestamp rendered invalid timestamp: 2022-05-16T02:15:43+00:00Z
i may be mixing up what's wrong too 😄
yep so this is the problem, what i linked above is what gets generated
- platform: template
sensors:
attic_fan_turn_off_timestamp:
device_class: timestamp
value_template: "{{ as_timestamp(states('input_datetime.attic_fan_turn_off_time')) | timestamp_utc | replace(' ', 'T') }}Z"
Please use a code share site
The docs tell you exactly what format you need to use
how do we delete a entity that I created by a template that I no longer want to use?
If you already removed it from your config file and it's showing as restored in the UI,
-> Devices & Services -> Entities
I removed from the config file but in the UI is showing as "readonly" status and I can't select it
Then reload templates or restart HA
did both but the entity is still there
@marble jackal sorry to have to bring this up again but I think I figured out what was wrong with the template sensor we talked about
binary_sensor.heat:
{{ is_state('binary_sensor.outside_heat', 'on') and now() - timedelta(hours=72) > as_local(as_datetime(states('input_datetime.heat'))) }}
the first sensor must also be on in order for the stamp to trigger, so if it changes now, it won't matter that it hasn't been 72 hours yet - it will stamp, so the second binary sensor will switch off
(yes I changed the time value to test further)
Yes, indeed the first sensor has to be on, otherwise this template will also render true if it the first sensor has been off for 72 hours
If it just changed, it just changed, so it will not be on for 72 hours
so then it defeats the purpose
isn't there a way to write the template for the attribute of the weather sensor?
so as to avoid all of this binary sensor and timestamp nonsense
this is the binary_sensor.outside_heat :
{{ state_attr('weather.home','temperature') > 17 }}
isn't there a way to make this template for 72h ?
Sorry, you lost me here
You want to know if it has been cold or warm for a period of 72 hours
but you also want that to be true when it just changed
those two are in confict
just for reference, this wont do ofc. it will reject the non numbers, but wont check if the total of sensors is correct... was late yesterday
it changes when it just changed atm because the both conditions must be true for the sensor to turn on, but only one for it to stamp so that the sensor turns off
nevermind this, I don't wanna waste your time anymore with it, just think if there's a way to write the template above so that the outside heat sensor turns on/off after the attribute has been above 17 for 72h (without resorting to additional binary sensors and helpers)
Sorry, I'm really trying to understand the issue here. If it just changed from 15 to 17 degrees, binary_sensor.outside_heat will turn on, but binary_sensor.heat will remain off because it has not been 72 hours since the last change
yes
binary_sensor.heat will turn on after 72 hours, unless binary_sensor.outside_heat turned to off in that period again
even for a second
Guess that's why I didn't understand it 🙂
but 'heat' will turn off if outside heat turned to on even if it hasn't been 72h
sensor2: sensor1 AND sensor1for72h
the only reason we went with the timestamp was to avoid the restart issue that HA only calculated the value of the first binary sensor (outsideheat) since the last restart. Now I'm asking that considering the attribute of the weather sensor is stored in the integration, and not lost along with restart, isn't it more wise to just use that ?
You are losing me again here, if it hasn't been 72h, binary_sensor.heat should be off right.
ok, put it another way: it changed twice in the last 6hours. I can show you the logs
from on to off then to on again
btw Fes, we can not reverse that is_number can we?, so we could so something like:```
{% set items = 'group.switches_total_device_power' %}
{{expand(items)|selectattr('state','not','is_number')|list|length == 0}}
what is it? Is that binary_sensor.heat or binary_sensor.outside_heat?
You can use rejectattr
sure, but then we still can not count those?
that would make it easer yes
comp: ```
{% set items = 'group.switches_total_device_power' %}
{% set x = ['unavailable','unknown'] %}
{{expand(items)|selectattr('state','in',x)|list|length == 0}}
That would work with rejectattr
sorry, I didn't mention. Yes I was referring to the Heat one, and not Outside Heat
['5', '7', '9' ] | reject('is_number') | list | count == 0 will be true
That's basically the same as you are doing here
Okay, and outside_heat was not changing state on the same moments?
yes it was
it is! how smart.... it rejects all numbers and then we should have count 0. So if not 0, there was an incorrect state. nice.
heat turned on - 1:47:14 PM - 2 days ago
heat turned off - 12:36:52 AM - 10 hours ago
Yes, that is indeed a lot smarter than the comparison I proposed 🙂
So If outside_heat changed from on to off it changed from eg 17 to 15
(it seems it didn't turn on off in the past six hours, I just got the notification that it turned off twice and didn't fully read it. But it's weird that it recorded when it turned from off to off)
and if it then changes back to on the count starts from there
yeah IDK, it's way more trouble than its' worth
{% set items = 'group.switches_total_device_power' %}
{{expand(items)|rejectattr('state','is_number')|list|length == 0}}
``` for full disclosure 😉
For me it still seems it's acting exactly like it should
which offers 2 scenarios: either only count the entities from given set, and ignore the non-numbers, and use: - unique_id: switches_total_device_power name: Switches total device power state: > {{(expand('group.switches_total_device_power') |rejectattr('state','in',['unknown','unavailable']) |selectattr('state','is_number') |map(attribute='state') |map('float')|sum)|round(2,none)}} unit_of_measurement: W icon: mdi:label-multiple device_class: power state_class: measurement only. Or use it with the availability template, change to state_class: total_increasing, and be able to use it in the energy dashboard
okay. I'll keep it like this and I'll make a separate sensor for the template I asked about, but can you please tell me how to write it? It will then make it less confusing for me and if you are right (which you probably are and I just didn't get the entire thing clearly) the two sensors will match up
with the added caveat that it will keep me from coming back to ask about it ^^
this one: {{ state_attr('weather.home','temperature') > 17 }}
how to add 'for 72h' to it?
You can not do that in a reliable way in just one template, as the last_changed attribute will change every time you reboot
So that's why I proposed to use the method you are doing now
Maybe using an SQL sensor you could, by getting the data of the last 72 hours out of your database, and check if they are all above 17
would I need a server for that?
but I don't know what that SQL query would be, I don't have a lot of experience with SQL
No, you don't need a server, you are using the HA database
ok, please pardon my frustration then, I just happened to receive that notification twice in six hours and just presumed it wasn't functioning well. Didn't bother checking the actual values of the state change, as I didn't even factor it changing from OFF to OFF
You could add that to the notification
or add a condition that it should only send the notification if the state from is different from the state to
okay
I didn't even know that you were talking about the notification here..