#templates-archived

1 messages · Page 140 of 1

mighty ledge
#

backtic is unshifted tilda key

regal temple
#

'echo {{ states("input_number.screen_brightness") }} > /config/rpi_brightness/bright'

mighty ledge
#

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

regal temple
#

I try to write the value to a file

mighty ledge
#

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

regal temple
#

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'

mighty ledge
#

then it should work

regal temple
#

It doesn't... 😫

mighty ledge
#

check your log for errors

#

and fix the errors

regal temple
#

Empty, no errors...

mighty ledge
#

and does the command work from CLI?

#

without a template?

regal temple
#

Yes, it does, and I also can write a specific value to the file

mighty ledge
#

Then it should be working

#

otherwise you'd get errors

regal temple
#

Like this: 'echo 10 > /config/screen/brightness'

#

The above works fine

mighty ledge
regal temple
#

Thanks for you patience @mighty ledge !!!

mighty ledge
#

np

weary pumice
#

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 }}'
nimble copper
#

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?

marble jackal
open coral
#

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?
rare panther
rare panther
weary pumice
open coral
bright plaza
#

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?

pine spoke
#

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?

coarse tiger
#

what main device list?

pine spoke
#

Configuration -> Devices

#

I'd rather avoid having a bunch of useless things in there

coarse tiger
#

it should not populate anything there

#

devices should only pop up as entities

pine spoke
#

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

coarse tiger
#

that… is just nonsense

pine spoke
#

Why? I don't see any need for having useless entities.

coarse tiger
#

it does not matter how long your list of entities gets

pine spoke
#

I know it doesn't, but I'd rather keep useless things out of it. Why is that such a surprise?

coarse tiger
#

its not useless if you NEED IT

pine spoke
#

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 😂

coarse tiger
#

you are free to do so

pine spoke
#

👍 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 🙂

coarse tiger
#

i have a simple php script which outputs a json of active devices

#

then use a rest sensor to feed them into ha

pine spoke
#

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.

coarse tiger
#

opnsense 👍

barren jungle
#

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)

ornate onyx
#

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...

dreamy sinew
#

{{ "foo" in "foobar" }}

ornate onyx
mighty ledge
#

@pastel moon today_at is a filter, not a property of now()

pastel moon
mighty ledge
#
today_at('00:00')
#

or

#
'00:00" | today_at
pastel moon
#

Ah. I got stuck in trying to format the output from now() to look the same.

#

I will remove that and try again, thanks 🙂

mighty ledge
#

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

pastel moon
mighty ledge
#

it does not matter, however == comparisons will never work with microseconds

regal temple
# mighty ledge np

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!

ornate onyx
#

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

mighty ledge
ornate onyx
mighty ledge
#

Then your switch should work, however your state will updated based on the polling frequency

ornate onyx
mighty ledge
#

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

ornate onyx
#

I can totally live with that 😄 I have about 50 "OK1" being sent from the projector.. still nothing 😦

mighty ledge
#

no, that's not how it works

ornate onyx
#

the good thing with this "shared session" in the projector is that I can see each request / response...

mighty ledge
#

home assistant asks for the state every 30 seconds

#

ah ok

#

try stripping the whitespace

ornate onyx
mighty ledge
#

'{{ value.strip() == "OK1" }}'

ornate onyx
#

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?

mighty ledge
#

that platform does not support quick reloading

#

if that template doesn't work, then try this one

#
"{{ '1' in value }}"
ornate onyx
#

will try! But now the poling actually stoped .. will restart the host to be safe..

ornate onyx
#

"1" seems quite weak 🙂

mighty ledge
#

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

ornate onyx
#

but at least its getting "something" back... and with a 1 in the response

mighty ledge
#

yep, so, i'd just use that

#

simple and it will work

ornate onyx
#

.. I will dry-run it for some time to see what happens!

#

but THANKS!

mighty ledge
#

np

ornate onyx
# mighty ledge 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 }}" 😄

snow laurel
#

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!

fossil venture
#

{{state_attr('binary_sensor.edgeos_interface_eth0', 'MBytes/ps (Sent)') | round(2, default = 0) }}

