#templates-archived

1 messages Β· Page 23 of 1

mighty ledge
hoary wing
#

can anyone help me with a mushroom template title card?

Id love to show the following when more then 1 persons are watching plex
But the following code doesnt work

{% if is_state("sensor.tautulli_watching", '>1') %}🎬{{ states.sensor.tautulli_watching.state }} persons are watching plex {% endif %}

mighty ledge
hoary wing
#

hero! Thanks very very much

dry lichen
#

hey, i struggling a the state of an entity. I just want the state of an entity but in the same format like in a entity card.
If i use this: { states('switch.xxxxxx') }}
i get only "on" or "off". Is there a way to get the state back like "On" or "Off" and also the translation?

mighty ledge
#

translations are strictly front-end only at the moment

#

You can manually translate it yourself

waxen rune
dry lichen
mighty ledge
#

Not in a backend template

#

@dry lichen ^

waxen rune
# dry lichen is there a way to get the language and translate it in 2 languages?

Not sure if I know what you mean, but If you use lovelace-template-entity-row, it will translate to the current language.
"In evaluated templates the function _(<key>) (underscore) will localize the <key> to the current language. E.g. _(state.binary_sensor.motion.off) will be replaced with Clear if your language is set to English."

dry lichen
# waxen rune Not sure if I know what you mean, but If you use lovelace-template-entity-row, i...

sorry i meant @mighty ledge
i had a quick look at template entity row but for me it is not clear how to use this my card is currenlty like this:
type: custom:mushroom-template-card primary: Fernseher secondary: '' icon: '{{ ''mdi:power-plug'' if is_state(entity, ''on'') else ''mdi:power-plug-off'' }}' icon_color: '{{ ''orange'' if is_state(entity, ''on'') else ''red'' }}' entity: switch.fernseher tap_action: action: toggle layout: vertical
and i want the state in the secondary field

mighty ledge
#

You can't get translations

#

I can't say it enough

#

if you want to use the custom card boneheadfraggle mentioned, you have to completely use that card

#

otherwise, you cannot get translations

#

@dry lichen ^

dry lichen
#

thats what i understand from you petro. I understood that the first you wrote it

mighty ledge
#

Yes, but you keep asking for it

#

if you just want the under the hood state for secondary,

secondary: "{{ states(entity) }}"
dry lichen
#

thank you for clarification

nimble copper
#

Is there a way to convert a sensor value that is a string currency -> a float / int?

E.g. the sensor value is Β£2.40 and I want to get it as a float so 2.40?

mighty ledge
#

is the unit in the string?

nimble copper
#

Yes

mighty ledge
#

if it's always the first character... float(value[1:])

nimble copper
#

Yes.

#

That works. Thank you

#

If the character moved around would there be another way to remove it?

#

May be regex?

silent seal
#

You could also value.replace("Β£","") and cast to a float .

mighty ledge
#

but it's slower

solemn frost
#

value_template: '{{ value | regex_findall("[0-9.]+") | first }}'
That's what I did just the other day with a gas price sensor

silk smelt
#

Are there any Utility Meter experts here? πŸ™‚ I am tracking a device that can go negative. For example -20 one day. Does it start at 0 the day after or does it have to work from -20 if the following measurement is positive?

mighty ledge
#

that'll work jumbers unless it gives you 3423.2342.324234 as a number

#

regex to find a safe number is lengthy

marble jackal
#

If it always has 2 decimals you can do
value | split | select ('is_number') | join | multiply(0.01) 😜

nimble copper
#

Thanks for all the help and tips everyonie!

tepid onyx
#

boneheadfraggle lol

plain magnetBOT
#

@glass veldt I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

that is not a proper template

glass veldt
#

Sorry, I pasted that quickly

inner mesa
#

{% if states('sensor.water_room_offline', '1') %}

glass veldt
#

I am trying to change the color of temperature based on the offline sensor

inner mesa
#

{% if is_state('sensor.water_room_offline', '1') %}

#

you're also listing "red" twice?

#

not a very interesting template πŸ™‚

glass veldt
#

That is just to error catch. I can't get it to go red at all!

inner mesa
#

you're also not introducing a multiline template

glass veldt
#

I will change to different colours once it's working πŸ˜‰

#

I'm a beginner, can you tell lol

inner mesa
#

I don't use card_mod for this, but I would try this

#

we all are at some point

glass veldt
#

I think I actually sent you a DM about this. Sorry about that.

inner mesa
#

color: "{{ iif(is_state('sensor.water_room_offline', '1'), 'red', 'blue') }}"

#

yeah, please just post in the forum

#

I saw that you did that

glass veldt
#

Won't happen again

inner mesa
#

no worries

glass veldt
#

Like this: card_mod:
style: |-
hui-generic-entity-row:
$: |
.text-content:not(.info) {
color: "{{ if(is_state('sensor.water_room_offline', '1'), 'red', 'blue') }}"

        }
inner mesa
#

I'll reiterate that I don't use card_mod for this, so you'll probably get more help in #frontend-archived

#

the template is not the hard part here

#

"iif" not "if"

#

not a typo

glass veldt
#

oh wow, ok lol. Totally thought that was a typoi

random wing
#

