#templates-archived

1 messages · Page 156 of 1

marble jackal
#

note that I don't know the contents on beforehand, It could even b that a is not included

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.

buoyant pine
#

Just in case 😄

marble jackal
#

Hehe, the problem is complicated.
I have a script where people to resume Google Home Speakers after they have been interrupted
They can provide any service call in it which will be performed, and after that the previous stream (spotiy, tunin will be resumed)
For one specific case I replace the target with another one. That works fine, but it could be that the actual target has been provided under data.
So for that specific case I want to remove entity_id, area_id and/or device_id from data

#

Well, not so complicated in the end

#

I could possibly do something like:

{% set ns = namespace(s={}) %}
{% for item in service_call.get('data', {}).items() | list %}
  {% if not item[0] in [ 'entity_id', 'device_id', 'area_id' ] %}
    {% set add = { item[0]: item[1] } %}
    {% set ns.s = dict(ns.s, **add) %}
  {% endif %}
{% endfor %}
{{ ns.s }}
#

Jep, that works

#

Figured out how to do it with a filter as well:

{% set example = { 'a': 1, 'b': [2, 5], 'c': {'d': 4} } %}
{% set test = example.items() | rejectattr('0', 'eq', 'a') | list %}
{{ dict(test) }}
naive swan
#

Hey everyone, I'm looking for assistance regarding a TTS automation. I currently have a sensor that tracks my sleep time and lists the state as 6:53 for example but when read it says 6 53 hours. Is there a template i could use to get it to read 6 hours 53 minutes instead?

inner mesa
#

without knowing where it's getting the "hours" from, I would do this:

{% set time = states('sensor.whatever').split(':') %}
{{ time[0] ~ " hours " ~ time[1] ~ " minutes" }}
naive swan
#

Thanks very much Rob I appreciate that

#

That's come up with 6 hours 53 hours minutes, is there a way to remove the second hours mention?

inner mesa
#

no idea where it's coming from

naive swan
#

Ah I see the issue. The problem was my original template i used to convert 413 minutes into hours, I removed the hours mention in that so your template only picks up the numerical values and its working now. Thanks again

silent barnBOT
naive swan
#

Ugh i hit 15 lines only due to including the surrounding context 😄

rose scroll
#

What is the current state of your Fitbit sleep hours sensor in Dev Tools > States?

naive swan
#

6:53, the template i used got it close to what i wanted then used robs to separate it into hours and minutes

rose scroll
#

What the error seems to be indicating is that when you split the Fitbit sleep hours state by : , the resulting list doesn't have an element in the 1th position.

#

This could happen if say the state is 'unavailable'

#

Are you getting the error now, when the state is 6:53?

naive swan
#

Last even log showed the warning 13 minutes ago.

#

It looks to be that it's falling into an unknown state for a very brief time every so often

#

There's no drop outs on the original sensor its referencing so I'm unsure what's causing the template to do so

fallow ruin
#

guys
is it possibly to somehow get which light toggled on a group
with a template ?

marble jackal
#

Yes, how would you like to use this information?

#

You can create an automation or trigger based sensor with the group turning on as the trigger. Then use a template to expand the group and determine which entities are on

#

When they are all on, the group itself was turned on, and not a single entity

fallow ruin
#

i use the mushroom card, and i want to know which light in the specific group has turned on the light and show that on a card

marble jackal
#

Okay, so you want to use it in a template card?

#

If you need to know which entity turned the group on, I would suggest to create the trigger based template sensor.
You need to know the information at the time of the state change, not at the current moment, so you need to store it somewhere.
If you need to have it survive a HA reboot or a template reload, store it in an input_text using an automation.
Display the state of the sensor or the input_text in your card

#

Maybe trigger on the group turning on and off

#

The template can then be something like:

{% set group = 'light.your_light_group` %}
{% set member_count = expand(group) | list | count %}
{% set members_on = expand(group) | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') | list %}
{% if trigger.to_state.state == 'off' %}
  Group is off
{% elif members_on | count == members_count %}
  Group itself
{% else %}
  {{ members_on |  join(', ') }}
{% endif %}
#

@fallow ruin disclaimer: typed on mobile without testing

fallow ruin
#

thnx i'm giong to try that

fallow ruin
#
UndefinedError: 'trigger' is undefined

i'm really bad with templating @marble jackal

marble jackal
#

@fallow ruin The template relies on a trigger, it will only work when there is a trigger, and will therefore not work in the template editor.

You can add {% set trigger = { 'to_state': { 'state': 'on' } } %} at the top of the template editor to mimic it

#

@fallow ruin Or change the template to:

{% set group = 'light.your_light_group` %}
{% set member_count = expand(group) | list | count %}
{% set members_on = expand(group) | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') | list %}
{% if is_state(group, 'off') %}
  Group is off
{% elif members_on | count == members_count %}
  Group itself
{% else %}
  {{ members_on |  join(', ') }}
{% endif %}
fallow ruin
#

this works great, your a template king 😉

young shadow
#

I get a Config error for this, however yaml-wise it is correct according to Yamllint. How should I create a templated open_cover: in my Template Cover?

        open_cover: >
          {% if is_state('cover.garage','closed') %}
            - service: mqtt.publish
              data:
                topic: automation/xx
                payload: garage
                retain: false
          {% endif %}```
```Invalid config for [cover.template]: expected dictionary @ data['covers']['garage']['open_cover'][0]. Got '{'. (See ?, line ?).```
willow rapids
#

Are there only 2 states possible? Is it ever unavailable or unknown?

young shadow
marble jackal
#

You can not put yaml in a template like that

#

Use a choose for something like this

#

Ah, should have read all posts

narrow surge
#

How do I check if a condition has ran in the past 5 minutes? My bedroom curtains are opening because my living_room curtains are opening, it detects motion because of this and that will trigger to open the bedroom curtains.

#

value_template: "{{ (as_timestamp(now()) - 60) < as_timestamp(state_attr('automation.open_curtains_living_room_right', 'last_triggered' )) }}?

#

Yep, that works!

marble jackal
#

That will be the last minute though, not 5

narrow surge
#

Yeh, used it to test it 🙂

novel quail
#

What do you actually need to put into a template condition?
It right now gives me this error while testing: template value should be a string for dictionary value @ data['value_template']. Got None
The template is just this one line: {{ as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off"].last_updated) > as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off_2"].last_updated) }}
That line works fine in the Dev Tools template editor.

steady nebula
#

Random question. Can you do an if statement based on who the current user is?

inner mesa
novel quail
#

I can't seem to post screenshots here, but surrounding it in quotes makes no difference.

#

It's just a simple Condition, with Condition type set to Template, and the exact string up there in the Value template field

inner mesa
#

You could describe it, or actually post it

novel quail
inner mesa
#

As text

#

That's why you can't post images

novel quail
#

The text is the one above

inner mesa
#

Oh well

novel quail
#

I don't understand what you're asking from me, sorry

#

{{ as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off"].last_updated) > as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off_2"].last_updated) }} is the text of the template

inner mesa
#

Post the whole damn thing. As text

tepid onyx
#

heh

novel quail
#

What whole damn thing? I'm making this script via the visual editor.

#

If there is a plain text representation of it, I don't know how to get it to show it to me.

#

Ah, seems like when I try to run it once, it shows up in the "Show Trace" section...

#

Seems like the "Test" button is just straight up broken. The script seems to work fine.

tepid onyx
#

as_timestamp(states.light.3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off.last_updated) ?

novel quail
#

Can't do that because of the leading number

tepid onyx
#

use single quotes?

novel quail
#

It makes no difference. I tested that line in the Template-Editor in dev tools. I'm pretty confident it works fine.
The script also runs and behaves like I'd expect, so it seems to be working fine as well.
Just the "Test" button throws an error.

tepid onyx
#

why not rename your entities to something useful

novel quail
#

I wasn't aware you could rename them at that level? I gave them useful names in the UI

#

ah, you sure can... yeah, that sure makes things easier

tepid onyx
#

pretty sure you can

novel quail
#

Yeah, I never noticed that the Entity ID field was editable. I took them as device given

marble jackal
#

Press the 3 dots at the top right in the GUI, switch to YAML view and share the complete condition

novel quail
#

Ahhh, that's good to know. Thanks

#

Just the condition out of it is:

          - condition: template
            value_template: >-
              {{
              as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off"].last_updated)
              <
              as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off_2"].last_updated)
              }}

The whole thing is what I already pasted on bpaste

marble jackal
#

Don't see any issues with it, besides that they are both datetime object which you can perfectly compare with each other without converting them to a timestamp

novel quail
#

ah, that makes it quite a bit nicer

#

yeah, the whole script also works from what I can tell

#

Just the Test button doesn't like it. Or really anything I put in there

#

I think the Button just broken

marble jackal
#

Is that the one which is new in 2022.4

#

What does it show when you press it?

novel quail
#

I made this install literally today, so I couldn't tell :D

#

A popup error box with template value should be a string for dictionary value @ data['value_template']. Got None in it

marble jackal
#

Hmm, maybe a bug in that check button then indeed

novel quail
#

At least this slight mess of a script seems to work. One button blinds control, yay

tough lily
#

how do I get the area an entity is in? Sorry, derp, it's right in the docs

tough lily
#

Ok, so I can pull a list of entities in my kitchen in, and I can get their friendly names and states, but how do I get their domain? ``` {% for foo in area_entities('Kitchen') %}
{{ state_attr(foo, 'friendly_name') ~ ' ' ~ states(foo) }}
{% endfor %}

inner mesa
#

from the entities

#

area_entities() returns complete entity_ids, including their domains

tough lily
#

as just a string though, right?

#

I can parse the string, but thought there might be a cleaner way

inner mesa
#

entitied_ids are strings, yes

#

an entity_id like switch.fr_table_lamp is just a string

#

{{ "switch.fr_table_lamp".split('.')[0] }}

tough lily
#

I'll give that a shot, thanks

#

Basically, I'm trying to make a template that for a given area will output a light icon if any lights in that area are "on", a door icon if any doors are "on" and a lock icon if any locks are "unlocked". Could I just do that with some kind of select?

inner mesa
#

those are three different things to output, but yes, that's much easier

#

{{ states.light|selectattr('state', 'eq', 'on')|list|count > 0 }}

#

or in your case, {{ area_entities('Family Room')|expand|selectattr('domain', 'eq', 'light')|selectattr('state', 'eq', 'on')|list|count > 0 }}

tough lily
#

thanks!

inner mesa
#

that returns true if any lights in that area are on

tough lily
#

selectattr is great.

inner mesa
#

it is

tough lily
#

Why doesn't states.light|selectattr('area_name', 'eq', 'Kitchen')|list return anything? When I use states.light|selectattr('state', 'eq', 'on')|list I get a list that includes:

#

It shows as area_name as an attribute, but looks like I can't select for it

#

Got it! states.light|selectattr('attributes.area_name', 'eq', 'Kitchen')|list

pastel moon
#

Hi guys! I am using this in my scripts to define a few variables; all_lights: "{{ area_entities('Bathroom') | expand | selectattr('domain', 'eq', 'light') | map(attribute='entity_id') | list }}" lights_on: "{{ area_entities('Bathroom') | expand | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}" number_of_lights_on: "{{ lights_on | length }}"

#

they check out fine in dev_tools, but I get this error in the gui when the scripts are called;Invalid config for [script]: invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['variables']['all_lights']. Got None invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['variables']['lights_on']. Got None. (See /config/configuration.yaml, line 15). Invalid config for [script]: invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['variables']['lights_on']. Got None. (See /config/configuration.yaml, line 15).

#

I can't seem to find the issue. It complains on the 'expand' filter/command which is needed... What can I do?

pastel moon
#

No idea at all?

pastel moon
#

If what I have written above is not correct, can these values be retrieved in a better way, so that it don't generate an error when actually run?

marble jackal
#

expand can not be used as a filter

pastel moon
#

Ah... Explains the error. Was confused because 'ha core check' found no issue, nor the 'check config', but will try this, thanks! 🙂

marble jackal
#

That check can't check templates

#

Use devtools > templates for that

pastel moon
marble jackal
#

Btw, you can use your all_lights variable in all_lights_on

marble jackal
#

It does accept it in the template checker

pastel moon
#

Yes, but all in all, there's a lot that works really nicely these days, so I wouldn't complain... 🙂

marble jackal
#

I will have a further look and might create an issue if I get the same result

pastel moon
#

Great! Thanks for the help!

open coral
#

hi everyone! I have a little D1 mini with an ultrasonic sensor attached to measure the salt in my water softener. I am using update_interval: 3600s on the D1 but im wondering if there is a way for me to get the D1 to report every an average of say 10 consecutive measurements (maybe every 1s) to eliminate any errors?
not sure if this is a problem for a template?

silent barnBOT
floral shuttle
#

replacing my python script which does components = hass.states.get('sensor.ha_rpi4_config').attributes['components'] built on ```

  • platform: rest
    name: Ha Rpi4 config
    resource: !secret resource_ha_rpi4_config
    value_template: > #components|list|count}}
    {{value_json.version}}
    json_attributes:
    • components
    • unit_system
    • config_dir
#

can we not do this yet with the new integrations template options? or what am I missing. ;-/

final abyss
#

Trying to create a template that checks if everyone is in bed. Got all the bed sensors in group.bed_presence and want to compare that to zone.home. so If 1 person is at home and 1 or more are in bed the sensor should be true. However if 0 people at home and 0 people in bed it should not be true.
I think i got the first part figured out, but not sure about the last part.
i got this now:

{{ states.group.bed_presence|expand|selectattr('state', 'eq', 'on')|list|count|int >= states('zone.home') | float }}

Any suggestions / ideas?

pastel moon
marble jackal
final abyss
#

That works! {{ expand(states.group.bed_presence)|selectattr('state', 'eq', 'on')|list|count|int >= states('zone.home') | float and states('zone.home') != '0'}}
Thanks 🙂

tribal holly
#

help

#

Month:
value_template: {% if now().month() in (0,) %}Janeiro{% elif now().month() in (1,) %}Fevereiro{% elif now().month() in (2,) %}Março{% elif now().month() in (3,) %}Abril{% elif now().month() in (4,) %}Maio{% elif now().month() in (5,) %}Junho{% elif now().month() in (6,)%}Julho{% elif now().month() in (7,)%}Agosto{% elif now().month() in (8,)%}Setembro{% elif now().month() in (9,)%}Outubro{% elif now().month() in (10,)%}Novembro{% elif now().month() in (11,)%}Dezembro{% endif %}

marble jackal
#

now().month() counts from 1 to 12, not from 0 to 11

#

You could also do it like this:

{% set months = [ 'January', 'February', 'March', 'April' ] %}
{{ months[ now().month() - 1 ] }}
#

Add all the months of course, don't stop at April

#

You could also try {{ now().strftime('%B') }}

pastel moon
#

The latter was neat... Is there anything to consider when choosing method, or are they equally good?

marble jackal
#

Well, the list with month names always gives the same result, the latter depends on language settings

floral shuttle
#
            **{{- d[0]}}:**
            {% for i in d[1] if i.state in ['unavailable','unknown'] -%}
            > {{i.name}}: *{{i.state}}*
            {% endfor %}
          {%- endfor -%}``` give me a nice ordered list of domains and their entities. It does however show the domain when there is no entity to list. Ive tried to set a count !=0 and even exclude some domains completely (if d not in ['alert','media_player','zone'], but that wont make a difference. Would appreciate some help to figure this out
#

wait, another go made this work: {%- for d in states|groupby('domain') if d[0] not in [ 'alert','media_player','zone'] %} so I only need to be able to check for 0 entities in a domain and deselect that domain

marble jackal
#

What if you used:
{%- for d in states|groupby('domain') if states[d[0]] | list | count > 0 %}

#

Or something like that

#

Well, that won't work for domains with only entities with state unknown or unavailable

astral turtle
#

Hi,
Have several sensors that measure outdoor weather, have a template that takes avarage.
The issue is that if one sensor is unavaliable then the average is wrong (in case of 2 sensors it will be just half of the real number).
What is the best approach to solve this issue, ofcourse I could do 'if then', but when there are a lot of sensors construction can get pretty big. Please advise. Thanks!
value_template: >-
{{ (( (states('sensor.filtered_outdoor_humidity_1') | float) +
(states('sensor.filtered_outdoor_humidity_2') | float)
) / 2) | round(0)
}}

astral turtle
#

thanks

silent barnBOT
marble jackal
#

Whoops, copied in the original post and forgot to remove it. This is what I wanted to post

I don't think that won't solve the issue.
This might:

{% set sensors =  'sensor.filtered_outdoor_humidity_1, sensor.filtered_outdoor_humidity_2' %}
{{ expand(sensors) | map(attribute='state') | select('is_number') | map('float') | average }}
#

Copying part of a message is a pita on discord mobile

#

Maybe combined with an availlibility template that at least one sensor should be available

wraith basalt
#

I'm trying to add a condition to an automation like this:

condition: template
value_template: '{{ states.person|selectattr("state","equalto","home")|list|length > 0 }}'

but i am getting: template value should be a string for dictionary value @ data['value_template']. Got None

I also tried:

condition: template
value_template: '{% states.person|selectattr("state","equalto","home")|list|length > 0 %}'

but that gives me: invalid template (TemplateSyntaxError: Encountered unknown tag 'states'.) for dictionary value @ data['value_template']

Could someone help me out?

inner mesa
#

the second doesn't output anything, so it won't work. the first looks fine, and I suspect that the UI editor is hosing it up somehow

wraith basalt
#

I am using the "edit as yaml" function if that matters here

wraith basalt
#

I also tried

condition: template
value_template: >-
  {{ states("sensor.schlafzimmer_sensor_temperature") | float >
  states("sensor.openweathermap_temperature") | float }}

which i need for another automation, but i still get
template value should be a string for dictionary value @ data['value_template']. Got None

young jacinth
#

hey, how do i update a dict entry?

{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'märz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}

i want to update the month of mai with 110 in this example

inner mesa
#

you can't directly. you have to create a new dict with a different key/value

inner mesa
#

I give up. I can't figure out how to do that in Jinja. Perhaps somebody smarter will come along...

odd crystal
#

I have an NFC tag and i want only the device that scans it to get the notification. Is there a way to do that?

#

right now, the "notify" trigger is sent to a specific device.

stuck remnant
#

so you have a bunch of android devices and you need a template to divine which one of those been scanned

odd crystal
#
description: ''
trigger:
  - platform: tag
    tag_id: 80520be9-7d5d-490e-98ff-e08e878ae5d8
condition: []
action:
  - service: notify.mobile_app_schwiingmobile_s22
    data:
      message: command_activity
      data:
        channel: com.google.android.deskclock
        group: >-
          android.intent.extra.alarm.LENGTH:2700,android.intent.extra.alarm.SKIP_UI:true
        tag: android.intent.action.SET_TIMER
mode: single

This is my automation thus far.

silent barnBOT
odd crystal
#

However, this says that regardless who scans my tag, it'll notify schwiingmobile_s22

#

i want it to notify phone_that_scanned_my_tag

stuck remnant
#

hmm maybe you could do it with a helper as well, but I believe a template would be the cleanest looking way (which I don't know)

odd crystal
#

never used templates before. i wouldnt know where to start

#

something like a condition?

stuck remnant
#

via a helper, you'd have to set it to choose from a list of devices

#

from a dropdown list

odd crystal
#

how do you use helpers in automations?

stuck remnant
#

it's like any other sensor basically

odd crystal
#

is it a condition? action?

stuck remnant
#

only you change the value manually (or via automation)

#

no, it's an entity

#

which changes value based on what you give it

odd crystal
#

sorry, what category is it under in the automations UI

stuck remnant
#

it's not

#

go back a screen

#

you have autos, scripts, helpers

odd crystal
#

ah, not automations. separate "helpers" i see.

stuck remnant
#

scenes

#

gah, I hoped there would be someone here who knew the template

odd crystal
#

it would even be OK if i had 2 automations

#

one for each device

#

"if android_ONE, do X"

#

"if android_TWO, do Y"

#

i just dont know how to set that condition

stuck remnant
#

you can have a lot more, there's no shortage of space or computing for autos afaik

odd crystal
#

huh?

stuck remnant
#

ok, so at this point no one has answered us, you could ask for the template again tomorrow

odd crystal
#

no worries.

#

so close.

stuck remnant
odd crystal
#

np

waxen seal
#

I am cross posting this with #frontend-archived because I am not sure it belongs there or in templates

#

I have an attribute with a datetime in it, which I want to display on a markdown card. The attribute looks like this timestamp: '2022-04-04T03:20:00+00:00' I want to display it in local time and don't need anything other than the date, time is not needed. Currently in the markdown card it has "The last update was at {{package.timestamp}}" But of course that displays the whole ugly thing in UTC. I have pored over the template docs for quite some time and can't seem to get it right.

inner mesa
#

{{ ("2022-04-04T03:20:00+00:00"|as_datetime|as_local).date() }}

#

-> 2022-04-03 for me

#

might not need the as_datetime if it's already a datetime

bitter atlas
#

why does state_attr yield additional brackets and hypens in the result when there are none. I have an attribute on a sensor that gives me a url but it spits that result in ['/some/url']

inner mesa
#

maybe it's really a list of 1 item

bitter atlas
#

it is, but I don't know why it's doing that

#

was an easy fix but took me forever to catch it lol

inner mesa
#

integrations can do whatever they want in their attributes

#

which integration?

waxen seal
bitter atlas
# inner mesa which integration?

it was a custom addon to the IMAP, maybe cause it just adds to the existing rather than replacing it is why the additional attributes was list

waxen seal
inner mesa
#

Jinja uses Python data structures and you can use their methods

waxen seal
#

🙂 thought it was probably something like that!

#

And now I have made it even better with strftime, you made my day!

marble jackal
# young jacinth hey, how do i update a dict entry? ``` {% set month = 'mai' %} {% set x = 110 ...

You can do it like this. It will also keep the months in order:

{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'märz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
{% set ns = namespace(paid={}) %}
{% for item in paid.items() | list %}
  {% if item[0] == month %}
    {% set ns.paid = dict(ns.paid, **{ month: x }) %}
  {% else %}
    {% set ns.paid = dict(ns.paid, **{item[0]: item [1] }) %}
  {% endif %}
{% endfor %}
{{ ns.paid }}```
inner mesa
#

Well, yeah :). I wasn't going anywhere near that 🙂

versed shore
#

hey how would I take a template from a history_state and multiply it by a constant to get a sensor registering a kWh unit_of_measurement?

#

the history_state is 1h over a duration of 365.25 days

#

right now I have:

   - platfrom: energy
     id: heating_oil_usage
     unit_of_measurement: 'kWh'
     value_template: {{ states('sensor.hourly_furnace_runtime') * 33.410107 }}
marble jackal
#

states are always strings, so you need to cast it to a float and you need to place quotes around your template if you use a single line

versed shore
#

so {{ states('sensor.hourly_furnace_runtime') | float * 33.410107 }}

marble jackal
#

And quotes around it

versed shore
#

or {{ parseFloat(states('sensor.hourly_furnace_runtime')) * 33.410107 }}

marble jackal
#

Double quotes, as you use single ones inside

#

Just use float( something ) then

versed shore
#

I'm getting: 2022-04-11 01:36:48 ERROR (MainThread) [homeassistant.bootstrap] Failed to parse configuration.yaml: invalid key: "OrderedDict([("float(states('sensor.hourly_furnace_runtime')) * 33.410107", None)])"

#

it seems to be casting my float back to a string...

marble jackal
#

What is the complete code you gave now for this sensor

versed shore
marble jackal
# young jacinth thanks alot 🙏

BTW, you could also use this more simple version which will put the month (mai) at the end of the dict

{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'märz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
{{ dict(paid.items() | rejectattr('0', 'eq', month) | list, **{ month: x }) }}
#

Scratch all that, this works and keeps the order intact

{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'märz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
{{ dict(paid, **{ month: x }) }}
versed shore
#

any Idea for the energy sensor? I just tried {{ float(parseFloat(states('sensor.hourly_furnace_runtime')) * 33.410107) }} and its still going into safemode

marble jackal
#

I told you 2 times now that you need to place quotes around your template

versed shore
#

quotes outside the curly braces?

marble jackal
#
   - platfrom: energy
     id: heating_oil_usage
     unit_of_measurement: 'kWh'
     value_template: "{{ float(states('sensor.hourly_furnace_runtime')) * 33.410107 }}"
#

Yes

#

Otherwise it will treat it as a dict

versed shore
#

thanks, I didn't register that when you said quotes I thought you meant around the float method

marble jackal
#

Or use the multi line format as you did in the other template (using >-)

versed shore
#

@marble jackal do you know why the id / entity_id does not appear in developer tools under states?

marble jackal
#

Don't know, check the log

#

Not sure if that id key is accepted

versed shore
#

maybe it should be entity_id

marble jackal
#

Can't find any docs on this platform energy sensor

floral shuttle
# marble jackal What if you used: `{%- for d in states|groupby('domain') if states[d[0]] | list ...

thanks, this is getting closer (added the counter to check if that works as expected): {%- for d in states|groupby('domain') if d[0] not in ['alarm_control_panel','alert','automation', 'counter','media_player','proximity','scene','zone'] %} **{{- d[0]}}:** *({{states[d[0]] |selectattr('state','in',['unavailable','unknown']) |list|count}})* {% for i in d[1] if i.state in ['unavailable','unknown'] -%} > {{i.name}}: *{{i.state}}* {% endfor %} {%- endfor -%} but yes, it still lists the domains with count 0

#

btw, this is the markdown version hence the **, * and > and specific whitespace killers

#
        content: >
          {%- for d in states|groupby('domain') if
              d[0] not in ['alarm_control_panel','alert','automation','button',
                           'counter','media_player','proximity','scene','zone'] and
              states[d[0]]|selectattr('state','in',['unavailable','unknown'])|list|count != 0 %}
            **{{- d[0]}}:** *({{states[d[0]]
                               |selectattr('state','in',['unavailable','unknown'])
                               |list|count}})*
            {% for i in d[1] if i.state in ['unavailable','unknown'] -%}
            > {{i.name}}: *{{i.state}}*
            {% endfor %}
          {%- endfor -%}``` does the job 😉
tepid onyx
#

what is {{- d[0]}}:

#

**{{- d[0]}}:**

#

fukn escape

floral shuttle
#

tidied that up a bit:```
{% set x = ['unavailable','unknown'] %}
{% set exclude_domains = ['alarm_control_panel','alert','automation','button',
'counter','media_player','proximity','scene'] %}

      {%- for d in states|groupby('domain') if d[0] not in exclude_domains and
          states[d[0]]|selectattr('state','in',x)|list|count != 0 %}
        **{{- d[0]}}:** *({{states[d[0]]
                           |selectattr('state','in',x)
                           |list|count}})*
        {% for i in d[1] if i.state in x -%}
        > {{i.name}}: *{{i.state}}*
        {% endfor %}
      {%- endfor -%}```
tepid onyx
#

more specifically the asterix

floral shuttle
tepid onyx
#

missed that...thanks

floral shuttle
#

but there's 1 spot in the template I can leave the [0] out I guess, in d not in exclude_domains. no, thats not true, need that for the domain filter too..

tepid onyx
#

oh it's just markdown i thought it was part of jinja

#

cool

floral shuttle
#

yeah, you can do very nice things with that, but this is my default markdown toolset, bold, italic and paragraph. Most other things I tend to use card-mod for, although one can also use the # header options with good result

#

and you need to test it in the frontend, because dev template only creates the correct template result, but not the formatting...

tepid onyx
#

sweet 👍

floral shuttle
#

yeah, sweet indeed, what isnt so sweet though, is when editing these heavier templates in dev tools and during editing the interpreter tries to create an output, my Ping sensors always go down. and because there is a flaw in that integration, if 1 goes down they all go down... and set off all kinds of alarms in the home, checking to see if my essential hubs are down 😭

#

as for the d[0] functionality, it takes the first item in the list of the domain object, you can see for yourself when you do {%- for d in states|groupby('domain') %} {{- d}} {% endfor %} instead.

stuck remnant
#

'{{ iif(states.input_number.volume_level.context.user_id) }}'

#

I used this in a condition til now to only make an automation trigger when that input is changed manually by me

#

but what if I needed the opposite

#

for the input to only trigger when changed automatically by automation?

nocturne chasm
#

Easiest way is to flip an input boolean as the first service of your action. Then you can use the input boolean in the condition of other automations. Then when it makes sense, turn the input boolean off

#

I get notifications when my thermostat mode and temp change, but only if changed manually, not by an automation.

stuck remnant
#

cheers

#

I will experiment with this

#

but isn't there also a template

#

like to change context.user_id to something denoting an auto action

#

i.e. not by user

marble jackal
#

'{{ not iif(states.input_number.volume_level.context.user_id) }}'

stuck remnant
#

wow

#

thanks , turns out Im not that bright :))

marble jackal
#

Or '{{ iif(states.input_number.volume_level.context.user_id, false, true) }}'

stuck remnant
#

cheers

shell arrow
#

I have a template binary_sensor that is based on two template sensors. I'm having trouble getting the binary_sensor to reevaluate when I change the templates for the template sensors and then reload template entities.

#

when I run the template in developer tools, it's showing the expected value. So it must just be something missing from the triggers on the template binary_sensor.

marble jackal
#

remove the trigger from the binary_sensor

#

then it will be state based

#

Not sure if you need triggers for the other ones as well

shell arrow
#

I need the triggers on the binary sensor because I want it to trigger at the time seen in the other two sensors. There will not be a state change at that time.

#

Unless there's another way to do that?

mighty ledge
#

that template will only update when you change the state of your entities, when the time occurs, and restart

#

if you want it to update on a period in relation to now, you need to add a time_pattern trigger

shell arrow
#

I added a every 5 seconds time trigger and that works just fine, but that's less than ideal.

marble jackal
#

remove tht trigger completely, you don't need it

mighty ledge
#

a template like that, with removed triggers, will only update once per minute

shell arrow
#

shouldn't this pick up the reload of the template entities:

    - platform: event
      event_type: event_template_reloaded
#

@mighty ledge because of the now() it'll update every minute?

mighty ledge
#

yes

#

only if you remove the triggers

#

otherwise, it'll only update on the triggers

shell arrow
#

I guess that's wasteful, but, better than it not updating at all.

mighty ledge
#

your updating options are: Triggers or entities inside the template without the triggers

shell arrow
#

right. I was trying to fine tune the triggers to cover all the cases where it should update. But, catching the reload of template entities themselves seems to be the issue.

mighty ledge
#

the template reload occurs before the templates reload

#

so, it never effects template sensors itself

shell arrow
#

ugh.

marble jackal
mighty ledge
#

I'll be honest, I don't get your templates for the out_front_lighting_start and end

shell arrow
#

But I guess it'll trigger within a minute according to @mighty ledge, so that's probably good enough.

mighty ledge
#

what's this trying to do?

#

the whole setup

#

just have a 2 hour period before and after sunset that's on for 2 hours?

shell arrow
#

set a lighting window for outdoor lighting. 2 hours before sunrise through 2 hours after sunset. But also with literal max/min times. So... if two hours before sunset is 8am, then it still starts at 6am.

#

I want the lights on during the "dark" times when people are awake, but also late enough/early enough that it ALWAYS includes the times we typically leave the house or get home.

mighty ledge
#

ok

#

you can change

{%- set window_start_max = (next_rising.year|string + '-' + next_rising.month|string 
              + '-' + next_rising.day|string + ' ' + '06:00:00')|as_datetime|as_local
        -%}
#

to

#
{%- set window_start_max = today_at('06:00') %}
#

unless it's tomorrow

shell arrow
#

that works even if the next rising is tomorrow. yeah.

#

?

mighty ledge
#

no but you could still change it

#
{%- set window_start_max = next_rising.date() ~ ' 06:00:00')|as_datetime|as_local -%}
shell arrow
#

what does the "~" do?

mighty ledge
#

adds 2 objects together and ensures both sides of the addition are strings

shell arrow
#

oh nice!

#

yes. that works. and much easier to read.

mighty ledge
#

I still think there's room for improvement in that, but I just woke up and I'm not thinking straight

shell arrow
#

without the triggers, all three of these are evaluating every minute (since they all include now()). So I can probably get rid of this block now too:

        {%- if now() + timedelta(days=1) < window_start -%}
          {%- set window_start = window_start - timedelta(days=1) -%}
        {%- endif -%}
mighty ledge
#

if you get rid of now that template won't resolve every minute

shell arrow
#

.... blink.... blink.... of course. it's early for me too....

mighty ledge
#

SO, you're just trying to make a binary sensor that is on or off for your timeperiod?

shell arrow
#

yes.

mighty ledge
#

Ok, I think this can be optimized. Give me like 5 minutes

#

To think about it

shell arrow
#

okay. thank you!

mighty ledge
# shell arrow okay. thank you!

So to clarify, you're trying to show a window between todays current rising and falling? You remove the day when it falls into tomorrow because it's past that point in time?

#

Basically, looking at that code, it should never have tomorrows date even when next rising is tomorrow

shell arrow
#

I had to remove the day because if it evaluated after the sun set, but before the window elapsed, next_setting was tomorrow.

mighty ledge
#

ok

#

so to reiterate, your goal is to always have a timestamp for today, and you really don't care about tomorrow

#

endgoal is to just have an on/off for todays timespan

shell arrow
#

correct. IDEALLY as soon as the window elapsed the values would be set to to tomorrows information. But, if that happens at midnight, that's fine too.

#

yes.

mighty ledge
#

right, but
"window elapsed the values would be set to to tomorrows information"
doesn't really need to happen

shell arrow
#

as long as it happens before the next window starts, it's fine.

mighty ledge
#

ok

shell arrow
#

yeah. that part doesn't mater, I don't think, if it's evaluating every minute.

#

though... maybe it still does. sun.sun will show tomorrows times as soon as the rising/setting event for today has passed. If it evaluates every minute, then on the next evaluation after sunset, both rising and setting times will be tomorrow and the current time will no longer be "in the window" even though I would still want it "on".

#

subtracting the day brings it back to today's times (though, technically, not 100% accurate since sun rise/set times are slightly different every day... but it's close enough for this purpose. I imagine there might be some weird case around start/end of daylight savings time but, that's fine).

#

If I didn't care about the 06:00 and 21:30 max/min times, how would I create a sensor that was always set to 2 hours after today's sunset? Because, if I can make that, I can use another template sensor to handle the min/max cases based on the time produced by that.

mighty ledge
#
- binary_sensor:
  - name: past_rising
    state: >
      {%- set next_rising = state_attr('sun.sun', 'next_rising')|as_datetime|as_local - timedelta(hours=2) -%}
      {%- set offset = timedelta(days=1) %}
      {%- set next_rising = next_rising - offset if next_rising > today_at() + offset else next_rising %}
      {{ now() > min(next_rising, today_at("06:00")) }}

  - name: before_falling
    state: >
      {%- set next_setting = state_attr('sun.sun', 'next_setting')|as_datetime|as_local + timedelta(hours=2) -%}
      {%- set offset = timedelta(days=1) %}
      {%- set next_setting = next_setting - offset if next_setting > today_at() + offset else next_setting %}
      {{ now() < max(next_setting, today_at("21:30")) }}

  - name: out_front_lighting
    state: >
      {{ expand('binary_sensor.past_rising', 'binary_sensor.before_falling') | selectattr('state','eq','on') | list | length == 2 }}
#

that would resolve properly at all times, including reload

shell arrow
#

groking. one sec.

#

what does today_at() do when you don't give a time?

mighty ledge
#

00:00:00

#

so, the only thing is, it wouldn't fire perfectly at 2 hours before next setting etc

#

it'll be on the minute

#

so if the setting falls at like 24 seconds, it'll turn on at the following 0

shell arrow
#

yeah. that's good enough for this case.

mighty ledge
#

there was a typo

#

fixed

#

was using next_rising in next_setting.

shell arrow
#

this is better, because at least only two of them evaluate every minute, where, my version had all three going every minute.

mighty ledge
#

you could easily turn it into 1 template

shell arrow
#

yeah. but it'd be the same amount of "work" for HA every minute, right? I'd still need all the same computation to happen.

mighty ledge
#
- binary_sensor:
  - name: out_front_lighting
    state: >
      {%- set offset = timedelta(days=1) %}
      {%- set next_rising = state_attr('sun.sun', 'next_rising')|as_datetime|as_local - timedelta(hours=2) -%}
      {%- set next_rising = next_rising - offset if next_rising > today_at() + offset else next_rising %}
      {%- set next_setting = state_attr('sun.sun', 'next_setting')|as_datetime|as_local + timedelta(hours=2) -%}
      {%- set next_setting = next_setting - offset if next_setting > today_at() + offset else next_setting %}
      {{ min(next_rising, today_at("06:00")) <= now() <= max(next_setting, today_at("21:30")) }}
shell arrow
#

I have plenty of CPU to throw at it. So it shouldn't be an issue. I just like to optimize as much as I can upfront because once it's working, I'll forget about it.

#

right.

mighty ledge
#

it's up to you

#

I personally make everything an 'on/off'

#

or I make everything an event

shell arrow
#

on/off is what I aim for too, usually. In this case, I made timestamp sensors because it helped me to see the values for debugging.

mighty ledge
#

So, have you used this all year?

#

because I see potential issues with this and your old template

shell arrow
#

I've not used it at all. I am currently doing this same thing using an entirely different method (pyscript code) and I'm trying to move it into something more standard just to see if I can.

mighty ledge
#

so you haven't ran into an issue when the days are shrinking in your pyscript?

shell arrow
#

no.

mighty ledge
#

so........ the days shrink by 3 minutes

#

so you could have a scenario where you turn on, then immediately turn off after next rising changes to tomorrow, and then it'll turn on again

shell arrow
#

trying to see that corner case myself in this. I think I don't have that issue with the pyscript code because I'm computing rise/set using the astral package instead of relying on data from sun.sun.

mighty ledge
#

yep

shell arrow
#

ahhh. i see the issue with shrinking days now. grrr.

#

the only way around it that I can see (and I don't like it) is to use two input_datetimes and an automation that triggers at midnight. In that automation, set the datetimes to the rise/set times in sun.sun at that exact moment. Then use those input_datetimes for all the computations in this.

#

If I use two template sensors that trigger at midnight, when I reload template entities, they will be "unknown" until midnight occurs, right?

mighty ledge
#

right

#

sun.sun is due for an overhaul because of issues like this

shell arrow
#

yeah. but... even then, how would you cover everyone's weird use cases? lol. Does resetting the values in sun.sun only at midnight work for everyone? what about people with really long days and/or really long nights?

mighty ledge
#

by separating todays rising and tomorrows rising

shell arrow
#

oooh. yeah. that would do it.

mighty ledge
#

it's done in sun2, a custom integration

shell arrow
#

looking at that now.

mighty ledge
#

which is also more accurate

marble jackal
#

Is there and advantage of using {{ expand('binary_sensor.past_rising', 'binary_sensor.before_falling') | selectattr('state','eq','on') | list | length == 2 }} instead of {{ is_state('binary_sensor.past_rising', 'on') and is_state('binary_sensor.before_falling', 'on') }}

shell arrow
marble jackal
#

expand a really nice function 🙂

shell arrow
#

okay. now I have sun2. this should make it a lot easier.

mighty ledge
#

Yeah, sun2 is nice and it's more accurate. Although there was changes that made sun.sun as accurate as sun2

#

awhile back

shell arrow
#

just having the today/yesterday/tomorrow bits is helping a lot here.

#

does today_at() in a template sensor cause evaluation every minute?

tepid onyx
#

petro 👍

stuck remnant
#

2022-04-11T12:51:07+00:00 this is the actual state for the entity im trying to automate. This is the template im using: {{ ( now() - states('sensor.thegoat420_lastactive') | as_datetime).total_seconds() >= 9 }}

#

it doesn't trigger, condition comes back as false

#

the last active sensor is a user input sensor for windows10

#

it resets each time I move the mouse

#

in dev tools the stamp shows as above, but in the UI it looks clean, always shows how many seconds from the last time I moved the mouse or whatever

shell arrow
#

You could make this template be the trigger, but, templates with now() are only evaluated every minute, so, it wouldn't trigger at exactly 9 seconds.

#

instead, you should set "mode" to "restart" and add a 9 second delay to the top of the action.

stuck remnant
#

oh so I need to give it a minute when testing either way?

#

ok, doing that.

shell arrow
#

if you use the delay I mentioned, it'll happen exactly 9 seconds after thegoat420_lastactive is updated.

steep mulch
#

hi guys i hope i write in the right place..
can some one explain me how to configure a switch as a light from .yaml?

#

my configuration is working whit no problem but i would love to have it set as a light instead as a switch

stuck remnant
#

I dont know from yaml but you can use the helpers tab

steep mulch
#

i know that but if its possbile from yaml that will be amazing 🙂

stuck remnant
#

is this the way you meant?

shell arrow
stuck remnant
#

without the condition it triggers with every state change

#

each second

shell arrow
stuck remnant
#

just for the record, the 9 seconds and the switch are just there until I can see it working then I can change the timing and device

shell arrow
shell arrow
stuck remnant
#

no, the point of making the automation is I want it to work

shell arrow
#

haha. no. I mean... it will work with the "for".

stuck remnant
shell arrow
#

you have a sensor that basically updates CONSTANTLY when it's being used, and doesn't update at all when the thing isn't being used. So, with the trigger above, you're just waiting for it to stop updating for 9 seconds. I think that does what you want.

shell arrow
stuck remnant
#

lemme check

shell arrow
#

if you do the "trigger" with "for" like above, you don't need the condition, the delay, or the mode: restart. You're just going to wait for it to stop changing for 9 seconds. This assumes that it changes constantly (at least once every 9 seconds) when it is in use.

#
trigger:
  - platform: state
    entity_id: sensor.thegoat420_lastactive
    for: 9
action:
   - service: switch.toggle
     data:
       entity_id: switch.bathroom_fan

This means, wait for the state of thegoat420_lastactive to change and KEEP THAT VALUE for 9 seconds, then toggle the fan.

steep mulch
shell arrow
#

if the value changes after 5 seconds, say, then then it doesn't trigger.

shell arrow
#

your "turn_on" will be "switch.turn_on". your turn_off will be "switch.turn_off". you can do nothing with set_temperature, set_color, set_white_value, etc... since you don't actually have a light. value_template wil have to look at the state of the switch, etc, etc.

shell arrow
# steep mulch do you know wehre i can find an example?

In an old post from petro, there is this:

light:
  - platform: switch
    name: Light Name
    entity_id: switch.name_switch
  - platform: switch
    name: Light Name 2
    entity_id: switch.name_switch_2

Not sure if this syntax still works, but you could try it.

stuck remnant
#

swift thanks for the help I think I ve got it

#

it works as you described

mental violet
#

Hi, I want to put a service in an automation which turns on input_booleans with a specific entity_id and a specific state.

data: {}
target:
  entity_id:
    {{states.input_boolean |selectattr('object_id', 'search', 'is_fixkosten')|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}
``` like this, but what is the right synstax?
shell arrow
mental violet
#

yes

shell arrow
#

change "object_id" to "entity_id", I think. and it works?

mental violet
#

{{states.input_boolean |selectattr('object_id', 'search', 'is_fixkosten')|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}
this gives me the right entity_ids I want to change. But I dont know how to put this statement into a service call

shell arrow
#
service: input_boolean.turn_on
data:
  entity_id: "{{ blah blah blah|list }}"
mental violet
#

thank you 😄

shell arrow
#

you can probably do it with "target" too... I'm just not sure because I rarely use it.

marble jackal
#

target works as well

#

just not:

service: input_boolean.turn_on
entity_id: "{{ blah blah blah|list }}"
#

That field doesn't accept templates

acoustic fox
#

Hey guys, im have some hard times with one of the param of a template cover. Im using shelly for controlling my covers, and im trying to do a template cover, where the original cover entitys position 1-25% is defined as 1% in the template cover, and the 26-100 percent is the other 99. I need that because the shelly calibration is don't take in consideration the roller blinds holes (between the bars) that take some time to close.
So, my problem is that the set_cover position not working properly. With that config (in the next message) the slider (or simply call the service) act as the original cover. How should i change that to work with the positions i set in the template?

silent barnBOT
merry marsh
#

Is there/does someone have an example for a template sensor, which solves the same requirements, where I would use state for x minutes in an automation or delay_on in an binary template sensor? I want to set a state only when another criteria is in a certain state for x minutes.

mighty ledge
merry marsh
# mighty ledge You can use triggers with templates

Yes. Thanks. Perhaps my intention was not clear. I know this, could also use an automation or helper or variable, etc.

I was more interested in, how such things could be solved within a template. To learn and play around.

mighty ledge
#

Templates are limited to current information only. So you can only do so much with timing in templates

#

at one point I had a duration on one of those triggers but removed it in favor of something else

#

Otherwise you have to calc it yourself and hope your state didn't change over the duration you're checking against

mental violet
#

Hi, is there a filter for this expression:
selectattr('state','eq','on') for 2 mins
? Thank you^^

swift lance
#

hello, i have this template for a restful sensor

value_template: "{{ state_attr('sensor.cmi', 'Outputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join }} "

now some of these Value.Value are binary
i try do get the number 1 or 0 and make it a word, on/off

value_template: "{{ 'On' if is_state('sensor.cmi_xxx', '1') else 'Off' }}"

The second value template would work, however i dont want two sensors.
How would i combine the second template into the first one? I dont understand the jinja2 expressions, prob very easy if you know how.
Thanks

marble jackal
#

This should work | selectattr('state','eq','on') | selectattr('last_changed', '<', now() - timedelta(minutes = 2))

swift lance
marble jackal
#

value_template: "{{ 'On' if state_attr('sensor.cmi', 'Outputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join == '1' else 'Off' }}"

wraith basalt
#

I'm trying to create variables in a script with the context id included, but i'm getting:
UndefinedError: 'context' is undefined

That's my code for the variables:

variables:
  action_yes: '{{ ''YES_'' ~ context.id }}'
  action_no: '{{ ''NO_'' ~ context.id }}'
#

Okay i found the problem

olive dust
#

Quick question: I had this working last week, but I'm not sure if between updating to 2022.4 or me tinkering with the dashboard, something got tweaked somewhere.

I have an automation that calls a shell script that posts a sensor state to a slack channel:

service: shell_command.slack_topic
data: {{ states('sensor.weekly_special') }}

however, when I click Run Actions and view the trace, it's being replaced with

service: shell_command.slack_topic
data:
  '[object Object]': null

Has anyone seen this before?

inner mesa
#

You need to surround the template in quotes

olive dust
#

updated to

service: shell_command.slack_topic
    data: "{{ states('sensor.weekly_special') }}"

which is then 'autocorrected' to

service: shell_command.slack_topic
    data: '{{ states(''sensor.weekly_special'') }}'

and says "Error: Error rendering data template: Result is not a Dictionary"

#

Tried via yaml editor in the HA interface as well as editing via nano

#

Also, getting the right output via the template debugger under Developer Tools

naive swan
#

Is there a template that would work to make a sensor showing how many minutes an entity has been in its current state?

inner mesa
olive dust
inner mesa
#

data: is not a key, it's a dict, which contains key/value pairs

#

and it wouldn't be indented like that in any case

echo oracle
#

Hi all, struggling to create a value template for a sensor. the sensor scrapes a value from the web, and gets something like "Next Collection: 8 days from now on Thursday, 21 April 2022"
In the template editor in dev tools, I have:
{% set text = states.sensor.blackbin.state %}
{{ text.split(', ')[-1].strip() if ',' in text else text.strip() }}
which outputs the date part as a string. Im really struggling to understand how to convert this to a date in a value template

arctic sorrel
#

What is the output you're getting, and what are you trying to do with the result?

echo oracle
#

the result should be able to be referenced by an automation to remind me to put the bin out, so a date comparison

marble jackal
#

What's the full YAML for the template sensor

echo oracle
marble jackal
#

You are referring to the same sensor right? That won't work

echo oracle
crystal nest
#

Guys, my goal is to use 2 conditional cards to show either "Switch on server using WoL" if off, or "Show server stats from mqtt json" if on. Issue is how to determine "is on". My thoughts were that since I include the date time stamp in my sent mqtt json, I could do an "If now() > last received json (MyServer/timestamp + 10 minutes), then the server is off" Time stamp is in the format now.strftime("%Y-%m-%d %H:%M:%S"). Anyone want to point me in the direction of the jinja to put that into a template binary sensor?

marble jackal
#

Remove the {% set text %} part and replace text with value

#

Assuming the part after select: is correct

echo oracle
#

oops typo.. i ll try again

echo oracle
echo oracle
#

sensor:

  • platform: scrape
    name: blackbin
    resource: https://www.n-kesteven.org.uk/bins/display?uprn=XXXXXXXXXXX
    select: "#content > div > div > div.bin-dates > div.bg-black.text-white.bin-black-next.bins-next.position-relative > p:nth-child(2) > strong"
    value_template: >-
    {{ value.split(', ')[-1].strip() if ',' in text else value.strip() }}
    scan_interval: 86400
#

right, missed a "test" in the middle, its now returning a state of "21 April 2022"

marble jackal
#

That was the idea right?

echo oracle
#

I need to have a device class of timestamp somehow

mighty ledge
#

customize.yaml

echo oracle
# mighty ledge customize.yaml

could you expand on that please? I now have a sensor, with a state that is a string containing the date, how do I convert that to a timestamp?

silent barnBOT
#

By default, all of your devices will be visible and have a default icon determined by their domain. See customizing devices for how to change that.

mighty ledge
#

see manual customization in that link

echo oracle
#

that link does not explain how to change from a string to a timestamp

faint crater
#

How can I use a template in a payload for an MQTT switch? This, for example, is just sending the literal string rather than interpolating the payload:

payload_off: >-
  {"value": {{ 1 if is_state('switch.charger', 'on') else 4 } }}
marble jackal
#

Your closing curly brackets do not match the opening brackets

faint crater
#

Sorry, typo in my white-spacing

#

Should be:

payload_off: >-
  {"value": {{ 1 if is_state('switch.charger', 'on') else 4 }} }
marble jackal
#

That looks better already

faint crater
#

Well, maybe, but it doesn't work 🙂

mighty ledge
echo oracle
marble jackal
mighty ledge
tepid onyx
#

yo dudes

#

laptops got no pubes need some charging back soon

echo oracle
#

I though %m would change April to 04

mighty ledge
#

||you don't||

echo oracle
marble jackal
#

Are you doing this in the scrape sensor itself?

echo oracle
#

at the moment, Im doing it in Devtools - Template

mighty ledge
echo oracle
#

so the scrape sensor alread has the value 21 April 2022 as the state

echo oracle
mighty ledge
#

and is the word April 04?

echo oracle
#

the word is just april, I thought it would change it to 04

mighty ledge
#

so what %<letter> gets you the word April?

#

you're converting your String to a datetime object

marble jackal
#

%Better use something else then

mighty ledge
#

strptime takes the string and format and uses the format to convert the string

#

so you're saying convert a 04 month when you're providing a word month

echo oracle
mighty ledge
#

🎉

echo oracle
#

just need to figure out how to add that to the value tmplate, thanks guys 🙂

mighty ledge
#

np

#

always helps to understand what strptime and strftime does

#

strptime takes a string and converts it to a datetime

#

strftime takes a datetime and converts it to a string

echo oracle
mighty ledge
#

if it's any consolation, this is the hardest aspect of templates

echo oracle
#

20 years ago I would have been all over this. These days, the old grey matter is a little slow

marble jackal
#

You can replace the state_attr part with the current template, or create a variable using the current template and use the variable

faint crater
echo oracle
marble jackal
#

That would be easier to read

#

So basically:

{% set date = current_template %}
{{ strptime(date, format) }}
echo oracle
marble jackal
#

Nope

#
      {% set date = value.split(', ')[-1].strip() if ',' in value else value.strip() %}
      {{ strptime(date, "%d %B %Y") }}
#

Like that

marble jackal
#

BTW, that whole if is not needed, you can just split something by , . It will do nothing if there is no , in it besides making it a list

#
      {% set date = value.split(', ')[-1].strip() %}
      {{ strptime(date, "%d %B %Y") }}
midnight saddle
#

I have several occupancy sensors that appear as binary sensors, and the states are either "on" or "off". How can I make a text field show "Occupied" or "Unoccupied" based on that?

mighty ledge
#

you should be able to do that through the UI on the entity itself

midnight saddle
#

ah good idea

#

hmm they were seemingly already set to occupancy

mighty ledge
#

in the backend it will always be on/off

midnight saddle
#

Ok so in Configuration > Devices & Services > Entities it's set to show as Occupancy, but when i set a Mushroom template card's text field to {{ states('binary_sensor.music_room_occupancy') }} it shows on/off

mighty ledge
#

yes, because that's a template

mighty ledge
midnight saddle
#

ah gotcha

#

that makes sense, thanks for explaining

winter path
#

So not so good at templating, but trying to get better. Need som ehelp as I try t transition away from nodered. In nodered I had a function: msg.payload = msg.payload.split(" "); var index = msg.payload.indexOf('in'); // get index if value found otherwise -1 msg.payload.splice(index); msg.payload = msg.payload.join(" "); return msg;

I am basically trying to convert this into a template. Basically the task is to take a long sentence, find the word in, and splice it off from there. It seems jinja doesnt have a splice function? Right now I am basically at this:
{% set string = states('sensor.pixel_5_last_notification').split(" ") %} {% set index = string.index("in") %}

and unsure of how to chop off from index on before joining the remaining words back up.

#

any help would be appreciated

marble jackal
#

You want the part after "in"?

winter path
#

nah the part before.

#

I think I got it. Took a long time but this is the end state and seems to work:
service: tts.google data: entity_id: media_player.home_group message: >- {% set string = states('sensor.pixel_5_last_notification').split(" ") %} {% set index = string.index("in") %} {% set string = string[:index] %} {{ "Attention " + string|join(" ") }}

marble jackal
#

Yes, I thought after, so I was about to suggest this :)

{% set index = string.index('in') if 'in' in string else 0 %}
{{ string[index:] | join(' ') }}
winter path
#

ah that may still help make it cleaner though! Basically get notifications from my cmmmunities app when someone checks in, and same boilerplate

marble jackal
#

The if statement for index is to avoid errors in case there is no in in the string

winter path
#

Good thinking

#

and like the string[:index]|join.... wasnt sure how to join those two expressions

marble jackal
#

But you need to replace the 0 in that statement now, because you need the first part. However, if you replace it with -1 it will remove the last word

winter path
#

oh in should always be in there

marble jackal
#

You could do it like this:

{% set index = string.index('in') if 'in' in string  %}
{{ ( string[:index] if 'in' in string else string) | join(' ') }}
winter path
#

figured with 0 there it means their whole notification boilerplate changed and would need to recheck it

#

oh I see

marble jackal
winter path
#

No its conditioned from a certain app

#

package

marble jackal
#

Ah okay

winter path
#

but better safe than sorry

#

strings come out like ['person', 'arrived', 'in', 'the', 'community', 'and', 'was', 'verified', 'and', 'entry', 'granted.', 'Please', 'note', 'that', 'guests', 'can', 'be', 'approved', 'on', 'multiple', 'accounts', 'and', 'may', 'be', 'here', 'to', 'see', 'another', 'resident.']

#

so i basically aim for google to say Attention person arrived

exotic galleon
#

could someone explain what's wrong with how i'm using the "float" in this template? Everything calculates correctly in the developer tools templates, i get proper data in the sensor within HA. But I receive a warning in the log "Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1"

#
        value_template: >-
          {{ (states('sensor.plug1_office_powerbar_current') | float) + (states('sensor.plug2_office_powerbar_current') | float) + (states('sensor.plug3_office_powerbar_current') | float) }}
#

i seem to have problems with so much of my templates revolving around floats

buoyant pine
#

You need to specify a default value which will be used if the entity you're using the float filter on isn't available.

| float(0)
``` for example
mighty ledge
buoyant pine
#

😂

#

Can't wait for the next wave

mighty ledge
#

I hope you know, I have a million ips

buoyant pine
#

"I own all the IP addresses in existence"

mighty ledge
#

I own them all + 1

#

I’m also totally smart

buoyant pine
#

Careful though. He might be watching cz_freakouteyes

mighty ledge
#

Like really smart

#

Like so smart, Google can’t stop me

buoyant pine
#

I am become Google

mighty ledge
#

Nooo

inner mesa
#

{{ all_ipaddresses|random|torment(tediore) }}

mighty ledge
#

Lol

inner mesa
#

to, ya know, bring it back around to the topic

mighty ledge
#

I love how he chose tediore

#

Talk about bad luck

buoyant pine
#
Currently 'torment' will return 'me', however this template will fail to render in Home Assistant core 2022.1
buoyant pine
#

I do find it funny/sad that this is how they've decided to use their time

#

To prove...that they can use a VPN? I guess?

exotic galleon
exotic galleon
buoyant pine
#

Thankfully not

exotic galleon
#

Ok .. I thought I might have hit on a touchy subject 😛

buoyant pine
#

Some troll got upset the other day and decided to take it out on me in the lamest way imaginable

exotic galleon
#

Ahh .. so it was just purely coincidental that was asked after my inquiry …

#

I thought my question about floats was triggering haha

buoyant pine
#

Oh! Yeah

#

Oh 😂

#

Nope, unrelated

mighty ledge
#

Haha, yeah sorry! Completely unrelated

exotic galleon
#

No worries 🙂

floral shuttle
#

trying to cut the template evaluation as much as possible in the system, I seem to have forgotten how we can prevent daily (or longer) templates to be calculated each minute... things like {{now().day}} ... what was it again please?

marble jackal
#

Templates with now() in it will be evaluated every minute

#

As now() will update every minute

floral shuttle
#

yes, thats why I asked.... I have quite a few of those, that don't need that. Maybe its not such a huge burden on the system, but hey, the devil is in the details

stuck dock
#

I am trying to create three sensor

#

Invalid config for [sensor.template]: required key not provided @ data['sensors']. Got None. (See ?, line ?).
Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See ?, line ?).

#

getting this error

rose scroll
#

Check your indentation carefully. Error in line 2.

floral shuttle
#

a specific reason you dont use the template: format, but the 'legacy style' platform: template?

stuck dock
#

you mean it should be ```

  • platform: template
    sensors:
    template_grid_feed_in:
stuck dock
floral shuttle
#

give the new style a try, its very nice

#
template:
  - sensor:
      - unique_id: new_years_day_countdown
        name: New years day countdown
        state: >
        icon: >
floral shuttle
marble jackal
#

and don't place this in your sensor.yaml, place it in configuration.yaml or in a separate template.yaml for which you have to create an include in configuration.yaml

floral shuttle
#

yes, considering he has utility_meter on the same level, that should be ok here though

stuck dock
floral shuttle
floral shuttle
#

yep, that was it, rate-limiting and updating on```
template:

  • trigger:
    • platform: time_pattern

      This will update every night

      hours: 0
      minutes: 0
    • platform: event
      event_type: homeassistant_start
    • platform: event
      event_type: event_template_reloaded``` beautifully
#

I do believe I found an issue because this template: state: > {{states('sensor.dag')}} {{states('sensor.current_day')}} {{states('sensor.maand')}} {{states('sensor.year')}} of which the second and last nested templates also use the same trigger base show 'unavailable'. see: https://github.com/home-assistant/core/issues/70036

marble jackal
#

Are you sure sensor.current_day and sensor.year actually exist? Maybe they _2 has been added for some reason (old version still existed when you updated the unique_id or something)

stuck dock
#

How it should be?

floral shuttle
#

one other problem template: ```
- unique_id: christmas_time
name: Christmas time
state: >
{% set today = now().day %}
{% set month = now().month %}
{{month == 12 and today >= 24 or month == 1 and today <= 2}}

#

somehow the nesting causes havoc

stuck dock
#

still same error

floral shuttle
stuck dock
#

where i am doing it wrong?

#
  - sensor:
    template_grid_feed_in:
      name: "Solar 2 Grid"
      unit_of_measurement: 'W'
      device_class: power
      state: >
        {% if states('sensor.grid_active_power') | int > 0 %}
          {{ states('sensor.grid_active_power') }}
        {% else -%}
          0
        {% endif %}
```?
floral shuttle
#

try again:```
template:

  • sensor:
    • unique_id: template_grid_feed_in
      name: Solar 2 Grid
      state:
      etc....
stuck dock
#
  - sensor:
    - unique_id: grid_feed_in
      name: Solar 2 Grid
      unit_of_measurement: 'W'
      device_class: power
      state: >
        {% if states('sensor.grid_active_power') | int > 0 %}
          {{ states('sensor.grid_active_power') }}
        {% else -%}
          0
        {% endif %}
#

is this correct now?

marble jackal
#

looks fine

stuck dock
#

how to format the next two?

#

still

#
Source: config.py:454
First occurred: 2:20:18 PM (6 occurrences)
Last logged: 2:50:01 PM

Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 147). Please check the docs at https://www.home-assistant.io/integrations/sensor
Invalid config for [template]: [template_grid_consumption] is an invalid option for [template]. Check: template->template_grid_consumption. (See /config/configuration.yaml, line 161).
Invalid config for [template]: [unique_id:curent_solar_consumption] is an invalid option for [template]. Check: template->sensor->0->unique_id:curent_solar_consumption. (See /config/configuration.yaml, line 174).
Invalid config for [template]: [unique_id:curent_solar_consumption] is an invalid option for [template]. Check: template->sensor->0->unique_id:curent_solar_consumption. (See /config/configuration.yaml, line 175).
marble jackal
#

add a space after the :, remove the : at the end

#

unique_id: curent_solar_consumption

#

Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 147). Please check the docs at https://www.home-assistant.io/integrations/sensor this is about something else you didn't share in your codepile

#

Could also be about something in sensor.yaml

marble jackal
#

back to legacy format

stuck dock
floral shuttle
#

you're quite accomplished in not following advise here.... I mean even the first one still has indents differently from what we suggested and what is in the docs..

#

btw, the 'next two' should be indentically formatted below the first one

chilly ferry
#

What is wrong with these conditions?

- conditions:
    - condition: or
      conditions:
        - condition: state
          entity_id: binary_sensor.home_occupied
          state: 'on'
        - condition: and
          conditions:
            - condition: state
              entity_id: binary_sensor.home_occupied
              state: 'off'
            - condition: trigger
              id: door
#

I basically want it to be true only if home is occupied or (home is not occupied and the door got opened), but it triggers even if the home is occupied when the door is open

#

it looks exactly like this example in the documentation but with reversed or and and conditions

inner mesa
#

that's what you've told it to do

#

the first part of the "or" condition will allow the automation to proceed if you're home regardless of the state of the door

#

it won't even bother to look

chilly ferry
#

oooh gotcha!

#

stupid me... 😆

#

thanks!

#

I think I'm gonna have to find a better way of creating automations because mixing triggers and actions make them sometimes very complex (maybe not much this one, but...)

inner mesa
#

might be easier to sort out in a choose:. There are several ways to handle conditions

merry marsh
marble jackal
merry marsh
marble jackal
#

No, not possible for template sensor

#

You could add an uptime sensor, and trigger x minutes after the datetime in that sensor

merry marsh
#

Will try this. Thank you. Good idea, if not possible directly in a trigger. Or I will switch to an automation.

#

To be honest, currently I'm not seeing the benefit of a trigger template sensor compared to an automation. Is there any, so that has been intrupoduced recently?

inner mesa
#

a trigger-based template sensor returns a value that can be used elsewhere, where an automation can do a bunch of things based on a trigger & condition, but doesn't have a state other than enabled/disabled

#

template sensors don't do anything other than define their own state

marble jackal
merry marsh
#

Yes and (currently, until I perhaps get it) no. I compare it against a helper or a custom variable (instead of the template sensor), have the triggers as here and set the value via the different set_value services. Then it is the same, isn't it? But then with more options, like steps and delays before finally setting the value, log, and esp. trace.

inner mesa
#

Yes, you can emulate the functionality of a trigger-based template sensor with an automation & helper

merry marsh
#

And because of this my question above, where the benefit of the trigger based template is and so it has been introduced, if I have only limited options compared to the other way?

inner mesa
#

it's simpler and doesn't require another entity?

#

you should use what makes sense for you and your situation

marble jackal
#

Advantage of a helper is that it is persistent and will survive a reboot

inland kayak
#

I have this action

            entity_id: media_player.shop
            data: 
              message: The shop is now open.

Could I template the message? The reason is based on the time of day, would like to say good morning, afternoon, or evening. Just thinking out loud, is there not a sensor for that?

mighty ledge
inner mesa
#

it's easy enough to write a template for that based on now().hour, though

floral shuttle
wraith basalt
#

What helper would i use if i want it to represent a true/false template?

wary helm
#

The following template used to work, any idea what changed?
{{ state_attr('sensor.recycleapp_restafval', 'Days-until') }}
The state of the entity is here: 19 Apr

floral shuttle
# merry marsh ``` - platform: event event_type: homeassistant_start ``` Is there a way to ti...

check for the various HA type events https://www.home-assistant.io/docs/configuration/events/#homeassistant_start-homeassistant_started and https://www.home-assistant.io/docs/automation/trigger/#home-assistant-trigger, and, tbh, I dont understand the difference either 😉 I only noticed the homeassistant_started (not _start) event yesterday.. what I did noticed was that my trigger based templates didnt update on the platform: event, homeassistant_start event, but did on the home-assistant-trigger. might be because of 123's deduction here: https://community.home-assistant.io/t/enhance-trigger-based-template-sensors/308037 ?

marble jackal
#

Maybe they changed it to lowercase

wraith basalt
mighty ledge
wraith basalt
mighty ledge
#

You can’t configure template sensors from the ui

wraith basalt
#

Yes that’s what I meant

#

Thank you

mighty ledge
#

Np

#

@merry marsh

platform: homeassistant
event: start
floral shuttle
#

yeah,but why is that different form the others, specifically homeassistant_started?

#

they're all core events, why cant we use those platform: events ?

mighty ledge
#

One is fired from the event bus the other is probably handles before

#

They are 2 different integrations

floral shuttle
#

tbh, I feel some sort of short explanation should be provided in the docs to explain the difference, and when to use which

mighty ledge
#

Just use home assistant start

mighty ledge
#

The other is an event

#

Use the event when you want 1 trigger and to parse through separate events

floral shuttle
#

yes, and events are valid triggers, so should also be valid for trigger based templates ?

mighty ledge
#

Yes

floral shuttle
#

but they arent....

mighty ledge
#

Did you subscribe to the event?

#

Does it occur

floral shuttle
#

I briefly saw Arganto mention that (its gone now), and it is what I described in my issue

#

not sure I understand what you ask. when I used the platform: event on homeassistant_start, the trigger based sensor didnt work, using the platform: homeassistant, event: start, it works fine

#

I now see that homeassistant_start is too early in the process, and maybe should use homeassistant_started

mighty ledge
#

And you’re 100% sure this event is real?

floral shuttle
#

I would hope so ;-=) my system did startup ...?

mighty ledge
#

Yes but that doesn’t mean that HA creates that event

floral shuttle
#

yes, and thats why I hope some explanation will be offered on the whens and whys

#

its not very silly to expect an event homeassistant_started to be created on homeassistant start is it? If that cant be used, it should really be indicated as such, and what we Can use it for

mighty ledge
#

FYI this is covered in the docs

#

You just didn’t look for it

floral shuttle
#

exactly, as I quoted in my Community post, and yet we can not use it for the trigger based template

mighty ledge
#

It literally says to use the built in platform not the events

floral shuttle
#

yes, it says we recommend

#

thats not the same as you can not use these events, nor does it explain why.

mighty ledge
#

You probably don’t need to know why because it’s not meant for you to use

floral shuttle
#

ah but there you go, I always want to know why....

mighty ledge
#

Well how about just use what everyone tells you to use

floral shuttle
#

i dont like to be told I dont need to know 😉

mighty ledge
#

Read the code then

floral shuttle
#

yes, I started to do that indeed, but couldnt find the definitive answer yet

mighty ledge
#

It probably happens before templates are loaded therefor templates dont trigger off it

#

Because there probably is no definitive answer. The loading process is complicated. Homeassistant event triggers are ensured to work

#

So use them

floral shuttle
#

yes, That was my conclusion too as reason for why nested templates in the trigger based templates remain unavailable. And ofc I did change to the platform: homeassistant after that. np. Its just that I dont grasp why the events are there in the first place

mighty ledge
#

Otherwise read the code

merry marsh
mighty ledge
#

I just confirmed. so, use the other.

quaint flame
#

need some help with a template sensor. i'd like to make one show the difference between a static number, and a different sensor. so say {{ 100 vs (current sensor) = (+ or - value) }} . so 100 vs (current sensor at 50) = -50. or the opposite at 100 vs (current sensor at 150) = +50. hope this makes some sense lol. TIA

rose scroll
#

Umm why not just do {{ states('sensor.xxx') | int(0) - 100 }}?

quaint flame
#

cuase i was way over thinking it and trying to do it oposite lol

rose scroll
#

Is it critical to have the + if the difference is positive?

quaint flame
#

no

#

what does the int(0) define?

#

how do you link text in the black box to show correct format

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

rose scroll
#

Ensure that the value from the sensor is cast to an int. (0) is the default if the sensor's state can't be cast to int, eg. If sensor is unavailable.

inner mesa
#

or single backticks

quaint flame
#
  - sensor:
      - name: "titanoinvestment"
        state: >
          {{
              ( states('sensor.titano') | int(0) - 14000 )
              }}
        unit_of_measurement: "$"   
#

oh nice

#

does that look ok in my template.yaml

rose scroll
#

Throw the {{...}} into Dev Tools > Template and see if any errors pop up. But looks legit from here.

quaint flame
#

tyvm

#

can i enter a negative minimium for input numbers?

fossil venture
#

Yes

arctic sorrel
#

Check devtools -> States for the list of attributes

#

You're probably looking for something like

{{ state_attr('sensor.smartdry','Humidity') }}
inner mesa
#

I'm surprised that didn't catch fire 😉

#

The states() part

fringe pewter
#

If this doesn't belong here, please advise.

Input Number Slider Question: I have a slider with a min/max/step of 0/70/1. I want the slider to show value in percent, where 0=0% and 70=100%, is this possible? if so, how?

barren jungle
#

Hmmm...
Out of all trigger based entities binary_sensor is the only one that retains it's state between reloads and restarts.
sensor|number|select defaults to unknown state and requires special handling.
Interesting, hope one day all will be able to retain state.

floral shuttle
#

soon.... the PR;s for that are almost ready....

wet lodge
#

Hey folks. My old automation for forwarding persistent notifications to my phone hasn’t worked properly in a number of months. I can see that they are all listed in states.persistent_notification, but I need help fishing the details out. Does anyone have a template (or combination of templates) for grabbing the title and message for the most recent persistent notification?

sacred sparrow
#

what would be the wait template for my sensor so it doesn't move on to the next step of the automation until nothing on the cover has been triggered for 5 seconds? {{ is_state('cover.living_room_blinds_', '.........

#

the lag in web api for my blinds can be up to 10 seconds and sometimes the values arent sent to HA before the wait template has had a chance to see the new values

inner mesa
#

You can't use a wait_template for that

#

You would want wait_for_trigger with a state trigger with no to or from and a for:

#

Assuming that it is actually changing state and you want it to settle on a value

#

The 'nothing on the cover has been triggered for 5 seconds' is a little confusing

rose scroll
thorny snow
#

im trying to count how many lights are on but somehow i can't get it to work
im using this code and did put ut in my sensor.yaml file

    count_lights_on:
    friendly_name: "# Lights on"
    unit_of_measurement: 'on'
    value_template: "{{ states.light | selectattr('state', 'eq', 'on') | list | count }}". ```
fossil venture
#
  - platform: template
    sensors: 
      count_lights_on:
        friendly_name: "# Lights on"
        unit_of_measurement: 'on'
        value_template: "{{ states.light | selectattr('state', 'eq', 'on') | list | count }}"
#

Or using the new template integration:```
template:

  • sensor:
    • name: "# Lights on"
      unit_of_measurement: 'on'
      state: "{{ states.light | selectattr('state', 'eq', 'on') | list | count }}"
#

(That goes in your configuration.yaml file, not sensors.yaml)

thorny snow
#

such a hero

#

it works!

#

i see it also counts groups

#

can i also only count the lights

#

i created a light group in helpers

fossil venture
#

I don't think so. The light group creates a light entity. There's no way to distinguish it from other lights. I could be wrong. Petro or Fez might know a way.

marble jackal
#

To count lights which are on, and exclude light groups, note that groups have an attribute entity_id You can exclude the lights who have this attribute defined.
This attribute entity_id contains the members of the group

#
template:
  - sensor:
      - name: "# Lights on"
        unit_of_measurement: 'on'
        state: "{{ states.light | rejectattr('attributes.entity_id', 'defined') | selectattr('state', 'eq', 'on') | list | count }}"

or, if you use hue_groups or deconz_groups and want to exclude them as well

template:
  - sensor:
      - name: "# Lights on"
        unit_of_measurement: 'on'
        state: "{{ states.light | rejectattr('attributes.entity_id', 'defined') | rejectattr('attributes.is_deconz_group') | rejectattr('attributes.is_hue_group') | selectattr('state', 'eq', 'on') | list | count }}"
thorny snow
wet lodge
thorny snow
modern sluice
#

Having trouble understanding the regular expressions to get contains in a template. The state of a media player allows me to trigger based on song, artist, or album. The problem with this is it must be exact and so many artists/songs/albums have collabs in their names it's difficult to build effective triggers. Can somebody help me with a template that triggers when a song CONTAINS media_artist: Nicki Minaj
so it will still fire even if media_artist: Nicki Minaj feat. Drake, Lil Wayne & Chris Brown please?

buoyant pine
#
"{{ 'Nicki Minaj' in state_attr('media_player.whatever', 'media_artist') }}"
buoyant pine
#

Wut?

mighty ledge
#

No I haven’t switched

modern sluice
torpid reef
inner mesa
#

it's hard to tell if your big yellow outline has obscured something

torpid reef
inner mesa
#

but {{ state_attr('sensor.xxx', 'entries')[0].content[0].value }}

#

ok, well, try that in devtools -> Templates

torpid reef
#

That worked perfectly thank you very much for your help!

lyric crown
#

I have a pretty crude rest sensor that I'm using right now that just uses a single entity but I'd like to actually create different entities for each prediction. I also want to expand this to get the location of each vehicle from another endpoint.

#

hmm, might be able to do it with pyscript and hass.states.set(..., ..., ...)

green lynx
#

Hello, i used a vibration sensor to try to "smartify" my dryer, problem is, i cannot figure out how to make an accurate template, this is what it looks like when it's on vs when off https://prnt.sc/tyqnNcdtKRJb

#

it fluctuates so much when working i cannot use it to create an automation, any idea how can i solve it?

lyric crown
#

did it turn on ~8:48?

#

just check if it's not Apaganda

green lynx
#

yeah it turn on at 8:48ish

#

yeah but one sec is off and next sec on

lyric crown
bright quarry
#

trying to make a script that changes defined hue light targets to a random color. dunno where to put random. could've swore it used to work as effect/light effect, but it doesn't.

marble jackal
#

Use service: light.turn_on with rgb_color: "{{ [ range(0,256) | random, range(0,256) | random, range(0,256) | random] }}"

late island
#

Heyho. So I am trying to combine my automations into one right now. But its not really working how I thought it would work. The trigger is a template and the entity_id that triggered the automation should be used in the action. https://pastebin.com/d2jcLfry

marble jackal
#

As you use a template trigger, there is no trigger.entity_id variable

late island
#

So is there a way to go about that?

marble jackal
#

Yes, add a trigger id and use the entity is there

#

Or add any other trigger variable as introduced in 2022.4

#
      - platform: template
        id: climate.comet_dect_3_wohnzimmer
        value_template: >-
          {{ state_attr('climate.comet_dect_3_wohnzimmer','current_temperature') | int(default=0) > 21 }}

Then use trigger.id instead of trigger.entity_id

#

Or, with these templates you can just use numeric_state triggers and then you can use trigger.entity_id

#

No template trigger needed

late island
#

So just for my understanding for the next time I am doing something like that. First variant is just sending an id with it so it what triggered it. Second variant would be something like this?

#
    - platform: numeric_state
      entity_id: climate.comet_dect_3_wohnzimmer
      attribute: current_temperature
      above: 21```
lone lion
#

trying to use the chat integration to let people know if they are free, dnd or busy based on the RGB Lites example:

        rgb_color:
          - "{% if color == 'red' %}255{% else %}0{% endif %}"
          - "{% if color == 'green' %}255{% else %}0{% endif %}"
          - "{% if color == 'blue' %}255{% else %}0{% endif %}" ```
changed it to 
  data:
    option: 
      - "{% if roomstate == 'dnd' %}'DND'{% endif %}"
      - "{% if roomstate == 'vrij' %}'Vrij'{% endif %}"
      - "{% if roomstate == 'bezet' %}'Bezet'{% endif %}"
But that fails
silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

lone lion
#

error is: Received invalid slot info for kamer: value should be a string for dictionary value @ data['option']

marble jackal
#

You are providing a list for option

#

This should be only one value

lone lion
#

one of those three indeed

marble jackal
#

That's not how that works

lone lion
#

When i set it to :
option: "{{roomstate}}" , it works, but i have to type the correct state

marble jackal
#
      option: >
        {% if roomstate == 'dnd' %}
          DND
        {% elif roomstate == 'vrij' %}
          Vrij
        {% else %}
          Bezet
        {% endif %}
lone lion
#

let me try that!

#

i was searching for that indeed, but couldnt find much info in the google chat bot and passing the slots except the light example

#

worked ! ty

wet lodge
# wet lodge Hey folks. My old automation for forwarding persistent notifications to my phone...

If it helps, here is an example of the output:


[<template TemplateState(<state persistent_notification.config_entry_reconfigure=notifying; message=At least one of your integrations requires reconfiguration to continue functioning. [Check it out](/config/integrations)., title=Integration requires reconfiguration, friendly_name=Integration requires reconfiguration @ 2022-04-13T21:11:02.077940-03:00>)>]
wet lodge
#

Never mind. I managed to piece it together myself. I guess I’m starting to figure this stuff out after all.

amber hull
#

I use a markdown card that uses ```
| {{ states.sensor.updater_core.attributes.current_version }}

inner mesa
#

two were disabled by default

amber hull
#

Not sure how I can pull just the version number into my markdown card.

inner mesa
#

the state?

#

easy

amber hull
#

Tried | HassOS | {{ state.sensor.home_assistant_operating_system_version }} and this does not work

inner mesa
#

it's not what the docs say

#

{{ states('sensor.home_assistant_operating_system_version') }}

#

suggest reading that link

marble jackal
amber hull
#

Rob's answer worked. I had tried using states.sensor.home_assistant_operating_system_version and it was not working.

inner mesa
#

right, because it's not correct. you're missing .state, as TheFes mentioned

amber hull
#

At the end?

inner mesa
#

the link explains

amber hull
#

Got it. Thanks.

bright quarry
lyric crown
#

quote it

#

rgb_color: "{{ ... }}"

#

also looks like an extra ] maybe

bright quarry
lyric crown
#

same error?

#

try rgb_color: "{{ [ range(0,256) | random, range(0,256) | random, range(0,256) | random ] }}"

bright quarry
#

that works, ty. 🙂

marble jackal
pastel moon
marble jackal
#

You'll need a loop to add light. to each entity in your variable, which seems a bit much for this

pastel moon
#

That could work. But in the description for entity_id, it says a string, or a list of strings as input?

#

and yes, this is a proof of concept script to learn this, so may seem a bit too much like this

slate forum
#

Howdy ya'll!
I got stuck with this one 😦

{% if is_state('sensor.washer', 'off') %}
Standby
{% else %}
Time Remaining: {{% state_attr('sensor.washer', 'remain_time') %}}
{% endif %}

#

basically trying to have the dishwasher say "Standby" if its off, or show Time Remaining when its on

pastel moon
#

anyone know how to do this? #templates-archived message Why is the docs talking of "list of strings" as value for 'entity_id' if some kind of loop is still needed?

marble jackal
marble jackal
#

To make a list of light entities out of your current variable, you would need something like

{% set ns = namespace(lights = []) %}
{% for item in light %}
  {% set ns.lights = ns.lights + [ 'light.' ~ item ] %}
{% endfor %}
{{ ns.lights }}
pastel moon
#

Awesome! Than you, will try this 🙂

pastel moon
#

WoW. Finally got it working as I need. Thanks much @marble jackal !

round pecan
#

I'm using {{ states("binary_sensor.window_contact") }} to display on my dashboard the state of the window sensor, but if shows on/off. Is there any method/function to use to display open/closed as it does if I use a entity or button card ? So I don't need to write if else statemant, or is that the only way?

inner mesa
#

There's no way to access the translated values via a template

rigid chasm
#

hi guys. i am trying figure out how to count lights sensors on within groups.

#

i got this sensor who counts all light

#

sensor:

  • platform: template
    sensors:
    count_lights:
    friendly_name: "Count Of Lights"
    value_template: >-
    {{ states.light | list | count }}
#

but how do i create sensor that will count lights on

marble jackal
#

{{ states.light | selectattr('state', 'eq', 'on') | list | count }}

rigid chasm
#

ok thanks that works but if i have a light.group let's say kitchen how do i point to that?

inner mesa
#

{{ expand(state_attr('light.kitchen', 'entity_id'))|selectattr('state', 'eq', 'on')|list|count }}

#

or maybe you can now just directly expand the light group? I don't have any and don't know

rigid chasm
#

thanks alot guys i got this now

marble jackal
#

You can expand light groups directly

#
{{ expand('light.kitchen')|selectattr('state', 'eq', 'on')|list|count }}
quaint flame
#

is there a way to track the history of a template sensor? i'd like to see what the value was say 24hrs ago. heres my sensor: ```

  • sensor:
    • name: "thor"
      state: >
      {{
      ( states('input_number.thor_daily_increase') | float | round(2)) *
      ( states('sensor.cryptoinfo_price_thor_usd') | float | round(2))
      }}
      attributes:
      number: >
      {{ ( states('input_number.thor_daily_increase') | float | round (2)) }}
      unit_of_measurement: "$"
hallow pebble
#

I have a automation that triggers on all available motion and door/window sensors when I am not at home and send me a notification. For various reasons I am not interested in the entities name or friendly name that triggered the automation, but in the area the entity id is related to. However I am struggling to find the correct template to find the area name assigned. So far I tried {{ area_name ('trigger.entity_id') }} and also {{ area_name ('trigger.to_state.name') }} but both return 'None'. It seems that the copied trigger entity does not belong to the area of the originating entity.

mighty ledge
hallow pebble
mighty ledge
#

Templates are designed to frustrate you

quaint flame
marble jackal
#

The state of 24h ago should be stored in your database

quaint flame
#

what database

marble jackal
#

The one of Home Assistant, unless you excluded this sensor from the recorder

quaint flame
#

i have not. could i set that as a attribute? how would i enter that?

marble jackal
#

I can't help you with the code to get it out though, I don't know much SQL

quaint flame
#

tyvm its a start

teal peak
#

Hi everyone, I need some help with a template to count the number of lights that are on in my house. I currently have this one :
{{ states.light|selectattr('state', 'eq', 'on') | list | length }}

#

It was okay until I added lights group through the UI, because they are created in the light domain
I think the only difference between a proper light and a light group is that the latter has an entity_id attribute
How could I exclude these?

inner mesa
#

I thought a solution was already provided for that

#

For someone else, apparently

low blaze
#

Is it possible to create a template switch? I'd like to make a switch that turns on/off multiple entities as one. Do I need to make it manually or is there a format that will just take the entity names and be done?

inner mesa
#

but it sounds like you actually want a group

low blaze
#

what are the advantages?

inner mesa
#

It groups entities together to control them together, which sounds like what you asked for

low blaze
#

yes it looks like a better option

#

template switches seem to be powerful, but yes a group makes more sense

#

when I put ```
switch:

  • platform: group
    name: "T1 All Clip Fans"
    entities:
    • switch.t1_clip_fans
    • switch.t1_clipfan_upper```
#

into groups.yaml

#

I get: Invalid config for [group]: value should be a string for dictionary value @ data['group']['switch']['entities']. Got None. (See /config/configuration.yaml, line 8).

#

groups.yaml is in config.yaml as a group - is this why ?

inner mesa
#

that doesn't belong in groups.yaml

#

it's a switch

#

it's probably easier for you to just create it in the UI

low blaze
#

is it a helper choice?

#

I see it in helpers

#

thx

marble jackal
low blaze
#

ok I got it from the wiki directly on the groups integration

soft flare
#

So since the new release (2022.4) it is possible to 'hide' entities. Does anyone know if it is possible to filter entities when they are hidden?

#

I actually don't think this is possible because 'Hidden' (or 'Disabled' for that matter) is not an attribute of the entity.

formal ember
#

Hey all. Have created two sensors to convert MB to GB, but they end up showing as KB....

- sensor:
    - name: "NBN Download GB"
      unit_of_measurement: "GB"
      state: >-
        {{ (states('sensor.nbn_downloaded') | filesizeformat(GB)) }}
- sensor:
    - name: "NBN Upload GB"
      unit_of_measurement: "GB"
      state: >-
        {{ (states('sensor.nbn_uploaded') | filesizeformat(GB)) }}
#

Any ideas why it would do that?

inner mesa
#

Probably needs to be a string?

#

GB is a variable name

rose scroll
#

If I'm understanding the Jinja docs for the filesizeformat filter, you can't force it to report the filesize in a certain order of magnitude. It will report it to the order of magnitude that makes the most sense from a human readability POV.

inner mesa
#

Actually, I don't see that it takes that argument at all

#

Right

rose scroll
#

Yup. Only takes the filesize value and whether you want the true binary size.

#

If you specifically want it in GB, just math it?

formal ember
teal peak
ember coyote
#

hey guys.
I was thinking of starting with light groups, but realized thats gonna mess up this template:
'{{ states.light|selectattr("state", "equalto", "on")|list|length }}'<

#

does anyone have an idea on how to subtract the number of turned on light groups to get the right number of turned on lights? 😄

inner mesa
#

Immediately above your post

marble jackal
#

Seems to be quite popular to count the number of lights which are on

ember coyote
#

Awesome. Thanks @inner mesa

teal peak
silent barnBOT