snow laurel
#

Ah yes

#

Thanks!

winged dirge
#

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?

inner mesa
#

Should be. You can test in devtools ->Templates

snow laurel
#

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 %}
inner mesa
#

You didn’t surround it with {{}}

snow laurel
#

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

dense sleet
#

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 🙂

charred dagger
#

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

silent barnBOT
#

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.

silent barnBOT
hazy trench
#

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
...

marble jackal
#

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 %}
mighty ledge
#

what @marble jackal said

floral shuttle
#

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 ..

hazy trench
mighty ledge
floral shuttle
#

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

nimble copper
#

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' }}

floral shuttle
#

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?

marble jackal
#

Which part would you like to have?

floral shuttle
#

living_ceiling_4

marble jackal
#

Is alwayls like domain.a_b_c_d_e where you want a_b_c?

floral shuttle
#

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.

nimble copper
#

@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"

floral shuttle
#

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 _

floral shuttle
#

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 😉

mighty ledge
floral shuttle
#

thanks, but.... TemplateRuntimeError: No test named 'device_id'.

#

maybe we cant use the device_id () templates like this?

mighty ledge
#

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

floral shuttle
#

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'.

mighty ledge
#

then use device_entities

#

and check to see if those entities are in your hue group

floral shuttle
#

list those, so I can use them in an automation and set that to input_select.set_option

mighty ledge
#

it's probably just a list of entity_id's so you'd need to expand it

#

just checked, it is

floral shuttle
#

Thats is! Bingo! {{expand(device_entities('e6f4e9redacted dbe8601')) |selectattr('attributes.is_hue_group','eq',true) |map(attribute='name')|list}}

mighty ledge
#

yes

#

something like taht

floral shuttle
#

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.

regal temple
#

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`?
inner mesa
#

Like {{ states(‘input_number.brightness’)}}?

regal temple
#

That is how I get to know the value of input_number.brightness right? But what would the script look like?

slow hound
#

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

mighty ledge
pastel crescent
#

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?

inner mesa
#

How does it ‘return’ that?

#

Might be better to use MQTT

mighty ledge
#

2nd for MQTT, you won't have a polling rate. It'll just update when it updates

dry matrix
#

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.

buoyant pine
#

Third for MQTT because it's da best

silent barnBOT
smoky pagoda
#

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) }}
silent seal
#

Shouldn't you have state: before the template code? And the template code needs to be quoted.

smoky pagoda
#

i think thats what I was getting wrong, going to try it now...thank you

buoyant pine
#

for legacy template sensors it's value_template:

marble jackal
#

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?
inner mesa
#

{{ info.keys()|list }}

marble jackal
#

Knew it would be simple 😅 Thanks!

slow hound
#

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.

mighty ledge
#

They have built in effects that can do that at the hardware level.

analog coral
#

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 }}
inner mesa
#

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)

analog coral
#

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.

inner mesa
#

ok. regardless, you need to use the right template syntax

analog coral
#

I understand that, what would be the equivalent JavaScript expression?

inner mesa
#

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

analog coral
#

Ok. Thank you for your help!

winter sleet
#

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?

inner mesa
#

use an availability template

winter sleet
#

can you point me to an example? I'm having trouble finding one (my google fu is weak today)

inner mesa
#

yes

#

it depends on which template sensor format you're using, but both support it

winter sleet
#

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?

inner mesa
#

this is simpler:

#
        availability_template: "{{ not is_state('sensor.average_temperature','unknown') }}"
winter sleet
#

ah

inner mesa
#

you don't need the default anymore, unless you need to catch other stuff

#

in which case, you should adjust your availabiilty_template

winter sleet
#

good point

#

though the warning messages iiuc make it sound like default will become mandatory soon?

inner mesa
#

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

winter sleet
#

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) }}
silent barnBOT
#

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).

inner mesa
#

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

winter sleet
#

as in the old vs new format?

inner mesa
#

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..

winter sleet
#

sorry, will paste now

#

one sec

inner mesa
#

you can just fix it

#

no need to paste

winter sleet
#

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?
inner mesa
#

there's a section for the legacy format at the bottom of the page, and the whole top part is the new one

winter sleet
#

i see that - ok i have them side by side. examining it now

winter sleet
#

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?

inner mesa
#

I wouldn't have expected it to evaluate the state template if the availability template evaluates to false

winter sleet
#

i almost feel like i have to put the defaults in just to quiet those warnings

inner mesa
#

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

winter sleet
#

hmm

inner mesa
#

perhaps you didn't reload template entities or restart HA

winter sleet
#

i am restarting HA each time

#

which version of HA are you using?

inner mesa
#

2021.11.3

winter sleet
#

same here

inner mesa
#

then I do not know

winter sleet
#

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

formal ember
#

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]}}
dreamy sinew
#

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?

floral shuttle
#

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 ..

stable fable
#
                                |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>)>```
