#templates-archived

1 messages · Page 128 of 1

sharp bone
#

I am trying to template my vacuum robot to get the room list from a template as the room numbers change from time to time. I have tried https://paste.ubuntu.com/p/pkRQsvqfyh/ but it only cleans room 0 on the list and i am not sure why

#

It looks like i am getting a comma separated list back but it only cleans the first room in the list then says cleaning complete.

hearty mica
#

I'm using a paper-button-row that has an icon and I'd like to add temperature from another entity. I saw that i can use jinja2 to pull the state of a thermometer i have in HA but I want to add the degree Fahrenheit at the end, how can I achieve that?

#

I am displaying the temperature with this: {{ states(''sensor.philip_sensor_temperature'') }} how can I add the units at the end?

pine musk
#

a quote for the ages:Tinkerer — Today at 1:50 PM
Quotes... you're missing quotes

blazing wagon
#

any way to get a name from an entity id?

#

trying to get the name of an entity from trigger.entity_id

dreamy sinew
#

trigger.name ?

inner mesa
#

Or trigger.to_state.name

waxen rune
#

I have a template that list all unavailable entities {{ states | selectattr("state", "in", ["unavailable"]) | map(attribute="name") | list | join(", ") }}
That works fine, but I'd like to show the name of the device - and only once - instead of the friendly name for every entity. Is that possible?

inner mesa
#

So you want the name and not the friendly_name (if it’s set)?

#

If so, why?

#

Oh, you want the name of the device that the entity comes from?

#

I don’t think that’s possible from a template.

waxen rune
#

Exactly so. Would be neat in the GUI. And ok, thanks anyway.

inner mesa
#

Devices were bolted on later and I don’t think they’re exposed in Jinja (yet?)

pastel moon
#

going nuts over this calculation. I'd want the end result to be an integer... Please help

#
{% set dim_light1 = ' | int / 2 | round(0)' if (states('sensor.period_of_day') in ['day', 'morning', 'evening']) else ' | int' %}
{% set d = (states('sensor.brightness_hallway') + dim_light1) %}
{{ d }}
inner mesa
#

States are strings

#

Add |float

pastel moon
#

ah, tried with int, which didn't work. will try

inner mesa
#
{% set d = (states('sensor.brightness_hallway')|float + dim_light1) %}
#

Oh, you’re trying to put a set of filters into a variable? Does that even work?

#

I would assume not

pastel moon
#

I am trying to divide the value returned from sensor.brightness_hallway pending the state of sensor.period_of_day...

#

the start value will differ so static values would not work

inner mesa
#

Right, but I doubt you can put filters (I.e., logic) into a variable like that

pastel moon
#

No, agreed. It does not seem to be interpreted as I need them.

inner mesa
#

You’d need some sort of eval() or similar

pastel moon
#

Ah? Jinja can do that??

inner mesa
#

Maybe? Don’t know

#

I would just repeat it with the proper filters based on the time of day. You’re not really saving much

#

You can use a variable for the state to shorten it

pastel moon
#

true

#

I will have to rethink this I guess. Thanks 🙂

slow vine
#

I have a template that is returning ['00:00:00', '00:50:00', '05:40:00', '09:00:00', '18:50:00', '22:40:00'] I want to know how to return each one seperately. i.e. using a for loop. Can this be done?
I am using https://github.com/nielsfaber/scheduler-component that is returning that array.

inner mesa
#

Yes, there’s an example in the default text in devtools -> Templates

#

Depends on what you want to do with each item

slow vine
#

I looked at the example. I did not see what I need, I am getting those times from a state_attr I want to be able to know that eg state_attr('switch.schedule_ac_schedule', 'times',)[1] is 00:50:00 and that there are 6 times.

#

I tried:```
{% for i in state_attr('switch.schedule_ac_schedule', 'times') %}
{{ state_attr('switch.schedule_ac_schedule', 'times',)[i] }}
{% endfor %}

inner mesa
#

Again, depends on what you want to do with them

#

The loop in the example doesn’t use an index, it iterates through a list

#

Go back and look again

slow vine
#

I want to be able to reference the actions that match the times. state_attr('switch.schedule_ac_schedule', 'actions',)

#

How do I use an index?

#

Sorry for being thick-headed I'll try to look again and figure it out.

inner mesa
#

that's what I meant about "what you want to do with it". If you want to match two lists based on indices, then looping on an index may be the best way to do it

slow vine
#

How can I loop on an index? I'm trying to figure it out. I'm poking in the dark because I don't know what to do.

inner mesa
#

this matches up two lists:

#
{% for day in state_attr('weather.upstairs', 'forecast') -%}
  {{ day.condition ~ state_attr('weather.downstairs', 'forecast')[loop.index-1].condition }}
{%- endfor %}
#

the general concept is iterate through one list and index into the other

slow vine
#

ok. working on it. Thanks.

#

Got it. Thanks so much.

rancid copper
#

thanks for reply, the update is every 60 second if there is a updated value

slow vine
#

loop.index is what I needed, But even if I found it I would have been thrown off from the fact that the index starts at 1 but is index[0]....

inner mesa
#

I got tripped up by that first and then added the "-1"

fossil venture
rancid copper
#

ok, but i integrate the sensor before midnight, it will reset the next day at the same time. But since I would need a sensor that would give me a value for the previous day, I would not have solved anything like this, since the irrigation would start at 05:00 the sensor would have already reset, is that correct?

fossil venture
#

No. You're still not getting it. If you set the max age of the statistics sensor to 24 hours it can cross midnight. If you read the stats sensor at 5am it will give you the max value for a 24 time period to 5am the day before. Not to midnight.

rancid copper
#

ok thanks, now I understand! 😅

pulsar glacier
#

What exactly does the following line do... is default something user defined.. or is it some built in function in jinja?

{% set attributes = states.sensor.template_sidebar.attributes | default %}```
ivory delta
#

Default is a filter. They're a Jinja thing and well documented on the Jinja site.

edgy umbra
#

Is it possible to make a group or template that show which doors have been open/closed instead of showing open/closed in the history log.

dreamy sinew
#

definitely possible

#

either with both or just a template

#

little easier with both

edgy umbra
#

Any change to show or explain how? Tried for hours making this but don’t succeed.

#

Already have a group.doors.

dreamy sinew
#

{{ expand(state_attr('group.doors', 'entity_id'))|selectattr('state', 'eq', 'on')|map(attribute='name')|list }}

#

might need to adjust that state check

edgy umbra
#

Already tried that but the thing is it won’t show a history on my card, instead it shows a colored bar…

#

And I can’t use this in a binary_sensor or add a device_class to the template.

dreamy sinew
#

right

#

that wasn't in the AC of your question

#

you might need to do a |join(', ') at the end to make it text

#

it might render then

edgy umbra
#

Yeah sorry about that. It’s just strange that a simple thing like that isn’t possible. 🙂

#

Yep but that way it shows open/closed instead of the door name(s).

dreamy sinew
#

trying to use this for something in particular?

edgy umbra
#

Yeah I made a single custom button card that shows the state of my doors and if all are open it shows all doors open. If I now use the more-info to view the history it shows just a colored bar instead of the usual history with which doors have been openende/closed (like a normal card with a single entity will do).

dreamy sinew
#

could do this to force it:

{{ ', '.join(doors) if doors|length > 0 else 'Closed' }}```
#

that way there's always something returned

#

so then you'll have an entity that will always have the names

#

group itself will be on if any of the doors are open

#

use the 2 together to inform

edgy umbra
#

Thanks! Will give it a try in a template and see if this will show the history log instead of the colored bar.

dreamy sinew
#

you'll probably still get a colored bar but there should be text in there

edgy umbra
#

Oh, that’s what I already have accomplished. 🙂

#

Maybe I just have to forget that nice history view. 😉

dreamy sinew
#

i mean, there are only 2 ways to render data there. Colored bars for states or graphs for numeric sensors

edgy umbra
#

Can’t post a screenshot here I see but what I mean is a history log like a single entity that shows all the states from the entity, like frontdoor closed 10pm, opened 11pm, etc.

dreamy sinew
#

you'd need to look at the lines for the entities themselves

edgy umbra
#

Yeah if I press the entity in the colored bar I can see it but really like that quick overview log from a single entity.

#

Maybe it something I can ask to implement…

dreamy sinew
#

i think if you want something more complex you're going to have to start looking at graphana

edgy umbra
#

Thanks for your time and patience, really appreciated! 👍🏻

dreamy sinew
#

np

pulsar glacier
#

is config code enclosed in [[[ ]]] brackets also templating or is that something else? not easy to google for [[[

dreamy sinew
#

Need more context

pulsar glacier
#
          [[[ return entity === undefined ? 'rgba(255, 255, 255, 0.3)' : '#efefef'; ]]]```
#

as an example

dreamy sinew
pulsar glacier
#

cool ty

ivory lily
#

I'm struggling a bit with rounding... If I only do {{states('sensor.somesensor') | round(1) }} it works as I expect it to do, but {{states('sensor.somesensor') |float/100| round(1) }} does not (all decimals show). I'm probably misunderstanding something, but I'm too stupid to figure out what.

jagged obsidian
#

try {{ (states('sensor.somesensor') |float / 100) | round(1) }}

#

you're rounding the 100 currently

ivory lily
#

Oh... thanks.

pastel moon
#

How can I find out what triggered an automation? I was told it could be done with templates?

charred dagger
#

Like, in the automation while it's running, or after the fact?

pastel moon
#

Right, should have mentioned that. While running

charred dagger
pastel moon
#

Cool, would it be possible to determine if it was invoked by another script or manual even?

#

Ok, will do some testing. Thanks for the help! 🙂

charred dagger
#

I like using the system_log.write service for testing out this kind of thing. Then you can print variable contents to the log and see what you've got to work with.

inner mesa
#

but if an automation is "manually" triggered from the UI or via automation.trigger, there's no actual trigger and any references to trigger variables should fail

#

maybe you could detect that with {% if trigger not undefined %} or similar

pastel moon
#

Good advice, and the log service should prove useful, thanks again! 👍

charred dagger
pastel moon
#

default filter?

charred dagger
pastel moon
#

Thanks! Hadn't heard of that before, will check it out! 🙂

#