It is possible, to get the name from the NFC-Tags based on the ID in the template?`(The name from NFC-Tags tab in Home Assistant under Settings)

glass veldt
nimble copper
#

I have 2x datetime objects. Is there a way to find the difference between the two and represent them in another datetime-like format e.g. HH:MM:SS?

Sample data:

2022-12-29 20:15:38
solemn frost
#
{{ as_datetime("2022-12-29 20:15:38") - as_datetime("2022-12-29 19:55:52") }}
nimble copper
#

Thank you @solemn frost I didn't know you could do datetime addition / subtration like that.

solemn frost
#

If it's more than a day, it'll come out like this: 3 days, 0:19:46

nimble copper
#

Even better!

#

Is the resulting out still a datetime object? Or a string?

inner mesa
#

it's a timedelta object

solemn frost
#

The template page in the dev tools will tell you it's a string, but yeah it's actually a timedelta

plain magnetBOT
#

@turbid breach I converted your message into a file since it's above 15 lines :+1:

turbid breach
inner mesa
#

I expect that it's the previous state of the sensor, not the one that you're setting now

#

oh, and states are all strings, so it will never be 0

#

{% if this.state == '0' %}

#

but if you want to use the current state that you're setting in that definition, you'll need to replicate the logic in the "state" section

turbid breach
spark stirrup
#

This is exactly what i did. Thank you!

copper sedge
#

Im wondering if templates are the best way to create a solution for this, but Im trying to create a multi state sensor to use in automations to determine if:

  • Someone is asleep
  • Everyone is asleep
  • Nobody is asleep
    To use for various lighting automation conditions. The biggest problem Im running into is the scalability of having checks which tell if multiple people are awake or asleep based on presence and phone charging status after a certain time. I want to factor presence in, as lighting automations need to fire even if the other person is out of town or something
#

My 'whiteboard solution' is something like this:

if (person x home and person y home) and (person x phone charging and person y phone chargin) everyone is asleep is true
if (person x home and person y not home) and (person x phone charging) everyone is asleep is true
if (person y home and person x not home) and (person y phone charging) everyone is asleep is true

If (person x home and person y home) and (person x phone charging or person y phone charging) someone is asleep is true

if (person x home and person y home) and (person x phone not charging and person y phone not charging) nobody is asleep.
#

But it really doesn't feel scalable if I need to add another person. Is there a cleaner way to scale it to multiple people, all of whom have their own devices attached to them?

young jacinth
#

good evening everyone

i want to get a list of every entity form the group group.battery_devices that has a state < 10
this is what i tried with no luck
https://pastebin.com/tSV5BFPY

lofty mason
# copper sedge Im wondering if templates are the best way to create a solution for this, but Im...

Probably leveraging groups. You can create a group of "all people home", a group of "some people home", a group of "all phones charging", and a group of "some phones charging". Then adding new people is just adding them to the groups, and you don't touch the logic.

Though I'm not quite sure I follow the implication that anytime someone plugs in their phone they must be asleep, but πŸ€·β€β™‚οΈ

Or actually I see you might need more than that. I would maybe create a per person sensor: "person is away or charging", and then make a group of those to use.

young jacinth
inner mesa
#

the problem with your code is that states are strings and can't be compared directly with numbers

young jacinth
#

ouch
checkin for unavailable entities is fairly easy
but numbers are hard

inner mesa
#

and you can't currently apply a filter to the incoming state without losing the entity_id

#

we desperately need a way to apply a filter to the incoming collection for selectattr and related filters

#

Grab this attribute, apply this filter, then use it with with the test & value

young jacinth
#

this seems to work, thanks alot
would have never figured that one out

inner mesa
#

I kinda hope that somebody else comes along with a more elegant solution...

atomic blade
#

Might've just found a bug (still on .12). state_attr seems to work as a filter in the dev tools template editor, but when I try it on a template sensor I get an error: No filter named 'state_attr'.

#

The fact that it errors I think lines up with the docs. I didn't think it would work, but then it did so I rolled with it. Either way, I'm pretty sure these should be consistent

inner mesa
#

I'll bet I have a PR to fix that

#

One day maybe it'll get in

tepid onyx
#

πŸ‘

marble jackal
muted halo
#

It's still not working but I don't have any error message... juste the entity stay empty.
I would like to have in one entity the attributs starting with android.text* (like android.text_com.android.systemui or android.text_com.facebook.orca) from the mobile entity "sensor.a52s_active_notification_count" whne the value of these attribut are different from 'Bruit dΓ©tectΓ©' or 'avant pleine'
Maybe it's too complicated for home assistant ?

marble jackal
#

well, this was not clear from what you posted before

#

Should be possible, but currently I'm working, and this is quite complex

azure ridge
#

type: entity
entity: sensor.pool_cover_status_unsigned
state_color: false
value_template: '{{ states(''sensor.pool_cover_status_unsigned'') | float / 255 * 100 | float }}'

#

Id like to have that sensor display a value from 0-100%

#

The current values are 0-255, so I setup the value template, but it is somwhow not working. Any ideas?

mighty ledge
mighty ledge
azure ridge
#

any ideas on how to do it otherwise?

mighty ledge
#

make a template sensor

azure ridge
#

How would I do that since its a knx sensor?

mighty ledge
#

I'm not following you

#

you simply create a template sensor and use that in your UI instead of the knx sensor

azure ridge
mighty ledge
#

in yaml, you add a template sensor, which is a separate integration

#

check out the pins at the top of this channel

plain magnetBOT
mighty ledge
#

you already have the template that you posted above, you just need to add it

azure ridge
#

Made it work, thanks alot!

mighty ledge
#

np

marble jackal
#

the | float at the end is not needed BTW

plain magnetBOT
#

@rancid dagger I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

for the second one, you can't use templates in a tap_action

#

use the template in your script itself

rancid dagger
#

but my script might be called by different entities, I need to pass him the right entity too as a variable.. won't I get the same problem there ?

upper mulch
slate raptor
#

I just discovered this. Unreal.

sonic sand
#

Hey,
I’m trying to make something that looks like a SWAKES Sensor counter, but I can’t figure it out by myself.
image

I want to count the number of entities within a group that I have and show also how many of them are in the β€˜On’ state
For example:
I have group.cameras with 3 entities of my cameras, 2 of them are β€˜On’ state and 1 is β€˜Off’ state
So I want to show up in my dashboard 3/2 (3 is the total number of entities within the group, and 2 is the number of β€˜On’ devices within the group).

How do I do that? I want to count my lights and some devices I have.

Thanks for helping!

obtuse zephyr
west marsh
#

try to get the temperature from this in my sensor.yaml whats the mistake?

  • platform: template
    sensors:
    climate.control_zo1
    value_template: "{{ state_attr('climate.control_zo1', 'current_temperature') }}"
    unit_of_measurement: 'Β°C'
    friendly_name: 'Wohnraumtemperature'
    state_class: measurement
    device_class: temperature
plush willow
#

Can this be written in a shorter version? I need a - before every item and each item should be on a new row:

{%- set doors = expand('binary_sensor.deuren_open') | selectattr('state', 'eq', 'on') | map(attribute='name') | list %}
{%- set data = namespace(entities=[]) -%}
{%- for state in doors -%}
{%- set data.entities = data.entities + ['- ' + state] -%}
{%- endfor -%}
{{ data.entities | join("\n") }}

When I do a join in teh first line then the first item doesn't has a - at the start

heavy crown
#
template:
  - sensor:
    - name: "climate_control_zo1"
      state: "{{ state_attr('climate.control_zo1', 'current_temperature') }}"
      unit_of_measurement: "Β°C"
      friendly_name: "Wohnraumtemperature"
#

you should be able to paste this 1-on-1 in Templates (under Development Tools) and see where it works/fails, I have no clue of your 'climate'

#

and seeing ou add 'measurement'...do you only want to have this show the temp?

sonic sand
heavy crown
atomic blade
#

Oh wow expand doesn't work in template sensors either? How have I not run into this before

heavy crown
obtuse zephyr
atomic blade
atomic blade
#

Yeah exactly. Well I mean it is in dev tools. That's what I Rob pointed out above

#

Seems to be a bug

mighty cobalt
#

How do i invert a input in YAML?

#dim Down
- conditions:
- "{{ command == 'down_press' }}"
sequence:
- service: light.turn_on
target: !input light
data:
** brightness_step_pct: !input dimmingIntervall**
transition: 1

this should be negative

timid osprey
#

* -1 ?

inner mesa
#

I know nothing about blueprints

#

or how to incorporate an !input into a template, which is probably what you need to do

mighty cobalt
timid osprey
heavy crown
inner mesa
#

As that's exactly the problem that I set out to fix...

heavy crown
#

ok...thanks then I step out as this is already on the next level πŸ™‚

marble jackal
sweet steppe
#

So I'm just now coming back and revisiting a template I had for a sensor that stopped working awhile ago and see that there's now a new recommended syntax

#

I used to have, in my sensors.yaml:

#
- platform: template
  sensors:
    internet_in_mbps:
      value_template: "{{ (state_attr('sensor.usg_wan_in_stats','change_rate')|float*0.25*(state_attr('sensor.usg_wan_in_stats', 'sampling_size')-1)/1000000)|round(2) }}"
      unit_of_measurement: "MB/s"
      entity_id: sensor.usg_wan_in_stats
#

and am now trying to move that into a new template.yaml:

#
sensor:
  - name: internet_in_mbps
    unit_of_measurement: "MB/s"
    state: "{{ (state_attr('sensor.usg_wan_in_stats','change_rate')|float*0.25*(state_attr('sensor.usg_wan_in_stats', 'sampling_size')-1)/1000000)|round(2) }}"
silent seal
#

- sensor: should be the first line

#

It's a list, not a dictionary πŸ™‚

sweet steppe
#

YAMLKHAAAAAN shakes fist

#

all of the state_attr stuff can stay the same in the state: as it was in the value template before though?

silent seal
#

You may want to set unique_id: internet_in_mbps and set the name to something friendly

#

Yes, you can leave that as is

sweet steppe
#

Hmm, still showing unavailable after a reset. Any way I can find more detailed info about what's failing in it?

silent seal
#

"Reset"? Do you mean reloading the templates?

sweet steppe
#

Well, I restarted HA entirely.

silent seal
#

And if you didn't have the templates.yaml file before your last restart you'd need to restart

#

Ah you did restart. You can just reload the template in developer tools now though, probably.

sweet steppe
#

It's definitely reading in the templates.yaml file as it now shows the pretty name and the unique ID

silent seal
#

Good

sweet steppe
#

and I've verified that the sensor.usg_wan_in_stats sensor has data in it

silent seal
#

Does sensor.usg_wan_in_stats exist?

sweet steppe
#

Exists, and is populated with an integer value that refreshes/increases every 10 seconds

silent seal
#

You may want to try:

    state: >
      {{ (state_attr('sensor.usg_wan_in_stats','change_rate') | float(0) * 0.25 * ( state_attr('sensor.usg_wan_in_stats', 'sampling_size') | int(0) - 1) / 1000000) | round(2) }}
marble jackal
#

Could it be you have a working sensor.internet_in_mbps_2?

sweet steppe
#

Nope, I thought of that, and it did indeed create one, but that is unavailable as well.

silent seal
sweet steppe
#

vscode is saying something about a missed comma between flow collection entries?

marble jackal
#

Does the template work in developer tools > template

sweet steppe
#

It does not appear to. But this is helpful πŸ™‚

marble jackal
#

Well, that explains why it is but working then

#

What's the error there?

sweet steppe
#

no error, it just returns -0.0 as the state

#

although that doesn't explain why the sensor is unavailable

silent seal
#

Well that's due to the defaults

#

But in the dev tools try outputting just {{ state_attr('sensor.usg_wan_in_stats','change_rate') }}

#

And the same with sampling_size, to see which one(s) are empty

sweet steppe
#

Yeah it's weird, it says "None" for both.

#

oh! I wonder if this has to do with the change I had to make to the sensor definition

silent seal
#

Well that's your problem πŸ˜„

sweet steppe
#

HASS complained that the statistics platform needed a state_characteristic attribute set

silent seal
#

Maybe? It depends. But you can look at {{ states('sensor.usg_wan_in_stats') }} to make sure it has something

sweet steppe
#

which it did not previously have or need

#

it definitely has something, if I output {{ states('sensor.usg_wan_in_stats') }} it outputs a number as expected

#

and updates every 10s

silent seal
#

Good!

plain magnetBOT
silent seal
#

You can look into this to see which attributes are available

sweet steppe
#

Those links never work for me, still not sure why.

silent seal
sweet steppe
#

ah, http/https issue. Thanks.

#

Do I now need to specify every state_characteristic I want a statistics sensor to have?

#

or should I be creating a separate statistics sensor for each characteristic?

silent seal
#

What kind of sensor is this?

#

If it's a statistics one, then yes you need to add a sensor for each one you want πŸ™‚

sweet steppe
#

Gotcha. Previously it was just a generic "statistics" sensor and I think it had ALL of them. A recent HA update made it so that was invalid config.

#

So that was perhaps something that changed semi-recently?

silent seal
#

Not in my recent memory. But these attributes must be on a sensor that the statistics integration is using

#

What does your statistics YAML look like?

plain magnetBOT
#

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.

sweet steppe
#

http://pastie.org/p/5DudCbpU0kBiX4zxtycqNa this is what it was. I had put in a state_characteristic=mean just to get it to let me restart HA because it was complaining but I suspect that's what messed up the others

#

going to try creating multiple stat sensors for it

#

with change_sample and change_second

silent seal
sweet steppe
#

Don't update shame me. πŸ™‚

#

(it's possible that the change was made then but it was officially deprecated/started throwing errors recently?)

silent seal
#

Well it was listed in the changes, if you get very behind it can be annoying but is definitely worth checking the breaking changes on every single update you need to do. They are always listed

#

It was an immediate change by the looks of it, but I didn't check the code to make sure

sweet steppe
#

So the long story is that this whole thing broke a very long time ago not because of HA but because of my network. SNMP is not enabled by default on my new gateway so all my stats stopped working. I just manually installed SNMP on the new one and am trying to get it all working again but running into rabbit holes on multiple fronts πŸ™‚

silent seal
#

Rabbit holes are my favourite way to learn and discover new things

#

Be warned: The Discord search is amazing, and excellent at providing new rabbit holes (which may lead to other dimensions πŸ˜‚ )

sweet steppe
#

lol

#

I've gone down enough rabbit holes learning about SNMP OIDs today. πŸ™‚

#

and narrowing down what I want from the 57 interfaces on my router

#

lol

silent seal
#

A mere 57? There are some in this server who would want at least a 0 on the end πŸ€ͺ

sweet steppe
#

This might actually simplify things quite a bit though

#

{{ states('sensor.usg_wan_in_change_rate') | float(0) / 1000000 }} this alone I think should do it

#

if I set state_characteristic: change_second

silent seal
#

Nice!

sweet steppe
#

Hey, thank you very much for your help and insights today @silent seal and also @marble jackal - much appreciated.

silent seal
#

You're welcome! Happy automating!

late wolf
#

`binary_sensor:

  • name: "Has updates?"
    state: >
    {{is_state('update.home_assistant_core_update','on')}}`
    I get missed comma between flor collection entries. Why?
inner mesa
#

I don't understand the question

late wolf
#

I'm getting an error in VSCode and don't understand why. The message is the one above " missed comma between flor collection entries".

inner mesa
#

that just sounds like broken English

late wolf
#

now I'm the one not understanding you

inner mesa
#

this is not an English sentence that makes any sense "missed comma between flor collection entries"

late wolf
#

*flow instead of flor

inner mesa
#

anyway, it seems like you're trying to create a template binary_sensor without using the proper format

late wolf
#

this is inside a templates.yaml file that came from template: !include templates.yaml

inner mesa
#

it's still not right

#
- binary_sensor:
  - name: "Has updates?"
    state: >-
      {{ is_state('update.home_assistant_core_update','on') }}
#

you need a list

#

you had a map

late wolf
#

it still gives me the same error

#

oh wait i see, it's the ident

grizzled grove
#

Are there any ways to change an 'Unavailable' state for something like 'Idle'?

#

If it was from '0', for instance, it could be:

#
  - name: "Sensor XXXX"
    unique_id: sensor_xxxx
    state: >-
        {% if (states('sensor.XXXX') | float <= 0) %}
           Idle
        {% else %}
          {{ states('sensor.XXXX') }}
        {% endif %}
#

But for 'Unavailable'....

atomic blade
#

Should the order of things defined in your config ever matter? I have some template sensors that are defined as a static value (yes I know this could be done other ways) and if they are defined in my config after another template sensor that uses them then I get errors in my log

solemn frost
inner mesa
atomic blade
#

This seems like a bug. I've never heard of ordering mattering with any HA YAML configuration

inner mesa
#

Need to see an example

#

Order makes no difference at all as long as you follow the proper formatting

grizzled grove
#
  - name: "Time Heater Seconds"
    unique_id: time_heater_seconds
    state: >
      {{ (4.186*(80000*(60-states('sensor.temperature')|float(0)))/states('sensor.heater_watts')|float(0)) | round(0) }}
    availability:  "{{ states('sensor.heater_watts') | float(0) }}"
atomic blade
# inner mesa Need to see an example

Keeping it terse just for the example but I can provide a fuller one:

- sensor:
  - name: I use my sensor
    state: >
      {{
          states('sensor.my_sensor')|float
      }}
- sensor:
  - name: My sensor
    state: "1.23"
grizzled grove
#

The availability solves the log's error caused when the 'sensor.heater_watts' is '0'

#

But then it becomes 'Unavailable', has it should.

atomic blade
#

I think it's blowing up on the float parsing specifically

solemn frost
inner mesa
#

your indentation is wrong

grizzled grove
#

It's more of a aesthetic matter... I guess.

atomic blade
#

Ok sounds like you want a full example then lol

inner mesa
#

no, it's just wrong

atomic blade
#

I'm not getting indentation errors, though

inner mesa
#

I guess we need a real example πŸ™‚

#

not a broken one where we wave away the brokenness πŸ™‚

atomic blade
#

I made it more right if you want to take another look. I was leaving out that one level of sensor.

inner mesa
#

like i said, order makes absolutely no difference as long as the indentation and formatting are correct

#

ok, and what's wrong?

atomic blade
#

ValueError: Template error: float got invalid input 'unknown' when rendering template [...] but no default was specified
ValueError: Template error: float got invalid input 'unknown' when rendering template

#

If I define them in the other order then I don't get this

silent seal
#

Your float doesn't have a default πŸ˜‰

inner mesa
#

you'll probably get that when loading them because it's evaluating each one in turn

#

is it preventing the system from loading them?

atomic blade
#

Hm wait maybe I lied. I'm trying again and I'm still getting the errors

atomic blade
silent seal
#

Never assume that something will not be "unknown" or "unavailable"

inner mesa
#

At some point the first entity will be created, and at another point the second one will be created. They don't happen all at the same time

#

this isn't a YAML thing at all, it's just the nature of a computer

atomic blade
#

I do kinda seem to get less errors though...

atomic blade
silent seal
#

And all it takes is someone making a typo when editing a file or renaming a sensor and the entity could vanish πŸ™‚

inner mesa
#

and I don't think it will prevent you from loading the templates at all, but instead give you an error, but then be fine later on

atomic blade
silent seal
#

No

atomic blade
#

Ok good to know

silent seal
#

A list by technical definition does not necessarily have an order.

inner mesa
#

is it just an error at startup/reloading?

silent seal
#

In general each YAML file is loaded in in alphabetical order (whatever your system defines alphabetical as), but the contents of those are processed in whatever order makes most sense to the parser

atomic blade
#

lol I think it's a race condition. I move the template sensor that has dependencies to the bottom of the file and I don't get that error

#

But if there's no dependency checking then yeah I shouldn't rely on that and basically do what @silent seal was saying and check for things

silent seal
#

It's not a race condition, it's just your template not failing gracefully πŸ™‚

atomic blade
#

I mean it is still a race condition lol

#

I run it multiple times with different results with the same input

#

Not saying it doesn't make sense if there's no guarantee of order though

grizzled grove
#

You're right.

#

How should I go to add float <=0, so it would have the same behavior with '0' and negative values? I can't seem to get the template right.

inner mesa
#

With an elif. That's what you started with

#

Or use 'or'

grizzled grove
#

Ugh... true. Was thinking of something else.

prime kindle
#

How can I convert a MQTT sensor which is currently an entity into MQTT device?

merry marsh
#

If I use

          - service: light.turn_off
            continue_on_error: true
            target:
              entity_id: |
                {{ expand('light.alle_lampen') 
                  | selectattr( 'state', 'eq', 'on')
                  | rejectattr( 'entity_id', 'eq', 'light.weihnachtskegel')
                  | rejectattr( 'entity_id', 'eq', 'light.galeriegelander')
                  | rejectattr( 'entity_id', 'eq', 'light.lichterkette')
                  | map(attribute='entity_id') 
                  | join(', ') }}

and get sometimes (not always) Error for call_service at pos 3: Template rendered invalid entity IDs: without further information, what could be the reason and how to avoid this?

#

Unfortunately I have no output of this template for the error point in time either to see, what is perhaps wrong there.

inner mesa
#

No lights are on

marble jackal
#

Create a variable out of the template and first use that in a condition in an if

inner mesa
#

Use a condition above it

marble jackal
#

That's what I would do

#
- variables:
    lights: >
      {{ expand('light.alle_lampen') 
          | selectattr( 'state', 'eq', 'on')
          | rejectattr( 'entity_id', 'in', ['light.weihnachtskegel', 'light.galeriegelander', 'light.lichterkette']
          | map(attribute='entity_id') 
          | list }}
- if: "{{ lights | count > 0 }}"
  then:
    - service: light.turn_off
      continue_on_error: true
      target:
        entity_id: "{{ lights }}"
#

Indentation is a bit off because I'm on mobile, but you get the idea Indentation fixed

viral frost
#

Hi. Is it possible to create a template sensor which takes the value of another sensor but only at specific times? Eg. Right before midnight when the sensor resets. I haben't found any examples of this. 😢

marble jackal
#

yes, create a trigger based template sensor, and use a time trigger just before midnight

waxen rune
mighty ledge
plain magnetBOT
mighty ledge
# waxen rune Out of curiosity, what is your use case?

There are many use cases for this. I have one that updates at midnight every day and when HA restarts to specifically limit the number of times it calculates so that it does not alter an automation that uses it during the day.

#

I use it for seasonal calculations based on the current date. It's a heavy template and it really only needs to be available 100% of the time, but it should only calculate once a day because there's no need to run it more. If I were to remove the trigger, it would update once a minute, which is overkill.

viral frost
shell fractal
#

In the history stats integration, I need a configuration that gives the duration of my last translation when it switches from off to on and after a certain period of time when it switches back to off. History stats came to mind as an integration, I am open to other options and suggestions... I would appreciate your help

#

{{ is_state('binary_sensor.pir_sensor_4', 'on') and (now() - states.binary_sensor.pir_sensor_4.last_changed).seconds < 900 }}

Can I keep the result of this sensor on the screen for 15 minutes? In other words, if we divide an hour from 15 minutes to 4, can I make it write true if there has been movement in the motion sensor in the last 15 minutes and false if not?

obtuse zephyr
shell fractal
# obtuse zephyr I'm not sure what the "dividing hours" has to do with it, but do you just want a...

My goal is: If the sensor has been true in the last 15 minutes, it stays true for 15 minutes...The sensor configuration I have: the sensor detects motion and gives true and returns false again after 10 seconds...What I want is that if the pir sensor detects motion, it stays true for 15 minutes....Is there motion or not for the last 15 minutes?

Note: I don't want to do this from the pir sensor settings... It would be great if it is possible with templates or different systems

#

I'm sorry I didn't see the rest of your message... This is what I wanted "delay_off"... I will apply it, thank you very much

pallid hull
#

Is there a way to tell if I'm accessing the frontend from the mobile app vs a normal browser?

mighty ledge
#

only with browser mod

#

the custom integration, and even then, it's painful to get the current browser mod entity that contains the user you care about

#

but it's all possible using that custom integration

#

just keep in mind, the logic to get which one you're using will still fail when you're logged into both a web browser and the app. Which will happen more than you anticipate.

marble lily
#

it's there anyway I can make an entity from 1 attributes from another entity? my samsung tv state is on or off, but I want to get state for source of TV

mighty ledge
#

yes, using a template sensor

plain magnetBOT
marble lily
#

thank you!

nimble copper
#

I'm having some trouble with this jinja statement and not sure why.

#
{{ state_attr('calendar.test', 'message') is not none | iif(state_attr('calendar.test', 'message').split(' ')[0], none)  }}
#

Trying to make sure the split only happens when the 'message' is defined in the calendar sensor.

however the Dev Tools tempalte keeps giving me this error

UndefinedError: 'None' has no attribute 'split'

marble jackal
#

iif always renders both the true and false option

#

and you are apply the iif on none now

#

{{ state_attr('calendar.test', 'message').split(' ')[0] if state_attr('calendar.test', 'message') is not none }}

mighty ledge
#

uh, the whole filter and beyond don't make sense

marble lily
#

{{ states | state_attr('media_player.samsung_tv_remote', 'source') }} how can i tell to use only when TV is on ?

#

and when it's off to be null or something else?

nimble copper
marble jackal
mighty ledge
marble jackal
#

it's a media_player, they usually are not on, but playing, (or idle, or paused)

mighty ledge
#

depends on the media player

marble lily
#

that's perfect, thank you so much! @mighty ledge

#

it's a Samsung TV, I want to get the source as a state, to use in nodered

marble jackal
#

you can probably also do:
{{ state_attr('media_player.samsung_tv_remote', 'source') | default('off', true) }}

marble lily
#
  - name: "Samsung TV Source"
    state: "{{ state_attr('media_player.samsung_tv_remote', 'source') if is_state('media_player.samsung_tv_remote', 'on') else 'off' }}"``` I added this to my template folder in a file sensors.yaml, I have this in configuration ```template: !include_dir_merge_named template``` , and after restart I don't see the entity, I do something wrong ?