marble jackal
#

| map(attribute='friendly_name')

mighty ledge
#

If you're not using it in a for loop, use | list.

spare sleet
#

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') }}"```
mighty ledge
spare sleet
#

thanks I'll try and get that

silent seal
#

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? 😄

stable fable
silent seal
topaz silo
#

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 %}
inner mesa
#

I don't think "modes" is a single value - it's a list of possible modes

#

check in devtools -> States

#

mine: hvac_modes: heat_cool, heat, cool, off

topaz silo
#

ahh yes it is a list

inner mesa
#

the current mode is the state of the entity. There's also an hvac_action attribute, which is what it's doing right now

topaz silo
#

i have no idea then.

inner mesa
#

about what?

topaz silo
#

hvac_action was removed from this LG integration

#

because it didnt properly show the current action

#

the developer removed it

inner mesa
#

ok

topaz silo
#

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

inner mesa
topaz silo
#

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

covert zealot
#

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
winter sleet
inner mesa
#

@covert zealot

action:
  - service: >-
      {% set currentState = states ('climate.upstairs_hall')[-1] + state_attr('climate.upstairs_hall', 'hvac_action')[-1] %}
      script.99bedroomaction_{{ currentState }}
covert zealot
inner mesa
#

then do it in the YAML editor

covert zealot
covert zealot
covert zealot
inner mesa
#

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

covert zealot
spare sleet
#
      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?
inner mesa
#

what logic are you trying to accomplish with that?

spare sleet
#

just trying to stop it from triggering from, and to, those states listed

inner mesa
#

ok, that's not correct then

#

it's starting with whether trigger.from_state.state is true or false

spare sleet
#

I see. Should it be or, instead of and?

inner mesa
#

no, you need a different construct

#

I think something like this would work, but would need to test it:

