2022-05-19 14:54:12 ERROR (MainThread) [homeassistant.config] Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got '{{ trigger.to_state.state | as_datetime - trigger.from_state.state | as_datetime).seconds }}'. (See /config/configuration.yaml, line 133).
#templates-archived
1 messages · Page 161 of 1
And, it will not work anymore after a reboot or template sensor reload prior to 2022.5, as trigger based templates do not restore states
there's a missing ( here some where
2022-05-19 14:56:14 ERROR (MainThread) [homeassistant.components.template.sensor] Error rendering state template for sensor.difference: UndefinedError: 'None' has no attribute 'state'
i guess i need it to run once first?
na, you need to guard against 'uknown' or 'unavailable'
sensor.to_on doesn't exist
unfortunately that was added in 2022.4
hahah
ok.. what do i do? i can't believe this is not doable in pre-2022 h-a
i have mqtt
so i can publish to a node
you could probably do it with the SQL sensor, but you'd have to write the search
sheesh 🙂
again: how? 🙂
i don't have time for this.. i should be pumping water in the basement 😄
SELECT * FROM (SELECT * FROM states WHERE entity_id = 'sensor.temperature_in' ORDER BY state_id DESC LIMIT 2) two_entity ORDER BY state_id ASC LIMIT 1;
Which version are you running?
yeah, i found the same
ok, i have the query
how do i combine that with a trigger and then a sensor?
what's the output
select * from (select * from states where entity_id = "switch.pumpe_teknisk_rom" and state = "on" order by state_id desc limit 2) two_entity order by state_id asc limit 1;
yeah, it's in the output of the query
> select * from (select * from states where entity_id = "switch.pumpe_teknisk_rom" and state = "on" order by state_id desc limit 2) two_entity order by state_id asc limit 1;
+-----------+--------+--------------------------+-------+---------------------------------------+-----------+----------------------------+----------------------------+----------------------------+------------+-----------------+--------------+
| state_id | domain | entity_id | state | attributes | event_id | last_changed | last_updated | created | context_id | context_user_id | old_state_id |
+-----------+--------+--------------------------+-------+---------------------------------------+-----------+----------------------------+----------------------------+----------------------------+------------+-----------------+--------------+
| 146908225 | switch | switch.pumpe_teknisk_rom | on | {"friendly_name":"Pumpe teknisk rom"} | 148139786 | 2022-05-19 12:51:48.497793 | 2022-05-19 12:51:48.497793 | 2022-05-19 12:51:48.497793 | NULL | NULL | 146906213 |
+-----------+--------+--------------------------+-------+---------------------------------------+-----------+----------------------------+----------------------------+----------------------------+------------+-----------------+--------------+
ough.. maybe not paste this here
you'd need to split the response on the | and extract the correct time, not sure which oen that is. They all the same
then you need to convert that to a datetime
doesn't the sql platform separate the fields into attributes?
it's not handled as a string, no?
they both are a pain
but i really can't understand why this is so hard to accomplish?
the MQTT route you have to make an MQTT configuration in yaml
well, i already have mqtt configured
then you'd make an automation that publishes a timestamp to the topic that the MQTT configuration is pointing to
you'd probably need 2 mqtt sensors
1 for the last on
1 for the duration
- alias: Update pump sensors
trigger:
- platform: state
entity_id: xyz.abc
to: 'on'
action:
# UPDATE DURATION
- service: mqtt.publish
data:
topic: ....
payload: "{{ (now() - states('sensor.last_update')).seconds }}"
# UPDATE LAST UPDATE TOPIC
- service: mqtt.publish
data:
topic: ....
payload: "{{ now() }}"
so you can just make 2 state topics that holds a datetime and one that holds a float
then configure them as sensors
sensor:
- platform: mqtt
state_topic: ...
value_template: "{{ value }}"
etc
i'm sure I'm missing something there, but you get the idea
the value template for the last_updated should be "{{ value | as_datetime | as_local }}"
Out of curiosity what are you running HA on?
Docker container
I'll try that :) thanks!
nuh I mean what infra like esxi, KVM or bare metal or ...
Bare metal
i can't reload just sensors individually? i have to restart h-a for that?
Depends on the sensor, template sensors can be reloaded from developer tools > yaml
Oh no, prior 2022.5 it is configuration > server tools
Mqtt sensor
Could be, but if it is the first one you add, you always need a reboot. After that, just check if it shows up in server tools
just discovered I can not use the get() in this mapper? state-badge { {% set speed = states(config.entity)|int(default=0) %} {% set mapper = {0:'green',1:'darkgreen',3:'orange',33:'orangered',66:'maroon'} %} color: {{ mapper[speed] if speed in mapper else 'red'}}; hoped to do color: {{ mapper.get(speed,'red')}}; but that does not kick in
(this is in a card_mod, so strictly speaking frontend, but its about the jinja template....)
or:```
animation:
{% if speed != 0 %}
{% set mapper = {1:'4',3:'3',33:'2',66:'1'} %}
{% set rotation = mapper.get(speed,'0.3') %}
{{'rotation ' + rotation +'s linear infinite'}}
{% else %} null
{% endif %}
what's the erorr when you use mapper.get
fyi, thats a dictionary
I regret that first post I made with mapper all those years ago because people keep calling it that
that's just the variable name I decided to use that day 😐
yeah sorry, didnt mean to use the reserved word.... just the variable name, Ill change that. really odd though, because now that I test it. by changing the state in dev tools state, it does work.... huh
yeah, maybe a typo?
anyways, I find it best to name the dictionary what it contains
like that would be colors, then colors.get(speed, 'red') makes way more sense when reading it
could be a typo, and it wasnt working for over months... might have been winter so the fan didnt have to spin on the Rpi4 😉 and yes, ive changed them to color and fan
Hi. Isn't this the correct way to create a variable containing a list? variable_name: "{{ [var_1, var_2, var_3] }}"
@mighty ledge i'm getting Error rendering data template: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'
@mighty ledge even though i have the value_template "{{ value | as_datetime | as_local }}" for the value from mqtt
When you subtract them in the template sensor, you need to convert the state to a datetime
It’s in my example
Ah I forgot it
Just add the | as_datetime after the states()
You may need to add as_local too
like so: '{{ (now() - states("sensor.pump_last_update") | as_datetime | as_local).seconds }}' ?
yeah, that seems like it stuck
let's try restarting h-a and see
Update pump sensors: Error executing script. Error for call_service at pos 1: Error rendering data template: AttributeError: 'NoneType' object has no attribute 'tzinfo'
argh
catch-22 here
after restart that is empty
and then it won't update
no way mqtt can poll for the last value?
You have to retain the value on startup
It’s part of the sensor configuration
For mqtt
hey jedis,
{% set x = ['a','b','c'] %}
{% set y = ['b','c','d'] %}
is it possible to print out the intersection of two lists?
so the output would be
['b','c']
{{ x | select('in', y) | list }}
thanks alot
hi guys Im tryin to set a template to use a timer entity to reflect how much time is left until the next Android alarm
anyone know how to?
the purpose is to have a flipper card show up on my device at the time when I set the alarm, counting down to when the alarm is set to go off
any timer in the UI won't count down like that
hence Tinkerer's love of whales and petunias
What's not to love?
but isn't there a way to have a template tell the automation to subtract 'now' from the set time of the alarm and give the value one time to the timer entity? Or maybe there's a different way to achieve this?
My purpose is to set an alarm via voice while cooking and then to have HA automate the process of pulling up the remaining time til the alarm is set. Like: 'next alarm time' (minus) 'now' (equals) 'timer value'
Alexa does that anyway. (assume google does too). Why HA?
Yes, you can do that, but I think petro means that a timer won't show as a flipper card on your dashboard
oh, ok, I already set the flipper card to reflect the timer but need the template for converting the value formats and to run the operation
how do you mean it does that? I set the alarm via voice, the sensor reflects a timestamp to when the alarm is supposed to go off. It doesn't provide a timer countdown to that date (re:google)
service: timer.start
data:
duration: "{{ ((as_datetime(states('sensor.your_phone_next_alarm')) - now()) | string).split('.')[0] }}"
target:
entity_id: timer.your_timer
cheers!
OK. Alexa does. If not a screen based device, you can ask it how long to go.
oh okay, yes google does it too, but the thing is to do all this on the fly. I have an android in each room and it's neat to be cooking and just say an alarm then have the countdown pull up on every screen to know how long left. Not have to ask it every time
I created a template sensor for my energy dash in watts that either returns + value or 0 and it works but the sensor i created the changes it to kWh using the template sensor as the source is still showing - value, how can this be?
.share your sensor configuration
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.
Command '.share' was invoked by: TheFes
template:
- sensor:
- name: "Solar return to Grid Power (Dashboard)"
unit_of_measurement: "W"
state: >-
{% if states('sensor.meter_min') | float < 0 %}
{{ 1 - states('sensor.meter_min') | float }}
{% else -%} 0 {% endif %}
state_class: measurement
device_class: power
- name: "Solar return to Grid Power (Dashboard)"
That equation makes no sense, but it shoud work fine assuming that your spaces are correct
basically, whenever it's negative you're output will be the absolute value of the minimum + 1
which just doesn't make sense
just use absolute value and don't add the one
The kWh conversion comes out neg - platform: integration
source: sensor.solar_return_to_grid_power_dashboard # <-- the actual name of your sensor
name: return_to_grid_kwh
unit_prefix: k
unit_time: h
round: 2
the integration integration works off your history
so if there's still negatives in your history from before you made the template sensor postive, they will still be in the KW calculation
clear your history or wait for those values to purge
Figured but shouldnt it update when the underlying sensor does?
it does, but the integration sensor uses a history to determine the area under the curve
so, if your last 2 values in the database are above zero, you should be good
if it continues to be negatvie, then you're most likely using the wrong entity_id for the integration sensor
you can verify the entity_id through the dev tools -> states page
you can also verify that your template sensor is positive there as well. It should be based on your equation
I also used helper to create a kWh and definitely chise correct sensor
as long as you restarted or reloaded after adding your template sensor too
Right, I understand you think that, but the integration integration is simple math. It's only going to calc negative if your source sensor is negative
9 times out of 10 in these situations, you're doing something wrong.
so it's good to check everything
that still doesn't verify anything I've said
that's just showing what you've said from the beginning
Then i dont understand
what's your source for the integration sensor?
that's the source.
hint: It's your template
Are you talking about the entity_id or sensor im usung for the the template source?
you have 3 sensors in your setup
sensor.meter_min, sensor.solar_return_to_grid_power_dashboard, and sensor.excess_solar_kwh
what are the values and history of all 3
Meter has neg in history
that shouldn't translate to your template sensor though
what does your template sensor look like?
unless your template sensor has data from when you were playing around and had negatives
Yes so i just have to wait which is fine just makes me weary of future data being timely or stuck so to speak. A newly created excess_solar gives me unknown
All sensors in home assistant only calculate when new data comes through
Ok and are you saying just delete this whole line {{ 1 - states('sensor.meter_min') | float }}
I'm just saying that it's an odd equation
{{ states('sensor.meter_min') | float | abs }}
Ty much. So replace above line with yours?
replace {{ 1 - states('sensor.meter_min') | float }} with {{ states('sensor.meter_min') | float | abs }}
Your version was giving a wrong result as well, as it would end up one kWh too high, if you would have replaced 1 with 0 at leas the result would have been correct 🙂
But anyway, the version using | abs is easier 🙂
Question regarding the Statistics sensor. When did it stop surviving reboot? My state_characteristic: change is reset everytime I restart the server.
That would be something for #integrations-archived
Hello everybody!
I want to create an automation that is launched on update of the desired temperature of my HVAC, wait until the temp sensor reach that temperature and power off the HVAC
The only blocking point is the waiting template in the automation. Is it possible to use is_state?
Like : wait_template: '{{ is_state(' 'climate.mqtthvac.temperature' ', ' '<= climate.mqtthvac.current_temperature' ') }}'
"{{ state_attr('climate.mqtthvac', 'temperature') <= state_attr('climate.mqtthvac', 'current_temperature') }}"
Nice, thanks!
Hello, I am trying to historize the sun attributes. Can someone please help what's wrong with this syntax?
- platform: template
sensors:
sunrise:
sun_elevation:
value_template: '{% if states.sun.sun %}{{ ((states.sun.sun.attributes.elevation)) | float }}{% endif %}'
sun_azimuth:
value_template: '{% if states.sun.sun %}{{ ((states.sun.sun.attributes.azimuth)) | float }}{% endif %}'
Not sure why you are wrapping this in an if it might have something to do which the fact that you are using a way to get the attribute which is advised against
spacing is wrong
And sunrise: is empty
or ya, it's emtpy
well I of course, didn't come up with it, it's from here: https://community.home-assistant.io/t/how-to-use-entity-attribute-in-history-graph/209847
oh yeah, indeed it is empty
and these attributes are already a float, but if they were not, casting them to float use useless, as a the state of the sensor will be a string anyway
ok so this example is crap then
Well, in the time since that forum post a lot has changed, but the post after your example already gave the right way to get the attribute
but there is also a new template format now
you mean with sth like this?
- platform: template
sensors:
sunrise:
state_attr(‘sun.sun’, ‘sunrise’)
sun_elevation:
state_attr(‘sun.sun’, ‘elevation’)
sun_azimuth:
state_attr(‘sun.sun’, ‘azimuth’)
Why do you want to create these sensors anyway? To put them in a history chart?
yes, I want to have historic values
so I can determine values to control my shutters
You probably don't need separate sensors for that
You can use state triggers with an attribute for example
ok, I read that here: https://community.home-assistant.io/t/history-of-sensor-attributes/393209
trigger:
- platform: numeric_state
entitiy_id: sun.sun
attribute: elevation
above: 4
This will trigger when the elevation is above 4, no need for a separate sensor
That would have been required in 2015, at the time of that topic 🙂
ok, I get that, but I am not sure yet what azimuth and elevation triggers I need
so I wanted to historize those values and take a look at them over the day to get the trigger values I need best
since I have windows in different angles I can't do it all "live"
Okay, well you can of course create these sensors if you want
fair point. I trying a lot to learn through reading that's already there and I feel I am asking too many questions already, but it's really hard
- platform: template
sensors:
sunrise:
value_template: "{{ state_attr('sun.sun', 'sunrise') }}"
sun_elevation:
value_template: "{{ state_attr('sun.sun', 'elevation') }}"
sun_azimuth:
value_template: "{{ state_attr('sun.sun', 'azimuth') }}"
thank you very much, this is indeed much easier
trying it now
works great, thanks so much
does it make sense to post that to the forums post above or is it adviced against that due to the age of the post?
I wouldn't post corrections/suggestions on very old posts if there hasn't been a recent post, no reason to bump it to the top again
ok, thanks
I have one more, finding these in my log, everything seems to be working with the template covers, not sure where "none" comes from though:
[homeassistant.helpers.template] Template variable error: 'None' has no attribute 'sumstate' when rendering '{{ state_attr('sensor.blinds_endpoint', 'item13').sumstate.value.split(';')[1] |float }}'
2022-05-20 16:11:30 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('UndefinedError: 'None' has no attribute 'sumstate'') while processing template 'Template("{{ state_attr('sensor.blinds_endpoint', 'item13').sumstate.value.split(';')[1] |float }}")' for attribute '_attr_value' in entity 'number.rollo_ronja_gross'
is it just trying some things after restart when the values are not loaded?
Yes
great, thank you
hi guys, i am in need of rather urgent help as i came back with my wife from holiday and our house is hot as hell - the automation I tried to use apparently did not work. The thing is I don't know where to put the following "- platform: template
sensors:
sun_azimuth: ......." because of the - platform template I thought maybe here is the right place to ask - forgive me if i was wrong
@surreal kite Isn't this very similar as the question a couple of posts before
This
for an automation, is there a way to modify / create a variable in a condition template area, before I use a service to notify? IE: the binary_sensor is toggling, i want to pull the state and change it from on/off to say open/closed. Is there a way to do an if block in the notify section?
I don't want to change the sensor's data/payload directly, as that would ruin some of my other integrations (as they look for on/off)
nm - got it! message: > {% if trigger.to_state.state == 'on' %}
Hi 🙂 maybe i just need some little start help... i have two problems ... 1.) i've created a template for my energy dashboard (energy -> power grid) .. but sometimes the values jumps to 0 and then back to the old value... what causes that the difference between 0 and the old valued gets added to the total amount:
- name: "Netzeinspeisung (Gesamt)" unit_of_measurement: "Wh" state: "{{ states('sensor.photovoltaik_klein_gesamtnetzeinspeisung')|float(0) }}" device_class: energy state_class: total_increasing attributes: last_reset: "2022-05-17T17:35:00+01:00" last_reset_value: "2022-05-17T17:35:00+01:00" availability: > {% if is_state("sensor.photovoltaik_klein_gesamtnetzeinspeisung", "unknown") or is_state("sensor.photovoltaik_klein_gesamtnetzeinspeisung", 0) %} false {% else %} true {%- endif %}
Well, last reset is not needed for total_increasing, so remove that
@supple forge posted a code wall, it is moved here --> https://hastebin.com/hutetadiyo
States are always strings, and you're comparing with an integer. And you can remove the while true/false bit
But why is your source sensor becoming 0, is that a template sensor as well?
Well, the default is set to zero
sensor.photovoltaik_klein_gesamtnetzeinspeisung come from modbus
(and the other energy-values too)
- name: "PV Tagesertrag"
unit_of_measurement: "Wh"
state: "{{ states('sensor.photovoltaik_gross_tagesertrag') | float + states('sensor.photovoltaik_klein_tagesertrag') | float }}"
device_class: energy
state_class: total_increasing
availability: >
{{ states("sensor.photovoltaik_klein_tagesertrag") | is_number and states("sensor.photovoltaik_klein_tagesertrag") | is_number }}
🤔 .. i've added the (0) due to the warning in the log-file
But you don't actually want zero?
You don't need that if you know for sure the input is actually a number
on PV-Tagesertrag it can be 0 ... (at night, theres no sun)
You should use lifetime sensors for the energy dashboard
Right, but you don't rely on the default for that
Doesn't it still contain the value it gathered while the sun was up?
your're right... the source is also total_increasing
Okay, so both reset to 0 at midnight
no.. the source-sensors keep the values as they where .. but home-assistant reset's it (visually?), when it's added to the energy-dashboard ... but what about the data from the previews day .. the amout of yesterday gets displayed at 00:00 - 01:00 (so the day starts with 150 kWh)
Oh, do they are lifetime sensors
That would happen if your sensor shortly becomes 0 and then gets the right value again
as i understand, the difference between the two values gets added to the total .. today, two times the values dropped from ~5200 to 0 and up again... and now i have a grid-feed (for today) of over 10000 kWh (would be nice if i got paid for this 🤣 )
the reality is 67kWh
If a total_increasing sensor gets a lower state than the previous, a reset is assumed, so indeed, when it becomes 0 and then gets the correct value again, you'll get it doubled
So that is also why Rob stated that you might not want to default your floats to 0
You shouldn't need any default if you configure your availability template properly
ok.. i'll fix my templates and look, if it also fixes my day-start-problem 🙂 thank you all
I am having a hard time returning the current outside temp using a value template as the value templates only seem to be able to return strings.
This is the sample from my config, again only returning the temp as a string. https://www.codepile.net/pile/3EB0NPRA
How can I have this report as an int?
And sorry, I know this is most likely a very simple answer.
Are you sure it's a string? Put it in the template editor in developer tool and it will tell you the type
Welp, it was a mix of two mistakes on my end. It does return as a number. The error was on frontend with a typo on my behalf as mini-graph-card reported the output was a string, and given the value_template is encased in "", I figured that was the cause of returning a string.
Thanks 🙂
Hi, can u guys help me with 1 more thing? This is not working, i cant get the attribute game inside this sensor on my variable:
{% set steam_check = states.[sensor.steam_765611980387894].game %}
That's broken syntax
How can i fix this?
Kinda curious where you got that
That works perfectly, thank you
Well, all states are strings anyway, so it will be a string in the end
Hi Everyone, hope you're well.
Hoping someone can help me out with what is probably a fairly simple issue. I have spent hours on this trying multiple methods but I'm just not winning.
In a nutshell, all I am trying to accomplish is to create a binary sensor that returns true/on if the day is e.g Saturday and a defined input boolean named Saturday is on. This part I have gotten to work in a few different ways. Most noteably:
- binary_sensor:
- name: zone1dayofweek
state: >
{{(now().strftime("%a") == "Sat") and (states.input_boolean.zone1_saturday.state=="on")}}
- name: zone1dayofweek
The above is in my templates.yaml file.
The problem that I am trying to solve is: How can I expand this out to include all other days of the week?
Does the above template evaluate properly? Not sure what you mean by expanding this to include all other days of the week. Do you mean you have an input Boolean for each day of the week and want to check if the input Boolean matching the current day is on?
{{ now().isoweekday() == 6 }}
You could also create a sensor that displays the name of the current day.
What is your goal with these sensors?
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
Command '.xy' was invoked by: TheFes
100%, sorry this is all pretty new to me.
So to clarify, what I am trying to do is create a binary sensor that will return true if today's day as well as a specific input boolean are on/true
With reference to my above mentioned code, in my mind what I was looking to achieve is something like this:
- binary_sensor:
- name: zone1dayofweek
state: >
{{(now().strftime("%a") == "Sat") and (states.input_boolean.zone1_saturday.state=="on")}}
or
{{(now().strftime("%a") == "Sun") and (states.input_boolean.zone1_sunday.state=="on")}}
- name: zone1dayofweek
@rose scroll without the "or" section the template does evaluate properly. In the above example, adding the "or" is what I was trying to say about expanding this out.
you could use string concatenation with now()'s time to select the input_boolean
This is wrong {{ x and y }} or {{ a and b }}
It should be {{ (x and y) or (a and b) }}
- binary_sensor:
- name: zone1dayofweek
state: >
{{ (now().isoweekday() == 6 and is_state('input_boolean.zone1_saturday', 'on'))
or
(now().isoweekday() == 7 and is_state('input_boolean.zone1_sunday, 'on')) }}
@marble jackal you can get the word saturday from strftime
{{ is_state('input_boolean.zone1_' ~ now().strftime('%A')|lower, 'on') }}
Guess that is what @petro meant
yes
basically a 1 shot template forget it and set it
just need to name your input booleans by day
why write all the 'or's out when you and just have the template check the correct boolean right off the bat
So, I'm on my fathers mac, let me tell you. I don't like a 1 button mouse pad... I can't reply to people in discord. It doesn't accept my rmb clicks on the reply
Hehe
ffs, now it's showing up
Thanks guys! Let me play around with this!
@mighty ledge for the mac, if you tap with two fingers does that help at all?
thats does help, musch better than my ctrl click that i was trying
Thanks again @mighty ledge and @marble jackal Works perfectly
Recycling is this week
{% else %}
Recycling is not this week.
{% endif %} ```
I want that to be a little smarter and know if it is the weekday 2 or not. (Tuesday) based on the weekday sensor.
so how do I do a if else, elseif, endif?
maybe a helper like this? - binary_sensor: - name: recyclingdayisnow state: > {{(now().strftime("%a") == "Tue") and (states.input_boolean.recylingday.state=="on")}} or {{(now().strftime("%a") != "Tue") and (states.input_boolean.recyclingday.state=="off")}}
Look a few posts up
And use is_state('entity', 'state') instead of what you are using now
sensor.recyclingweek is the entity and A is the state {% if is_state('sensor.recyclingweek', 'A' ) %}
remove the if? is that what you are saying?
No, I meant in your second template
oh ok thanks
BTW, there's a nice Garbage Collection custom component that does a good job of tracking trash/recycling/whatever days: https://github.com/bruxy70/Garbage-Collection
hmm, why does this no longer work? ```
{% set group_list = states.light
|selectattr('attributes.is_hue_group','eq',true)|map(attribute='entity_id')|list %}
have been using this as a base template for a larger markdown template for a ling er time, and now shows nothing because of that error..?
ofc, thats whay this template should do the selection.... and it has done so
No
no? what do you mean?
well it has been working ever since I used that, see https://community.home-assistant.io/t/template-to-entity-sensor/392231/3
You first brought it up here: #templates-archived message
I also filed this: https://github.com/home-assistant/core/issues/71921
corrct! ``` {% set group_list = states.light
|selectattr('attributes.is_hue_group','defined')|map(attribute='entity_id')|list %}
thanks!
still seems a change from before, as https://github.com/home-assistant/core/issues/71921 mentions. But, it is 100% possible I missed it earlier, and link to that from the other discussed issues you copied.... my bad for that, sorry
your memory of my posts is better than mine 😉
It was logging a warning for a long period already, since 2022.5 it's actually an error making the template unable to render
I don't remember there being a warning. Is it related to the change to defaults?
Mm, there have been no warnings in the logs at all, homeassistant.log that is
What filter can i use to remove the first 5 characters of a string?
perfect, thanks
@floral shuttle Okay, I think I didn't interpret the answer of Frenck correct when I asked him about it in the Dutch Discord. As far as I understood from him he said it has been depreciated for a long time already, and now support has been removed
Ok, so this was on purpose then
I don't recall it being called out as a breaking change
Im not even sure what ‘it’ means when you’re talking about it… imho, there should have been some explanation why the selectattr suddenly would have stopped working, and we now need to use defined.
it is performing selections on non existent attributes
In hindsight it all seems very logical, but when transitioning from perfectly fine working templates it requires some extra info
I agree on that, but I don't write the release notes 😅
According to Frenck it was announced as a breaking change a long time ago, but he didn't specify when. And then the conversation got sideways
So that's all I know
Is it possible to put !secret pirateweather_api in place of the actual api key in this sensor?
sensor:
- platform: rest
resource_template: 'https://dev.pirateweather.net/forecast/<apikey>/{{states.person.<NAME>.attributes.latitude}},{{states.person.<NAME>.attributes.longitude}}'
json_attributes:
- currently
name: pirateweather_api
value_template: 'OK'
Not unless you put the whole resource in the secret
You can put the api key in a input_text
And you could even use the secret as initial value if you create it in YAML
so the secret would look like:
pirate_rest: 'https://dev.pirateweather.net/forecast/<apikey>/{{states.person.<NAME>.attributes.latitude}},{{states.person.<NAME>.attributes.longitude}}'
Yes
both are tempting options....
I dont see one being better than the other, unless i am missing something.
The all in one secret would be better. Having the input text would allow you to see it in entities in dev tools i would think.
Yup, just confirmed it.
If I want to get the value of a helper, is this the way? '{{ states("input_text.some_id") }}'
Yes. You can test in
-> Templates
I'd like to make a binary sensor template trigger from an event start to turn it on and a separate event for end to turn it off. Can you have two templates updating the same sensor?
You can have two triggers and a template based on the one that fired
Thanks, will give that a try. Is there also a notion of a condition in a template? i don't see it
I'd basically like to filter some of the events and ignore them with respect to changing the binary sensor state.
To be explicit, i'm using calendar triggers which have an event start & event end, then have a payload with the title, description, etc
You can return whatever you want in the state template, including the current state if you want
So if you don't like the trigger data, just return the current state
Or you can use an availability template, but that will cause it to be 'unavailable'
I do think that a condition that potentially leaves the state unchanged would be a most excellent addition
I'm trying to get a list of devices with a battery level under 80%, but this gives me everything below 80, but also 100.0: {% for state in states.sensor|selectattr('attributes.device_class', 'eq', 'battery')|selectattr('state', '<', '80.0') %}
You won't be able to do it with a filter because it requires a cast to float to do a proper comparison
oh, it's just doing a string comparison?
I would just get rid of the last bit and use a separate if statement that does the conversion and comparison
Yes
Tricky part is, I'm using it in a Markdown Card where a previous if statement checks a list count see whether it should display a header or not:
{% if states.sensor|selectattr('attributes.device_class', 'eq', 'battery')|selectattr('state', 'ne', '100.0')|selectattr('state', '<', '60')|list|count>0 %}
### Battery
{% endif %}
I piped it through two selectattr()s as kludge for now that seems to work
Hi, trying to get this script https://paste.debian.net/hidden/a1c670a7/ working, but it fails to match from the variable trace , which should be formatted as a list. Can it be written more efficiently, or what can I do to make it work? Thanks
Unless all your sensors have a device class, you also need to check if the device class is defined
frontend template, im getting the following error for the following like:
missed comma between flow collection entries (7:72)```
``` content: {{state_attr('person.jack5mikemotown', 'friendly_name')}}
dont see what the error is about, here
card is mushroom chip card
that was the first thing i tried, idk what i did wrong. works now, thanks
quick question.. Is it possible to search for a value in a input_text, lets say for the latest 1h?
I want to know if a input_text had a value equal to x for the latest 1h ...
I don't see how motion or precense ends up in trace. Do you pass that as a variable?
You could use an SQL sensor to get the states of the last hour out of your database.
morning all,
how to give these 2 templates a default value i can't get it to work
{{ state_attr('calendar.ajax_seizoen_2021_2022', 'message')}}
{{ as_timestamp(state_attr('calendar.ajax_seizoen_2021_2022', 'start_time')) | timestamp_custom('%d-%m-%Y') }}
{{ state_attr('calendar.ajax_seizoen_2021_2022', 'message') | default('Geen wedstrijd', true) }}
{{ as_timestamp(state_attr('calendar.ajax_seizoen_2021_2022', 'start_time')) | timestamp_custom('%d-%m-%Y', default='Geen wedstrijd') }}
the first one is working, but the second gives a error
ValueError: Template error: as_timestamp got invalid input 'None' when rendering template '{{ as_timestamp(state_attr('calendar.ajax_seizoen_2021_2022', 'start_time')) | timestamp_custom('%d-%m-%Y', default='Geen wedstrijd') }}' but no default was specified
Oh, forgot to paste that. Yes, it's a variable passed to the script, defined like this trace: "{{ [trigger_id, transition_time, calling_entity, this_entity_id] }}" in the calling script
Why not split it in 4 separate variables?
Makes it easier to refer to the one you need
That is another way of doing it, sure. My aim was to use the 'trace' as a collection of sorts of everything needed. this varies with what script generates it
meaning, it's content is not always the same. Would be a lot of variables to keep track of
got the second template working now
with this
{{ as_timestamp(state_attr('calendar.ajax_seizoen_2021_2022', 'start_time'),default='Geen Wedstrijd') | timestamp_custom('%d-%m-%Y',default='Geen Wedstrijd') }}
Hello Guys, i want to controll my heater with an calendar. I connected the calendar and already managed to rerieve the start and end time from it. I guess my only option is to create an binary_sensor Template wich turns ON when there is an entry on the calendar and turns off when there is none. And creating an automation on that sensor controling the heater. So far i got this together {% (as_timestamp(strptime(state_attr('calendar.kalender', 'data')[0].start, '%Y-%m-%d %H:%M:%S%z', 0)) - 3600) | timestamp_custom('%Y-%m-%d %H:%M:%S') %} which takes my start Time and sets it on hour before wich should be the time where the heater should start. How can i manage the Sensor turns on and keeps like this until the calendar entry? Is there maybe a simpler solution for this? Thank you
You were right. How would you recommend doing it instead of this?
you then asked me what my purpose for this was, and I said it's for having all the heating automations in my house to switch off once a certain outside temp is achieved anually. So far, below 11*C with an offset of 24 hours seemed to work but upon changing it to 36 I can't tell if it's working or not ^^
Use a binary sensor without offset, and set an input_datetime with the current datetime as soon as it turns on. Trigger your automations as soon as that input_datetime is 36 hours in the past
Maybe trigger on every state change though and check if the current state is on
That's great! The part I don't know is how to set the input datetime to 'now' -is that a template?
And what about when the datetime is 36h in the past, is that a template too?
Both can be done using templates
service: input_datetime.set_datetime
data:
datetime: "{{ now() }}"
target:
entity_id: input_datetime.petunia
thanks! I just realized this would mean I'd have to have an adtional binary sensor to determine when this is on or off
seeing as it would trigger upon state change of the initial binary sensor, lol
wouldn't it be easier to skip the entire binary sensor though? seeing as it's set to trigger on/off when the weather sensor from outside has is below 11degrees
in other words, isnt there a template to trigger an input helper to on/off when there has been 36h of below 11 degrees on the meteorologisk default integration?
No, you can just use the current binary sensor for that
that does make sense but it shows up as "unknown" if I set it with delay on
hmm maybe thats not the way. maybe the delay should be in the template?
{{ state_attr('weather.home','temperature') < 11 }}
There should be no delay for the binary sensor
You are handling the delay using the input_datetime
but if it triggers on state change, it would mean having another binary sensor to determine when this is on/off
No
Trigger on every state change to set the input datetime.
Use the input_datetime in your automations in combination with a state condition in the binary sensor
oh ok now i get it
And what about when the datetime was changed to 'now' 36h in the past, is that a template too?
Yes
{{ now() - timedelta(hours=36) > as_datetime(states('input_datetime.whale')) }}
thanks a lot dude!
You could even combine it with the check on state:
{{ is_state('binary_sensor.petunia', 'on') and now() - timedelta(hours=36) > as_datetime(states('input_datetime.whale')) }}
next lvl
I know how to use | round (1) function but I do not want to round I just want to drop anything after first decimal. What is the syntax for that? Thx
Is round(1, ‘floor’) correct?
Yes, that should do the trick
trying to do
data:
datetime: "{{ is_state('binary_sensor.outside_cold', 'on') and now() -
timedelta(hours=36) > as_datetime(states('input_datetime.cold')) }}"
target:
entity_id: input_datetime.cold```
but it won't let me
says invalid datetime specified, value false
please format any code properly
soz
and if I take out the first part -- is_state('binary_sensor.outside_cold', 'on') -- it says cant compare offset-naive and offset-aware values
oh so i need a boolean entity as a target
didnt do the trick
what are you doing now?
where do I add that? would that be instead of the "as datetime" at the end?
no
Im trying to devise a way to determine when the outside temperature has been below 11degrees
for 36h straight
and you're trying to set a datetime to that?
the fes said it would work best like that, Im just trying to make it work
I leave you in his capable hands, then 🙂
okay thanks for your help but just curious, where did you mean to add "as_local"
to fix this:
-- it says cant compare offset-naive and offset-aware values
I get that but I meant where in the template to add it
now() - timedelta(hours=36) > as_datetime(states('input_datetime.cold'))|as_local
Allright... Never tried that before....... This will be interesting...
What Rob said! 👆
but it doesn't work
What do you have now?
invalid datetime, false dictionary value
That's not what I meant, what is your current code
sorry
data:
datetime: "{{ now() -
timedelta(hours=36) > as_datetime(states('input_datetime.cold'))|as_local }}"
target:
entity_id: input_datetime.cold```
No, that's not right. In the input_datetime you simply need to set "{{ now() }}"
Correct
I liked yours the most because it also took into consideration the binary sensor
Where you compare the current time to your input_datetime to see if the last state change of your binary_sensor was over 36 hours ago
You can add it as a template condition
will try this one :
{{ is_state('binary_sensor.petunia', 'on') and now() - timedelta(hours=36) > as_datetime(states('input_datetime.whale')) }}
You need the | as_local
Or the similar function:
{{ is_state('binary_sensor.petunia', 'on') and now() - timedelta(hours=36) > as_local(as_datetime(states('input_datetime.whale'))) }}
ok so this is what I understood: please dont laugh 😄
I created a datetime named Now and set it to actualize itself every minute with the 'now' value
I then created a second automation and gave it the 36h trigger as well as the value template condition from above. BUT it doesn't work when I click test, saying it needs a string value and got none
https://pastebin.com/5U5Ey9Qm
I assume this was only for testing then? Because the trigger should be your binary sensor changing state
And the test button doesn't work for template conditions
The trigger to to set the input_datetime should be something like:
- platform: state
entity_id: binary_sensor.its_a_bit_chilly
ok but this means the trigger will make it check against itself
if it changes state now, it will check if it hasn't changed state again in the last 36h
No, it's a separate automation just to set this input_datetime
you mean apart from the two in my paste?
Okay, for my suggestion to work, you need:
- an binary_sensor which is
onwhen the temperature is below 11 degrees (egbinary_sensor.cold) - an input_datetime which can store both date and time ( eg
input_datetime.cold) - an automation to set the input_datetime to
now()on every state change of the binary_sensor - (optionally) a second binary_sensor which uses the value_template above to make it easier to use it in your other automations (eg
binary_sensor.cold_for_36_hours)
oh now it all makes sense
I did not see the 2nd automation before, but I don't know what you expect of that one
I had it backwards
didnt expect anything, was just showing what I did
ok so I;ll get to work
thank you for putting it plainly so my old brain can see
Additional suggestion, use this trigger instead of the one I proposed for the automation to set the input_datetime. It prevents it to set it after a reboot because the binary sensor is loaded
- platform: state
entity_id: binary_sensor.its_a_bit_chilly
to:
- "on"
- "off"
from:
- "on"
- "off"
ok I did the auto like you said (I hope)
https://pastebin.com/XLjMDP5h
also the additional binary sensor
but then I thought why not be able to also action it manually if36 is too much or not enough so I used an input boolean instead:
https://pastebin.com/Nj5F5J9t
Anyone have an idea of how I can get the info from the last instance if a sensor? I have tried this but it fails
{{ state_attr('sensor.calendar', 'data')[-1].start_day }}
yeah, that's not it 🙂
the easiest way to do it is to create a trigger-based template sensor whose state is trigger.from_state.state
there's no built-in way to do what you want
#automations-archived message now the question would be why my attempt was not correct while using the expand-map-list is (?)
nevermind it does not work either: homeassistant.exceptions.HomeAssistantError: Template rendered invalid service: cover.close_cover ['cover.finestra_sala', 'cover.finestra_cucina']
The template is fine, but you can't use templates in that field
you need to put it in target or data
service: cover.open_cover
target:
entity_id: "{{ expand('cover.finestra_sala') | map(attribute='entity_id') |list }}"
wouldn't it repeat entity_id twice?
one from map one statically before the template?
Huh, you lost me here, what do you mean with before the template
service: cover.open_cover
target:
entity_id: "{{ expand('cover.finestra_sala') | map(attribute='entity_id') |list }}"
^^^^^^^^^^
entity_id: is a key, which expects a (list of) entitie(s) as value
you provide that list using the template
i'm not totally sure how map works in this case, the doc says it's a filter but we're not supplying a KV struct to filter against
Just test it in developer tools > templates and see what the result is
I did not write the program language, I'm just providing you a way to get the list of entity_ids you need for your service call
You can use map to take out one specific attribute out of your expanded state object generator
yea i think i was lost on the expand
it seems it substitute the '' with an object
instead of interpretating it like a string
It's because you've put a group in, it expands the group members of that group
so when you say cover.something it becomes the cover itself, not a string
and then yes it can find the attribute with the map
without quotes jinja expects a variable, which you have to define first
now the real problem is that it outputs it as an array ["cover.one", "cover.two"] instead of what the service expects (i think) -cover.one\n-cover.two
{% set petunia = 'cover.finestra_sala' %}
{% set whale = 'entity_id' %}
{{ epand(petunia) | map(attribute=whale) | list }}
No, the service expects a list, and ["cover.one", "cover.two"] is a perfectly fine list
Try this in developer tools > services
#templates-archived message
YAML is a different way to write json
This:
target:
entity_id:
- cover.1
- cover.2
Is exactly the same as:
target:
entity_id: [ 'cover1', 'cover.2' ]
huh it works in services too?
yea the stack of different languages makes it confusing i think
target: { 'entity_id': [ 'cover1', 'cover.2' ] }
(had backticks instead of quotes)
And that also explains why you need to put quotes around you templates if you use a single line notation. Otherwise it things it's a very badly written dictionary
but it does not explain why my try with the for loop didn't
i would have expected it to output the list in yaml at runtime before the service was called
Because you didn't put it under target or data
You put it directly under entity_id in the service call where templates are not allowed
isn't jninja interpreted before the section is executed?
And your template resulted in a list of complete state objects, which is wrong anyway
or is the config passed as is and then interpreted at runtime after the yaml expansion?
setAllWindowsOpen:
action:
service: cover.open_cover
entity_id:
{% for cover in expand('cover.slaapkamer_groep') %}
-{{ cover }}
{% endfor %}
result:
setAllWindowsOpen:
action:
service: cover.open_cover
entity_id:
-<template TemplateState(<state cover.slaapkamer_links=open; current_position=0, device_class=blind, friendly_name=Slaapkamer links, supported_features=15 @ 2022-05-23T04:27:11.164509+02:00>)>
-<template TemplateState(<state cover.slaapkamer_midden=open; current_position=0, device_class=blind, friendly_name=Slaapkamer midden, supported_features=15 @ 2022-05-23T04:27:11.164073+02:00>)>
-<template TemplateState(<state cover.slaapkamer_rechts=open; current_position=0, device_class=blind, friendly_name=Slaapkamer rechts, supported_features=15 @ 2022-05-23T04:27:11.165971+02:00>)>
Does that look good?
Oh, and you need to add a > for a multi line template
mmh interesting... no because they get substituted with the object by the engine
setAllWindowsOpen:
action:
service: cover.open_cover
entity_id: >
{% for cover in (expand('cover.slaapkamer_groep') | map(attribute=entity_id) | list)%}
-{{ cover }}
{% endfor %}
``` perhaps?
needs a space between : and >
That would work, but makes no sense
you are just using a loop to format a perfectly fine list into the yaml format
that's just a waste of resources
Failed to call service cover.close_cover. Template rendered invalid entity IDs: nope doesn't like it
it is
target:
entity_id: >
{% for cover in (expand('cover.finestra_sala') | map(attribute=entity_id) | list) %}
-{{ cover }}
{% endfor %}```
entity_id needs quotes
Failed to call service cover.close_cover. Template rendered invalid entity IDs: -cover.finestra_sala with quotes
But again, why do you so desperately want it like this?
Just use the json formatted list
just to understand how the logic works behind it
it wants the - inside the {{ }}
but does not like more than one cover
¯_(ツ)_/¯
Well I also can't get it working, but as it is pointless anyway I won't spend more time in it. Just use the list the template provides in json format
yep i just wanted to get a good grasp to not bother again for some trivial error out of a misunderstanding of the stack
I want to count the number of seconds a switch is on. I am using the history stats integration but the problem is that it only measures to the hundredth decimal place so it's only accurate to every 36 seconds. How can I accomplish this behavior with a template?
- platform: history_stats
name: "Bag Duration"
entity_id: switch.volcano_air_state
state: "on"
type: time
start: "{{ states('input_button.change_bag') }}"
end: "{{ now() }}"
Does it need to be that precise? How is there between bag changes?
Yeah it's not any use if it's not more accurate then to 36
Ideally accurate to a second, if it's much more it's not very useful
So, if I understand correctly, you press a button (input_botton.change_bag)
after that you turn on a swith, turn it off again, turn it on, turn it off, etc
and after a while it has been on for a number of seconds, which alerts you it is time to change the bag again
yes
Okay, you can write the number of seconds to an input_number, and reset it on a press of the button
yeah, I can get the elapsed time since the last btn press with {% set elapsed_time = ((as_timestamp(now()) - as_timestamp(states('button.volcano_power_button')))) %}
but I wasn't sure how to actually add that number to an input_number
I guess I could maybe just have template sensor storing that and then an automation or python script to just add that number to the running elapsed total
- service: input_number.set_value
target:
entity_id: input_number.whale
data:
value: "{{ states('input_number.whale') | float + ((as_timestamp(now()) - as_timestamp(states('button.volcano_power_button')))) }}"
This will not do what you want though
you need to do this every time you switch the switch to off and use trigger.state_from.last_changed in your template
ok I tried something similar to that eailer but I wasn't using triggers and was getting confused why I had no .last_changed, but that makes sense now because I was trying to get the last_changed attribute instead
last_changed is not an attriubte (in HA terms)
this will not work properly after a reboot though, as last_changed will be the time of HA start
so if it was already on for 1 hour before reboot, it will not count that time
and as 36 seconds difference wasn't accurate enough
I suggest an automation which writes the datetime it was turned on to an input_datetime and then the state of that and compare it to now() when it gets turned off again
By itself the second statement works however when it's used with an or it does not. Is there a way to keep this as one template with an or?
{{ states('weather.openweathermap') |regex_replace(find='fog', replace='foggy', ignorecase=False) or states('weather.openweathermap') |regex_replace(find='partlycloudy', replace='partly cloudy', ignorecase=False) }}
Works this way:
{{ states('weather.openweathermap') |regex_replace(find='partlycloudy', replace='partly cloudy', ignorecase=False) }}
No, you can only use or for logical expressions
{{ a == b or c > d }}
You can do something like this:
{% set conditions = {
'fog': 'foggy',
'partlycloudy': 'partly cloudy'
}
%}
{{ conditions[states('weather.openweathermap')] if states('weather.openweathermap') in conditions.keys() }}
Would I replace what I have in this statement with that?
{% if state_attr('weather.openweathermap','forecast')[0] .temperature -
state_attr('weather.openweathermap', 'temperature') | abs >= 3 %} <break
time=".03s"/> at {{ (state_attr('weather.openweathermap','forecast')[0]
.datetime | as_datetime | as_local).strftime("%I %p") }} it will be
{{ state_attr('weather.openweathermap','forecast')[0] .temperature }}
degrees outside and {{ state_attr('weather.openweathermap','forecast')[0] .condition |regex_replace(find='fog', replace='foggy', ignorecase=False) or state_attr('weather.openweathermap','forecast')[0] .condition |regex_replace(find='partlycloudy', replace='partly cloudy', ignorecase=False) }}. {%
else %} {% endif %}
Guess this would work:
{% set conditions = {
'fog': 'foggy',
'partlycloudy': 'partly cloudy'
}
%}
{% set s = states('weather.openweathermap') %}
{% set condition = conditions[s] if s in conditions.keys() else s %}
{% if state_attr('weather.openweathermap','forecast')[0].temperature - state_attr('weather.openweathermap', 'temperature') | abs >= 3 %}
<break time=".03s"/> at {{ (state_attr('weather.openweathermap','forecast')[0].datetime | as_datetime | as_local).strftime("%I %p") }}
it will be {{ state_attr('weather.openweathermap','forecast')[0].temperature }} degrees outside and {{ condition }}.
{% endif %}
I removed the {% else %} as it was empty
As I have 3 similar if statements would I need to use this before each if statement or just once?
Are they all in the same template?
@silent vector posted a code wall, it is moved here --> https://hastebin.com/fipajazene
You only need to do it once then
just place it at the top as I did above
and replace what you did with {{ condition }}
Sounds good thank you.
If it's not fog or partlycloudy it will just evaluate to what the state is right? Such as sunny or clear
yes
Perfect
I just noticed it only tracks the state. I have separate statements for forecast 0 through 3. I think I would need to repeat what you had prior to each statement and change {{ condition }} to something else for each one right?
For example
{{ state_attr('weather.openweathermap','forecast') [1] .condition
{{ state_attr('weather.openweathermap','forecast')[2] .condition
Remember that time I made a for loop that did all that without specifying which index? Peperridge farm remembers.
I do lol. But I had an issue where it repeated the same temperature. For example it would repeat at 7am it will be x.
well, you should have posted that and tried to fix it
I'm sure there was an easy fix
That's what the template editor is for
test in the editor and go from there
Results in
<speak>
Good morning.
It is 06:38 AM. The high today is 71 degrees and the low is 56 degrees. <break time=".03s"/> It is currently 56 degrees outside. - <break time=".03s"/> at 06 AM it will be 56 degrees outside. </speak>
It's already 06:40 past 06:00. Ideally it wouldn't say that and not say the same temperature as current.
Put in an if statement checking if the datetime attribute is later than it is right now
replace {% if hourly.temperature - ns.previous > 3 %} with {% if hourly.temperature - ns.previous > 3 and hourly.datetime | as_datetime | as_local > now() %}
Are you sure the forecast is hourly and not the next 10 days?
looking at mine, it's the next 10 days
Certain.
ok, well this will work
<speak> {%- set t = now() %}
{%- set weather = expand('weather.dark_sky') | first %}
{%- set forecast = weather.attributes.forecast %}
{%- set temps = forecast | map(attribute="temperature") | list %}
{%- if t.hour < 12 %}
Good morning.
{%- elif 12 <= t.hour < 17 %}
Good afternoon.
{%- else %}
Good evening.
{%- endif %}
It is {{ t.strftime("%I:%M %p") }}. The high {{ temps | max }} degrees and the low is {{ temps | min }} degrees. <break time=".03s"/>
It is currently {{ weather.attributes.temperature }} degrees outside.
{%- set ns = namespace(previous=-300) %}
{%- for hourly in forecast[:3] | rejectattr('datetime', '<', utcnow().strftime("%Y-%m-%dT%H:%M:%S+00:00")) %}
{%- if hourly.temperature - ns.previous > 3 %}
- <break time=".03s"/> at {{ (hourly.datetime | as_datetime | as_local).strftime("%I %p") }} it will be {{ hourly.temperature }} degrees outside.
{%- endif %}
{%- set ns.previous = hourly.temperature %}
{%- endfor %} </speak>
Edited to remove whitespace
the -'s seem redundant with the break times. I'd just make the breaks longer as that's what the dashes do IIRC
Sounds good I will try this thank you.
Is it also possible this template would be able to work with a temperature that is 3 degrees lower than previous and not just greater than previous? In my template I'm using abs >= 3. Also can it besides just doing greater than previous also do greater than current which is {{state_attr('weather.openweathermap', 'temperature') }}
To add precipitation probability would it be hourly.precipation_probability for example hourly.precipation_probability > 70
Just put the abs in the check
Also it doesn't seem to be rejecting an equal temperature to current.
<speak>
Good morning.
It is 07:56 AM. The high 71 degrees and the low is 55 degrees. <break time=".03s"/>
It is currently 58 degrees outside.
- <break time=".03s"/> at 08 AM it will be 58 degrees outside. </speak>
Set the previous in the namespace to the temperature as well
On mobile so you’ll have to make the changes
Nevermind the abs fixed it.
{%- if hourly.temperature - ns.previous | abs >= 3 %}
Remplqce the -300
Pedmas
Math order of operations
If you want to apply the abs on the result of the subtraction… what would you do?
I honestly don't know.
Parenthesis
Pedmas-> parenthesis, exponent, division, multiplication, addition, subtraction
Bring yourself back to 6th grade math
I remembered that lol but I wasn't sure if parentheses would be used. We used "please excuse my dear and Sally" and some McDonald's thing too but I wasn't sure if parentheses should be used.
There is no filters in pedmas.. 😉
So it would be previous=(300)?
No, you asked 2 questions and you got 2 answers and your mixing them
Oh yes greater than current and greater than previous.
If I'm getting this right
{%- if hourly.temperature - ns.previous | abs >= 3 %}
in the second template you are only applying the abs to ns.previous
How would I fix that?
Where would the parentheses go though?
{%- if hourly.temperature - ns.previous | int (3) %}
{%- if (hourly.temperature - ns.previous) | abs >= 3 %}
It's not that difficult, just put parenthesis around the part you want to apply first
@silent vector posted a code wall, it is moved here --> https://hastebin.com/oyuzefilel
It's not the first time today that this happened isn't it?
Is there a problem?
https://dpaste.org/SmCsK
The output isn't including the {{ state_attr('weather.openweathermap','forecast')[3] .temperature }} which is 3 degrees greater than current right now.
it checks for 3 degrees above the previous temperature
so, do you want it 3 degrees above the current or 3 degrees above the prevous temperature
Is it possible to do both?
that wouldn't change your current output
3 above previous or 3 above current
{%- if (hourly.temperature - ns.previous) | abs >= 3 or (hourly.temperature - weather.attributes.temperature) | abs >= 3 %}
Would this work? There were no errors in the template editor but I'm curious as to whether it would work in the loop.
https://dpaste.org/4C0TD
I used the editor and it evaluates with no errors. I was curious as to whether it would be sequential meaning would it output 0 temperature from the forecast and then the precipitation probability or would it loop through the forecast 0-3 first then loop precipitation probability. Potentially resulting in at 10 it will be 60 degrees at 11am it will be 63 degrees at 12 am it will be 66 degrees. At 10 am it will be 71% chance of rain. At 11 am it will be 75% chance of rain etc.
you can play with that by changing the comparison values in the template editor
change the 3 to 0 and change > 70 to >= 0 and you will get it all
I don't think you tried it in the correct editor then
because you'd see on screen exactly what you're asking
what are you trying it in?
developer tools -> template?
unless it's not raining, then I could see this being an issue
Here's the output
<speak>
Good morning.
It is 09:04 AM. The high 71 degrees and the low is 55 degrees. <break time=".03s"/>
It is currently 61 degrees outside.
- <break time=".03s"/> at 10 AM it will be 61 degrees outside.
<break
time=".03s"/> at 10 AM The chance of rain is 0%.
- <break time=".03s"/> at 11 AM it will be 62 degrees outside.
<break
time=".03s"/> at 11 AM The chance of rain is 0%.
</speak>
Exactly what I was looking for
Now how would I fold the regex replace we were talking about with fog and partlycloudy into the loop?
{% set conditions = {
'fog': 'foggy',
'partlycloudy': 'partly cloudy'
}
%}
{% set s = states('weather.openweathermap')
{% set condition = conditions[s] if s in conditions.keys() else s %}
I was wondering when this would come in the picture again
Lol I didn't forget
What do you want as result here for the next hours? Only when it differs from the current and/or previous?
When it differs from current and/or previous would be best
Is there a way to save a template that will be used over and over in many automations or do I have to paste the template code in each time?
Depends, if it is exactly the same every time, create a template sensor out of it, and use the state of the sensor
well the value wont' be the same everytime, but the template will. I'm looking to create a template that is reading the chance of rainfall for today and tomorrow. So the value will be different but the template should remain the same
I think the template sensor is just what you want
I still see only 2 templates. one for today and one for tomorrow
yes
https://dpaste.org/jzhYn (corrected version)
It says 404 not found?
Now it doesn't anymore (new link)
ok, so I just need to determine how to write the template to get what I want out of it then. For example if I wanted to take the value of precipitation_amount and precipitation_probability over the span of 2 days and create a value out of that...🤔
Hm it says UndefinedError: 'h_cond' is undefined
Are you sure you copied everything relevant, including this line {% set h_cond = hourly.condition | replace('fog', 'foggy') | replace('partlycloudy', 'partly cloudy') %}
Missed that. Now it says hourly is undefined. Is that because hourly isn't defined until the next line?
Just take the entire thing and only replace your entity at the top
Hi,
what is wrong with this one? The addition does not work, the value is simply equal to the first:
template:
sensor:
name: power_consumption_total
unit_of_measurement: 'W'
state: '{{ states("sensor.l1_power") + states("sensor.l2_power") + states("sensor.l3_power") }}'
Working now thank you.
Something like this?
{%- set weather = expand('weather.climacell_daily') | first %}
{%- set forecast = weather.attributes.forecast %}
{% set amount = forecast[0:2] | map(attribute='precipitation') | sum %}
{% set probability = forecast[0:2] | map(attribute='precipitation_probability') | max %}
states are always strings, you can't add strings together, you have to cast them to a float first
ah, that is what the "| int" is for. thx, will try that
use | int if you don't care about decimals (or if the sensor doesn't have decimals), use | float otherwise
Hm I don't think it was supposed to say the 12pm condition
<speak>
Good morning.
It is 10:06 AM. The high 71 degrees and the low is 55 degrees. <break time=".03s"/>
It is currently 63 degrees and sunny outside.
- <break time=".03s"/> at 11 AM it will be partly cloudy.
- <break time=".03s"/> at 12 PM it will be partly cloudy. </speak>
You wanted this. When it differs from current or previous. It differs from current
That's true. Is it possible to be different from current or previous but not repeat the way it did at 12pm? If not it's fine.
I guess only checking if it is different as the previous one would suffice then
Hm yeah that makes sense, the only reason I wanted greater than 3 from current or previous was for temperature as it is possible to be 60,61,63. For condition it doesn't appear to make a difference sunny,cloudy,cloudy,sunny,rainy for example those are different from previous and it would work to not have different from current.
then remove the comparison to cond in the if statement
I tried h_cond != ns.prev_cond and h_cond != cond and its still repeating for some reason
wait, my bad
whoa...this is a lot to take in haha
replace this at the end:
{%- endif %}
{%- set ns.previous = hourly.temperature %}
{%- endfor %} </speak>
with
{%- endif %}
{%- set ns.previous = hourly.temperature %}
{%- set ns.prev_cond = h_cond %}
{%- endfor %} </speak>
and replace:
{%- if h_cond != cond or h_cond != ns.prev_cond %}
with:
{%- if h_cond != ns.prev_cond %}
That worked.
It takes the first two items out of your weather entity (so today and tomorrow) and sums the precipitation of both days, and sets that as a variable
And the max value of the probability, and also sets that as a variable
I see. But if precipitation is an amount (in mm) and not a percentage, how would that work?
How would what work? I knew it was an amount in mm, that's why I summed them to get the total of the the two days
Hey! I have a template sensor showing my sunrise with offset of -45 minutes. How do I make it show this based on my timezone (GMT+1) ?
{{ state_attr('sun.sun', 'next_rising') | as_datetime - timedelta(minutes = -45) }}
i got a sensor that has a text and emoji in every state, how would i remove the the emoji with a template?
depends on how the emoji is represented as text in the sensor
i just copy and pasted an emoji from Whatsapp
Ok and what does it look like in the sensor state in HA?
the emoji just shows up
I can't actually see the format
like this "Bewölkt ☁️"
Is the emoji always at the end? Maybe you can split on space and remove the last part and join it again
please see what it shows in developer tools -> states page
in my mobile app exactly what we see here
then [:-1] would be everything before the emoji and [-1] would be the emoji
@marble jackal sorry to bother you again with this but you didnt confirm yesterday if that automation was the same as what you told me to do. I believe it is but can you please take a quick peak just to be sure? https://pastebin.com/Nj5F5J9t
I also did it the exact way you said (with the additional binary sensor to check for 36 elapsed hours) but then thought an automation on an input boolean would be more useful. If it isn't good I can switch back to the sensor
No, this doesn't look right
The automation with this trigger should set your input_datetime to now(). Nothing more than that
And it should not have this condition
oh no, I did that separately, for the datetime
this is a boolean
thisone is instead of the binary sensor with the 36 condition check
I figured I can't action a binary sensor, but I can action a boolean if I happen to need it to trigger
you would start with this: state_attr('sun.sun', 'next_rising') | as_datetime | as_local
like this yes? https://pastebin.com/XLjMDP5h
There is no need to turn off these automations. You have a perfectly fine condition to place in these automations to check if they should run
and the binary sensor
- name: "Cold"
state: >
{{ is_state('binary_sensor.outside_cold', 'on') and now() - timedelta(hours=36) > as_local(as_datetime(states('input_datetime.cold'))) }}```
Do you have two binary sensors cold now?
yes
Oh I see
I'm one mobile, so it's a bit hard to get the overview
So binary sensor cold outside just checks if it is below 11 degrees right?
No that's fine
Okay, great. Now just use your new binary_sensor.cold as condition in your automations
Don't turn them off
oh that's even better!
Yes so far I manage to get it right, but then how about that offset? How/where do I add that in the code?
where it was before
I just gave you the part that changed. Although subtracting a negative timedelta is a strange thing to do
I would either subtract or add a positive timedelta
you should really stop messing around with offsets from sunrise/sunset and just use sun elevation
oh ok! maybe that's better? 🙂 Because I want my outside lights to go on just when it gets dark. And +45 minutes after sunset seem to be a good time. But how do Elevation work? should I just notice the elevation when its dark and notice and use that in automation?
Oh it is? well that's interesting will try it out! thx
So I found what elevation should be good here when its dark. Its -4.63. But should that go in "below" or "above" in the automation to turn on the lights? 😛
But wait, it's -4.63 2 times during a day, right?
You can use a numeric_state trigger to differentiate if you want
Maybe there's a simpler way to do this but is there a way to include the state of one entity as part of an entry for another entity? Something like
{{(sensor.state_attr('person.Morgan', 'friendly_name')}}
Where friendly name is Morgan and the result of the tensor would be sensor.Morgan
Yes I used that, and to turn ON lights I used "below -4.63" and to turn OFF light "above -5.10" I hope that turn out the right way? 😛
Should be fine, but you need separate triggers
yes I use 2 automations one for on and one for off
Is it possible to pull measurement history and convert that to a value template? I'd like to get a 3 day moving average for my download speed from sensor.speedtest_download but am struggling as it's not a readable state or attribute.
the only way to retrieve history is either to create a template sensor or sensors that sample every so often and retain the number of historical points you want, or to use the SQL sensor
or, just use the statistics sensor
I tried statistics sensor, but was getting an error [state_characteristc] is an invalid option for [sensor.statistics]
which is what the documentation uses to explicitly call "mean"
[:-2] did it
looks like a spelling mistake
and it's optional, with the default being "mean"
I thought it was state_characteristisosucoiuts?
That's the British English spelling
- platform: statistics
state_characteristic: mean
name: "3 Day Avg Download Speed"
entity_id: sensor.speedtest_download
max_age:
hours: 72
That's the sensors.yaml entry, and it spits out an unavailable error in dev tools>states
is it ok to still use state_attr or should I be using States always?
Hi I have a template sensor for my bathroom cam that works and an identical one for my kitchen cam that shows up as unavailable
- platform: time_pattern
seconds: "/1"
binary_sensor:
- name: "Bathroom motion"
state: >
{{ (now() - states.sensor.samsung_j3_ipcam_motion.last_changed).seconds < 30 }}
I checked them both physically as well as inside HA and the individual motion sensors are working live
- platform: time_pattern
seconds: "/1"
binary_sensor:
- name: "Kitchen motion"
state: >
{{ (now() - states.sensor.fig_lx1_ipcam_motion.last_changed).seconds < 30 }}```
this last one shows up Unavailable
They're used for different purposes - one to get a state and the other to get an attribute, so 🤷
That kind of design is...not good. Why poll every second when you can just let it update when the entity updates?
as far as why it evaluates to 'unavailable', plug the template into
-> Templates and see
says false. which would mean for the binary sensor to be showing up as off
like the other one does
but it doesn't, it shows up as unavailable
I suggest just removing the trigger from both of them
I feel you. But this particular motion sensor is based on a camera, it shifts the value on which it rests when no motion is registered, it's weird. I'll try it the way you said, but I remember trying that way once
it sounds like it's not actually triggering
hmm interesting. So not adding anything instead of the trigger part? just removing it
you can use some other trigger that helps filter how often it runs, but it's indiscriminate now, so now how much worse can it get?
yes, just let the entity updates drive the sensor
template sensors didn't have a "trigger" section until a few months ago
cool
ooh now I remember why
someone said whenever you work with 'now(0)' it triggers only once a minute
like it evaluates the template and checking conditions only once every minute or so
which is why I thought of adding the trigger every second
you're also referencing an entity, but I don't know if it will pick that up
you should just use a state trigger instead, based on the sensor entity
then it will definitely only trigger when it changes state
it's not related to templating
this is my sensor.fig_lx1_ipcam_motion entity
- trigger:
- platform: state
entity_id: sensor.fig_lx1_ipcam_motion
it's just a trigger like any other trigger
since this is a template question, is it possible to include a template here? what would the proper way to do this be (if even possible)
{% for person in states.person %}
{% if states('sensor.'~person.attributes.friendly_name~'_home_value')|float > 0 %}
{{
{
'type': 'template',
'entity': 'person.entity_id',
'content': '{{content}}'
}
}},
{% endif %}
{% endfor %}```
id want a template where {{content}} is
You can't nest templates
If you can, you would just not quote it behaves it's not a string
do you mean like this:
'content': content
got it, thanks
this.entity_id (auto-entities) doesnt work there for some reason
in the template editor?
there's no reason why it wouldn't work where it's valid
{% set this = {"entity_id": "foo.bar"} %}
{%- for person in states.person -%}
{%- if true -%}
{{
{
'type': 'template',
'entity': 'person.entity_id',
'content': this.entity_id
}
}},
{%- endif -%}
{% endfor %}
->
[
{
"type": "template",
"entity": "person.entity_id",
"content": "foo.bar"
},
{
"type": "template",
"entity": "person.entity_id",
"content": "foo.bar"
}
]
it doesnt work in to get state or attribute values here, but it does work otherwise
ah but neither does person.entity_id
so states('person.entity_id') doesnt work but person.state does
last question, i think, how would i include
action: more-info```
yeah but try 'content': states('input_text.entity_id') and it wont work
or 'content': states('this.entity_id')
i was using person.states, and no, i dont have an entity called that
Ok, then it won't work 
right but, it works in the dev tools template but not in auto-entities
{% if states('sensor.'~person.attributes.friendly_name~'_home_value')|float > 0 %}
{{
{
'type': 'template',
'entity': 'this.entity_id',
'content': states(person.entity_id),
'icon': 'mdi:home' if person.state=='home' else 'mdi:home-export-outline',
'icon_color': 'grey',
'tap_action': {
'action': 'more-info'}
}
}},
{% endif %}
{% endfor %}```
And again, this.entity_id is a variable and shouldn't be in quotes
eh either way, its honestly a non-issue
Great. But I hope you'll see what's wrong
There are some fundamental misunderstandings there
me too, but right now i just dont have the brainpower for it 😅
Hi 🙂 Any way to format a number based on the users current locale, and not that of the server?
Only on front-end using custom cards which provide a user variable as far as I know
Ok, thats too bad. Thanks.
If this is still about auto-entities (sorry didnt catch up on the whole backlog) , that requires the output to be a list, so maybe encapsulate it with [ ]. also check there's no default on the |float, which my system is complaining about 😉 lastly, you have a type: template? It seems you have several fields not related to a card config there?
check: filter: template: >- {% set threshold = states('input_number.battery_alert_level')|float(0) -%} {%- for s in states.sensor|selectattr('entity_id','search','battery_level') if s.state|float < threshold -%} {{ { 'type': 'custom:button-card', 'template':'custom_ui_hack_for_button_card_template', 'entity': s.entity_id } }}, {%- endfor %}
moving another example to your question in frontend, see #frontend-archived message
I want to show when an entity last changed state in my dashboards. For example when a door (that now is open), was opened.
Today I use {{ as_timestamp(states.binary_sensor.altandorr.last_changed) | timestamp_custom('%Y-%m-%d %H:%M') }} which works fine.
But it is not always correct since last_changed is reset when HA is restarted, and hence all open sensors that hasn't changed state since HA's last restart now show HA's restart time instead of the actual/physical state change. The actual state change is stored in the logbook. Can I fetch it there? Or some other way that is not reset by HA restarts?
logbook uses the database, you can also get it out using a sql sensor, but that requires you to create an sql sensor for all your entities.
BTW, you can also do {{ states.binary_sensor.altandorr.last_changed.strftime('%Y-%m-%d %H:%M') }}
{{states('input_datetime.staubilastrunkueche') }}
{{ now().strftime('%Y-%m-%d') }}
both entities result in 2022-05-24.
Question: how can i put this into a template that returns true/false on comparing those two entries?
{{ states('input_datetime.staubilastrunkueche') == now().strftime('%Y-%m-%d') }}
I've managed to correctly convert my input_datetime's into seconds so i can work with them, but I can't do the same with "now"
states('sensor.time') gives me the correct hours:minutes of right now
but trying to convert it, I get 0 or unknown.
What I am trying to actually accomplish is this. I have a time (input_datetime, like 9am (9:00). I also have a buffer variable (input_number) which is a number of minutes
Just need to determine if right now it is within (buffer minutes) of that time.
The only thing stopping me from accomplishing this is that I can't turn "now" into seconds so that I can compare them.
state_attr('input_datetime.t1_sleep', 'timestamp') gives me the time I want in seconds, but I switching that out for sensor.time does not work
{% set nowseconds = (as_timestamp(states.sensor.time.state)) %} i get "none"
what are you trying to do? Does your datetime have a date or just time?
ok, and what are you trying to do
I have set my "grace period of 20 min" (an input_number)
I just want to determine if it's between 8:40 and 9:20
during a template sensor
I guess the problem is that my sensor.time doesn't have a date, but I don't need one nor does my other calculation but that does not seem to mind not having a date
{% set offset = timedelta(minutes=20) %}
{% set alarm = today_at(states('input_datetime.t1_sleep')) %}
{{ alarm - offset < now() < alarm + offset }}
need to use a sensor for 20 it will be an input_number
ok
{% set number = states('input_number.xyz') | int(default=20) %}
{% set offset = timedelta(minutes=number) %}
{% set alarm = today_at(states('input_datetime.t1_sleep')) %}
{{ alarm - offset < now() < alarm + offset }}
np
can I drop the default, it will always have a value
sure
still needs int
if you're using it as a template sensor, it may error on startup
you'll be fine if it's in an automation
yes I left the |int
should be ok, It's part of an if/else
so if it errors on startup, it would just "else"
which is fine
the take a way is that today_at will error if the input_datetime returns 'unknown', which is unlikely
if you swap them to sensors instead of helpers, you'll have errors
i.e. things that can go unavailable or unknown
gotcha
would it actually error or would it just not pass true and thus drop to the else?
it would error out
im only using helper so it should be fine
yep
Sorry, folks wish to paste some code how do I do that politely?
Trying to create multiple If statements to change icon, what am I doing wrong? {% elif s = 'Eco+' %} mdi:leaf-circle
Sorry {% set s = states('select.myenergi_zappi_20435419_charge_mode') %} {% if s = "Stopped" %} mdi:stop {% elif s = "Eco+" %} mdi:leaf-circle {% elif s = "Eco+" %} mdi:leaf-circle-outline {% else %} mdi:run-fast {% endif %}
You're using = when you need ==
is there any way to return only the value from a key value pair? and is there a way to do this systematically without necessarily listing out each key?
Probably, can you give an example
yeah so i have an input_text.entity which contains a string (or i can make it an array with states.input_text.entity.state.split(', ')) of key value pairs {'BT-ID':'MAC-address'} and I want to do something like
{% set = device_list states.input_text.entity.state.split(', ')%}
{%for device in device_list%}
{{devicevalue in state_attr('sensor.pixel_4a_bluetooth_connection','connected_paired_devices')}}
{%endfor%}```
where device is any single key:value pair from the list and devicevalue is the value of the key value pair (not sure how to tell it to return devicevalue)
id like to match the value and perhaps (but less importantly so) return which key it belongs to
example value of the input_text.entity is {'BK01':'EB:06:EF:26:45:94'}, {'Lexus':'94:B2:CC:D6:89:1C'}, {'Bond':'DE:63:AD:73:7A:D1'}
{% set d = "{'a': 'b'}, {'c': 'd'}".split(', ') %}
{{ d }}
Results in:
[
"{'a': 'b'}",
"{'c': 'd'}"
]
So you will end up with a list of strings, not a list of dicts
yeah, how do i turn it into a list of dicts is part of what im trying to figure out
Real ugly, but this works:
{% set d = "{'a': 'b'}, {'c': 'd'}".split(', ') %}
{% set ns = namespace(d = []) %}
{% for x in d %}
{% set x = (x | replace('{','') | replace('}','')).split(':') %}
{% set ns.d = ns.d + [ { x[0] | replace("'", "") | trim: x[1] | replace("'", "") | trim }] %}
{% endfor %}
{{ ns.d }}
But I think we are having an xy-issue here
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
Command '.xy' was invoked by: TheFes
haha, ive no doubt that im taking a bit of complicated route here, but in the name of simplicity later. i'd like to match for bluetooth mac addresses based on one entity, so that i can add/remove them with relative simplicity (changing the entity rather than editing the automation). this is simple enough with split, but i also want to return the name of the bluetooth device that was connected. the best answer i can think of is dictionaries with name:mac-addr to match the mac address and return the name which the mac address belongs to, so thats what im trying to go for here
I have this working template to count devices in my network:
https://paste.debian.net/1241932/
when I try it in the template editor in devtools i get:
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'scanner'
what is going on?
Check if the attribute is defined first
{% set total = states.device_tracker | selectattr('state', 'eq', 'home') | list | count %}
{% set luci = states.device_tracker
| selectattr('state', 'eq', 'home')
| selectattr('attributes.scanner', 'defined')
| selectattr('attributes.scanner', 'eq', 'LuciDeviceScanner')
| list | count %}
{{ total - luci }}
Sorry for the crappy indentation, I'm on mobile
works. that part I figured - that it stumbles upon the entities without the attr and fails but the definedis new to me thanks.
but I wondered why it works as template sensor but not in dev tools
seems dev tools is a bit more strict
Store your dict in the input text using | to_json, then when reading the input text use from_json
That’s the best way to store complex structures to serialize and deserialize them
ok, ill give that a try, thanks
Is there a way to remove the leading 0 from the hour? Ex. 06 am 07am 06pm.
https://dpaste.org/qarkL
<speak>
Good morning. It is 05:34 AM. The high today is 72 degrees and the low is 52 degrees. <break time=".03s"/> It is currently 52 degrees and clear-night outside. The humidity is currently 84%. - <break time=".03s"/> at 06 AM it will be sunny - <break time=".03s"/> at 07 AM it will be partly cloudy
Its weird because it said 5:34 likely because it recognized it as time even though It said 05:34 above however the 06 and 07 were pronounced 06 and 07 rather than 6 and 7am
got one more question on this here. in my testing the following template evalutes to boolean true if there is exactly one entry that is true or boolean false if all entries are false, but if multiple entries are true, it evalutes True as a string for each entity
{%set device_list = states.input_text.car_bluetooth_connections.state.split(', ')%}
{%for device in device_list if device in state_attr('sensor.pixel_4a_bluetooth_connection','connected_paired_devices')%}
{{true}}
{%endfor%}```
for example, in my test there are 2 matching entries and the result i get is
```Result type: string
True
True```
how can i make this example result to a boolean true
Should have thought of that :)
If you are using the beta of the app, the connection list will be an actual list, which will make this a lot easier
{{ device_list | select('in', state_attr('sensor.pixel_4a_bluetooth_connection', 'connected_paired_devices')) | list | count > 0 }}
Otherwise you have to make sure it is a correct list using the json filters
I added to my template due to getting spikes ```
value_template: >
{{states('sensor.bill_br_govee5075_humidity') | is_number and
states('sensor.bill_bathroom_average_linear_3h') | is_number}} {{(states('sensor.bill_br_govee5075_humidity') | float -
states('sensor.bill_bathroom_average_linear_3h') | float) |round (1)}}
The check is_number. Do I need to add something between this and the rest of the template? I no longer get a graph in history
Developers tools shows true and a value i.e .3
The first part should be added as availability_template and should not be part of the value_template
That was the link Petro sent me yesterday, I did not understand from the docs how to format it correctly. So does this statement go in the template by itself and then the value statement?
So Reading some of the forums I need to add a separate line in my template called availability_template and then the is number?
Hi template gurus.
Is there a best practice to validate a state as a datetime before running as_datetime()?
I have a sensor (mobile phone next alarm time) that is only a valid datetime when an alarm is set.
{{ now() >= as_datetime(states('sensor.phone_next_alarm')) - timedelta(minutes = 15) }}
This fails if the alarm is not set.
- platform: template
sensors:
your_object_id:
friendly_name: "Your friendly name"
value_template: "{{ your template for value }}"
availability_template: "{{ your template for availability }}"
Is there a way to remove the leading 0 from the hour? Ex. 06 am 07am 06pm.
https://dpaste.org/qarkL
Output:
<speak>
Good morning. It is 05:34 AM. The high today is 72 degrees and the low is 52 degrees. <break time=".03s"/> It is currently 52 degrees and clear-night outside. The humidity is currently 84%. - <break time=".03s"/> at 06 AM it will be sunny - <break time=".03s"/> at 07 AM it will be partly cloudy
Its weird because it said 5:34 likely because it recognized it as time even though It said 05:34 above however the 06 and 07 were pronounced 06 and 07 rather than 6 and 7am
What is the state if no alarm is set?
Got this error when I run config check. Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('sensor.bill_br_govee5075_humidity') | is_number and states('sensor.bill_bathroom_average_linear_3h') | is_number", None)])"
in "/config/integrations/../entities/sensors/bill_delta.yaml", line 21, column 0
No error in developers tools.
availability_template: {{states('sensor.bill_br_govee5075_humidity') | is_number and states('sensor.bill_bathroom_average_linear_3h') | is_number}}
Rule #1 for templates, put quotes around them if you use the single line notation
Thank you!!
Change the format for your time strings
Perfect that worked.
Good question.... It shows as unavailable
{% set s = states('sensor.phone_next_alarm') %}
{{ now() >= as_datetime(s) - timedelta(minutes = 15) if not s in ['unavailable', 'unknown'] else false }}
so im back on dictionaries now, and ive got things mostly working, the 2 things i cant seem to find in my search are how to a) list all values without iterating and b) how to get the key from the value. current example im messing with
"BK01": "EB:06:EF:26:45:94",
"Lexus": "94:B2:CC:D6:89:1C"
}```
use %I instead of %H
I never used %H. The fix was %-I %H was only used for the rejectattr you created for me not for what would be spoken.
you have a list of dictionaries and you only have the mac address?
yeah i mean, it goes both ways. i the human, want to get the name when the device gives me back a mac address, but conversely if i give the device a name, itll want the mac address. so i'd like to make it work both ways
you have to turn it into tuples
or a list of tuples
@orchid oxide can you post what you're pushing to the input_text and and post how you're using the input_text.
Post all the Jinja.
text input: {"BK01": "EB:06:EF:26:45:94", "Lexus": "94:B2:CC:D6:89:1C", "Bond": "DE:63:AD:73:7A:D1"}
and the jinja i have. this right now is a condition/trigger
{%set device_list = (devices.values()|list)%}
{{device_list | select('in', state_attr('sensor.pixel_4a_bluetooth_connection', 'connected_paired_devices')) | list |count < 1}}```
I think I have this part worked out. But I then want to be able to return (in a notification for example) the name of the bt device
Thanks! I'm afk now, so I'll try it later. Really appreciate the pointer
using connected devices to test since its way easier, so I have this part which is what im trying to get
{%set device_list = (devices.values()|list)%}
device_list|select('in', state_attr('sensor.pixel_4a_bluetooth_connection', 'connected_paired_devices'))|list```
except this last part returns the mac address (value) and i want some way to get the device name (key) from the value so I can display that isntead
I'm looking to replicate something like
{% for i in states.switch and states.sensor and states.binary_sensor and states.lock and states.input_boolean %} {% endfor %}
in a trigger. I ultimately would like any entity state change in any of those domains (and new domains I add to this in the future) to trigger home assistant to call my own API.
I just dont know how to do this in templates, or maybe I shouldn't do it in templates at all. I know I could just list out all the entities in a regular state trigger but there are so many of them.
I could use the event state_changed trigger as well as I was pointed to a little bit ago, however that triggers the automation on and off way too much for my likings. I want to prevent any automation/script state changes from triggering the automation.
Perhaps this will help:
{% set devices = {"BK01": "EB:06:EF:26:45:94", "Lexus": "94:B2:CC:D6:89:1C", "Bond": "DE:63:AD:73:7A:D1"} %}
{% set connected = ["94:B2:CC:D6:89:1C"] %}
{{ devices.items() | selectattr('1', 'in', connected)|map(attribute='0') | list | first }}
->
Lexus
ah ok, so it's a dictionary, not a list of dictionaries
{%set devices=(states('input_text.car_bluetooth_connections')|from_json)%}
{{ devices.items() | selectattr('1', 'in', state_attr('sensor.pixel_4a_bluetooth_connection', 'connected_paired_devices')) | list }}
that will return [('key', 'value'), ('key', 'value') ]
using selectattr('1' will check against the value
using selectattr('0' will check against the key
i forgot, then after you make your list, you access each one with a [0] or a [1], depending on what you want
For further clarification, how are you setting the input_text.car_bluetooth_connections? Because I believe this could be changed to potentially get a better setup.
uhh, well for the time being i was just writing it manually. i had considered making a some kind of device picker, but i havent gotten that far yet
also thanks both for the help
how do you plan on getting it?
a device picker? i use an automation app on my phone that I know could do that pretty easily. home assistant doesnt even store the device names afaik (and i'm not as familiar with home assistant tbh) so i dont even know where i'd start if i went that route
So, is this just a configuration then?
the input_text I mean
I'm just trying to figure out how that input_text is populated and what is expected of it in the future.
yeah right now it is. In the future I will probably use a device picker like i said, have it output all key and values properly formatted and then use an api call to change the input_text in ha
I guess I don't know what a 'device picker' is
by device picker, do you mean a template sensor or something?
oh, no, just some sort of dialog box that lets me check off the options
of bluetooth devices i want to include
Ok if that's the case you should make a template sensor who's main state outputs the number of devices, and contains an attribute with a list of dictionaries that contain the information you care about.
you should have this structure for your attribute:
[{'name': 'BK01', 'mac': 'EB:06:EF:26:45:94'}, ... ]
@orchid oxide then, you can simply use selectattr the normal way. Assuming your attribute in the sensor is named devices and the template sensor has a name sensor.bluetooth_connections, the syntax would be
{{ state_attr('sensor.bluetooth_connections', 'devices') | selectattr('name','eq', 'BK01') ...
or
{{ state_attr('sensor.bluetooth_connections', 'devices') | selectattr('mac','eq', 'EB:06:EF:26:45:94') ...
and you wouldn't need to use |tojson or |from_json
ok gotcha. that does make sense. ill look into setting that up
Personally, I'd set that up first before going with some other option
otherwise, going backward might not help
although, there is a 'new' development style where people work backwards with their data and it's proving to be a good process
im kinda just all over the place, i never really follow a process even though I should 😅 . I definitely decided to do more with this than I had initially planned though, otherwise I probably would have started there
That’s how it always go
Small question, before starting to play around with this: Are trigger.to_state.state etc. available in trigger-template-sensors as well. Or only within autmations?
Yep, the trigger objects are passed to all the templatable areas in the new template style.
Hey I have a little problem, has anybody an idea why sometimes the icon color doesent update until i refresh the browser or switch the dashboard?
Probably some caching.. seems more #frontend-archived related
brainstorming,
I have sensor.basement_hvac_mode
which I want to know how many minutes it has been in "cooling" in the last 2 hours... but cannot just use last_changed since it can go from cooling to idle and idle to cooling.... to make it harder, I want
sensor.basement_hvac_mode is cooling OR sensor.other_hvac_mode is cooling
since they both same same compressor
theory is that if its running for too long... something is wrong