mighty ledge
#

!include_dir_merge_list

marble lily
#

thank you so much! it's working now

floral steeple
#

Hey all, I'm trying to create a tts message to let me know what my calendar events of the day are, but this does not seem to work as it keeps saying there are no calendar events today but there are 5 listed. Any idea what is wrong with this? thanks for your help.

#

{% set ns = namespace(events=[])%} {% set cals = states.calendar |
map(attribute='entity_id')| list %} {% for cal in expand(cals) |
selectattr('attributes.start_time', 'defined') |
sort(attribute='attributes.start_time') | map(attribute='entity_id') |
list %} {% if now() < state_attr(cal, 'start_time') | as_datetime |
as_local < today_at() + timedelta(days=1) %} {% set ns.events =
ns.events + [state_attr(cal, 'message')~" at "~ (state_attr(cal,
'start_time')|as_datetime|as_local).time()] %} {% endif %}{% endfor %}

    {% set todays_events = ns.events %} {% set qty = todays_events | count
    %}  {% if qty != 0 %}  There {{'is an' if qty==1 else 'are '~qty}}
    event{{' ' if qty==1 else 's '-}} on the calendars for today. {{' and
    '.join((todays_events|join(', ')).rsplit(', ', 1)) }}. {% else %} There
    are no calendar events today. {% endif %}
mighty ledge
#

don't you want between midnight and now()?

#

right now you have the opposite

#

ah, missed the + 1 day

inner mesa
#

Between now and today at midnight + 1 day is how I read it

floral steeple
#

yes, it goes off in the morning

inner mesa
#

I suggest breaking it down and debugging the parts

mighty ledge
#

well, it's simply never getting into that if statement

#

wouldn't you want to check the entire event?

#

i.e. the start and end?

#

if the start is before now, that check will fail

#

looking at my calendar data, it's outputting correctly

floral steeple
#

that is a good point, but if it past, then its not important, maybe?

mighty ledge
#

that depends, the event is still occuring if the end time is after now

floral steeple
#

you're right

#

so this works for you calendar...? lol

inner mesa
#

You should debug on your calendar

floral steeple
#

I should

inner mesa
#

Do you actually have events that match that logic?

floral steeple
#

most of my calendar entries are from google cal, if that matters

mighty ledge
#
{% set t = now() %}
{% set ns = namespace(events=[])%}
{% set cals = states.calendar | map(attribute='entity_id')| list %}
{% for cal in expand(cals) 
    | selectattr('attributes.start_time', 'defined') 
    | sort(attribute='attributes.start_time') 
    | map(attribute='entity_id') 
    | list %}
  {% set start = state_attr(cal, 'start_time') | as_datetime | as_local %}
  {% set midnight = today_at() + timedelta(days=1) %}
  {% set end = state_attr(cal, 'end_time') | as_datetime | as_local %}
  {% if t < start < midnight or t < end < midnight %}    
{% set ns.events = ns.events + [state_attr(cal, 'message')~" at "~ (state_attr(cal, 'start_time')|as_datetime|as_local).time()] %}
  {% endif %}
{% endfor %}
{% set todays_events = ns.events %}
{% set qty = todays_events | count %}
{% if qty != 0 %}
There {{'is an' if qty==1 else 'are '~qty}} event{{' ' if qty==1 else 's '-}} on the calendars for today. {{' and'.join((todays_events|join(', ')).rsplit(', ', 1)) }}. {% else %} There
        are no calendar events today. 
{% endif %}
inner mesa
#

It's easier because you're already populating a bunch of intermediate variables

floral steeple
#

ok, if I put the block above as you pasted, i get there are no caledar entries....so it must be something to do with how the events input. For example, right now its 9 am, I have an entry at 10am and 4 all week events....still says there are no calendar entries.

mighty ledge
#

are these all day events?

#

what's the start time and end time that's listed

eager reef
#

i want to count how many of my state.climate entities currently have the attribute hvac_action set to heating.
My best guess till now was:
{{ states.climate | select('is_state_attr', 'hvac_action', "heating") | list | count }}
but this this fails:
AttributeError: 'TemplateState' object has no attribute 'lower'

Pointers anyone?

mighty ledge
#

also keep in mind that calendars only show the next event

#

they do not show a list of events

floral steeple
#

yes all dat events...but I also have an 10 am appointment (in 1 hr)....and it didn't pick that one up

mighty ledge
#

so, at most each calendar will produce 1 event

floral steeple
#

ok this sheds some light on the code, it may not pick up all day events that started yesterday and beyond

eager reef
floral steeple
#

I thought the code would go beyond the first event...but that also explains that

mighty ledge
#

also, looking at your template, you're doing a lot of... unnecessary conversions

floral steeple
#

oh, where?

mighty ledge
#

well, it can be reduced to this

#
{% set t = now() %}
{% set ns = namespace(events=[])%}
{% for evt in states.calendar
    | selectattr('attributes.start_time', 'defined') 
    | sort(attribute='attributes.start_time') %}
  {% set start = evt.attributes.start_time | as_datetime | as_local %}
  {% set midnight = today_at() + timedelta(days=1) %}
  {% set end = evt.attributes.end_time | as_datetime | as_local %}
  {% if t < start < midnight or t < end < midnight %}    
    {% set ns.events = ns.events + [evt.attributes.message ~" at "~ start.time()] %}
  {% endif %}
{% endfor %}
{% set qty = ns.events | count %}
{% if qty != 0 %}
There {{'is an' if qty==1 else 'are '~qty}} event{{' ' if qty==1 else 's '-}} on the calendars for today. {{' and'.join((ns.events|join(', ')).rsplit(', ', 1)) }}.
{% else %}
There are no calendar events today. 
{% endif %}
#

there's more oddness in your output line too, like you output a space or s with a space, but then remove the space after

#

just output nothing or s and remove the trailing whitespace remover

#

and you're adding an extra space on are

#

and you're missing a space on and at the end

floral steeple
#

when I run this code, it says its looking at the domain calendar, vs the older code, it specifically lists each calendar i have, which does clean that up as domain calendar means every calendar I presume

mighty ledge
#

no, the space after the are is needed, my b

floral steeple
#

yes, the spacing is weird....I think it worked before but then the values were not spaced or something like that

#

so I added extra spaces

mighty ledge
#

well thats becaues you had -}}