spare sleet
#
      value_template: "{{ trigger.to_state.state not in ('unavailable', 'unknown', 'none') }}"
    - condition: template
      value_template: "{{ trigger.from_state.state not in ('unavailable', 'unknown', 'none') }}"```
inner mesa
#

{{ [trigger.from_state.state, trigger.to_state.state]|select('in', 'unavailable,unknown,none')|list|length == 0 }}

spare sleet
#

This is what I currently have, I'm just messing around trying to learn a bit, and condense it

inner mesa
#

you want "not xxx in yyy" if you do it that way

#

I'm trying to be fancy

spare sleet
#

just to learn, what is the list and length part about

inner mesa
#

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

spare sleet
#

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

inner mesa
#

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

spare sleet
#

yep just tossed it in there, works like a charm

#

You the man, thanks

true otter
#

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

inner mesa
#

Profit!

true otter
#

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?

fossil venture
#

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')

marble jackal
#

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

mighty ledge
#

I just gave you additional suggestions.

mighty ledge
# true otter I am trying to create a template for my Gen-2 ZCOMBO 2 in 1 smoke detectors so I...

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.

marble jackal
#

numbers are also shown in a different color in devtools -> States

mortal jetty
#

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

inner mesa
#

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 }}

mortal jetty
#

Oh ok, Test

inner mesa
#

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

mortal jetty
#

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

inner mesa
#

it is. attributes.forecast[0].precipitation_probability' is not the name of an attribute

#

the attribute is "forecast"

mortal jetty
#

So how do I get the precipitation_probability?

inner mesa
#

I gave you the answer up there

mortal jetty
#

Oooh sorry I missed that

inner mesa
#

sigh

mortal jetty
#

the code you pasted works. Thanks!

inner mesa
#

take a moment to understand it

#

it will help you later on

mortal jetty
#

I am looking at it but still don't understand it fully

final abyss
#
  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?

inner mesa
inner mesa
final abyss
#

I want to count booleans 😄

inner mesa
#

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

final abyss
#
  value_template: >
    {{ states.device_tracker
        | selectattr('state', 'eq', 'home')
        | selectattr('attributes.is_guest', 'eq', false)
        | list | count }}

That works!

inner mesa
#

attributes can retain their native types

final abyss
#

Thanks Rob! Learnt something new today 🙂

inner mesa
#

same thing often happens with numbers in attributes, so watch out for that, too

#

"1" and 1 are different

mortal jetty
inner mesa
#

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'] }}

mortal jetty
#

I thought the [] was for lists

inner mesa
#

it's for indexing in general. with a list, it takes an index. with a dict, it takes a key name

mortal jetty
#

but the precip_prob is a attribute?

inner mesa
#

like all object-oriented languages, types can define what various operators mean for them

#

no, it's a key

mortal jetty
#

Ok I'm kind of following. It's a dict:key lookup when you call precip_prob?

inner mesa
#

you look up the key in the dict by its name, which is precipitation_probability

mortal jetty
#

Ohh ok that makes sense. Yeah this is definitely going to help my automations. Thanks again

inner mesa
#

anyway, you get the idea

blazing burrow
#

is there anywhere besides the template tester in dev tools that's suitable for testing Jinja? like, a plugin for vscode maybe?

blazing burrow
#

oh... I guess there wouldn't be with ha entities, huh 🤔

floral shuttle
#

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)}}'

floral shuttle
#

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?

mighty ledge
mighty ledge
mighty ledge
# inner mesa

What are you using to make that graphic? Looks like snagit but I don't recognize those arrows. Also, is it freeware?

floral shuttle
#

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 %}

floral shuttle
mighty ledge
#

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.

floral shuttle
#

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}}

floral shuttle
mighty ledge
floral shuttle
#

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 %}
mighty ledge
#

expand(light_group) | first | default(none), then check for none

floral shuttle
#

wait, this is mixed up now. my reply above was for the json issue, not the light_group template

inner mesa
mighty ledge
#

ugh

#

that means it's not free on windows

blazing burrow
#

windows has the snip tool

#

win shift s

mighty ledge
#

the snip tool is shit

blazing burrow
#

lolol fair enough

#

to what level do I need to be in order to share images? lol

mighty ledge
#

no rolling log, no markdown with arrows or text, no editing]

blazing burrow
#

can't even send a gif 😅

mighty ledge
#

you can only share images via imgur or the like

blazing burrow
mighty ledge
#

we mods

blazing burrow
#

aha!

blazing burrow
#

mod me lol

#

jk I get it

#

that's more responsibility than I feel like having anyways 😅

mighty ledge
blazing burrow
mighty ledge
#

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

blazing burrow
#

isn't that the only "ui-oriented" channel? lol

mighty ledge
#

homeassitant_os, off-topic

blazing burrow
#

fair enough

mighty ledge
#

maybe anroid and ios_and_mac too

blazing burrow
#

not that I "need" to send images, just curious

floral shuttle
#

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

copper delta
#

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]" }}'
inner mesa
#

That doesn’t look like a JSON data structure, but an expression to reference an item within one

copper delta
#

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.

mighty ledge
floral shuttle
#

We’re talking about the same here? The rest sensor with the json value_template ? There’s nothing to expand…

copper delta
mighty ledge
floral shuttle
#

?? I was yes, responding to you ?

ripe torrent
#

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

snow laurel
#

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)

inner mesa
#

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

snow laurel
#

You mean unsupported?

#

So my next best option is just a custom sensor then huh

inner mesa
#

yeah, sorry, multitasking and omitted the critical word 🙂

#

Marius is leading the maintenance fight, as far as I can tell

marble needle
ripe torrent
marble needle
#

wrap it in a conditional like this i guess:

{% if state_attr('media_player.dining_room', 'sonos_group') %}
   <YOUR_TEMPLATE>
{% else %}
   False
{% endif %}
inner mesa
#

they'll need an "else" in there or it'll be unhappy

#

but better is to use an availability template field

marble needle
#

edited

marble needle
inner mesa
#

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

ripe torrent
inner mesa
#

the template sensor docs

ripe torrent
#

I'm blind, thank you!

inner mesa
#

if it returns false, the state will be "unavailable" and the state: field won't be evaluated

ripe torrent
#

“`

  • 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
      ` “
#

Simple as this?

inner mesa
#

That’s not a template

#

And it’s not formatted properly. And it’s just true?

#

Check the docs again 🙂

ripe torrent
#

Idiot with Discord, not knowing how to use code blocks

inner mesa
#

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

ripe torrent
#

Thank you

silent barnBOT
thorny snow
#

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.

buoyant pine
#

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

thorny snow
#

Thanks. I see this in the logs: Setup of sensor platform rest is taking over 10 seconds.

inner mesa
#

It’s drunk

buoyant pine
#

is it working now though?

#

if not...

#

.share the JSON from the endpoint

silent barnBOT
silent barnBOT
buoyant pine
#

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?

thorny snow
#

how can I see? ping from the Terminal tab seems to have trouble

atomic blade
#

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...

fossil venture
#

See how the document says "string" | (or) "list" but no "template" next to the option?

atomic blade
#

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

fossil venture
#

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.

atomic blade
#

So what do I want? haha

fossil venture
#

A script.

#

If you want a button on the frontend.

atomic blade
#

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

fossil venture
#

Then you cant use a light group.

atomic blade
#

Ok what would I use?

fossil venture
#

A script.

atomic blade
#

Right but that doesn't seem to do what I want, does it? Isn't a script something that just runs one off?

fossil venture
#

It runs whenever you call it, like from the tap action of a Lovelace button.

#

Take a step back and explain your actual issue.

inner mesa
#

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

atomic blade
# fossil venture Take a step back and explain your actual issue.

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

fossil venture
#

See Rob's idea above about using scripts and template lights.

atomic blade
#

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

inner mesa
#

That’s where the code I gave you yesterday comes in

atomic blade
#

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?

inner mesa
#

You can just use a group

#

Doesn’t need to be a light.group

atomic blade
#

Yeah that's fine, was just hoping to keep it as a light group if possible

inner mesa
#

Does it matter?

#

You have your template light

atomic blade
#

Learning experience I guess. I'd rather not change my setup just due to lack of knowledge

inner mesa
#

Who cares what it controls?

#

Could just be a list of lights

atomic blade
#

How would you get all entities associated with a light group though?

#

I think I got it working though 🙂 Really appreciate the help

inner mesa
#

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

atomic blade
#

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

inner mesa
#

That’s what I provided above

#

You saw my message?

atomic blade
#

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

inner mesa
#

It does what you want?

atomic blade
#

I thought that had a little more going on since you were doing the filtering

inner mesa
#

It does what I said above

#

Anyway, you’re welcome to proceed as you wish. Hopefully you have enough info now

atomic blade
#

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

atomic blade
#

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

atomic blade
#

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?

fervent hemlock
#

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?

marble jackal
#

@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

fervent hemlock
#

@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}}'

mighty ledge
#

or

#
{{ (state_attr("sensor.dje44g_auxheat_status", "auxheattime2") | today_at - today_at()).seconds * 60 }}
mighty ledge
#

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

atomic blade
#

@mighty ledge ^ That's how I ended up handling the issue where it was empty. Is your way better?

mighty ledge
#

🤷‍♂️ it depends on what you understand

#

brightness | int(0) would also do the job

marble jackal
sweet atlas
#

Oh, I just realised I posted this in the wrong chat, sorry!

topaz silo
#

hi, i need help on making a template sensor from zha_events so i can use them in some automations

topaz silo
#

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

fossil venture
#

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?

sonic nimbus
#

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?

topaz silo
#

it never seems to stop repeating

inner mesa
#

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’

topaz silo
#

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

inner mesa
#

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

topaz silo
#

it only sends the single event on the HOLD

#

and nothing again until STOP

#

actually..

#

maybe it is sending multiple events while holding..

inner mesa
#

That’s consistent with what I suggested. But if you have something else to use…

topaz silo
#

i think i stuff something up

#

because once i try this, the entity seems to get stuck

#

as if the automation is still running

swift glade
#

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.

silent seal
#

You should use state_attr

swift glade
silent seal
#

Did you try the template tool in home assistant to get see what the attributes are? Attributes are usually lowercase in my experience.

swift glade
#

Wow that's a great tool!

pastel moon
#

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

fossil venture
#

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.

pastel moon
#

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

bright plaza
#

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 %}"

pastel moon
#

Rats... Turns out it is infact not the testfile throwing the log. Have some digging to do. Thanks @fossil venture

bright plaza
#

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

glass flint
#

where is isocalendar documented? like now().isocalendar()[1]

dreamy sinew
#

that's a function of the python datetime.datetime object

trail estuary
#

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?

marble jackal
#

See the pinned message about the default values

inland fossil
#

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.

inner mesa
#

Maybe + timedelta(seconds=0.5)?

#

Then chop off the seconds

inland fossil
# inner mesa Then chop off the seconds

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?

inner mesa
#

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

inland fossil
#

Yeah, that's what got me hung up, the round() not working.

inner mesa
#

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

inland fossil
#

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.

inner mesa
#

I was making up a time

inland fossil
#

Oh, I see what you were doing. Okay.

inner mesa
#

and you asked for rounding

#

not just truncation

inland fossil
#

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) }}```
inner mesa
#