Sounds really useful, and a great jinja-resource page as well! Thanks a lot! 😄

charred dagger
#

It's the jinja resource. Usually first hit when you type "jinja3" into google too.

ivory delta
#

Also linked to from the pins in here.

charred dagger
#

Oh. You even updated it for 3.0. Nice.

ivory delta
#

Just now. Noticed the link you shared wasn't the same.

charred dagger
#

Hass is running on 3.0 since 21.6 apparently

dreamy sinew
#

also the bot message

silent barnBOT
dreamy sinew
#

goes to latest

neat mesa
#

Hi, very basic question. Trying to understand how to get attributes that are deeper than the root. e.g. {{state_attr('weather.home', 'temperature')}} works and gives me 27.1 which is easy as its only one value.

However {{state_attr('weather.home', 'forecast')}} give me a JSON blob like https://hastebin.com/rurasivuna.yaml how would i go about getting to the data for tomorrow like this https://ibb.co/4tXrwP9 instead of the full JSON blob? (the data is from accuweather)

inner mesa
sonic pelican
#

I'm hoping for some help. I have a fan that really needs a quirk update. However, thats way beyond my skill set. So I'm trying to create a fan template as a bandaid. I've gotten presets working, but I'm failing to understand how to make the percentages work.

silent barnBOT
sonic pelican
#

Oops. Thanks bot! Anyway, that's what I have. But when I slide the percentage input, nothing seems to happen.

sonic pelican
upper sand
#

Can anyone tell me why this line works when I test it in the template developer tool
{{ float( states('sensor.stikkontakt_7_electric_consumed_kwh') ) }}
but when I add it to my script
service: input_number.set_value
target:
entity_id: input_number.vaskemaskin_kwh_forrige
data:
value: '{{ float( states('sensor.stikkontakt_7_electric_consumed_kwh') ) }}'
I get the error message

Failed to call service input_number.set_value. expected float for dictionary value @ data['value']. Got None

ivory delta
#

Your quotes are wrong. The second quote will close the first one, leaving a whole load of gibberish after it.

#

You need to mix quotes. Either use single outside and double inside, or vice versa.

pulsar glacier
#

So.. I have a list of lights i use in a template listed as states.light.name, I really don't want to have to go into the template to update it each time i add or remove a light.. I do have a group with all lights, is there a good way to use that as a source for the list?

inner mesa
#

yes, use expand()

pulsar glacier
#

cool I'll have a look at that

upper sand
upper sand
#

Is there any way to extract a previous state from the history (or otherwise) using templating?

inner mesa
#

The straightforward way is via the from_state of a trigger, but it’s pretty limited. You could also use the SQL sensor, I think

#

But that’s not straightforward

dreamy sinew
#

but the more important question is "what are you trying to accomplish?"

upper sand
#

I have Tibber integration which gives me the hourly electricity rate. Whenever the rate changes I want to use the previous hour's rate to calculate costs on my various appliances.

inner mesa
#

Crossposting this groundbreaking template here by popular demand:

#

@mental coral Here's a template that looks up a friendly_name based on a user_id:
{{ states.person|selectattr('attributes.user_id', 'defined')|selectattr("attributes.user_id", "==", "xxx")|map(attribute="attributes.friendly_name")|list|first|default }}

arctic sorrel
#

Given how often somebody has asked that...

#

(now you just need to edit it to use code markup 😛 )

inner mesa
#

yeah, I guess that was lost in the copy/paste

dreamy sinew
#

its too bad comprehensions aren't a thing in jinja

