#templates-archived
1 messages · Page 140 of 1
'echo {{ states("input_number.screen_brightness") }} > /config/rpi_brightness/bright'
I can't see the first and last quote
yes that looks correct
if that's not working you need to verify that the field you're trying to template accepts templates
I try to write the value to a file
yes, but the yaml field you are putting that template needs to accept templates for templates to work
templates only work on specified template fields
the documentation for the integration you're using will say 'template' next to the field if it accepts templates
In the example on home assistant docs they show similar code: shell_command: set_ac_to_slider: 'irsend SEND_ONCE DELONGHI AC_{{ states("input_number.ac_temperature") }}_AUTO'
then it should work
It doesn't... 😫
Empty, no errors...
Yes, it does, and I also can write a specific value to the file
^
if not, head over to #integrations-archived and ask why the commands are not working, your template is fine.
Thanks for you patience @mighty ledge !!!
np
I need some help please... Why does this code for an automation produce an error like template value should be a string for dictionary value @ data['message']
- alias: "[LOGGING] Error notification"
trigger:
platform: event
event_type: system_log_event
action:- service: notify.system_mail
data_template:
title: Something bad happened
message: '{{ trigger.event.data.message }}'
- service: notify.system_mail
12021-11-12T00:00:00+00:00 how do I remove the T from this time stamp so that I can use it on a more meaningful way?
data_template is depreciated a long time ago, just use data . Are you sure {{ trigger.event.data.message }} returns something? As message is a required field, it could be that it errors on it being empty
hi everyone. basic question (i think) but im stuck.
im trying to create multiple sensors as follows:
- platform: integration
source: sensor.smappee_5010001397_local_total_consumption_active_power
name: Total_consumption
unit_prefix: k
round: 2
- platform: integration
source: sensor.smappee_5010001397_local_load_1st
name: 1st_consumption
unit_prefix: kW
round: 2```
but I get the error [object Object] when i try to restart. any ideas?
just print trigger and see what values you are getting, then expand based ont he event.. and more
message: '{{ trigger}}'
Do the source sensor exists?
Turns out that message is an array, message: '{{ trigger.event.data.message[0] }}' is working. I have to look into this a little, but i think i have seen log entries in the web gui containing mutliple lines
ah there was a typo! thanks! that seems to have fixed it..
So I'm seeing these errors in my HA log: TemplateError('UndefinedError: None has no element 0') while processing template 'Template("{{ state_attr('sensor.carbon_intensity', 'data')[0].generationmix[4].perc }}")' for attribute '_attr_native_value' in entity 'sensor.carbon_intensity_generation_nuclear'
I have tracked that down to a template sensor created after calling a REST api which is created as such : value_template: "{{ state_attr('sensor.carbon_intensity', 'data')[0].generationmix[4].perc }}"
if I look in the states table for that sensor I can see NULL state entries occasionally - I presume because of a failed rest api call to the url (but not certain)
I've tried to improve it myself by doing this: value_template: "{% if state_attr('sensor.carbon_intensity', 'data')[0].generationmix[4].perc is defined %}{{ state_attr('sensor.carbon_intensity', 'data')[0].generationmix[4].perc }} {% endif %}"
is that the right/best way?
I've got the MikroTik integration enabled but all of the devices it generates disabled (they make a mess in my main device list). Is there a way for me to count the devices created by this integration using a template even though they're disabled?
what main device list?
Ah well I'd rather not fill that list with nonsense either
I don't want every device on my network appearing as an entity in HA
that… is just nonsense
Why? I don't see any need for having useless entities.
it does not matter how long your list of entities gets
I know it doesn't, but I'd rather keep useless things out of it. Why is that such a surprise?
its not useless if you NEED IT
I don't need the individual devices, they are just clutter. If that's the only way to count them then I guess I'm writing a custom integration 😂
you are free to do so
👍 was hoping the MikroTik integration exposed a "router" entity with some attributes on it that I could use. Might look at just forking it and adding that, as it seems a nice way to go about it.
Cheers for the help anyway 🙂
i have a simple php script which outputs a json of active devices
then use a rest sensor to feed them into ha
Yeah I was thinking of potentially writing something like that which would push the number of active devices over MQTT. I wonder if I can throw together a script and run it on the router itself...
Shame MikroTik went with some arbitrary text-based API instead of a RESTful one.
opnsense 👍
Question about trigger based template sensor / binary_sensor:
Let's say I have 2 triggers (A and B).
Only trigger A can change certain state or attribute value.
It there an easy way to return current state/attribute value when trigger B fires?
(this is one of those basic questions that have been bugging me for a while and was afraid to ask sooner)
newbie question.. would this work?
value_template: '{{ value contains "OK1" }}'
I.e. if the respons contains "OK1" . seen all examples with == "STRING".. looking for contains / like rather than exact match...
{{ "foo" in "foobar" }}
thanks!
@pastel moon today_at is a filter, not a property of now()
Thanks, I probably got that mixed up a bit... I am trying to compare what today_at produces with now()... Perhaps I am overcomplicating again...
Ah. I got stuck in trying to format the output from now() to look the same.
I will remove that and try again, thanks 🙂
what do you mean look the same
they will 'look the same'
now() is a datetime object and the return from today_at('00:00') is also a datetime object
I forgot they are actually DateTime objects, I noted the output of now() has microseconds as well, which output from today_at has not. I found it not to matter now
it does not matter, however == comparisons will never work with microseconds
If you are interested: it turns out shell_command cannot handle the template. But it does support templates if you use bash in the shell command: bash -c 'echo {{ states("input_number.rpi_brightness") | round(0) }} > /config/rpi_brightness/brightness' I also needed to get rid of the fractions so I rounded the outcome!
Having some strange problem getting my projector to work with the telnet switch.. is there any way to debug and see exactly what response HA is getting back?
My config, and output from telnet:
https://pastebin.com/xkv8YKpX
when you send "~00124 1", the response is "OK1"?
Yes, if the projector is on.. otherwise I get a OK0
Then your switch should work, however your state will updated based on the polling frequency
yea, and this is where I start to grow grey hair.. or loosing it all 🙂
If a manually connect to the projector I get into the same "session"... i.e. I can see the responses that it sends.. (see pastebin).. and it really seems to be sending OK1..
Is there any way I can debug HA to actually see what is coming back in? (tcpdump not available in the HaOS)
are you waiting upwards of 30 seconds for the state to respond?
the polling frequency is 30 seconds
so when you turn it on, it can take upwards of 30 seconds for the switch to show on
the downside of polling.
the reason it works fine without value template is because you're using an assumed state
I can totally live with that 😄 I have about 50 "OK1" being sent from the projector.. still nothing 😦
no, that's not how it works
the good thing with this "shared session" in the projector is that I can see each request / response...
home assistant asks for the state every 30 seconds
ah ok
try stripping the whitespace
yea, and when I telnet in to the projector I can see that its answering with OK1 every 30 sek.. have also tried adding \r to the command.. then it response with "f"...
'{{ value.strip() == "OK1" }}'
thanks! Done.. restarting... btw, any way I can manually just reload /config/switch.yaml or do I need to do the whole "Server management" restart?
that platform does not support quick reloading
if that template doesn't work, then try this one
"{{ '1' in value }}"
will try! But now the poling actually stoped .. will restart the host to be safe..
that worked!! Now I really want to debug the incoming response to HA!
"1" seems quite weak 🙂
well, it's always going to be OK1 or OK0, the rest really isn't needed
there's most likely hidden characters in that string
but at least its getting "something" back... and with a 1 in the response
np
got tcpdump running.. seems like the actual response was:
Transmission Control Protocol, Src Port: 23, Dst Port: 55035, Seq: 1, Ack: 11, Len: 16
Telnet
Data: OK1\r\n
Data: Optoma_PJ>
so: value_template: "{{ 'OK1' in value }}" 😄
Hi! I am trying to create a default for some of my templates. Can someone tell me where I should be putting it in here?
network_upload_speed:
friendly_name: "Network Upload Speed"
unit_of_measurement: "MB/s"
value_template: >-
{{state_attr('binary_sensor.edgeos_interface_eth0', 'MBytes/ps (Sent)'|round(2, default = 0))}}
Should it be in the round filter?
Looks like that works!
The round() filter goes outside state_attr(), not inside.
{{state_attr('binary_sensor.edgeos_interface_eth0', 'MBytes/ps (Sent)') | round(2, default = 0) }}
Is this the correct syntax when fixing templates to have a default value (of 0), previously it was: int(base=16) now it's int(base=16, default=0). Does that look right?
Should be. You can test in
->Templates
If I am trying to write an attribute into a new sensor but I want if statements too, how can I do that? Right now, it is printing state_attr('media_player.tv_living_room_cast','media_position')
tv_living_room_media_position:
friendly_name: "TV Living Room Media Position"
value_template: >-
{% if state_attr('media_player.tv_living_room_universal', 'app_name') == "YouTube" %}
{{ state_attr('media_player.tv_living_room_cast','media_position') }}
{% elif state_attr('media_player.tv_living_room_universal', 'app_name') == "Plex" %}
state_attr('media_player.plex_plex_for_android_tv_chromecast','media_position')
{% else %}
Problem
{% endif %}
You didn’t surround it with {{}}
Ah it seems I did have it right, its just those particular attributes that may be the issue.
Yeah I fixed the first one, sorry for the confusion
Hi guys, templating is just not for me :/ so even for easy things i need your help..
I do have a sensor with this value:
12.11.21 12:19:54
I am able to change it to
12-11-21T12:19:54
But the entities lovelace card says its a wrong format. How can i change 12-11-21 to 2021-11-12 ?
Thanks in advance 🙂
I think you need to tell us what you are trying to do in a more broad view. I have a feeling you've gotten stuck on a detail along the wrong track.
I think there's a bot command for that
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
@hazy trench posted a code wall, it is moved here --> https://hastebin.com/ogitaveleb
I am moving my legacy templates into a separate templates.yaml file to match the modern templating scheme. So far so good, but I cannot resolve the issue of icon_template. The exemple below works as a legacy template, but I cannot make it work in the modern way...
...
icon_template: >-
{% if is_state('sensor.cat_flap_chatiere_cuisine', 'unlocked') %}
mdi:lock-open-variant
...
Just place it under icon: like this:
icon: >-
{% if is_state('sensor.house_mode', 'Guest') %}
mdi:account
{% elif is_state('sensor.house_mode', 'Away') %}
mdi:home-outline
{% else %}
mdi:home
{% endif %}
how can we add the device_id check to this template: {{states.light|selectattr('attributes.is_hue_group','eq',true) |selectattr('device_id','eq','e6f4e95redacted8601') |map(attribute='name')|list }} without it the list is created nicely, and the standalone template {%- for s in states.light if s.attributes.is_hue_group == true and device_id(s.entity_id) == 'e6f4e9redacteddbe8601' %} {{s.attributes.friendly_name}} {%- endfor %} shows a correct outcome
I need the former format though because it should auto-populate an input_select.set_options automations ;-
been figuring I might also start with {{device_entities('e6f4e95dredactede8601')}} which is a nice list, but then how to only select those that have attributes.is_hue_group == true ..
I love this board... so many smart people around... Thanks @marble jackal
you need to map the generator to entity_id before using selectattr('device_id'...
you mean like: {{states.light|selectattr('attributes.is_hue_group','eq',true) |map(attribute='entity_id') |selectattr('device_id','eq','e6f4e9redacted8601') |list }} ? still empty I am afraid
Is there away to create a online if statement in jinja? I.e something like this.
{{ state_attr('group.residents', 'entity_id') | list | count > 2 | if true return 'house if full' }}
hmm, this is silly, but if I have a multiple slugged entity_id, like scene.living_ceiling_4_sofa_concentreren how do I select the object_id up to the last underscore?
Which part would you like to have?
living_ceiling_4
Is alwayls like domain.a_b_c_d_e where you want a_b_c?
been fighting with {{states.scene.living_ceiling_4_sofa_gedimd.object_id.split('_')[-1]}} and stuff, but simply fail to see how I get there...
no, the amount of _ is not fixed, some have 1 some have 2... or 3 as you can see.
@floral shuttle Whats the input string and whats the expected output?
Is this not what you want? {{ 'scene.living_ceiling_4_sofa_concentreren'.split('.')[1:]}}
This outputs
"living_ceiling_4_sofa_concentreren"
i need to do this: {%- for s in states.scene if select == s.object_id.split('_')[0] %} {{s.entity_id}} {%- endfor %} where select is the string living_ceiling_4 and I check if that is the exact string in the object_id, minus the last _
thnk I found it: {{states.scene.living_ceiling_4_sofa_gedimd.object_id.split('_')[:-1]|join('_')}}
yup, working perfectly in an auto-entities filter now: filter: template: | {% set select = states('input_select.hue_group_v2')|lower|replace(' ','_') %} {%- for s in states.scene if select == s.object_id.split('_')[:-1]|join('_') %} {{s.entity_id}} {%- endfor %} allowing me to filter scenes .living_lezen from .living_ceiling_4_sofa_lezen 😉
use select instead of selectattr, remove the eq as well.
thanks, but.... TemplateRuntimeError: No test named 'device_id'.
maybe we cant use the device_id () templates like this?
Then you have to use map('device_id') then select
device_id is a filter
so you have to apply the filter on an entity_id
keep in mind that this is going to wipe out the entity_id, so you may need to approach this from a different direction
let me explain the use case: from my Hue bridge with device_id e6f4e9xyz8601, I want to select the entities that have an attribute is_hue_group = 'true'.
list those, so I can use them in an automation and set that to input_select.set_option
yeah, thats what I figured here #templates-archived message but I couldnt select anything after the initial device_entities() list
it's probably just a list of entity_id's so you'd need to expand it
just checked, it is
Thats is! Bingo! {{expand(device_entities('e6f4e9redacted dbe8601')) |selectattr('attributes.is_hue_group','eq',true) |map(attribute='name')|list}}
a perfect list of the hue_groups on that bridge! made my day!
cool. Now I only need to get the template-entity-row in my auto-entities card to show the scene attribute: name and all is perfect and automated. But I dont think we can set options under a template filter.
Here is something I can't work out on my own: I want to create a template light for which a input_numer.brightness helper defines the intensity of the light:
service: script.level_brightness
data:
brightness: "{{ brightness }}"```
How do I apply the brightness value from the template light to the `input_number.brightness` entity in the `script.level_brightness`?
That is how I get to know the value of input_number.brightness right? But what would the script look like?
does anyone have a party mode template /blueprint or whatever? i want to use it for a 150/160 bpm (hardstyle) party. with a speed switch would be ideal
home assistants event loop only has 1 second resolution, anything lower than that may not respond as expected. So if you're trying to cycle lights, then you should be looking towards hardware that supports that instead.
I have a sensor that returns sensor data that looks like this:
{
"tamper" : false,
"batteryLow" : false,
"alarm" : false,
"lastUpdateTime" : 1636833942,
"lastAlarmTime" : 1636833927,
"serial" : 172511,
"isMotion" : false
}
(Which I can massage quite a lot). I was thinking the sensor could curl a POST to hassio's REST API. I keep thinking that a webhook template sensor (https://www.home-assistant.io/integrations/template/#storing-webhook-information).
Am I wildly off-path?
2nd for MQTT, you won't have a polling rate. It'll just update when it updates
Hi! I’m using the WLED integration to turn on some preset light variations. They are named Christmas1, Christmas2, Christmas3 (and so on), and my goal is to use the random function to pick a different preset each night. I tried using the following syntax to do this:
option: Christmas{{ range(1,3) | random }} Any ideas how to append “Christmas” with a random number to choose one the 3 presets I have set up so far? It appears to only pick the first one each time.
Third for MQTT because it's da best
@manic onyx posted a code wall, it is moved here --> https://hastebin.com/tunoyozayi
Hi! I am trying to get a value based on dividing two sensors. In the template editor, I get no errors but when I put it in my config it gives me an error of invalid key
- platform: template
sensors:
percent_shares:
friendly_name: "% of shares"
unit_of_measurement: "%"
{{ (float(states('sensor.nodered_b200b78fac3dcbe1'))) / float(states('sensor.nodered_d5331f58123a7457')) | float | round(2) }}
Shouldn't you have state: before the template code? And the template code needs to be quoted.
i think thats what I was getting wrong, going to try it now...thank you
for legacy template sensors it's value_template:
I have a dictionary like this:
'Test 1':
{ 'type': 'A', 'value': 5 },
'Test 2':
{ 'type': 'B', 'value': 12 },
'Test 3':
{ 'type': 'C', 'value': 14 }
}
%} ```
I would like to get a list of the first level after info, so `[ 'Test 1', 'Test 2', 'Test 3' ]` but I can't find out how. Any suggestions?
{{ info.keys()|list }}
Knew it would be simple 😅 Thanks!
Then how do smart lights with no hub do that with built in scenes/effects?
Yeelight for instance
The ones without hub respond like I thought they would. (I had similar lights with no hub before)
Hama to be precise
I have a picture of a friend of mine who has a yeelight in his home assistant (integration) and he has a lot of scenes/effects which he didn't create him self.
They have built in effects that can do that at the hardware level.
I'm new to templating and I'm trying to figure out why this just displays the code exactly how it is, opposed to the value of the expression:
type: custom:button-card
show_label: true
label: |
{{ expand('group.my_lights') | selectattr('state', 'eq', 'on') | list }}
you're not using the right template format for that card
you're putting Jinja templates in a custom button card, which uses Javascxript
the easiest thing is to create a template sensor with that template and then use it in the card (again, using the right syntax)
I'm trying to develop a card that automatically adjusts itself to the group.entity I give it. The group.my_lights would eventually be replaced with a decluttering-card variable, so I'm trying to avoid configuration sensors.
ok. regardless, you need to use the right template syntax
I understand that, what would be the equivalent JavaScript expression?
it isn't straightforward, and I don't know Javascript well enough
like I said, the easiest way is to create a template sensor for that
I've never used the decluttering card, so I don't know how that changes things
Ok. Thank you for your help!
with this template, i kept getting errors when one of the input sensors (temp or humidity) is "unknown" for some reason. i set default values for the floats which gets rid of the error but technically its not correct as it now just sticks in 0 itno the formula if temp or humidity value is unknown. what I'd prefer to do is have the sensor return unknown if temp or humidity is unknown. is that possible in a template?
use an availability template
can you point me to an example? I'm having trouble finding one (my google fu is weak today)
my simplified test example:
- name: "T"
unit_of_measurement: "°C"
availability_template: >-
{{ 0 if is_state('sensor.average_temperature','unknown') else 1 }}
state: >
{% set T = states('sensor.average_temperature') | float(0) %}
{{ T | round(1, default=0) }}
does that look right?
this is simpler:
availability_template: "{{ not is_state('sensor.average_temperature','unknown') }}"
ah
you don't need the default anymore, unless you need to catch other stuff
in which case, you should adjust your availabiilty_template
good point
though the warning messages iiuc make it sound like default will become mandatory soon?
no
the warning specifically mentions that a template without a default will fail to render if it gets garbage that it can't handle. avoid the garbage and you don't need the default
you don't want the default value anyway - that's why you're here
thanks
hmm, syntax doesn't seem to be working for me
unit_of_measurement: "°C"
availability_template: "{{ not is_state('sensor.average_temperature','unknown') }}"
state: >
{% set T = states('sensor.average_temperature') | float(0) %}
{{ T | round(1) }}
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://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
and what about it isn't workign?
oh, you're mixing up the two formats
pick one and stick with it
read the page, follow the examples, don't mix them up
as in the old vs new format?
yes
you're using availability_template from the old one and state: from teh new one, at least
but you didn't mention the error, so..
the template page doesn't make it obvious what the difference is. is it the new syntax
{{}}```
or am I barking up the wrong tree?
there's a section for the legacy format at the bottom of the page, and the whole top part is the new one
i see that - ok i have them side by side. examining it now
ah... availability vs availability_template
unit_of_measurement: "°C"
availability: >
{{ not is_state('sensor.average_temperature','unknown') }}
state: >
{% set T = states('sensor.average_temperature') | float %}
{{ T | round(1) }}
this seems to work but still I see this warning:
Nov 15 12:28:31 ha hass[782818]: 2021-11-15 12:28:31 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'float' got invalid input 'unknown' when rendering template '{% set T = states('sensor.average_temperature') | float %} {{ T | round(1) }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
but i guess that's ok to ignore now I have a working availability state?
I wouldn't have expected it to evaluate the state template if the availability template evaluates to false
i almost feel like i have to put the defaults in just to quiet those warnings
this works for me:
- sensor:
- name: foo
availability: "{{ is_number(states('input_text.test')) }}"
state: "{{ states('input_text.test')|float }}"
if I put a number in input_text.test, I get a number in the sensor state. If I don't, I get "unavailable", as I would expect. I never get a warning
hmm
perhaps you didn't reload template entities or restart HA
2021.11.3
same here
then I do not know
ok, I'm putting that mystery on the back burner now
got to do some other stuff
thanks for your assistance @inner mesa
much appreciated
I've got a template that selects the next lighting effect on a WLED Light, it achieves the desired result in the template area of developer tools. I would like to know how I can use this triggerd by a button press on an Ikea remote...
{%- set effect_list = state_attr('light.wled', 'effect_list') %}
{% set effect = state_attr('light.wled', 'effect') if state_attr('light.wled', 'effect') else effect_list[0]%}
{{ effect_list[effect_list.index(effect)+1] if effect_list.index(effect) < effect_list|count-1 else effect_list[0]}}
line 2 could probably be condensed to `{% set effect = state_attr('light.wled', 'effect')|default(effect_list[0]) %}
wonder if you could use a counter to make this easier?
not sure if this is useful to anyone, but for me it is, and I just found out we can nest the new device_id template options, eg {{expand(device_entities(device_id('Philips Hue 1'))) |selectattr('attributes.is_hue_group','eq',true) |map(attribute='name')|list}} using the actual device name. No more hassle goijg through the device_registry ..
|selectattr('state', '==', 'dead')|list -%}
{{state}}
{%- endfor %}```
How would I filter friendly name from this?
<template TemplateState(<state sensor.powerplug_node_status=dead; friendly_name=PowerPlug: Node Status, icon=mdi:robot-dead @ 2021-11-15T16:20:31.136989+02:00>)>```
| map(attribute='friendly_name')
If you're using selectattr(...) in a for loop, you don't want to use | list. |list converts the generator to a list, it will be faster without the | list.
If you're not using it in a for loop, use | list.
Can I have this do to, and from, or does it need a separate template?
value_template: "{{ trigger.from_state.state not in ('unavailable', 'unknown', 'none') }}"```
Yes, use and between the checks in the template
thanks I'll try and get that
I'm trying to use an automation to set a input date_time to 7 hours in the future. I'm currently trying {{ now() + timedelta( hours = 7 ) }} which does not work, and nor does {{ as_local(now() + timedelta( hours = 7 )) }}, does someone have a suggestion before I get lost down a rabbit hole? 😄
I can't manage to do it. Can you show me a complete example based on my use case?
I was almost there, I needed to set the timestamp field rather than the date field (oops) and use as_timestamp: {{ as_timestamp(now() + timedelta( hours = 7 )) }}
so i wanting to read the attribute 'hvac_modes' from climate.air_con and have a new sensor based on it.. but its not working.. im new at this, can someone point out what im doing wrong? Here is a basic example
{% if states.climate.air_con.attributes.hvac_modes == "cool" %}
Cooling
{% elif states.climate.air_con.attributes.hvac_modes == "dry" %}
Drying
{% else %}
Off
{% endif %}
I don't think "modes" is a single value - it's a list of possible modes
check in
-> States
mine: hvac_modes: heat_cool, heat, cool, off
ahh yes it is a list
the current mode is the state of the entity. There's also an hvac_action attribute, which is what it's doing right now
i have no idea then.
about what?
hvac_action was removed from this LG integration
because it didnt properly show the current action
the developer removed it
ok
so im trying to recreate it basically
it said "cooling" and "heating" etc.. i was using that value in notifications
hmm, actually..
im overthinking this i believe.
the 'state' is actually what i want.. lol
slaps himself
its been a rough morning. I'm still 'pre-coffee'.
so i can do {% if is_state('climate.air_con', 'cool') %} yeah ?
ok, im properly confused now.. so my template sensor appears to have the correct value, but calling it in a notification gives a strange output
according to Developer Tools, the Entity "sensor.air_con_action" has a State of "Cooling" which is correct..
but calling that in a notification with {{ states.sensor.air_con_action }} gives something else
<template TemplateState(<state sensor.air_con_action=Cooling; friendly_name=Air Conditioner Action @ 2021-11-16T08:17:49.943941+10:00>)>
ahh
states('sensor.air_con_action') ... got it
im very new to all of this
I'm clearly not quite understanding how templates can work - I want to call a script from an automation, but I want to make the script name using a template. I can make a template that computes the name of the script correctly, but when I try to put the template into the automation it never saves and it simply won't work. What do I need to do?
alias: Test Automation
description: ''
trigger:
- platform: time_pattern
seconds: '0'
condition: []
action:
{% set currentState = states ('climate.upstairs_hall')[-1] + state_attr('climate.upstairs_hall', 'hvac_action')[-1] %}
- service: script.99bedroomaction_{{ currentState }}
mode: single
so after fixing my template to not give spurious values, is there some way i can clear out old values that are wrong? https://i.imgur.com/gW3eASi.png
@covert zealot
action:
- service: >-
{% set currentState = states ('climate.upstairs_hall')[-1] + state_attr('climate.upstairs_hall', 'hvac_action')[-1] %}
script.99bedroomaction_{{ currentState }}
Visual editor won't take that, if I edit it in automations.yaml, it just deletes the parts it won't accept.
then do it in the YAML editor
Yes, it won’t take it. I can’t save the changes from there.
Thank you for your help. Am I missing some setting or something?
What is the - following the multi line marker for? “>-“
this works fine for me:
- id: test
alias: test
initial_state: true
trigger:
platform: state
entity_id: input_text.test
action:
- service: >-
{% set phone = "iphone" %}
script.notify_{{ phone }}
data:
message: test_message
title: test_title
I don't know what the UI editor is doing, but it's wrong
Ah, got it - there's an extra indentation there. Thank you again.
value_template: "{{ trigger.from_state.state and trigger.to_state.state not in ('unavailable', 'unknown', 'none') }}"``` could someone tell me what I'm doing incorrectly on this?
what logic are you trying to accomplish with that?
just trying to stop it from triggering from, and to, those states listed
ok, that's not correct then
it's starting with whether trigger.from_state.state is true or false
I see. Should it be or, instead of and?
no, you need a different construct
I think something like this would work, but would need to test it:
value_template: "{{ trigger.to_state.state not in ('unavailable', 'unknown', 'none') }}"
- condition: template
value_template: "{{ trigger.from_state.state not in ('unavailable', 'unknown', 'none') }}"```
{{ [trigger.from_state.state, trigger.to_state.state]|select('in', 'unavailable,unknown,none')|list|length == 0 }}
This is what I currently have, I'm just messing around trying to learn a bit, and condense it
just to learn, what is the list and length part about
select() returns a generator, which is a function that returns the next element each time it's called, and |list turns that into a list. Then you can check for the length
Gotcha. Must fancier 😛
You recommend anywhere specific for learning to get better with templates. Starting to get a decent grasp but hope to one day be useful around here too
and googling for "Home Assistant thing I want to do" and seeing what pops up on the forum
I think there's a forum for it
looks like that should work in a quick test
I am trying to create a template for my Gen-2 ZCOMBO 2 in 1 smoke detectors so I have created this {% if is_state_attr('sensor.garage_smoke_and_co2_detector_smoke_alarm_sensor_status', 'value', '0') %} Test {% elif is_state_attr('sensor.garage_smoke_and_co2_detector_smoke_alarm_sensor_status','value', '1') %} Smoke {% elif is_state_attr('sensor.garage_smoke_and_co2_detector_co_alarm_sensor_status','value', '2') %} CO {% elif is_state_attr('sensor.garage_smoke_and_co2_detector_system_hardware_status', 'value', '5') %} CO_EOL {% else %} Messed up {% endif %} Although the entity provides a state value, I am trying to get the state attribute value which is a number that corresponds SDS13713 Notification Command Class.. I am not getting a error and have checked it in Dev Tools template
And...?
Profit!
the output is Messed up
so my template appear to be correct , but the entity does not seem to respond to the numeric values.
I wish it was Profit
I have tested out the devices and see that the numeric value does change in dev tool attributes, but still nada.
is there any thing I am doing wrong in this case?
What is the actual state of the sensor value attribute though? "5" or '5.0' ?
Or should you be trying to get the sensor state? is_state('sensor.garage_smoke_and_co2_detector_system_hardware_status', '5')
are you sure there is an attribute value? Shouldn't it be is_state('sensor.garage_smoke_and_co2_detector_smoke_alarm_sensor_status', '0')
Oh, wait, that's exactly what Tom said 🙂
If it is an attribute, the value can be a number, so you maybe need to remove the quotes around the number
@marble jackal gave you the answer, look 1 post above my previous response.
I just gave you additional suggestions.
If that's truly an attribute, you should be using a number not a string
is_state_attr('sensor.garage_smoke_and_co2_detector_smoke_alarm_sensor_status', 'value', 0)
you can verify the attribute is anumber by adding something to it. For example, if the result of the attribute is 5 and you put this in developer tools -> template editor:
{{ state_attr('sensor.garage_smoke_and_co2_detector_smoke_alarm_sensor_status', 'value') + 5 }}
and the result is 10.0, then it's a number. If you get an ValueError, then it's a string.
numbers are also shown in a different color in
-> States
can someone tell me why my above code won't work in template section?
Sorry, I tried to format it properly but I guess I suck at discord
you didn't close your surrounding backticks - that's why it didn't format it
it's just broken
{{ state_attr('weather.home', 'forecast')[0].precipitation_probability }}
Oh ok, Test
consider what you're doing there. state_attr() extracts the value of an attribute, and then you need to parse it. You were treating the whole parsing expression as the name of the attribute
none of my weather entities have precipitation_probability, so make sure you do
Hmm I am not very familiar with coding but I thought the second part was the name of the attribute you want returned. I do have that attribute working through Node-Red so I know it's there
it is. attributes.forecast[0].precipitation_probability' is not the name of an attribute
the attribute is "forecast"
So how do I get the precipitation_probability?
Oooh sorry I missed that
the code you pasted works. Thanks!
I am looking at it but still don't understand it fully
value_template: >
{{ states.device_tracker
| selectattr('state', 'eq', 'home')
| selectattr('attributes.essid', 'eq', 'MyWifi')
| list | count }}
This works, but when grabbing a true/false attribute it does not work?
so this does not work
value_template: >
{{ states.device_tracker
| selectattr('state', 'eq', 'home')
| selectattr('attributes.is_guest', 'eq', 'false')
| list | count }}
Any idea why?
state_attr('weather.home', 'forecast') returns the attribute, which is a list.
[0] pulls the first item from the list. .precipitation_probability returns the value of the precipitation_probability key from that list item
a count is a number, not a boolean
I want to count booleans 😄
you need to add a test, like > 0, if you want to test for non-zero
oh, so you're saying that selectattr('attributes.is_guest', 'eq', 'false') isn't selecting the "false" items?
it's probably a boolean and not a string. Try selectattr('attributes.is_guest', 'eq', false)
or selectattr('attributes.is_guest', 'eq', False) or something like that
I don't remember what Jinja wants there
value_template: >
{{ states.device_tracker
| selectattr('state', 'eq', 'home')
| selectattr('attributes.is_guest', 'eq', false)
| list | count }}
That works!
attributes can retain their native types
Thanks Rob! Learnt something new today 🙂
same thing often happens with numbers in attributes, so watch out for that, too
"1" and 1 are different
Ok that makes sense. I was spending my time on the HA doc and not on the jinja docs. I appreciate the help.
np. also helps to know some Python, but Jinja still has some of its own tricks, like that dot notation
which is equivalent to {{ state_attr('weather.home', 'forecast')[0]['precipitation_probability'] }}
Lol thanks for confusing me a bit more! I am not a programmer so learning all this as I go
I thought the [] was for lists
it's for indexing in general. with a list, it takes an index. with a dict, it takes a key name
but the precip_prob is a attribute?
like all object-oriented languages, types can define what various operators mean for them
no, it's a key
Ok I'm kind of following. It's a dict:key lookup when you call precip_prob?
you look up the key in the dict by its name, which is precipitation_probability
Ohh ok that makes sense. Yeah this is definitely going to help my automations. Thanks again
is there anywhere besides the template tester in dev tools that's suitable for testing Jinja? like, a plugin for vscode maybe?
oh... I guess there wouldn't be with ha entities, huh 🤔
asof late an ERROR is raised on my rest sensor to the SolarEdge api with value_template: > {{value_json.overview.currentPower.power|round(2,none)}} . apparently sometimes the json isnt available, and ```ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'value_json' is undefined when rendering '{{value_json.overview.currentPower.power|round(2,none)}}'
another tiny but irritating issue: state: > {{(states('sensor.teller_1')|float(0) - states('sensor.teller_1_daystart')|float(0))|round(2,none)}} sometimes renders -0.01 while it should be 0. as a consequence, recorder complains it cant be total_increasing. Should I abs this? or change the template in another way?
You should always check to see if value_json exists because it's an internet based endpoint that could be empty.
You should find out why it's going -0.01 and catch it. use an availability template to make the sensor unavailable during that time.
What are you using to make that graphic? Looks like snagit but I don't recognize those arrows. Also, is it freeware?
No, only template tester
can only think of a tiny decimal discrepancy in the floats, making the 2 not exactly identical at reset . can we set a minimum 0 as default value maybe?
getting another difficult warning, Template variable warning: 'None' has no attribute 'last_changed' when rendering which I already tried to guard with none:``` secondary: >
{% set object = states('input_select.hue_group_v2')|lower|replace(' ','_')%}
{% set group = 'light.' + object %}
{% set bri = state_attr(group,'brightness') %}
{% set rgb = state_attr(group,'rgb_color') %}
{% if states[group] is not none %}
{% if states(group) == 'on' %} Bri: {{bri}}, Rgb: {{rgb}}
{% else %} Off {% endif %} since {{relative_time(states[group].last_changed)}}
{% else %} Initiating
{% endif %}
about the test, what should i have it return if 'is none'?
use expand on your group, not states[]
you should remove all states[] if you can unless you're accessing the entire domain directly. Expand can do everything but that.
not sure about how to do that, 'group' here is used as the name, I don't need the entities in that hue_group, or expand, I just need the {{states.light.alarm.last_changed}}
for the max 0 sensor, maybe do {{[0,(states('sensor.teller_2')|float(0) - states('sensor.teller_2_daystart')|float(0))|round(2,none)]|max}} ?
already had ``` availability: >
{% set x = ['unavailable','unknown'] %}
{{states('sensor.teller_1') not in x and
states('sensor.teller_1_daystart') not in x}}
doesnt the 'none' take care of that in that case?
Verify that statement in dev tools
I cant... it always happens when I am not around 😉 most of the time is shows just fine. Still If I were to encapsulate it in an if/else clause, what would the else need to be? All deriverate templates check for existence of this main template, so I guess I would need it to be none
{% if value_json is not none %}{{value_json.overview.currentPower.power|round(2,none)}}
{% else %} ?
{% endif %}
just use expand man, that's what it's for
expand(light_group) | first | default(none), then check for none
wait, this is mixed up now. my reply above was for the json issue, not the light_group template
Skitch. It’s a good screenshot/annotation tool for Mac.
the snip tool is shit
no rolling log, no markdown with arrows or text, no editing]
can't even send a gif 😅
you can only share images via imgur or the like
^ what about this? lol
we mods
aha!
mod me lol
jk I get it
that's more responsibility than I feel like having anyways 😅
you can post images in #the-water-cooler or channels that are UI oriented
not in #frontend-archived 🤔
nope, someone probably went overboard
we have people who don't speak english here and they try to talk in images
it gets annoying fast
homeassitant_os, off-topic
fair enough
maybe anroid and ios_and_mac too
not that I "need" to send images, just curious
even with {% if value_json is not none %} {{value_json.overview.currentPower.power|round(2,none)}} {% else %} Currently unavailable {% endif %} I now see the full sensor is not available, as in not created at all, throwing the orange triangle alert in the frontend. so no testing in dev states possible other than {{states('sensor.solaredge_overview')}} being unknown
Hi, quick question.
This is how my Json object looks.
payload.ENERGY.Power[0]
On home assistant, i am trying to use this template in the mqtt sensor and nothing shows up. Any help with the format will be useful. thanks.
value_template: '{{ value_json["ENERGY"]["Power[0]" }}'
That doesn’t look like a JSON data structure, but an expression to reference an item within one
Apologies for the confusion.
{"Time":"2021-11-17T21:53:25","ENERGY":{"TotalStartTime":"2021-11-17T21:02:27","Total":0.020,"Yesterday":0.000,"Today":0.020,"Period":[ 0, 0, 0],"Power":[ 7, 6,10],"ApparentPower":[111,117,112],"ReactivePower":[110,117,112],"Factor":[0.06,0.05,0.09],"Frequency":[50,50,50],"Voltage":[254,262,259],"Current":[0.436,0.447,0.434]}}
I am trying to capture the 3 values in the power object.
Which is why you should use the code I posted with expand
We’re talking about the same here? The rest sensor with the json value_template ? There’s nothing to expand…
I did some permutations combinations based on google answers and this worked.
value_template: '{{ value_json.ENERGY["Power"][0] }}'
thanks.
thought that last response was to me, apparently you're just talking to the wind?
?? I was yes, responding to you ?
Hi, I have a template sensor that registers if my Sonos speakers are grouped, but not master. Unfortunately it throws a lot of errors, when my HA instance boots up, as the sensor is ready before my Sonos speakers are. In the template documentation, there is an example on how to make it adhere to such a scenario, but I am unsure on how to implement it in my case.
An example of the sensor is found here: https://www.codepile.net/pile/6r2vo1r3
And here is the link to the documentation: https://www.home-assistant.io/integrations/template/#startup
Can templates be used in customize: ? I want to add an icon to a scrape sensor that changes depending on the scraped value. (afaik you cant do it directly on the scrape sensor)
only if you use the custom_ui custom_component, which has not been officially supported for years. some of the avid users try to keep it working, though
yeah, sorry, multitasking and omitted the critical word 🙂
Marius is leading the maintenance fight, as far as I can tell
you're trying to use the state attribute as a list before it's available
Yup, how can I modify it to check if it's available first?
wrap it in a conditional like this i guess:
{% if state_attr('media_player.dining_room', 'sonos_group') %}
<YOUR_TEMPLATE>
{% else %}
False
{% endif %}
they'll need an "else" in there or it'll be unhappy
but better is to use an availability template field
edited
nice, i should convert a bunch of mine to use that instead 👍
it should mainly help with folks who are graphing a sensor and don't want periodic dropouts, but other times it may be better to use what you suggested. depends on the need
Interesting, could you point towards some documentation for this? Googling nets me nothing! 🙂
I'm blind, thank you!
if it returns false, the state will be "unavailable" and the state: field won't be evaluated
“`
- binary_sensor:
- name: 'dining_room_speaker_grouped_not_master'
state: >
{{ state_attr('media_player.dining_room', 'sonos_group')[0] | string != 'media_player.dining_room'
and state_attr('media_player.dining_room', 'sonos_group') | length > 1 }} - availability: true
` “
- name: 'dining_room_speaker_grouped_not_master'
Simple as this?
That’s not a template
And it’s not formatted properly. And it’s just true?
Check the docs again 🙂
Idiot with Discord, not knowing how to use code blocks
Full code here: https://www.codepile.net/pile/290A1pvq
It doesn’t make any sense
The point of the field is to provide a test for when the state should be evaluated to avoid the problem you had
And you’re not including it in the sensor definition anyway
Making it ‘true’ doesn’t do anything. That’s the default
Start by removing the ‘-‘ that precedes it to include it with the sensor definition
Thank you
@warped arch posted a code wall, it is moved here --> https://hastebin.com/yucanabegu
Hi, I'm trying to add a REST sensor to read data from a Pi I have on my Wifi. I added this to my configuration.yaml:
https://www.toptal.com/developers/hastebin/igohozuwod.less
Going to the resource URL in the browser retrieves the JSON result I expect, but when I got to entities I don't see anything for this sensor. I've already reloaded the config.
the value template should just be "{{ value_json['Beer'][0] }}"
assuming Beer is a top-level key which it appears to be based on your config
also you can remove the verify_ssl line
Thanks. I see this in the logs: Setup of sensor platform rest is taking over 10 seconds.
It’s drunk
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://hastebin.com/ (sometimes may not allow you to save)
Please don't use Pastebin, since it can randomly add spaces to the main view.
I still don't see it on the entities page
I just saw the snippet here: https://www.reddit.com/r/homeassistant/comments/kr7ags/comment/gilfog4/?utm_source=reddit&utm_medium=web2x&context=3
whoops
first "cat on the keyboard" situation
anyway, that's a little brain-hurty because it's basically a circular reference
that's why i suggested my change. for good measure i'd put the resource URL in quotes, but that shouldn't be strictly necessary
also, is the endpoint reachable from your HA host?
how can I see? ping from the Terminal tab seems to have trouble
I'm trying to control a group of lights but only have the any adjustments affect lights that are turned on (for instance not turning on a light when I'm trying to adjust the brightness of others). I think I have what I want, but I'm just not sure what to do with it. Where would I put this?
{{ expand('light.all_home_lights')[0].attributes.entity_id }}
I thought it might make sense to put it in my configuration.yaml as another light group, but even though the above returns an array, it's an invalid config to do something like this:
light:
- platform: group
name: All home lights on
entities: >
{{ expand('light.all_home_lights')[0].attributes.entity_id }}
This is my first template so I'm probably missing something obvious...
That option can not be templated. https://www.home-assistant.io/integrations/light.group/#entities
See how the document says "string" | (or) "list" but no "template" next to the option?
Ah ok I see. That's helpful to know
So where would I template this. I just came across light templates, but I'm not exactly sure if this is what I want
No that's not what you want either. You could use that template when calling the light.turn_off service in an automation or script.
So what do I want? haha
Well I just want to use the normal light group or something along those lines to control a group of lights, but I don't want the changes to affect lights that are off
So if I change brightness, temperature, etc
Then you cant use a light group.
Ok what would I use?
A script.
Right but that doesn't seem to do what I want, does it? Isn't a script something that just runs one off?
It runs whenever you call it, like from the tap action of a Lovelace button.
Take a step back and explain your actual issue.
you might actually want to make a template light, and then call the script with whatever changed in the template items
that way it still looks like a light to the system and uses the same cards and such, but you can control what actually happens
I think I did before. I'm trying to control a group of lights. The light group works great because I can change all aspects of different lights at once. The only problem with this is it applies to lights in the group that are off and I don't want this. How do I get all of this exactly except with the lights that are off not being affected
See Rob's idea above about using scripts and template lights.
Ok nice I got something! 😄
I think I just need to fix my template now because I just have it running on all lights and not just the ones that are on
That’s where the code I gave you yesterday comes in
Was trying to see if I could derive it myself first by looking through the docs so I can learn this stuff better
One question I do have though is the join(','). Can you substitute something that should be a list with those items separated by commas?
foobar:
- foo
- bar
foobar: foo,bar
Are those equivalent?
@inner mesa Also there was a problem with what you had given me. I don't think you can expand a light group. Or at least that isn't the behavior I saw. When you expand it, it just returns a list with a single element of the group itself
That's why I had to do expand('light.all_home_lights')[0].attributes.entity_id to actually get at the list of lights
I'm not able to see a terser way of doing that though. Like how do I just get at a single entity by name?
Yeah that's fine, was just hoping to keep it as a light group if possible
Learning experience I guess. I'd rather not change my setup just due to lack of knowledge
How would you get all entities associated with a light group though?
I think I got it working though 🙂 Really appreciate the help
this takes a light.group and either returns a comma-separate list of entities that are on, or the light group itself if none are:
{{ states.light|selectattr('entity_id', 'in', state_attr('light.foo', 'entity_id'))|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|join(', ')|default('light.foo', true) }}
replace light.foo with whatever your light.group is called
either way, you do need to handle the case where all lights are off
maybe you do that with a condition preceding the light.turn_on that just aborts if none are on, or you decide to turn them all on as I did in the code above
but you can't just end up with an empty entity_id list because that will cause an error
Think I'm getting the hang of this, or at least a good start
I got all the states synced up with the template light and all the adjustments are applying appropriately
I'd still like to find a way for me to not need to define all those entities twice, once for the light group and then once for the group
I guess I could just get rid of the light group and make it a template that is just all the entities in the group?
I did see it
It does what you want?
I thought that had a little more going on since you were doing the filtering
It does what I said above
Anyway, you’re welcome to proceed as you wish. Hopefully you have enough info now
This is what I have now
Ok so essentially it's this part that gets all entities for a light group: states.light|selectattr('entity_id', 'in', state_attr('light.all_home_lights', 'entity_id'))
I guess it seems kinda messy compared to just expand('entity_id')
But yeah kinda seems like either do that or define it in two places. Not sure how else I could keep it centralized
I kinda see what you're saying about the off state but I'm not sure I understand why. I have the turn on and off and also value template pointed at the light group
But as soon as i turn the lights off it gets all weird
The state doesn't update and it still shows as on, and clicking it does nothing
I do understand why adjusting levels wouldn't work because those entities are determined by what lights are on. So when there are none it has nothing to act on
value_template: "{{ states('light.all_home_lights') }}"
Like the state should be the same as that one but it's not
level_template: "{{ state_attr('light.all_home_lights', 'brightness') }}" same goes for the brightness.
As soon as I turn off all the lights it just gets stuck in the last state it was in and doesn't update
ok so maybe some of them make sense since after all the lights are turned off light.all_home_lights just doesn't report brightness so I guess it doesn't update
but what about the state? The state does update but the state of the template light doesn't update
Interesting. Seems like I need to default the temp and brightness otherwise the card doesn't update
Confusing though because I would think the state is what would determine if the bulb was on or off
but BOTH the temp and brightness need to be defaulted. Maybe it just gets all messed up when there isn't something there?
Hi I wounder if I in some way could convert a string consisting of time in 24 hour format like '13:45' to an integer with minutes from midnight. That is 13 hours equals 760 minutes so 13:45 would be 805.
I'm new to templates, but I hope that could be a way to go?
@atomic blade I had that as well, there is an PR pending to fix it after I reported an issue about it. You can fix it now by converting the value to an integer (with a default to avoid warnings).
When the light is off, there is no brightness attribute anymore. There was fix in place to work with "None" but at some point that was replaced with None (so not a string anymore) and the fix didn't work anymore.
When you use level_template: "{{ state_attr('light.all_home_lights', 'brightness') | int(0) }}" None will be converted to an integer (0 with this template) and it will work again
Here is the PR https://github.com/home-assistant/core/pull/59705
@fervent hemlock found the answer my self 😉
'{{ state_attr("sensor.dje44g_auxheat_status", "auxheattime2")[:2]|int*60+state_attr("sensor.dje44g_auxheat_status", "auxheattime2")[3:]|int}}'
{% set h, m = state_attr("sensor.dje44g_auxheat_status", "auxheattime2").split(':') | map('int', 0) | list %}
{{ h * 60 + m }}
or
{{ (state_attr("sensor.dje44g_auxheat_status", "auxheattime2") | today_at - today_at()).seconds * 60 }}
You need to adjust your light template to handle the case when brightness doesn't exist
something like
level_template: >
{% set brightness = state_attr('light.all_home_lights', 'brightness') %}
{{ brightness if brightness is not none else 0 }}
Then when your light is off, the brightness drops to zero and if you move the slider or turn the light on, it will bounce back.
That's what I do and it works wonders
Great thanks for letting me know. I was using default(0, true) instead of int(0). Would 1 be preferred over the other?
@mighty ledge ^ That's how I ended up handling the issue where it was empty. Is your way better?
The result will be the same I guess
Oh, I just realised I posted this in the wrong chat, sorry!
hi, i need help on making a template sensor from zha_events so i can use them in some automations
i want to be able to tell when a button if being held, vs when its released
as i wish to use those in a 'repeat' in an automation
You are probably going to have to use a triggered sensor or automation as your button will generate events, not state changes. Does your button generate a released event?
Hello, I want to call 2 API's. FIrst, GET - to get XSRF token from response header, and then POST with that XSRF token in header. How can I achieve that?
it seems to generate a 'stop' when you release the button.. ive tried to 'repeat until' but it doesnt work properly
it never seems to stop repeating
Then you should trigger on ‘stop’. My zwave button sends ‘keypressed’ for a tap, rapidly repeats ‘keyheld’ or similar for a hold, and a ‘keyreleased’ when you release after a hold. ‘Pressed’ works for a tap, ‘released’ works for press and hold, and I just ignore the ‘keyheld’
i want to be able to hold the button to dim the light
so i assumed i would have to 'trigger' on the HOLD and then 'repeat until' the STOP
So an automaton with a time_pattern and an input_boolean that you set to true when the button is pressed and false when released?
No
That’s not what that’s for
I mean it could be, I suppose, but not directly with another event
I just dislike that construct
it only sends the single event on the HOLD
and nothing again until STOP
actually..
maybe it is sending multiple events while holding..
That’s consistent with what I suggested. But if you have something else to use…
i think i stuff something up
because once i try this, the entity seems to get stuck
as if the automation is still running
Hello, I have a sensor (air_quality.air_quality_detector) that has Attribute 'Humidity'. I would like to make a separate sensor that will have value of that attribute.
This is what I have so far:
- platform: template
sensors:
mija_humidity:
value_template: '{{ states.air_quality.air_quality_detector.humidity }}'
unit_of_measurement: '%'
Thought value is always 0. Not sure what's wrong here. Any help appreciated.
Many thanks 🙂
I tried this:
sensor:
- platform: template
sensors:
mija_humidity:
value_template: "{% if states.air_quality.air_quality_detector %}{{ state_attr('air_quality.air_quality_detector', 'Humidity') }}{% endif %}"
unit_of_measurement: '%'
But it't just returning 'unknown' state
Did you try the template tool in home assistant to get see what the attributes are? Attributes are usually lowercase in my experience.
Wow that's a great tool!
Moving here from #automations-archived ... I am struggling with a simple test automation, https://pastebin.com/Jj8XqgUt, I can't get the conditions to work. I have read the doc's over and over again and tried too many variations in the process. Please help me see what I am doing wrong. Thanks
There's nothing obviously wrong with the syntax of what you have written. Use the template editor to check each part of the conditions. Enter things like this ```
{{ is_state('sensor.period_of_day', 'morning') }}
{{ is_state('input_boolean.luxcontrol', 'on') }}
{{ (is_state('weather.home', 'sunny') }}
{{ (states('sensor.avg_illumination') | int < 40) }}
Alternatively you can inspect the automation trace.
Yeah, that part checks out... The issue is in the formatting I suppose. I get this in the log, and have issues decipher it... Invalid config for [automation]: Expected a dictionary @ data['action'][0]['choose'][0]['conditions'][2]. Got None. (See ?, line ?). Invalid config for [automation]: Expected a dictionary @ data['action'][0]['choose'][0]['conditions'][0]['conditions'][2]['conditions'][0]. Got None Expected a dictionary @ data['action'][0]['choose'][0]['conditions'][0]['conditions'][2]['conditions'][1]. Got None. (See ?, line ?).
Ok, there was a parenthesis wrong in the second from bottom, but still no dice. Same log message. Thanks for trying to help
Can anyone advise on whether the following is the best way to stop 0.0 value states getting logged from a template sensor derived from a rest api call?
value_template: "{% if state_attr('sensor.testnumber', 'number') is defined %} {{ (state_attr('sensor.testnumber', 'number') }} {% endif %}"
Rats... Turns out it is infact not the testfile throwing the log. Have some digging to do. Thanks @fossil venture
This is what I had which was giving me a very occasional 0.0 which I'm trying to fix with the above: {% if is_state_attr('sensor.testnumber', 'number', '0') %} {% else %} {{ (state_attr('sensor.testnumber', 'number')| float / 10**15) | round(2) }} {% endif %}
obviously the old code for whatever reason (that I can't identify) was still occasionally giving me a 0.0 instead off a genuine number
where is isocalendar documented? like now().isocalendar()[1]
that's a function of the python datetime.datetime object
I have this template: https://pastebin.com/dHcxP6ur
It works as intended, but whenever I restart HA and the source sensors are briefly unavailable, my logs are flooded with errors like this:
WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'float' got invalid input 'unavailable' when rendering template
Can the template be modified somehow to not throw errors when the input is a string?
See the pinned message about the default values
Does anyone have a good way of rounding a timedelta object to the nearest second from this:
Time Remaining: {{ (as_datetime(states('sensor.washer_completion_time')) - now()) }}
I get values like Time Remaining: 0:13:59.057523
It seems to be impervious to timestamp_custom.
Time Remaining: {{ ((as_datetime(states('sensor.washer_completion_time')) - now())) + timedelta(seconds=0.5) }}
is returning a datetime.timedelta object which leaves me in the same place as before. Unless I'm missing something. How would you chop off the seconds?
there's gotta be a better way, but:
{{ ((((now() + timedelta(seconds=1.7)) - now()) + timedelta(seconds=0.5))|string()).rsplit('.')[0] }}
it's the last part that matters - convert to string, split at the . for the fractional part, then take the first part
I see Google references to round() that's supposed to work on a timedelta, but doesn't
Yeah, that's what got me hung up, the round() not working.
then you could use strptime on that string if you wanted a datetime
I feel like I often do at Home Depot, having gone in to get one piece and coming out with 10 adapters that connected in a sequence
This works:
Time Remaining: {{ ((as_datetime(states('sensor.washer_completion_time')) - now())|string()).rsplit('.')[0] }}
No need to add the timedelta. I don't know if you were adding it to change it into a timedelta or what, but it already was somehow.
I was making up a time
Oh, I see what you were doing. Okay.
It's for display, not calculations, so this will do. The alternative was:
{{ '{:02d}:{:02d}:{:02d}'.format((t // 3600) % 24, (t % 3600) // 60, (t % 3600) % 60) }}```
yeah, that's worse
But I'd rather just make a lovelace card with a template than to make a template sensor just for display.
I'm not loving it, but it'll have to do seeing as the round() doesn't work as I think it's supposed to.
Thank you.
NSFL:
{% if (remt|string()).rsplit(':')[0] != '0' %}
{{(remt|string()).rsplit(':')[0]}}
hours and
{% endif %}
{{ (remt|string()).rsplit(':')[1].lstrip('0') }} minutes.```
almost finished aligning templates, but one
instead of ...| int }} should work with ...| int(default,0) }} ?
it depends on what you want. first, it would be |int(0), and then it would simply evaluate to 0 if the input was a string such as the ones you're filtering for
well...honestly....i want that tempalte to ork when upgrading to 2022.1 🙂 🙂
there's nothing there that won't work
the log says...template will fail to render after 2022.1
so i want to have a clean log from my ha 🙂
what's the error, specifically?
what's the state of states('input_number.motion_status_mqtt_ago')?
it's usually better to fix things that are broken than to rely on a default
which is why they're making this change
no problem with changes...that's why i try to stay on same line with latest version
it's curious that an input_number.* helper would ever be unknown
but it may be related to where you're using the template
if it results in "null", and then you're setting the value of that helper to the result of that template, then...
i copied sensors for mqtt so to know if something is broken to check that devices i am relying for
so...for instance i like that mqtt message dropped sensors is unknown... 🙂 so for that i'm happy to not have dropped messages in my smart network
but i will modify int (0) because that sensor tells me when it was last connection to my mqtt...not that important
Why can I not get this right? I have tried to define a default value here, but HA is still complaining that this template will fail to render in 2022.1:
{{ ns.states | sum | round(2, "floor", 0) }}
2021-11-20 23:14:30 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'float' got invalid input 'unavailable' when rendering template
There’s no float in what you posted
Sorry... https://pastebin.com/Nys57Yy8
I'll be honest and say that someone wrote this template for me. I have no idea how to troubleshoot it. But as far as I can understand, line 6 takes the state from each sensor, converts it to a float and sums it with the previous ones?
Yes, for a brief time before HA has gotten data on the sensor, it has unavailable as state. The template works great as it is, but during startup it floods my logs with error messages...
If you just want it to evaluate to zero in that case, just use float(0.0)
Is that what it syays here: https://www.home-assistant.io/docs/configuration/templating/#numeric-functions-and-filters ?
That behavior is changing. That’s what the warning is telling you
Yeah, I've seen the warning for a few weeks but putting off trying to understand it. While trying to figure it out I was always looking at my round function as the problem. I understand now what was really the problem.
Thank you!
Is there a way to loop over all entities with a name matching a pattern, like "light.office_"?
Yep, a few
Cool! My idea is when motion is detected loop over all lights in that area and increase their brightness % by a factor.
Would you mind pointing me in the right direction?
You don’t want to loop - you just want to generate a list of entities that you pass to light.turn_on
right?
Correct
- Generate a list
- Switch each light on and set brightness_pct = current brightness_pct * 1.5
{{ states.light|selectattr('entity_id', 'match', 'light.office_')|map(attribute='entity_id')|join(', ') }}
If you want to set them all to a certain percentage, then you just do what I said above using that template for the entity_id. If you want to individually control each light by adjusting it separately, then you will need to loop
but you can't do that entirely within a template
Best case would be having this as a script with two in parameters, entity pattern and brightness factor
Where can I find the documentation for the templating/scripts ?
For example I notice the match filter isn't accepting patterns and I would like to add a reject to my list as well:
Something like this rejectattr('entity_id', 'match', "*window") |
Thank you
are conditions not allowed in scripts? I have the following in a sequence of a script
- service: notify.telenotify
data:
message: First service
- conditions: "{{ service_mode in state_attr('sensor.mycarentity','service_check'}}"
- service: notify.telenotify
data:
message: Second Service
and it reports the following during the config validation 2021-11-22 08:07:14 ERROR (MainThread) [homeassistant.config] Invalid config for [script]: [conditions] is an invalid option for [script]. Check: script->sequence->1->conditions. (See /config/configuration.yaml, line 194).
I have verified that this template works fine, i.e returns true or false "{{ service_mode in state_attr('sensor.mycarentity','service_check'}}"
The following worked. but strange, this is not the same according to this doc https://www.home-assistant.io/docs/scripts/conditions/#template-condition
- service: notify.telenotify
data:
message: First service
- condition: template
value_template: "{{ service_mode in state_attr('sensor.mycarentity','service_check'}}"
- service: notify.telenotify
data:
message: Second Service
See the big yellow warning box at your link
agreed I overlooked that. However, the template condition is also different format as per docs, it should be
condition:
alias: "Iphone battery above 50%"
condition: template
value_template: "{{ (state_attr('device_tracker.iphone', 'battery_level')|int) > 50 }}"
but the above does not work. only the below works. what am I missing here?
- condition: template
value_template: "{{ service_mode in state_attr('sensor.mycarentity','service_check'}}"
What do you mean by ‘doesn’t work’?
I've tried searching the forums & this channel, the answer may be there but I can't find it! I was wondering what the binary sensor yaml code is to extract the status of multiple switches from one state topic. This is the way it spits out below
tele/tasmota_D026F3/SENSOR = {"Time":"2021-11-22T15:35:48","Switch1":"OFF","Switch2":"ON","Switch3":"OFF"}
if I give the below, which is as per the docs https://www.home-assistant.io/docs/scripts/conditions/#template-condition
- condition:
condition: template
value_template: "{{ service_mode in state_attr('sensor.mycarentity','service_check'}}"
I get this error ERROR (MainThread) [homeassistant.config] Invalid config for [script]: Unexpected value for condition: 'OrderedDict([('condition', 'template'), ('value_template', {{ service_mode in state_attr('sensor.mycarentity','service_check'}})])'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['sequence'][1]. Got None. (See /config/configuration.yaml, line 194).
if I give the below, there is no error and executes just fine.
- condition: template
value_template: "{{ service_mode in state_attr('sensor.mycarentity','service_check'}}"
Those docs are for the condition portion of an automation. A single condition inside a script sequence is simply
- condition: template
value_template: "{{ service_mode in state_attr('sensor.mycarentity','service_check'}}"
Yes I got that, however, I believe we would need to update the docs to avoid somebody wasting their time.
No, you're in the wrong spot, you're linked from the automation docs
you should be in the script section, not automation
you wasted your own time
Don't want to argue, but if you look at the link I gave it is linked form scripts and that page starts with this statement Conditions can be used within a script or automation to prevent further execution. When a condition does not return true, the script or automation stops executing.
Furthermore, there is this statement in the same page This shorthand notation can be used everywhere in Home Assistant where conditions are accepted. and after which there is indeed a helpful warnings. So all I am saying is we could relook at docs. But if you are so insistent that all is fair and well, then we'll, its your viewpoint of not accepting a fault
Then you're welcome to contribute by clicking the
instead of arguing like you don't want to do
Would anyone have a template that looks like the default gauge but works with a thermostat's attributes? I have a current_humidity I'd like to show in a gauge.
You make a template sensor to expose they attribute, then use that new entity with the card
OK. I guess I'll do some research and try to figure out what that means. lol Thanks.
Thanks!
I'm trying to display hh:mm:ss till a certain timestamp but I can't for the life of me figure out how to do this
I've created a template thingy to just how the seconds remaining as follows:
sensor:
- platform: template
sensors:
timer_remaining_sec:
friendly_name: "Timer - Remaining Seconds"
value_template: >-
{%- if (states['sensor.kitchen_speaker_timers'].attributes.next_timer_status == "none") -%}
{{ 0 | int }}
{%- else -%}
{{ (as_timestamp(states['sensor.kitchen_speaker_timers'].state) | float - as_timestamp(now()) | float) | int }}
{%- endif -%}
entity_id:
- sensor.kitchen_speaker_timers
But this only updates once every 30 seconds or so
Hi, my practical use case is that -after pressing a turn-on button (trigger b)- I would like to turn on only those lights and switches that were on right before i pressed the turn-off button (trigger a), thereby basicly creating a simple toggle mechanism. I don't want to make use of the scene.create functionalty anymore, because recalling those scenes is flooding my zigbee network (because it will not only send an 'on' command to individual devices, but also info about color temperature, brightness value, transition time, etc) . Instead, i just would like to send some simple "on" commands to my lights and switches via the Zigbee network. Therefore, within an automation i would like to temporarely store a list containing all entity_ids for all lights and switches in a specific area that are on right before i pressed the off-button (within the choose option for trigger a). I would like to use this list in another part of the automation later onwards in time(within the choose option for trigger b) when i'd like to turn the same lights on again. For the template itself, i am pretty much done:
|selectattr('state', 'in', ['on'])
|selectattr('domain', 'in', ['light', 'switch'])
|selectattr('entity_id', 'in', area_entities('Hobbykamer') )
|rejectattr('entity_id', 'in', ['switch.hobbykamer_adaptive_lighting'])
|map(attribute='entity_id')
|list
}}```
My question is: how could i temporarly store the ouput (a list of entity_ids) so i can use it somewhere else in the automation *later onwards* in time (for example after 5 minutes)?
I feel dumb. I put the template code for a new sensor in configuration.yaml and it worked great, so I thought I'd move it to its own file. I created sensors.yaml and added sensor: !include sensors.yaml to configuration.yaml, right underneath the scene: definition. Then I put the code for the new sensor in sensors.yaml.
But I keep getting the error: The system cannot restart because the configuration is not valid: Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 12). which I don't understand.
(and line 12 is actually the line before my new sensor: !include line)
My sensors.yaml file says:
- platform: template
sensors:
basement_humidity:
friendly_name: "Basement Humidity"
unit_of_measurement: "%"
value_template: "{{ state_attr('climate.basement_thermostat', 'current_humidity') }}"
What am I doing wrong?
remove sensor from your sensors.yaml
ahhhhh. thanks!
So just looking for some general guidance - I’m looking to create a sensor that gives the total rainfall from the past 72 hours. I have a sensor from weewx that gives total rain in the last 24 hours. I’m thinking I could create a template cumulative sensor from that value, then use history_stats or statistics to pull a ‘previous 72 hours’ value from that?
Is there a way to get the previous state without using it for a trigger? I know I can use from_state bit that only works when an automation is triggered.
@median mason posted a code wall, it is moved here --> https://hastebin.com/efuyadagus
My deebot robot vacuum has an autoempty on/off in the official app. I can listen by deebot_custom_command and get the information on whether the autoempty is on or off.
its in data.response.body.data.enable in the following example.
https://pastebin.com/jjkQ58kC
How can I make a template switch from this information? to enable/disable the autoempty, I have a separate script. which only enable/disable, but don't return the status.
Xiaomi can i get help with this?
Message #330990055533576204
@vagrant monolith posted a code wall, it is moved here --> https://hastebin.com/xabazopomi
Hey! How could I make this return the state of the closest value? Thanks!
How do you define "closest"?
I mean like if the timestamp for evening is at 1637665324.452021 and midday is at 1637665322.452021 then i want it to return like if timestamp now is 1637665323.452021 = midday 1637665325.452021 = evening. Do you unstand?
Then you need to compare things differently. Instead of comparing now - sun_state_time < 0 compare now < sun_state_time
e.g. if now < sunrise_today then you know it's Daylight
So I will need to do now < sun_state_time for all?
That's certainly what I'd do.
Play with it in the template editor in the developer tools.
The problem is that it returns evening while it should return midday
Or should I not have timestamps?
It might be easier to use {{ states('sun.sun') }} or the state_attr option for this to be honest
I know, but I want this sensor 😛
Which sensor is it?
Tbh, I think it's easier to have an automation trigger when sun_state_time == now and then put a value into a input_select
But like I want that sensor
Templates only update when a sensor updates. If now is included in the template, it will also update once per minute on the minute.
Put that template into a variable. Variables can be accessed at any time throughout the automation. If you want it to persist on separate triggers, then you need to store the list of entities in a group by setting the entitys on a group.
Use history stats integration, no need for template.
the current state in the state machine is always the previous/current state. Meaning, if you have a template and you access itself, it will be the previous state before the template resolves.
You make a template sensor using an event trigger. You have to use the new format. Then you access the data through trigger.event.data
Oh that still kinda sucks, how would I go about making a sensor/template that would show the seconds remaining till a certain timestamp then?
{% set sensors = 'sensor.sunrise', 'sensor.nautical_dawn', 'sensor.dusk', 'sensor.dawn', 'sensor.solar_midnight', 'sensor.solar_noon', 'sensor.sunset' %}
{% set next = expand(sensors) |rejectattr('attributes.today', 'eq', none) | rejectattr('attributes.today', '<', now()) | list | first | default(none) %}
{{ next.name if next is not none else none }}
You can't, it's near impossible.
Oof that really sucks, when I put a timestamp in lovelace it does show "in 2 minutes" and when less than a minute it does count down
the event loop in home assistant isn't good enough. The front end displays seconds periodically through timestamp sensors, but even those don't update every second
But I want it to always show hh:mm:ss remaining
right, the in 2 minutes is a device_class timestamp
which the front end attempts to handle
that's the only foramt that will be close.
you cannot get hh:mm:ss
I'll try with a custom front-end component I guess
Timers do work that way though don't they?
I don't use timers, so I have no idea. Based on the questions i've answered in the past, timers do not update in the UI
Personally I find timers useless and I just use timestamp sensors.
Alright I'll look into a custom front-end card then
thanks. i am able to make a sensor with the value now 🙂
- trigger:
- platform: event
event_type: deebot_custom_command
sensor:
- name: deebot_auto_empty
state: "{{ trigger.event.data.response.body.data.enable }}"
Try something like {% if now() < state_attr('sensor.my_home_astronomical_dawn', 'today') %} rather than the as_timestamp things.
I already posted a solution
this
Whoops, sorry!
That's much better, I had to do my day job and came back and realised my HA restart was complete so just played with the templates.
That was easy to set up, I just matched the names of the sensors to my install, and replaced some string and it tells me it's dusk!
Wow, super neat. Great example Petro, I love this!
Well, it's good that it works, I didn't try it🤣
Seems to be working great for me!
Interesting! But i'm not sure if this is going to work. See below my automation so far. I have indeed multiple triggers. So, i am looking at your group solution. However, i have my doubts: by defining a group, my assumption is that this will become a fixed list. Is that correct? I'm looking for a dynamic list, that is created every time right before i turn off the lights. So far, i am not getting it to the finish line (although it feels i am getting close :P).
@lethal spoke posted a code wall, it is moved here --> https://hastebin.com/fagimotumi
switch.palceholder is that typo intentional?
And I think you need to define your variables outside of your choose? Because you're defining them inside your trigger to turn lights off.
use the group.set service to change the entities dynamically
Awsome!! i was looking exactly for that functionality, but i was unable to find it in the documentation: https://www.home-assistant.io/integrations/group/
Is it indeed missing , or am i looking in the wrong place? If it's missing, i can submit an improvement
I don't think it's in the docs but you don't ever need docs for services
use developer tools -> services tab to see what you can do in services
services are defined in manifests and they have all the information they need right in the UI
grrr, got a 0 reading after all on this template: state: > {{(expand('group.switches_total_device_energy') |map(attribute='state') |rejectattr('state','in',['unknown','unavailable']) |map('float',0)|sum)|round(2,none)}} where it should have been unavailable to prevent the energy panel from panic... shoudl I also add an availability template here? (believed the rejectattr to take care of that)
Is there such a thing as using the output of a shell command in a template? pseudo-code: state: {{ $(cat /proc/uptime) }}
No. You could use a command line sensor, though
Yes. You’ll probably get zero if that results in no entities
fiddled this just now:``` {% set items = 'group.switches_total_device_energy' %}
{% set x = ['unavailable','unknown'] %}
{{expand(items)|rejectattr('state','in',x)|list|count == expand(items)|count}}
just use this for your availability template:
{{expand('group.switches_total_device_energy')
|rejectattr('state','in',['unknown','unavailable'])|list|length > 0 }}
thanks, I'll look into that.
thanks Rob, even better... cool
I'm looking to create a list to fill the options of an input select. (how) would a sensor be able to have a list?
I removed the unnecessary middle bit
You can use the value_template to generate the list. Either a comma-separated list in the state or a list as an attribute would work.
but wait, thats not true is it? the unfiltered list length should be identical to the list with the filter?
it depends on what you want
if one (of the 42) of the group members is unavailable, it would still result in being >0 making that sensor available
first, you cannot end up with an empty list. that's what I'm preventing
if you want to know if any are unavailable or unknown, then you'd want a different template
{{expand('group.switches_total_device_energy')
|selectattr('state','in',['unknown','unavailable'])|list|length == 0 }}
right, I can try that too yes, thing is I am not sure why the sensor dipped to 0
the zero can only come from your mapped float. Try:
{% set values = expand('group.switches_total_device_energy')|map(attribute='state')|float(none)|reject('eq', none) | list %}
{{ values | sum | round(2) if values else none }}
you also had some useless rejections in there
because of the order of operations
you mapped the generator to state str, then rejected based on the state
that template results in null..... must be a typo. let me check
well if you want to use your template reverse the order and drop the default.
{{(expand('group.switches_total_device_energy')
|rejectattr('state','in',['unknown','unavailable'])
|map(attribute='state')
|map('float')|sum)|round(2,none)}}
"none" may still mess up the graph/stats. probably still want an availability template
reject -> map -> convert -> sum -> round
for reference, this is the full sensor now, with added availability (which I hadn't before):```
- unique_id: switches_total_device_energy
name: Switches total device energy
state: >
{{(expand('group.switches_total_device_energy')
|map(attribute='state')
|rejectattr('state','in',['unknown','unavailable'])
|map('float',0)|sum)|round(2,none)}}
availability: >
{% set items = 'group.switches_total_device_energy' %}
{% set x = ['unavailable','unknown'] %}
{{expand(items)|rejectattr('state','in',x)|list|count == expand(items)|count}}
still wrong
you're mapping before rejecting
if you want to reject like that, change rejectattr to reject and drop 'state'
or reverse the order of the map and rejectattr
see this
|rejectattr('state','in',['unknown','unavailable'])
|map(attribute='state')
|map('float',0)|sum)|round(2,none)}}```
yes, but you can drop the ,0 in float now
sorry, internet delay
because you're already rejecting things that will convert
or you can take advantage of is_number
please...do
{{ expand('group.switches_total_device_energy') | selectattr('state','is_number') | map(attribute='state') | map('float') | sum | round(2,none) }}
TemplateRuntimeError: No test named 'is_number'. ??
are you not at the latest?
I am on dev latest yes 2021.12.0.dev20211123
"test"
haha, thanks!
same difference
really sorry, but got an emergency call now. have to split for a few
then go back to the upper one, but you still have to add robs comment
because sum will return 0 on an empty list
will get back here later on ok? thanks for the inspiration to continue searching for improvements
yeah, i'll see how easy this is. It wasn't possible back in the day. But now it is. Should still be simple
Lol, 1 line of code. You want it?
self.tests["is_number"] = is_number
This is what I have. Its not working as I expect. When I check in developer tools the state is just blank.```
sensor:
- name: ESPHome Devices
platform: command_line
command: echo $(avahi-browse --all --terminate | grep '_esphomelib._tcp'|grep 'wlan0'| cut -f 5 -d ' ')| sed -E 's/ +/, /g'
value_template: "{{ value }}"
btw: I tried the command from terminal of the host machine and it outputs a comma separated list as expected.
There is (imho) a gap in that line of thinking: this only works once you know of the existence of group.set. I do agree fully that the interface is very clear and self-explanatory once you found the option. I think it should be added to the docs, with a short and simple reference to all possible group service calls. I'll make a proposal for that
By the way, thank you very much for your help! It's much appreciated 👍
how did you install HA? What does your sensor and script look like?
the example from the docs for cpu temp works.
I tried a test sensor to just show the date. I'll put it here.
You're more than welcome to make a PR but I can tell you first hand that there's an astronomical number of services that are not documented. If you do the work I'm sure they won't turn it down. Your first line of thinking after you add any integration should be to check out the services it offers via the services tab.
sensor:
- name: ESPHome Devices
platform: command_line
command: "/home/pi/esphome_devices.sh"
value_template: "{{ value }}"
- name: CLI Sensor Test
platform: command_line
command: "date"
value_template: "{{ value }}"
the test sensor works the other one does not.
#!/bin/bash
echo $(avahi-browse --all --terminate | grep '_esphomelib._tcp'|grep 'wlan0'| cut -f 5 -d ' ')| sed -E 's/ +/, /g'
the file is +x btw.
I think that a) there should be a group.turn_on/off, b) group.set should be documented, and c) groups should be configurable in the UI. But I don't care enough to do any of these things
but I do think that all have caused confusion with newcomers
oh I agree
pretty sure groups will never be configurable through the UI
because of areas
all the very old integrations don't have any docs on the services they provide
it wasn't a requirement at that time
So, now here we are 6 years later and no docs for the services
I think groups were also part of configuring the UI, so had a different purpose
they were
they're what built the auto generated UI back in the day
they had other options too, like hidden and crap
how did you install HA?
I created the request: https://github.com/home-assistant/home-assistant.io/issues/20414 The only thing that i don't know: which attributes are optional and which ones not. Does anyone know?
I fully understand why old integrations have no documentation. I hope my proposal will make it a little bit better
thanks. According to this, only the object_id is mandatory for group.set. Am i correct?
looks correct. would be a pretty boring group
supervisor install I think. How should that affect this sensor?
because the command will run in the HA container, and I don't have avahi-browser in mine
i've updated the github issue. Let's hope this will help others
and there's no /home/pi in there, so it's all wrong
oh, I see now.
can I ssh to the host system and run it from there? ssh pi@home-assistant "/home/pi/local_script.sh" The problem I see with that is I would need to add ssh keys to the HA container to be able to ssh to the host.
there are several threads on the forum about how to specify keys
yeah I'm trying now using the ssh addon to add keys and then ssh-copy-id.
It is not advised to install extra packages using apt install (avahi-browse) right?
you can't use apt, since it's alpine
you can use apk add if there's a package, and do it in the addon config to ensure that it's always there. If there's a suitable package
Hey there,
i am quite new to automations and templates.
In my automation i have a template that iterates over all entities in a list called "lights" .
But for sadness it throws an error: 2021-11-23 20:48:33 ERROR (MainThread) [homeassistant.components.automation.nachts_licht_kuche] Error while executing automation automation.nachts_licht_kuche: not a valid value for dictionary value @ data['entity_id']
in the automation channel i got the hint to try it in the developer tools/templates.
Could you guys give me a hint how i could do this?
this is the automation with the template: https://pastebin.com/QZp8ZZQN
i copied this: https://pastebin.com/58F3eycL and think i understand what it is doing* but not how to test it in the template editor.
- search all states for entity_ids that are listed in the variable "lights" and select all that have the state "on"
simply copy the thing into there
copy....paste...observe
you do need to add the definition for the variable:
{% set lights = ['light.kuchenfenster'] %}
thank you - but thats strange. The result is light.kuchenfenster
isn't that what you want?
sure it is but the automation throws the error i mentioned
then review the automation trace and go through the debugging steps in the pinned message in #automations-archived
and that's just the action part. it sounds like the condition isn't working, so check that
Not sure if this is the right channel...let me know if not. What's the appropriate way to create a switch in HA that's not really tied to anything except it's own state? I need to be able to "flip the switch" from a card and check it elsewhere to see if it's on or off...that's it.
so until is_number is there Ill use availability: > {% set items = 'group.switches_total_device_energy' %} {% set x = ['unavailable','unknown'] %} {{expand(items)|rejectattr('state','in',x)|list|count == expand(items)|count and expand(items)|count > 0}} for the availablity
and state: > {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='state') |map('float')|sum)|round(2,none)}} for state. Think I have all your directions in there then
and expand(items)|count > 0}}
your group has items?
all that expand()ing is expensive
as I mentioned earlier, this:
{expand(items)|rejectattr('state','in',x)|list|count == expand(items)|count
is just a long-winded and expensive way to say this:
expand(items)|selectattr('state', 'in', 'x)|list|count == 0
humanely speaking meaning: available if none of the group entities is unavailable?
if none of the items has a state in that list
for the sake of science.... If I were to set the expand(items) as a var and call that: {% set items = 'group.switches_total_device_energy' %} {% set x = ['unavailable','unknown'] %} {% set switches = expand(items) %} {{switches|rejectattr('state','in',x)|list|count == switches|count and switches|count > 0}}
would that make any difference on the expensive side of things? only calling it once, instead of thrice?
you're really attached to that
no no, just asking (already edited in your suggestion)
should be better, but overall uses a bunch of memory proportional to the number of entities in the group
right, guess you're right because it still would have to reject on that var.. for reference, note the typo around 'x' in the template:``` {% set x = ['unavailable','unknown'] %}
{{expand(items)|selectattr('state','in',x)|list|count == 0}}
o dear, this has immediate effect, trickling down in the system.... have 1 or 2 notoriously difficult lights, that show unavailable. The state isnt bothered by that, it will simply only count the available energy measurements. The availabiltiy template marks False though.... might have to resort to {{expand(items)|rejectattr('state','in',x)|list|count > 0}} for that reason, though not sure if that is strict enough... I guess for now must do.
Template for a MQTT Binary_Sensor with payload value of a number
so a type: count history_stats sensor with a duration: 72:00, looking at sensor.rainfallcm24h?
what state: do i use?
the history_stats page looks mostly at if lights have been on, or you've been watching tv - so binary things
I think you want statistics
yeah i thought so