yeah, that's worse

inland fossil
#

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.

inland fossil
glossy viper
#

almost finished aligning templates, but one

#

instead of ...| int }} should work with ...| int(default,0) }} ?

inner mesa
#

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

glossy viper
#

well...honestly....i want that tempalte to ork when upgrading to 2022.1 🙂 🙂

inner mesa
#

there's nothing there that won't work

glossy viper
#

the log says...template will fail to render after 2022.1

inner mesa
#

sigh

#

it does not

glossy viper
#

so i want to have a clean log from my ha 🙂

inner mesa
#

what's the error, specifically?

glossy viper
inner mesa
#

what's the state of states('input_number.motion_status_mqtt_ago')?

glossy viper
#

0

#

oh..is unknown

inner mesa
#

it's usually better to fix things that are broken than to rely on a default

#

which is why they're making this change

glossy viper
#

no problem with changes...that's why i try to stay on same line with latest version

inner mesa
#

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...

glossy viper
#

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

trail estuary
#

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

inner mesa
#

There’s no float in what you posted

trail estuary
inner mesa
#

One of your sensors doesn’t have a number as its state

#

Line 6 is your problem

trail estuary
#

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?

inner mesa
#

Sigh

#

One of those sensors has a state of ‘unavailable’.

#

And yet