#
users = {x.attributes['id']: x.attributes['friendly_name'] for x in states.person}
print(users.get(trigger.whatever)
inner mesa
#

I ♥️ comprehensions

ivory delta
#

No comprendo.

inner mesa
#

Mindblowing when I first saw them in python

dreamy sinew
#

they can get you in trouble if you're not careful

#

but list + dict comps are my jam

inner mesa
#

I call them ‘turn 15 lines of code into a single line’ magic

dreamy sinew
#

haha

inner mesa
#

sometimes I go too far 🙂

#
        map = [
            self._get_key(k)
            for k in self._entities[self._object_id][ENTITY_MAP][self._lm.model_name]
        ]

        return {convert_key(k): convert_value(k, data[k]) for k in map if k in data}
dreamy sinew
#

have this gem that i'm kinda proud of

#

or this:

#
        final_payloads.extend(
            [
                {"uri": uri, "devices": {"devices": cat_payloads[i : i + chunk_size]}}
                for i in range(0, len(cat_payloads), chunk_size)
            ]
        )
mighty crystal
#

Hey all! Just a quick question I don't quite understand with the newer templating. I have created sensors for the purpose of taking a value from attribute from an entity. But not quite sure some sensors are shown as "Unavailable", but also will not change even when the data from the referenced entity changes.

#

Hmm... how do you do code formatting here? 🙂

silent barnBOT
mighty crystal
#

Can a guru kindly point out what I have done incorrectly? Is it because those attributes were not ready at the time the template tries to populate the values?

ivory delta
#

We have gurus? 🤔

mighty crystal
#

Hmmm.... wiser ones 🙂

mighty crystal
ivory delta
#

No, and don't tag me...

mighty crystal
#

No worries mate!

mighty ledge
#

The docs cover this btw

#

In the examples

mighty crystal
#

Thanks for answering my question petro. I thought the "sensors" format is legacy config format? Do you mind pointing out to the doc with this particular one by any chance? I did try to search for a bit but couldn't find a reason why.

#

The sensors will populate, but behave differently depending on how many sensors I create, which is bizzare.

inner mesa
#

you are using the "new" format, which is now recommended, but the point is that it's expecting a list of sensors

#

the first example here shows multiple sensors in a list:

#

you can ignore the trigger: section if you don't need it, and just start with - sensor:

mighty crystal
#

Thank you for taking the time to point out!! I did misunderstood the format.

inner mesa
mighty crystal
#

Can template be used in packages?

inner mesa
#

not that style

#

the old style can

mighty crystal
#

Ohhh... that's probably what has let me to do it differently in the first place.

#
  • led
inner mesa
#

the introduction of the new template style has brought all the package users out of the woodwork

mighty crystal
#

May be I should stick to the 'old" style if I want to keep things neat in a package like what I do with climate?

inner mesa
#

all of mine are still the legacy format and I see no need to chagne

mighty crystal
#

Thank you once again for your wisdom.

torn meteor
#

in my config file, if i have ```value_template: |>

{{ don't use me! }}

{{ use me! }}

#

aka, is this the right syntax for this

pastel moon
worn phoenix
#

Hi everyone, im not quite sure where to start but guessing this would be the right channel. it's been quite a few years since i've actively used hass. I have a particle.io shield which controls 4 relays, which controls 4 water-sprinkler channels. I can successfully using curl turn on/off the 4 channels. however im struggeling with how hass has intended to implement this.
Ideally i would like to have the option to turn on/off the channels manually, which led me to Switch, and Template?
I would also like to have an automation, that based on rain report will turn on/off the channels with a timer.

To start with i thought i would just create something basic, like either a "channel 1 on" "channel 1 off" button, or a toggle switch.

I updated configuration.yaml with: https://pastebin.com/zLSHfA9x

I'm not looking for someone to do this for me, just asking for help on what things i should read up on and how to tie them together.

keen sky
#

how to get in template value those two values :

#

The forecast is {{ state_attr('weather.home','???????') }}

keen sky
#

{{ state_attr('weather.home','forecast')[0].condition}}

hollow girder
#

hello all i would like to use the icon of one entiy on other with template... i tried "icon_template: "{{ state_attr('cover.livingroom_cover1', 'icon') }}" but does not work

stuck tiger
#

is there a way to limit an attribute output? i have an entry with date and time but only need the date

jagged obsidian
#

There's a way to extract what you need with a template

stuck tiger
#

I have already read the attribute,{state_attr('garbage_sensor_3', 'start_time')} , but I don't know what to do next

#

"2021-06-24 00:00:00" is my output

#

i don´t need "00:00:00"

inner mesa
#

{{ state_attr('sensor.garbage_sensor_3', 'start_time').split(' ')[0] }}

#

your sensor entity name was incomplete, so I guessed

stuck tiger
#

no it was not incomplete there is an variable with the real sensor name

inner mesa
#

ok

stuck tiger
#

thanks that works

inner mesa
#

then you shouldn't have quoted it

stuck tiger
#

i rewrite an blueprint to work for me, it was wrote from an other guy

inner mesa
#

ok. my point is that 'garbage_sensor_3' in state_attr('garbage_sensor_3', 'start_time') isn't referencing a variable

stuck tiger
#

ok

#

ok now we have to wait until the event happens, it should be ready next week wednesday

acoustic arch
#
      - conditions:
          - condition: template
            value_template: '{{ trigger.entity_id == "sensor.v1_badkamer_switch_nr_1" }}'
#

how can i rewrite this to match ON state

#

im not familair with the syntax

inner mesa
#

Lots of examples there

acoustic arch
#

so i have 2 switches hooked up to sensors. both have an ON and OFF state

#

i would like 4 conditions.
sw1 ON
sw1 OFF
sw2 ON
sw2 OFF

#

because then i can disable a motion sensor automation messing up with light on timer

#

(i think)

dreamy sinew
#

probably overthinking it

#

Automation 1:
2 state triggers
s1 to on
s2 to on
actions
start timer
turn on light

#

Automation 2
1 state trigger:
motion to on
condition: timer idle
actions: turn on light
(optional): restart timer

#

Automation 3:
1 state trigger: motion to off
condition: timer idle
action: turn off light

#

Automation 4:
event trigger: timer.finished
condition: motion off
action: turn off light

#

2 and 3 can be combined with choose in actions

#

all of this can be done without templates actually

nocturne nexus
#

Hi. I'm working on using templating for the first time. I'm still pretty new to HA. I'm very close, but trying to do a while statement that watches the device that was involved in the trigger. Can anyone help me understand what I need to change?

silent barnBOT
inner mesa
nocturne nexus
#

I think everything works great except line 22 to stop the repeating only while the triggered sensor is reporting wet.

#

*only when the triggered sensor stops reporting wet

formal ember
#

hey templaters....

#

I want to create a sensor that shows how much my energy consumption is costing. I know its a sensor that is the multiplication of the power consumed (kWh) by the cost per kWh, but no idea where to start with making the template. any help would be great.

fossil venture
#

value_template "{{ ( states('sensor.your_kwh_sensor')|float * states('input_number.your_cost_per_kwh')|float )|round(2) }}"

formal ember
#

thanks Tom, and the input_number, I am not 100% sure how to set that up, it has a min 0 and max 100 value as default, but unsure where I should be putting the $ value there...

#

in the UI anyway...

fossil venture
#

Does it not have a 'Unit of Measurement' field?

formal ember
#

oh, thought that was for $/kWh

fossil venture
#

The template above is for $/kWh. If you use cents/kWh change it to this: value_template "{{ ( (states('sensor.your_kwh_sensor')|float * states('input_number.your_cost_per_kwh')|float ) / 100 )|round(2) }}"

formal ember
#

i am guessing I've done this wrong

fossil venture
#

You don't get charged between $1 and $100 per kWh !! You get charged something like 29c per kWh. So either change the min and max to 0-1 and enter the cost as 0.29 or leave it as is and change the unit of measurement to c/kWh. In both cases don't put a step size (it's optional) and change the type from slider to input field to allow you to type in a value.

formal ember
#

right now I get it.... have hit input field though and nothing has changed...

fossil venture
#

Reload helpers?

formal ember
#

oh step size?

#

derp

#

also, 0.296879 is my rate, that would be $ no?

fossil venture
#

Yes

#

So just change the min and max and use the first template

formal ember
#

perfect

#

lets give it a crack

#

hmmm, its returning 0.0

#

value_template "{{ ( states('sensor.kitchen_fridge_smartplug_energy_total')|float * states('input_number.energy_cost')|float )|round(2) }}"

fossil venture
#

Did you put a number in the input number?

formal ember
#

gonna go out a limb here and say I have stuffed that yeah?

fossil venture
#

The imgur URL? Yes 😆

formal ember
#

fmd

#

haven't even had 3 tins tonight....

#

oh f me....

#

i just realised...

#

thats better

#

i thought you meant that the pic was showing i had entered the wrong settings

fossil venture
#

Delete the step size. You aren't going to get a price increase of exactly that value. Now put the input number entity in Lovelace and fill out the value there.

formal ember
#

you beauty, all working now

nocturne nexus
#

Hi. I've been struggling for a few days to understand how to use a template. I've done a lot of reading, searching and can't figure it out. I'm probably missing some simple concept...

#

I'm trying to set a routine to warn of water leaks without typing in every leak sensor.

#

I think I have it working as desired except for line 22 isn't doing what I want it to do.

#

Maybe instead of saying, while that triggered water sensor is wet do xxxxxx, I should be saying while ANY water sensor is wet do xxxxxx? Is someone able to help me with what syntax I would use for that?

inner mesa
#

it all looks a bit over-complicated

#

rather than triggering on a state_changed event, just use a state trigger

#

then trigger.to_state.state, trigger.to_state.entity_id, trigger.to_state.name

#

that's what it's designed for

nocturne nexus
#

I have not seen the Alert function. I'll take a look. Thank you!!!

inner mesa
#

but to address your concern about line 22, the state key isn't under entity_id

#

you did it right earlier in the template: trigger.event.data.new_state.state

#

if you're using the state_changed event, which I wouldn't recommend.

deft sail
#

Hello all, trying to learn to combine my entities for a Shelly1 that cycles my garage door, and a 433mhz magnetic reed switch that shows whether the door is closed full or not closed fully. Managed to get the following code and all seems to work well except, at first the icon was an exterior window, I changed it to mdi:garage, but it won't show it as open like my other garage door does. Anyone know how to do this? I'm assuming I need to somehow show a different icon for each state but I can't seem to find how to do that. Thanks
cover:

  • platform: template
    covers:
    garage_door:
    friendly_name: "Lower Garage Door"
    unique_id: "2021061901"
    value_template: "{{ is_state('binary_sensor.lower_garage_door', 'on') }}"
    open_cover:
    service: script.open_lower_garage_door
    close_cover:
    service: script.close_lower_garage_door
inner mesa
nocturne nexus
inner mesa
#

Yes

nocturne nexus
#

Got it. Thank you!

deft sail
inner mesa
#

this is from my cover template:

#
        icon_template: >-
          {% if is_state('binary_sensor.garage_door_sensor', 'off') %}
            mdi:garage-open
          {% else %}
            mdi:garage
          {% endif %}
#

petro mentions the device_class: garage option in the second post

deft sail
nocturne nexus
inner mesa
#

Yes, you’d need an automation for that. No reason to manually implement the alert there, though

nocturne nexus
#

So setup a template of any leak sensor to trigger the automation that will call the valve to close and also call the alert function, right?

#

Or are you saying to just have the alert be totally separate and they would both just trigger off of the same criterial in two separate spaces?

inner mesa
#

The latter. You don’t call an alert

nocturne nexus
#

Ok. My head is still spinning a bit, but I think I'm starting to get it. I'll keep reading/experimenting. Thanks, sir.

inner mesa
#

np. alert encapsulates a lot of functionality, so if it does what you want, you can just use it

nocturne nexus
#

I essentially want a leak to trigger a valve to close, activate a few scenes to turn lights blue, send a leak alert to all of my mobile devices, play an alert on an alexa device every 10 seconds. I want the name of any triggered sensors to be listed in the app notification and spoken on the alexa device. Then once all leaks are cleared, I want to activate scenes to turn lights back to white, send a single leak cleared app notification and have alexa announce that the sensor name is now dry.

#

Would one alert and one single automation make sense for all of that, or would you suggest splitting it up more or something else entirely.

#

Oh, and the valve should open back up too once all sensors are back to dry

#

Seemed much simpler in my mind until I started to type it all out... 🙂

inner mesa
#

that's a bit much for me to work out

nocturne nexus
#

How about this: the alert function will not activate scenes, close valves, send TTS notices to alexa, right?

#

So I could maybe work though those in an automation and then just do the app notifications via alerts. That sound like I'm headed in the right direction?

inner mesa
#

yes

nocturne nexus
#

THx

nocturne nexus
#

So if, on an automation, I try to trigger on "State" it is asking for an entity ID. But I want my trigger to be any sensor switching to "on" that has a device class of moisture.

#

Is that possible to do? That is what a "template" is referred to as in HA, right?

inner mesa
nocturne nexus
#

So what would I fill in on the "entity" field of the trigger to have it look at all moisture sensors instead of a single entity or having to manually list each one individually? I feel like there is some simple thing I am missing/not grasping with this concept... And once I get that, I'll be on my way...

inner mesa
#

template triggers don't have an entity_id field

nocturne nexus
#

It's the entity field on the automation that I'm referring to.

#

the automation trigger

inner mesa
#

I get that, but if you're using a template trigger, it doesn't have one

nocturne nexus
#

I keep googling this thinking there has to be someone else that has already done what I'm trying to do and surprised I'm not finding anything.

inner mesa
#

you have to determine how you're identifying the entities that you want to monitor

nocturne nexus
#

I think, simply put, I want to create an automation trigger of any moisture sensor triggering.

#

going from off to on

#

device class of moisture

#

I keep seeing people listing every single sensor, but I want a way to have it use any of them with a certain device class

#

so if I add/remove one later the automation will still work.

#

Make sense?

inner mesa
#

{{ states|selectattr("attributes.device_class", "==", "moisture")|selectattr("state", "==", "on")|list|length > 0}}

#

that will trigger if any entity of device_class moisture is "on"

#

and a similar construct can be used to iterate through that list to generate a comma-separate list of entities, for instance with |join(', ')

nocturne nexus
#

Again, thank you! Is there some place that I might find real world examples of people with setups like this? I feel like I am just not searching for the right terminology or something... I hate bugging you with all of these questions, but really appreciate your patience!

inner mesa
#

the forum is usually the best place for examples. I didn't see any specific to your use case in a quick search, but it's not uncommon and I expect that there are some examples there

#

{{ states|selectattr("attributes.device_class", "==", "moisture")|selectattr("state", "==", "on")|map(attribute="name")|join(', ') }}

#

Espresso Machine, Water Heater, Fridge, Master Vanity, Rachio v3 rain sensor, Upstairs Humidifier

oak quail
#

Can you use templates in the snapshot_entities: part of a scene.create service call? I'm trying to use a light group there, so I don't have to constantly update my scripts whenever something changes to my setup (e.g. I get a new light). Just using the group there gives weird behaviour, where it gets and saves the average from all the lights in the group.

#

So when one light is blue and another is red, the scene contains two light that are set to purple :/

#

Expanding the light group with a template would work nicely, since then only the group configuration needs changing when a new light is bought, but it seems I can't get it to work properly

inner mesa
#

It’s part of data:, so it should work

#

You have to either output a comma-separated string of entities or a list

oak quail
#

I currently have this {{expand(state_attr('light.bedroom', 'entity_id'))|map(attribute='entity_id')|list}}

#

which outputs

inner mesa
#

and it doesn't work?

oak quail
#

nope

inner mesa
#

seems like a weird template, but the output looks okay. What does your actual call look like?

oak quail
#

oh wait... I thought it needed quotes around the template, turns out it didn't 😅

#

it works now!

blazing wagon
#

how do I return the current time in 12hr form? (6:02 PM)

inner mesa
#

{{ now().strftime("%I:%M %p") }}

uneven pendant
#

Ok I have limited coding experience mostly LPC. But im trying to get an automation to fire with a random string from a list.

Like when x happens. Call service
Restful.service.random...

And in the rest web hook it want them URL to be one of about five. And I dont see a clear way to randomize these with a built in command

ivory delta
#

@uneven pendant You'd use a template. Use a list and the random filter.

young jacinth
#

hi,
i want to use a template in a time_pattern trigger. the automation should trigger every interval seconds.

- platform: time_pattern
  seconds: '/{{ /interval }}'
#

i get an error here 😫 i can't get the syntax right

inner mesa
#

That’s not supported

young jacinth
#

damn

#

so there is no way to trigger an automation per templated interval?

inner mesa
#

You could use a template trigger that tests the time via now()

#

But. it only runs every minute

#

Or, you can use a fixed time trigger and a condition template to decide if the time is interesting

#

But in general, wanting to use a time_pattern trigger often indicates that you haven’t really thought through the problem and identified the actual triggering event that makes sense

#

It’s a trap that people accustomed to more transitional programming languages often fall into. For event based systems, looping/polling is rarely the best solution

young jacinth
#

iam building a blueprint for adapting lights over time based on sun position (i know adaptive lighting exist but i dont want to use it)
the idea is to let the lights adapt everytime they turn on and after a certain amount of time

#

the % sun position is calculated by sunset and sunrise
using sun.sun elevation attribute to trigger the automation may be a good idea

inner mesa
#

If you don’t plan to do anything unless the elevation changes, yes

young jacinth
#

the problem is that the sun.sun sensor only reports elevation changes every couple of minutes

#

another option would be to use a loop

inner mesa
#

Gack

young jacinth
#

gack? rubber_duck

mint dome
#

hi - does google home not support the command "stop" for covers within HA?

#

I have the blinds programmed for open, close, and stop and open and close work fine but google home says device is already stopped when I try to stop it

inner mesa
thorny snow
#

anyone know how to convert from color_temp to 565 RGB in a template?

#

I found how to go from RBG to 565 RGB, but lights don't always have rgb_color so templates die when lights use color_temp instead

thorny snow
#

I guess I'll just map some values and approximate

pulsar glacier
#

if i want to test a template from a script that recieves a data_template: value from an automation call, in the template tool.. how can i simulate the content of that data_template??

formal ember
#
      value_template: "{{ ( states('sensor.kitchen_fridge_smartplug_energy_total')|float * states('input_number.energy_cost')|float )|round(2) }}"
    dishwasher_cost_total:
      value_template: "{{ ( states('sensor.kitchen_dishwasher_smartplug_energy_total')|float * states('input_number.energy_cost')|float )|round(2) }}"
    server_cost_total:
      value_template: "{{ ( states('sensor.server_smartplug_energy_total')|float * states('input_number.energy_cost')|float )|round(2) }}"```

I would like to add these three sensors together into a 'total total' sensor - how do I add them in a template though? And is there a specific area in the docs this is mentioned? I could not find it in this area https://www.home-assistant.io/integrations/template/
formal ember
#

or am I better off using a group?

fossil venture
#

Groups do not add up sensors. Al you need is value_template: "{{ states('sensor.fridge_cost_total')|float + states('sensor.dishwasher_cost_total')|float + states('sensor.server_cost_total')|float }}"

formal ember
#

a simple plus, who would have thought

dreamy sinew
#

it could get even easier

#

{{ [states('sensor.fridge_cost_total'), states('sensor.dishwasher_cost_total'), states('sensor.server_cost_total')]|map('float')|sum|round(2) }}
Proof:
{{ ["4", "5.5", "10"]|map('float')|sum }}
-> 19.5
Could probably simplify further if you use a group

inner mesa
pulsar glacier
#

ok

#

thanks

dreamy sinew
#

sorry, mixed threads there, cleaned up my response

#

group example:
{{ expand(state_attr('group.my_group', 'entity_id'))|map('state')|map('float')|sum|round(2) }}

north acorn
#

Is it possible to create a template title for the notify service call? Basically I want the title to return the name of the user that has activated the service-call. I couldn't find anything regarding that in the template docs or notify docs. Or if it's possible in the message that would be great too.

inner mesa
#

anything that's under data: can be templated

north acorn
#

do you have an idea what the syntax might be? I tried {{user}} but that only works with markdown afaik

inner mesa
#

~share your service call

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

inner mesa
#

"user" is just a random variable name

north acorn
#

the service call is part of a button-card tap_action

#

so I added that to the paste just to be safe

inner mesa
north acorn
#

well, it's the template engine right?

#

I want to use it for more than only the button-card

inner mesa
#

the frontend doesn't natively handle templates, so it's up to the individual card to do it, and they all do it differently or not at all

#

the custom button card does support templates there, for instance

#

but I don't think the default, built-in button card does

north acorn
#

ah ok, gotcha

tidal heart
#

I have a brainfart! I can't for the love of it remember how I do a countdown template from an input_datetime'

#

Like hours and minutes left

inner mesa
#

relative_time

#

it's only for a datetime in the past, though

tidal heart
#

Oh

#

Yeah I have an next alarm that is a datetime so I'm looking for "Wake you up in Xh"

inner mesa
#

you can just do datetime math

tidal heart
#

{{((states('input_datetime.morgon_alarm')|as_timestamp|int - now()|as_timestamp|int)/60)|int}}

This seems to do it for minutes

inner mesa
#

yep. you could also use strptime() to convert back into a datetime, assign the datetime difference to a variable, and do .hour(), .minute(), etc.

#

I suspect

#

working with datetime values is not fun

tidal heart
#

No it's rocket science to me, I'm not a programmer 🙂

inner mesa
#

that doesn't work anyway, so ignore

#

it always turns into an exercise in mashing on teh keyboard in the template devtool

tidal heart
#

Here is an example if someone looking for this {% if states('input_boolean.vackning') == 'on' %} {% set time = ((states('input_datetime.morgon_alarm')|as_timestamp|int - now()|as_timestamp|int)/60)|int %} {% set hours = ((time | int / 60) | string).split('.')[0] %} {% set minutes = time | int % 60 %} {% if hours == '0' %} Väcker dig om {{ minutes }} minuter {% else %} Väcker dig om {{hours}} timmar och {{minutes}} minuter {% endif %} {% else %} {% endif %}

inner mesa
#

good job! I look at that and think "there must be a better way..."

tidal heart
inner mesa
#

you probably don't want the empty {% else %}

#

it'll lead to an error

tidal heart
#

Thanks! I'm off to bed, have a nice day/night

thorny snow
#

Is there a built in clamp/constrain/bounds function?

inner mesa
#

I don't think so. something like this works: {{ max(min_value, min(value, max_value)) }}

fossil venture
#

Tarras showed me this version which I thought was a neater solution: {{ ( [min_value, value, max_value]|sort )[1] }}

thorny snow
#

well dang

#

that's simple and elegant

#

wait. that's only maxes

#

right?

fossil venture
#

Nope it bounds between min_value and max_value

#

Once sorted the list will be in increasing order. Then the middle value is picked.

thorny snow
#

OH.. because it takes the middle item in [1]

inner mesa
#

That’s an interesting solution

dreamy sinew
#

did that PR for native types for input_datetime ever get merged?

inner mesa
#

no, got squashed

#

Paulus killed it because datetime isn't serializable

#

apparently that's bad for the recorder

granite pendant
#

I’ve been directed here, although looking at post history doesn’t seem like this is what I’m looking for….

I’m trying to create a script, or blueprint, or something that allows me to separate out a conditional on an entity state to either directly update brightens or set a zwave parameter for the brightness to be honored when it’s next turned on. A repeatable macro of sorts.

This is what I have in the Script, but I have so far been unable to templatize passing in the target entity (e.g. light). Several forum posts suggest this cannot be done, but @arctic sorrel said they do this successfully, so I’m hoping others have examples they would be willing to share.

https://paste.ubuntu.com/p/YCw34qTYRJ/

All I need is the ability to execute steps given a variable device and brightness values so that I can set my own rules from separate automations. I explicitly do not want to hardcode all of the potential permutations in one giant glob of unmaintainable scripting. Thanks for any help anyone can provide.

charred dagger
#

That seems like it should work if you put that sequence in a script and replace entity_id: light.bathroom_light with entity_id: "{{ entity }}" everywhere.
Then you can call that script with yaml service: script.set_brightness data: entity: light.bathroom_light

#

I think templating should work in target too, but if it doesn't you can probably use the legacy method ofyaml service: ... data: entity_id: like you do with zwave_js.refresh_value.

granite pendant
marble jackal
granite pendant
#

This is what I get from the Script editor…

charred dagger
#

Ok. So the problem is in the condition. Maybe that doesn't support templates.

#

Try a template condition instead. yaml condition: template value_template: "{{ is_state(entity, 'off') }}"

granite pendant
#

Okay, that saved at least. Thank you.
So am I able to select entity and brightness in the UI when creating an Automation? I tried adding fields to the script, but it doesn't seem to be providing any sort of input for them.

#

Ah, looks like selectors were added recently. They haven't made it into the docs; I found the GH merge.

#

Success! Thank you @charred dagger, I really appreciate your direct help.

novel whale
#

Keep getting errors - platform: mqtt
name: "BI Driveway Night Motion"
device_class: motion
state_topic: "Blueiris/Driveway Night"
payload_on: "on"
payload_off: "off"
value_template: "{{value_json.state}}"
off_delay: 30

#

'value_json' is undefined

#

sorry, unable to see the upload image so I cannot show the actual config and error

inner mesa
#

it says this:

#
binary_sensor:
  - platform: mqtt
    name: "FDC Motion"
    state_topic: blue_iris/binary_sensor/fdc_motion/state
    payload_on: "ON"
    payload_off: "OFF"
    device_class: motion
#

but that was a long time ago. so you need to look at what you're actually getting the from the topic, and make sure you're using the right topic

novel whale
#

Am I limited to upload images on this board...I cannot find the upload button?

finite dune
#

plz use an upload service; imgur etc

novel whale
#

sorry, not sure how-to...anyway to drag and drop?

inner mesa
#

no

novel whale
#

Thanks, let me sort out posting images.

inner mesa
#

then you're not flying blind about what's being published and what you should listen for

valid hatch
crude tartan
#

Why does this always have state = off. I have tested in developer tools and see that I can get both true and false values ```binary_sensor:

  • name: "hasp night mode"
    state: >
    "{{ is_state_attr('alarm_control_panel.area_1', 'arm_up_state', 'fully_armed') and
    is_state('cover.scott_side', 'closed') and
    is_state('cover.elizabeth_side', 'closed') }}"```
valid hatch
#

I think you don't need quotes after the >. Does that make a difference?

crude tartan
valid hatch
#

🤩

#

I guess it was just evaluating the whole template as a string

winter sleet
#

I'm trying to write a template to calculate a "heat index". but I'm getting an error about non-int and floats: http://ix.io/3qNT

#

any ideas what I'm doing wrong?

inner mesa
#

a couple of things

#

first, this is just converting 100 to a float: {% set R = states('sensor.living_room_humidity') * 100 | float %}

#

{% set R = states('sensor.living_room_humidity')|float * 100 %}

#

that might be all, unless it doesn't like the giant multi-line expression at the end

winter sleet
#

ah ok

#

yes! that seems to have fixed it

#

thank you

#

same error with the round(1) I think

#

do i have to restart HA to load the modified template?

inner mesa
#

you can reload template entities from configuration -> Server Controls. And yes, the expression preceding |round(1) needs to have parens around it

#

you're currently rounding the last R

winter sleet
#

yeah

inner mesa
#

or just use a weather service or station that reports it natively (like my Weatherflow)

winter sleet
#

i'm calculating it based on a sensor in my office

inner mesa
winter sleet
#

i want to see how the Aircon temp/humidity affects my perception of temperature. and if Heat Index corelates

#

just for the fun of it

inner mesa
#

it would be cool if there was a "template sensor blueprint"

winter sleet
#

hmmm something still wrong with my formula. i'm getting -70751.6 😂

#

definitely not that cold in here

inner mesa
#

I'm not at all surprised that that monstrosity doesn't work 🙂

winter sleet
#

are relative humidity percentages stored internally as 0.50 or 50 for example?

inner mesa
#

it's just the state, which is a string

#

it doesn't know that it's a percentage

winter sleet
#

ah

#

thanks

#

perfect, that fixed it

#

can i delete the history in the heat index sensor somehow? as it now has some -70000 entries

#

which messes up the chart

inner mesa
#

you can prune an entity

#

it was just added in teh last few releases

winter sleet
#

oh nice

#

so back in the paste, you can see the average temperature calculation: {{ ((bmp280 + sht3xd) / 2) | round(1) }}

#

every so often it returns 0 for some reason

inner mesa
#

one of those sensors is probably "unavailable" or similar sometimes

winter sleet
#

so how do i account for that in the formula?

inner mesa
#

you can give it a default with |default(xxx), but probably not what you want

winter sleet
#

any way to track why the sensor is unavailable at that moment?

inner mesa
#

you'll have to debug that with the integration that's providing that sensor

winter sleet
inner mesa
#

yes, I get it 🙂

winter sleet
#

hmmm

#

how would I get a log or anything about it when it happens?

inner mesa
silent barnBOT
winter sleet
#

thanks RobC

#

got to do real work now. that's a question for another day

hearty prairie
#

I've multiple integrations that show up as "Devices" such as a Synology NAS. These devices may have some interesting attributes that I want to use in a template such as Model number or version. Is there a way to get this info through templates? I mean.. a device doesn't seem to be/have a entity I can address... Basically I'm looking for the parent of a entity

mighty ledge
plain zinc
#

Template question, I ran across some syntax that I do not understand: https://paste.ubuntu.com/p/3fSdmGvsZp/
I can't seem to find some documentation on it either.

Specifically the turn_on: &toggle_coffee and the turn_off: *toggle_coffee

Is the & and addressing definition and the * a pointer type reference?

(This is from the latest hassio podcast, was just looking at the show notes design here https://www.hackster.io/xbmcnut/hack-a-breville-espresso-machine-for-home-assistant-control-ec5213)

It really does appear that one references the other, I just can't find any docs about it.

brisk temple
#

it's YAML anchors

plain zinc
#

ah I just wasn't googling the right term. My C programmer was making me search references

#

Anchors!!, thanks @brisk temple

#

Very cool.

wanton cloud
#

I'm using the MQTT HVAC climate panel to control my split unit ACs, but there's a mode that's missing (side to side swing), anyway I can add that mode to the Climate panel?

acoustic arch
#

hello. im looking for a template:
on each buttonpush i would like to increment input number. thats a call service ofcourse.

But how can cycle the steps? i would like to go to the lowest step after the highest step

#

its for a light. i would like to cycle the dimmersteps

#

so push once for 10 20 30 40 50 60 70 80 90 100 brightness. and then push for 10

#

its also a brightness_step but how to go to the beginning

valid hatch
#

Is it possible to force HA to record the state of an unchanged sensor template? I've done some looking around and found homeassistant.update_entity and maybe it does update, but it still doesn't record if the sensor is unchanged. For plotting purposes, it would be helpful to record the last value of a sensor just before it shifts to unavailable. I've found many threads of people looking for similar functionality and resorting to hacks like changing the value just a bit before a change (https://community.home-assistant.io/t/updating-template-sensor-on-attribute-change/106263/16). I wonder if there's an alternative!

valid hatch
dreamy sinew
#

@acoustic archwonder if a counter would work here

#

but input number could work

acoustic arch
#

I'll have a look! Thx

#

Counter looks pretty good. It has a reset as well. I'll go mess with it this evening

thorny cedar
#

Hi guys, I have sort of a dynamic "template within a template" but I can't figure out why it's returning a value of 0:
{{ state_attr('light.{{ states("input_text.lifx_device_lower") }}', 'brightness')|float }}
I'm trying to get the brightness state attribute of dynamically changing light names, which, as you can see, is dictated by the state of an input_text.lifx_device_lower. The input_text's state is currently "lightstrip", whose brightness value is 76, but this template returns 0. If I replace {{ states("input_text.lifx_device_lower") }} with the actual name of the light (lightstrip) it indeed returns 76.

acoustic arch
# dreamy sinew <@!370447748954062850>wonder if a counter would work here

not sure if i may tag you or not...

https://pastebin.com/v4SLmLUS

got this base automation running so far:

This base works:
longpress: HOLD mqqt --> toggles on/off
shortpress: TOGGLE mqtt --> this increments the counter
If counter >5 then reset to 1. SO i got 5 settings

but now for the actual brightness settings per counter value. I would like to add my own values to each value since not all lights are liniair in brightness it seems. I would like to add another choose action on TOGGLE:
A. Numaric value is always < > value. and not =
B State quotes the number and it doesnt work

any ideas?

acoustic arch
#

It looks templatish to get it working

mighty ledge
mighty ledge
#

Can be done without templates

acoustic arch
#

can it be done in ui/yaml?

#

if counter=1 then call service
if counter=2 then call service
etc?

mighty ledge
mighty ledge
acoustic arch
#

i know. But
A. i would like to add my own brightness values to eacht counter, since not all light are liniair
B. Reset to counter 1 after 5

#

so short presses: 1 2 3 4 5 1 2 etc

#

hold is off or toggle, dunno yet

mighty ledge
#

Yeah just have a choose that sees if the input number is at the your max and if it is set it to your min

acoustic arch
#

so all i need ( i think ) is a working choose action

#

thats where i break down

#

condition: numeric value?

#

condition: template?

mighty ledge
#

Either

#

No, you don’t need a template

#

State

acoustic arch
#

numeric is above or below... not IS

mighty ledge
#

Or numeric state

#

Then use state

acoustic arch
#

state is a string?

mighty ledge
#

So?

acoustic arch
#

not a value...? doesnt it matter?

mighty ledge
#

“1” is still “1”

acoustic arch
#

guess not then haha

#

i couldnt get state to work. but ill try again in a super simple automation first

#

thx. at least i know it SHOULD work

#

back to the drawing board

thorny snow
#

hello i have a sensor for a window that sends an on off signal every time i open or close the window. now i want so craet a sensor that works like a switch. firs on of signal = sensor on second off and so on could anyone help me please i have no idea how that works

#

pls help me

jagged obsidian
#

you should make more sense first

#

a switch implies you can toggle it, a sensor only shows the state

thorny snow
#

sorry i want a sensor that shows open on the first impulse of another sensor and on the second impulse close and so one

jagged obsidian
#

and what is that other sensor? what states does it have?

plain zinc
thorny snow
thorny snow
fossil venture
#

So substitute its entity id where I wrote binary_sensor.your_window_sensor_here

gentle cape
#

Sorry, I must have missed clicked

fossil venture
#

ping_tuya_motion_sensor_master_bedroom is not an entity id. binary_sensor.ping_tuya_motion_sensor_master_bedroom is.

thorny snow
#

thx

fossil venture
#

Be aware that you may have to flip the state of the window toggle sensor initially (it might not be synchronised with the actual physical state of the window).

thorny snow
#

it always shows closed

fossil venture
#

You will also need a dash before sensor:

#

Above.

thorny snow
fossil venture
#

"Does not work" is not very descriptive. Did you do a configuration check? Did it pass? Are there errors in the log?

thorny snow
#

i restarted the server an checked the config

fossil venture
#

And....

thorny snow
#

and the log shows no error

#

the binary switch works

fossil venture
#

What switch? You have no switch only binary sensors

thorny snow
#

soory the sensor

fossil venture
#

Which sensor?

thorny snow
#

but the window sensor does not work

#

binary_sensor.ping_tuya_motion_sensor_master_bedroom this one works

#

the values are on and off

fossil venture
#

Is that the actual entity id? Look in developer tools / states menu

thorny snow
#

yes but i can rename it to something shorter

fossil venture
#

Looking at your forum post it should be binary_sensor.ping_tuya_motion_sensor_maeleigh_pir_bathroom

thorny snow
#

but the sensor platform is ping and we use state is this the problem ?

fossil venture
#

I don't understand the question.

thorny snow
#

sec i send the config

fossil venture
#

A binary ping sensor has on/off states which we can use. In fact I just read that the template can resolve to on/off or true/false so we could just use states() instead of is_state().

thorny snow
fossil venture
#

This: state: "{{ is_state('sensor.window_toggle', 'off') }}" should be state: "{{ is_state('binary_sensor.window_toggle', 'off') }}"

#

My mistake.

#

Sorry.

#

You can also just use: state: "{{ states('binary_sensor.window_toggle') }}" if you want.

#

Slightly simpler.

thorny snow
#

it works thankeyou verry much

#

if i want so learn how that works where can i find that information

thorny snow
#

thanks

thorny snow
#

I am trying to take a device's state "[255, 214, 123]" and use it in a template like I have for another devices attribute: {%- set red=(state_attr('light.dining_light',"rgb_color")[0] * brightness)|int -%} and I am failing. When I do this: "{% set red=color_rbg.split(',')[0] %}" I get "[255"

#

Is the best way to "|replace" the stuff I don't want, or a better way to get the RGB out of [255, 214, 123]?

inner mesa
#

it's not clear what you got with state_attr('light.dining_light',"rgb_color")[0]

#

the attribute is most likely a list

#

you just said "I am failing"

thorny snow
#

yes, RGB, as a list

inner mesa
#

so what do you get with what I put above?

thorny snow
#

255

inner mesa
#

that's what you want, right?

#

or you just want the whole list to use elsewhere?

thorny snow
#

state_attr is all working for the dining light, yes, but that's an attribute... the state of this color sensor is [255, 214, 123]

#

I am just trying to do the same thing with a state instead of an attribute

inner mesa
#

ok, that wasn't clear at all 🙂

thorny snow
#

I am not sure how to word this

#

I can pull from an attribute correctly, but when I try to use the state of another device, I am not able to split it correctly

inner mesa
#

yeah, I don't see a convenient way to take a list-formatted-as-string and turn it into a real list without that string manipulation nonsense

thorny snow
#

my best bet I guess is to make the state into an RGB array

#

or attributes which I can work with

inner mesa
#

this gives you a list of strings: {{ "[255, 100, 10]"[1:-1].split(", ") }}

#

magic: {{ "[255, 100, 10]"[1:-1].split(", ")|map('int')|list }}

green karma
#

Hi all, I'm trying to migrate to the "new" recommended sensor template format and having some issues. I currently have something like this for each one:

- unique_id: washer_amps
  name: "{{ state_attr('switch.washer','friendly_name') }} Current"
  state: "{{ state_attr('switch.washer','current_a') }}"
  unit_of_measurement: "A"

I expected the unique_id to be used as the entity_id by default, but that doesn't seem to be the case. Right now, the name fills in correctly, but the entity_id is coming out as "none_current", seemingly based on the name.

Is there any way to set the default entity_id in the template or do I just have to go through each one in the UI and override it there?

charred dagger
#

{% set red = (state_attr('light.dining_light', 'rgb_color') | from_json)[0] | int %}

inner mesa
#

that's the just "red", right?

charred dagger
#

yes. Updated

inner mesa
#

not sure what they're actually looking for, but it's in there somewhere

thorny snow
#

that already works... what doesn't work is this: {% set color_rbg = states('sensor.global_rgb') %} The state is: [255, 214, 123]

inner mesa
#

yes

thorny snow
#

I am trying to use the RGB similar to the state_attr above

inner mesa
#

Thomas gave you a way to get just red, I gave you a way to convert to a list that you can index into, just like the attribute

charred dagger
#

@green karma unique_id is for making sure the entity id doesn't change if the name changes, even after a restart. It does not affect the initial entity_id in any way.

gloomy bear
#

Can anybody tell me why this font size has no effect on my template widget from the android app?
<font size="7">{{ states('sensor.my_weather_station_temp')}} and {{ states('weather.home')}}</font>

inner mesa
#

and using the from_json trick: {{ states('sensor.global_rgb')|from_json|map('int')|list }}

charred dagger
#

You probably get the name none_current because switch.washer didn't exist yet when your sensor was created during the boot process.

thorny snow
#
{% set color_rbg = states('sensor.global_rgb') %}
{% set red = (color_rbg | from_json)[0] | int %}
#

there... thanks!

green karma
#

@charred dagger Ah I see. I'll just enter them in the UI then. Thanks for the help

charred dagger
#

That'd probably be the easiest way.

gloomy bear
charred dagger
#

Sounds more like an issue for #android-archived, but I notice you're mixing ' and ", so you get:
the string '<font size="7">{{ states(' followed by the undefined variable sensor.my_weather_station_temp followed by the string ')}} and {{ states(' etc.

gloomy bear
#

Oh I was just trying to format it for discord

#

There are no ' on either side in the real thing

#

Fixed it

winter sleet
#

I made a template to calculate a Heat Index - it mostly works but occasionally gets a spurious result causing the graph to have sharp lines in it. I had a similar problem with average temperature calculation which i fixed with a min-max entity. what can I do for this one? http://ix.io/3r2C https://imgur.com/rLCrmLe

fossil venture
#

You probably need to sanitise your template input data. Any filters like |float or |int will return 0 if the sensor state they are applied to is unknown. You can overcome this with an availability template.

winter sleet
#

thanks tom

#

I'll look into that

fossil venture
#

If you link a pastebin copy of your template here we can help.

manic onyx
#

hi guys. Can someone please help me with templates/json?
I have a device that returns its state attribute as a number, but I want to display it as text.

dreamy sinew
#

gonna need more context

manic onyx
#

type: entities
entities:

  • entity: vacuum.viaomi_s9_vacuum_robot_cleaner
    type: custom:multiple-entity-row
    name: RoboVac Viomi S9
    show_state: false
    entities:
    • attribute: fan_speed
      name: Fan speed
    • attribute: battery_level
      name: Battery
      unit: '%'
    • attribute: vacuum.status
      name: Status
#

the last one "vacuum.status" returns an integer value. I want to be able to display a corresponding text value instead

dreamy sinew
#

what do you want it to say?

manic onyx
#

{'value': 0, 'description': 'Sleep'}
{'value': 1, 'description': 'Idle'}
{'value': 2, 'description': 'Paused'}
{'value': 3, 'description': 'Go Charging'}
{'value': 4, 'description': 'Charging'}
{'value': 5, 'description': 'Sweeping'}
{'value': 6, 'description': 'Sweeping and Mopping'}
{'value': 7, 'description': 'Mopping'}

inner mesa
#

Then you want a template sensor to transform the value

manic onyx
#

yeah, I tried, but got lost 🙂

#

I could not even get the original value to display

#

I tried to use it like that:
- attribute: template
value_template: "{{ state_attr('vacuum.viaomi_s9_vacuum_robot_cleaner', 'vacuum.status') }}"

inner mesa
#

That’s…not how that works

manic onyx
#

🙂

#

I am learning 🙂

#

have OneNote running just for all of that

inner mesa
manic onyx
#

It very brief. I dont understant how to use the examples given

#

every time I try to do any data transform, I get told that I need to create a new entity just for that transformed value 😦

inner mesa
#

Unless you use a card that allows for templates, yes

#

Not a big deal

manic onyx
#

every time it happens, something twists inside me 🙂 Dont know why 🙂

fossil venture
#

If that does not work (untested) someone else will have to help. I'm off to bed.

inner mesa
#

that's pretty much what I was going to do

#

attribute names usually don't look like vacuum.status with a ".", so check on that

#

works fine with appropriate values in the template editor. 'vacuum.viaomi_s9_vacuum_robot_cleaner'->'vacuum.xiaomi_s9_vacuum_robot_cleaner'

manic onyx
#

the "vacuum.status" attribute is just a name that integration chose to use. Can be anything else

inner mesa
#

Sure, just atypical

manic onyx
#

it worked great, guys! Thanks you again 🙂

somber burrow
#

hi, i'm trying to make a template in an automation that select randomly an effect for the light, but it doesn't seems correct

inner mesa
#

that syntax is incorrect

#
  - service: light.turn_on
    target:
      device_id: bc76ab1fc1dc1de6dd2238c28f1a57f7
    data:
      effect: "{{ (''Morning Sky'', ''Lightscape'', ''Vaporwave'' )|random }}"
somber burrow
#

it tells me this "Message malformed: invalid template (TemplateSyntaxError: expected token ')', got 'Morning') for dictionary value @ data['action'][0]['data']"

#

ok it was the ' '

dreamy sinew
#

{{ ['Morning Sky', 'Lightscape', 'Vaporwave']|random }}

inner mesa
#

a tuple won't work?

dreamy sinew
#

you need a list, not a tuple

inner mesa
#

I didn't try it

#

well, there ya go

somber burrow
#

ok, let me try this

dreamy sinew
#

also, the double single quotes are a dumb thing that the UI does, you don't need to replicate it

inner mesa
#

this works for me, BTW: {{ ('foo', 'bar', 'blah')|random }}

somber burrow
#

yeah, i through that if it does in that way it probably would be correct

dreamy sinew
#

odd

inner mesa
#

I amused myself for like 10s

dreamy sinew
#

might be something weird with the double quotes then

somber burrow
#

ok, it didn't changed

inner mesa
#

what issue do you have now?

somber burrow
#

probably the action is not correct to set the effect

#

i tried using the service to change the effect , maybe should i try to use device?

inner mesa
#

maybe you should try the entity_id: for the light

#

device actions are voodoo

somber burrow
#

ok, i'm checking this

#

it doesn't seem to work

#

this is just the action

inner mesa
#

does it support those effects?

#

with those names, including the case?

somber burrow
inner mesa
#

you probably need to look in devtools -> States to see what it says in the attributes

somber burrow
#

probably it's just me but i'm quite confused

inner mesa
#

can you manually set the effect using devtools -> Services?

somber burrow
#

wait, maybe now it works

#

one moment

#

yes, it goes

#

and maybe i found the problem

#

i tried to use before the device id of the lights with homekit and not the one i've made in configuration file

#

now it seems working!

#

thanks you for the assistance

rancid jewel
#

Hi I am trying to integrate the UK transport API into HA. It provides a sensor with the next train information which I am able to create a card for. But there is an attribute to the sensor which has the next 25 trains information. is it possible to list the next three trains using the template. Sorry I'm a newbie and dont have a lot of experience

arctic elm
#

Is there a way to determine an entity’s integration to use in a template?

dreamy sinew
#

Not typically

trail estuary
#

I don't understand the error I am getting with this template. ZeroDivisionError: float division by zero

{{ ((states('sensor.guest_room_heater_daily_energy') | float / states('sensor.tibber_daily_energy_total') | float) * 100) | round(2) }}
inner mesa
#

what's the value of states('sensor.tibber_daily_energy_total')?

trail estuary
#

Oh.... Unknown
That would certainly explain that....

inner mesa
#

indeed

trail estuary
#

Great work! 😉

inner mesa
#

I do what I can

earnest cosmos
#

Hi, guys! Need to verify this:

Invalid config for [plant]: expected int for dictionary value @ data['plant']['lavendel']['min_moisture']. Got '{{ states.input_number.planter_lavendel_fukt.state | int }}' 

The state of the input number is: "12.0", and I would think I convert this to an integer using

min_moisture: "{{ states.input_number.planter_terrasse_fukt.state | int }}"

Where am I missing here?

inner mesa
#

~share the whole yaml definition

silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

earnest cosmos
inner mesa
#

I see no evidence in the docs that it supports templates

earnest cosmos
#

So that’s why then. I was assuming the same setup for a template would work all over in HA.

inner mesa
#

Only if the key is under data:, service:, or target:, or if the docs mention it

dull dune
#

I have a pulse counter that measures waterflow, and I've successfully calibrated it to show it's state in liters/minute. Now I'm trying to use the utility meter integration to calculate a total for a day and a week, but they are way off and I think it's because the sensor is displaying 40 litres/minute with a sensor update rate of 10 seconds... Is there any way I can template this to be accurate? I'm thinking the template should increment the sensor value (40litres/min) every minute, then, the total should be accurate

fossil venture
#

The utility meter will not take any flow rate sensor. Only an accumulated use sensor (Litres). You need to use the Riemann sum integral sensor to convert your flow rate into total flow then use that in the utility meter. https://www.home-assistant.io/integrations/integration/

manic onyx
#

hi everyone 🙂 still on my vacuum integration.
I need to make 2 switches that take their state (on/off) from the vacuum entity attribute value (0 or 1) and if switched manually will send the command back to the vacuum.
Now, I kind of guess that I need to use a template switch. But do I need to make new binary sensor for each of the attributes I want to switch?
Say, I have 2 attribues that I want switches for:

  • collect_dust
  • repeat_vacuum
    Do I create 2 binary sensors (collect_dust_state and repeat_vacuum_state) with the values of these attributes?
    But I dont understand how to use the template switch. Like what do I put under
    switch:
    • platform: template
      switches:
      ??? switch name?
      And do I create a script that sends the command to vacuum (toggle_vacuum_dust_collection and toggle_repeat_vacuum) and use it under turn on/turn off sections?
fossil venture
#

Which vacuum is this for?

manic onyx
#

Viomi S9

#

or v18:1

fossil venture
#

So you are using a custom integration for this? The reason I ask is that there is no vacuum service to change these values.

manic onyx
#

yes, its a custom integration for all Mi devices.

#

ok, more specific question 🙂
If I have this script:
toggle_vacuum_bin_auto_empty:
alias: Toggle vacuum bin auto empty
sequence:
- service: xiaomi_miot.set_miot_property
data:
entity_id: vacuum.viaomi_s9_vacuum_robot_cleaner
did: 378451326
siid: 4
aiid: 41
value: 0

How do I set "value" to be the opposite value of binary_sensor.vacuum_auto_bin_empty?

#

*should be piid, not aiid

fossil venture
#

value: "{{ 0 if is_state('binary_sensor.vacuum_auto_bin_empty', 'on') else 1 }}"

manic onyx
#

too easy 🙂 I guess for the switch I should probably be using 2 different scripts - one for ON and one for OFF

signal canyon
#

Hi, I was wondering how to get the state of a specific day in the weather forcast for the weather entity

#

i want to make a template that gets the next days high, low, and condition

#

but it is a little confusing because I know that I can get the state of "forecast" but then it just gives me a bunch of days, i need to get the specific temperature from a specific day, how would that be done? please ping me if responding

#

Oh nevermind, i found it in a video

dull dune
grim geyser
#

Hello everyone. I’m trying to toggle my climate.office_ac entity by using the tap action in custom button card. Climate. Can’t be toggles which is where I’m stuck. I can’t seem to make a template to toggle the climate entity. Any help would be appreciated. Thanks.

thorny snow
#

Hi folks!
rebuild Frenks 2$ dorbell
https://frenck.dev/diy-smart-doorbell-for-just-2-dollar/
now I try to see on the UI when somone last rang - but I have my issues with the template.
I tryed

{{ relative_time(states.switch.doorbell_button.last_changed) }}
or 
{{ state.switch.doorbell_button.last_changed }} 

but its always empty in the template editor

#

...

#

nvm

#

binary_sensor.doorbell_button 🤦‍♂️

honest solar
#

I have the following attributes in a rest sensor entity which returns a JSON. How do I extract the value of station_id: S114 ?

timestamp: '2021-06-28T11:00:00+08:00'
readings:
  - station_id: S77
    value: 0
  - station_id: S109
    value: 0
  - station_id: S90
    value: 0
  - station_id: S114
    value: 0
  - station_id: S11
    value: 0
  - station_id: S50
#

Im stucked at {{ state_attr('sensor.myentity', 'readings') }} but unsure how to get the value based on the key value.

inner mesa
#

Add [0][‘station_id’] and so on

honest solar
#

But the position may change. I do not want to use the index position.

inner mesa
#

Oh, I see

honest solar
#

I want to get the value where station_id = S114

inner mesa
#

I understand

#

there's probably a better way, but this works:

#

{{ (data|selectattr("station_id", "eq", "S114")|list|first)['value'] }}

#

{{ data|selectattr("station_id", "eq", "S114")|map(attribute="value")|first }}

#

so... {{ state_attr('sensor.myentity', 'readings')|selectattr("station_id", "eq", "S114")|map(attribute="value")|first }}

honest solar
#

Nice! That works. I am very new to Jinja and still trying to learn. The above codes is just mindblown

inner mesa
#

I enjoy these problems far more than the DNS/can't boot issues we usually get in #330990055533576204 🙂

pastel moon
#

Hi... I have this script https://paste.ubuntu.com/p/SQXKrR9tPj/ which is triggered by an automation. I want to use variables for the value templates inside the choose block. This does not seem to work (is accepted by all checks), light goes out despite humidity is well above threshold. What am I doing wrong?

mighty ledge
charred dagger
#

or make it "string" Never mind. That won't help.

mighty ledge
#

Lol yeah, that’s what I meant but it capitalized the s

#

On mobile 😕

#

Took me like 2 months to find the ` on the iOS keyboard

charred dagger
#

Lot's of secrets in that keyboard. I found them quickly because there's an é in my name...

mighty ledge
#

Ah, yeah I did not. I’ve never used the accents until then

#

I think I accidentally found the accents then had an epiphany.

charred dagger
#

What I meant was that string: "template" may not be valid, but "string": "template" may be. But as I edited to, that won't work here.

mighty ledge
#

I think what’s happening is that it doesn’t even attempt to replace existing variables from the variable dict when they conflict in the jinja namespace

charred dagger
#

I later realized that string is not reserved in yaml. There it's !!string.

pastel moon
#

Thanks, just in case I changed it to msg, though that part seemed to work. It's the above & below that did not. Those did not accept the value I fed them, demanded a float, and adding |float didn't work either. That's when I changed it into a value template, but perhaps missed out on the functionality I needed in the process... :S

charred dagger
#

I see.

#
- conditions:                                                                                                                                                
  - condition: template                                                                                                                                    
    value_template: "{{ threshold }}"``` From what I can tell `threshold` is 75, right?
#

So what you're saying here is "if 75, do this".

#

Later you also wait for 75 to occur before continuing.

#

You probably want {{ (humidity | int) < threshold }} or something.

unreal merlin
#

Howdy 🙂

#

is there a way to list sensors per integration?

#

I'm trying to get a battery monitor in place for my sensors, and I'd love to grab Zigbee and Zwave, but unlikely that I care about stuff my latop / phone reports as battery level

pastel moon
charred dagger
#

What does it say?

pastel moon
#

Nothing at all, it just don't do what I'd expect, never enters those conditions

#

But works well if written as numeric_state conditions

unreal merlin
#

is there some one-pager on rejectattr options? I'd need to do something like rejectattr(state|float, 'le', 50)

#

trying to avoid running a loop on things I don't have to

unreal merlin
#

Thank you!

charred dagger
pastel moon
#

I don't get an error. When running it in DevTools;

{% set threshold = 75 %}
value_template: "{{ threshold }}"
#

gives value_template: "75"

#

If I remove the quotes it wont pass ha core check: "ERROR:homeassistant.util.yaml.loader:invalid key: "OrderedDict([('threshold', None)])"

inner mesa
#

You can’t separate the template like that

pastel moon
#

Separate?

inner mesa
#
value_template: >-
  {% set threshold = 75 %}
  {{ threshold }}
pastel moon
#

Aha, that was olny for test in devtools

inner mesa
#

Ok

earnest cosmos
#

Hi All!
I have a script that runs every 30 minute from an automation. The script checks if the tomatoes need watering, by comparing the humidity sensor in the soil against the wanted value for soil humidity.

Lavendel, measured: 10
Lavendel, target: 5
Lavendel, need water? True

Obviousely there is an error in the logics here. I test using a condition template to carry on it the test is TRUE

- condition: template
  value_template: "{{ (states.sensor.planter_lavendel_fukt | int) < (states.input_number.planter_lavendel_fukt.state | int) }}"

What am I missing ?

inner mesa
#

You’re missing the .state in the first one

#

And you should be using states()

dreamy sinew
#

{{ states('sensor.sensor_1')|int < states ('input_number.whatever')|int }}

earnest cosmos
#

Obviousely. Typo when pasting here

inner mesa
#

Typos happen during a paste?

earnest cosmos
#

Sure not, but while editing before hitting publish here 🙂

inner mesa
#

What are we supposed to evaluate?

earnest cosmos
#

I have this, then

Lavendel need water? {{ states('sensor.planter_tomater_fukt') | int < states('input_number.planter_lavendel_fukt') | int }}

#

Evaluate two numbers to see if the humidity sensor reports lower value than the wanted value set by th input__number

pastel moon
brittle turtle
#

Hi, not sure if it's the right place to ask the question. I'm new in ha and struggling with dynamic token storage and use. I've setup one REST sensor to download authentication token from extrenal service. It's working ok, sensor's state is set to retrieved value (the token). Now I would like to use that token in other REST sensors in "headers". How to do it propery?
Tried ```
(...)
headers:
(...)
X-Gizwits-User-token: states('sensor.hottub_login.state')

inner mesa
#

I don't see any evidence from the docs that templates can be used there

#

it's just a string, or a list of strings

brittle turtle
#

Any idea how can I store token obtained from external API and use it in sensor?

inner mesa
#

someone should file a feature request, if there isn't one already

silent barnBOT
#

If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.

fluid cedar
#

What's the syntax for ANDing two states to get a true/false result?

#

{{ states('binary_sensor.porch_pir_sensor_occupancy') && states('light.porch_light_bulb') }}

#

?

inner mesa
#

states are strings, so ANDing those two things doesn't make sense

#

you want is_state('xxx', 'on') and such

#

that compares the state and returns a boolean, which can be ANDed

fluid cedar
#

OK thanks.

#

{{ is_state('binary_sensor.porch_pir_sensor_occupancy', 'on') && is_state('light.porch_light_bulb', 'on') }}

#

Complains about &.

inner mesa
#

right, it's "and"

fluid cedar
#

cool

#

It works, thanks, is there a document that explains template syntax/funcs ?

inner mesa
#

and it's Jinja

silent barnBOT
vagrant narwhal
silent barnBOT
humble grotto
pastel moon
#

Hi... I asked yesterday for help with this script https://paste.ubuntu.com/p/XdKq7yhmqX/ Never understood why the conditions in the choose block don't work. I don't get any error or message, they are just not run. The commented-out alternative works fine... Please help 🙂

inner mesa
#

{{ threshold }} is curious NR star it’s always true as long as the value isn’t zero

#

So it’s of no use that I can see

pastel moon
#

Aha... But in that case shouldn't it enter the condition?

inner mesa
#

Enter?

#

Conditions are evaluated

#

You mean the sequence?

pastel moon
#

yes

#

The sequence don't run

inner mesa
#

Might not, as it’s looking for a boolean and getting a number

#

Jinja may not treat zero as false and non-zero as true

#

You need a test of some sort

pastel moon
#

So that is what troubles it... That should be easily fixed to have it report true/false. Strange it accepts the number without complaining...

#

Yes, thanks! I will rewrite it to return a boolean instead! Been a headscratcher for some time... 😄

inner mesa
#

It’s not an error, it’s just not what it was looking for. Hard to say what the result would be

#

It’s just not clear what you were planning to do with it. But carry on..

pastel moon
#

What I try to do is for it to run the sequence when the humidity is over the threshold, and by that pausing shutting the light off

#

But now realize I forgot the compare with the sensor...

inner mesa
#

Then that’s the test

pastel moon
#

Exactly, thanks!

unreal merlin
#

(how)? can I sort a group of sensors by state before iterating through them?

ivory delta
#

Check the pins, mb. There's a list of filters on the official Jinja docs.

unreal merlin
#

I've got through a bunch of them, e.g. filtering the entity_ids and sorting them looks all ok, but sorting by state didn't have much I could get going on 😕

#

the base is a group with about 20 entities

ivory delta
#

Did you try the sort filter?

unreal merlin
#

not all of them seem to be int, so I've got to do conversion too in order for |sort to work

ivory delta
#

Then you may need to map everything first so you have sensible values before you sort.

unreal merlin
#

I was playing with something like {% for item in mydict|dictsort(false, 'value') %}

#

so like mapping the entity_id and the value too, so I can then sort it like a hashmap by value?

ivory delta
#

Could you describe in more detail what you're trying to do? I'm sure someone can help build a template for you once you do.

unreal merlin
#

I've got a group with entity_ids that represent power (e.g. battery state of a certain sensor)

#

I've built a template sensor that tells me if anything is below X value

#

and what I'm trying to do is list all of those in ascending order as attributes that are below that value

#

so ideally what I need to do, is: 1) get entities from group 2) sort them by state 3) list them as a single attribute with something like comma separation, nothing fancy (e.g. to know what to replace asap)

#

something like: {% for s in state_attr('group.low_battery_zigbee_sensors', 'entity_id')|dictsort(false, 'value') %}

#

but that obviously doesnt work 😄

mighty ledge
#

Strings “” vrs “3$$;$4$:)8(“

#

Dicts and lists resolve false if they are empty

proper adder
#

hi guys - could someone perhaps help explain the math for a template to me 🤦‍♂️
value_template: "{{(states('sensor.inverter_voltage_analog_a0') | float - 29.5) / 1024 * 3.3 *5|round (2) }}"
This is for a voltage sensor via tasmota (nodemcu) providing an analog value of +-896
The template value I get is: value_template: "13.978271484375"

mighty ledge
#

Parenthesis around everything before the pipe round

unreal merlin
#

the ()|round() mistake I run into every month 😄

unreal merlin
#

reran that, e.g.: {% for s in state_attr('group.low_battery_zigbee_sensors', 'entity_id')|sort(attribute='state') %}
I think it's not actually sorting by the group member's entity_id's state.

#

I'm getting a sorted list back as 100, 100, 100, 91, 100, 66, 100 - while I'd expect 100, 100, 100, 100, 100, 91, 66...

dreamy sinew
#

well, that state_attr just gives you a bunch of entity_ids and not states

#

expand(state_attr('group.whatever', 'entity_id')|map(attribute='state')|list|sort might work

#

actually, this works:

#

{{ expand(entities)|map(attribute='state')|map('float')|sort }}

#

replace entities with your state_attr()

unreal merlin
#

so if I put that within a loop, is there a way to get my entity_id back?

#

for example:

#

{% for s in expand(state_attr('group.low_battery_zigbee_sensors', 'entity_id'))|map(attribute='state')|map('int')|sort
in this case {{ s }} is the actual state, and I'm looping through them in the right order

#

a |map(attribute'entity_id') (as a blind guess) seems to mix things up

dreamy sinew
#

what do you want your output to be?

unreal merlin
#

ideally it's a list of [friendly_name: value, ] so I can easily spot sensors that are due battery replacement

#

something wife understands 😄

#

so the idea was to put this in a loop, and add them to a new list that I can put out as attributes to a template sensor

dreamy sinew
#

try this but the ordering could get weird because of strings

#
{% for state in expand(entities)|sort(attribute='state', reverse=True) -%}
{{ '{}: {}'.format(state.name, state.state) }}
{% endfor %}```
unreal merlin
#

oh... that: {{ '{}: {}'.format(state.name, state.state) }} ... I've seen that in one example but couldn't make much sense out of it

#

yeah this looks close

#

but as you mentioned sort is a bit kooky, I've got like 96, 95, 94, 63, 44, 100, 100, 100, 100

#

let me see if I can tweak that to be something better

#

all I need is to throw off anything thats > 50 really

dreamy sinew
#
{% set ns = namespace(mapped = []) %}
{% for state in expand(entities) -%}
{% set ns.mapped = ns.mapped + [{'name': state.name, 'level': state.state|int}] %}
{% endfor %}
{%- for entity in ns.mapped|selectattr('level', 'gt', 50)|sort(attribute='level') -%}
{{ '{}: {}'.format(entity.name, entity.level) }}
{% endfor %}```
#

that'll do it

unreal merlin
#

that swallows an error when I add my group instead of (entities), e.g. {% for state in expand(state_attr('group.low_battery_zigbee_sensors', 'entity_id')) -%} will fail

dreamy sinew
#

odd, what's the error?

unreal merlin
#

can't see - returns blank, and any template under it stops processing

dreamy sinew
#

doing it in the template tester?

unreal merlin
#

yep

dreamy sinew
#

i don't have any number sensors in a group

#

that's it with a random group though

unreal merlin
#

let me clean that up

dreamy sinew
#

and the gt changed to lt to get all the 0s

#
{% for state in expand(state_attr('group.living_room', 'entity_id')) -%}
{% set ns.mapped = ns.mapped + [{'name': state.name, 'level': state.state|int}] %}
{% endfor %}
{%- for entity in ns.mapped|selectattr('level', 'lt', 50)|sort(attribute='level') -%}
{{ '{}: {}'.format(entity.name, entity.level) }}
{% endfor %}```
unreal merlin
#

oh ok, I reset the template tester and it all seems to work now - not sure what swallowed it before

#

wow nice, now it's gonna take a bit of time for me to understand what exactly is happening there 😄

#

many thanks for your help!

dreamy sinew
#

the namespace thing is because you can't update something that lives outside of the loop from inside

unreal merlin
#

yep, that's clear

dreamy sinew
#

the weird behavior with the ns.mapped = ns.mapped + [] is because .append() doesn't work

unreal merlin
#

this ns.mapped + [{'name': state.name type mapping is the one that needs understanding

#

so that is actually adding new items to the [list]

#

so where does state.name and state.state come from?

dreamy sinew
#

its re-creating the list with the combination of the original + what you're adding

unreal merlin
#

are those actual attributes of the entity_id, e.g. name is "friendly_name" and state is state (value)?

dreamy sinew
#

name and state are properties of the state object that comes out of the expand

unreal merlin
#

oh ok, so what I should definitely read up on is expand

dreamy sinew
#

that's the magic that makes this work

#

also name will return the friendly name if its set or the entity_id if it isn't

unreal merlin
#

oh cool

dreamy sinew
#

the selectattr there filters down the list to the ones you care about

unreal merlin
#

there's a few things I think I can refactor by understanding what expand does

dreamy sinew
#

sort you already had

unreal merlin
#

selectattr and rejectattr are cool - that I've been experimenting with in the past couple of days

dreamy sinew
#

'{}'.format(var) is a python trick for string manipulation

unreal merlin
#

can you explain how the |map(attribute= vs map(int) work exactly?

#

that looked like we're pulling out an attribute and making it int (by mapping to int?)

dreamy sinew
#

map("<filter>") applies that filter to all items in the list
map(attribute="some_value") pulls the attribute "some_value" from all objects in a list and outputs a list of those values

unreal merlin
#

can you map multiple attributes?

inner mesa
#

nope

dreamy sinew
#

i don't think so

inner mesa
#

I just looked it up

unreal merlin
#

e.g. map(attribute="entity_id")|map(attribute... didn't work for me

dreamy sinew
#

would have saved us an extra loop

inner mesa
#

there's a request from 2016 and bunch of people recommending a loop

earnest cosmos
#

Hi, guys!
I need some help pointing me in the right direction for finding this error from the log.
It´s in a scipt, OK, but then searching for some % is hopeless.

Invalid config for [script]: invalid template (TemplateSyntaxError: unexpected '%') for dictionary value @ data['sequence'][1]['data_template']. Got None. (See ?, line ?).