#

that minus removes trailing whitespace

floral steeple
#

got it!

mighty ledge
#

FYI that's why it's good practice to space out your operations so you can easily read your code

floral steeple
#

thank you! now I just have to figure out why my events are not showing up in this code

mighty ledge
#

i.e. {{1+2}} is bad where {{ 1 + 2 }} is good

#

do this for me

floral steeple
#

I promise, next time I will

marble jackal
# mighty ledge do this for me

I always wonder why people don't add them, it makes the code so unreadable. Like reading an entire book without paragraphs

mighty ledge
# floral steeple I promise, next time I will

sorry, i didn't finish my response, do this for me. Paste the output here

[
{%- for c in states.calendar %}
  {
    'entity_id': '{{ c.entity_id }}',
    'attributes': {
      'start_time': '{{ c.attributes.start_time }}',
      'end_time': '{{ c.attributes.end_time }}',
      'message': '{{ c.attributes.message }}'
     },
  },
{%- endfor %}
]
eager reef
floral steeple
mighty ledge
floral steeple
mighty ledge
#

right, I want that list to see where your template is screwing up

#

use pastebin

obtuse zephyr
floral steeple
#

here's one event

mighty ledge
#

I'd like the whole thing

#

also, your current time

floral steeple
#

ok ill paste bin it now

mighty ledge
#

and by current time i mean paste this here too
{{ now() }}

floral steeple
#

now is last line

mighty ledge
#

There are 3 events on the calendars for today. Tempo Christmas Break at 00:00:00, Garbage Cart at 00:00:00 and Epiphany at 00:00:00.

floral steeple
#

yes!

mighty ledge
#

ok, the template I provided does that

#

so, did you copy/paste it correctly?

floral steeple
plain magnetBOT
#

@lilac folio I converted your message into a file since it's above 15 lines :+1:

lilac folio
#

can someone please help with this?

mighty ledge
#

what's the output of states('sensor.fajr_prayer')

lilac folio
mighty ledge
#

you don't need a template

#

@floral steeple you have all day events

#

i'm not sure why it's selecting the events, i'll look at it

#

the second event shouldn't be showing up

#

oh, because I added 7 days

#

give me a moment

floral steeple
#

For sure, thanks petro

mighty ledge
#

ok, got it

#
{% set t = now() %}
{% set ns = namespace(events=[])%}
{% set events = states.calendar | selectattr('attributes.start_time', 'defined') | sort(attribute='attributes.start_time') | list %}
{% for evt in events %}
  {% set start = evt.attributes.start_time | as_datetime | as_local %}
  {% set midnight = today_at() %}
  {% set midnight_tomorrow = midnight + timedelta(days=1) %}
  {% set end = evt.attributes.end_time | as_datetime | as_local %}
  {% if start <= midnight and midnight_tomorrow <= end or (midnight < start < midnight_tomorrow or midnight < end < midnight_tomorrow)%}
    {% set ns.events = ns.events + [evt.attributes.message ~" at "~ start.time()] %}
  {% endif %}
{% endfor %}
{% set qty = ns.events | count %}
{% if qty != 0 %}
There {{ 'is an' if qty == 1 else 'are ' ~ qty }} event{{ '' if qty == 1 else 's' }} on the calendars for today. {{ ' and '.join((ns.events|join(', ')).rsplit(', ', 1)) }}.
{% else %}
There are no calendar events today. 
{% endif %}
``` @floral steeple
#

and if you want it to be alittle better...

floral steeple
#

bam! that was it, what was the issue?

eager reef
# eager reef aaaahhhh! thank you!

how would i print the friendly names of the heated rooms? This fails again because of the missing lowerattribute:
{{ states.climate | selectattr('attributes.hvac_action', 'ne', 'heating') | list | map('state_attr', 'friendly_name') | list }}

mighty ledge
#

anyways, this might be more what you're looking for

obtuse zephyr
mighty ledge
#
{% set t = now() %}
{% set ns = namespace(events=[])%}
{% set events = states.calendar | selectattr('attributes.start_time', 'defined') | sort(attribute='attributes.start_time') | list %}
{% for evt in events %}
  {% set start = evt.attributes.start_time | as_datetime | as_local %}
  {% set midnight = today_at() %}
  {% set midnight_tomorrow = midnight + timedelta(days=1) %}
  {% set end = evt.attributes.end_time | as_datetime | as_local %}
  {% if start <= midnight and midnight_tomorrow <= end or ()%}
    {% set ns.events = ns.events + [evt.attributes.message ~" all day"] %}
  {% elif t < start < midnight_tomorrow %}
    {% set ns.events = ns.events + [evt.attributes.message ~" starts at " ~ start.time() ] %}
  {% elif t < end < midnight_tomorrow %}
    {% set ns.events = ns.events + [evt.attributes.message ~" ends at " ~ end.time() ] %}
  {% endif %}
{% endfor %}
{% set qty = ns.events | count %}
{% if qty != 0 %}
There {{ 'is an' if qty == 1 else 'are ' ~ qty }} event{{ '' if qty == 1 else 's' }} on the calendars for today. {{ ' and '.join((ns.events|join(', ')).rsplit(', ', 1)) }}.
{% else %}
There are no calendar events today. 
{% endif %}
``` @floral steeple
#

made an edit

#

anyways, it tells you when it starts or ends or if it's an all day event, i.e. no start/end

floral steeple
#

@mighty ledge thank you! this more cleaner now!!

eager reef
obtuse zephyr
#

those aren't state objects, they're entity ids

floral steeple
#

@mighty ledge

mighty ledge
#

try it

#

in 2022.11 I added the ability to use state_attr as a filter, which means you can use it in map

mighty ledge
eager reef
#

Ah, makes sense.

mighty ledge
obtuse zephyr
#

πŸ™‚ all good, yeah it definitely does work if you pass it an entity id though, which is awesome

sharp oxide
#

Hi, I've a question regarding to template sensors. As I see the attributes of the template binary sensor is restored whenever HA restarts or templates are reloaded if template triggers are used. Is this a feature or is it just a side effect of something and it will may be changed in the future (in that case I won't use it)? If it is a feature why is it not working with simple (not binary) sensors? Maybe a bug? (sorry if wrong channel)

marble jackal
#

Is this a trigger based template sensor, or a state based template sensor?

#

State based template sensors are reloaded when the state of any of the entities used in the template sensor changes.

#

For a trigger based template sensor you control when it's rendered, based on the trigger

lethal bison
#

I'm currently using a template to return a light group from a switch name: yaml {{ states.light | selectattr('object_id','search','^group_') | selectattr('object_id','search',trigger.event.data.device | slugify) | map(attribute='entity_id') | list }}
How can I use this same criteria to determine if the light group is on or off? ```yaml
action:

  • if:
    • condition: template
      value_template: "{{ is_state('light.group_backporch','on')}}"````
inner mesa
#

do you expect that to return one entity or many entities in a list?

lethal bison
#

I'm creating a single light group per switch, so one entity

inner mesa
#

that seems overly complicated. Can't you just generate the name based on the trigger data, rather than searching for the entity?

#

if the switch is called switch.foo and the light group is light.group_foo, then you can just build that

lethal bison
#

I guess so - I could append 'light.group_' to the trigger.event.data.device

inner mesa
#

yes

#

then... {{ is_state('light.group_' ~ trigger.event.data.device|slugify, 'on') }}

lethal bison
#

sweet. I"m trying to avoid having to set up an automation for each switch. Once this works, I can automate creating a light group for each switch, and then all I have to do is add the light entity in the future

inner mesa
#

you can't really "automate creating a light group" πŸ€”

#

you can automate transforming a switch entity_id into the entity ID for the light group, as above

#

but you'll be creating the actual light group manually

lethal bison
#

hmm

lethal bison
#

{{ is_state('light.group_' ~ trigger.event.data.device|slugify, 'on') }} doesnt seem to be pulling the device. If I substitute 'trigger.event.data.device' with 'officeceiling', the state returned is ['unavailable']

inner mesa
#

I was just copying what you had above, which you said worked

#

where are you testing it?

#

it won't work as-is in the template dev tool, if that's what you're trying to do

lethal bison
#

in the templates developer page. yaml {% if is_state('light.group_' ~ 'officeceiling'|slugify, 'on') -%} The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago. {%- else -%} The sun will rise at {{ as_timestamp(state_attr("sun.sun", "next_rising")) | timestamp_local }}. {%- endif %}

inner mesa
#

well, there's no "trigger' there, so...

#

hope that makes sense

lethal bison
#

correct, which is why I changed the trigger to what the trigger should be returning

#

unless the tilde is a special operator

inner mesa
#

I see

#

no

#

does light.group_officeceiling exist?

lethal bison
#

yes. [<template TemplateState(<state light.group_officeceiling=on; supported_color_modes=[<ColorMode.RGB: 'rgb'>, <ColorMode.WHITE: 'white'>], color_mode=white, brightness=255, entity_id=['light.office_bulb_1', 'light.office_bulb_2'], icon=mdi:lightbulb-group, friendly_name=Office Ceiling, supported_features=LightEntityFeature.TRANSITION|FLASH @ 2023-01-06T16:27:16.702616-06:00>)>]

inner mesa
#

you're not actually outputting the state anywhere in that expression, so I don't know what you mean by this:

the state returned is ['unavailable']

lethal bison
#

the test should have output The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago.

inner mesa
#

where did you get

#

the state returned is ['unavailable']

#

what is printing that?

lethal bison
#

oh hell.

#

fricking ADD>

#

I was not looking at the right section

#

ahh, there's an issue. The trigger is no longer device, but now device_id

lethal bison
#
target:
  entity_id: '{{ ''light.'' ~ trigger.event.data.device ~ ''_indicator_light''|slugify }}'```