trail estuary
#

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...

inner mesa
#

If you just want it to evaluate to zero in that case, just use float(0.0)

trail estuary
inner mesa
#

That behavior is changing. That’s what the warning is telling you

trail estuary
#

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!

proud cradle
#

Is there a way to loop over all entities with a name matching a pattern, like "light.office_"?

inner mesa
#

Yep, a few

proud cradle
#

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?

inner mesa
#

You don’t want to loop - you just want to generate a list of entities that you pass to light.turn_on

#

right?

proud cradle
#

Correct

#
  1. Generate a list
  2. Switch each light on and set brightness_pct = current brightness_pct * 1.5
inner mesa
#

{{ 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

proud cradle
#

Best case would be having this as a script with two in parameters, entity pattern and brightness factor

proud cradle
#

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") |

inner mesa
#

It takes a regular expression

#

And the jinja docs that it points to

proud cradle
#

Thank you

rare panther
#

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'}}"

rare panther
#

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   
inner mesa
#

See the big yellow warning box at your link

rare panther
#

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'}}"
inner mesa
#

What do you mean by ‘doesn’t work’?

steel marsh
#

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"}

rare panther
# inner mesa What do you mean by ‘doesn’t work’?

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'}}"
mighty ledge
#
      - condition: template
        value_template: "{{ service_mode in state_attr('sensor.mycarentity','service_check'}}" 
rare panther
mighty ledge
#

you should be in the script section, not automation

#

you wasted your own time

rare panther
#

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

mighty ledge
#

instead of arguing like you don't want to do

ancient swan
#

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.

inner mesa
#

You make a template sensor to expose they attribute, then use that new entity with the card

ancient swan
ancient swan
#

Thanks!

austere lark
#

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

lethal spoke
#

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)?
ancient swan
#

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?

dreamy sinew
#

remove sensor from your sensors.yaml

ancient swan
#

ahhhhh. thanks!

fallow gulch
#

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?

grim flicker
#

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.

silent barnBOT
median mason
#

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.

opaque pumice
silent barnBOT
vagrant monolith
silent seal
#

How do you define "closest"?

vagrant monolith
#

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?

silent seal
#

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

vagrant monolith
#

So I will need to do now < sun_state_time for all?

silent seal
#

That's certainly what I'd do.

#

Play with it in the template editor in the developer tools.

vagrant monolith
#

The problem is that it returns evening while it should return midday

#

Or should I not have timestamps?

silent seal
#

It might be easier to use {{ states('sun.sun') }} or the state_attr option for this to be honest

vagrant monolith
#

I know, but I want this sensor 😛

silent seal
#

Which sensor is it?

vagrant monolith
#

It's a custom component called sun2

vagrant monolith
#

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

vagrant monolith
#

But like I want that sensor

mighty ledge
mighty ledge
mighty ledge
mighty ledge
mighty ledge
austere lark
mighty ledge
mighty ledge
austere lark
#

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

mighty ledge
#

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

austere lark
#

But I want it to always show hh:mm:ss remaining

mighty ledge
#

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

austere lark
#

I'll try with a custom front-end component I guess

austere lark
mighty ledge
#

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.

austere lark
#

Alright I'll look into a custom front-end card then

median mason
silent seal
silent seal
#

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.

mighty ledge
#

yah, templates are fun if that's your thing

#

they are my favorite

silent seal
#

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!

mighty ledge
silent seal
lethal spoke
# mighty ledge Put that template into a variable. Variables can be accessed at any time throug...

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).

