#templates-archived
1 messages ยท Page 165 of 1
how do i insert a space between a and test
this is the string that template creates: "This is atest."
you can't, you're removing whitespace with the -'s
{%- means remove whitespace before this {% means don't remove whitespace before this
-%} means remove whitespace after this {% means don't remove whitespace after this
you're doing both
ahh ok
I have a question about scripts. Is it possible to pass a input number entity state to service call data parameters?
- choose:
- conditions:
- condition: state
entity_id: input_select.cover_master_bedroom_close_mode
state: Ventilatie
sequence:
- service: cover.set_cover_position
data:
position:
states('input_number.master_bedroom_cover_ventilatie_positie')
target:
entity_id: cover.master_bedroom
So this: states('input_number.master_bedroom_cover_ventilatie_positie') should be used as position value
Have you read up on template basics?
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
Todays date is {{ now().date() }}
Last time the vacuum robot ran was {{ states('input_datetime.staubilastruneingang')[0:10] }}
It would be great to get the delta/difference from these two dates. eg: 1, when it was running the last time yesterday.
Any idea how I can compare two dates, or any other template-idea on how to extract the information how many days it has been since a certain script was run?
{{ relative_time(states('input_datetime.date_time') | as_datetime | as_local) }}
thanks a lot. that is awesome. follow-up question: since this returns "2 hours", how can i use that return for a logical check, such as "true/false if return is greater then 24h" eg?
you can't, that's just for output
if you want to perform logic, you haveto use the datetime
{% set time = states('input_datetime.date_time') | as_datetime | as_local %}
{% if (now() - time).days >= 1 %}
{{ relative_time(time) }}
{% else %}
...
{% endif %}
thank you very much @mighty ledge
Damn....I tried a lot but nothing works.....But I found it...I was forgotten to change an input_select to the correct value. Sorry
Hi,
I'm quite new to MQTT and even more to templates...
I'm trying to get lights, but I can't get the states right (command seems to be working)
The command I can send :
{"type":"Buffer","data":[1]}
The status that doesn't seem to be understood by my template
"{"value":{"type":"Buffer","data":[1]}}"
With this config :
light:
- platform: mqtt
object_id: "Mur Salon"
name: "Salon - Applique"
payload_off: "{"type":"Buffer","data":[0]}"
payload_on: "{"type":"Buffer","data":[1]}"
command_topic: "knx/1/0/3/write/dpt1"
state_topic: "knx/1/3/3/"
state_value_template: "{{ value_json.data | replace([0], 'off') | replace([1], 'on') }}"
( Last one, I tried many others )
Could somebody please help me ? ๐ฅบ
Yeah, that's not right ๐
It's giving you a list with an integer in it
you would access that item with {{ value_json.value.data[0] }}
then, probably use payload_on: 1 and payload_off: 0 or whatever the actual values are
Thanks for your help
Let's try that ๐
Please see: https://www.codepile.net/pile/1AQDYwbx
It seems to only work if I concatenate ' ' to a variable.
Could this be because I'm stripping whitespaces with the -%}
If I change "{{ ' ' ~ name1 ~ ' ' ..... to
{{ name1 ~ ' '.......
It appears to populate the input_text as expected but following the script in the debugger it does not run
What is the correct way to create a template that triggers when there is a sharp drop in a sensor? So if sensor.drive_to_work decreases by 20% for instance.
you probably want a trend sensor
Can't be done with a use of ".from_state.state"?
you could, but that would just register a difference between two readings
if that's what you want, it's easy
yeah I suppose that is too small a delta.
the following means: dont continue if input_select.mode has not been 'home' for less than 5 seconds.
conditions:
- condition: state
entity_id: input_select.mode
state: Home
for:
hours: 0
minutes: 0
seconds: 5
``` how can i say: dont continue if input_select has been 'not home' for less than 5 seconds
do you really mean the string "not home" or anything other than "Home"?
i mean anything other than home, sorry
I would just make a template condition for that
The easiest way is to create a template binary_sensor that represents the thing you care about and then base your condition on that
{{ is_state('input_select.mode', 'Home') }}
then, {{ not is_state('binary_sensor.home', 'on') and states.binary_sensor.home.last_changed < utcnow() - timedelta(seconds=5) }}
thanks. looks like last_changed shows in utc, so I just changed now() to utcnow(), and also, unless im understanding wrong. it'd have to be.{{...< utcnow() - timedelta(seconds=5)}}, that seems to work, vs the other way the last_changed is always gonna be less
yeah, that's what I get for multitasking ๐
luckily, you can hack around in
-> Templates to catch stuff like that
Is there a way to set a value in a for statement and have the scope live outside the for statement? It doesn't seem to be working with this script:
{% for weatherAlert in weatherAlerts %}
{% if weatherAlert.event == 'Heat Advisory' %}
{% set isHeatAdvisory = True %}
{% endif %}
{% endfor %}
Is heat advisory? {{isHeatAdvisory}}```
Yes, with a namespace
Great thanks!
But this looks like it should be possible without a for
{{ now() - states.sensor.dual_dishwasher.last_changed }}gives me a result of 18:45:45.828521 which is H:M:S. How can I get it to just show hours and minutes?
OK I'v got this but surely there is a nicer option ```{{ (now() - states.sensor.dual_dishwasher.last_changed)
| string | truncate(5,True,'',0) }}
Also a bit of a hacky workaround {{ today_at(now().replace(microsecond=0) - states.sensor.dual_dishwasher.last_changed.replace(microsecond=0)).strftime('%H:%M') }}
Not pretty either - but maybe mine would fail when hour is only one digit ?
Or this ๐ {{ ((now() - states.light.booglamp.last_changed) | string).split(':')[0:2] | join(':') }}
If only there was something like unix cut
Any idea what's wrong here? I'm trying to use a single action to loop through those cameras I put in a variable.
template value should be a string for dictionary value @ data['action'][0]['repeat']['sequence'][0]['data']
https://dpaste.org/suPx6
This part is wrong: "{{ if trigger.entity_id == 'sensor.outdoor_light_on' | iif('ON','OFF') }}"
2 things:
Remove the first if
Add brackets, because you now only apply the iif filter to sensor.outdoor_light_on
The last one is why I rather use the iif function, it's more clear
"{{ iif(trigger.entity_id == 'sensor.outdoor_light_on', 'ON','OFF') }}"
I see, it was my first time using it and it made perfect sense for this scenario, thank you.
Still getting the error though.
Ah wait, this part is also wrong
{{ frigate/{{ camera }}/improve_contrast/set }}
use this:
topic: >-
{% set camera = cameras[repeat.index] %}
frigate/{{ camera }}/improve_contrast/set
or
topic: >-
{% set camera = cameras[repeat.index] %}
{{ 'frigate/' ~ camera ~ '/improve_contrast/set' }}
you can not nest templates
Oops yep can't nest templates. Thank you again.
BTW you might want to use repeat.index -1 because that index starts at 1
or use a for_each repeat
How would I use a for each repeat
- repeat:
for_each: '{{ cameras }}'
sequence:
- service: mqtt.publish
data:
topic: "frigate{{ repeat.item }}/improve_contrast/set"
payload: "{{ iif(trigger.entity_id == 'sensor.outdoor_light_on', 'ON','OFF') }}"
Shouldn't it be "{{ iif(trigger.entity_id == 'sensor.outdoor_light_on', 'ON','OFF') }}"
I figured, although even with that ^ I'm getting expected a dictionary for dictionary value @ data['action'][0]['repeat']
I also did not fix the other issue
The nested template?
how is it like this (see edited post above)
Same error https://dpaste.org/dL5QK
Is it because I have a list variable and not dictionary?
it's because your indentation is wrong.
compare your yaml to the example. What's different
That was definitely an issue and I think the editor on mobile was being weird. Sometimes it messes up my spacing. It works now. Thank you both.
Not sure what I did then or if it was the mobile automation editor which is buggy for me some times.
Guaranteed you copied/pasted but you already had 2 spaces.
how do I know this? Because it happens all the time
@dusty thorn posted a code wall, it is moved here --> https://hastebin.com/xiqadavezo
I'm having trouble getting self referencing to work with a "heat index" temperature entity.
https://www.home-assistant.io/integrations/template/#self-referencing
I get an error that makes no sense given what the documentation shows as an example
jinja2.exceptions.UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'temp'
sounds like it doesn't have that attribute
But it's defined right there?
right where?
In the attributes section of the entity
it probably doesn't have it yet
this represents the current state, and you're in the process of defining it
Suppose I can stick the entity in the value template, but I was hoping to be able to just have a generic value template I could copy over to other temp/humid sensor pairs if I make any changes etc
I don't think that will help
you can check if the attribute exists in the state, or use an availability template
I guess only the former will work
or, as you say, just use the states() value there
The temp&humid entities are ZHA and exist outside of reloading the template entities, so it does work directly grabbing from the value section
(I had it working before trying to genericise it)
What's the order of the entities being updated?
I'm guessing state then attributes given the issue I just had
If that's the case the example in the documentation is a bit misleading
the current state is a complete thing, the order in which the new state is calculated isn't relevant here
your problem is just a chicken-and-egg problem
It is relevant if it means it's always "one update behind" and you're calculating state off it as the doc example does
I'm not following
yes, this is always the current state, which you can use when calculating the new state
The doc example uses a templated value in the attributes, and calculates the value with a template referencing that attribute
there's nothing in between where some of the current and some of the new state is represented in this
it also has a default
which you do not
So if I understand correctly, it's always one update behind
What is "current" here? The state that is currently showing in the UI etc, before it is updated with new values when sensors update?
what you see in
-> States
in the example, the first state will be "Value when missing", and the next update it will be the time of that update
That feels like a bug tbh, as you'd have to some workaround mechanism to trigger a second update if you want your template to actually do anything useful on start (if you do as the docs suggest you do)
Might be an idea to stick a note on that docs example
To be clear, not saying it is a bug, it's just unexpected behaviour
I suppose you could suggest a note. It's consistent from my viewpoint
There are buttons at the bottom of each doc page to suggest an update
I don't know how it could work any other way. It needs a current state in order for the next state to get evaluated.
Hallo everybody. What is API alternative (if any) for gathering properties for an object? Thanks in advance.
{{ states.light.lvr_cc1 }}
Result type:ย string
<template TemplateState(<state light.lvr_cc1=off; min_mireds=153, max_mireds=500, supported_color_modes=[<ColorMode.COLOR_TEMP: 'color_temp'>, <ColorMode.HS: 'hs'>], off_brightness=None, friendly_name=Kolorowa lampka, supported_features=59 @ 2022-06-14T20:28:56.903707+02:00>)>
I created an (Template?) Input Select (Dropdown?) via the Home Assistant GUI - Helpers. I need to rename some and reorder them. Can I do this without deleting and recreating them?
if you created it in the UI, it's unrelated to templates
as far as i can tell, you can only delete options and add new ones
fair enough - i thought "Helpers - Input Select" was effectively a front-end gui for "Template - Input Select", hence choosing this channel
i guess i'll delete and recreate them, thanks
Hey Guys
I wanna send a notification witch inclued a sensor state. and a url from local ip with sensors state. like
I want to inclued the states of two sensores in message is this how it should be put or ?
message: '{{ states(''sensor.1'') ( https://www.local.ip/api=1&query={{ states('sensor.1.jpg') }} }}'
This is working: '{{ states(''sensor.1'') }}' when i push a message.
But i want to include this to the message: https://www.mylocalip.com/?api=1&query={{ states('sensor.mysensor2') }}
I thought this would be easy to find so sorry if it's obvious: can configurations for old-style sensor: templates and ones for new-style template: sensors coexist int he same configuration.yaml?
(I'm adding a new one and I'd prefer to do it in the most up-to-date format but I have a bunch of old ones I don't have the time to convert right now.)
I tried it and it appears to work (it was easier than I expected to test), so I think I've answered my question, but I'll leave this here in case I've gone down a horribly wrong path. Thanks!
Yes, no issues with using new and legacy template sensors together
.share the entire yaml code for the automation/script
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.
Subject in what?
my alarmclock automation has stopped working, and it seems to be something with the templates,
{{ (states('sensor.date') + ' ' + states('sensor.time')) == ( states.input_datetime.next_alarm.attributes.timestamp | int - (30*60) ) | timestamp_custom('%Y-%m-%d %H:%M', True) }}
and
{{ states('sensor.time') >= '22:30'|timestamp_custom('%H:%M', True) or states('sensor.time') <= '12:30'|timestamp_custom('%H:%M', True) }}
i cant find anything in the releasenotes about change to this, but it stoped working without me changing anything in the automation so i'm guessing its a result from updating home assistant version
it should fire 30min before my alarm ( input_datetime.next_alarm )
What is the error you are seeing, and how are you using these templates?
im getting that there is no default for timestamp
That answers the first question
{{ today_at('12:30') <= now() <= today_at('22:30') }}
This removes the need to use these custom_timestamps at all (and the need for sensor.time and sensor.date)
anyone any idea how I can count number of hue lights turned that are connected via a bridge? theres no sensor entity for it?
Hi. Is there a simplest way to get input_select index than:
{% set eid = 'input_select.console_audible_information_level' %}
{% for idx in range( 0, state_attr( eid, 'options') | length) %}
{{- loop.index0 if states( eid) == state_attr( eid, 'options')[idx] -}}
{% endfor %}
@manic tartan {{ state_attr(eid, 'options').index(states(eid)) }}
Thx. I was looking for this in Jinja template manual :-(. To clarify my undestanding - this method is Python list method or part of templates?
BTW, I expect the 'calculation cost' is the same (for manual search and index()), it should no be calculated every time I need this value. I have created sensor to have it calculated in advance. Is this best approach for having such a value?
- sensor:
- name: console_audible_information_level
state: >-
(...)
- name: console_audible_information_level
Not sure, I only know that it works ๐
OK :-).
Which manual are your referring to here?
And it's not clear to me what you want to achieve here
input_select: console_audible_information_options: name: "Poziom powiadomieล gลosowych na konsoli (tablet)" options: - "Cisza, brak powiadomieล gลosowych" - "Tylko alarmy" - "Ostrzeลผenia i alarmy" - "Informacje, ostrzeลผenia i alarmy"
An array of options available via GUI. I want to have numeric value based on zero based index of the selected value (states(eid)).
To have it calculated on-time (not evaluate every time I need this) I have created a sensor that uses the template to get that index:
- sensor: - name: console_audible_information_level state: >- (...)
Not sure if it is the best approach, but anyway it was easy to archive not having to calculate every time I need an index.
And works perfectly. But, I'm new to HA so looking for proper way if any :-).
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).
๐
I don't think it will make much difference using this simple template to get the index, or get it as the the state of a template sensor
Will try to test and compare, but if it is one-lines it looks much better :-).
Hi, I am trying to find the position of covers at a numerical value, but the only attribute I can find is a bolean "open" or "closed" value. Thanks for the help in advance ๐
if you don't see it in the attributes in
-> States, it's probably not available. It's also possible that your cover doesn't support it
dager_til_matavf:
friendly_name: Matavfall hentes om
value_template: '{{ (( as_timestamp(strptime(states.sensor.mat_plast_og_rest.state, "%d/%m/%Y")) - as_timestamp(strptime(states.sensor.date.state, "%Y-%m-%d") ))/ (3600*24)) | round() }}'
unit_of_measurement: dager
Can anyone please help me with why this code is not working after the latest update? ๐ Thank you in advance
the -platform: template is on top. I hve about 10 template sensors ๐
what is "not working" about it?
It is saying unavailable
It is supposed to read date from another sensor, and was working in 2022.4
without any more info, I'm going to assume that you have some garbage in your sensor state and you didn't add a default
so the template is failing to render. And you would have a log message about that
and would have for 6 months or so
I can check the log. ๐
TemplateError('ValueError: Template error: strptime got invalid input '2022-06-22 00:00:00' when rendering template '{{ (( as_timestamp(strptime(states.sensor.mat_plast_og_rest.state, "%Y/%m/%d")) - as_timestamp(strptime(states.sensor.date.state, "%Y-%m-%d") ))/ (3600*24)) | round() }}' but no default was specified') while processing template 'Template("{{ (( as_timestamp(strptime(states.sensor.mat_plast_og_rest.state, "%Y/%m/%d")) - as_timestamp(strptime(states.sensor.date.state, "%Y-%m-%d") ))/ (3600*24)) | round() }}")' for attribute '_attr_native_value' in entity 'sensor.dager_til_matavf'
So I guess my question is. What am I doing wrong? ๐
Anyone? :/
you should debug it in
-> Templates
you're providing the state of an entity and a format, and the two don't match
I guess coding is not my greatest skill ๐
ValueError: Template error: strptime got invalid input '2022-06-22 00:00:00' when rendering template '{{ (( as_timestamp(strptime(states.sensor.mat_plast_og_rest.state, "%Y/%m/%d")) - as_timestamp(strptime(states.sensor.date.state, "%d-%m-%Y") ))/ (3600*24)) | round() }}' but no default was specified
This is the output I got in template
You could really tell ๐คฃ In between copy paste is a friend
Anyways the sensor it reads from is a custom component which provides a date for emptying of garbage bin, the sensor counts down the days until. Any idea how I can fix this. because it was working before? ๐
again, you need to debug it in
-> Templates. That doesn't just mean "paste it in there"
2022-06-22 00:00:00 This is the output from the custom component
and that's clearly not the format you've provided for it
perhaps this will help: https://www.programiz.com/python-programming/datetime/strptime
So it is missing the hours? bc the format is correct? ๐ Y m d ๐ฅ
I could really just as well read chinese right now. Is it an easy fix, or should I just delete the code?
Anyways, thanks for that. I should have known I could have used google instead of discord. I guess Ill comment out or delete the code and forget about it. Have a good day ๐
Hi, how would I add leading zeros to a number? this is my current template, however it should always have 5 digits: {{ range(0, 99999) | random }}
the template resolver will remove them. Post where the template is going and we might be able to get around that issue
@mighty ledge mm. Its really just like that: I just want to have a random 5-digit number set as door open key every week.
https://strftime.org will help you format the timestamp properly
Can you just post all the yaml around your tempalte? That's all I'm asking
Thank you petro ๐
@mighty ledge this is the automation:
- id: '1655307170540'
alias: 'Set new code'
trigger:- platform: time
at: 01:00:00
action: - service: input_text.set_value
data:
value: '{{ range(0, 99999) | random }}'
target:
entity_id: input_text.kennwort_haustur
- platform: time
sensor:
- platform: template
sensors:
carro_bluetooth:
friendly_name: 'Carro Bluetooth'
value_template: >
{%- if states.sensor.poco_f2_pro_bluetooth_connection.attributes.connected_paired_devices == "[00:87:61:06:65:32]" %}
Bruno
{% else %}
Desligado
{%- endif %}
Hi guys, I have this template that suddenly stopped working. I don't really know how to solve it. Can anyone help? Thank you very much
go to the template tester (
> Templates) and check the value of:
{{ state_attr('sensor.poco_f2_pro_bluetooth_connection', 'connected_paired_devices') }}
chances are it should be == ["00:87:61:06:65:32"]
@dreamy sinew Thank you very much for your precious help, in the template tester I have true and false depending on whether the device is turned on or not. But I'm not able to create the sensor... I don't know much about this type of code...
Did you update the app recently? The connected Bluetooth device list is not actually a list and not a string looking like a list
I updated yes, the problem is that it stopped working a while ago and only now I noticed it. When I test the template I have this. The device is off, but if you turn it on it passes true
Well the change is already 2 months old
sensor:
- platform: template
sensors:
carro_bluetooth:
friendly_name: 'Carro Bluetooth'
value_template: >
{%- if "00:87:61:06:65:32" in state_attr('sensor.poco_f2_pro_bluetooth_connection', 'connected_paired_devices') %}
Bruno
{% else %}
Desligado
{%- endif %}
Try that
Working with a blueprint and trying to use multiple selector for media_player domain entities
media_players_str: !input "media_players" media_players: "{{ expand(media_players) | list }}" media_states_str: !input "media_states" media_states: "{{ expand(media_states) | list }}" media_timeout: "{{ states('input_number.media_occupancy_timeout') | int(10) }}" media_is_playing: "{{ expand(media_players) | selectattr('state','in', media_states) | list | count > 0 }}"
I think something isn't right with what I am trying to do on expanding.
I get a "list" I believe of entity_id's from the selector, and I want to check if ANY of them are playing.
morning,
This works but how do I write this in the newer format:
value_template: "{{ trigger.from_state.attributes.media_content_type == 'movie' }}"
This doesn't work:
value_template: "{{ state_attr(trigger.from_state.entity_id, 'media_content_type') == 'movie' }}"
Which newer format? You can't use state_attr for trigger templates. There is no replacement for what you had
that would be why, whoops
thanks fes
Is there any way to test trigger templates in the template editor?
Hm. Will the Utility Meter's
"source: sensor.energy"
"cycle:daily"
use the daily-energy use from my energy dashbord? I want my daily energy as a sensor! Is that possible?
So far it just says "unknown" the sensor.daily_energy
@marble jackal I can see you have s good day today :-). Do you know how to dump script/automation variables? this.data or this.variables doesn't work. Thx in advance.
hi is it possible to use this piece of code transition: '{{( as_datetime(state_attr(''sun.sun'', ''next_setting'')) - now()).seconds }} into part of a delay call? if so how do i do it.. thanks .. maybe delay: seconds: <<code here>> ?
see the last example: https://www.home-assistant.io/docs/scripts/#wait-for-time-to-pass-delay
awesome thanks.. will give it a go
does that mean I need to convert it to minutes then?
oh sorry looking at the code again.. looks like the final output is in seconds?
Is there a way to select light groups that are on? Not individual lights but light groups. Specifically zigbee groups not ha groups if that makes a difference. I know you can check a specific area but can you select light groups whether that's a specific area or globally?
data: >
{{ {'value': '%05i'%(range(0, 99999) | random) } }}
there's a lot to unpack there ๐
how do you differentiate a zigbee light group from any other light in HA?
I know Deconz and Hue both have an attribute for that on the entity. is_hue_group for example
Which can be true or false
I don't know how that is for ZHA and Z2MQTT
I don't think so, unless you define them all under one specific key
Thx. ๐
I use "lights" at the end of every light group entity id. daniels_bathroom_lights, daniels_bedroom_lights, kitchen_lights, living_room_lights Individual lights do not have light in the entity id. light.bathroom_1 for example.
{{ states.light | selectattr('entity_id', 'match', '.+_lights$') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
but you might also want to check if they have an attribute you can use, so you are more free in the naming
No special attributes other than the fact I gave all light groups icon: mdi:lightbulb-group
Which Zigbee integration do you use?
ZHA
On temperature change the state result is 2 temperatures. I assume it's because I'm going to the minute on both the end of a time block and the start of a new one. Is there a template to only allow 2 digits (68)? Rather than 68 69 for example. Or is it as simple as a < 100 template. Or I can just stop going to the minute too lol.
https://dpaste.org/zVpmF
You could change {% for h in hours if h[0] <= t <= h[1] %} to {% for h in hours if today_at(h[0]) <= now() <= today_at(h[1]) %}
you can remove {% set t = now().strftime('%H:%M') %} then
Perfect. Yeah as of now I don't think there's anything special for zha groups. Could that template be modified to check an area too?
Just for this schedule. I used different settings for the winter. https://dpaste.org/X6uTw
BTW, at eg 5:30, which state do you want to have then?
{{ states.light | selectattr('entity_id', 'in', area_entities('Living Room')) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }} this is used for regular lights. If i wanted to check an area for light groups with your template how would I add in the area?
Summer Daniels Thermostat Schedule changed to 63 65 per logbook. That's what was happening.
Yes okay, but at that time, would you want it to show 63 (so using the end time 5:30) or 65 (using the start time 5:30)
At that time it should show 65
https://dpaste.org/268vh this way you won't need the for loops
the same way, but you need to make sure the group is also added to an area
I also have the individual lights in the areas though. I would want to use the same lights filter you used to select the light group.
yes, just combine it
{{ states.light | selectattr('entity_id', 'in', area_entities('Living Room')) | selectattr('entity_id', 'match', '.+_lights$') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
Perfect. Would the thermostat schedule you just sent also work for multiple day settings? All I would do is use the conditional state on which attribute to use as I did here right?
https://dpaste.org/X6uTw
Yes, as soon as you define hours the rest is the same, so it will also work there
Perfect. Thank you.
Could this work? The repeat.item isn't working. https://dpaste.org/O19Jr
From step details
service_data:
topic: frigate//improve_contrast/set
payload: 'OFF'
trigger.item only exists in a for_each repeat
you are now using a count repeat
- repeat:
for_each: "{{ outdoor_cameras if trigger.id == 'outdoor' else indoor_cameras }}"
sequence:
- service: mqtt.publish
data:
topic: frigate/{{ repeat.item }}/improve_contrast/set
payload: >-
{{ 'ON' if trigger.entity_id in ['sensor.outdoor_light_on', 'input_boolean.downstairs_shades_status' ]
and is_state('input_boolean.downstairs_shades_status', 'on') else 'OFF' }}
Hi I need some help:
total_energy_consumption_from_grid: friendly_name: "Stromverbrauch" unit_of_measurement: "kWh" device_class: energy value_template: > {% if states('sensor.total_energy_text') == 'unavailable' %} {{ states('sensor.total_energy_consumption') }} {% else %} {{ ((states('sensor.total_energy_text') | float) * 0.0001) | round(2) }} {% endif %}
The sensor is not available to energy dashboard, how can I fix that?
it needs state_class: total_increasing
But you can't add that using the legacy format, so either convert it to the new format, or add that using customize.yaml
as you are using two different sensors here, be careful you don't get value decreases, that will mess up your energy dashboard
That works, thank you @marble jackal
Oh I didn't knew there is a new format. I have to check that. The second should only show the current value in case my sensor is down. I also could remove it. I thought I would avoid problems with that.
@marble jackal Awesome it worked - but I just used the customize entry. I have to convert the sensors later on. Thank you for your help.
Is there a way to use a template to add parameters to a shell_command from the service call itself? I searched and saw that I can use a template to get data from a different sensor but I couldnt find how to send data via service_call. Example:
shell_command:
echo_test: echo {{ my_name }}
automation:
...
action:
service: shell_command.echo_test
data: "Russell Joseph"
How can i parse this number 1655326503002 (Javascript timestamp) to a relative time.
This one is working, and show me the correct time
{{ (1655326503002 / 1000 ) | timestamp_custom("%Y-%m.%d %H:%M:%S.611725-03:00") }}
But i cant parse to get it as relative time
having this template works fine: {% set presence = states('zone.home')|int(0) %} {% set icon = {0:'mdi:account-off', 1:'mdi:account', 2:'mdi:account-multiple', 3:'mdi:account-multiple-check'} %} {{icon.get(presence,'mdi:account-group')}}
however, template for the colors goes awol: {% set presence = states('zone.home')|int(0) %} {% set colors = ['grey','steelblue','saddlebrown', 'gold','darkorange','maroon'] %} {{colors.get(presence,'green')}} with UndefinedError: 'list object' has no attribute 'get'
this works, but hasn't got the guard {% set presence = states('zone.home')|int(0) %} {% set color = ['grey','steelblue','saddlebrown', 'gold','darkorange','maroon','green'] %} {{color[presence]}} so I would need to go back if /else, while i like the getter.. what am I missing?
{{ relative_time((1655326503002 / 1000) | as_datetime) }}
colors is a list, not a dict. Lists don't have the method get(.
icon is a dict btw
in your first template
I love you petro, i have 10 days trying differents approachs!
Thx.. ofc.. what was I thinking..
Nothing wrong with a good old fashioned if / else ;/)
or just change your last line to
{{ colors[presence] if presence < colors | length else 'green' }}
@floral shuttle
Ok let me think that through ..thx!
I have a list with long/lat and see that HA has a distance/closest function allowing me to calculate the distance from home to that point... any idea on how I may reorder that list by running that function for every item? I mean.. is there anything similar to a sort lambda kind of function in jinja? The only thing I can find is sort(attribute=foo)
looks like distance isn't set up as a filter, only as a function
@hearty prairie try something like this:
{% set ns = namespace(distances=[]) %}
{% for location in locations %}
{% set ns.distances = ns.distances + [{'name': 'loc{}'.format(loop.index), 'distance': distance(location[0], location[1])}] %}
{% endfor %}
{{ ns.distances|sort(attribute="distance") }}```
Thanks, that's pretty close to what I've come up with too
was just hoping I could do this as a oneliner/simpler :p
that was working in the template tester so could definitely mess with it
yeah, without distance as a filter you have to use a loop
ok, but then I'm on the right track, awesome ๐
Hi
I already talked about my issue a few days ago, but I still can't figure out how to make HA "understand" the status of my light ๐ฆ
My config :
https://dpaste.org/SC5Cv
( Using last version, I changed since last time )
I tried using payload_on=1 and payload_off=0, but I couldn't make it work either
Since my last try, I enabled logs, and it doesn't complain with that config, so I thought I was on the right way ๐ฆ
Is there a way to give a command template using those payload ? So that it receives a json message ?
There's no point to that, you just need to parse it in the state_value_template so you end up with a string
You're trying to move the wording around, which isn't allowed, and just makes it more complicated
You can go to
-> Integrations -> MQTT -> Devices, find your device, click MQTT Info to see what's it's getting and how the payload is being parsed
"This entity ('light.salon_plafonnier') does not have a unique ID, therefore its settings cannot be managed from the UI. See the documentation for more detail."
To avoid that, I tried to use object_id but it doesn't seem to change much
Now the status is ok, if I switch the light on/off without using HA, but trying to do it with HA doesn't work as following the logs, HA send "1", while "{"type":"Buffer","data":[1]}" is expected
Ok, it's unique_id that I must use, not object_id ๐
Ok, maybe not the best solution, but works using template schema :
https://dpaste.org/di4is
Thanks for your help @inner mesa ๐
This isn't triggering off the time pattern and I assume it's because the condition is messing it up. How would I keep the condition efficient while accounting for the fact one of the triggers is a time pattern?
https://dpaste.org/EpG4u
I have a known entity_id light.wled from a device WLED Livingroom. I want to get the entity that contains the string _intensity and has numberas device_id.
How could I do that?
I got the device_id from this:
{% set con = states
| selectattr('entity_id','eq', 'light.wled')
| map(attribute='entity_id')
| map('device_id')
| first %}
Now I'm missing the part to track down the number with _intensity in entity_id which is child from this device_id
{{ device_entities(con) | expand | selectattr('domain', 'eq', 'nubmer') | selectattr('entity_id', 'search', '_intensity') | list }}
Hey!
@vagrant monolith posted a code wall, it is moved here --> https://hastebin.com/sexemepaju
I would like to take https://www.toptal.com/developers/hastebin/pabuvekadu.lua and only return the ones that includes a Date to the sensorData. My current problem is that some may be none, that makes my template break. Since it checks them against Dates.
reject the ones that are none if they are actually none. if they aren't defined, only select the ones that are defined
How?
how did you select the ones with the datetime?
did you copy/past that template or make it yourself? I guess that's what I should ask you.
I made it myself with some help of template guys
I mean, some of the sensors only works on some days, because other days the values can be none
do you understand selectattr?
Not exactly
ok
then just add | selectattr('attributes.today', 'defined') | selectattr('attributes.today', 'ne', none) before your other selectattr
defined?
yes defined
yep
Lets see if it works, and is it possible to check so its a date instead?
nope
Okay
you have to check to see if it exists
try it in the template tester
no point in restarting if it doesn't work there.
templating 101
where does that come from
yeah, so is it always strings or is it always datetimes? right now they look like strings, not datetimes
I have no idea how that template ever worked before.
Well, what custom integration
that's for the main state
Okay
Looks like i solved it chaning none to "none"
{{(sensorData|selectattr('attributes.today', 'defined')|selectattr('attributes.today', 'ne', "none")|selectattr('attributes.today', '<', now())|
ok, it's always a string, just looked at code
Do you have any recommendation for making the template better?
Still doesnt work tho
becuase they aren't datetimes
they are strings
you don't have enough indents
yes
Okay, thanksรค
Now it works, thanks ๐
I have one more problem
My SMHI sensor returns unavailable
Until I reload the sensor after each restart
script.toggle service is such a weird concept.
I wonder in what scenario folks use this?
when you have a delay, turning off a script stops the script in the delay
This isn't triggering off the time pattern and I assume it's because the condition is messing it up. How would I keep the condition efficient while accounting for the fact one of the triggers is a time pattern?
https://dpaste.org/EpG4u
yeah, but .toggle in specific?
I would guess it makes sense for the sake of complete api... but otherwise?
(this isn't really serious problem i'm just bored)
But then why doesn't camera and climate have a .toggle?
if they have .turn_on and .turn_off defined
because they don't have on/off states?
toggle only works on something that has an on, off state and the on off state needs to be known to HomeAsisstant
cameras and climate have other states aside from on, off
so toggle doesn't make sense
where a script can be 'on' when running, so you can toggle it off
it's not something that's purposely given to that domain, it's inherited by the fact that it has an on/off state.
but media_player has multiple states (like paused, idle, buffering) and supports toggle. And so does vacuum.
This seems an #integrations-archived discussion to me
Yes, the condition is the problem because a time_pattern trigger doesn't have those variables because it's not triggered by a state change. https://www.home-assistant.io/docs/automation/templating/#time-pattern
Add and trigger.platform != "time_pattern"?
I'm not entirely sure what you're doing there because you're not actually using the values from the state change
I'm trying to stop it from doing anything if the to state is null or unavailable
That's one way to limit it
The to state will be a number
But you're just unconditionally proceeding at 5 after the hour anyway
Well actually I want it to pass if it's a time pattern I just want it to not pass if it's the sensors and their value is null or unavailable. The way the sensor is setup both will occur.
But, again, you're going to proceed once an hour no matter what
I'm not sure I'm following. How would that occur? It's ok if it's the time pattern that's the trigger. It's not ok if the trigger is the sensors and their to state value at the time of the trigger is null or unavailable. That's idea of what I'm trying to prevent.
Ok, it does that
My point is that regardless of whether those sensors are valid, it's going to proceed to the action once an hour
But how lol that's why I'm confused
Because you're explicitly restricting the condition to the state trigger
If you want it to apply all the time, put both sensors in the condition explicitly
Yeah I realized that wouldn't make sense. can I do a conditional statement if elif in a condition?
You don't need that
Yeah it would make sense to be if the trigger is either of the sensor their values can not be equal to null or unavailable. If it's a time pattern it's fine to pass and then I should probably check the state of the sensors though to make sure they aren't equal to null or unavailable
You really don't care what the trigger is
It only happens for a minute. So it will be corrected next time around.
Yeah I guess that's correct. I really care about the state value.
I should just say both have to be not equal to unavailable and null
So just check that with a template
It happens on template reload the way the template is setup it will result in null for 1 minute. Yeah that makes more sense.
Apologies in advance - I still don't quite get the layout and structure of the yaml files in HA. Trying to implement a 'presence detection timer' sensor - to report how long it's been since a user has been 'home' - using this as a guide (https://community.home-assistant.io/t/presence-detection-calculate-time-away-and-set-as-variable/92453/3). Is there a way to add a variable or three in the yaml so a sensor is kept for each of my configured users, without having to manually add/copy/paste the entire codeblock for each user?
Hey
How do I convert attributes.today to a Datetime?
{{(sensorData|selectattr('attributes.today', 'defined')|selectattr('attributes.today', 'ne', "none")|selectattr('attributes.today', 'ne', "")|**selectattr('attributes.today', '<', now())**|
Is attributes.today a timestamp? Could be easier to convert now() to match the format of attributes_today.
hey I need a little help:
My I have no idea how to extract the hours in format HH:MM out of this template.
{{ (as_timestamp(fcast.datetime) | timestamp_local) }}
I wanted to use .strftime() but the object type that I get from these are either float or string.
of course I want the local hours and minutes.
you can use as_datetime(now) iirc
please make sure to notify me when answering!
Use as_datetime(fcast.datetime).strftime('%H:%M')
You can not using fillters, you will have to convert now() to the same format as attributes.today if you want to use this approach
Can a math expression be a variable? I'm trying to do this in the template editor and it's not working.
{% set input_number = 50 %}
{% set mode = '+' %}
{{ input_number mode 2 }}
Ideally the answer would be 52.
Then I guess the answer is no ๐
{{ input_number + 2 if mode == '+' else input_number - 2 }} maybe?
Yeah that's perfect. Good to know that it can't be done the way I tried.
Or this
{% set input_number = 50 %}
{% set mode = '-' %}
{{ input_number + int(mode ~ 2) }}
Only works for + and - though
Yeah that's all I needed + and -. What is ~ called?
Both sides of it will be combined together as a string
So in the example above it will be "-2"
I see, is there a name for the specific ~ though? Is it concatenate?
Well that is what is does ๐๐ผ
How would I get this to evaluate to true? Based on current conditions it should be evaluating to true. temperature is 70 and the input number is 70
{% set input_number = 'input_number.daniels_scheduled_temperature' %}
{% set mode = '-' %}
{% set entity = 'climate.daniel_s' %}
{% if states(entity) == 'cool' and state_attr(entity,'hvac_action') == 'idle' and state_attr(entity,'temperature') | int(mode ~ 2) < states(input_number)| int %}
true
{% endif %}
This worked
{% set temperature = state_attr('climate.daniel_s','temperature') %}
{% set input_number = states('input_number.daniels_scheduled_temperature') | int %}
{% if temperature + 2 > input_number %}
e
{% endif %}
thanks for the help earlier! I have another question tho:
What am I doing wrong here? I want to store the values of my for loop calculation in this list to use it later in the template.
{% set offsetList = [] %}
{% for i in range(columns) %}
{% if columns % 2 == 1 %}{% set columns = columns - 1 %}{% endif %}
{% set offsetList = offsetList.append((i - (columns / 2) - crossShift)) %}
{% endfor %}
however I get SecurityError: access to attribute 'append' of 'list' object is unsafe..
I could just use the values straight away but It makes the code messy and very long lines in this case
What does this return:
{% set input_number = 'input_number.daniels_scheduled_temperature' %}
{% set mode = '-' %}
{% set entity = 'climate.daniel_s' %}
{{ states(entity) == 'cool' and state_attr(entity,'hvac_action') == 'idle' and state_attr(entity,'temperature') | int + int(mode ~ 2) < states(input_number)| int }}```
That worked thank you as always!
I used int as a function, and you used that part as the filter to convert the state to an integer
how would i turn the [132.0, 136.5, 140.5] the statistics sensor gives out into a list?
would i just have to do string parsing or is there a better way?
It's not a list?
{{ states("sensor.co2_history")[0] }} gives me just a [
so does {{ states.sensor.co2_history.state[0] }}
there's probably a better way, but:
{{ "[1, 2, 3]"[1:-1].split(', ')|map('float')|list }}
that does indeed work
now time to see if i can actually get the automation to work
so {{ states("sensor.us_nw_psei_co2_intensity") | float <= (states("sensor.co2_history")[1:-1].split(', ') | map('float') | list)[0] }} should get if the co2 intensity is relatively low
{{ ("[132.0, 136.5, 140.5]" | from_json)[0] }} gives 132
So does {{ states("sensor.co2_history") | from_json)[0] }} work for you?
see, I knew there was a better way ๐
works ๐
I'm creating a template cover so the cover shows closed when the position is 8 or lower. and otherwise uses the state of the actual cover.
closed
{% else %}
{{ states('cover.screen_kamer1_source') }}
{% endif %}```
The problem is. When closing the cover a little bit, the cover assumes it's open and so doesn't display the up arrow on the frontend. Is there a way to fix this?
Found the answer myself, by just adding the position template ofcourse. Problem solved.
Hi, I'm struggling to get my mind around how I could get this to work. Any suggestions will be much appreciated```
- condition: time
after: "{{ states('input_datetime.reminder_start_time') }}"
before: "{{ states('input_datetime.reminder_end_time') }}"
Nevermind - Found it. Read over it probably 20 times ๐คฆโโ๏ธ --> condition:```
- alias: "Example referencing a time helper"
condition: time
after: input_datetime.house_silent_hours_start
before: input_datetime.house_silent_hours_end
still need help with this - pls ping me with answers!
Hey everyone, can anyone help me with this value template. Trying to get 3 values from a sensor. But itโs failing for some reason and Iโm having a total brain freeze. {{ state_attr('sensor.my_gmail_com','body')
|regex_findall_index("(?:^|(?<= ))(light|off|bedroom)(?:(?= )|$)")
If I use {{ trigger.now }} it displays as a full timestamp e.g.: 2022-06-19 19:36:00.000589+10:00'
What filter can I use to just display %H:%M
I've tried:
{% set test = { "ts":"2022-06-19 19:36:00.000589+10:00" }%} "{{ as_timestamp(test.ts) | int(0) | timestamp_custom('%H:%M', False) }}"
but it displays 09:36 instead of 19:36 for some reason
in the automation i would use: "{{ as_timestamp(trigger.now) | int(0) | timestamp_custom('%H:%M', False) }}"
but it converts it to the wrong time
https://www.codepile.net/pile/yqP0YkqZ is the full automation
had to remove "false", solution is:
"{{ as_timestamp(trigger.now) | int(0) | timestamp_custom('%H:%M') }}"
Does that mean it's using utc time. My HA instance has the correct time from my ntp servers. addiing "False" to "timestamp_custom()" makes it localtime right?
@tepid onyx you can try trigger.now.strftime('%H:%M') if it is a datetime object. Otherwise as_datetime(trigger.now).strftime('%H:%M')
thanks for the brief answer, tho can someone give a little further help, as I'm really stuck on this
maybe something like a not-random example ^^'
yes I read it - with namespace reference do you mean the method in the example?
because I do not understand the use of namespace()
Ok
Without the namespace you can not define a variable in a for loop and use it outside the loop
got so far
trigger.now.strftime didn't work error was "'str object' has no attribute 'strftime'"
as_datetime() worked. That's a bit cleaner code there ๐
And how far did you get in applying it to your code?
I got this from an xda devs pretty much as a skeleton but I do not understand it:
{% set crossedAt = namespace(value=0) %}
{% for entry in state_attr("weather.home_hourly", "forecast") | reverse() -%}
{% if entry.temperature|float > 22 %}
{% set crossedAt.value = loop.revindex %}
{% endif %}
{%- endfor %}
{% set crossedAt = crossedAt.value %}
it works
Okay, and which part do you not understand?
what I need to put into namespace and what it does to the variable I'm setting it to
In your case you need to create a namespace for your offsetList
something like:
{% set ns = namespace(offsetList = [] %}
And then use ns.offsetList instead of offsetList
Embarassing question: I see a lot of mention of sensors like sensor.count_sensors and sensor.count_binary_sensors but I don't see any reference of how those are created. Could someone point me to the idiot's guide on how to create these sensors?
Thanks, found what I was looking for!
Hey.... i was wondering if anyone knows why is this wrong:
- platform: mqtt
state_topic: "nudge/ou_04"
name: "esp_nudge_04"
value_template: {{value_json.state}}```
This is what i get when i check the configuration:
Error loading /config/configuration.yaml: invalid key: "OrderedDict([('value_json.state', None)])"
in "/config/configuration.yaml", line 78, column 0```
Yes, surround the template in quotes
Okay thank you!
It works!
Didn't expect otherwise ๐
Hi folks! Apologies if this isn't the right place to ask. I am tinkering with getting Home Assist to talk to a homemade MQTT light I rigged up years ago that has a VERY non-standard control format as a result. I'm comfortable creating the logic to control it, the only question is, how do I determine what is present in the command payload when I control it with the dashboard. For instance, if I slide the brightness slider, how do I know if the information passed to the MQTT Light template has things like colors or effects defined. Is there a way to interrogate exactly what's being sent by Home assistant when I adjust a light with the GUI?
how should the template look like for it to be correct? https://pastebin.com/KmJB0brr
Replace the triple single quotes
You probably used the GUI to add it, and added quotes around the template there, the GUI added more quotes
yeah haha
You can listen to the service call events
On the developer tools -> Events -> Listen to events thing? I was tinkering with that but I wasn't sure what to type into the "listen" field.
That one indeed. Try service_call. It will show the service call events, which will be triggered by the GUI.
Bingo. That was it! Well, call_service was it, but it's what I was looking for!
Thanks!
Can I directly use a device_trackers's attribute inside a templae sensor where I want to count how many device_trackers are in a certain state or do I first need to create seperate template sensors for each attributes themselves ?
What attribute?
ap_mac
You just want to know how many have a certain value?
{{ states.device_tracker|selectattr('attributes.ap_mac', 'defined')|selectattr('attributes.ap_mac', 'eq', 'whatever')|list|count }}
{{ [
is_state('state_attr(device_tracker.xxx', 'ap_mac)', 'xx:xx:xx:xx'),
is_state('state_attr(device_tracker.xxx', 'ap_mac)', 'xx:xx:xx:xx'),
is_state('state_attr(device_tracker.xxx', 'ap_mac)', 'xx:xx:xx:xx'),
is_state('state_attr(device_tracker.xxx', 'ap_mac)', 'xx:xx:xx:xx'),
] | select('true') | list | count }}
was hoping to use it like that since I'm only interrested in 4 devices
but that's not working :p
TIL, thanks !!!
if you just want some device_trackers:
{% set devices = ['device_tracker.xxx', 'device_tracker.yyy', 'device_tracker.zzz'] %}
{{ devices|expand|selectattr('attributes.ap_mac', 'defined')|selectattr('attributes.ap_mac', 'eq', 'whatever')|list|count }}
Use what Rob provided indeed, if you want to limit it to this 4, you can put them in a group
Or do that :)
wow, I wish I had 10% of your skills ๐คฃ
Nice thing about a group is that you can do that in the GUI, so it's easy to add or remove trackers
@sturdy juniper What you had didn't work because you were checking for the string 'true'. It would have worked if you used select()
{{ [ true, true, false ] | select() | list | count }} results in 2
Oh, and instead of state_attr(x, y) == z you can also use is_state_attr(x, y, z)
Just for future templates ๐๐ผ
thanks alot ! I'll have to schedule some tutoring lessons with you sometime ๐
Any help?
What is the proper way to write
- platform: template sensors: door_garage_single_door: value_template: >- {% if ((float(states.sensor.xiaomi_vibration_garage_single_door_angle_y.state) > 60)) and ((float(states.sensor.xiaomi_vibration_garage_single_door_angle_z.state) > 0)) %} Closed {% else %} Open {% endif %}
Regex is not my strongest suit, what are you trying to achieve here?
The proper way is not to use state.some.entity_id.state, but use states('some.entity_id').
You are also using the legacy template, which is not an issue right now, but it could be that it will be depreciated in the future.
And you are not providing defaults for your float functions, or providing an availablity template, which will cause issues when the sensors are not available (eg just after restart)
Iโm trying to have a trigger or a condition in automation using value template, so when I receive an email with certain words in it through imap integration, the automation that contains the template runs. The order of words can be in any order and letter case can be either upper or lower case. Thatโs why Iโve tried regex way as I was trying to simplify the search/match of the key words
The whole idea is to have an automation that runs and executes on keywords that appear in an email no matter in which order they show up nor what letter case they are in. Using Siri, i tell her โNote Turn off the lights in the living roomโ , Gmail gets an email in folder/label Notes with subject/body โTurn off the lights in the living roomโ. HA automation gets key words โoff light living roomโ and kills the light in living room. Thatโs why I need help with the template, canโt figure out how to have it search for words in non particular order and not depending on letter case
Uhm, I might be mistaken, as I don't use Apple, but I believe there is an integration to link HA with Siri (HomeKit)
That part Iโve already figured out, the only reason Iโm using Siri here is to have it put a note in google notes aka make a new email that syncs instantly with the gmail folder/label notes. Subject ends up being the note Iโve told Siri to make
Then having imap integration check for that folder and get the note aka email as state, in my case subject/state ends up being โset living room light offโ
That part is done
Now Iโm trying trigger an automation using a template that searches/matches keywords from the state/subject of the email imap integration received
And thereโs where Iโm stuck, canโt figure out how to make a template that searches/matches keywords in no particular order and no matter what lettercase keywords are
For some reason I can't paste these variables into an automation editor without an error. I tested the logic and it works. Not sure why I'm getting an error.
https://dpaste.org/K5TTm
Hi guys! Possibly a stupid question, but... How do I extract 'last_changed' value of an entity so I can use it in templates? If I'm not mistaken it used to be under attributes, but I don't see it there any more? Thanks!
entity.last_changed
Ah, yes; states.entity.last_changed. I was trying with state_attr which of course returns nothing. Thanks!
define an error
The red line, if you go back to ui editor and come back it's gone because It thinks something is wrong with it. It won't save with it either. Never had this happen so I assume there may be an issue with the code? I tried saving and it saved but removed it.
The dpaste shows some strange syntax highlighting, did you use tab instead of spaces maybe?
and you intend it a bit much
I do about 99% of my editing on Mobile on an app called "quick edit" and I think it tends to jack up spacing. I did some changes in the automation editor and it took it. One more question.
how would i format this
{{ now().strftime('%H:%M') >= '20:00' and now().strftime('%H:%M') <= '06:00' }}
As that doesn't seem to work
then how would i add a Not (both not between the time frame and cooling) meaning if it's between the timeframe it can't be cooling then.
{{ states(condition) != '' and states(condition) != 'unavailable' and states('input_boolean.3_zone_script_running_status') == 'off' and not now().strftime('%H:%M') >= '20:00' and now().strftime('%H:%M') <= '06:00' and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' }}```
That will not work, but you can probably see that for yourself. Eg "21:00" is higher than "20:00" but not lower then "06:00"
{{ now() >= today_at('20:00') or now() <= today_at('06:00') }}
You need to use or here, not and
states(condition) != '' this will probably never be the case, states() always returns the state, or unknown, or unavailable.
Yeah I remembered the time from the schedule we worked on together but I couldn't figure out how to put that in a condition. When it's null it will be unknown or unavailable?
states.some.entity_id.state can return null, but states() will never do that
and x == '' will not check for null, you need to use x is null then
{{ states(condition) not in ['unavailable', 'unknown'] and states('input_boolean.3_zone_script_running_status') == 'off' and (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' }}
Does the not in make the rest of the statement not? As in it would be true as long as all of those are not what is specified.
no, not all of those, only the states(condition) in [ 'unavailable', 'unknown' ] part
I would want to have the time and cooling be tied together. If it's during that time and cooling it's false if it's not during that time and it's cooling it doesn't matter.
Maybe it's easier if you split it into different parts
{% set condition_state = states(condition) not in ['unavailable', 'unknown'] %}
{% set boolean_state = is_state('input_boolean.3_zone_script_running_status', 'off') %}
{% set time_cooling = (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' %}
{{ condition_state and boolean_state and time_cooling }}
I was thinking that.
And to use in a condition just make it a variable
That can be used that way in a condition?
Yes, it will return true or false
Because it will be either true true true = true or false true true = false?
Yes
Wow I didn't know that was possible. Thank you.
It's not different in what you were already doing, it's just cut into chunks
#templates-archived message this is also retrurning {{ true and true and (false or true) and true }} which will evaluate to true
Hi, I am having issues with getting a garage door cover setup using a single relay (zooz zen17) and single door sensor (SM-4201-LQ) mounted to the bottom of the door on one side. The overall function is working fine aside from the change of state reported by the sensor. What happens is when the sensor changes state it will quickly 'bounce' and go from 'open > closed > open' or 'closed > open > closed'
I am looking for some advice on how to go about debouncing that state change so it only goes from open > closed or closed > open.
I see, makes sense. Thanks again.
.share your current code
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.
Is it right that only template "sensors, binary (on/off) sensors, buttons, numbers and selects" use the "modern configuration"? https://www.home-assistant.io/integrations/template/#configuration-variables
So template switches, locks, covers, etc still use the "legacy" style?
Correct
Where can I find more documentation on the various functions available to me in templates? E.g., the {{ states('climate.garageac1') }} states() function. My google-fu is failing me.
https://www.home-assistant.io/docs/automation/templating/
https://www.home-assistant.io/docs/configuration/templating/
This isn't evaluating to true. The first 2 are. The time isn't. The goal would be for this to be true outside of the hours between 20:00 and 06:00 if the thermostat is also cooling. Meaning if during 20:00 and 06:00 the thermostat is cooling this would be false. in addition to the first 2 conditions being true of course. Would I do this {{ not (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' }}
this translates to:
Not after 8pm
Not before 6am
hvac action is cooling.
So it would only be true after 6am, and before 8pm, when the HVAC is cooling
How would I make that true If it's after 8pm and before 6am and the HVAC is Cooling? I want this automation not to run during those conditions. After 8pm and before 6am when the HVAC is Cooling. Along with the initial 2 conditions that are whenever they occur. Boolean on or unavailable/unknown then I would not want it to run then either.
Original post from thefes
{% set condition_state = states(condition) not in ['unavailable', 'unknown'] %}
{% set boolean_state = is_state('input_boolean.3_zone_script_running_status', 'off') %}
{% set time_cooling = (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' %}
{{ condition_state and boolean_state and time_cooling }}
Most of this is just writing down what you want to do and adding English words like and and or
There's little magic involved
Yeah I know. The problem I'm having is the time.
Getting the time frame correct.
It's easy to say and and or not. I'm struggling with saying and and not between the time frame and cooling during that time frame
Start by writing something that evaluates to true for the time.
Then write something that returns true for the HVAC
Now take both statements and write
(statement 1) and (statement 2)
You only need to wrap them in brackets if they contain and or or, but adding extras, as long as they line up, doesn't hurt.
If it has to be true if it is after 06:00 and before 20:00 you can use today_at('06:00') <= now() <= today_at('20:00')
so if it has to be true in that timeslot, and when the state is cooling, it would be:
{{ today_at('06:00') <= now() <= today_at('20:00') and is_state_attr('climate.daniel_s', 'hvac_action', 'cooling') }}
Ideally it would be this.
These 2 have to be true 24 hours a day.
{% set condition_state = states(condition) not in ['unavailable', 'unknown'] %} {% set boolean_state = is_state('input_boolean.3_zone_script_running_status', 'off') %}
then after 20:00 and before 06:00 if the thermostat is cooling it is false but only if it's during that time frame that the thermostat is cooling else true
okay, so it needs to be false when this is true {% set time_cooling = (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' %}
{% set condition_state = states(condition) not in ['unavailable', 'unknown'] %}
{% set boolean_state = is_state('input_boolean.3_zone_script_running_status', 'off') %}
{% set time_cooling = (now() >= today_at('20:00') or now() <= today_at('06:00')) and is_state_attr('climate.daniel_s', 'hvac_action', 'cooling') %}
{{ condition_state and boolean_state and not time_cooling }}
Yes. I also have a weird automation issue. This works sometimes and others it doesn't. It's weird because in the template editor it works everytime but in the automation it is null or only one of 2 variables needed actually does anything. I'm not sure if it's because I'm using 'true' and it's messing with stuff but the other one should be a number. I also don't think I did the value on the for each properly.
Here's when it worked but only for being 'true' and null for the number below it.
https://dpaste.org/5q3YF
When it didn't work.
https://dpaste.org/1FZwB
What the automation yaml was when it did and didn't work.
https://dpaste.org/naKAK
Full Yaml
https://dpaste.org/UJdEK
okay, then the template above shoud work
Going to check now thank you.
That worked (time condition). And would that fix the null temperature deviation too (the changes you said to make)
Is that true supposed to be there with the elif on line 29?
Oh ok. Is what I'm doing with the for each value going to work? Using repeat.item to evaluate the state
Looks okay, but it is a bit hard to read because the GUI probably messed it up
but states(repeat.item) should work
Yeah the gui does mess it up I wish it didn't. I just tested the changes. The deviation was true. Perfect. But the temperature keeps nulling out.
Which Is so weird because as I said it works in the template editor.
Error rendering variables: UndefinedError: 'repeat' is undefined Error rendering variables: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
Do you get that repeat is undefined error in the template editor?
Nope that's an automation error
homeassistant.components.automation.new_automation77 Source: components/automation/__init__
If you put something like this at the the top of the template editor, the template seems to work without errors:
{% set repeat = { 'item': 'input_number.left_dockpro_temperature' } %}
{% set dockpro_condition = 4 %}
But I don't have these entities, so it doesn't render anything for me. But you can probably use it to debug your template
however, the variable repeat should be available in your repeat action
I will try.
And for the temperature deviation temperature? Any idea why it's null, it's a really simple template.
It does work in the template editor so weird.
{% set repeat = { 'item': 'input_number.left_dockpro_temperature' } %}
{% set dockpro_condition = '+' %}
{{ states(repeat.item) | int + int(dockpro_condition ~ 4) }}
Evaluates to 78
It will fail on this trigger:
- platform: state
entity_id:
- sensor.daniels_summer_temperature_overshoot
- sensor.master_bedroom_summer_temperature_overshoot
id: Overshoot Fallback
from: 'False'
to: 'True'
The trigger.entity_id won't have an attribute temperature then because it is not a climate entity
That's why I have the fall back thermostat variable. It works. It takes the object Id and changes it to the climate entity id
but not in the temperature deviation temperature variable
It's not meant for that action. It's meant to track the the attribute temperature changes from the trigger.id 'Temperature' only the overshoot uses the fallback thermostat variable to determine the correct thermostat
temperature_deviation_temperature: >-
{% if trigger.to_state.attributes.hvac_action == 'cooling' %}
{{ state_attr(trigger.entity_id, 'temperature') + 2 }}
{% elif states(trigger.entity_id) == 'cool' and states(trigger.entity_id) == 'idle' %}
{{ state_attr(trigger.entity_id, 'temperature') }}
{% elif trigger.to_state.attributes.hvac_action == 'heating' %}
{{ state_attr(trigger.entity_id, 'temperature') - 2 }}
{% elif states(trigger.entity_id) == 'heat' and states(trigger.entity_id) == 'idle' %}
{{ state_attr(trigger.entity_id, 'temperature') }}
{% endif %}
The 2nd and 4th statement can never be true, the entity has to have 2 different states at the same time
both (cool or heat) and idle
This template will also fail to render on the trigger Overshoot Fallback so you might want to make sure it only renders on the right triggers
looks like you want to check if trigger.to_state.attributes.hvac_action is idle instead of states(trigger.entity_id)
I didn't even notice that. It really should be HVAC action.
'idle' is an HVAC action
so that's probably why it didn't return a value, as you don't provide an else
temperature_deviation_temperature: >-
{% if trigger.to_state.attributes.hvac_action == 'cooling' %}
{{ state_attr(trigger.entity_id, 'temperature') + 2 }}
{% elif trigger.to_state.attributes.hvac_action == 'heating' %}
{{ state_attr(trigger.entity_id, 'temperature') - 2 }}
{% else %}
{{ state_attr(trigger.entity_id, 'temperature') }}
{% endif %}
why not use this?
Because it's a +2 when it turns on -2 when it turns off threshold in the winter and -2 +2 in the summer.
So idle and heat is different from idle and cool if that makes sense. The thermostat triggers above x in the summer and below x in the winter.
Yes, the +2 and -2 are still in
But all the other statements returned just the temperature
It should have always returned something if I was tracking the HVAC action correctly as an attribute.
That's fair
Then it would have had a temperature as one of them would have always been true unless it was off. But I think your way is cleaner.
And that's the goal
It also doesn't refer to a non-existing trigger attribute in case the trigger is Overshoot Fallback anymore, avoiding template errors.
That's a plus because I'm getting these errors. The repeat action worked once. But never again.
https://dpaste.org/Kygf0
hi guys, I'm trying to create an automation based on a template condition as explained to me before by TheFes on the linked message, but I'm not sure what I'm doing wrong.
As far as I can see, value_template is correct, but obviously is not because the automation goes to the default action everytime it's runned.
pastebin with automation code is here: https://pastebin.com/JYKxqpS0
thanks again for your help ๐
You need to put quotes around your entity_ids
states('sensor.whale')
Not: states(sensor.whale)
thanks. back in your message from the other day there was no quoutes around the entity_ids, why is that? is a diferent scenario or they are just missing? (asking in order to know more about this)
There are no entity_ids in that template
Only references to the this variable and now()
Without quotes you are referring to a variable
Temperature deviation worked, I used the cleaner template you sent. Now I'm just trying to figure out why the repeat is acting weird. Working 1 time and not the other times.
I don't see an error that repeat is not defined here
Something was blocking the automaton from triggering properly. It was greyed out but I could see the time.
It attempted to trigger.
It said nothing was executed essentially
oh, that's true. thanks again. I had a weeding last weekend from friday to saturday and I'm not longer in my 20s hahaha
I tried to change the template it's reading for repeat and I'm getting this error. The spacing is fine. It got messed up pasting it from the editor to dpaste.
https://dpaste.org/3P1ov
You are missing a + in your last statement
dockpro_condition == '-' and states(repeat.item) | int >= 89 %} {{ states(repeat.item) | int +
int(dockpro_condition ~ 4) }} {% endif %} ^ THERE
That's supposed to be concatenated? From the DockPro condition
No
You have the + in the statement above that
int(dockpro_condition ~ 4) creates an integer, which is either 4 or -4. You still need to add that integer to the current state
That's how you told me to do it I thought over the weekend. To concatenate.
I'm confused because this works
{{ states(input_number) | int + int(mode ~ 2) }}' it will +/- if the mode is + or if it's -
Yes, and you have the + there
{{ states(input_number) | int + int(mode ~ 2) }}
^ THERE
That's also what I have above no?
No in this post I added the +, in your code it is missing
dockpro_condition == '-' and states(repeat.item) | int >= 89 %} {{ states(repeat.item) | int
int(dockpro_condition ~ 4) }} {% endif %}
This is what you have
Ohhh now I see I thought I had it already.
{% set sign = -1 if x == '-' else +1 %}, then multiply everywhere. 100x more efficient
or something to that effect.
That would be dockpro_condition sign 4? For example?
{% set sign = -1 if dockpro_condition == '-' else +1 %}
then check for sign being > or < 0
then use sign in the calc
+ sign * 4
I see. +1x4 or -1x4
no, the sign does that
Yeah I don't use it anymore lol. So I would have never thought of this process.
parenthesis, exponent, division, multiplication, addition, subtraction
Yeah we had a McDonald's song and a dear aunt Sally to go with it in school. It just never comes to mind that pemdas can be used for this
I'm learning a lot from you 2. I went from using 0 variables in automations/scripts to changing everything from massive choose automations/scripts to variables everywhere.
So you could do this:
dockpro_condition: "{{ iif(trigger.to_state.attributes.hvac_action == 'cooling', 1, -1) }}"
{{ states(repeat.item) | int + dockpro_condition * 4 }}
same with mode
and instead of dockpro_condition == '-' you can use dockpro_condition < 0
With mode it would need to be different because of cooling -2 idle +2 and heating +2 idle -2
But it will work for the DockPro.
I meant that mode now also results in "-" or "+" which you can change to -1 or 1
and for temperature_deviation_mode you can then use mode * -1
I can see so much I would do different, and I know for sure you will see so much you will do different if you look at it again in a couple of months ๐
I see. this change may fix whatever was stopping the DockPro option from working reliably. Yes for sure even just a few weeks even I am thinking of how something could become more efficient. I never used an iif until a week ago and now I'm using it in 10 places probably.
Hi guys.
How to put in the template a condition if my humidity sensor is above some percentage?
Im getting the correct value when I type this {{states('sensor.bathroom_thp_humidity')}}
But I want something like
action:
- if: "{{states('sensor.bathroom_thp_humidity') > 53}}"
then: #do something
states are always strings, so you need to convert it to a number
"{{ states('sensor.bathroom_thp_humidity') | float(0) > 53 }}"
thanks @marble jackal I got it ๐
Hey TheFes I had to change the temperature service call to keep the state of the input number if idle else do +/-2 but I think I messed up something with the iif
- service: climate.set_temperature
data:
temperature: >-
{{ iif (trigger.to_state.attributes.hvac_action == 'idle', 'states(input_number) | int', 'states(input_number) | int +
int(mode ~ 2)') }}
Result:
params:
domain: climate
service: set_temperature
service_data:
temperature: states(input_number) | int + int(mode ~ 2)
I have a template sensor producing a url. Don't seem to be able to get a tap_action to open it though. Is that not possible?
tap_action:
action: url
url_path: >
https://uk.flightaware.com/live/{{ states('sensor.opensky_tracked_plane')
}}
depends on the card, most cards don't support jinja
custom:mushroom-template-card Not sure what it's based on
Nevermind I need to remove the '' around the input number and else statement
You may need to ask in #frontend-archived or on the forums.
There are some mushroom card wizards on the mushroom post.
Is it possible to break down (split) a value of a helper, containing a long number (or text of numbers)?
like using first 5 digits, then using next 5 digits...
something like [:5] in python
like that?
"{{ states('input_text.kitchen_zone')[:5] | int }}"
working, thanks
Trying to make a binary sensor that display off when my lux is lower than 120
```ceiling_light_state:
friendly_name: "Ceiling Light State"
value_template: >-
{%- if states('sensor.0x00158d000704f8e4_illuminance_lux')|float < 120 -%}
Off
{%- else -%}
On
{%- endif -%}```
However I get an unknown
nvm the hyphens
got it
Just use
ceiling_light_state:
friendly_name: "Ceiling Light State"
value_template: >-
{{ states('sensor.0x00158d000704f8e4_illuminance_lux')|float < 120 }}
Hello, I have a few ceiling fans that I'm trying to control with Broadlink RM pro via RF. I have learned the codes.
Can't figure out how to work with the new speed templates for the fans, I had fans more than a year ago and it worked with speeds without templates. Now it seems to have changed and a lot of outdate and confusing information.
Anyone has such config working perhaps?
Was told to post this in here
Im trying to do very basic maths in an integration, haven't had to use YAML before, so not sure how I'm meant to do it, trying to set a helper value to calculate excess solar, since I know total usage and solar, but just not excess solar, got the automation running every 5 mins, and trying to get it to set correctly, below is the setting, its not working, but not sure what to change to make it work, I know the 2 entities are correct, its just the syntax im not sure about
data:
value: {{ {{ sensor.inverter_zina_goodwe }} - {{ sensor.goodwe_monitoring_91000hku21b01692 }} }}
target:
entity_id: input_number.excess_solar```
There is a lot wrong here
I figured there would be, this is my first attempt at trying to do yaml, done everything else in the GUI so far, just saw on the input_number examples they used the {{ }} to wrap values
Got it working with a template sensor instead, much better solution than what I was trying to do, and the docs for it showed the proper syntax as well
- sensor:
- name: "Solar Excess"
unique_id: solar.excess
unit_of_measurement: "kw"
state: >
{% set generation = states('sensor.inverter_zina_goodwe') | int %}
{% set consumption = states('sensor.goodwe_monitoring_91000hku21b01692') | int %}
{{ generation - consumption }}```
You are nesting templates, you are not using quotes inside and outside your template
You you are not getting the state of your friends entities
You are not casting the strings (which states are) to a number so you can use them in a calculation
You are doing that all now (took me some time to type this)
Well no quotes outside your template, but you are now using the multi line notation
I also saw the post on Facebook, you can do it in a one liner
I'd prefer the multi-line, more explicid, but someone on facebook said it eneds up needing to use python because of the sets or something, need to look up any performance implications etc, would rather figure it out now, im sure I'll end up using many more template sensors etc over time, only going to add more and more automations and calculations, I'm about to add 30+ devices in the next couple months
template:
- sensor:
- name: "Solar Excess"
unique_id: solar.excess
unit_of_measurement: "kw"
state: >
{{ states('sensor.inverter_zina_goodwe') | int - states('sensor.goodwe_monitoring_91000hku21b01692') | int }}
That's not true, it's all Jinja
I don't think it has any effect on performance, and it increases readability
I think the multi-line is more readable, the extra-long line redability changes to much with line length
๐
Any idea why this isn't continuing past the input number set value when it is null? I added continue on error for this reason but the script is stopping.
https://dpaste.org/pVY4h
Stopped because an error was encountered at June 22, 2022, 5:53:11 AM (runtime: 0.09 seconds) It stops on the climate service call. Because the input number failed because it was ''
Put the whole service call in an if-then so it only runs with a valid value
Didn't think of that, that's a good idea thank you.
Hi, I'm trying to bold text in notification template that's part of my automation. Tried using single asterisk () and triple (**) but with no success. Is there some way other way to do it?
depends on whatever you're sending the notification to and whatever langauge it accepts for formatting
Using Gmail
I've tried it in the development tab but it doesn't format their either
right, but the development tab doesn't do formatting
Gmail excepts HTML, so that's how you'll have to make things bold.
All right, I'll give that a try
Is it possible to bold text in push notifications from HA?
pretty sure that also accepts html
did you include the ending characters?
Yup. Also tried including <hmtl></html> and <body></body>
Then it may not be possible
All right, thanks anyway
If your RF codes are stored in your broadlink as numbers 1 to X where 0 is off and X is the maximum speed, then you can just use remote.send_command with the command templated:
{% if target_fan_power == false %}
Off
{% elif ((target_fan_speed | int) / 100 * X) | round(0) | int == 0 %}
Off
{% else %}
{{ ((target_fan_speed | int) / 100 * X) | round(0) | int }}
{% endif %}
Since the template fans now return the fan speeds as a percentage in range [0,100], you may need to convert from the percentage to your numerical fan speeds
i got a helper and i am trying to check if the date in my helper is todays date.
can someone help me get this here right, so that is returns true/false:
{{ {{ states("input_datetime.staubilastrunburo")[:10] }} ==
{{ now() }} }}
You have way too many {{ }}
Depends on how exact you want to be (include seconds? no?)
{{ (states('input_datetime.date_test')|as_datetime).replace(second=0) }}
{{ now().replace(microsecond=0).replace(second=0).replace(tzinfo=none) }}
{{ (states('input_datetime.date_test')|as_datetime).replace(second=0) == now().replace(microsecond=0).replace(second=0).replace(tzinfo=none) }}
In his post he mentions date:
{{ as_local(as_datetime(states('input_datetime.test'))).date() == now().date() }}
oh, nevermind :). Much easier
{% if trigger.idx == 1 or trigger.idx == 2%} camera.doorbell_main {% elif trigger.idx == 3%} camera.garage_camera {% endif %}
is there anything wrong with that code?
i keep getting an invalid entity id error
it's the first action calling camera snapshot
if i remove the trigger idx stuff the entities work
seems like the if statement is causing the problem
i replaced all the references to trigger.idx with numbers and the code works.
Thank you, unfortunately they are not, but I guess this can be changed?
trigger.idx starts at 0
Was just going to ask that ๐
Just checked in a trace of my own
was wondering about that, but the code still doesn't work
Was not sure myself
somebody should update the docs
If you give the triggers the entity_id as trigger id, you can just use:
target:
entity_id: "{{ trigger.id }}"
Or a trigger variable (as they already have a trigger id)
trigger:
- platform: something
variables:
snapshot_target: camera.doorbell_main
I will try your suggestions, but that simple if statement should work right?
Yes, with trigger.idx 0 to 2
And maybe use an 'else' as the last bit
And a space between 1 and %} I guess ( where you had 2%}
And also in the other statement
Where you had 3%}
{% if trigger.idx <= 1 %}
camera.doorbell_main
{% else %}
camera.garage_camera
{% endif %}
is there an editor or something to catch syntax errors like that?
> templates
But that is tricky with trigger variables. But if will error on syntax errors before it will error on the missing variable
You can always define it for testing purposes:
{% set trigger = { 'idx': 1 } %}
ahh nice. will definately use that
kinda dumb that the parser trips on that, considering that %} should be readily identifiable
I wonder if you can use that in a string ๐
I'm trying to get my head around this and why this is not working```
{% if is_state('input_select.speaker', 'Kitchen') %}
{% set active_speaker = 'media_player.kitchen_speaker_cast' %}
{% elif is_state('input_select.speaker', 'Living Room') %}
{% set active_speaker = 'media_player.living_room_speaker_cast' %}
{% endif %}
Test: {{ is_state('{{active_speaker}}', 'idle') }}
I have been testing this on the GUI under templates
you're using quotes around the variable
which makes it a string
and you're also using is_state() incorrectly at the end
look at the others...
That was an accident - Fixing it quickly.
Should the syntax be {{ is_state({{active_speaker}}, 'idle') }}
Or am I looking at the wrong quotes?
{{ is_state({{active_speaker}}, 'idle') }}
Error to: TemplateSyntaxError: expected token ':', got '}'
Doh! Seems I was trying to over complicate it - Thank you for pointing me in the right direction.```
{{ is_state(active_speaker, 'off') }}
Just want to thank everyone that has assisted me on here - Without the help I received here, my HA instance will not be half as awesome as it it. Much appreciated!
Is there any way I can easily make my items in the sidebar permanently ordered a certain way without having to manually do it for every device?
I was reading so far the only thing I saw was making a custom sidebar but that seems kind of excessive for just wanting to make sure the side bar items stay in a certain order
How do you currently have your broadlink codes learned? It should be in some sort of dictionary, if you look into the files in .storage:
{ X1: xxxx,
X2: xxx,
X3: xxx,
...
}
What are the X1, X2...?
Low, Med, High.
Then something like this may work:
{% if target_fan_power == false %}
Off
{% elif target_fan_speed | int(0) == 0 %}
Off
{% elif target_fan_speed | int(0) <= 33 %}
Low
{% elif target_fan_speed | int(0) <= 66 %}
Med
{% else %}
High
{% endif %}
Idea is to map the percentages coming out of the fan speed to your commands saved in Broadlink.
Does anyone have an elegant / oneline way of comapring if a datetime is today. i.e. 2022-06-23 00:00:00 is today?
This is what I have. Happy for improvements to be suggested:
{{ now().date() | string == strptime(states('sensor.next_dry_laundry_day'), '%A %d %B %Y')|as_timestamp|timestamp_custom('%Y-%m-%d') }}
The original sensory state example is Thursday 23 June 2022 It's a string rather than a datetime object or UNIX timestamp.
{{ now().date() == strptime(states('sensor.next_dry_laundry_day'), '%A %d %B %Y').date() }}
changed it (jinja edit ๐)
Thanks. Was just about to say it failed.
That, works now.
what would be the best way to turn this into a template:
trigger:
- platform: time
at: '05:00:00'
condition: []
action:
- service: input_number.set_value
data:
value: '{{ states(''sensor.outside_home_thermometer_temperature'') }}'
entity_id: input_number.outside_min_temp
I want it to display the temp at of that sensor at 5am.
then I only want it to change if temp drops below that 5am that day
I don't understand this part
well if at 5am the temperature is 8 and then sometime that day it goes to 7 I want it to change the template state to 7 as its lower than the temp at 5am
Is there a way to get strptime to work using map on a list?
I.e.
{{ state_attr('sensor.next_dry_laundry_day', 'forecast')[1:]
| map('strptime', '%A %d %B %Y')
| list }}
Jinja throws an error TemplateRuntimeError: No filter named 'strptime'.
The add that as a trigger
trigger:
- platform: time
at: '05:00:00'
- platform: numeric_state
entity_id: sensor.outside_home_thermometer_temperature
below: input_number.outside_min_temp
Guess you need a for loop with a namespace for that
Or is there a way to use map to remove the last 5 characters of every item in the list?
Same way I guess ๐
is there a way to make it into a template instead of a automation?
Create a trigger based template sensor using the same triggers?
i guess there is a datatype problem, but why is this returning false, even thou both is 2022-06-23
{{ states("input_datetime.staubilastruneingang")[:10] == now().date() }}
I already answered that yesterday
ah. didnt see. let me check. sry
working. thank you guys!
how can i combine two statements, each of them returning true/false on their own into one statement, so that if at least one returns true, the entire statement returns true?
example:
statement1: is it raining? (yes)
statement2: is today sunday? (no)
what i am looking for statement: is today sunday, or is it raining (yes)
got it. however its very ugly ๐
https://dpaste.org/gWsYs
That's very ugly indeed
- platform: time
at: '05:00:00'
- platform: numeric_state
entity_id: sensor.outside_home_thermometer_temperature
sensor:
- name: "Outside Min Temp"
availability: "{{ not is_state('sensor.outside_home_feels_like_temperature', 'unavailable') or is_state('sensor.outside_home_feels_like_temperature', 'unknown') }}"
state: ???
what would I make the state of my sensor to show the min temp of my sensor? I want to remove the need of 'input_number.outside_min_temp' entirely
I can't find many template examples to figure this out
- trigger:
- platform: time
at: '05:00:00'
- platform: numeric_state
entity_id: sensor.outside_home_thermometer_temperature
below: sensor.outside_min_temp
sensor:
- name: "Outside Min Temp"
availability: "{{ not is_state('sensor.outside_home_feels_like_temperature', 'unavailable') or is_state('sensor.outside_home_feels_like_temperature', 'unknown') }}"
state: '{{ states(''sensor.outside_home_thermometer_temperature'') }}'
This should work i guess
can I use the templates entity inside the template?
below: sensor.outside_min_temp
yes, for the trigger that doesn't matter
{% set utc_midnight = today_at().astimezone(utcnow().tzinfo).isoformat() %}
{{ states.input_number | selectattr('entity_id', 'match', '^input_datetime.staubilastrun') | selectattr('state', '>=', utc_midnight) | list | count > 0 }}
assuming you have no other input_datetimes with that naming convention
Is there a trigger or a template that detects when the automations are reloaded?
Perfect.
how do you do an or opeartor in a template (i.e. or, ||, etc?
nvm i assume its just the word or since i can use the word and
Correct
trying to fix this janky count of lights on :/ its showing 3 extra entities which means 0 lights off echoes -3 etc
Hello all, I am trying to set the new badges on my mushroom cards but I cant seem to get the template to work for a reading of a sensor. I built a fart sensor for the bathroom and I want to set a badge if there is a high TVOC levels. This is what I have but its not setting the badge and the sensor is over 1. Will adjust after its working.
{% if is_state('binary_sensor.basement_bath_pir_sensor', 'on') %} mdi:paper-roll {% elif is_state('binary_sensor.basement_bath_pir_sensor', 'off') %} mdi:cancel {% elif is_state('sensor.basement_bath_tvoc', | float > '1.0' ) %} mdi:scent {% else %} {% endif %}
{% elif is_state('sensor.basement_bath_tvoc', | float > '1.0' ) %}
That part is not correct, use:
{% elif states('sensor.basement_bath_tvoc') | float > 1 %}
.share the code so we can have a look
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 i have been banging on this for a while i need some tips... I want to count how many lights are on but i do not want to count the lightswitches - I only want bulbs (Hue)
I have tried this:
{{ states.light | selectattr('state', 'equalto', 'on') | list | count }}
but that counts the switches too and anything in the light domain.
since each light has a unique name i thought maybe i could check each one and increment a count but that is dumb and messy
nvm got it working.... never fails you spend hours then after you ask you figure it out
I'm trying to create a variable so I can add it and get the result but it's not working. Where did I go wrong?
{% if loop.last %}
{% set bca = (loop.index|int) %}{% endif %}
{% endfor %}
{{bca + bcb}}
i'm testing in dev tools in order to get it working before putting it into action.
You're missing at least the start of the for loop...
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.
Here is the full code: https://www.codepile.net/pile/RV9GAQK6
I only want to get the count if all criteria is met. I was building as I went so it could also be two ideas merging into one.
This will be used for a "status report" that gets fed to Alexa for devices that have low battery conditions
Well, tip 1: break things down into smaller chunks. You're repeating yourself with item.name | lower, and a good rule for programming is DRY (don't repeat yourself)
Did you look at using something like this?
states.sensor | selectattr('attributes.device_class', 'eq', 'battery') | selectattr('state', '>=', '90')
That's just a snippet, but it'll grab all the batteries for you pretty neatly
you'll have to excuse me, the HA platform is new to me so I am learning (and googling) as I go... I'm used to other languages. if I remove that, the code fails (item.name....) so not sure what I would put in place of or the best optimization for the code.
Well, set a variable ๐
well, honestly, the code I am using I found and it worked so I stopped googling lol.
Jinja Template Designer Documentation
Much of the power of Jinja comes from its filters and tests.
For more examples and samples, visit see this page.
Here's a small template which might get you off to a better start:
Paste the following code into the Template Builder in Developer Tools to list all sensors and their names:
{%- set domains = [states.sensor] %}
{{ \"Entity ID\".ljust(50) }} {{ \"Entity Name\" }}
{%- for domain in domains %}
{% for item in domain %}
{{ item.entity_id.ljust(50) }} {{ item.name }}
{%- endfor %}
{%- endfor %}
so, that errored out when I pasted it hah.
TemplateSyntaxError: unexpected char '\' at 40
Well, this is a quick attempt at simplifying what you currently have:
{% for item in states.binary_sensor %}
{% set item_name = item.name | lower %}
{% if (
"battery" in item_name
and not "voltage" in item_name
...
and not "pixel" in item_name
and "off" in item.state | lower )%}
{{ (item.name+' '+item.state) |regex_replace(find=': Low Battery Level', replace='', ignorecase=true) |regex_replace(find="'", replace='', ignorecase=true) |regex_replace(find=",", replace='', ignorecase=true)}}
{% if loop.last %}
{% set bca = (loop.index|int) %}
{% endif %}
{% endif %}
{% endfor %}
But you still have a lot of repetition in there, what are you trying to achieve?
I get what you did. For some reason it added massive space between the items. I am essentially trying to list all sensors and binary sensors that indicate a low battery condition. I want to count each of them, (IE: 3 sensors and 2 binary sensors) and then add the two values together to get, in that case, 5 devices. Then i'll pass that to the Alexa notify service to tell me about it once a condition I set is met.
{% set battery_sensors = states.sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'battery') | map(attribute='entity_id') | list %}
{{ battery_sensors }}
That's a list of the entity IDs of battery sensors.
You could add in rejectattr('state', 'in', ['unavailable', 'unknown', 'discharging', '100']) | after selecting the battery, and a further filter for battery < your_threshold_here
Then after all that you could instead have {{ battery_sensors | join(', ') }} which will do a nice comma separated list.
Well, that is definitely cleaner code haha. I'm looking at it trying to get that filter in place.
Do it before the map, the map takes your objects and changes them into strings of entity_ids (have a play to see what else you can return there too)
For the numerical filter < 25, is it as simple as '<25' because that feels wrong on all levels to me hah
It's a bit tricky to do in a one liner, because the state is actually a string
{% set battery_sensors = states.sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'battery') | rejectattr('state', 'in', ['unavailable', 'unknown', 'discharging', '100']) | sort(attribute='state') | map(attribute='entity_id') | list %}
{% set low_battery = namespace(sensors=[]) %}
{% for battery in battery_sensors %}
{% if (states(battery) | int) < 30 %}
{% set low_battery.sensors = low_battery.sensors + [state_attr(battery, 'friendly_name') ~': '~states(battery)~'%'] %}
{% endif %}
{% endfor %}
{{ low_battery.sensors | join(', ') }}
That's probably what I'd do. The array creation is a bit of a hack, but it works
Updated to include the battery %, and sort them lowest to highest (most urgent first)
oh nice. thanks for the help so far, btw. I think I almost have it.. I just have to get the counting in place but I have an idea on that already.
You have an array, use the | length filter on it ๐
{{ low_battery.sensors | length }} will tell you how many items
I was count to "|count" it lol
*was going to
my brain and fingers are beginning to disconnect already
I'm not sure why the sort isn't quite working for me, everything is great, 1% up to 27%, and then an 8% ๐ค
haha. story of my life sometimes.
But as I have 6 in order, I'll blame the IKEA integration that I've almost done away with for now ๐
so I added:
{% set bsa = low_battery.sensors | count %}
then duplicated what you did for binary sensors (adjusted accordingly)
then added
{{ low_bbattery.sensors | count }}
{% set bsb = low_bbattery.sensors | count %}
{{ bsa+bsb }}
haha. You had to compile the IKEA integration yourself, right?
๐
Nope. I'm replacing it with Zigbee2MQTT. Much more stable
'twas an Ikea joke.
Seems reasonable.
Though another programming trick: variable names are free, and descriptive ones help avoid headaches and confusion ๐
oh I know.. I am also lazy too so there is that. lol
find and replace is a great friend of mine.
if it's something I can do, how can I comment out code lines in templates.
In the YAML file you can use # at the beginning of the line
what about the actual template, like in the dev tools template editor.
In dev tools/jinja wrap your line with {# #}
of course. I tried everything BUT that...
I swear this used to work but it doesn't any more:
{{ states.person | select('eq','home') | list | count }}
It returns and empty list though someone is home
I searched this channel and this similar one does work:
{{ states.person |
selectattr('state', 'eq', 'home') |
map(attribute='name') |
list | count
}}
Just finding it odd :/
I don't see how the first one would have ever worked
Looking in the doco I can't even see a function called select()
Ah yeah, I see why the map() isn't needed . List size is the same regardless
They are states, so strings. And string sorting is based on the first character.
So "8" > "23" returns True
(as it becomes: "8" > "2" == True)
a great gotcha in programming; everyone will hit that one once ๐
would have worked with leading zeroes, or if there was a way to cast values to another type while using filters. I know petro was working on that for select and select_attr