#templates-archived
1 messages · Page 157 of 1
you can't use a template to construct another template like that 🙂
luckily, it's much easier
yeah, that's what I was building
thank you anyway 🤘
Wondering if there is a simple way to track users in zones after they've left to report who was last in zone such that if a new person or persons enter a zone, it shows them all, but once the last person leaves, it shows who was last there. Triggers work as expected when the last person leaves, but I'd like additional context to know who was last to leave in order to route notifications.
Try this?
- Use an input_text to store a person ID
- An automation that triggers whenever a person's state changes to not_home, whose action is to update the input_text
- Then you can use another automation that triggers when the zone state goes to 0, whose action is to send a notification to whoever's ID is in the input_text
Anyway this may belong better in #automations-archived
hello, im looking for a way to track the previous 24hrs of a sensor to find the difference between its current state and its state 24hrs ago. i was using a SQL sensor, but after i updated my system the SQL sensors are basically worthless
I don't see any templates here, seems to be more for #automations-archived
Is there a particular reason why the | default(<value>,true) filter doesn't work with the state() method?
It doesn't return the <value> if the state object returns None
With the state_attr() it works...
So it returns the <value> only if the method returns null and state() returns None. Am I missing something?
Hi everyone. I am using feedparser to get fuel prices for today/tomorrow for my local petrol stations. I is parsed as an array?
``entries:
- title: '148.3: United'
price: '148.3' - title: '184.9: Coles Express'
price: '184.9' - title: '185.9: 7-Eleven South'
price: '185.9'
``
I want to get an average/min/max prices for the day, so that when tomorrow's prices are available, I want to compare and alert if there is a major price difference
guess I need to use a loop, but still struggling with yaml syntax
Array of dicts. You have to map it to an array of price, then floats, then avg them. Sry on mobile can’t write it out.
Because state method always returns a valid value
Default is only possible when the method returns none
By HA restart using state() method for template entities I.e. returning error, so I need for a moment to fallback to a default
Check for unknown and unavailable
It will returnunavailable or unknown which is a valid value
Or make an availability template on your entity
Trying to get a state() from a non existing entity it returns none in template editor
There’s a resolver that changes it to unknown or unavailable
You have to check for those.
Will do thanks
{{ states('light.whale') }} returns unknown for me in the template editor.
You are right, now I am confused how did I see the None...
@mighty ledge I tried to do something like this, but in template tester I get an error - says append is not safe:
{% set avprice = [] %} {% for num in state_attr('sensor.fuel_watch_today_ulp', 'entries') %} {% if avprice.append(num.price) %}{% endif %} {% endfor %} Average price: {{ avprice | sum / avprice | count }}
You don’t need a for loop. {{ stateattr(…) | map(attribute="price") | map("float") | list| average }}
@mighty ledge - how! 🙂 looks so easy when its done and it works 🙂
hey, how would i add a string as an item to a list?
{% set x = ['a1','b2','c3'] %}
{% set y = 'd4'|list%}
{{ x + y }}
i tried this one but 'd4' is get ripped appart. this is the output:
['a1', 'b2', 'c3', 'd', '4']
because it's a string. you can do
{% set x = ['a1','b2','c3'] %}
{% set y = ['d4'] %}
{{ x + y }}
mhh is there no way to achieve this with a string?
you turn it into a list, just like I did there
not like you did, which pulls it apart, as you discovered
a Jinja filter takes an iterator, and when you treat a string as an iterator, you get individual characters
with a list, you get individual list items
i believe this fits in here. i want to combine my door contact sensor with my door lock, so that one icon can show state if door-closed-locked vs door-closed-unlocked vs door-opened. i have rarely dabbled in templates. if wrong place then let me know
i will have to find another solution for my needs here then
i dont want to use conditional card because everything is already nested in button card - vertical card - popup card. so it would be too much
i found it, google was my friend
you can split the string to turn it into a list:
{{ "d4".split() }}
Result: [ "d4" ]
thanks!
Hi all it's me again with silly questions. How do i create counter sensor with devices on, by value over 30w ? . Examble. If washer and dryer are running, counter sensor shows me..2 devices on😁
How can you identify which devices you care about, specifically the entities that measure power?
if you just want to list them, then it's simple
{{ ['sensor.foo_power', 'sensor.bar_power']|expand|selectattr('state', 'gt', '30')|list|length }}
This just what i was l looking for. Thanks again
Quick and probably silly question I have started to work on a simple template. The template is outputting my alarm volume as 51.0 and I need to convert to decimal so .51 Can someone point me in the direction to change the output number in my template? "{{states('number.bedroom_speaker_alarm_volume')| default(0) | float }}"
And I see that its as simple as diving by 100 😆
"{{states('number.bedroom_speaker_alarm_volume')| default(0) | int /100}}"
sensors:
power_outage:
icon_template: mdi:power-plug-off
value_template: >-
"{{ is_state('switch.bathroom_fan', 'on') }}"```
I don't get why the sensor template isn't on, because the bathroom fan it;s on
What does the template return if you enter it in
> Templates
Oh wait, I see it, you shouldn't quote your template if you use multi-line notation
Either use:
value_template: "{{ is_state('switch.bathroom_fan', 'on') }}"
or
value_template: >-
{{ is_state('switch.bathroom_fan', 'on') }}
thank you!
and is_state('switch.switch_speakers', 'unavailable') }}```
i'm making a template sensor for power outage
Okay, and is there a question about this template you posted?
it's working fine, thanks for help.
Please help I want to enumerate my sonarr sensor to return the missing episodes, however it does not have keys?
{{ states.sensor.sonarr_queue }}
It returns the below:
<template TemplateState(<state sensor.sonarr_queue=3; Beat Shazam S04E05=97.74%, Beat Shazam S04E06=47.70%, Deadliest Catch S18E01=43.16%, unit_of_measurement=Episodes, icon=mdi:download, friendly_name=Sonarr Queue @ 2022-04-21T13:17:11.814043+02:00>)>
I would like to return the list:
Beat Shazam S04E05: 97.74%
Beat Shazam S04E06: 47.70%
Deadliest Catch S18E01: 43.16%
Not sure I understand how to return atributes without keys.
Well, they do have keys, they're just the names of the shows
That's pretty annoying, though
{{ states.sensor.sonarr_queue.attributes }}
``` will show you the keys
And if you want to filter that for just the shows, you'd need to look for something identifiable, like a % in the value
Or ' S'
This is definately closer
{'Beat Shazam S04E05': '97.74%', 'Beat Shazam S04E06': '47.70%', 'Deadliest Catch S18E01': '43.16%', 'unit_of_measurement': 'Episodes', 'icon': 'mdi:download', 'friendly_name': 'Sonarr Queue'}
How would you filter out the 'unit_of_measurement', 'icon', 'friendly_name' keys?
Can you elaborate please?
Where is that coming from? I don’t know why they wouldn’t plop the episodes into a list
Stupid entity design imo
Sry on mobile, can’t really write out code
Fully agreed.
What integration?
https://www.home-assistant.io/integrations/sonarr part of HA Core.
this will return a list of shows, assuming they conform to SxxEyy:
{% set data = {'Beat Shazam S04E05': '97.74%', 'Beat Shazam S04E06': '47.70%', 'Deadliest Catch S18E01': '43.16%', 'unit_of_measurement': 'Episodes', 'icon': 'mdi:download', 'friendly_name': 'Sonarr Queue'} %}
{{ data|select('search', 'S\d+E\d+')|list }}
-> ```
[
"Beat Shazam S04E05",
"Beat Shazam S04E06",
"Deadliest Catch S18E01"
]
I don't know if it's possible to reference the value of a dict item in selectattr. Couldn't figure it out
Working perfectly
{% set data = states.sensor.sonarr_queue.attributes %}
{{ data|select('search', 'S\d+E\d+')|list }}
Result:
['Beat Shazam S04E05', 'Beat Shazam S04E06', 'Deadliest Catch S18E01']
Hi. I'm trying to set up a numerical sensor which will sometimes have infinite values (let's say it's inverse power when something is off). What should I make the sensor report in this case, so that the history charts look fine. Is returning an empty string fine?
data.values() | selectattr('0', …
But you have to map(attribute='0') too
but then you can't get back to the name
as we've discussed in the past, I want to be able to apply a function to each item to modify it, before the comparison
this.value()
Not sure what you mean, you just want the list of keys right?
Cause that’s what it will do. The kvp is 0 for key, 1 for value
I want to make a decision based on the value and return the key
ah, so '0' and '1' will do that
Yeah, you can do that as long as the decision is a filtering of the list with select or selectattr
that's totally unintuitive, BTW 🙂
If you need to do a if statement or something, it won’t do it
will file that away. I'm pretty sure that it's come up before now that I think about it, but completely forgot
Yeah I’ve brought it up a few times. I use it a lot to get around dynamic length dicts limitations
would you expect this to return the first key?
{% set data = {'Beat Shazam S04E05': '97.74%', 'Beat Shazam S04E06': '47.70%', 'Deadliest Catch S18E01': '43.16%', 'unit_of_measurement': 'Episodes', 'icon': 'mdi:download', 'friendly_name': 'Sonarr Queue'} %}
{{ data|selectattr('1', '==', '97.74%')|map(attribute='0')|list }}
Yea
alas it does not
but then
No .items()
ah
so I think that
{% set data = {'Beat Shazam S04E05': '97.74%', 'Beat Shazam S04E06': '47.70%', 'Deadliest Catch S18E01': '43.16%', 'unit_of_measurement': 'Episodes', 'icon': 'mdi:download', 'friendly_name': 'Sonarr Queue'} %}
{{ data.items()|selectattr('1', 'search', '%')|map(attribute='0')|list }}
is a better solution to the OP's problem
TIL
Hey, is there any way in jinja to get the opposite of a boolean? E.g if it's 0 then I'd get 1 and the other way around?
{{ (not 0)|int }} -> 1
{{ (not 1)|int }} -> 0
Is there a filter/function to take a value, evaluate an expression, and pass that value along if true, and another specified value if false?
Like f(val, cond, fallback) e.g. f('a', true, 'f') == 'a' and f('a', false, 'f') == 'f'
@mighty ledge hey man i was lookin on the forums and saw you were responding a ton on recalling a sensors state from 24hrs ago. lots of what i saw showed using a SQL sensor, and i had it working, however i did a large jump in updates and now the sensor no longer works. i've tried everything including rolling back, with no luck. do you know of a way to do this? here is the SQL sensor i was using before my update. ```
- platform: sql
queries:- name: Crypto Total Yesterday
query: "SELECT * FROM states WHERE entity_id = 'sensor.crypto_total' ORDER BY ABS(strftime('%s', created) - strftime('%s', datetime('now'), '-1 day')) LIMIT 1;"
column: 'state'
- name: Crypto Total Yesterday
iif(boolean, 0, 1)
Is it possible to define your own filter/functions that will be globally accessible in your templates just like the custom ones HA gives you?
{% set weather = 'rainy' %}
how would i test if "rain" is part of weather?
{{ 'rain' in weather }}
trying to run this sql sensor and getting an error saying that created dosent exists in my logs. anyone know a better syntax for the query? ```
- platform: sql
queries:- name: Investment Total Yesterday
unit_of_measurement: "$"
query: "SELECT * FROM states WHERE entity_id = 'sensor.investment_total' ORDER BY ABS(strftime('%s', created) - strftime('%s', datetime('now'), '-1 day')) LIMIT 1;"
column: 'state'
- name: Investment Total Yesterday
{% set list1 = ['rainy','lightning-rainy','snowy-rainy','pouring','hail'] %}
{% set list2 = ['cloudy','cloudy','rainy'] %}
how do i test if one item of list1 is equal to atleast one item of list2
I have an entity for my Oven's cooknig completion time coming in like this:
2022-04-22T00:56:46.954Z
What format is this currently in so I can convert it to my local time? And what template syntax would I use to display that?
{% set list1 = ['rainy','lightning-rainy','snowy-rainy','pouring','hail'] %}
{% set list2 = ['cloudy','cloudy','rainy'] %}
{{ list2|select('in', list1)|list|count > 0 }}
I'm trying to make a binary sensor indicating i'm working at home. Here's the template code I've got which works fine in the template dev tool...
on
{% else %}
off
{% endif %}```
But for some reason when I build the template sensor with it its always "off". Any ideas?
My sensor code is....
binary_sensor:
- name: Working At Home
state: >
'{% if is_state('person.name', 'home') and is_state('binary_sensor.workday_sensor', 'on') and (now().hour > 8 and now().hour < 18) -%}
True
{%- else -%}
False
{%- endif %}'
Just make the value template
{{ is_state('person.name', 'home') and is_state('binary_sensor.workday_sensor', 'on') and (now().hour > 8 and now().hour < 18) }}
So
state: "{{ is_state('person.name', 'home') and is_state('binary_sensor.workday_sensor', 'on') and (now().hour > 8 and now().hour < 18) }}"
``` or
state: >
{{ is_state('person.name', 'home') and is_state('binary_sensor.workday_sensor', 'on') and (now().hour > 8 and now().hour < 18) }}
Thanks! Yeah that seems like its working. Aside from being much simpler why is that working?
any time you feel compelled to return True or False, you really just need to return the boolean result of the test you're doing
Fair enough!
@untold zodiac posted a code wall, it is moved here --> https://hastebin.com/adakayafuq
I'm not very good on templates....for this one, I'm getting the Away/Home that I want, but why am I also getting the word off in the notification?:
For the notification I get:
off
Away
most of it is checking if it's actually been triggered by something.
when the home condition fires, then I actuaally get the word On instead, so I don't think it's a line like {{ iif(triggerstate is none, "off", triggerstate) }}
for an notify action as part of an automation
so a switch is thrown when one of 3 devices come home (they're controlled by homekit as they're apple devices as I don;t have teh home assistant app on all 3 devices, and dont' have my home assistant exposed.
Hello. Im trying to make a template that if the thermostat, room temperature, and room humidity is present to show all 3 else only show the thermostat. The below works for showing all 3 but I cant get it to switch from 3 to 1 in the cases that the room doesnt have the temp and humidity. How can I make that if statement?
secondary: |-
Set: {{ state_attr('[[thermostat]]', "temperature") }}°c |
Current: {{ states['[[temperature]]'].state |
round(1)}}°c | Humidity: {{
states['[[humidity]]'].state | round(0)}}%
Ok so it is this line
{{ iif(triggerstate is none, "off", triggerstate) }}
I put a # in front of it, and the notification changed to #off #on
Think your problem is is not defined in line 7. What is the purpose of this statement? Think it is not doing what you intend.
I think I repurposed it from something to cover if the item wasn't the trigger, as in just the automation was run without being triggered by one of the trigger items
I've stripped a lot of it down now.
message: |
{% set triggerstate = trigger.to_state.state %}
{% if triggerstate == "on" %}
Home {{ trigger.to_state.name }}
{% else %}
Away {{ trigger.to_state.name }}
{% endif %
Which gets me that someone is home, and who the someone is. Pity I can't update a device tracker, or person with an automation.
device_tracker.see
Doesn’t that just ask where it is? Rather than set it to a zone or home via away? That’s how I read that
The device_tracker.see service can be used to manually update the state of a device tracker:
Hmm maybe I need to rn2readbetterers
template:
- sensor:
- name: "Percentage of energy produced"
unit_of_measurement: "°%"
state: >
{% set daily yield = states('sensor.daily_yield') | float %}
{% set Estimated production today = states('sensor.energy_production_today') | float %}
{{ ((daily yield /Estimated production today ) * 100) | round(1, default=0) }}
tried this too in templates ```
template:
- sensor:
-
name: "Percentage of energy produced"
unit_of_measurement: "°%"
state: >
{% set daily yield = states('sensor.daily_yield') | float(0) %}
{% set Estimated production today = states('sensor.energy_production_today') | float(1) %}{{ ((daily yield /Estimated production today ) * 100) | round(1, default=0) }}
availability: >
{{ states('sensor.daily_yield') not in [ unknown, unavailable, none ] and
states('sensor.energy_production_today') not in [ unknown, unavailable, none ] }}
-
Got this error ```TemplateSyntaxError: expected token 'end of statement block', got 'yield'
template:
- sensor:
- name: "Percentage of energy produced"
unit_of_measurement: "°%"
state: >
{% set daily_yield = states('sensor.daily_yield') | float(0) %}
{% set Estimated_production_today = states('sensor.energy_production_today') | float(1) %}
{{ ((daily_yield /Estimated_production_today ) * 100) | round(1, default=0) }}
availability: >
{{ states('sensor.daily_yield') not in [ unknown, unavailable, none ] and
states('sensor.energy_production_today') not in [ unknown, unavailable, none ] }}
tried this in demo and got this ```
template:
- sensor:
-
name: "Percentage of energy produced"
unit_of_measurement: "°%"
state: >33.2
availability: >
True
-
Okay, that seems fine then
Think you should enclose each of unknown, unavailable and none in quotes, otherwise Jinja thinks that those refer to variables with those names rather than the values themselves.
{{ states(...) not in ['unknown', 'unavailable', 'none'] }}
Just do scratch that, you already indicated unit of measurement as %.{{ ((daily_yield...default=0) }} % to make it display a % after 33.2
#percentage of enrgy produced
template:
- sensor:
- name: "Percentage of energy produced"
unit_of_measurement: "%"
state: >
{% set daily_yield = states('sensor.daily_yield') | float(0) %}
{% set Estimated_production_today = states('sensor.energy_production_today') | float(1) %}
{{ ((daily_yield /Estimated_production_today ) * 100) | round(1, default=0) }}
availability: >
{{ states('sensor.daily_yield') not in [ unknown, unavailable, none ] and
states('sensor.energy_production_today') not in [ (unknown), (unavailable), (none) ] }}
this is how it should be?
Quotes, not brackets. And you should do that for both lists.
Ah, sure, you're right there!
I would suggest to use a unit_of_measurement instead of putting the percentage in the state
You already corrected that while I was typing this 😀
hero 💪 Iam going to try this later
are there any recommended tutorials for learning Jinja?
the Jinja docs are a little to high for me alot of the times
#percentage of enrgy produced
template:
- sensor:
- name: "Percentage of energy produced"
unit_of_measurement: "%"
state: >
{% set daily_yield = states('sensor.daily_yield') | float(0) %}
{% set Estimated_production_today = states('sensor.energy_production_today') | float(1) %}
{{ ((daily_yield /Estimated_production_today ) * 100) | round(1, default=0) }}
availability: >
{{ states('sensor.daily_yield') not in [ 'unknown', 'unavailable', 'none' ] and
states('sensor.energy_production_today') not in [ 'unknown', 'unavailable', 'none') ] }}
this is how it should be?
Yes, that looks alright.
@stuck dock suggestions, check if the state of your source sensors is a number, and not if it is an invalid state. And with that availability template in place, there is no need for defaults.
- name: "Percentage of energy produced"
unit_of_measurement: "%"
state: >
{% set daily_yield = states('sensor.daily_yield') | float %}
{% set Estimated_production_today = states('sensor.energy_production_today') | float %}
{{ ((daily_yield /Estimated_production_today ) * 100) | round(1) }}
availability: >
{{ states('sensor.daily_yield') | is_number and states('sensor.energy_production_today') | is_number }}
*a
I know, but in your availability template you were checking if the state is neither unavailable, unknown or none. My version checks if it is indeed a number, which it will not be if it is any of these states
added a pipe in the template above
simple logic
just to nail that availability sensor: the states('sensor.xxx') will never be none, but only unavailable or unknown. It's the states.sensor.xxx that can be none. If that happens the states('sensor.xxx') will be unknown. Hence the trigger conditions like:```
condition:
- >
{% set x = ['unavailable','unknown'] %}
{{trigger.to_state.state not in x and
trigger.from_state.state not in x}}
- >
{{trigger.to_state is not none and
trigger.from_state is not none}}
But states are always strings?
The is_number filter works on strings. {{ "5" | is_number }} returns true
Huh. Well TIL.
You can also use it in like this {{ states.sensor | selectattr('state', 'is_number') | map(attribute='state') | map('float') | sum }}
thats nice. however, I just tested: {{ states.sensor | map(attribute='state') | map('float') | sum }} and that returns an identical outcome....
seems the |map('float') filters the non floats too? or maybe floats them to 0...
It floats them to zero. If you use average instead of sum, you’d see a lower average
was just adding a count to prove that..
Yes, I should have used average because it is a better use case for the filter 🙂
Hi all, I'm searching a way to count number of motion within a time windows of 5min. my sensor is binary_sensor.hue_motion_sensor_cuisine which give 3 values (on,off,unavailable). I don't know if a template could do that
okay 🙂 I will look into that direction , thank you @mighty ledge
I am using an API to return a time period string, which is formatted either as "35 min", "1 h 45 min" or "3.5 h", depending on some unclear boundaries. What would be a good template to convert this to, say, minutes which wouldn't fail when I try to split it on a non-existent term like "h" or refer to a second element when it's not there.
I've tried to search the community and Discord, but apologies if I've overlooked something. I have a template to count the number of lights that are turned on, but I would like to be able to filter out hidden entities, rather than having to add a separate rejectattr filter for each light separately. Is there a filter that would accomplish that?
| rejectattr( ## if entity_id is hidden in entity registry ## )
| map(attribute='entity_id') | list | count }}```
I think you can take advantage of the fact that the string always returns in the format "X h Y min" i.e. a space-delimited string whose length is always an even number. Then it's just a matter of splitting the string into a list of tokens, looking at the even-numbered tokens to figure out if the preceding item is in h or min, and mathing it.
{% set timestring = '1 h 45 min'.split(' ') %}
{% set ns = namespace(minutes = 0) %}
{% for i in range((timestring | length / 2) | int) %}
{% if timestring[i * 2 + 1] == 'h' %}
{% set ns.minutes = ns.minutes + (timestring[i * 2] | float) * 60 %}
{% else %}
{% set ns.minutes = ns.minutes + (timestring[i * 2] | float) %}
{% endif %}
{% endfor %}
{{ ns.minutes }}
You can modify that to assign your api output to the timestring variable.
hmm, this is new. I get a template default error when using {{distance('device_tracker.myphone_app')|round(2,0)}}
I figured the example at ```
returns rounds 1.23 down precision of 0, if fails returns 0
{{ 1.43 | round("floor", 0) }}``` to be the exact case? or do I need default=0 as second argument after all
Don't think so, there is nothing in the entity details available to filter on as far as I can see.
must say the app currently is not correctly found by the mobile_app integration, so yes, there is actually an issue with the data, forcing it to use the default for the first time (which would explain I never saw the error before..)
Hey everyone! Having an issue with what I think is a rather straightforward template condition for sun elevation. The following condition:
condition: template
value_template: '{{ state_attr('sun.sun','elevation') < 2 }}'
Evaluates as true/false in the template editor dev tool, but is giving me an error if I attempt to use it in an automation:
template value should be a string for dictionary value @ data['value_template']. Got None
Not sure why this is throwing that error - any help is appreciated!
You need to replace the outer single quotes with "
Can someone point me in the right direction, I have sensors that give their reading in Celsius but I want to see it in fahrenheit. I am using ha in docker compose. The sensors are using mqtt.
Thanks. I wasn't seeing anything either, but wanted to make sure others weren't seeing something that I might have missed.
Thanks - that did not do the trick, unfortunately.
what does the condition look like now?
using the UI and switching over to YAML mode, the system automatically puts double-single quotes on the attributes and if I try to wrap the whole thing in double quotes, it will automatically change those to single quotes:
value_template: '{{ state_attr(''sun.sun'',''elevation'') < 2 }}'
seems like it should work. I have other similar ones that work just fine. I was wondering if it has something to do with the sun component tho, since my other value_template conditions are for general sensors.
I don't get how it is erroring out to template value is None for dictionary value @ data['value_template']
@fallow sand posted a code wall, it is moved here --> https://hastebin.com/ukegoyowew
that was a pony wall, at best, hass bot!
You can just use a numeric state condition there, no need for a template condition
provide the attribute elevation as well
actually @marble jackal you're 100% correct. I didn't put the attribute in ...but that template SHOULD work, no? I'm wondering if that is a bug in the condition test
26 lines, that's well above 15
And yes, the template should work as well
🙂
anyone else seeing condition tests fail using value_template?
No, they work fine here
Your condition in the code wall can easily be done without a template as of next month, as you can provide state_not then
Is your template accepted if you enter it manually in automations.yaml?
And can you save the automation? Is it only the test button which gives this error?
I suspect it is just a bug in that test button
Confirmed
I think so too. I haven't tried saving it directly in automations.yaml yet (truth be told, your suggestion was easier!)
In looking at a different/working automation, the test fails if using the test button in the automation editor, but troubleshooter shows that the step evaluated the condition properly as true
bug
bingo! - thanks for finding that one so quickly!
OK so I feel better now lol
with {{ trigger.from_state.attributes.friendly_name }} is there a way to remove characters at the end of the friendly name? I want to remove "battery level" from the friendly name
is there a trim?
there's replace()
{{ "foobar"|replace('foo', 'blah') }} -> blahbar
{{ "foobar".replace('foo', 'blah') }} does the same with a Python string method
{{ trigger.from_state.attributes.friendly_name.replace('battery level', '') }}
would that work? I don't know how I would test it
It should. You would test it by replacing trigger.from_state.attributes.friendly_name with whatever the string is and testing in
->Templates
Or write an automation
what is a rest automation?
Autocorrect/typo for 'test automation'
trying a template sensor that give me a timestamp when my camera noticed movement last time. But this one only give me a long wierd number as timestamp.
- trigger: - platform: state entity_id: binary_sensor.baksidagarage_person_detected to: 'on' sensor: - name: "Last Movement Garage" state: "{{ as_timestamp(states.binary_sensor.baksidagarage_person_detected.last_changed) }}"
Because you’re using as_timestamp
Remove that
Right! I tried this then:
- sensors: kamera_garage_last_movement: entity_id: binary_sensor.baksidagarage_person_detected friendly_name: "Kamera Baksida Garage Senast Movement" value_template: "{{ states.binary_sensor.baksidagarage_person_detected.last_updated }}" device_class: timestamp
And now it seem to show the exact time! But when I add it to Dashboard it wont show the exact time but only "33 minutes ago" hm
So I just moved that secondary info that was below "person detected" to its own sensor 😛 Cool.. but I still want an exact timestamp in Dashboard hm
Maybe I need some HACS frontend card for that
Maybe not the best way, but using the Markdown card and use this type: markdown content: '{{ (states.binary_sensor.occupancy_1_occupancy.last_changed) }}' title: Last movement for configuration, you'll get the real date on the dashbord...
Cool ! Well that does the job! It do give me this:
2022-04-23 10:06:23.993805+00:00
Dont know what those last ".993805+00:00" is? Can I remove that?
Yes, you can format it how you want using strftime
I have this defining two binary sensor. They get recreated showing up as binary_sensor.dishwasher_can_run_nn, now in the count of tens (1-19). What is happening?
template:
- binary_sensor:
- name: "Dishwasher Can Run"
state: "{{ is_state('input_boolean.power_best_save', 'on') }}"
- name: "Dishwasher Running"
device_class: power
delay_off:
minutes: 5
state: "{{ states('sensor.bry_dishwasher_power')|float > 1 }}"
Thanks!
Adding a unique id for each sensor could maybe help
Strange they get re-created, even after a reboot. I´ll give the unique ID a shot
It did help assigning an unique ID, Thank you!
one more thing.... without the is_number, my template makes the log viewer go out of its mind..... no default. one might not notice in the frontend, but the backend really chokes on this. however using {{ states.sensor | map(attribute='state') | map('float',0) | sum }} returns 'nan'... so that is probably not correct 😉 even though it stops the error flood
and I found another oddity, i have longtime had a sensor: {{expand('sensor.zp_actuele_opbrengst','sensor.netto_verbruik') |map(attribute='state')|rejectattr('state','in',['unknown','unavailable']) |map('float',0)|sum|round(2,none)}} whihc has a fine state in the frontend, and no config error in the checker. However, the order of things is incorrect, which the dev template tools indirectly tell me: UndefinedError: 'str object' has no attribute 'state'
isnt this strange? how come the config checker doesnt notice this?
I think you need map('float', default=0) there
yeah I tried that too, but the result is still 'nan'
and check the other real life template above, it also uses the |map('float',0) as has a correct outcome
The docs mention default= as well there https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.map
but isnt that because that has a possible 3 arguments, and when only using 2, we need the default=? float would only ever have 2 arguments, so ,0 would suffice ?
Yes, but you are not using float, you are using map
right, you're right! but then why doesnt this error anymore, it would still need a default in that case, and, more interestingly, the 0 is the second argument now, so ho to explain that.. hmmm
Not sure
well, if using the | selectattr('state', 'is_number') we can a) leave out the default because it will always be a number, and b) leave out the |rejectattr('state','in',['unknown','unavailable']) because of the same reason...
👍🏼
I suppose we can even leave put the final default in the round here: {{expand('sensor.zp_actuele_opbrengst','sensor.netto_verbruik') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='state') |map('float',0)|sum|round(2,none)}} and make that: {{expand('sensor.zp_actuele_opbrengst','sensor.netto_verbruik') |selectattr('state', 'is_number') |map(attribute='state') |map('float')|sum|round(2)}} ?
I would say so indeed, you will always have only numbers
But also in the first one, the sum would have thrown an error if there were still incorrect states included
agree, but these are always number entities, and only could have gone unknown/unavailable. Its way less risky then with the states.sensor iteration
This binary_sensor don´t seem to change status on state change. What am I missing?
template:
- binary_sensor:
- name: "Dishwasher Running"
unique_id: 'F1E94D22-84F0-415F-88EE-31D73F3D5792'
state: "{{ states('sensor.bry_dishwasher_power') | float > 0 }}"
The state of sensor.bry_dishwasher_power is indeed 0.0, still the binary_sensor reders to false
If it's zero, false is correct
Seems there is the GUI that lags/don´t update
It did so after some minutes, though
Not entirely true, it seems, testing again: Flipping the power button on: State for the binary sensor was changing to true, but turning off the power the binary sensor remains on
This is also the status in the States view
Meaning Power is off, and binary sensor state is still on
Is it some trigger interval for template updates?
zero is 0.0 . 0.1 is greater than zero, right?
you didn't say "0.1"
The state of sensor.bry_dishwasher_power is indeed 0.0, still the binary_sensor reders to false
I know, just had to check if my knowledge of > 0 was correct 🙂
Seems there is some delay for turning the binary sensor to false after there is no power (0.0), while turning on power consumption imediatelly returns "on"
that would only happen if the sensor itself is slow to respond. you can test it by changing the value manually in
-> States
Then it updates fine. The binary_sensor seems slow updating, though, which is defined as above, and the state for sensor.bry_dishwasher_power changes immediatelly
I can live with the delay in real life, just now, when defining everything and testing it is not good to have the delay there, and it seems odd too 🙂
I restarted HA and now it updates as expected. Must have been something hanging somewhere. 🙂
is it possible (or smart) to define "helpers" with a .yaml instead of 1 at a time with the gui. I have a lot to make and I feel like it would save a ton of time
(basically I want to make maybe 100 input_number helpers maybe 200)
Yes
awesome and what would the line in config.yaml look like for the !include statement (with this many I'm going to dedicate a .yaml to them)
input_number checks: !include checks.yaml
input_number: !include /path/to/file.yaml assuming you just want one file for it
right?
How would I write to format this with "strftime" so that it only show me date and timestamp?
Here's a cheat sheet https://strftime.org/
'{{ states.binary_sensor.occupancy_1_occupancy.last_changed.strftime("%H:%M") }}' for example
Thanks! If i try to change the template sensor to:
value_template: "{{ states.binary_sensor.baksidagarage_person_detected.last_updated.strftime("%H:%M") }}"
I get error, hm
Or should I just change the Dashboard card with that code , is that enough?
I looks like this now:
- sensors: kamera_garage_last_movement: entity_id: binary_sensor.baksidagarage_person_detected friendly_name: "Kamera Baksida Garage Senast Movement" value_template: '{{ states.binary_sensor.baksidagarage_person_detected.last_updated.strftime("%H:%M") }}' device_class: timestamp
You could just put it in the markdown card. You could also include the date, have a look at the link I posted for the codes to use
Ok will try, thanks!
Cool, it worked. Thanks 🙂
Learn something new each day here hehe
@buoyant pine I didn't say thankyou earlier. Thank You 🙂
Hello, I just want to take a random element from an array and use it like this: service: rest_command.jarvis_say_something data: text: mytestarray[line1,line2,line3,line4,...] | randomelement
data:
text: "{{ [line1,line2,line3,line4,...] | random }}"
Is it possible to do this?
template:
- sensor:
- name: "Plant Moisture"
unit_of_measurement: "%"
state: {{ states('input_number.moisture') }}
So I want a template sensor that show me the current dew point out of my Aqara temp/humidity sensors. How should that code look like? Hm
But you need some kind of calculation, maybe someone already have a working sensor and would like to share their code? :)
Maybe, but the math is probably googleable. I assumed you were looking for syntax
This was the top hit for me: https://community.home-assistant.io/t/calculations-for-dew-point/5145/5
Thank you! That seems to have all the maths 🙂 Thx. Must be better to check the forums first 🙂
Or at least a little google-foo 😉
Exactly that. Forgot the quotes!
Hello All, lets say i want to create a template sensor of type Select. and i want to push some data onto mqtt when such enttity changes. I could use the select_option key to run an action when an option is selected right?
the documentation is not very clear to me
The state of the entity will change to the selected option. So as trigger for an automation you could use a state trigger. But this is more a topic for #automations-archived if you are not asking about the actual Jinja templates
ok thanks
I hoped I could define the "action" to run when an option was selected
directly withn the select template.
Oh right, seems you can do that
@gentle ivy Sorry, haven't used one of those yet, but you are right
You can just use the same actions as in a script or automation
Use choose to determine actions based on the set option
hi, I have an adaptive lighting integration that takes its brightness and temperature values from a circadian sensor
problem is, it also adjust brightness but I don't need it to do that since the sleep mode already handles that
I need a template to invert the values of brightness from the circadian sensor because atm when it's bright it makes it very bright and vice-versa
(already turned the integration's brightness adjusting off so that won't get in the way - it just adjusts the temperature of the lights now)
platform: state
entity_id: sensor.pixel_4a_bluetooth_connection
attribute: connected_paired_devices
from: |
{{'00:02:5B:01:5F:D1' in state_attr('sensor.andreas_bluetooth_connection',
'connected_paired_devices') }}```
Why's it adding the | followed by the line break and the line break before connected_paired_devices') }}, and is that syntax ok?
Seems fine. The | is just one of the possible ways to indicate that the value assigned to the key (in this case from:) should be the result of a Jinja block over multiple lines. And sometimes the code editor in the UI will add in line breaks to make the code more readable. As long as the indentation is correct, there should be no issue.
I wanted to create an "other consumers" energy sensor by having my main consumption total and subtract my measured consumers total.
I get this error in the sensor template:
https://pastebin.pl/view/b8f40003
This is the preferences of the sensor:
device_class: energy
state_class: total_increasing```
Any ideas how I should approach this?
Please mention with notification on the above question. Thanks! 🙇♂️
When you do float(xxx, default = 'invalid number'), it returns a string if the state of xxx is not a number. This causes the error of not being able to add a string and an int.
The point of specifying a default is to avoid such an error, so specify a number instead of 'invalid number' as default.
Thanks DanielLeong, that's fine..
Did you notice the last line (47) in the log?
To me, it looks like that makes the template sensor not be able to be used in Energy dashboard... ?
Maybe I should ask in #energy-archived instead?
Yes, because the value of your sensor may decrease if the other consumers consume less energy today vs yesterday. But total_increasing requires the sensor's value to only increase over time. You probably want to change your state_class to total.
Humm, but consumption can't be total as I'm always consuming. (I have no energy producers in my setup).
Do you understand what I want to achieave with this template sensor?
Are all the sensors involved in your template of class total_increasing?
What the error indicates is that the sensor that takes the template had a value that decreased.
I have a 3phase sensor meashuring my consumed energy on my mains.
I also have several other energy consumer sensors for individual devices connected.
Now I want do deduct the individual devices from the mains so I get an "other individual devices" that aren't directly measured themselves.
Or was the result decreasing due to the (un)timely reporting from sensors?
Yes I was thinking that was the case. Some inaccuracy in your sensor readings.
Or the sensor reports just come in and every time it comes in, it recalcs the template.
If the Mains sensors aren't updated but an individual sensor does the template will have a decreasing value.
Yup exactly.
Can this be recalculated every e.g. 5/10 min ?
I've looked at this from all angles now, trying to use below in a condition, but it won't accept it. any clue?
value_template: {{ states('sensor.envoy_current_power_production') > (states('input_number.blinds_wattage_threshold')) }}
it says template value should be a string for dictionary value @ data['value_template']
I would advise to put in a condition to check that the new value is not less than the old value before updating the sensor's value. Because even if you set the update frequency to some value, the desync in individual sensors update times could still occur.
Humm, I was not aware of condidions in template sensors... ?
@floral shuttle posted a code wall, it is moved here --> https://hastebin.com/ijaruyaleb
I'll get looking at it ...
trying my first trigger template select:```
- select:
- name: Mode selector
unique_id: mode_selector
state: >
{{states('input_select.mode')}}
options: >
{{state_attr('input_select.mode','options')}}
select_option:
service: script.turn_on
data:
entity_id:
- script.mode_{{option|slugify}}_select```
- name: Mode selector
I get an error, not in the logs, but in the popup failed to call service. Service not found. but I can not check the template or the service it is trying to turn on. wondering if the template in the entity_id is parsed at all tbh, so please could anyone check with me?
option would be the state of the select, {{states('input_select.mode')}} as it is described in https://next.home-assistant.io/integrations/template/#select_option?
well, it says it can not find the option. that can be because of some other backend logic though. (i think i can fix that) whats more, I need it to parse both of these```
select_option:
service: script.turn_on
data:
entity_id:
- script.mode_{{option|slugify}}select
- script.scene{{option|slugify}}
would that be correct?
can you please just post the error
I don't want a 'translated error via marius', I'd like to see the actual error in the logs
hehe. its a bit hard to screenhot those popups, there fast than me (I am..?)
they appear in your logs
well, they dont. But the cause for that was found so no need to focus on that toaster error popup. I just want to make sure both of these scripts are turned on in the select_option, and I dont think we can trace that? nor can we check in in the dev tools template
about the popup, just try a non existing service in a service call on a button
script.turn_on is an existing service
so this is why I'm questioning waht the error is
because what you're saying doesn't make sense
let me reiterate: I have these buttoins in the frontend, with an underlying script call to a script. These scripts I am now trying to replace with this new (for me) trigger template select. I commented the original scripts in the yaml. so they no longer exist. The buttons however still use them. So clicking those buttons made the error popup....
So then what's the problem
I guess I don't understand your question
Are you just trying to ensure that the slugified is giving you the correct result?
I can not trace the execution of the 2 scripts, so I must presume they are not..
but there's no indication anywhere of an error
thats why I want to make sure the syntax I used is correct in the templates of the option field
alright, then you should be looking at sluggifying your sections from the input select
{{ state_attr('input_select.mode', 'options') }} returns ['Regular', 'Full house', 'Kiosk', 'Developer']
{{states('input_select.mode') | sluggify}}
so for the service calls I need them to be script.mode_{{states('input_select.mode')|slugify}}_select
or making a for loop on those options and outputting that and seeing if your script name is correct
typo!!
or? is it sluggify.., you got me confused now.... 😉. nope, no typo, its slugify .
I don't have it memorized
well this is correct: script.mode_{{states('input_select.mode')|slugify}}_select
then it should be running
the only thing I see is that you're using the old 'entity_id inside data'
so I guess the question is, can we write: select_option: service: script.turn_on data: entity_id: - script.mode_{{option|slugify}}_select - script.scene_{{option|slugify}} or should we write those as 2 separate services
yes, I use them inside the data field, because they are templates, and not entity_id's directly
you mean like: select_option: service: script.turn_on target: entity_id: - script.mode_{{option|slugify}}_select - script.scene_{{option|slugify}} ?
Yes
that's the current method you should try to use if you're creating something new. Although the old method should still work.
regardless, I don't see how your stuff isn't working.
Ok, thanks!. I'll leave like that (target) for now. Still, none of the scripts are traced, so I guess I need to see that as proof of an issue. Quite difficult not to be able to check if those templates are in fact seen by the backend. It's a bit like with the new This variable in self referencing templates: only way to find out if they are correct is by reloading and simply trying
right, so I made another conceptual mistake.... I was still using the regular input_select. entity to change modes, and not the new select. entity. Using the new select, I can in fact see the modes happening 😉
Still have to very much get used to using a trigger template instead of automations. I do notice an issue on reloading the template platform though, but have to investigate if thats because of restore or not, or some other error in my config.. anyways, thanks for now!
You don’t need a trigger template though and you aren’t using one?
You’re using a normal template entity.
right, you're spot on. I meant template select...
They work the same way as any other template entity
The state is defined by the template and the actions are performed based on the current state. With a select entity, the action isn’t actually executed via the state because it’s always the same. Select option. So its easier to understand
yes, and its very nice that I can now do away with many verbosely written subscripts, and have them all executed via 1 simple new template entity select. (I could maybe have done that before, but never had a trigger (....) to do so. This new functionality pushes me in the back just enough to want to try and experience that)
Petro, on the new This variable in templates, and it throwing errors in the log we can not mitigate, could you please have a look at https://github.com/home-assistant/core/issues/70359#issuecomment-1107923362 ?
I made this hideous thing, which works, but also gives empty brackets ("[]"): {% set areas = ["Hallway", "Kitchen", "Closet", "Living room", "Bathroom"] %} {% for area in areas -%} {{expand(area_entities(area)) | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list}}{{", " if not loop.last }} {%- endfor %} How can I prune these in a good way? They can be in front or behind, or both...
What are you actually trying to do? Get all the lights that are on in each area?
Yes, and returned in one variable
You need a | join(', ') after the list most likely... but right now you're combining arrays
Oh, that's where the brackets come from then...
for now use to display which lights, and how many
I will reuse this in my automations, or that's the plan 🙂
I think I'd like to have the output as an array if possible. Would it be possible to join those?
Hi guys, how can I calculate a power of 2 in a template? thanks!
ok. so would something like this work:
{{ (trigger.from_state.state - trigger.to_state.state)**2 }}
?
I would do it like this:
{% set areas = ["Hallway", "Kitchen", "Closet", "Living room", "Bathroom"] %}
{% set ns = namespace(l = []) %}
{% for area in areas -%}
{% set ns.l = ns.l + expand(area_entities(area)) | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list %}
{%- endfor %}
{{ ns.l | join(', ') }}
Combine all entities in a big list, and join that in a comma separated string
state_attr is "[DE:63:AD:73:7A:D1, E8:7F:6B:65:C9:2A]" so why does this return false
{{"E8:7F:6B:65:09:2A" in state_attr("sensor.pixel_4a_bluetooth_connection",
"connected_paired_devices") }}```
Because it's false 🙂
your attribute result looks like list, but it is a string
One has a C9 and the has a 09
Thank you! Works nicely 🙂
but that should not matter though indeed
Omg I'm blind, thanks lol
@noble fractal posted a code wall, it is moved here --> https://hastebin.com/pihifidube
It seems I posted too many lines of code to the above posting. I'm having a little trouble with a template sensor, I'm trying to assign a value of 0.0 if no other if of elif conditions are met, yet I still get an "Unavailable" value.
{{ state_attr('sensor.fireboard_one', 'latest_temps') | selectattr('channel', 'eq', 1) | map(attribute='temp') | list | first | default(0.0) }}
if your list is more than 5, then it'll still work. If you want to truncate it to 5...
{{ state_attr('sensor.fireboard_one', 'latest_temps')[:5] | selectattr('channel', 'eq', 1) | map(attribute='temp') | list | first | default(0.0) }}
I think I see, some of this templating is new to me. the channel value should be anywhere from 0 to 5 so I think this should be great
then just use the first one
Much thanks, this will certainly shorten my config since there are 6 of these in total, one for each possible channel value of 0-5.
yes checking now
The second one you provided does it perfectly. The first one seems to return 0 no matter the channel.
Again thank you very much I'll have to research the jinja to learn from this
@mighty ledge I was mistaken, the values are not 0-5, but 1-6 instead. Would it be correct to do it like this:
{{ state_attr('sensor.fireboard_one', 'latest_temps')[:6] | selectattr('channel', 'eq', 1) | map(attribute='temp') | list | first | default(0.0) }}
can you post the result from the template editor for this:
{{ state_attr('sensor.fireboard_one', 'latest_temps') }}
Currently it is:
[
{
"channel": 4,
"created": "2022-04-25T16:36:04Z",
"temp": 82.4,
"degreetype": 2
},
{
"channel": 6,
"created": "2022-04-25T16:37:05Z",
"temp": 82.4,
"degreetype": 2
}
]
the first template is what you want then, but channel 1 doesn't exist
It will only have values if a temperature probe is plugged into the associated channel
this:
{{ state_attr('sensor.fireboard_one', 'latest_temps') | selectattr('channel', 'eq', 1) | map(attribute='temp') | list | first | default(0.0) }}
that will traverse all temp sensors and return a value if it see's channel 1, otherwise it will be 0.0
if you want another channel, just change the channel number next to the 'eq',
That works! I'm testing them all now (takes 60 seconds for a full test of each channel).
Much thanks again
I'm a little confused here. I'm trying to make it so that when the device attribute's "from" includes "DE:63:AD:73:7A:D1" it triggers the automation.
I'm using from: ' {{"DE:63:AD:73:7A:D1" in state_attr("sensor.pixel_4a_bluetooth_connection", "connected_paired_devices") }}' which evaluates to true, but I'm not sure how to make it so that that triggers the automation, since the automation triggers when from matches the previous attribute state, rather than matching true
you should change the automation so that it triggers on any change to that sensor's attribute, and use a condition that checks that the value was in the "from" attributes and isn't in the "to" attributes
something. like:
trigger:
platform: state
entity_id: sensor.pixel_4a_bluetooth_connection
attribute: connected_paired_devices
condition:
condition: template
value_template: >-
{% set prev_devices = trigger.from_state.attributes.connected_paired_devices %}
{% set new_devices = trigger.to_state.attributes.connected_paired_devices %}
{{ "DE:63:AD:73:7A:D1" in prev_devices and "DE:63:AD:73:7A:D1" not in new_devices }}
action:
...
Trying to make a light template. In its most basic mode it works. However, I tried adding a transition to the set level, but that ens up breaking the template when I use the light it creates on a dashboard. Is there a way to make one light that includes transition ability, but does have to use it? IE, want to be able to use it in a dashboard (currently doesnt like it becuase doesnt pass transition), but also use it in an automation which may include transition
how did you specify it in the light template?
Attached the working template
this is something im trying to figure out here:
set_level: service: light.turn_on data_template: entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" {% if {{ transition != none }} %} transition: "{{ transition | float }}" {% endif %}
use choose
im not a jinja guru
ah ok i see. BTW, how would the condition work to see if transition was passed?
{{ transition is defined }}
cool
Sorry, tried to template, because modifying the light template to have choose got me a little confused. Think template would be simpler, but I'm getting transition not defined:
set_level: service: light.turn_on data_template: {% if {{transition is defined}} %} entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" transition: "{{ transition | float }}" {% else %} entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" {% endif %}
you can only template a single field
unless you get all tricky about it
I guess is choose the next level after set_level?
your choose would have the default without a transition as your action sequence
and with transition defined, it would contain your transition
@abstract cape posted a code wall, it is moved here --> https://hastebin.com/alojexegev
okay.. not sure why the bot called that a code wall..
@winter path this would also work, but if you don't understand code, you'll have issues changing it.
set_level:
service: light.turn_on
data: >
{%- set d = {'brightness': ((brightness) / 1.429) | int, 'transition': transition | float(0.0) } %}
{%- set kvps = d.items() | rejectattr('0', 'eq', 'transition') | list if transition is defined else d.items() | list %}
{{ dict.from_keys(kvps) }}
I know some code, but that is a little above my level. may use it because what I have with choose isnt working yet
set_level: choose: - condition: template value_template: "{{ transition is defined }}" sequence: data_template: entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" default: service: light.turn_on data_template: entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" transition: "{{ transition | float }}"
your template isn't in quotes
gack
your yaml doesn't look correct
You're missing conditions: and sequence: should be in line with conditions.
I have this sensor that pulls data from a googlecal which is already integrated into HA then selects the start time atrribute but the date format is not what I want. Can someone help me with the timestamp_custom syntax to get it to display %d/%m/%Y
It is displaying the data like this atm 2022-04-30
My code for the template is here - https://paste.debian.net/1239004/
you can do this:
{{ state_attr('automation.alarm_notifications', 'last_triggered').strftime("%d/%m/%Y") }}
or this:
{{ state_attr('automation.alarm_notifications', 'last_triggered')|as_timestamp|timestamp_custom("%d/%m/%Y") }}
this is throwing the following error for me when i try to test the condition:
"template value should be a string for dictionary value @ data['value_template']"
Can anyone maybe give me a hint how I can get a comma separated sequence/list/array of all „input_datetime“s that have „has_date: false“ ?
how are you testing it?
with the "test" button in the conditions section of the automation
@inner mesa like this - {{ state_attr('calendar.aston_villa_fixtures', 'start_time')[0:-9].strftime("%d/%m/%Y") }}
I don't know why you're doing this: [0:-9].
to remove the time
i need to this is the point of making this value template to just get the date and nothing else
and if it's really a string, then you need to may need to use strptime() on it first
I know, that's what the last part does
it takes a datetime and formats it to just output the date
try it
ohh, okay, thanks
you can't do that because it won't have a trigger
That button doesn't work for template conditions. It's a bug
@obsidian lintel posted a code wall, it is moved here --> https://hastebin.com/sosoqisuhu
For some reason, I cant seem to set the color
@obsidian lintel posted a code wall, it is moved here --> https://hastebin.com/avihopixoq
Full code is here ^^
I can't seem to find any documentation on how to change the icon color in the modern template sensors. Under legacy there was icon_color. I currently have a template.yaml with the following contents. I want to make the icon Red if off and Green if on.
name: "Alarm Status"
state: "{{ states('input_boolean.alarm_status') }}"
icon: mdi:shield-home-outline```
Can anyone point me in the right direction?
I am trying to create a demo light entity
Okay, I figured out how to do this using themes instead
I will legit pay somebody to help me out been trying this for months
@obsidian lintel posted a code wall, it is moved here --> https://hastebin.com/nizofonazo
I have updated the code, this seems to work but I cannot use the color radio selector as set_color: does not seem to be working
Hence I am not able to update the values of Hue and Saturation through set_color to my input_numbers.
Means I have to use 2 entities to control the color hahaha
$100 for me to tell you search 'demo' in integrations.
Hey petro, I know about demo integrations, however they only provide 6 RGBW light entities. I need more than that. I have tried to edit the lights.py file under custom components, messed around with entities and devices registry however it just keep having an error of unavailable.
why do you need more than 6...
Hence I just decided to do templates. I managed to get something working by cheating a little but set_color: doesnt seem to update my input numbers.
I need more than 6 because I am trying to build a demo floorplan which have color sync. I need some more because I happen to have a lot of lights in this floorplan hahaha, that includes lamps!
Wish I could send a video here to show what I am going through now haha
Is it possible?
Why not alter the demo code to just give you like 30 lights
you can copy the whole demo integration as a custom integration and then just add lights to this section
I'll save you the Picard meme...this time...
Hi everyone. Need a hand with template to get the time when the probability of rain is high. I have a weather sensor that lists probability % in a hourly array (list?) like that:
``
forecast:
- datetime: '2022-04-26T02:00:00Z'
temperature: 21
condition: sunny
precipitation: 0
precipitation_probability: 10
wind_bearing: WNW
wind_speed: 24
...
What I want to do use it in an automation with say an hourly trigger and a condition of rain probability in this hour (when automation is triggered) > 80%. I just dont understand how to filter the info 😦{{ state_attr('weather.hocking_hourly', 'forecast') | map(attribute="precipitation_probability") | list }}``
will give me a list of %, but how do I just filter for the current hour?
Is the current hour just the first item in the list? You can just index into the list with [0]
I.e. {{ (state_attr(...) | list)[0] }} or something similar, if the current hour's forecast always appears in a predictable position in the list.
trying to figure out why this evaluates to "false"
condition: template
value_template: >-
"None" in trigger.from_state.attributes.error and "Dust collector missing" in
trigger.to_state.attributes.error```
im almost positive the state is changing from "none" to "dust collector missing"
this is the full code https://www.toptal.com/developers/hastebin/raw/detolaqizi
Unfortunately not, as it depends on the time when it updated the forecast. So need to get the time as well
``forecast:
- datetime: '2022-04-26T03:00:00Z'
temperature: 21
condition: rainy
precipitation: 0
precipitation_probability: 20
wind_bearing: WNW
wind_speed: 22 - datetime: '2022-04-26T04:00:00Z'
temperature: 21
condition: rainy
precipitation: 0
precipitation_probability: 20
wind_bearing: WNW
wind_speed: 22``
You have 'is' and not 'in'
you mean the other way around?
Nope
oh, i changed it to see if that would make a difference
The part above doesn't match your link
it was in before
How do you know that that's the condition blocking the automation?
the debug shows that it makes it past the first conditions but evaluates false to the second
then says "Stopped because a condition failed at April 25, 2022, 11:34:08 PM (runtime: 0.00 seconds)
I suggest using a persistent_notification to display what the value is each time it changes
like make a simple automation that shows the status in a persistent notification?
Sure, or just remove the condition and add a persistent_notification in the action
i think its the fact that the value of the attribute is "none"
when the state is dustbin whatever, the notification shows fine, but when its "none" it errors out
OK, I mostly figured it out. But now need to somehow get the current time/date 🙂
{{ state_attr('weather.hocking_hourly', 'forecast') | selectattr("datetime", "eq", "2022-04-26T05:00:00Z") | map(attribute="precipitation_probability") | float > 20 }}
same, when i create a persistent notification where the state is "none", i get Failed to call service persistent_notification.create. template value is None for dictionary value @ data['message']. Got None
now()?
Then you just manipulate the string to get the next hour, if that's what you're looking for.
2022-04-26T05:00:00Z in the data is in UTC
utcnow() then? Anyway the options for handling time in templates is in https://www.home-assistant.io/docs/configuration/templating/#time
yes, thank you. Found it
the further I go, the more issues I get 🙂
Stupid, I know, but how do I combine and compare strings? Like if I wanted to compare 12 characters of one string to another?
somestring1[x:y] == somestring2[x:y], where x and y denote the positions of the first and last characters to extract from a string. Zero-indexed of course.
nice and easy 🙂
So if you want say the date part of your UTC timestamp, you'd do '2022-04-26T05:00:00Z'[0:10], or for similar effect, '2022-04-26T05:00:00Z'[:10]
problem I have is that I need to compare something like this from UTCNOW 2022-04-26T05:34:13.957763+00:00
to something like this from the sensor value 2022-04-26T05:00:00Z
I get the right string with this utcnow().isoformat()[0:14]~"00:00Z" (2022-04-26T04:00:00Z), but when I use this like below, it does not work
{{ state_attr('weather.hocking_hourly', 'forecast') | selectattr("datetime", "eq", utcnow().isoformat()[0:14]~"00:00Z") | map(attribute="precipitation_probability") | float > 20 }}
So i "solved" my issue by not looking for the "none" state. Maybe the devs should look into allowing states named none? since I'm guessing it's a bug/oversight
ok, done 🙂
{{ state_attr('weather.hocking_hourly', 'forecast') | selectattr("datetime", "eq", utcnow().isoformat()[0:14]~"00:00Z") | map(attribute="precipitation_probability") | join | int > 70 }}
When I create a sensor for the thermometer of an AC unit, do I have to specify a trigger in order to have it updated at state changes?
- name: "Temperatura Outdoor"
unit_of_measurement: "°C"
state: "{{ state_attr('climate.midea_ac_xxxxxxxxxxxx', 'outdoor_temperature' ) | float }}"
icon: mdi:thermometer```
with this template it seems not updating at all
I'm not ever sure whether I should use a template or a sensor ... this thing confuses me quite a lot:
sensors:
outdoor_temperature:
friendly_name: "Temperatura Outdoor"
unit_of_measurement: "°C"
value_template: "{{ state_attr('climate.midea_ac_xxxxxxxxxxxx', 'outdoor_temperature' ) | float }}"
icon_template: mdi:thermometer```
These two approaches seems like bringing the same result.
The first one is the new format, the 2nd one the old legacy format
both have the same result
the new format supports state_class for example, which is not supported by the legacy format. And the new format has the option to provide triggers
But both should update on state changes of the entities used in the template used for the state
Thank you for the clarification.
At this point I suppose that the climate entity does not update unless manually triggered. It's a custom integration that works through a local api over LAN.
- platform: time_pattern
minutes: "/1"
sensor:
- name: "Temperatura Outdoor"
unit_of_measurement: "°C"
state: "{{ state_attr('climate.midea_ac_xxxxxxxxxxxx', 'outdoor_temperature' ) | float }}"
state_class: measurement
icon: mdi:thermometer```
This won't work either. Is syntax correct?
define won't work
it shows a state but not the right one? This won't update your climate entity, it will just update the template sensor every minute, but if your climate entity doesn't update, so won't the template sensor
You might be better off leaving your template as you had it, and create an automation with a time pattern to update your climate entity every minute using homeassistant.update_entity
At the moment when I check the sensor history it says "last updated 1 hour ago" and "last changed 1 hour ago" and keep showing the value of when I saved and reloaded the template, 1 hour ago.
but did the state of the outdoor_temperature in the climate entity change?
fear This https://github.com/home-assistant/core/issues/70359 is going to be an issue during the beta tomorrow..... currently there's no way we can prevent it from happening, nor should we have to (add a default to the This variable imho). This ought to be taken care of in core natively
nope, it does only change when I trigger some of the AC actions or when I reload the sensor template
refered from #automations-archived , I'm trying to get this condition to work: value_template: "{{ (states('sensor.envoy_current_power_production')|float) > (states('input_number.blinds_wattage_threshold')|float) }}"
but it keeps telling me template value should be a string for dictionary value @ data['value_template']. Got None
Now I'm sure I'm doing smth stupid, but can't see it anumore
hello, how can I put different actions under one event_data
- platform: event
event_type: mobile_app_notification_action
event_data:
action: 'LOCK_FRONTDOOR'
# - platform: event
# event_type: mobile_app_notification_action
# event_data:
# action: 'UNLOCK_FRONTDOOR'```
I want something like: ```event_data:
action: 'LOCK_FRONTDOOR','UNLOCK_FRONTDOOR'
maybe templating can help here..
Where and when does it say that?
On testing or trying to save the automation
And the condition should look like this:
- condition: template
value_template: "{{ template }}"
Yes it is formatted like that
Put the check in actions in a template condition, or use two triggers, like you already had
.share the whole automation
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Your condition would be something like:
- condition: template
value_template: "{{ trigger.event.data.action in [ 'LOCK_FRONTDOOR', 'UNLOCK_FRONTDOOR' ] }}"
Aside from an unnecessary "- condition: and" and some unnecessary parentheses, I don't see anything wrong with it. Could just be the UI not liking templates
yeah the unnecessary stuff was UI created. lemme check doing it manually...
Well you most probably added the and condition yourself, the GUI doesn't do that magically.
I have to admit I cheated and pasted that condition in 😉 now I just added it directly in YAML and indeed it seems to work. thanks guys
but then, what would I be having in trigger part?
The idea is to have just one trigger platform, not the same xy triggers with different actions
@chilly locust posted a code wall, it is moved here --> https://hastebin.com/ehetulerib
I'm working on a "daylight remaining" sensor but I'm having some trouble with my value template. Overnight I want it to show the total daylight calculation for the coming day. I'm not super familiar with the jinga2 so help is appreciated!
- Line 6 doesn't like the &&. How do I put 2 parameters together for the if statement in Jinja2 format so it only counts down between dawn and dusk?
- Line 9 (the else statement) doesn't like the " - " operator because it thinks that "tomDawn" is null and "tomDusk" is "1651108901.21984". So I guess I'm not setting the variables correctly, because neither of those are a timestamp like they should be.
- My < and > operators only work opposite of what I think they should, which I'd like to understand.
Do i have a syntactical error here with my GPS coordinates? I'm getting the error "None for dictionary value @ data['gps']. Got None"
service: device_tracker.see
data:
dev_id: buds_live
location_name: '{{states(''device_tracker.pixel_4a'')}}'
gps: "{{state_attr('device_tracker.pixel_4a', 'latitude' )}}", "{{state_attr('device_tracker.pixel_4a', 'latitude' )}}"
gps_accuracy: '{{ state_attr(''device_tracker.pixel_4a'',''gps_accuracy'')|int }}'
I'm trying to have a template entity report it's last value if the underlying sensor it uses is reporting unknown, but what I have seems to fail after a restart:
{% set current = states('sensor.logitech_g_pro_mouse_power_level') %}
{% set previous = states('sensor.logitech_g_pro_mouse_battery') %}
{{ ((states('sensor.logitech_g_pro_mouse_power_level')|int - 3500|int) / 740 * 100) | round(2) if current != 'unknown' else previous }}
What am I doing wrong here?
I assume I'm missing something about the behavior after restart, but I'm not sure what the correct solution looks like
Something like this is what I use:
{% if is_state('sun.sun', 'above_horizon') %}
{{ (as_timestamp(state_attr('sun.sun', 'next_dusk')) - as_timestamp(now())) | timestamp_custom('%Hh %Mm %Ss') }}
{% endif %}
Though I should note, I only use that in the the template editor when I’m debugging my lux sensors
There’s a few Jinja links in the pins, but Python uses and rather than &&
Woo! That part worked. Now to try and workout why the attributes are being weird.
I want to craft an if statement that checks a value within 2 boundries. what do I add to this {% if (tent - ambient) > (-100) %}
I want it to be if (tent - ambient) is > -100 and <100
think i got it
{% if ((tent - ambient) > (-100)) and ((tent - ambient) < (100)) %}
true
{%else%}
false
{%endif%}
can i do something like this?
in the template, this is evaluating to false, when it should be trice
so im not sure if this isnt allowed, or if i did something wrong
you have extra quotes
and it's too compliated
{{ is_state_attr('device_tracker.buds_live', 'latitude', state_attr('device_tracker.pixel_4a', 'latitude')) }}
thanks, didnt realize that
trigger:
- platform: event
event_type: mobile_app_notification_action
You can also use {% if -100 < (tent - ambient) < 100 %}
Hi,
Trying to replace an item in list from a namespace like:
{% set list = namespace(l=[ "test", "two", "three" ]) %}
{% set list.l[0] = "one" %}
But of course it doesn't work :P
How should I do it?
@frank gale
{% set list = namespace(l=[ "test", "two", "three" ]) %}
{% set list.l = [ "one" ] + list.l[1:] %}
{% set list = namespace(l=[ "test", "two", "three" ]) %}
{% set list.l = list.l | replace("test", "one") %}
{{ list.l }}
This also like like it seems to work, but then {{ list.l[0] }} returns [ so it is actually a string.
If you store it in a variable in your script or automation though it will work as a list
Nice, thanks!
how do i use state.attributes? i used it yesterday but i cant find any documentation and cant remember how to use it for the life of me
state_attr(entity, attribute)
Oops, that's not the one i was thinking of. I'm looking for the one that lists all attributes got state
Please be more clear then, I don't understand what you mean
@silent vector posted a code wall, it is moved here --> https://hastebin.com/kotuhahovu
I would advice to not turn off automations, but use the state of the binary sensor as a condition in the automation instead
That's interesting I never thought of that. It's for when my cameras go offline (blue iris) and frigate would then see a gray screen and if someone is there suddenly the lights would turn off on them. The hallway motion sensors are an example I'm in the process of setting up mqtt sensors as I currently just listen for a specific payload for each camera if they go offline
I thought adding default would prevent this? ```
Template variable error: 'value_json' is undefined when rendering '{{ value_json.wifi_sta.connected|default(false) == true }}'
What is the correct way? Something like this? {{ if value_json value_json.wifi_sta.connected else false }}
it only prevents the first level
if value_json is not populated because the incoming data is not json, it will fail at the first .
{% set data = value_json | default(none) %}
{{ data.wifi_sta.connected | default(false) if data else false }}
you also don't need == true as true/false resolve to true/false
Thanks petro
hey was hoping someone can help me. How can I modify this {{ is_state('input_select.status_' ~ name, 'Just Left') }} to determine if input_select.status_ ~name is 'Just Left' and previous state is not 'Just Arrived'?
This would also work I guess
{% set data = value_json | default({}) %}
{{ data.get('wifi_sta', {}).get('connected', false) }}
I have data coming in from a rest sensor, but since the data contains {"title":null,"note":"cooked shrimp }
instead of {"title":"null","note":"cooked shrimp } the data isn't being read in correctly. is there an easy way to ignore null or replace them if they exist with correct values?
there is double quotes around all other values, although as I see not in my pasted example, but the data appears otherwise correct to me.
should actually read {"title":null,"note":"cooked shrimp" }
I've used a file editor and manually done a replace on all and then used that in the template editor in dev tools.... works beautifully.
Hi everyone. The docs say: LIMITED TEMPLATES Templates for some triggers as well as trigger_variables only support a subset of the Home Assistant template extensions. This subset is referred to as “Limited Templates”.
and TIME now() and utcnow() are not supported in limited templates.
so I thought that to trigger an automation 15 minutes before a time helper, I was going to need to do something complicated....
BUT, this works:
`alias: '!a light on for morning'
description: Turns on at boys morning time unless the late morning toggle is activated
trigger:
- platform: template
value_template: |-
{{ now().strftime("%H:%M:%S") ==
(today_at(states("input_datetime.boys_morning"))-timedelta(minutes=15)).strftime("%H:%M:%S")
}}`
so, what am I misunderstanding about the docs? or are the docs wrong?
template triggers are not limited to limited templates
Hi all, I'm looking for a bit of help translating a template that works in Developer Tools -> Template into a condition for use in an automation. I'm trying to find out if my phone has received a new notification in the last 60 secs. How do I reformat the following: {{as_timestamp( now()) - as_timestamp( states.sensor.phone_last_notification.last_changed) < 60 }} ?
condition: template
value_template: >
"{{(as_timestamp( now()) - as_timestamp( state_attr('sensor.pixel_3_xl_last_notification','last_changed'))) < 60 }}"
gives me "template value should be a string for dictionary value @ data['value_template']. Got None" when I Test it.
'''
The test button doesn't work for template conditions, it's bugged
If the template works in
> templates, your condition should be fine this way
more data, if useful: https://www.toptal.com/developers/hastebin/erorexoyik.coffeescript
@marble jackal Thanks 🙂 That kept me 'entertained' for a few hours!
how can I start an automation when any input_boolean with that filter: {{states.input_boolean |selectattr('object_id', 'search', 'is_mitv_on_')|map(attribute='entity_id')|list }} is switched from off to on ?
something like this? ``` alias: input boolean changes
description: ''
mode: single
trigger:
- platform: template
value_template: |-
{{states.input_boolean |selectattr('object_id', 'search',
'is_mitv_on_')|map(attribute='entity_id')| count | >1 }}
condition: []
action: - delay: '' ```
I don't understand, can you elaborate?
That’s not a limited template field
You’d literally see the phrase: limited template in the description of the trigger if it was a limited template
E.g.
Thank you... There must be a more clear way to describe these cases of limited templates on trigger fields than just template triggers, when there is an entire trigger platform that is template.
It would also be nice if you could use a template to specify a time for a time platform trigger, but I couldn't get that to work even if a template was properly rendering a formatted HH:MM:SS string
Templates are only allowed in fields that specify templates are allowed. Rule of thumb: if it doesn’t mention templates, it doesn’t support templates.
bit stumped here on why this wont work here
{% set brightness = (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round) %}
{%if is_state('sensor.light_sensor_illuminance', "<2") %}
75
{%else%}
{{brightness}}
{%endif%}
it always evaluates to false
and its got something to do with the < sign im prety sure, but i dont exactly understand what
also it seems i cant set variables in call service, or im doing it wrong, how can i simplify this?
service: light.turn_on
data:
transition: 0
brightness_pct: {{75 if (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round) > 75 else (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round)}}
target:
entity_id: light.fan_lights_group
what i wanted to do was this, but like i said, variables didnt seem to work how i did it:
{{75 if brightness > 75 else brightness}}```
The error here is in your if statement
{% if states('sensor.light_sensor_illuminance') | float < 2 %} will work
The error here is that you should place quotes around your template if you use a single line format.
service: light.turn_on
data:
transition: 0
brightness_pct: "{{75 if (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round) > 75 else (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round)}}"
target:
entity_id: light.fan_lights_group
gotcha, thanks
No idea why the bot thinks it is not valid yaml though
so, can you use variables in there, or no? cause its much harder for my eyes to parse without variables 😅
yes
same way, just quotes around it?
Use the > to indicate you are using multiple lines
service: light.turn_on
data:
transition: 0
brightness_pct: >
{% set brightness = ( 75 - ((( sqrt('states('sensor.light_sensor_illuminance')' | float - 2)) / 75) * 75) | round) %}
{% if states('sensor.light_sensor_illuminance') | float < 2 %}
75
{% else %}
{{ brightness }}
{% endif %}
entity_id: light.fan_lights_group
Oh, I see what is wrong in the other code as well now
You use both single quotes and double quotes in your template, and that doesn't work if you also need to put quotes around it because of the single line notation
service: light.turn_on
data:
transition: 0
brightness_pct: "{{75 if (75-(((sqrt(states('sensor.light_sensor_illuminance') | float - 2))/75)*75) | round) > 75 else (75-(((sqrt(states('sensor.light_sensor_illuminance') | float - 2))/75)*75) | round)}}"
target:
entity_id: light.fan_lights_group
Don't know why you placed those double quotes there BTW, they were not needed at all, and I would even expect they were causing the calculation to fail
i guess im still a bit unclear on when to use single and double quotes
Doesn't matter which one you choose, but use the one you've chosen consistently in your template
So you can use the other one around the template in case of the single line notation
got it
Does anyone know how to add custom attributes to sensors etc, using templates?
you can add them to a template sensor, but not to an existing sensor coming from another integration
Yeah I've got template sensors, but ideally wanted them as part of the attributes of another sensor
You can add attriubtes using customize.yaml, but I don't see template support mentioned in the docs
So if you want to use templates for your attributes, the only way is to create a template sensor out of the existing sensor, and add the attributes there
Can someone shred me some light on why this is happening?
this?
You can now
@gentle ivy posted a code wall, it is moved here --> https://hastebin.com/ocotocukad
Well
Your else 'None' kicks in
thus None = nothing = empty
Meaning select.prism_garage_wanted_status != Charge
Iol didn't know that "None" is a keyword
Yeah is it
BTW, bit unrelated, but please don't do:
states.select.prism_charge_priority.state
Use states('select.prism_charge_priority') instead
This statement states.select.prism_garage_wanted_status.state == 'Charge' is already false, so it already doesn't care about the rest
that's why it mentions it only listens to that one entity
And the other "issue" is that the HA template engine converts None to null, but in the template editor it only does that when it doesn't show anything else
It also converts strings which look like a list to a list
{% set test = "None" %}
{{ test }}
Returns null
That is intentional behavior though
I got an entity that returns a list of values (next departures of a tram), so far I got this in a Mushroom template (is there an easier way than referring to the specific sensor? The Mushroom thing allows you to pick an entity within the GUI but the documentation doesn't mention anything about it.
Następny o {% for state in state_attr('sensor.rozkladzik_poznan_2977', 'list') %} {{ state[2] }}
{% endfor %}
However, this returns all the values from the list, and I'm only interested in the [1-2] range. Is there any way to go about it?
{% set test = "None" %}
Result: {{ test }}
Returns: Result: None
Hi Guys when playing with History_stats is there anyway of previewing it before you add it to configuration.yaml?
I know, but it can be a bit confusing. The template editor might show a list as result, and also reports the result is a list, but when you then try to take a list item out of it by use of list[0] your get [
Example here: #templates-archived message
Hmm right, although in that case it tries to modify a collection, which is disabled in general
{% set list = [ "test", "two", "three" ] %}
{% set list = list | replace("test", "one") %}
{{ list }}
This does return:
Result type: list
[
"one",
"two",
"three"
]
But then list[0] returns [
{% set list = [ "test", "two", "three" ] %}
{% set list = list | replace("test", "one") %}
{{ list.replace('[', '').replace(']', '').replace("'",'').split(', ')[0] }}
Returns one, but is of course a bit ugly 😛
interesting
That is not an Home Assistant output parsing issue though
lol that is actually correct
replace() is a string method
it returns a string
not a list
But if you would put it in a variable in an automation or script, you would have a valid list to work with 🙂
Sure, as the result of a template is parsed again
but that doesn't mean inside the template you have to work with the restrictions there
the results of replace() is a string, getting the [0] of a string returns the first character of that string
in the case above its a [
Yes, I understand what is happening, but because the template editor already shows it is a list, while it actually is a string, can be a bit confusing 🙂
I agree. It makes the template editor a less useful tool.
First one is a string, 2nd one a list.
Depends on the scope
within the template: Yes
Jinja doesn't retain types in its result, not much we can do about that
(would love to see they added that though)
That returns None because the post typing resolver resolves everything in the template editor. When you omit the word Result: the resolver sees none and converts it to the type it expects.
Maybe we can add a dropdown on the left hand side to disable the resolver or not. Either way, if it looks like a list it's always going to look like a list. Not much you can do about that
the old template editor had that problem as well
any string that looked like an object fooled the user.
it's a damned if you do, damned if you don't situation IMO
at least in this mode, we can always see what HA will see when you supply just the template without extra fluff
maybe we should add a note that says something like: "For the best results, only use a template here, do not paste your entire YAML"
Or maybe add a few modes to the template editor: single template, multi line template, yaml included template.
Single will behave like it does now
Multi line will treat every yaml output as a separate template to resolve
And yaml included will take any shape yaml and resolve all endpoints as templates
How would I get this sensor to update to off when the server is down. Right now when I tested it all I got was an erorr because timed out when ideally it would actually update the sensor to off because a timeout would mean the server is offline.
- platform: command_line
name: Blue Iris Status
scan_interval: 8
command: /bin/bash -c "(echo > /dev/tcp/192.168.1.246/81) > /dev/null 2>&1 && echo on || echo off"
Error:
Timeout for command: /bin/bash -c "(echo > /dev/tcp/192.168.1.246/81) > /dev/null 2>&1 && echo on || echo off"
Warning:
Updating command_line sensor took longer than the scheduled update interval 0:00:08
#integrations-archived please
Got it. I wasn't sure where to post this.
is there any way to set a certain value for counters the same way you could variables? Is there a way to use them in a template sensor to have counter.yyy + input_number.xxx
you can only increment a counter, you can not set it to a value
you can set an input_number to a value, and you can use templates for that
oh wait, you can probably use counter.configure
ah I see, yes I missed that in the docs but I see it now
I can probably use that as a value template
I'll have a play around - thanks 🙂
@lime olive posted a code wall, it is moved here --> https://hastebin.com/ahabitezax
oops
What are the parameters value and default here: as_timestamp(value, default)
I'm trying convert Now() to a Unix timestamp and i don't know which one that is and what the other one is supposed to be
now() would be the value then, and the default would be a default in case it is not possible to convert the value to a timestamp
as_timestamp(now(), 0)
as_timestamp('this is a string', 'hello') would return hello
I'm trying to make a binary sensor to read out if the garage door has been used in the past # seconds. Unfortunately I can't use the "last_change" thing because that generates a lot of false positive. How do I format it so it focuses on specific states like "open" and "closed"?
Not if you're using the UI. But you can add alias: xxx in a number of places to document steps, and that also ends up in the log
It sounds like there are attributes that are changing and causing trouble for last_changed. You could create a template sensor just for the state of that entity and then use last_changed on that
well more specifically the state (not an attribute) will sometimes go to "unavailable" for a few seconds. My best guess is it briefly loses and regains connection. Regardless, that counts as a state change and I want a template that can ignore that specific state. I'll settle for one that can just tell me if the garage door's state has been "open" in the past # seconds
if i had a note, will it show up in step details? i'd like the step to show me one of the variables used, for debugging purposes
I'll settle for one that can just tell me if the garage door's state has been "open" in the past # seconds
also can i add variables at the start of the automations yaml, and have it use them throughout?
that should be a simple state trigger with for: '00:00:05'
but if it's flipping state to other things, that's going to cause problems. Hence my suggestion to make a template sensor that reflects exactly the state you want, and use that
Can someone help me I know this is super simple but templates baffle me. I am trying to set a date time sensor to the current date
data:
date: {{ now().day }}
target:
entity_id: input_datetime.last_hair_cut```
This isn't working its just what I have at the moment
Try date: "{{ now().day }}"
The first rule of templates is...don't talk about templates. And always surround single line templates in quotes.
Sorry, what would that template look like?
a binary template sensor with this:
It should start and end with a quote at least.
{{ is_state('sensor.whatever', 'open') }}
Ok hate to beat a dead horse to death but uhhhh still not working??? This is what I have
data:
date: "{{ now().day }}"
target:
entity_id: input_datetime.last_hair_cut```
and you can even add delay_on: 5 or whatever to that if you only want it to be true if it's been that way for x seconds
Thanks man
now().day is just a number
Ok does that mean I need to interpret that into an actual date?
you need to give it something that it understands: https://www.home-assistant.io/integrations/input_datetime/#input_datetimeset_datetime
all in the docs
if you just want a number, use an input_number
Note to self: Check what it takes to make date: now valid for that service call.
yeah, I feel bad for others and often myself when needing to figure out how to format a datetime using a template to get it into a usable format
we really need a non-template way to do normal things
the easiest way to just get today's date into an input_datetime is maybe with this:
data:
timestamp: "{{ as_timestamp(now()) }}"
Seems to work!
That would be great @inner mesa but just to make it clear I'm grateful for the people who take the time to develop and support what we have.
now().date() instead of now().day
oh, hey, that formats it properly
still, I try to avoid anything that relies on specific string formatting if I can
Gives exactly the same result as this though :)
But it would be nice if we could simply input now as @charred dagger suggested
can i do
condition: state
entity_id: light.fan_lights_group
attribute: brightness
state: {{is not '79'}}```
or != 79
or something of the sort
you'll get a not: directive in the upcoming 2022.5, but you can use this in the interim:
condition: template
value_template: "{{ not is_state_attr('light.fan_lights_group', 'brightness', 79) }}"
or update to the beta and enjoy not: https://rc.home-assistant.io/blog/2022/04/27/release-20225/#and-there-is-even-more
how do you put yaml code in that box in discord
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
It's pretty universal now. Slack supports it, too
I'm trying to set up template sensors but as soon as I create more than one, my YAML editor says "duplicate key" next to template
template:
binary_sensor:
- name: "occupancy patio"
state: >
{{((((as_timestamp(now()) - as_timestamp(states.binary_sensor.patio_contact_sensor_contact.last_changed)))) < 300) }}
template:
binary_sensor:
- name: "occupancy button"
state: >
{{((((as_timestamp(now()) - as_timestamp(states.sensor.aqara_button_action.last_changed)))) < 300) }}
right, you can't have duplicate keys
luckily, you don't need them
see the example right above this: https://www.home-assistant.io/integrations/template/#rate-limiting-updates
template:
binary_sensor:
- name: "occupancy patio"
state: >
{{((((as_timestamp(now()) - as_timestamp(states.binary_sensor.patio_contact_sensor_contact.last_changed)))) < 300) }}
- name: "occupancy button"
state: >
{{((((as_timestamp(now()) - as_timestamp(states.sensor.aqara_button_action.last_changed)))) < 300) }}
Now it says "incorrect type. expected "array".
you're not following the example
template:
- binary_sensor:
- name: "Has Unavailable States"
state: "{{ states.sensor | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"
yeah I don't understand the example other than the fact that I don't need template and sensor for each new one
it's right - you need to provide an array
you have
template:
binary_sensor:
the example has
template:
- binary_sensor:
ah
the first says that template is a dict, and the second says that it's an array/list
this is evaluating false, even though i have the template tool open and its evaluating true there
step details say
conditions/2
Executed: April 28, 2022, 7:18:04 PM
Result:
result: false
entities:
- sensor.light_sensor_illuminance
- light.fan_lights_group```
i have the exact same thing plugged into the template editor and it say true
where did you put the Jinja code in the link you posted?
the quotes are almost certainly misplaced
where in the automation? right below 2 other conditions
you just provided a bunch of Jinja code
its a condition within the action section, if thats what youre asking. i can post the whole thing if thats what youre asking, its a bit messy..
without knowing what's actually returning "false", I can't help much
the code i posted was the section thats returning false. ill paste the whole step config
@analog nova posted a code wall, it is moved here --> https://hastebin.com/cugosayawe
this part should not be in quotes:
"{{ not is_state_attr('light.fan_lights_group', 'brightness', (bright*2.55)|round) }}"
quotes only belong around single-line templates
got it, my bad. thanks
np, I wanted to see the context to make sure I was right without guessing
Trying to write a template so that it returns "true" if at least one of these three conditions returns true:
{{ is_state('binary_sensor.occupancy_button', 'true') }}
{{ is_state('binary_sensor.occupancy_garage_door', 'true') }}```
its still evaluating false. i moved it to the condition section now, so this is the whole step config https://dpaste.org/fNQPr
and or between them
or
{{ is_state('binary_sensor.occupancy_button', 'true') }}
or
{{ is_state('binary_sensor.occupancy_garage_door', 'true') }}```
no
it's one template
{{ is_state('binary_sensor.occupancy_patio', 'true') or
is_state('binary_sensor.occupancy_button', 'true') or
is_state('binary_sensor.occupancy_garage_door', 'true') }}
just like you're writing a sentence
ah sweet
might have fixed my problem
your problem may be that is_state_attr doesn't like a numeric comparison
I would do:
{{ state_attr('light.fan_lights_group', 'brightness') != (bright*2.55)|round) }}
wait, actually i think that did it
it's probably trying to do a string comparison or something silly like that
actually, it didnt work..
testing for equality with floating point numbers is usually a bad idea, anyway
yeahh...idk why it wont work
i wish it showed me the output instead of just saying false
oh well, guess ill jsut remove it for now. maybe itll work better when "not" is available in the full release
I think you'll be better off with > or < than == or !=
and you can always display the components and result of the calculation with a persistent_notification to see what they really are
ok well so far ive figured out that > and < both are still false, so theres somethings wrong
i dont really get this. the peristent notification shows them as not equal 176 and 191, but the template sees the equation as false
Hi all,
I'm trying to build an automation that will trigger when the garage door has been "forgotten" open.
Sensors in the garage:
- Espresense that detects the wife's or my phone
- Motion sensor
- Garage door reed switch
Conditions of the automation would be that we haven't been in the garage for 15mins
I'm confused over how I would build this. If the garage has been open for 14 mins and I go in to get something, I don't want it to close.
So every time we go into the garage, the trigger has to be reset
Here are the sensors and states:
- binary_sensor.garage (garage door - on/off)
- binary_sensor.garage_motion4_occupancy (motion sensor on/off)
- binary_sensor.rani_or_yara_in_garage (on/off) - Based on phone BLE presence, either phone within range will turn it on
Binary sensor states are on or off, not true or false
Hello, I am having trouble passing some JSON data via template to the restful notification integration. I wrote details here, if any of you could help me out: https://www.toptal.com/developers/hastebin/cugosayawe
is it possible to have a jinja as the result of a jinja if?
{% if value_json.cmd == "rx" %}
{{ value_json.data }}
{% endif %}```
this would be an mqtt sensor, that is receiving a json on the proper mqtt topic
figured out, value_template: accepts the template above
#automations-archived Please
You have to explain more, props is a proprietary field that seems to only be available for whatever service and rest endpoint that you are using. In order for anyone to help, we need to know every aspect.
brightness is an int, where your equation is a float. What does each side of the equation give you?
@mighty ledge well, the only thing that I know/can say is that because it is a proprietary field, I am trying to map it in the notify service config but I am not fully sure how to do that. WHat I need to basically say is "this field should hold a json payload.
From the docs:
Sets the post props, a JSON property bag for storing extra or meta data on the post.
Mainly used by other integrations accessing posts through the REST API.
The following keys are reserved: “from_webhook”, “override_username”, “override_icon_url”, “override_icon_emoji”, “webhook_display_name”, “card”, and “attachments”.
Props card allows for extra information (Markdown-formatted text) to be sent to Mattermost that will only be displayed in the RHS panel after a user selects the info icon displayed alongside the post.
they also provide an example with
{
"channel": "town-square",
"username": "Winning-bot",
"text": "#### We won a new deal!",
"props": {
"card": "Salesforce Opportunity Information:\n\n [Opportunity Name](http://salesforce.com/OPPORTUNITY_ID)\n\n-Salesperson: **Bob McKnight** \n\n Amount: **$300,020.00**"
}
}
The two links I am trying to work with are webhooks docs (https://developers.mattermost.com/integrate/other-integrations/incoming-webhooks/) and message attachments docs (https://developers.mattermost.com/integrate/admin-guide/admin-message-attachments/)
https://imgur.com/a/ZpncZHh I am trying to produce a template which can sense when a charger has <.1A for a particular amount of time, but it occasionally spikes above that value. Any suggestions on how to accomplish this? Maybe an average for X amount of minutes?
You can see how variable the charge acceptance is when you zoom in....
I'm sure the answer is in here somewhere: https://www.home-assistant.io/integrations/statistics
I looked at statistics, but I keep seeing "Average sensor has been built in since XYZ" when I try to search for help
Is this because statistics has the "window", since I am averaging the same sensor?
I'm not sure what you mean. It seems like providing a max_age and appropriate state_characteristic (like the default of 'mean') would be enough
And the sensor you want to monitor, of course
So I need 2 sensors.... one for the mean, and one for the binary of that when it's <.1A??? Since the Max_age is 5 minutes, the binary doesn't really need a time-based template??
you'll have the sensor that's reporting the current measurement and a sensor that provides a statistical analysis of the first one. You can use the latter directly in an automation as a trigger or condition if you like
Ok, I made the mean sensor, and now I must have the formatting wrong?
{{ states('sensor.house_battery_current_mean') < '-.1' }}
{{ states('sensor.house_battery_current_mean') }}
False
-0.08
Okay this is interesting.. my charging is a highly negative number, but my discharging is a positive number...
-.08 is more positive than -.1, so it's false.
Gonna have to put more logic into this
states are strings, and turning the compared value into a string isn't going to help 🙂
you want this comparison:
WHen I flip the comparator, it is true though
{{ states('sensor.house_battery_current_mean')|float < -0.1 }}, but perhaps you do still need to think about the logic you want
OH.. float that.. good point
Ok, maybe there's some casting logic going on in the background. But better to be explicit
LOL now it's not happy: TypeError: '<' not supported between instances of 'float' and 'str'
With: {{ states('sensor.house_battery_current_mean')|float(0) < '-.1' }}
I thought ' was for numbers and " for strings in my '-.1'
Its's now calling my -.1 a string?
Everything between quotes is a string
There is no difference in how single or double quotes are handled. Just remove the quotes around the number
{{ states('sensor.house_battery_current_mean')|float(0) < -.1 }} gets me TemplateSyntaxError: unexpected '.'
I quoted due to this error
in my -.1
states are strings, and turning the compared value into a string isn't going to help 🙂
that's what I mean by that
please, just use what I gave you
I made it 0.1 on purpose
one side gives me the current brightness value of the lights, the other gives me the value the lights would be set to. basically im trying to say "if the brightness is already set at the appropriate value, dont send a command to turn on/change the brightness", in order to avoid sending unnecessary actions
last night it was giving me values that should show true, ie brightness is lower than command to set brightness, but it was still evaluating false
Hello, I have an automation with a condition that uses this template_value: {{ (now().timestamp()) >= (state_attr("input_datetime.open_blinds_phone_alarm", "timestamp")|int + (16060)) }} . Since the last update I get an error on the condition (template value should be a string for dictionary value @ data['value_template']. Got None). Even state_attr("input_datetime.open_blinds_phone_alarm", "timestamp") evaluates to none, but the helper is available and has a value. In the template editor it works as expected. Did I miss a deprecation?
condition: template
value_template: >-
'{{ (now().timestamp()) >=
(state_attr("input_datetime.open_blinds_phone_alarm", "timestamp")|int +
(16060)) }}'
that was a typo
lol, it auto generated that 🙂
You have quite a lot of unnecessary parentheses
I know, it was for visual grouping, that's all
So, I tried to change it to the next:
condition: template
value_template: '{{ now().timestamp() >= state_attr("input_datetime.open_blinds_phone_alarm", "timestamp")|int + 16060 }}'
without any luck. Same error
template value should be a string for dictionary value @ data['value_template']. Got None
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
The 'input_datetime.open_blinds_phone_alarm' is a helper, has a datetime value
seem unlikely that you'd still get that same error
I know, it worked till recently and is still working in the template editor
I even recreated this on another instance
not sure what to tell you
Actually now I'm trying other things and whatever I enter in a condition template, It gives me the error 🙂
your problem was clearly the quotes, but you could very well have others
even
condition: template
value_template: '{{ now().timestamp() }}'
The quotes shouldn't be the problem. That was from copying it from the value template field. I wasn't in yaml mode when I copied the first text. I wanted to post a screenshot, but I don't think I have the rights to do so
If you are using the test button for the condition in the GUI, that doesn't work for template conditions
It gives an error, quite similar as the one you are posting 😅
It's not fixed in the beta yet
ah, that could explain the error here, but on the other end, the condition is skipped in my automation. I want my blinds to open 1 hour after my phone alarm sets. The last couple of days they open before my alarm sounds (the automation is also dependend on the height of the sun)
.share the whole automation
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
ok
Oh, and you said the condition is skipped. You are not pressing the RUN ACTIONS button in the Automation section in the GUI right? Because, in that case only the action part is performed, and conditions are skipped
To test an automation there's three stages you can follow. Testing the action, the condition and action, and the whole automation:
- Use Configuration -> Automations to find the automationand then push Run Actions. If this fails your problem is in the
action:section, and details should be found in your log file - Use Developer tools -> Services and call
automation.triggeron the automation withskip_condition: false. If the first passes but this fails then the problem is in yourcondition:block - Use Developer tools -> States to find the trigger entity, click the name, then change the state (at the top) to something that'll trigger the automation before pushing Set State. If this fails then the problem is with your
trigger:section, or the automation is turned off (you can check that in Developer tools -> States).
You can also see this section in the docs and with HA 2021.4 onwards debug automations.