silent barnBOT
silent seal
#

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.

mighty ledge
lethal spoke
#

Is it indeed missing , or am i looking in the wrong place? If it's missing, i can submit an improvement

mighty ledge
#

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

floral shuttle
#

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)

slow vine
#

Is there such a thing as using the output of a shell command in a template? pseudo-code: state: {{ $(cat /proc/uptime) }}

inner mesa
#

No. You could use a command line sensor, though

inner mesa
floral shuttle
#

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}}

inner mesa
#

just use this for your availability template:

#
          {{expand('group.switches_total_device_energy')
             |rejectattr('state','in',['unknown','unavailable'])|list|length > 0 }}
slow vine
floral shuttle
#

thanks Rob, even better... cool

slow vine
inner mesa
inner mesa
floral shuttle
#

but wait, thats not true is it? the unfiltered list length should be identical to the list with the filter?

inner mesa
#

it depends on what you want

floral shuttle
#

if one (of the 42) of the group members is unavailable, it would still result in being >0 making that sensor available

inner mesa
#

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 }}
floral shuttle
#

right, I can try that too yes, thing is I am not sure why the sensor dipped to 0

mighty ledge
#

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

floral shuttle
#

that template results in null..... must be a typo. let me check

mighty ledge
#

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)}}
inner mesa
#

"none" may still mess up the graph/stats. probably still want an availability template

mighty ledge
#

reject -> map -> convert -> sum -> round

floral shuttle
#

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}}

mighty ledge
#

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