should be returning 'light.Office_Ceiling_Indicator_light'.
Instead I"m getting the error `Error: Template rendered invalid entity IDs: light.Office Ceilingindicator_light`
inner mesa
#

First, that's an invalid entity_id anyway. They can't have capital letters

lethal bison
#

shouldn't slugify fix that?

inner mesa
#

Second, |slugify is only applied to _indicator_light there

lethal bison
#

ahh, the three are evaluated separately

inner mesa
#

Yes

mint drift
#

Hello, I have sensor: !include sensors.yaml in my configuration.yaml then have this in my sensors.yaml restarted but not showing the sensor - platform: template sensors: test_Heat: value_template: "{{ is_state_attr('climate.wiser_test', 'hvac_action', 'heating') }}" friendly_name: test Heating On

marble jackal
#

I guess it's the capital H in test_Heat:

#

You can't use uppercase characters in object_ids

#

And I would suggest to make this a binary_sensor instead of a sensor

short magnet
#

https://pastebin.com/uuncRUPg

I have this I use for my Garage door, and it works fine, but how do i add the state_color: true (or just yellow) when the door is open?

mighty ledge
marble jackal
#

Looks like a mushroom template card, you can use the icon_color setting and use a similar template

mint drift
#
  mdi:garage
  state_color: yellow
{% else %}
  mdi:garage-open
{% endif %}
marble jackal
plain magnetBOT
#

@thorny snow I converted your message into a file since it's above 15 lines :+1:

#

@thorny snow I converted your message into a file since it's above 15 lines :+1:

tiny temple
#

Hey all ! Is there a good place with detailed tutorials ? The docs seems a bit scare sometimes for very newcomers like me

#

I would like to read up one example and adapt to my needs

#

For example , i guess very famous, setting a custom binary sensor for home presence based on my own inputs

mighty ledge
#

@thorny snow you can't reduce open/close tags. 1 open/close tag per line of code

floral shuttle
#

I need to manipulate the entity_id's in this list:```
{% set list =
expand('switch.z_wave_switches')|map(attribute='entity_id')|list +

expand('switch.shelly_switches')|map(attribute='entity_id')|list %}in such a way that I change the domain from switch to sensor, and add a suffix '_device_energy'. I seem to run into a silly oversight, because I keep getting
UndefinedError: 'str object' has no attribute 'entity_id'```

#

what am I not seeing?

mighty ledge
#

why are you adding those, expand both entities

#

in 1 expand

floral shuttle
#

In a next step I need to add the resulting sensor.*_device_energy entities to a kWh number and feed that to the utility meter...

mighty ledge
#

that would be a separate add using states.sensor

floral shuttle
#

right, {% set list = expand('switch.z_wave_switches','switch.shelly_switches')|map(attribute='entity_id')|list %}... sorry for that

mighty ledge
#

also you don't want to overwrite the list variable

#

set mylist

floral shuttle
#
expand('switch.z_wave_switches','switch.shelly_switches')|map(attribute='entity_id')|list %}
{% for s in mylist %}
{{s.entity_id}}
{% endfor %}``` results in the same error.
mighty ledge
#

cause you're mapping the entity_id...

floral shuttle
#
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{{s.entity_id}}
{% endfor %}
mighty ledge
#

you're changing it from a list of state objects to a list of entity_ids

floral shuttle
#

bingo....

#

thanks!

mighty ledge
#

np

