#templates-archived
1 messages · Page 107 of 1
it still wont work
i fixed the errors
data:
power: true
transition: '{{ states("input_text.fade_time")|float }}'
color_name: red
brightness_pct: '{{ states("input_number.end_brightness")|int }}'
entity_id: light.ceiling```
Then you now have new errors...
i wont update the light
The template change in 0.117 broke some things for me.
I've had an mqtt.publish with a data_template which returned a json string. Now it's returning something different I guess
how do I cast that to string?
Hello everyone
I'm trying to build a template to dim all the lights that are on
It's a bit ugly - it has the first one hard-coded because it doesn't want to mess with commas, for one.
Is there a better way of saying "all the lights that are on in the bedroom" ?
Any idea why this is still evaluating to false? value_template: "{{states('sensor.date') and now().weekday() in (0,1,2,3,4)}}"
@balmy wedge if they're part of a group, yes
I have them in an area_id if that works, otherwise I can build a group, sure
@dapper aurora What do you get with {{ now().weekday() }}?
@balmy wedge This outputs a comma-separated list of entities in a group with a specific state:
{{ expand('group.fr') | selectattr('state', 'equalto', 'off')|map(attribute="entity_id")|join(',') }}
Oh, brilliant!
Thank you
It's a pity areas aren't more useful, or don't automatically create an alias group
i am trying to do something very similar to stereo, except I would like to select all circadian lighting switches: states.switch | selectattr('object_id', 'startswith', 'circadian_lighting') no test named startswith I can't seem to find a test to accomplish this
something like this perhaps:
{% for i in states.switch if i.entity_id.startswith(‘foo’) %}
- {{ i.entity_id }}
{% endfor %}
ooo
i didn't realize i could use templates like that in an automation, i thought it would need to be a string join in the entity_id field
data:
entity_id:
{% for i in states.switch if i.object_id.startswith('circadian_lighting') %}- {{ i.entity_id }}
{% endfor %}``` Invalid data for call_service at pos 1: not a valid value for dictionary value @ data['entity_id']
looks perfect in the dev tool template editor.... guessing that's not the right syntax though
you would need entity_id: >-
Hmm, the template expands in the 'template' tab in the dev tools, but I can't figure out how to pass that to lights.turn_on
and proper indentation
Oh, is that an answer for us both? 🙂
entity_id: >-
{% for i in states.switch if i.object_id.startswith('circadian_lighting') %}
- {{ i.entity_id }}
{% endfor %}
could be. what are you doing?
entity_id: >-
{{ expand('group.bedroom') | selectattr('state', 'equalto', 'on')|map(attribute='entity_id')|join(',') }}
if it doesn't like the list, you could do something like this:
entity_id: >-
{%- for i in states.switch if i.object_id.startswith('fr_') -%}
{{ i.entity_id }}
{%- if not loop.last %},{%endif%}
{%- endfor %}
@balmy wedge What does it do?
"Failed to call service light/turn_on. not a valid value for dictionary value @ data['entity_id']"
show the whole thing
Oh, I'm just calling it from the dev tools > service thing
that has issues with templates
Service: light.turn_on, and in the field below, that code
Ahh
That's good to know
It's not doing any better in the automation I'm trying to build
thanks for trying robc, but neither of those variants worked
service: light.turn_on
entity_id: >-
{{ expand('group.bedroom') | selectattr('state', 'equalto', 'on')|map(attribute='entity_id')|join(',') }}
transition: 1
brightness_step_pct: -30
you need to have a data: block
Ah, I tried that and that didn't work either. Let me try again.
see the examples in teh docs: https://www.home-assistant.io/integrations/light/
Ah, that's excellent
you'll have a problem if there are no matches, though
easy enough to fix by putting a condition: block above it that checks if the group is on, meaning that any of the entities are on
no, it will produce an empty list, which will make the service sad
so you need to make sure that you don't call it if it will be empty
data:
entity_id: "{%- for i in states.switch if i.object_id.startswith('circadian_lighting') -%}{{ i.entity_id }}{%- if not loop.last %},{%endif%}{% endfor %}"``` got it working!
doesn't work if entity_id is top level but does work if it's part of data
yes, that's correct
if you specify the actual string directly it works as part of the top-level, but it appears the template is not expanded in that position
either way! working! thanks
correct
entity_id: is one of the few things that can live outside data:, but it's more limited that way
So I just add a condition for state: group.bedroom: on ?
with proper syntax, yes
entity_id: group.bedroom
state: 'on'```
- condition: state
entity_id: group.dr
state: 'on'
Perfect 🙂
yes, like that 🙂
@balmy wedge would you mind sharing the complete automation? I might need it in the future 🙂
hi, Im looking for dynamic turning off all of my automations except a few..
something like automations.*
with a wild card, but after that something like ```except:
- automations.automation33
- automations.automation34
- automations.automation35```
I'm not sure something like that exists. What are you trying to do?
Generally, if you're turning automations on and off, your logic isn't good enough somewhere else.
Im basically trying to implement "Guest mode"
or "Vacation mode"..
input_boolean, when its on
So have input booleans for those modes and add those as conditions in automations.
to shutdown some automations
so if I understand you right, in each automation which I want to control from toggle boolean
I need to add false condition for that bool
?
in each automation? :)_
🙂
In each one that cares about 'guest mode' or 'vacation mode', yes. But that's a discussion for #automations-archived
yes ofc, but I was thinking that it could be solved via templates..
A template just returns a value. It doesn't control anything.
Templates won't turn off automations.
oh, I see
{% set alert = false %} {% for forecast in state_attr('weather.farm', 'forecast') %} {%- if forecast.temperature | float > states('input_number.bee_forecast_high') | float %} {% alert = true %} {% endif -%} {%- endfor %} {{ alert }}
trying to make a alert if any forecast days have temp higher then a input_number i set, how do i return a true value ?
is the template checking for True/False string or a boolean type?
Try True/False
TemplateSyntaxError: Encountered unknown tag 'alert'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
im not sure how to change the variable value inside from inside the loop
oh, yeah, you need to use a namespace
Example: #templates-archived message
and set you need set alert = True
okay
thanks worked, is True a Boolean or string? also will this namespace only be around while the binary_sensor runs? like if where to use same namespace in a different template will i have access to it?
ok thanks a lot
{{ True if state_attr('weather.farm', 'forecast')|map('float')|select("gt", states('input_number.bee_forecast_high')|float)|list else False }}
masterpiece 😄
it was bound to happen 🙂
lemme know when you finish the complete beekeeper package 🙂
wazzat?
presumably this is just one piece of a bigger puzzle
oh, prolly
it's fun to see the varied things that people are trying to control. Lights/motion sensors are so played out
yea basically its my bee storage, have to manage temperature, humidity and co2 in order to keep as many hives alive by spring HA is helping automate it a lot
@harsh anchor posted a code wall, it is moved here --> https://paste.ubuntu.com/p/6sgVPZzCN8/
I love you bot for taking the entire message to pastebin 💗
it's been a couple days I'm banging my head on this, still can't make it work
I have this sensor sensor.qnapups_battery_runtime that gets the battery runtime in seconds
I then create a template like so
https://paste.ubuntu.com/p/qpRrrG6ZZ9/
but it doesn't work
tried many permutations of the value template, but no joy
what am I missing?
{{ states('sensor.qnapups_battery_runtime') | float(0) / 60 }}
Also the bot did that because you forgot about the rules 😛
Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
@buoyant pine was it more than 15 lines? have to start writing messages in my code editor lol 😅
The entire message was (granted, you were just barely over)
Will this work as a trigger or do I need to add == true at the end
trigger:
- platform: template
value_template: "{{state_attr('sensor.riverrace', 'clan')['finishTime'] is defined }}"
i only want it when true, so ya i probably do
Output of that should be true/false already
why wont this work?delay: '{{ states(''input_number.off_delay'') | multiply(60) | int }}' power: false transition: 10 color_name: orange brightness_pct: 1 its in a script btw
I would replace the double simple quotes by double quotes
ok
https://pastebin.com/raw/t3uy0Nt1
error:Error executing script. Invalid data for call_service at pos 2: extra keys not allowed @ data['delay']
1 space too much on that delay element
value_template: > {{ states(sensor.qnapups_battery_runtime) | float(0) / 60 }}
keeps coming out as non numeric whereas the original is numeric, what's wrong with it?
@thorny snow check those spacings, the last line also looks lost
and share the errors
@harsh anchor , you miss the quotes around sensor.qnapups_battery_runtime
value_template: > {{ states("sensor.qnapups_battery_runtime") | float(0) / 60 }}
ok trying now
@thorny snow check those spacings, the last line also looks lost
and share the errors
@coarse tiger it all should be correct
value_template: > {{ states("sensor.qnapups_battery_runtime") | float(0) / 60 }}
@deft timber 🍻 🍻 🍻 🍻 🍻 🍻
finally! thanks man
@harsh anchor why you using float(0), default is zero, just omit it
{{ states('xx.xx') | float / 60 }}
ok thanks
- conditions:
- condition: template
value_template: "{{ states.speaker.state != 'on' }}"```
how can I these choose segment to re-write shorthanded?
obviosly I have only one condition
so I think that conditions tag is wrong
- choose: - conditions: "{{ states.speaker.state != 'on' }}"
thanks @deft timber that I was looking for 🙂
{{ states.light | map(attribute='entity_id') | list | join(',') }} gives me a list of all entities in the domain light,
but how do I get a list of all "light.hue*", all lights with an entity name starting with "hue"?
you could check for attribute, normally they advertise platform:hue if I‘m not mistaken
thanks, but hue was just an example, what I really want is to trigger for the first letters. lika all automations starting with "automation.t" or ..
@waxen rune you have to use namespace and check the string itself
hmm, thanks. not sure what that means (yet). reading the jinja documentation now. but one thing is clear, it wasn't as easy as I imagined 🙂
Why I have an error in this script
its regarding my choose statements
Invalid config for [script]: [condition] is an invalid option for [script]. Check: script->script->set_speaker->sequence->3->choose->0->condition. (See /config/configuration.yaml, line 19)
Sooo. With 0.117 there will be native types support for templates but yeeah. I am not getting it. Can someone lead me in the right direction?
For ex. this automation is giving me this error:
Invalid data for call_service at pos 1: value should be a string for dictionary value @ data['payload_template']
trigger:
- entity_id: input_number.couch_led_animation_speed
platform: state
action:
- data_template:
payload_template: '{"speed": {{ trigger.to_state.state | int }}}'
retain: true
topic: home/McLightingRGBCouch_ha/state/in
service: mqtt.publish
is it possible to somehow do a call of another services in template
like this
data_template:
entity_id: >
{{ speaker_entityid }}
source: >
{% if is_state("type", 'Spotify') %}
AVR Zone2
# - service: spotcast.start
# data:
# device_name: Denon AVR-X2400H
# entity_id: media_player.spotify_stefan
# uri: 'spotify:playlist:37i9dQZF1DX9loJQLuEvap'
# force_playback: true
# random_song: true
# shuffle: true```
so, after setting my Source and if the source is Spotify
to call service for playing spotify list?
Have a look at this: https://community.home-assistant.io/t/counting-watt-usage-of-tasmota-devices/232489/2?u=tom_l
@fossil venture Thanks!. Good for inspiration. Trivia: I just made HA restart spontaneously while trying out my code in Developer Tools
After a couple of more spontaneous restarts, I got this to work.
{% set ns = namespace(val=[]) %}
{% for s in states.sensor
if s.entity_id.startswith('sensor.idlock') and not s.entity_id.endswith('tmpl') %}
{% set ns.val = ns.val + [ s.entity_id ] %}
{% endfor %}
{{ ns.val | join(', ') }}
@late island the change in 0.117 shouldn't affect what you're doing - there's no need to add the "|int" filter because a string is fine
you should change data_template: to data:, too, but that's not your problem here
Hi Guys, I've got a problem with grouping thermostats as climate group.
I made a custom sensor which shows me if thermostat is heating or in idle mode.
I wish to make a group to check if any of thermostat is heating
But a group of custom sensors have a status unknown for all time,
Yeea. That really wasn't the problem.. Still getting Invalid data for call_service at pos 1: value should be a string for dictionary value @ data['payload_template']
action:
- data:
payload_template: '{"speed": {{ trigger.to_state.state}}}'
retain: true
topic: home/McLightingRGBCouch_ha/state/in
service: mqtt.publish
@green girder Soo what exactly is the group needed for? Like why do u need to know if any of the thermostats are heating? Maybe this Custom Component can help you. Not sure because I dont really get why you want to know that. https://github.com/daenny/climate_group
Soo if you want to know how long a boiler is heating you could use something like this. https://community.home-assistant.io/t/monitor-long-your-hvac-system-runs-per-day-or-month/75451
Any Idea on my Problem @inner mesa ?
@late island Not really. works fine in
-> Templates with a regular variable, so might have something to do with the value of trigger.to_state.state. You could stick that in a persistent_message to see what it really is. You also need to let the automation trigger so that it actually has a value
Also an Error on another automation.
Invalid data for call_service at pos 1: template value should be a string for dictionary value @ data['attributes_template']
that's custom_component, right?
Yup
you can always add "|string" to force it to a string
the custom_component may act unexpectedly with this change
0.117 stuff should be in #beta
Good evening, I wanted to know how to convert the signal "on" "off" from a motion sensor (which gives continuous changes between on and off even with presence) to a sensor that does not detect motion when there is no person for more than x minutes . I do not know if I have explained myself well, but I attach screenshots of what I have and what I am trying to achieve. Thank you!!
@thorny snow I guess you mean that if it detects an ON, it should stay on for some time before going off, right?
do you also need it to stay off for some time when it goes off?
exactly
Thank you very much
give this a try, you have to customize it to your sensor
also your sensor may already have such parameters, for example I have a zwave PIR sensor that has such parameters in it already
in the code there is a delay only for turning off
but it will immediately turn on
if you wish to delay turning on too, you can add delay_on: "00:03:00" to it
you're welcome 🙂
Can someone give a look at this template code : https://paste.ubuntu.com/p/VkK3h4VqHD/
i would like to have a datetime variable that holds the timestamp of the start of motion detected
group.buzz is a group of motion sensors
Good evening folks... I am trying to use {{utcnow().month}} in a template, but I was hoping to get the name of the month, not the number. Is there a way?
A quick reference for Python's strftime formatting directives.
utcnow().strftime("yourformat")
lol teach a man to fish
Would this be the right channel to ask about help formatting a rest get call?
I've tried to learn for various projects the last year and it never makes any sense to me
might be more for #general-archived or #integrations-archived depending on what you are trying to do
Could someone help me with something? I want to turn on a light with an automation but the brightness of that light needs to be time based. so between 23:00 and 7:00 the lights brightness need to be 30 and the rest of the day it needs to 80. is there a tutorial for time in a template? the trigger of the light is a binary motion sensor
maybe someone can give me a push in the right direction, i can do the rest
If you just want them to come on at a certain brightness, do that in the automation. Using a template seems overkill.
why would you need a template for that?
seems this is more automations
anyway, here's mine depending on the sun state: https://paste.ubuntu.com/p/sN6nX9JGfK/
easiest would be 2 automations with time conditions
yes i guess im thinking to hard. 2 automations with conditions would indeed be allot easier
Is there a way to calculate monthly average of a temp sensor?
The statistics integration might be what you're after.
Yeah, but it is hard to use, because for calculating the average (or anything) for the month, you need to know how many samples that will include...
I was looking at the HA-Average custom component, which looks promising, but I would have to template the start and the end of the calculations.... https://github.com/Limych/ha-average
The max age option documentation mentions that you´d have to increase sample size as well....?
yeah I coudn't figure that out myself in some cases, this average component looks good though
If someone would help me do the template stuff (which, in this case case is way to complicated for me) I agree... The average custom component looks perfect!
What if you choose a really high sampling_size and limit through the max_age ?
Small issue still... The max age would only be correct every other month and way off in February... 😛
From the average sensor docs:
start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}'
end: '{{ now() }}'
The example end: parameter would work for me, but I would need a "template" that got me to the first day of the month...
.replace(day=1)
.replace(day=1)
(I don't know Python)
I’m just guessing, BTW
legends
Now, I need the automation that this average data is used in to trigger at the end of every month.
Well you know where to find the #automations-archived channel.
Yeah, but I am pretty sure they´re gonna throw me back here to use a template as a trigger... 😉
But, I can try! 😄
Well you already know how to make a template that picks the first day of a month. Can't be too hard to get one that picks the last day...
is there a way in a template sensor to us a variable value as the friendly name?
or as part of the friendly name
Thanks! There's so many template related pages I keep getting lost
or did you want it to change dynamically?
Change it dynamically
Ideally it'll be taking what I get from a rest sensor and renaming based on one of the values
Yup seems to be working!
ah crud, I can't add that variable name to a constant secondary identifer.
what is that?
ideally I want a series of sensors '{{ states.sensor.batches.attributes["name"] }}' & a secondary identifier such as status, abv, date
nope I'm just an idiot. I didn't change that one from friendly_name to friendly_name_template...
to turn off a group of things, homeassistant.turn_off group.group_name?
or do you have to use the expand() template function?
homeassistant.turn_off turns off anything
so all i need to provide that service is the entity ID of my group of air conditioners
it will know how to turn that set off..?
Yes
awesome.
thanks. wasnt sure what the capabilities of groups were.
alternatively, i could use expand(group.my_group) with the climate.turn_off service, right?
(that must be what homeassistant.turn_off intelligently does in the background)
I guess you could
Hi everyone, I've set up an mqtt camera that works fine, but sometimes the frame streamer breaks quietly leaving me unaware of a problem. I'm trying to set up a mqtt sensor that listens to the topic of the mqtt camera and just keeps updating itself whenever a mqtt frame arrives. I've tried putting now() or len(value) to the value_template but nothing seems to work. Is there a way to do it?
Hello. Redirected from #automations-archived. Please help me out in an automation. Is there any way to check in an automation if a service was called by a script (automation) or it was called by the user from the Lovelace UI? Example: if climate.turn_off was called by pressing a button from the simple-thermostat card button or it was executed by an automation? Thank you.
@brisk nebula , what do you wan't exactly? You want a way to know if your camera stopped sending an image after a while, correct? Why di you need a mqtt sensor? Couldn't you simply test the value last_changed of your mqtt camera entity ?
@deft timber, tried that. last_changed doesn't work for cameras
you mean it is not updated?
oh ok
and the sensor you created on the mqtt topic of your camera, the last_changed is updated ?
no, not updated either
data:
entity_id: media_player.avr_zone1
volume_level: "{{ volume }}"```
I have an error it says expected float
this is my call
action: call-service
service: script.set_avr
data:
variables:
avr_media_player: media_player.avr_zone1
volume: 0.4
source: HEOS Music```
Hey guys, hoping someone could give me a quick hand. I'm trying to add 2 sensor values together and I'm sure I'm messing up the config. Currently I have code to change bytes to Gb, then I was going to combine them - platform: template sensors: bytes_received: friendly_name: "MB Received" unit_of_measurement: 'MB/s' value_template: "{{ states('sensor.gotasus_b_received') | filesizeformat(Gb) | round(2) }}" bytes_sent: friendly_name: "MB Sent" unit_of_measurement: 'MB/s' value_template: "{{ states('sensor.gotasus_b_sent') | filesizeformat(Gb) | round(2) }}" and this is the code that I'm having trouble with to add them together - platform: template sensors: combined_network_in_out: value_template: "{{ states('sensor.gotasus_b_received') | float} + { states('sensor.gotasus_b_sent') | float }}" friendly_name: 'Combined Network In Out' unit_of_measurement: 'Gb'
hmmm... I think I added those because it didn't work before. Let me try it again and see
Oh wait, that file size format filter adds the unit to the end of the number doesn't it?
yea, first time using it today. Seems to work well
think I got it working... i must have missed the other {
ty!
Can I combine those into 1 template?
think I answered my own q.... thanks again for the help!
hmm... its partly working? any idea? - platform: template sensors: bytes_received: friendly_name: "MB Received" unit_of_measurement: 'MB/s' value_template: "{{ states('sensor.gotasus_b_received') | filesizeformat(Gb) | round(2) }}" bytes_sent: friendly_name: "MB Sent" unit_of_measurement: 'MB/s' value_template: "{{ states('sensor.gotasus_b_sent') | filesizeformat(Gb) | round(2) }}" combined_network_in_out: value_template: "{{ states('sensor.gotasus_b_received') | float | filesizeformat(Gb) | round(2) + states('sensor.gotasus_b_sent') | float | filesizeformat(Gb) | round(2) }}" friendly_name: 'Combined Network In Out' unit_of_measurement: 'Gb'
the value I get in return is 1.7 GB153.2 MB gb
So I'm definitely missing something up
{{( states('sensor.gotasus_b_received') | float + states('sensor.gotasus_b_sent') | float) | filesizeformat(Gb) | round(2)}}
here you filesizeformat ads the units, so its returning a string, and then you concatenate to another string
the round is useless here
That's what I was getting at here heh: #templates-archived message
{{( states('sensor.gotasus_b_received') | float + states('sensor.gotasus_b_sent') | float) | filesizeformat(Gb) | round(2)}}
@deft timber So are you saying to just do this?"{{ states('sensor.gotasus_b_received') | float | filesizeformat(Gb) + states('sensor.gotasus_b_sent') | float | filesizeformat(Gb) }}"
You can't add those together with the letters at the end
no, this: {{( states('sensor.gotasus_b_received') | float + states('sensor.gotasus_b_sent') | float) | filesizeformat(Gb)}}
@deft timber @buoyant pine Thanks guys, I'll give it a shot
now my turn 😄
could you share your script?
Never used variables, but if I read at the doc (https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts), it says that either you use script.turn_on and put your variables in variables:, or you use script.set_avr and then you should put your variable in data directly
this partially works
it turn on correctly media_player
but when it turned on, it doesnt change volume or source
in your picture you use script.turn_on, that is not what is you do in your tap_action
k
I want to work from services tab
Invalid config for [script]: not a valid value for dictionary value @ data['script']['set_avr']['sequence'][2]['entity_id']. Got '{{ avr_media_player }}'. (See /config/configuration.yaml, line 19).
yes if you use script.ser_avr and not script.turn_on, you should remove the entity_id
just a thought but maybe the variables are passed as string ?! could you try {{ volume | float }} ?
yes if you use script.ser_avr and not script.turn_on, you should remove the entity_id
@deft timber but im using script.turn_on
in your image, you send 10 as the volume, it should be between 0 and 1
I'm lost 🙂 the error message occurs when you do what?
on my check config
Invalid config for [script]: not a valid value for dictionary value @ data['script']['set_avr']['sequence'][2]['entity_id']. Got '{{ avr_media_player }}'. (See /config/configuration.yaml, line 19).
if I replace everywhere {{avr_media_player}} with concrete entity_if for example media_player.zone1
then it works
in your script you have "{{not is_state('avr_media_player','on')}}", it doesn't look right to me. You should remove the quote around avr_media_player
idem for "{{is_state('source','HEOS Music')}}" and the quotes around source
still the same error
if you use templates, the entity_id should be below data
- service: media_player.select_source data: entity_id: "{{ avr_media_player }}" source: "{{ source }}"
instead
here is the updated code
now it works 80%
just volume doesnt work
🙂
new trigger:
so, volume is between 0-1
I set 0.33
but nothing is changing
your avr_zone1 is already on ? I'm asking because maybe it in not fully on when you call the volume after the turn_on. In that case a 'delay' or a wait_template could be needed to check that the media_player is well on
yes, I know, I need a wait template to wait state 'on' for the player
I will add it
but in boith situations when the player is off or on, the volume is not updating
if you replace the "{{ volume | float}}" with an hardcoded value, it works? To try to understand if the problem comes from the variable, or from the service call
Good news
so, the next thing is a spotcast service
that isnt triggering
if source = "HEOS Music"
source is a string, not an entity, so you should not use is_state
that also I was thinking
a simple {{ source=='HEOS Music'}} should make it
great
could not find device with name Denon AVR X2400H Zone1
but that friendly name is presented in my media_player.avr_zone1
sorry, i don't know spotcast...
if you can't launch it through the 'Service' screen, it is not anymore a #template topic, nor an #automation topic
How do you guys/girls deal with the unavailable state in templates? My roborocks vacuum only has 4 settings (silent, balanced, turbo, and max). So a state of unavailable throws an error. Any ideas?
Depends what you're trying to do and what the rest of your template looks like... but you can just test that state != 'unavailable'.
value_template: >-
{%- if is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Silent' ) -%}
Silent
{%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Standard' ) -%}
Balanced
{%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Medium' ) -%}
Turbo
{%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Turbo' ) -%}
Max
{%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'Gentle' ) -%}
Silent
{%- elif is_state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed', 'unavailable' ) -%}
Max
{%- endif -%}
How would that fit into here?
You're writing a switch case... you'd need to decide on a default case.
Which it looks like you have... you're setting it to Max when it's unavailable.
Yea, but that is just a work around.
Workaround is all you can do here, afaik. You want it to return based on a mapping... if it's not in your mapping, it'll fail (or return a default).
The sensible option is the default, which is what you've already implemented.
I might recommend an "else" instaed of the last "elif", just as a catch all
if that's what you're after
Ok, and this one gets fixed like this
{% if state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed_list', ! = 'unavailable') %}
{{ state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed_list') }}
{% else %}
starting.....
{% endif %}
{{ map.get(state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed'), 'Max') }}```
last bit there is the default on a miss
should work as is in your template tester but you can mess with it from there
replace the map.get() to change what you're looking up
And takes the place of both my templates?
yeah, this can get all of it in one go
it has your renaming and if it misses falls to a default value
miss conditions would be a new value or None / Unavailable
So
{{ map.get(state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed'), 'unavailable') }}```
yup, that would work
small typo in StanDard
oh yeah
That easy stuff.
nice solution. copy-paste for future use
yeah, much cleaner that a if/elif/else block
So it maps my values to what HAss uses and what does map.get do?
dict.get()
You're defining a dictionary and then looking up from the dictionary.
set correct_horse_battery_staple =
aww no staple
Ok, sure I will be back after template editor.
in lay man's terms, you set up your translations (map) and then use the value you get from (fan_speed) to find a match in your map. if found, use the translation. if not, use the exit (unavailable)
@ivory delta https://xkcd.com/936/
@waxen rune , so what phnx put is just a start, I have to do the map.get for each fan speed
it should cover everything that was in your if for the renaming
Trying to try it. At the office trying to figure out how I can paste discord into HAss at the house 🤣
{% set map = { 'Silent': 'Silent', 'Stanard': 'Balanced', 'Medium': 'Turbo', 'Turbo': 'Max', 'Gentle': 'Silent'} %}
it's like
if (the value from fan_speed) = Silent, then show Silent (because the first thing in the map is 'Silent':'Silent')
elseif (the value from fan_speed) = Standard, then show Balanced
elseif ...
else Unavailable
but much faster than evaling that
{{ now() }}
it won't solve every problem but its fairly powerful
Hi,
I have a switch that sometimes disconnect from the wifi for a few moments, and everytime it disconnects the Lock state is set to on. Any ideas why? Is there a way to set the default value to off?
lock:
- platform: template
name: Door
value_template: "{{ is_state('switch.door', 'off') }}"
lock:
service: switch.turn_off
data:
entity_id: switch.door
unlock:
service: switch.turn_on
data:
entity_id: switch.door
I totally get the set.map. The map.get is what is confusing me
because Unavailable != off
think of it as "get value from the map i just defined"
So I pasted it and it stays at max no matter what I change the fan speed to
@timid schooner {{ state('switch.door') not in ['off', 'Unavailable'] }}
because
Unavailable!=off
So it should be
"{{ not is_state('switch.door', 'on') }}"
?
{{ state('switch.door') not in ['off', 'Unavailable'] }}
Oh makes sense
it'll return True for on False for the other 2
if you want to invert that, remove the not
So mine will work as well
I want Unavailable and Off to function the same
both those should behave the same
@nocturne chasm and {{state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed')}} gives you?
Oh, no. State hadn’t actually changed. It works. Thanks @dreamy sinew and @waxen rune
So the map.get is the else?
Cause I don’t want it to show the unavailable.
no the .get("thing", "default")
Ok, now it makes sense. So what you had with max is what I actually need.
Does the same thing I was doing just in a cleaner way.
the reason i didn't put uav in the map is because sometimes attribs just return None instead
so it'll just miss on the lookup and fall to the default
Auh, but I could define unavailable in the set map part and not even need the map.get part
you could do a direct key lookup but that throws an exception if you miss
best to leave it as it is
and no. the map.get is the lookup
otherwise you have a nice map of "translations", but no one that uses it
Auh, ok. So map.get would work on its own but the extra variables define when the dict isn’t defined ?
no. or yes. maybe that's what you mean :-)
without a map, there nowhere to look for the answer.
-
define the map, what value should be replaced by what value
{% set map = { 'Silent': 'Silent', 'Stanard': 'Balanced', 'Medium': 'Turbo', 'Turbo': 'Max', 'Gentle': 'Silent'} %} -
use the map, look in the map for x, replace it with y, if you can't find a match, just use 'unavailable'
{{ map.get(state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed'), 'unavailable') }}
if you do a dict.get("thing") and it misses you get None
the 2nd value just sets a different default value
Right. So this would still work unless it misses.
{{ map.get(state_attr('vacuum.xiaomi_vacuum_cleaner', 'fan_speed')) }}
if you do dict["key"] and it fails you get a KeyError
everything fine then?
Yes, get the state unless unavailable
get the state unless you can't find a match, then use unavailable
Ok, so unavailable is the problem so I need to change it to max.
How do i iterate over items in a calendar sensor, specifically items for today's date?
I want to add the days events/appointments to my morning TTS readout
i don't have one of those, what are its attributes?
i have hyperion running on separate Rpi and HassOS running in another Rpi. I want to start/stop the software from HassOS with command line switch. I can successfully run a ssh command from following test switch
- platform: command_line
switches:
hyperiond:
command_on: 'ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no pi@192.168.1.17 "mkdir /home/pi/hello_from_switch"'
command_off: 'ssh -i /config/ssh/id_rsa -o StrictHostKeyChecking=no pi@192.168.1.17 "rm -R /home/pi/hello_from_switch"'
friendly_name: Hyperiond Reset
now on to the real switch. i will have a script that will check wheather hyperion running or not and depending on that i will start/restart hyperion. my question is what to put in "command_state:" and " value_template:" of the switch? In the docs under command_state, its written "If given, this command will be run. Returning a result code 0 will indicate that the switch is on.". what does result code 0 means?
0 means successful
Please help me out with an automation. Is there any way to check inside an automation if a service was called by a script (automation) or it was called by the user from the Lovelace UI? Example: if climate.turn_off was called by pressing a button from the simple-thermostat card button or it was executed by an automation? Is this possible? Thank you.
can secrets from secrets.yaml be read from within a jinja2 template? would something like this work?
{% set local_id = !secret telegram_georgechat_id %}
{% if trigger.event.data.user_id == local_id %}
Boiler schedule for tomorrow updated for George.
{% else %}
Boiler schedule for tomorrow updated for Vivian.
{% endif %}
@umbral pond no
do I have any option for something like this?
i.e. just an idea , put the secret value into a picker or something
and then read the state of the picker?
you could use an input_text and put the secret in it ?
maybe - haven't tried it yet - you can put the whole template in to secrets and the call that from a template sensor?
test_tmpl:
value_template: !secret my_template
it works with an ordinary secret, don't know if it will interpret the actual code though..
generally a bad idea anyway since secrets are supposed to be.. secret 🙂
@umbral pond well, I tried it and it actually works.
I put this in a secret
and the a template sensor:
test_tmpl:
value_template: !secret my_template
and sensor.test_tmpl evaluates and updates correctly
thank you I will do it this way too then!
generally a bad idea anyway since secrets are supposed to be.. secret 🙂
@waxen rune dont secrets remain secrets that way?
you are always using the !secret <name> syntax
regardless if you put the whole code in the secret value or just the value in the value
darn i'm confused
in "my" way, I guess it's fine, but in the first proposal we would expose the actual secret
that I don't get why.
we have a secret , let's call it my_secret.
and we put it into an input_text , now because i'm too bored to look for the actual syntax I will "imagine it" for speed sake
value: !secret my_secret
then in the template we would be like
if (incoming_data_value_id == input_text.value)
even if you share the whole thing to github , how can someone infer your secret ?
no, i was thinking abour your family/guests/other users
if you expose a secret in a input_text, any user can see that secret
you mean like in the UI ?
easily enough I'll hide that input from the UI
plus it's a Telegram chat_id 😛 most of my family members wouldn't know what to do with it , even if I gave them my API token as well 😛
That's the same approach I take for anything that needs to reference a secret in a template. It's good enough.
I do the same for addresses for the Waze travel time integration. I don't want to commit addresses to source control, so they live in secrets.yaml.
Does anyone know if there is a way to iterate through areas in templates? Or to get what area a device is in?
Or to use the devices at all instead of the entity states.
no and no iirc
Ok I've been trying to debug this for some 30 mins now. What is wrong with this line?
{% if states('input_text.telegram_chatid') == trigger.event.data.chat_id %}
I have also tried:
{% if states('input_text.telegram_chatid') == states('trigger.event.data.chat_id') %}
And also:
{% if states('input_text.telegram_chatid') == trigger.event.data.chat_id.state %}
First one looks fine. Post the entire thing
@umbral pond Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
@buoyant pine https://hastebin.com/urizizeten.yaml
essentially it's a telegram callback that has some if then else logic to decide which boolean to turn on
but always goes with the "else" option ... my if ... never comes through
also , the one I pasted has a mistake , uses this line {% if states('input_text.telegram_chatid') == states('trigger.event.data.chat_id') %} but I can assure you I also tried the one you deemed as fine
Is the entity ID right?
yes
it goes to the else clause every time
no mater if the ...data.chat_id is user1 or user2
which means it fails to evaluate the if clause (?)
as true
in every scenario
I mean is input_text.telegram_chatid the correct entity ID?
ah let me check that , good thinking
yes I just ctrl+c'ed it from "States" menu in the front-end and ctrl+f'ed it inside the code.
checks out
what is the easiest way to see the contents of the incoming event from telegram integration? to try debug what comes and whatnot ?
set the thing into a different input_text?
and check its content ?
Sorry not sure where to put this, can light groups be associated with an Area? I put some entities into a light group from only one area but it's placed in a seperate card automatically by lovelace so wondering if I need to associate it with an area
Hi all, trying to set up Kasa Smart Plugs as sensors and pretty much have copy/pasted from the example at the bottom of this page: https://www.home-assistant.io/integrations/tplink/
Here's the error being produced and my yaml: https://hastebin.com/jemafupihe.kotlin
Any ideas???
That's more an #integrations-archived question... but your indentation looks wrong.
sensors:
my_tp_switch_amps:```
Is possible to access the "friendly state name" in a template? For a binary sensor this results in on/off {{ trigger.to_state.state }}. It is a Modified Aqara Door sensor that in UI shows as open/close which would be much better.
sensors: my_tp_switch_amps:```
@ivory delta Thanks for this - apologies, couldn't decide if it was the template or the integration - the integration appears to be working perfectly (ie can see entity and all its attributes in developer section), just can't seem to get the template right to create a sensor out of it!
@glacial creek the under the hood names cannot change and that is by design. Everything in the UI is translated depending on the language.
the best option you have is to make a template sensor but the UI will show whatever your state is and it won't be translated. You can't have both.
the best option you have is to make a template sensor but the UI will show whatever your state is and it won't be translated. You can't have both.
@mighty ledge The UI show open/closed but the notification show on/off. I want the notification to also show open/closed.
@glacial creek Then you have to do the translation yourself in the notification
{{ 'open' if is_state('binary_sensor.xxxx', 'on') else 'closed' }}
@inner mesa I finally got back to my template issue from 9 days ago, and i figured it out. thought id let you know that i didnt let it win...
thank you again
I still haven't managed to determine why this logic always goes to the else clause. I've tried multiple different syntaxes , I 've verified correct spelling and indentation , I 've tried to troubleshoot by "printing" the event.data.chat_id inside a text_input to ensure its value is indeed what I'm expecting and all that in vain.
- service: input_boolean.turn_on
data_template:
entity_id: >
{% if states('input_text.telegram_chatid') == trigger.event.data.chat_id %}
input_boolean.one
{% else %}
input_boolean.two
{% endif %}
does the chat_id inside the event object not qualify as string? do I have to stringify it maybe somehow?
you could try forcing it to be a string: |string
making there are extra characters in there? you could try something like if trigger.event.data.chat_id|string in states('input_text.telegram_chatid'), or flipping the two
or actually, maybe that won't work
making there are extra characters in there? you could try something like
if trigger.event.data.chat_id|string in states('input_text.telegram_chatid'), or flipping the two
@inner mesa there is an "in" comparator? Not questioning , just making sure you meant to write "in"
yes
ok let me try!
my bad , I didn't try the "in" thingy , I had forgotten to reload automations after the |string change. I did , and it worked.
so apparently the attribute does not come as a string (?)
probably an integer
states are forced to strings, but other things, like attributes, retain their types
anyway, glad it's working
That was a valuable lesson for me on types! 😛 I'm glad too and thank you!
little bit of help with a trigger.
i've got devices a, b and c. I want to trigger if any of them experience a state change.
"if a.state, b.state, or c.state go from <any> to 'target_state', trigger"
sounds like a normal automations thing
Normal state trigger https://www.home-assistant.io/docs/automation/trigger/
No template needed from your description
but i don't want to create separate triggers for all of them
there are actually 14 devices
i thought maybe i could use group > expand?
automation:
trigger:
platform: state
entity_id: device_tracker.paulus, device_tracker.anne_therese
# Optional
from: "not_home"
# Optional
to: "home"```
note the multiple entity ids
oh. comma separated?
got it. can i shortcut this by using a template for entity_id?
i already have a group.all_house_Echo_dots
that trigger type doesn't accept templates
can't you use the group as entity?
answering my own question: well, you could, but then it will trigger as soon as any of the entities in the group changes state to on, but it won't go off until all of them are off
all boolean (optional, default: false)
Set this to true if the group state should only turn on if all grouped entities are on.
probably not helpful here, but wanted to point out an option that I just found out about a while ago
With the new native types for templates - is it now possible to use a template for the options: in - service: input_select.set_options in an automation?
Hm. I guess not. But it looks more like a bug than a feature: options: "{{ states.foo.attributes | list }}" => TypeError: __init__() missing 1 required positional argument: 'render_result'
definitely smells like a bug. can you report that please on github?
Want to see what issues are open (or were open and are now closed)?
- The core (backend) - for HA itself, and integrations
- The frontend (UI) - for cards and display issues
- The Supervisor
- HassOS
- The documentation
Finally, don't forget to check for any alerts
top one
hello all I have a problem with graph
like this: https://snipboard.io/V1tpd6.jpg
the value is good on the sensor, but the graph display an old value
or this in the UI: https://snipboard.io/5Q7SCE.jpg
I have reboot my server, now graph work, the problem isn't the ui
the database save none of all previous day
@halcyon island Please DO NOT cross post. Read the channel description, post it and wait for folks to respond.
Your problem sounds like frontend. Wait for a response over there.
yes after reboot I see it's a frontend not ui
hi guys, ive been reading up on templates and messed around with the template debugger, but im not sure where i create them?
create what? template sensors?
templates themselves just...are
and are used all over
How can i update this template to get last time in a certain state? last time vacuum was cleaning {{ relative_time(states.vacuum.roomba.last_changed) }}
Can anyone help me debug this error: https://paste.ubuntu.com/p/Hw35qwB73g/ Getting 'Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'd_printers') for dictionary value'
Heard in #integrations-archived that this something to do with numbers in sensors?
It's your templates, yes... you can't start the name of an entity with a number:
states.switch.3d_printers.name
.3d = bad
.threedee_printers = good
really?
Ah, no way to escape numbers etc? Ok will A3d_printers work?
So I've heard, Ludeeus. I think it's down to the way the templating engine tries to parse the string.
Ah ok, will try that
When I think of it, I think I saw this in the docs somwehere at one time
Yeah, I'm sure I've read it rather than just heard it in passing.
But I don't know enough Python/Jinja to understand why.
petro answered an old forum post about it: https://community.home-assistant.io/t/template-and-entity-id-beginning-with-a-number/54194/5
I wonder what it's trying to access when you do .number. In JavaScript, it'd be fine with that (even if it's bad practice to start variables with numbers).
Oh... it's expanding it 😮
got 'd_printers') for dictionary value @ data['sensors']['switch_threed_printers_amps']
switch_*threed*_printers_amps
Hmm, getting a syntax error on this: https://pastebin.ubuntu.com/p/5Ysm54TV9k/
I misunderstanding this?
What's the error?
And yes, you got it wrong 😄
states.switch.['3d_printers'].name should be states.switch['3d_printers'].name
Note the dot I removed.
can not read a block mapping entry; a multiline key may not be an implicit key at line 71, column 26:
unit_of_measurement: 'A'
Ah!
Where's the faceplant emoticon... 😉
Yeah, makes sense - although still getting: can not read a block mapping entry; a multiline key may not be an implicit key at line 71, column 26:
unit_of_measurement: 'A'
Which line is line 71?
I see bad quotes in there though... Careful about mixing " and '
If you're using ' around the template, you must only use " inside. Otherwise the second ' closes the pair and the rest is garbage.
All of your value_templates have the same issue
Hmm - yeah just lifted this from the home assistant site example and worked before introducing the numbered sensor, so this must be throwing it off. Ok, will try and adjust!
Ok validating now!
TBH in future I'll probably just avoid leading numbers in names, but good to understand the logic!
Thanks for help - never would have got that one!
anyway to get the selected index from an input_select?
yes, no, kinda
{% set idx = {"option1": 0, "option2": 1} %}
{{ idx[states('input_select.my_selector')] }}
hi guys, struggling on how to get started with templates, ive got my hue ambiance bulbs added in HA and can turn them on/off using alexa via emulated hue, but when i turn them on i want the bulb light temperature to be set dependant on time of day
that's not really a template thing, sounds more like an #automations-archived with a choose:
@rugged laurel that's what I was afraid of... I have 89 options in my select lmao
can I use something like zip in a template? I could get the state_attr of my input's options attribute as a list right? and then maybe zip with a range? or am I thinking too python?
@rugged laurel thats going to work perfectly, once i get all my options in 😅
does anyone know how to create sensors from weather forecast from met.no
i know how to crate sensors for temperature, humidity, ... but i have trouble creating sensors for forecast values. I'm using met.io home assistant plugin
guys.. when I run this I got error.. anyone can help me out? ```
binary_sensor:
- platform: threshold
entity_id: sensor.bedroom_ac_plug_current
upper: 400
name: Real Bedroom AC Plug Status
2020-10-30 23:36:14 WARNING (MainThread) [homeassistant.components.threshold.binary_sensor] State is not numerical
Greetings all, I am trying to wrap my head around templates and how to do calculations, anyone here who might be able to assist?
Greetings all, I am trying to wrap my head around templates and how to do calculations, anyone here who might be able to assist?
@pure pulsar what do you mean?
I am trying to divide number of deaths by number confirmed
sensor.us_coronavirus_deaths sensor.us_coronavirus_confirmed
to get a %
- platform: template
sensors:
worldwide_corona_percentage_infected:
friendly_name: Worldwide Percent Infected
value_template: '{{ ((float(states.sensor.worldwide_coronavirus_current.state) / float(states.sensor.worldwide_coronavirus_confirmed.state)) * 100) | round(1) }}'
unit_of_measurement: "%"
thats how I do it
"deaths": states('sensor.us_coronavirus_deaths'),
"confirmed": states('sensor.us_coronavirus_confirmed')
} %}
{{my_covid_json.deaths}}
{{my_covid_json.confirmed}}```
US Corona cases? I'm surprised it can handle numbers that big 🤷♂️
That was witty
Last year there were 34 Million cases of the flu so I guess we are not even close yet
@clear pulsar thanks that gets me closer. I am more trying to understand how to do calculations using the templates tab under development tools
so yours gets me close, but I am struggling with how to just do the basic math portion
When I built the template you have there it works for me
Added this to my Configuration.yaml for the moment:
- platform: template
sensors:
us_corona_death_percentage:
friendly_name: US Death Percentage
value_template: '{{ ((float(states.sensor.us_coronavirus_deaths.state) / float(states.sensor.us_coronavirus_confirmed.state)) * 100) | round(1) }}'
unit_of_measurement: "%"```
- platform: template
sensors:
worldwide_corona_percentage_recovered:
friendly_name: Worldwide Percent Recovered
value_template: '{{ ((float(states.sensor.worldwide_coronavirus_recovered.state) / float(states.sensor.worldwide_coronavirus_confirmed.state)) * 100) | round(1) }}'
unit_of_measurement: "%"
- platform: template
sensors:
worldwide_corona_percentage_deceased:
friendly_name: Worldwide Percent Deceased
value_template: '{{ ((float(states.sensor.worldwide_coronavirus_deaths.state) / float(states.sensor.worldwide_coronavirus_confirmed.state)) * 100) | round(1) }}'
unit_of_measurement: "%"
that does work on the templates page
thats is the rest
yep I am seeing it now, I am just using the covid stuff to better understand how to formulate my own templates
or better yet, calculations
at the momont try to figure something for my self
need to round my sensor.. but trying to figure it out where should I put it out..
anyone know why I got error for this template
- platform: template
sensors:
bedroom_ac_plug_current_round:
friendly_name: Bedroom AC Plug Current Roung
value_template: {{ states('sensor.bedroom_ac_plug_current')|round(0) }}
unit_of_measurement: "mA"
Please don't say I have an error or describe an error. Share the whole actual error message so we can help you.
@clear pulsar
@buoyant pine thanks.. I have been pulling my hair because of that indentation...
👍
I have been working on this all night. I had it working for quite some time until I added a new switch yesterday. I somehow lost the config that accomplished what I want. I have a MQTT switch that an arduino monitors. When the MQTT switch is press the MQTT topic is turned to 1 and the arduino mimics my garage door button press. When the arduino opens the door it returns the MQTT topic back to 0. And waits for the topic to return back to 1 before it mimics the garage button press again. Been working for over a year and works great. I have a zwave sensor on the garage door to know if the garage is open or closed. Until yesterday I had the MQTT switch icon change from "garage" to "garage-open" based on the zwave sensor. I can't seem to get this to work again. I'm not even sure how I did it because it was so long ago. I'm currently adding the following code to my switch but I don't think this is the proper way to do it.
icon: >- {% if is_state('binary_sensor.main_garage_door', 'on') %} mdi:garage-open {% else %} mdi:garage {% endif %}
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
That is my switch. - platform: mqtt name: "Garage Door Button" unique_id: "garagedoorbuttonmain" state_topic: "hass/garage/door_button" command_topic: "hass/garage/door_button" payload_on: "1" payload_off: "0" qos: 0 icon: >- {% if is_state('binary_sensor.main_garage_door', 'on') %} mdi:garage-open {% else %} mdi:garage {% endif %}
There's no indication that that field supports a template
I use a cover template for that:
Thanks. I'll use that code and lookup more about cover templates. I really needed a direction to look more than anything.
sure, np. main takeaway is that you only use templates where they're explicitly supported, or in a data: block of a service call
Trying not to sound stupid but is there a simple doc that indicates where templates can be used? Google searches brings back a lot of outdated or misleading data.
One way of achieving what you want is to do a separate template binary_sensor based on your mqtt switch. then you can have your icon in that template
Really, just what I said above
ha. missed that link
That wasn’t to you, trying to answer:
Trying not to sound stupid but is there a simple doc that indicates where templates can be used? Google searches brings back a lot of outdated or misleading data.
sure, np. main takeaway is that you only use templates where they're explicitly supported, or in a
data:block of a service call
‘Explicitly supported’ means ‘the docs say so’
@lost tide I agree it is a lot to plow trough when you start templating. A problem for me is that I need to know what you're looking for to google it - but I don't really know that just yet. I just know what I want to achieve, not what components to use - yet. I think the docs are great, especially compared to many other open source projects and despite the developing pace in HA is extreme, but it is not always user friendly.
Anyway, did you get the examples you needed to move on? If you don't want to use the example RobC gave in https://hastebin.com/agikakudiq.less, I would start with https://www.home-assistant.io/integrations/switch.template/ and/or https://www.home-assistant.io/integrations/binary_sensor.template/
I have been searching for "home assistant change switch icon based on sensor" I just tried the provided example but I'm not sure I implemented it correctly. Most likely I didn't communicate well enough to for RobC to know what I was asking. I have worked with Home Assistant for years but it runs so well that I by the time I want to add or update it I have forgot most of how I put it together.
what did you end up with? The strategy was to separate the MQTT switch from the cover abstraction, so you could simply replace my entities with your MQTT entities
I added your cover but it doesn't change when I open the garage. I'm still trying to wrap my head around it.
that looks near identical to my garage door template. You don't need the icon template.
you can use device_class: garage
or that
- platform: template
covers:
garage_door:
friendly_name: "Garage Door"
device_class: garage
value_template: "{{ is_state('binary_sensor.garage_door_sensor', 'off') }}"
open_cover:
service: switch.turn_on
entity_id: switch.garage_door_switch
close_cover:
service: switch.turn_on
entity_id: switch.garage_door_switch
stop_cover:
service: switch.turn_on
entity_id: switch.garage_door_switch
@waxen rune cover templates need to resolve on/off or true/false
that's probably why @lost tide's isn't changing state
could be. haven't seen it yet 🙂
Oh, sorry! It wasn't you
(I removed mine since it confused things more than helped..)
I had this working before without covers. I just don't remember how. Grrrrrr.....
most likely a switch template
which is going to be near identical.
- platform: template
switch:
garage_door: "Garage Door"
value_template: "{{ is_state('binary_sensor.garage_door_sensor', 'off') }}"
turn_on:
service: switch.turn_on
entity_id: switch.garage_door_switch
turn_off:
service: switch.turn_on
entity_id: switch.garage_door_switch
I recommend (like the others) using the cover template.
@lost tide what's your switch name, what's your sensor name. What state should the sensor be when the door is open?
acutally, I just moved up and saw your other post. Is your binary_sensor an MQTT device?
The switch name is switch.garage_door_button and the sensor is binary_sensor.main_garage_door.
and the switch is always being turned on?
Binary sensor is a zwave sensor.
WAIT!!! The sensor is a sensor from my alarm system. I forgot I changed that.
So.. is that MQTT?
no. its a sensor from my old DSC alarm system.
so you were checking the wrong sensor and that's why the icon wasn't changing?
@lost tide try this code exactly as written. Reload your templates https://hastebin.com/fujerevoru.less
RobC no. The name is the same. Its just not a zwave. Still a sensor.
When I run a rest command all I get a whole bunch of fields like this
"name": "power",
"label": "Power",
"type": "Boolean",
"value": 0
},```
Is there a way I can just extrapolate them all to a template, or do I have to specify the ones I want? The examples indicate you have to specify the fields you want.
This still doesn't change the switch icon. I need an entity to click on and the icon changes based on the sensor.
Hi, I have many heater valves, for all of them, I have a sensor that tells if it's set to the heating temperature or not.
The sensor template is:
{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float < 17 %}
off
{% endif %}
{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float > 24 %}
on
{% endif %}
@lost tide it's not going to change the switch, its going to change the cover.
there's nothing you can do to change the switch icon
That works for all my valves except one, I don't know why, it does not get the temperature.
that switch icon is set in stone. You can make a second template switch and have that icon change.
@lusty cipher you can send it to attributes if that's available for the integration you're using.
If I do {{ state_attr('climate.thermostat_wc_1er', 'temperature') }} then I have the right value
@acoustic wedge do you have that all in 1 template? because that syntax is not correct if you do.
I just put the value_template
OMG! I have a backup. Going to see if I can find my old config there. I did make this work at one time. It has been working for almost a year.
@acoustic wedge this is not correct
{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float < 17 %}
off
{% endif %}
{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float > 24 %}
on
{% endif %}
Thanks @mighty ledge This is just using the rest integration I was wondering if rest has enough of a standard that HA can figure out based on the type label to give it the proper characteristics.
@lost tide the only way for you to change the icon for an existing item is to use customUI
which, unfortunately, will just cause you pain down the road
@mighty ledge that syntax works for all my other climates
or, use a card that lets you change the icon in the frontend, like custom button card
@acoustic wedge but it's not correct. You're sending on and off.
you should be using elif
also, what happens if the temperature is between 17 and 24?
you send nothing
You're right on that but the issue concerns only one of the conditions
So this one does not work
{% if state_attr('climate.thermostat_douche_1er_2', 'temperature')|float < 17 %}
off
{% endif %}
also, what happens if the temperature is between 17 and 24?
@mighty ledge It's either set to 15 or 26. I use it to check that the valve has received the instruction.
While {{ state_attr('climate.thermostat_douche_1er_2', 'temperature') }} works fine
post your whole config for the section that's not working
OMG, you were right with your remark: 'what happens when it's in between' and it's the case for this valve, it's set to 22.
Sorry
always best to use the correct code!
Yeah
Well crap. my backup is to old.
{% set t = state_attr('climate.thermostat_douche_1er_2','temperature')|float %}
{% if t > 24 %}
off
{% elif t < 17 %}
on
{% else %}
lskdjfalkjdsljkfda
{% endif %}
Thank you again
np, is this a binary sensor?
you might have to swap it to a sensor if you want a 3rd state
Nope, a template sensor
ah ok, then you should be good
Yes
you can make it 'unavailable' between 17 and 24
lskdjfalkjdsljkfda is rather nice also
clear indication that the state is unexpected 👍
Actually I use this code for valves that I set either to 26 or 15, where 26 means on and 15 off. And I was facing the issue with the only valve that I set in between and forgot about it 🙂
So value of 22 should never happen
well, now you will know if it does 🙂
Yeah
Using the restsensor, how to set the value_template to the current timestamp/date. Now I am just doing value_template: true as value. But setting {{now()}} just gives an error
mind sharing the whole sensor config?
@waxen rune `
- platform: command_line
command: python3 -c "<command>"
name: fetch_Data_From_API
json_attributes:
- data
value_template: {{states.sensor.fetch_data_from_api.last_changed}}
scan_interval: 30`
I'm brute forcing any option I can think of to just get value_template populated with a timestamp or date
Above doesn't work though
OMG!!! I figured out what I was doing wrong. I wasn't trying to change the icon of a switch. Well I was, but that is a limitation which cannot be done. I created a button associated to the garage door sensor with a tap action associated to the garage button. I feel so stupid now. Thanks petro and RobC for your help. You have helped me understand some of the limitation of HASS. And I learned cover templates. Anyway, all is well.
I guess its mandatory to have single quotes around the statement
else the templating doesn't work
so i've figured a way to get the index of the selection from an input_select as a sensor value:
sensor:
- platform: template
sensors:
options_sensor:
value_template: >
{% set idx = {"Option 1": 1, "Option 2": 2} %}
{{ idx[states('input_select.options_list')] }}
input_select:
options_list:
options:
- Option 1
- Option 2
can i use similar (or different? 😅 ) logic to get the name if all i have is the index?
also, i'm good with docs, but don't know where exactly i'd look lol
The docs won't cover that since it's well beyond basic templating. Instead, you need to realise that the templating engine is Jinja, which uses Python. Googling for 'python find key by value' led me to this: https://stackoverflow.com/a/8023329/3907492
Looks promising, I'm sure someone can convert that into a template.
oh, it's that question above ^^
hold on
i'm trying to use this as an attribute template for a template sensor:
effect: '{{ states(''sensor.wled_effects'')[state_attr(''sensor.wled_state'', ''seg'')[0][''fx'']] }}'
in order to get the name of the effect.
{{ state_attr('sensor.wled_state', 'seg')[0]['fx'] }} gives me the index
@ivory delta came here from integrations
my end goal is to SET the input_select i have (also prepopulated, like yours) to whatever the light is currently reporting
What does it report? A number for the preset?
this way, if i change the settings from outside of HA, i can run automations to have them fixed
yes
https://github.com/Aircoookie/WLED/wiki/JSON-API: json/state['seg']['pal']
So just flip the logic of your previous template:
{% set idx = {1: "Option 1", 2: "Option 2"} %}
Looking up the index gets the name.
oh yeah i guess so lol
oof ok that's fine lol
wanted to try and make a template that zips those
to save some lines, get the effect list from wled, and range, and zip them
but i don't think jinja can do that?
Well is everything that cares about the template going to be in the same place? i.e. in the same automation/script?
Zip?
i'm putting everything in one file, as a package
but i've got inputs, sensors, automations, switches lol
But can the same template be referenced by everything that cares about it? There aren't global variables (yet).
i don't think so
If it can't be re-used, don't try to make one thing that solves every problem.
Solve the individual components.
Yeah, no creating zip files from templates
not a zip file
A bit like underscore.js's zip function: https://underscorejs.org/#zip
zip(a, b) -> {a[0]: b[0], ...}
Maybe there's a way... but it's overkill here.
Oh
You want WLED's response to set the input_select... and presumably you want changes to the input_select to drive WLED. That's two automations, with their own templates.
Keep it simple 😉
it is
yes
but i can't get the templates right lol
i have controlling wled down fine
works perfectly
They're both dictionaries, just looking up in opposite directions.
i just didn't wanna type out another 100+ element dict 😅
i've created controls for speed, intensity, palette, effects, and presets (with some piggybacking on drzzs)
Well if you're happy they're in the correct sequence, don't type them out.
but they don't agree if i change them in wled
Just keep that array... and reference the index within that array to get the name.
right, i can't get the array
i have a rest endpoint that returns a list
['a', 'b', 'c', ...]shouldn't this give the value? or do i need
value_json? neither works 😅- platform: rest name: WLED Palettes resource: http://192.168.1.189/json/palettes value_template: '{{ value }}' headers: Content-Type: application/json
@blazing burrow
Yeah, don't grab it via a sensor... just copy paste.
ohhhh :p
The list won't change unless you update WLED.
right, gothca
API calls are amazing (I work with and build them for the day job) but they're overkill when the data doesn't change.
When I first became a dev, I always wanted to build things the 'clever' way. Now I want to build them however is easiest to understand and maintain 😉
i mean, i get that
i've now got the same list defined three ways in three different sections
makes more sense to me to bring it in raw and manipulate it in each place
It would make sense if you could bring it in in 3 places. I think global variables are coming soon, so then you'll have a reason to try it again 🙂
👍
you know what... I worked way too hard on that for no good reason
I'm using the wled integration for my light... which reports current state for all of those
just an automation to set my inputs whenever this change
done
all working and synced between HA/wled/etc
It's all a learning process though.
thanks for your help 👍
Hi. has anyone got templete value for extracting met.io forecast values. I want to create a sensor for each day for 5 day weather forcast
What have you tried so far?
Do you know which attributes on the weather entity represent the forecasts?
.share them here if it helps
Please use https://paste.ubuntu.com/ or https://www.hastebin.com/ to share code or logs.
yes weather.home. but forcasts are under section forecast and there is a lot of values
i know how to create sensor for first values
but i don't know how to extract values under forecast. and there is 5 conditions
So... forecast is just a list (or an array, if you prefer to call it that). You can reference them using [index], where index is a number starting from 0.
ok
So the first entry in the forecast would be forecast[0].
ok
If you want something specific from the forecast instead of the whole forecast dict (object), you can use dot notation to get it... i.e. forecast[0].condition
forecast[0]. and then temperature, for temperature?
Yup
ok i'll try
Sounds like you've got this 🙂
yes...didn't know what that [0] indexes mean. but after reading codes from forums
it started to get clear
i can try this in developer tools right? (don't have to restart server)
Yeah, it looks weird if you're not used to coding 🙂 And yes, you can do it in
> Templates to test what a template will give you.
great thx man!
{{ state_attr('weather.home', 'forecast') }} is returning [{'condition': 'partlycloudy', 'temperature': 17.3, 'templow': 9.4, 'datetime': '2020-11-02T11:00:00+00:00', 'wind_bearing': 249.1, 'wind_speed': 14.4}, {'condition': 'sunny', 'temperature': 17.6, 'templow': 9.4, 'datetime': '2020-11-03T11:00:00+00:00', 'wind_bearing': 242.8, 'wind_speed': 11.2}, {'condition': 'cloudy', 'precipitation': 1.0, 'temperature': 13.5, 'templow': 9.0, 'datetime': '2020-11-04T11:00:00+00:00',
but after i want to choses some values from here, it doesent return nothing
or i'm not forming the code right
{{ state_attr('weather.home', 'forecast[0].temperature') }} ??? this is right?
or am i missing something?
You wouldn't use state_attr for that. Something more like this...
{{ states.weather.home.attributes.forecast[0].temperature' }}
Although you're probably better off making sensors than using a template like that everywhere.
Maybe break it down in steps. Make a 'tomorrow forecast' and get all the attributes in the right place using this integration: https://www.home-assistant.io/integrations/template/
Then you can use the simpler syntax ({{ state_attr('sensor.tomorrow_forecast', 'temperature') }}) everywhere else.
that's the plan, to create sensor for each day.
ok, trying with state_attr
I've read template integration document. That's was my plan, but i just have to extract attributes form weather.home and that's where it stopped for me
ok
this did the trick
"{{ state_attr('weather.home', 'forecast')[1].condition }}"
i have now all the attributes extracted
now I have to create sensors
that's it i think
thc
thx
Hi guys,
I'm trying to add a space as a thousand separator.
I could add a comma with this:
{{ '{:,}'.format(value_json[0].activeCases) }}
But I cant find any information on how to change this to a space
I have one that does just that, but it is an ugly one: "{{ '{:,}'.format(states('sensor.memory_use') | int).replace(',', ' ') }}"
only way I could find out. any improvements are welcome.
it works fine for displaying a value, but it screws up a graph since it only interprets the thousands as a value, so 1 300 becomes 1
https://imgur.com/a/I7Z9sNe
so I'm sure there's a better way, I just haven't found out yet
Hi,
Can anyone help me a bit to create one template?
I want to make something like this:
- platform: template
sensors:
effeciency_recuperation:
value_template: >
{% set value = (((states.sensor.vent_vallox_into_houre)-(states.sensor.vent_vallox_from_out))/(((states.sensor.vent_vallox_from_house)-(states.sensor.vent_vallox_from_out))*100)| round %}
{{ "%0.0f"%value }}
friendly_name: "Vallox Eff"
unit_of_measurement: "%"
But... does it make sense?
It should be like:
eff=(T2-T1)/(t3-T1)
@pseudo barn I see what you aim for, but you may have mixed it up a little.
an example could be something like
value_template: >-
{% set t1 = (states('sensor.vent_vallox_into_houre') | float ) %}
{% set t2 = (states('sensor.vent_vallox_from_out') | float ) %}
{% set t3 = (states('sensor.vent_vallox_from_house') | float ) %}
{{ ((t2-t1)/(t3-t1) * 100) | round(2) }}
that won't take care of div/0 and such, but as an example
..and this will give you the same result:
{{ ((states('sensor.vent_vallox_from_out') | float - states('sensor.vent_vallox_into_houre') | float) / (states('sensor.vent_vallox_from_house') | float - states('sensor.vent_vallox_into_houre') | float) * 100) | round (2) }}```
Hi @waxen rune
Thank you very much, I will give a try today 😊
Hi. I have "2020-11-02T11:00:00+00:00" datetime, how to get a name of that day. So i need to basicly convert date to day
@cinder basin start looking here https://strftime.org/
Example: {{ utcnow().strftime('%A') }} will present "Sunday" today
how do i make a template that only works on sunday and if a input.boolean it on?
a template? sounds like conditions https://www.home-assistant.io/docs/scripts/conditions/
ye a template if possible
could you describe more? a template will always work, but what do you want it for?
so i have a script to turn my lights on and off every day and i want to have a input boolean for every day of the week so i cant stop it runing on days i choose
the "Sunday" part is {{ now().day == 6 }}
@inner mesa is there a way to put it in a if statement with a input boolean at the end?
so... {{ now().day == 6 and is_state('input_boolean.xxx', 'on') }}
yes thank you
recommend reviewing the template docs: https://www.home-assistant.io/docs/configuration/templating/
@inner mesa TemplateSyntaxError: unexpected char '&' at 33
oh, and
thanks
sorry, C programmer 🙂
just curious, if you have an input_boolean for each day you want to run/nor run the script, what do you need the template for?
I imagine you have 7 input_booleans, one for each day? or am I assuming wrong here..?
I imagine you have 7 input_booleans, one for each day? or am I assuming wrong here..?
yes i do
so if you have an input_boolean for each day that to manually turn on/off wether you want to run the script or not. what will the template add to it?
nothing wrong with that, just curious to hear other peoples solutions.
so i have {% if now().day == 6 and is_state('input_boolean.sunday', 'on') %} on {% else %} off {% endif %} but it allways returns off in the template testing tool
ok so sundays one
returns 1
it responds 1 exactly
yep
it think you are in a country that start the week with sunday
uk
I can see two ways forward:
- Dive in to time handling (and please report back how you solved it)
- Number your week Sunday = 1, Monday = 2 .. even though you don't like it 🙂 (don't do this, I was wrong, see below)
0-6, I think, but 🤷
ok i gtg eat brb
another thing, I just realized it is November 1st.
doesn't .day report the day as in date (1)?
{{ now().weekday() }} gives 6 which would respond as day 6 (Sunday) then.
I don't know for sure, but https://docs.python.org/3/library/datetime.html suggests that
"date.weekday()
Return the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a Wednesday. See also isoweekday()."
it does, and I just realized that 🙂
I had a bunch of stuff in the template tool and was looking at the wrong output. I happened to have now().weekday() in there, too
thanks for clarifying
trying to learn. happy to find my own mistake sometimes 🙂
now that the template tool retains the content I type, it accumulates a lot of stuff
I made a template that I tried out in the template tool which made HA restart the other day. no proud moment
and it does return 0-6. Today is Sunday (for me) and it returns 6, while this returns 0:
{{ (now()+timedelta(days=1)).weekday() }}
If you name your input_booleans the same with the day last, like input_boolean.day0 - input_boolean.day6. (or 1 - 7 if you want to use now().isoweekday())
Then I guess you should be able to do this which save a bit of keystrokes:
{% set d = now().weekday() %}
{{ 'on' if states('input_boolean.day' + d | string) == 'on' else 'off' }}
I think you'd want
{% set d = now().weekday() %}
{{ states('input_boolean.day' + d | string) == 'on' }}
even better
you want a boolean, not 'on'/'off'
true (!)
even better:
{% set d = now().weekday() %}
{{ is_state('input_boolean.day' + d | string, 'on') }}
why is that better?
haha!
ok, I thought it was something like "Avoid using states.sensor.temperature.state, instead use states('sensor.temperature'). It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup)."