floral shuttle
#
             |rejectattr('state','in',['unknown','unavailable'])
             |map(attribute='state')
             |map('float',0)|sum)|round(2,none)}}```
mighty ledge
#

yes, but you can drop the ,0 in float now

floral shuttle
#

sorry, internet delay

mighty ledge
#

because you're already rejecting things that will convert

#

or you can take advantage of is_number

floral shuttle
#

please...do

mighty ledge
#
{{ expand('group.switches_total_device_energy') | selectattr('state','is_number') | map(attribute='state') | map('float') | sum | round(2,none) }}
floral shuttle
#

TemplateRuntimeError: No test named 'is_number'. ??

mighty ledge
#

are you not at the latest?

floral shuttle
#

I am on dev latest yes 2021.12.0.dev20211123

mighty ledge
#

bah, these asses didn't put is_number as a filter

#

I'll make a PR

inner mesa
#

"test"

floral shuttle
#

haha, thanks!

mighty ledge
#

same difference

floral shuttle
#

really sorry, but got an emergency call now. have to split for a few

mighty ledge
#

then go back to the upper one, but you still have to add robs comment

#

because sum will return 0 on an empty list

floral shuttle
#

will get back here later on ok? thanks for the inspiration to continue searching for improvements

mighty ledge
# inner mesa "test"

yeah, i'll see how easy this is. It wasn't possible back in the day. But now it is. Should still be simple

mighty ledge
slow vine
#

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.
inner mesa
#

I don't think it likes pipes

#

turn it in to a script and call that

slow vine
#

Oh. I see.

#

now I get unknown is the value template wrong?

lethal spoke
#

By the way, thank you very much for your help! It's much appreciated 👍

inner mesa
slow vine
#

the example from the docs for cpu temp works.
I tried a test sensor to just show the date. I'll put it here.

mighty ledge
slow vine
#
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.

inner mesa
#

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

mighty ledge
#

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

inner mesa
#

I think groups were also part of configuring the UI, so had a different purpose

mighty ledge
#

they were

#

they're what built the auto generated UI back in the day

#

they had other options too, like hidden and crap

lethal spoke
#

I fully understand why old integrations have no documentation. I hope my proposal will make it a little bit better

inner mesa
#

Create/Update a user group.

#

"user group"?

lethal spoke
inner mesa
#

looks correct. would be a pretty boring group

slow vine
inner mesa
#

because the command will run in the HA container, and I don't have avahi-browser in mine

lethal spoke
inner mesa
#

and there's no /home/pi in there, so it's all wrong

slow vine
#

oh, I see now.

slow vine
#

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.

inner mesa
#

there are several threads on the forum about how to specify keys

slow vine
#

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?

inner mesa
#

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

thorny snow
#

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?

inner mesa
#

just copy the whole thing into devtools -> Templates

#

and try to understand what it's doing

thorny snow
#

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"
inner mesa
#

simply copy the thing into there

#

copy....paste...observe

#

you do need to add the definition for the variable:

#

{% set lights = ['light.kuchenfenster'] %}

thorny snow
#

thank you - but thats strange. The result is light.kuchenfenster

inner mesa
#

isn't that what you want?

thorny snow
#

sure it is but the automation throws the error i mentioned

inner mesa
#

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

knotty lodge
#

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.

floral shuttle
# mighty ledge because sum will return 0 on an empty list

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

inner mesa
#
        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

floral shuttle
#

humanely speaking meaning: available if none of the group entities is unavailable?

inner mesa
#

if none of the items has a state in that list

floral shuttle
#

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?

inner mesa
#

you're really attached to that

floral shuttle
#

no no, just asking (already edited in your suggestion)

inner mesa
#

should be better, but overall uses a bunch of memory proportional to the number of entities in the group

floral shuttle
#

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}}

floral shuttle
#

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.

candid escarp
#

Template for a MQTT Binary_Sensor with payload value of a number

fallow gulch
#

what state: do i use?

fallow gulch
#

the history_stats page looks mostly at if lights have been on, or you've been watching tv - so binary things

inner mesa
#

I think you want statistics

fallow gulch
#

yeah i thought so