floral shuttle
#
{%- set ns = namespace(energy=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_device_energy' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}
{{ns.energy}}```
#

can I directly manipulate that with |selectattr('state','is_number') |map(attribute='state') |map('float')|sum|round(2)}} or would it be best to create a second template sensor on that list

#

this seems to work: {%- set ns = namespace(energy=[]) %} {% set mylist = expand('switch.z_wave_switches','switch.shelly_switches') %} {% for s in mylist %} {% set switch = s.entity_id.replace('switch','sensor') + '_device_energy' %} {%- set ns.energy = ns.energy + [switch] %} {% endfor %} {{expand(ns.energy)|selectattr('state','is_number')|map(attribute='state') |map('float')|sum|round(2)}} though I dont understand the outcome yet.... have to fiddle some more with the result πŸ˜‰

#

checking that, and understanding now.... can we sort this based on state:```
{%- set ns = namespace(energy=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_daily' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}

{% for s in expand(ns.energy) %}

{{s.name}}: {{s.state}}
{% endfor %}```?

marble jackal
#

Or easier, build a list of tuples

#
{% set ns = namespace(sort=[]) %}
{% for s in expand(ns.energy) %}
  {% set ns.sort = ns.sort + [(s.name, s.state | float)] %}
{% endfor %}
{% set sorted = ns.sort | sort(attribute='1') | list %}
tired wind
#

What's the syntax for 'not equal' when evaluating state? Templating noob trying to create a template that outputs a count of open garage doors. Since there's several cover states I need count any door that's not equal to 'closed' instead of any door that's 'open'.

#

I've avoided it by using rejectattr instead of selectattr and got it working, but not sure it's the best way to do it. Here's my code:

#

{{ states.cover | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'garage') | rejectattr('state', 'eq', 'closed') | list | count }}

#

also, not sure how to paste code in here lol

#

duh, nevermind. != is what I was looking for.

#

< idiot

floral shuttle
# marble jackal ```jinja {% set ns = namespace(sort=[]) %} {% for s in expand(ns.energy) %} {%...

not that easy...```
{% set ns = namespace(energy=[]) %}
{% set ns = namespace(sort=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_daily' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}

{% for e in expand(ns.energy) %}
{% set ns.sort = ns.sort + [(e.name, e.state | float)] %}
{% endfor %}
{% set sorted = ns.sort | sort(attribute='1') | list %}errors with
UndefinedError: 'jinja2.utils.Namespace object' has no attribute 'energy'```

marble jackal
#

@floral shuttle You replaced ns.energy with ns.sort

#

{% set ns = namespace(energy=[], sort=[]) %}

floral shuttle
#

ah yes, keen eye.```
{% set ns = namespace(energy=[], sort=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_daily' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}

{% for e in expand(ns.energy) %}
{% set ns.sort = ns.sort + [(e.name, e.state | float)] %}
{% endfor %}
{% set sorted = ns.sort | sort(attribute='1', reverse = True) %}
{{sorted}}```

#

now works, (note the final |list isnt necessary)

#

only thing now I have a nested list, and I want to list these without all of that :

#

like before:

marble jackal
#

Create the output based from the list with tuples in another for loop

#
{% for i ns.sort %}
  {{ i[0] }}: {{i[1] }}
{% endfor %}
floral shuttle
#

beat me to that, was building the full template like```
{% set ns = namespace(energy=[], sort=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_daily' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}

{% for e in expand(ns.energy) %}
{% set ns.sort = ns.sort + [(e.name, e.state | float)] %}
{% endfor %}
{% set sorted = ns.sort | sort(attribute='1', reverse = True) %}
{% for u in sorted %}
{{u.0}} - {{u.1}}
{% endfor %}``` but you;re using an index arent you?

thorny snow
#

just so I start off on the right foot - i want to make a sensor that is 'on' if the value of an entity is <0 and 'off' if the same entity is >0

Is it a template binary sensor that I want to write ?

nimble copper
#

Why does this code evaluate as False?

{{ 'a' in ['abc'] }}

#

But this one returns true.

{{ 'a' in 'abc' }}

inner mesa
#

Because the string isn't in the list

#

But the character is in the string

solemn frost
#

A list would normally have many elements and you would want to see if a string is in a list of strings, so it wouldn't make sense for it to do partial matches

nimble copper
#

Is there a way to match a substring in a list? Or will only exact matches of a string item in a list work?

inner mesa
#

{{ ['abc']|select('search', 'a']|length > 0 }}

nimble copper
inner mesa
#

In the second link in the channel topic

nimble copper
#

Thank you. Love how helpful everyone on the template channel is. @inner mesa

trail estuary
#

Hey everyone! Hope you all are having a good weekend? πŸ™‚
I am fiddling with an idea that requires me to use templates to process some values.
Problem 1:
I have this template:
{{ (state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025','today' ))}}
that returns this list: https://hastebin.com/evimapigaz.json
I want to calculate the average of all these values... Any hints on how to proceed?

inner mesa
#

|average

trail estuary
#

Problem 2:
I want to store the averaged value somehow, as the average for today, each month... These are electricity prices...
So for today I want to store the average value and have it overwritten on the same date next month

#

Too easy....

inner mesa
#

Feel free to try stuff πŸ™‚

trail estuary
#

I was reading the docs and expecting to have to use mapping... So... πŸ€·β€β™‚οΈ

#

Any idea on Problem 2?

inner mesa
#

12 input_number entities

#

Each set based on an automation with a time trigger set to trigger each month

#

Construct the entity name based on the current month name or number

trail estuary
#

So go directly to monthly averages, don't go via daily? I don't need daily.

inner mesa
#

🀷

#

I don't fully understand the goal

solemn frost
#

Does the energy dashboard not do what you're trying to accomplish with energy prices?

inner mesa
#

That's a strategy

trail estuary
#

Not at all.... Every day I am thinking that the energy dashboard has a ton of unused potential... Don't get me wrong, I am super happy with what it does, but it could do more....

As for this "project".... Here in Norway, due to the insane prices of electricity, the government has introduced a refund based on usage and the average price per kWh for a given month. They refund 80% of the price above the average. But identifying (and estimating) what the average value will end up at is hard. I still havent found anywhere to get that value, except for when the invoice comes. It would be great to have an idea earlier in the month....

#

Since I have all the data needed to calculate this I thought that would be easy enough....

#

And maybe it is... I could publish the day average to an MQTT sensor for storage, and use an automation maybe to add the next day average to the already published value...

sharp oxide
solemn frost
#

It was merged

sharp oxide
#

Okay that strange I can't reproduce the problem with some simple sensors only with complex ones. I'll try to reproduce the problem with a simpler example.

#

If I create a simple template sensor which returns the current minute:

template:
  - sensor:
      - name: sensor1
        state: >-
          {{ now().minute }}

Then I create another template sensor which calculates one of it attributes from it (in my original complex template there were multiple triggers and I only want to update specific attributes and keep the other ones based on the trigger.id):

#
- trigger:
    - platform: state
      entity_id: sensor.sensor1
      id: sensor1_change
  sensor:
    - name: my template sensor
      state: >-
        {{ 0 }}
      attributes:
        my_attr: >-
          {% if trigger.id == 'sensor1_change' and trigger.to_state.state|float("unknown")|is_number %}
            {{ states('sensor.sensor1') }}
          {% else %}
            {{ state_attr("sensor.my_template_sensor", "my_attr") }}
          {% endif %}
#

Next I reload templates and my_attr refreshed every minute. After that I modify the code of my template sensor to see if it restores the state (attributes):

- trigger:
    - platform: state
      entity_id: sensor.sensor1
      id: sensor1_change
  sensor:
    - name: my template sensor
      state: >-
        {{ 0 }}
      attributes:
        my_attr: >-
          {{ state_attr("sensor.my_template_sensor", "my_attr") }}
#

and I reload templates. The value of my_attr will be null.

#

If I use binary_sensor instead of sensor, the attributes are restored fine.

thorny snow
#

I have this template sensor which should take two values and perform a quick a - b = c but is doesnt seem to work (anymore)
What have I broken or not updated correctly?

` - name: Flow & Return Differential
unit_of_measurement: "Β°C"
state: >
{% set flow = states('sensor.flow_temperature') | float %}
{% set return = states('sensor.return_temperature') | float %}

    {{ (flow - return) | round(1, default=0) }}`
inner mesa
#

'Doesn't seem to work'

thorny snow
#

it did work - but no more

inner mesa
#

Details!

#

I have this car that doesn't seem to work, what's wrong?

#

What does it do?

buoyant pine
#

What does it don't?

thorny snow
#

it says entity not available on the dash - however I just removed it and re-added it and it now says "on"
but its a temperature sensor

thorny snow
solemn frost
#

What if the value is 0? Is that possible for whatever value you're trying to check?

thorny snow
#

actually it is possible

#

so <-0.01 or >=0.00 would work

dry narwhal
#

Hello everyone,
trying to use an input_text to supply both auto-entities and a template.

So I need to work with wildcards for auto-entities but how do I make this compatible with templates?

input_text e.g. "*ENERGY Power"

{{ ['-- - --'] + states.sensor|selectattr('name', 'search', states('input_text.text_wildcards'))|map(attribute='name')|list }}

returns error: nothing to repeat at position 0
If I remove the "*" it works for template but not auto-entities.

Ideally I need the wildcards to also work in the template because it might also be something like "Shelly* Power*1"

solemn frost
thorny snow
#

- name: Free Electric state: > {% if sensor.octopus_energy_electricity_current_rate < 0 %} on {% else %} off {% endif %}

so i need to add in | float after _current_rate by the looks of it

solemn frost
#

It should be states('sensor.octopus_energy_electricity_current_rate')

#

The whole thing would be

state: "{{ states('sensor.octopus_energy_electricity_current_rate') | float < 0 }}"

There's no need for the if, on/off, etc. The binary sensor just expects the template to return true or false, which the line above does

thorny snow
#

okay , so if the condition isnt met to make it on, it will be off

solemn frost
#

If it's -1 for example, the template will return true, which will set the sensor to on

thorny snow
#

thank you

#

its working - thats my trigger to turn on the electric water heater (instead of gas) when my electric is free from the grid

barren umbra
#

Aren't we supposed to provide default values now for float and int? As in | float(0) < 0 or | int(0) <> 77?

inner mesa
#

For a long time, and where needed

floral steeple
#

hey all, I have this automation that checks if any windows, doors or gates are open when my security is armed and when we leave home, problem is, it does not tell my which one is open. It would be great if this would tell me that via the actions/TTS. Any suggestions? http://pastie.org/p/2ykeoR1spg0nsJYfma3IvK

solemn frost
marble jackal
#

Better to start with states.cover

#

{{ states.cover | selectattr('state', 'eq', 'open') | map(attribute='name') | join(',') }}

marble jackal
stone imp
#

probably a silly question but, I have a rest sensor that returns a float, however the UI shows the history as 500 differently colored blocks instead of a line graph

#

how do I make it show a line?

#

I looked at device classes but theres no class tha tmatches

#

this is my template currently:
value_template: "{{ value_json.result.cics[0].flowRate | float(default=0) | round(2) }}"

barren umbra
plain warren
#

Good Morning,
I have a problem with a Number Template. My KNX Number entity has a factor 10 that means 160 -> 16A. That I want to correct for the interface with an template. But I don't know that to enter to the set_value parameter:

- number:
  - name: "Carport.Wallbox1.Stromaufnahme.maximal Laden"
    state: "{{ (states('sensor.carport_wallbox1_stromaufnahme_maximal_laden_temp')|float(0)) / 10 }}"
    set_value: "{{ value * 10 }}"
    step: 0.1
    min: 0
    max: 16
    availability: >-
      {{ 
        [ states('sensor.carport_wallbox1_stromaufnahme_maximal_laden_temp'),
        ] | map('is_number') | min
      }}
marble jackal
plain warren
silent vector
#

Is there a way to get the state last updated of all items in a dictionary and select the most recent? Such as outputting doorbell if doorbell was the most recent last updated.

  status_sensor:
    outdoor_2: 'binary_sensor.outdoor_2_notification_status'
    doorbell:  'binary_sensor.doorbell_notification_status'
pastel moon
#

If I have a string with time/date, and want to use it's time only with current date, would that be possible? I have been trying with this, but no success yet; ```
{% set debug_night = '2023-01-07 23:34:00+01:00' %}
{% set d = now().date() %}
{% set t = (debug_night | as_datetime).time() %}
{% set dt = ??? %}

{{ dt }}```

#

What I'd like to do is create a string with the two and then convert into datetime

#

At times like this a filter as_text or as_string would have been handy to build the string more easily

hoary surge
#

I would like to setup the utility meter helper to track my energy consumption. Unfortunately my electric meter is analog without the posibilty to read out the values in any other way then writing them on a paper.
My electric meter has two counters for day and night so two different values to feed into the utility meter. Now what i do not understand is the setup process of the utility meter helper.

#

As input source it wants one sensor. But only one. So how would I track two different numbers?

marble jackal
pastel moon
marble jackal
#

This will also work

{% set debug_night = '2023-01-07 23:34:00+01:00' %}
{% set dt = today_at(as_datetime(debug_night).strftime ('%H:%M')) %}
{{ dt }}
pastel moon
#

Really cool, thanks a lot!

barren umbra
#

@floral steeple Add those entities to a group like house_perimeter and then start with this template:

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

It will need more tweaking to get the friendly_name rather than entity_id.

barren umbra
#

@hoary surge
"my electric meter is analog without the possibility to read out the values in any other way then writing them on a paper.
(the) meter has two counters for day and night so two different values to feed into the utility meter"
So you intend to record those on a daily basis and input the numbers manually and consistently into HA via an input_number or ??

"As input source it wants one sensor. But only one. So how would I track two different numbers?"
On first thought I was thinking via tariffs, but that won't work as you do not have a single constantly increasing value to break into tariffed usage.
I think 2 meters will be needed, one for day and one for night.

marble jackal
hoary surge
barren umbra
#

@hoary surge I am visualizing two (very spikey) utility meters then. Also, the input has to be a sensor so I'm thinking a "templated sensor of an input_number"?

#

@marble jackal @floral steepleDoh! Thanks! Probably will want to strip single quotes and braces from the output.
My test group gives me ['Kitchen occupancy', 'Office occupancy'].
Maybe change the comma + space to space & space too!

#

@stone imp Google is my best friend!

marble jackal
#

['Kitchen occupancy', 'Office occupancy'] this is a list, not a string

pastel moon
#

What is wrong with this trigger please? ```

  • platform: template
    id: "set_light_on"
    value_template: "{{ (as_timestamp(now()) > as_timestamp(states('input_datetime.christmas_lights_on') | as_datetime)) }}"```
#

template evaluates to true in dev-tools so should fire, right?

barren umbra
marble jackal
#

and the as_timetamp is not needed

marble jackal
pastel moon
#

Oh. My intention with writing it as is was to make it trigger whenever true, so I should add "from/to" ? So only state changes then...

barren umbra
#

@marble jackal @floral steeple
Almost perfect...Kitchen occupancyOffice occupancy.
join(', ') = Kitchen occupancy, Office occupancy
Adjust the (...) to what you want.

marble jackal
#

today it's already after, so it won't trigger anymore today, It will trigger again tomorrow

#

well probably not, as you have a datetime input_datetime

pastel moon
#

Ah, that's why I felt it was failing. I expected it to trigger as it was true... Thanks for clarifying

marble jackal
#

when should it stop triggering then?

#

a trigger is always a single moment

#

not a period of time

pastel moon
#

Well, it just needs to trigger once

#

it then sets helpers with timestamps for on/off used elsewhere in my scripts

marble jackal
#

So that is why it will trigger when it becomes true, not when it is already true

barren umbra
#

@marble jackal @silent vector what do you mean with state last_updated. Only an entity itself has last_updated, not attributes
I think he was referring to a dictionary list of entities. Although the link I posted is manipulating attributes of an entity, I think it's a good starting point to play with sorting a dictionary list of entities and selecting the [0] item. There might be more relevant posts for what he wants...

silent vector
#

Thank you but I actually moved away from that I'll be doing something a little different and will probably be back tomorrow morning to figure it out. I'm trying to create a frigate notification automation so that 1 notification can be used among 2-3 cameras with priority. Meaning phones would receive 1 that gets overwritten with new notifications as needed rather than 2-3 separate notifications.

plain magnetBOT
dry narwhal
#

e.g. *ENERGY*Power
I am guessing it would need to be somehow separated into multiple searches? One search per * wildcard?

plain magnetBOT
#

@tidal meteor I converted your message into a file since it's above 15 lines :+1:

#

@barren umbra I converted your message into a file since it's above 15 lines :+1:

dry narwhal
#

Did I miss a breaking change?
My notification is no longer telling me which device triggered the alarm.

    action:
    - service: notify.mobile_app_sm_g975f
      data:
        message: "Alert: {{ trigger.to_state.friendly_name }} DEAD"
inner mesa
#

friendly_name has never been a property of the state object. Either use 'name' or 'attributes.friendly_name'

tired pebble
#

I'm trying to integrate the play time of a media player into the energy dashboard, to approximate power consumption. Would this solution work or am I doing something stupid?

plain magnetBOT
#

@tired pebble I converted your message into a file since it's above 15 lines :+1:

tired pebble
#

Will it count towards the the consumption even if the value is static and doesn't change?

#

Currently i do not have the readings of power consumption, so i can't hard code the value

marble jackal
#

You can also use the custom integration powercalc

#

It allows you to provide power consumption based on the state of an entity

tired pebble
#

O was about to use that, but they said they support switches and this is a media entity. Moreover, powercalc configuration still has to be done through the configuration yaml, so if i didn't mess up the logic in the code above, it should work, right? Or i just missed something really obvious. Because what i wrote seems way too simple to be true

marble jackal
#

It works on media players and config can be done in the GUI

tired pebble
#

Oh

#

The GitHub page talked about editing config. Will give this a shot then

brisk lava
#

Can templated variables be multiline within a script?

#
  action_on: "{{ 'Turn On_' ~ context.id }}"
  action_off: "{{ 'Turn Off_' ~ context.id }}"
  temp: {% if states('sensor.adelynn_temp_temperature') >= '71' %}
          Too High
        {% elif states('sensor.adelynn_temp_temperature') <= '64' %}
          Too Low
        {% else %}
          Just Fine
        {% endif %}```
#

Returns the error Message malformed: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'sensor') for dictionary value @ data['sequence'][0]['variables']['temp']

inner mesa
#

not like that

#

also, you're doing string comparisons when you want to compare numbers

brisk lava
#

the template as written produces a string output in dev tools.

inner mesa
#

🀷

#

this doesn't do what you want:
if states('sensor.adelynn_temp_temperature') >= '71'

brisk lava
#

{{ states('sensor.adelynn_temp_temperature') }} Result type: number 63.5

inner mesa
#
  temp: >-
    {% if states('sensor.adelynn_temp_temperature')|float >= 71 %}
      Too High
    {% elif states('sensor.adelynn_temp_temperature')|float <= 64 %}
      Too Low
    {% else %}
       Just Fine
    {% endif %}
#

all states are strings all the time

brisk lava
#

so by putting '71' i'm converting it to string?

inner mesa
#

that is a string, yes

tired pebble
#

This is fabulous. My step dad bitching on me for charging my phone or even turning on my PC for 10 mins that it costs a fortune. Meanwhile his speaker setup that is sitting idle 24/7 in the living room consumes 6,4W even when no sound is produced

brisk lava
#

well shit. Okay, your code, as expected, works. i tried to pipe the output to float previously but for whatever reason it wouldn't give the expected output

tired pebble
#

Ok, tv goes from 130-270W depending on how bright the scene is. I used constant 200W average. That shit consumes more power than my pc

tired pebble
# marble jackal

I did that, but the entity doesn't appear on the energy dashboard settings as an option to add

#

It needed some time to sample the data

narrow spire
#

Hi, hopefully this is the correct section to ask. I am trying to write an automation that triggers when a sensor changes (or if i run it manually then hoping it can get the information from the last time it would have ran). The aim is to send a load of information as part of a notification. I'm trying to get information about the last time a sensor was a value but the documentation to get the state object for the sensor seems to return null.
Last print ended: {{states('binary_sensor.octoprint_printing').last_changed}}
Is what I currently have inside message: but nothing is coming through

inner mesa
#

that's not how to do that

#

Last print ended: {{ states.binary_sensor.octoprint_printing.last_changed }}

narrow spire
inner mesa
#

you're confused

#

you're not getting the state there, you're getting a property of the state object

#

well, you were getting the state, and then trying to get the last_changed property from that, which doesn't make sense

#

states.xxx.xxx.state is indeed discouraged in favor of states('xxx.xx'), but that's not what you needed

narrow spire
#

Thanks, that's got me going again

floral steeple
#

here's my updated automation.

#

only minor issue is a grammar one...if its one entity it will say "is open" but if its 2 or more...it will also say "is open"...but should be "are open"....Oh I sometimes I think I need meds for my OCD πŸ˜…

solemn frost
#

You could solve it the easy way by rewording it e.g. "Please check the following: <list>", or the more complicated way which would be to run a count and then use that number to select "is" vs. "are"

#

Personally I'd just reword it because that's simpler

floral steeple
#

yes. The easy way also works thank you!

#

thanks all for your help

marble jackal
# floral steeple yes. The easy way also works thank you!
              message: >-
                {% set open = expand('binary_sensor.house_perimeter') | selectattr('state',
                'eq', 'on') | map(attribute='name') | list %}
                You {{trigger.id}}, but {{
                open | join(', ') }} {{ 'are' if open | count > 1 else 'is' }} open.
lethal bison
#

I"ve got an automation that uses ```yaml
if:

  • condition: template
    value_template: >-
    {{ is_state(('light.group_' ~ trigger.event.data.device | slugify), 'on')
    }}to decide whether to turn another entity on or off. The strings combine to makeentities:
  • light.group_office_ceiling```
    However, the statement is always evaluated as false, even though the entity is on
floral steeple
fierce hornet
#

Is it possible to display the current HA version with a template?

solemn frost
pine musk
#
service: notify.1204longhunterln
data_template:
  message: >
   "{{ input_text.slackmessage }}" 
  target: "#home automation"

How do I fix this? when I try to run it, i get: Error running action Error rendering data template: UndefinedError: 'input_text' is undefined

#

when I take out input_text. it saves, & runs, but notifys ""

solemn frost
#

{{ states('input_text.slackmessage') }}

pine musk
#

ah.

#

thanks jumbers

thorny snow
#

just so I am sure I have this in the correct part of my config , is this a template binary sensor?
`- name: Flow & Return Differential
unit_of_measurement: "Β°C"
state: >
{% set flow = states('sensor.flow_temperature') | float %}
{% set return = states('sensor.return_temperature') | float %}

    {{ (flow - return) | round(1, default=0) }}`
solemn frost
#
template:
  - binary_sensor:
      - name: "Has Unavailable States"
        state: "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"
#

The above example is a binary sensor, it returns true or false. Since you're trying to store Β°C, that'd just be a sensor

thorny snow
#

so i tried dropping that into my sensor block - and HA refused to restart - is the formatting correct for a sensor?

solemn frost
#

It looks like your indenting is wrong

plain magnetBOT
#

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.

marble jackal
#

So

template:
  - sensor:
      - name: ...
thorny snow
#

its just restarting - i cant remember what i just changed it to - lets see what the restart brings me!

solemn frost
#

What is the error?

thorny snow
#

Logger: homeassistant.config
Source: config.py:974
First occurred: 20:36:31 (1 occurrences)
Last logged: 20:36:31

Invalid config for [template]: [name] is an invalid option for [template]. Check: template->name. (See /config/configuration.yaml, line 447).

#

447 is the first line of that link above

mighty ledge
#

Youre missing sensor

#

And you aren’t listing it

#
template:
- binary_sensor:
  - name: …
solemn frost
#

Is what you pasted not what's in the config?

mighty ledge
#

I didn’t read what he has in his config, I’m just reading the error

#

The error sees:

template:
  name:
solemn frost
#

The paste syntax is right, which is why I'm confused what happened

mighty ledge
#

Maybe an old error and he doesn’t realize it?

inner mesa
#

"aren't actually using what they're posting" is always a possibility

solemn frost
#

From 20:36. Maybe old yeah

inner mesa
#

Oh, yeah, I just copied that from a reddit post...

thorny snow
solemn frost
#

What you pasted looks correct, so it doesn't line up with the error

thorny snow
#

just checked the log again - and this one is probably more likely the issue !

inner mesa
#

like you didn't reload

thorny snow
#

The system cannot restart because the configuration is not valid: Invalid config for [mqtt]: [state] is an invalid option for [mqtt]. Check: mqtt->mqtt->sensor->7->state. (See /config/configuration.yaml, line 57).

thorny snow
inner mesa
#

"restart" you mean

#

anyway, that's a completely different error

#

that looks like you put mqtt: in a file that you included from mqtt:

thorny snow
#

line 57
mqtt:

thorny snow
inner mesa
#

mqtt->mqtt->

#

when I add "mqtt:" to my "mqtt.yaml" file that's included from configuration.yaml, I get the same kind of thing:

2023-01-08 13:09:56.659 ERROR (MainThread) [homeassistant.components.homeassistant] The system cannot check_config because the configuration is not valid: Invalid config for [mqtt]: [mqtt] is an invalid option for [mqtt]. Check: mqtt->mqtt->mqtt. (See /config/configuration.yaml, line 101). 
thorny snow
#

im getting a bit lost here - should I not have mqtt: at the start of my mqtt entities (the same way I have always had it for about 6 years)?
or should it be changed to mqtt->mqtt-> ?

sullen quest
#

Morning all. I have a template sensor that I want to be based on a number value, however this code gives me an unavailible return

#

kitchen_filter_days_remaining is based on helpers that determines days left before filter needs to be changed

#

and works 100%

solemn frost
#

The name of the sensor in states() isn't valid. What kind of helper is it?

sullen quest
#

I have 2 helpers, one datetime helper that sets the date I install the new filter, the second helper is a number helper that states 90days before the next filter change. I then have a sensor coded in yaml that subtracts these to determine the days remaining

#
    sensors:
      kitchen_filter_days_remaining:
        friendly_name: Kitchen Water Filter Days Remaining
        unit_of_measurement: days
        icon_template: 'mdi:calendar-clock'
        value_template: >-
          {%- set inst = as_timestamp(states('input_datetime.kitchen_water_filter_installed')) -%}
          {%- set dif = states('input_number.kitchen_filter_lifespan') | int * 86400 -%}
          {%- set nt = as_timestamp(states('sensor.date')) -%}
          {{ (((inst + dif) - nt) / 86400) | round(0) }}```
solemn frost
#

states('sensor.kitchen_filter_days_remaining')

sullen quest
#

🀣 oh duh! ofcourse

#

been starting at it for to long! thanks Jumbers

solemn frost
#

You're also using the old format of template sensor

sullen quest
#

awesome thank you. I have quite a few that I will rework

solemn frost
#

Not urgent or anything, but best to follow the new format

open obsidian
#

I would love to know why this keeps being zero, (i'm new to templating)

#
{% set wv = 0 %}

{% for entity_id in states.group.thermostats.attributes.entity_id %}
  {% if state_attr(entity_id, 'current_temperature') <= state_attr(entity_id, 'temperature') %}
    {% set wv = wv + 10 %}
  {% else %}
    {% set wv = wv - 10   %}
  {% endif%}
{% endfor %}

{{ wv }}
#

I see that HA enters the if statement

#

But wv is 0 the initial value at the end

inner mesa
#

because you need to use a namespace if you want to modify a variable in a loop and them use it outside the loop

open obsidian
#

Ah!

#

I can google that

inner mesa
#

{% set ns = namespace(wv=0) %}

open obsidian
#

thanks

inner mesa
#

then reference it as ns.wv

open obsidian
#

Thanks, yes that works

spring pollen
#

Would this be the place to ask about formatting a mqtt message in esphome? Trying to get values from mqtt into a variable for an nspanel but end up with values like \x8c\x85\xfe?.

silent seal
#

Is templating the moon sensor broken for anyone else?

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

Is outputting the enum string key instead of the value for me (waning_gibbous instead of "Waning Gibbous").
(This is the latest release, 2023.1.1)

pine musk
#

Hmm. I get unknown

silent seal
#

Well you'd need the moon integration enabled πŸ™‚

pine musk
#

waning_gibbous with{{ states('sensor.moon_phase') }}

idle shore
#

It's enabled, same here, mushroom chip doesnt display properly

silent seal
#

Well at least I'm not alone!

sage stirrup
#

Hello, I hope everyone is having a wondering day. I couldn't figure out if it's possible or how to do it, but for an automation with multiple triggers is there a way to see in with template code to see which trigger set off the automation? Thanks!

solemn frost
#

Yes, you have to set a trigger ID on the triggers, then you can use trigger ID as a condition

sage stirrup
#

ahhh ok.

#

Thank you!

#

I'm getting the hang of templating and its amaaaaaaaaaaaazing!

solemn frost
#

You can also access the trigger data which has the entity_id, from_state, to_state, and some other things, but I can't find the doc on that at the moment. You can see the data in it via Traces though on the "Changed Variables" tab under trigger:

sage stirrup
#

Thanks @solemn frost !!

sage stirrup
#

What I was looking for was {{ trigger.to_state.name }}

#

it doesn't do anything in the template development window but when putting it an action of the automation it tells you the name of the trigger that set off the automation.

lethal bison
#

Trying to pull a different device from an automation trigger: yaml service: light.toggle target: entity_id: >- {{ states.light | selectattr('entity_id','search','group_') | selectattr('entity_id','search',trigger.event.data.device | slugify) | map(attribute='entity_id') | list }}
In the template editor, if I replace 'trigger.event.data.device' with 'diningroom', the correct entity (light.group_diningroom) is returned. However, the automation trace says "TypeError: decoding to str: need a bytes-like object"

inner mesa
#

I'll bet that trigger.event.data.device is None or something like that

lethal bison
#
  id: '0'
  idx: '0'
  alias: null
  platform: event
  event:
    event_type: esphome.single
    data:
      device_id: diningroom
      action: single_press
    origin: LOCAL
    time_fired: '2023-01-09T05:03:12.677551+00:00'
    context:
      id: 01GPAEJG95GM4W85DN53P3STZ2
      parent_id: null
      user_id: null
  description: event 'esphome.single'```
#

ahh, shit

#

I did it again. 'device_id'

solemn frost
#

The duck never fails

inner mesa
#

Yep, you already discovered that last time

#

I was searching for it

sonic sand
silent seal
#

It's a copy of the card YAML from the dashboard

#

So if you want to paste it into the card YAML box, remove the - on the first line and outdent the whole template.
(I usually cheat by replacing the - with a space and then select the whole lot and shift tab)

sonic sand
silent seal
#

Well for the cheat I mentioned, I do it in the card view YAML mode

sonic sand
#

Oh card view, I thought we were talking about Dashboard view

#

Do you create manual card and then edit or doesn't matter which card type?

plain magnetBOT
silent seal
sonic sand
silent seal
#

I'm on mobile so can't read the text files

plain magnetBOT
#

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.

sonic sand
#

Getting the error that on the first line

#

My question is, How can I get that template (card_room) ? I assume I don't have the 2nd one too (red_no_state)

silent seal
#

If you didn't install the card first then that would be your problem

sonic sand
silent seal
#

And you cleared your cache?

sonic sand
#

I did.

silent seal
#

I'll have to look at the pastie later or maybe someone else can help, I've just spotted my missing electrician show up.

barren umbra
#

@sonic sand
I had a quick look...
Review the Configuration Templates section https://github.com/custom-cards/button-card#configuration-templates on github custom-cards / button-card.
Define your config template in the main Lovelace configuration and then use it in your button-card.
Those two templates need to be defined/added to the main Lovelace configuration outside the cards.
How you add that depends on which type of Lovelace dashboard you are using: managed or yaml which is mentioned in the section I linked to.
I believe that code is from https://ui-lovelace-minimalist.github.io/UI/usage/cards/card_room/ ?
At the bottom there is Template Code
Expand that and then add that yaml to your Lovelace via Raw Configuration Editor for your dashboard (managed) or ui-lovelace.yaml (yaml mode)

floral shuttle
# marble jackal Create the output based from the list with tuples in another for loop

getting back to this, which is working fine as it is, showing me the ordered list in a Markdown, I had hoped to only show values that are > 0. so I entered that in the dev tools like: Per Switch: {%- for e in expand(ns.energy) %} {%- set ns.sort = ns.sort + [(e.name.split(': daily')[0], e.state | float)] %} {%- endfor %} {% set sorted = ns.sort | sort(attribute='1', reverse = True) %} {% for i in sorted if i[1] %} /* typing here */ {{- i[0]}}: {{i[1]}} {% endfor %}

#

and noticed I hadnt even added >0 after that, and it already filters the correct list πŸ˜‰ How does that work??

#

why dont I need {% for i in sorted if i[1] > 0 %}

marble jackal
#

@floral shuttle becasue 0 is considered false

#

so it's removed by if[1]]

#
{{ 'hi' if none else 'bye' }} # bye
{{ 'hi' if 0 else 'bye' }} # bye
{{ 'hi' if false else 'bye' }} # bye
{{ 'hi' if 'foo' else 'bye' }} # hi
{{ 'hi' if 1 else 'bye' }} # hi
{{ 'hi' if true else 'bye' }} # hi
barren umbra
#

Useful tips to save keystrokes!

floral shuttle
marble jackal
#

0.0 == 0

#

it can also work against you
{{ state_attr('media_player.whatever', 'volume_level') | default('not available', true) }} will also display not available when the volume is set to 0

dry narwhal
#

I looked through the Jinja docs but could not find the correct filter.

Could someone help me split a string into parts based on a separator?

E.g. for every * create a new string?

*Energy*Power would result in Energy and Power
It would probably need to be an array, but I am not sure since I need to then filter the friendly name for each of the strings (that I can do, if I know how to get the partial strings πŸ™‚ )

marble jackal
#

"this*is*a*string".split("*")
result: ["this", "is", "a", "string"]

sonic sand
marble jackal
#

{{ "*Energy*Power".split("*") }} will result in ['', 'Energy', 'Power']

#

so you might want to use
{{ "*Energy*Power".split("*") | select() | list }}

#

(which will also filter out 0, false, none, but you will never have those when splitting a string)

dry narwhal
dry narwhal
floral shuttle
dry narwhal
#

Does select only allow strings of length >=1?
Because the docs make it seem like I need to enter a filter criteria

marble jackal
#

no, the select() does the filtering

#

it filters out everything which is falsely (as also discussed above) It selects anything with is not considered falsely

#

empty strings/lists/dicts are also considered falsely

#
{{ 'hi' if '' else 'bye' }} # bye
{{ 'hi' if [] else 'bye' }} # bye
{{ 'hi' if {} else 'bye' }} # bye
marble jackal
dry narwhal
#

Okay. Just wondering because true or false would be relative to the criteria. So I would have thought that empty would be ...
scratch that, you just clarified πŸ™‚

#

I will test and hopefully be able to use the list as search criteria.

maiden magnet
#

Hey
is there a way to get the appointment name from a calendar entity? By default, you only get a feedback "on" and "off" whether an appointment is running or not.
same question on Spotify: can you show the song title instead of "running" and "paused"?

silent vector
#

How would I get the most recent and oldest last updated if I had 3 last_updated attributes to compare? With 2 it's easier I just compare one against another but I'm not sure of a clean way to compare 3.

Ex.
https://dpaste.org/na8OL

sonic sand
barren umbra
sonic sand
plain magnetBOT
sonic sand
#

is it the full code? because it ends with

state:
barren umbra
#

No, it's truncated...

sonic sand
#

ok let me try to add it, does it matter if it's on top of the room_card template on the raw config or no matter where

#

Okay, I placed it on top of everything, now getting another error:

#
button-card template 'ulm_translation_engine' is missing! 
barren umbra
#

Ok, good, that's where I'm at too...

#

➜ ui_lovelace_minimalist find . -exec grep -l 'ulm_translation_engine:' {} ;
./lovelace/translations/default.yaml
➜ ui_lovelace_minimalist

sonic sand
barren umbra
#

That's the output from me searching for the code!
It's in default.yaml (293 lines)...

sonic sand
#

if it's in default shouldn't it be automatically inserted into ANY template I have?

sonic sand
barren umbra
silent vector
sonic sand
#

How come? It's a problem with the template I got.

barren umbra
silent vector
#

Yes but it's a problem in the frontend not template sensors, automation templates, triggers etc.

barren umbra
jolly crest
#

Hope this is a template case

sonic sand
#

Thanks, will move!

barren umbra
jolly crest
#

Oh ill fix

marble jackal
waxen rune
# maiden magnet Hey is there a way to get the appointment name from a calendar entity? By defaul...

I'm sure there are more elegant variants, but this might get you started with Spotify:

        {% set artist = state_attr("media_player.spotify_youraccount", "media_artist") %}
        {% set song = state_attr("media_player.spotify_youraccount", "media_title") %}
        {% set delimiter = 'by' %}
        {% if song == 'unknown' %}
          {% set song = '' %}
          {% set delimiter = '' %}
        {% endif %}
        {% if artist == 'unknown' %}
          {% set artist = '' %}
          {% set delimiter = '' %}
        {% endif %}
          {{ song }} {{ delimiter }} {{ artist }}```
narrow spire
#

Is it possible to get a range of sensor values for a given time period in a template. I.e I have a start and end time, based on a binary sensor going On then Off, I want to get the average value of a different sensor during the time the sensor was on, so far I can only find the current value of the sensor, not its history. I have seen the sensor option which seems to let you average, but that seems to expect the amount of time to average over in advance, and the binary sensor I want to monitor can vary wildly (between 3 and 30 hours).

mighty ledge
#

i.e. not templates

#

templates can't look at history

silent vector
#

How would I get the most recent and oldest last updated if I had 3 last_updated attributes to compare? With 2 it's easier I just compare one against another but I'm not sure of a clean way to compare 3.

Ex.
https://dpaste.org/na8OL

Also is there a variable for when a service was executed or can that be set? I can see it in trace but is that something a template can read?

narrow spire
#

Thanks, Ill have to find a different way to try to get what I need then

marble jackal
upper basalt
#

Trying to create a generic- room card, how can i make this select entities of device_class "humidity" ?
{{ expand(area_entities(area_id(entity))) | selectattr('humidity') }}

The above code yields "<generator object select_or_reject at 0x7f754a36f0>" ... (invalid result ...)

marble jackal
#

as soon as you start filtering, you'll get a selector

#

you need to add join or list or first or whatever to convert it to something meaningful

#

but anyway, you also need to adjust your filters

silent vector
upper basalt
#

Was that for me? adding | first or | list makes it invalid, I'm not even sure if its allowed to selectattr('humidity')

marble jackal
#

{{ expand(area_entities(area_id(entity))) | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'humidity') | map('attribute='state') | map('float') | list }}

marble jackal
#

try what I posted above, it will create a list of all states (converted to float) of the sensors

mighty ledge
marble jackal
#

yep

#
{{ expand(area_entities(area_id(entity))) | selectattr('entity_id', 'is_state_attr', 'device_class', 'humidity') | map('attribute='state') | map('float') | list }}
mighty ledge
#
{{ area_entities(area_id(entity)) | select('is_state_attr', 'device_class', 'humidity') | map('states') | map('float') | list }}
marble jackal
#

oh wait, yes

#

even better

silent vector
#

Is there a variable for when a service was executed or can that be set? I can see it in trace but is that something that available for a template?

upper basalt
#

thanks a ton both of you!

mighty ledge
#

@marble jackal it's a pain to remember that we can use those after using selectattr for so long

marble jackal
#

you'll end up with a list, I don't know if you have any room with multiply humidity sensors

marble jackal
#

πŸ˜…

mighty ledge
#

lol

#

I'm beginning to become the washed up old guy

upper basalt
#

while you're at it, is it possible to do arithmetic in the oneliner of the list? e.g take the avg of the values?

marble jackal
#

you can, but it will give an error on an empty list

#
{% set hum = area_entities(area_id(entity)) | select('is_state_attr', 'device_class', 'humidity') | map('states') | map('float') | list %}
{{ hum | average if hum else 'no data' }}
#

since when did Discord change the colors in the code BTW

mighty ledge
#

you can do this to counter it

(hum or [0]) | average
#

but it'll be 0 as a result

#

or is powerful with empty items, use it!

marble jackal
#

I always forget about or (besides for usage in if statements)

upper basalt
#

yeah, its nice to have some fallback value, cheers!

mighty ledge
#

sometimes it's just easier to use or than to sit there writing 893487392478328 lines of if else code

marble jackal
#

hehe

mighty ledge
#

I use or when default doesn't work

#

for the most part

maiden magnet
#

How can i set a text with variable value? i have my calendar, now i want an entity with the current Appointment name, how can i write this automatically in a text helper?

i mean, i need the syntax to extract the state of a string variable

and after that, how i can extract different attributes from the entity

mighty ledge
#

you'd use an automation

#

with the service that's needed to set the text

upper basalt
#

create a template?
I have this from my calendar: "{{state_attr('calendar.bosstomming', 'description')}} i morgen!"

#

where description = Calendar entry

marble jackal
#

@mighty ledge I remember I first saw you could use or that way, and I asked if it would use the other if the first was falsely, and you made a very long post with examples
Which I said I would dig into, but never did, and when I wanted to check it, I couldn't find it anymore

silent vector
#

How can I pull this into a variable?

Executed: January 9, 2023 at 8:00:36 AM

marble jackal
silent vector
#

Lol nope

#

I want to get the service execution time

#

I'm not sure if it's available or if it needs to be set right after the service is executed. Which would be off by a few seconds or something but better than nothing.

maiden magnet
upper basalt
#

where do you get the string variable from? the "Executed: ..." ?

maiden magnet
mighty ledge
#

are you referring to 'states', and 'float'? in the map?

maiden magnet
#

and the goal is, that i can extract the name of the appointment and send it to me via telegram bot

silent vector