#templates-archived

1 messages · Page 48 of 1

mighty ledge
#

if not, you could auto detect the timedelta between the first two datetimes and assume the rest

#

then make it into hourly rates

marble jackal
#

I will do some testing

#

Was working on some updates anyway

thorny snow
#

In configuration.yaml I typed as state of my select template Very Good Very Nice and the entity is now working but now where did the state information go?

mighty ledge
#

not sure what you mean by "where did it go"

#

FYI select template entities support optimistic, so you can omit the state field all together when you set optimistic to True

thorny snow
#

What does the state do

#

Why is it required to put

mighty ledge
#

pretty sure we explained it yesterday

marble jackal
#

@glacial matrix what's your timezone??

glacial matrix
#

BST at the moment, (GMT) so i guess UTC.

marble jackal
#

well +1 hours for DST then right?

mighty ledge
#

with optimistic on

thorny snow
#

What is optimistic

marble jackal
#

I was wonedering why the data for tomorrow ends at 21:30, but that doesn't explain it then

mighty ledge
floral shuttle
#

aarghh, this should be it: - platform: time at: - '20:20' - '20:25' - '20:30' condition: - > {{now().strftime('%w') == '5'}} compare to #templates-archived message ... how did I miss that 😬

marble jackal
thorny snow
#

I deleted the state line but optimistic was true

#

But it says state is required in the logs

mighty ledge
whole raptor
#

I am using riemann sum integral to keep a running total of electricity cost, but if there is a period of time where no power is used (and the cost graph becomes flat) it changes to unavailable. The history graph still shows the total, is there anyway to make it show this total instead of unavailable whilst under the condition of no power being consumed?

thorny snow
# mighty ledge `state: Item1`, i.e. no template

Btw back to the list thing. Does ist make sense to create a Picture Elements Card Configuration and put service call buttons there, then make the service call buttons service call the template and a ready service call button to inform to the template that the list is finished?

#

(Then the template will service call the roborock vacuum cleaner a list of ids that come from other buttons)

#

because I want to clean a specific room and I can put my house plan there

mighty ledge
#

I'd make input_booleans and have them on picture elements, then have a button that says "run" that calls a script. The script will look at all the booleans and then take action based on which ones are on.

thorny snow
#

to have one service call instead?

#

(btw I realized I forgot to say thanks)

mighty ledge
#

yep, 1 service call, and it's easy to test

thorny snow
#

can the picture elements card configuration yaml create a list from the buttons then send as service call to the template something like this?

- 17
  21
  18

(order is not important, that ids are from specific buttons there)

mighty ledge
#

No, you'd do that in your script

#

I don't know why you want each button to send a serivce, just have a start button that does it all

thorny snow
#

in the script from "run I mean"

mighty ledge
#

you can even make a simple config for it

thorny snow
#

I mean how does it convert to input_boelans but not to the list

#

wait do you mean "calls a script" as calls the template?

mighty ledge
#

you make a dictionary and select from the dictionary based on which input booleans are on. The dictionaries value for said input_boolean is the number associated with the room that Xiaomi likes

thorny snow
#

and where does the dictionary thing happen?

#

in the template?

mighty ledge
#

in the script

#

in a template

thorny snow
#

but how does the "run" button collect information from other buttons and send the booleans?

mighty ledge
#

all in the template

#

there's nothing to send to the boolean

#

it gets from the booleans

#

the booleans just indicate that you're going to clean that room

thorny snow
#

does the template read the picture elements?

mighty ledge
#

no

#

it only reads the booleans

#

which you put on the picture elements

thorny snow
#

oh

#

but wait

#

the buttons are not entities right?

mighty ledge
#

they are input_booleans

#

they will show up on your picture elements as an icon

#

you can click it, it will light up as "on"

thorny snow
mighty ledge
#

you can use almost any of them

#

image, icon, etc

#

they all work the same way

#

look at the demo

thorny snow
#

they are technically entities?

#

So do I need to create entities for every room?

mighty ledge
#

They are entities, they are input_booleans.

#

Yes, you need to create input_booleans for each room

thorny snow
#

but what is the difference between a call service button that is calling a service to an entity and a button that is an entity?

#

Aren't they doing the same thing in the backround?

mighty ledge
#

well, for 1, you have to set all that crap up

#

input_booleans don't need service calls

#

they are on or off, and you can click them and they turn on and off

thorny snow
#

isn't service call just a signal?

mighty ledge
#

no, it calls a service

#

a signal would be an event

thorny snow
#

what happens when I call a service that says 21?

#

I mean

mighty ledge
#

that's not a thing

#

you're really trying to go the really hard route

#

the input boolean route is VERY easy in comparison

#

and the template code is probably less than 5 lines

thorny snow
#

service: template.send_command
data:
21
entitiy_id: template

#

okay

mighty ledge
#

that's just madeup bullshit

#

there is no template.send_command

#

services are services

#

you can't make up a fake service

arctic sorrel
#

Well... you can, but it won't work

mighty ledge
#

that too

thorny snow
#

but it needs to convert than the booelans to ids

arctic sorrel
#

What?

mighty ledge
#

How about this, how many rooms do you have?

thorny snow
#

11

mighty ledge
#

ok, and what is the room to number coorelation?

#

i.e. living room is 17?

thorny snow
#

wdym

mighty ledge
#

... xiaomi allows numbers for rooms, not names

#

what's the number associated with the room name

thorny snow
#

Mutfak: 19
Yemek Masası: 18
Salon: 17
Kiler: 20
Koridor: 26
Küçük Banyo: 25
Yatak Odası: 22
Büyük Banyo: 16
Tarık'ın Odası: 27
Eymen'in Odası: 23
Balkon: 21

#

sorry for turkish names

#

I made copy paste

mighty ledge
#

and what's the service you're using to start the vacuum?

#

vacuum.send_comand?

thorny snow
#
service: vacuum.send_command
data:
  command: app_segment_clean
  params:
    - segments:
        - INSERT ID(s)
    - repeat: 1
target:
  entity_id: vacuum.roborock_s6_maxv
mighty ledge
#

This right here is a basic example template

#

using input booleans

#

doing exactly what you want

#

with a python script

#

turning that into a script would be easy, here's an example...

thorny snow
#

wait you can put python script to home assistant?

#

wait a minute the tap action is call service?

mighty ledge
#
run_vacuum:
  variables:
    config:
      input_boolean.room1: 19
      input_boolean.room1: 18
      input_boolean.room1: 17
    rooms: >
      {{ expand(config.keys() | list) | selectattr('state','eq','on') | map(attribute='entity_id') | list }}
    segments: >
      {{ config.items() | selectattr('0','in', rooms) | map(attribute='1') | list }}
  sequence:
  - service: vacuum.send_command
    data:
      command: app_segment_clean
      params:
      - segments: '{{ segments }}'
      - repeats: 1
    target:
      entity_id: vacuum.roborock_s6_maxv
#

look at that, 2 template lines and 1 script

#

script.run_vacuum is your service call for the run button

#

now just make 11 input booleans and properly fill ou tthe conifg: section and you're done.

thorny snow
mighty ledge
#

Yes

#

noooooooooooooooo

#

jesus dude

thorny snow
#

wait I understood the yes as something else

mighty ledge
#

please take 5 minutes to understand what an input_boolean is

thorny snow
#

true/false yes/no on/off 1/0?

arctic sorrel
#

on and off, yes

plain magnetBOT
thorny snow
#

how does the input_booelan be in the script?

mighty ledge
#

it's in there, in the template

thorny snow
#

💀

#

ok

#

but wait a minute

mighty ledge
#

I use trickery to do things there, but trust me, it gets the states of the input_booleans

thorny snow
#

why is it an entity in the button yaml in the demo?

#

is the entity in the template and still counted as entity?

mighty ledge
#

I don't understand your question

arctic sorrel
#

You still have to create those entites listed in the template - putting them in the template doesn't create them

mighty ledge
#

Yes, that is correct

thorny snow
#

then how does the entities/input_booelans information go to the python script

#

does the script read that

#

does it count as variable in the script?

mighty ledge
#

do you understand how HA works?

plain magnetBOT
#

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

thorny snow
#

idk

mighty ledge
#

well, to me it seems like you're lacking basic knowledge of entities in home assistant

thorny snow
#

because I'm new to home assistant

mighty ledge
#

and you're trying to come up with something complicated and you're unwilling to learn the baby steps

thorny snow
#

where are the baby steps?

mighty ledge
#

creating a simple helper like an input_boolean, putting it in an elements card to see what it does and how it behaves

#

then, subsequently, using a template to get the state of the input_boolean

#

then, watching what happens to the template result when you click the input_boolean in the UI

thorny snow
#

do I need to create it in the configuration.yaml?

mighty ledge
#

none of what I just said needs configuration.yaml

#

you can create helpers in the ui, you can create the picture elements in the ui, and you can test templates in the ui

#

you might need 2 browsers side by side to do the template testing portion when clicking the item in the picture elements

thorny snow
#

oh I found the "Helpers"

thorny snow
#

I just couldn't find out how to find the state of one specific entitiy

#

what I found was a list of states of some entities

#

okay I found it

#
{{ states('input_boolean.agu') }}
#

agu is the name of my input_boolean

thorny snow
#

it says on or off

#

but that {{ states(entity.id) }} thing doesn't exist in the script you sent?

arctic sorrel
#

It is in the docs linked from the channel topic here, but Petro tackled it in other ways

thorny snow
#

so do I have to add other things than that script?

mighty ledge
#

as for the script, you need to add your input_booleans to the config section of that script

thorny snow
#

but how does it take the state without jinja

mighty ledge
#

e.g.

....
  config:
    input_boolean.agu: 15
mighty ledge
#

expand(config.keys() | list) makes a list of state objects. config.keys() | list is the list of input boolean entity_ids

thorny snow
#

yeah it was it the whole time

mighty ledge
#

the rest is filtering down to input booleans that are on

#

I was trying to tell you that it does everything you want and it's easy to maintain

thorny snow
#

and should I use helpers in the picture eleements

mighty ledge
#

corrrect

#

and you can make a picture-element button that calls the script

thorny snow
#

okay thank you a lot

mighty ledge
#

np

glacial matrix
marble jackal
#

ah, so before 4 to 6 pm you don't even have all the data of today?

glacial matrix
#

no i might only have data up to 9pm that day.

#

I'm happy for the template to calculate the above for 9pm to 9pm

#

So right now, i have this, and i wont get any more information until between 4 and 6 tomorrow.

plain magnetBOT
#

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

marble jackal
#

and that is the data from an attribute?

#

what is the entity_id and the attriubte key

crimson lichen
#

hi,
I had state of sensor with format: 123456789.
I want reformat above number to 123,456,789
How to do that
Thanks

marsh cairn
#

I'm using the following template to get the cheapest gas station nearby from the tankerkoenig integration.

  |selectattr('entity_id', 'search', '_diesel$')
  |rejectattr('entity_id', 'eq', 'sensor.template_diesel')
  |selectattr('state', 'is_number')
  |rejectattr('state', 'eq', 'unknown')
  |map(attribute='entity_id')
  |list) %}
{% set nameslist = nameslist|sort(attribute='state',reverse=false)|map(attribute='entity_id')|list %}
{{ states(nameslist[0]) }}```
If two (or more) gas stations are the same price, it sorts alphabetically.
Is it possible to sort the lowest price stations by distance (with reasonable effort)? The entities provide latitude and longitude in their attributes and can be seen on the map.
marble jackal
marble jackal
# marsh cairn I'm using the following template to get the cheapest gas station nearby from the...

can you try this?

{% set nameslist = expand(states.sensor
  |selectattr('entity_id', 'search', '_diesel$')
  |rejectattr('entity_id', 'eq', 'sensor.template_diesel')
  |selectattr('state', 'is_number')
  |rejectattr('state', 'eq', 'unknown')
  |list) %}
{% set ns = namespace(list=[]) %}
{% for n in nameslist %}
  {% set ns.list = ns.list + [dict(e=n.entity_id, s=n.state | float, d=distance(n.entity_id))] %}
{% endfor %}
{% set sorted = ns.list | sort(attribute='d,s', reverse=false) | map(attribute='e') | list %}
{{ sorted[0] if sorted else 'no stations found' }}
pastel moon
#

I have this template {{ (((states('sensor.dishwasher_w') | float < 2.7 ) and (states('sensor.dishwahser_a') | float < 0.1 )) or (states('sensor.dishwasher_w') | float < 0.1)) | default(false) } It started complain not having default value set so I added the last part. template shall eveluate to true or false so should be adequite, no?

marble jackal
#

no, it will still complain about missing defaults

pastel moon
#

I noticed... So what would I need to do please?

marble jackal
#

where are you using this?

pastel moon
#

In a trigger

#
    value_template: "{{ (((states('sensor.dishwasher_w') | float < 2.7 ) and
                          (states('sensor.dishwahser_a') | float < 0.1 )) or
                          (states('sensor.dishwasher_w') | float < 0.1)) |
                          default(false) }}"
    id: "dishwasher_off"
    for: "00:05:00"```
crimson lichen
marble jackal
marble jackal
pastel moon
marble jackal
#

you could also use states('sensor.dishwasher_a') | is_number

pastel moon
crimson lichen
marble jackal
#

so that's not what you said, you said you wanted to diplay it on the front end

#

but okay

crimson lichen
marble jackal
#
{% set value = 703747 %}
Tiền tháng này Công tơ Mẹ-303 là {{ "{:,}".format(value) }} VNĐ. +--> 13:53:34 Sun, 09-Apr
#

output: Tiền tháng này Công tơ Mẹ-303 là 703,747 VNĐ. +--> 13:53:34 Sun, 09-Apr

marsh cairn
marble jackal
#

Never used two options for sort before, so I wondered if it would sort correctly

#

Good to hear it works

sonic ember
#

@marble jackal Your macro is working brilliantly, thanks! In future I'm going to have to build my own array similar to the nordpool one for predicted solar production... Once I have my panels, but then I can still use the same macro.

#

Do you have any thoughts on how to implement a "deadline" in my timing? In my own script I had a time range within which I looked for the cheapest time (for example if I want my dishwasher to finish before 6pm), but I'm not sure how to do that with yours other than changing the input list of prices into a new entity.

marble jackal
#

Did you look at the documentation? You can provide a start and end for the datetime values which are used

sonic ember
#

ARRRG you're right sorry. Sometimes I forget to go back into the documentation when I've gotten my first part of the project to work

#

RTFM man! 😄

heavy crown
#

H all, I am trying to use the new image entity (template) where the picture changes every hour or so. After a back/forth with Frenck, he stated the template needed an update action, not the entity itself. Now I am struggling how to set this up with a trigger. This is what I have

#
template:   
  - trigger:
      - platform: time_pattern
        # This will update every quarter past
        hours: 0
        minutes: 15
    image:
      - name: MF_alert_today1
        url: http://192.168.1.20:8123/local/pictures/meteo_france_alert_today.png    
  
  - image:
      - name: MF_alert_today2
        url: http://192.168.1.20:8123/local/pictures/meteo_france_alert_today.png  
#

the first one is created but has no picture

#

the second one, outside of the trigger, is how the original setup is supposed to be and this indeed works

#

Why does the triggered 'image' not work?

marble jackal
#

the first one will update as soon as it's triggered

heavy crown
#

so not after the restart o fHA?

marble jackal
#

which is not every quarter past, it's only at 00:15 with your current trigger

#

no, only when it's triggered

heavy crown
#

yeah I know typo

#

ok

marble jackal
#

it will restore it's state after a HA restart

heavy crown
#

thanks...will try to trigger it earlier, to not wait 5min from now and restart

marble jackal
#

you can add HA restart as a trigger though

heavy crown
#

I set the trigger to minutes: 51

#

no update

marble jackal
#

what is your current trigger?

pastel moon
#

has_value below returns false, but if I use is_number it returns true... ```{{ states('sensor.washing_machine_a') }}
{{ states('sensor.washing_machine_w') }}
{{ states('sensor.washing_machine_a') | is_number }}
{{ states('sensor.washing_machine_w') | has_value }}

heavy crown
#

as per the yaml above

#

nothing else

marble jackal
#

so

  - trigger:
      - platform: time_pattern
        # This will update every quarter past
        hours: 0
        minutes: 51
#

?

heavy crown
#

yes

marble jackal
#

that's at 00:51 only

heavy crown
#

after restart no update, waited till 52

#

nothing

#

ah

marble jackal
#

like I already mentioned before

heavy crown
#

/51

marble jackal
#

no

#

just remove the hours: 0 line

heavy crown
#

duh...

marble jackal
#

there you define that the hour must be 0

marsh cairn
marble jackal
#

okay, that was indeed the part I was unsure of

marsh cairn
#

I had to wait for some price changes

marble jackal
#

you are now providing a state (so a string)

marble jackal
pastel moon
#

you did, and that confused me a little... I thought it was to challenge me, sorry!

#

I will try as you did it then

marble jackal
#

no, that's also why the the filters are IS number and HAS value

#

the first one checks if a specific input IS something (a numeric value in this case)

#

the second one checks if the input HAS someting (a valid value for it's state in this case)

pastel moon
#

Got it. 🙂

sonic ember
#

Not sure if that makes sense, it confused me when I read it back.

marble jackal
#

if you want it to end at let's say 18:00 today, you should indeed not set include_tomorrow: true

sonic ember
#

Ok, so then what I think will make sense is that I have that selector change based on when my "desired" datetime is.

#

Should be doable with simple if statement

sonic ember
#

Is there an easy way in Jinja to check if a datetime is today or tomorrow?

heavy crown
# marble jackal just remove the `hours: 0` line

The things seems to work , changed_at and updated_at show every 3 mins ( I changed it to /3), however, the image entity continues to show the picture that was there when the image entity was created ...changing the PNG does not do a thing. Frenck stated that I needed to re-render the image template and suggested a trigger for that....but to no avail so far. Any idea what os going wrong here?

mighty ledge
#

you have a hardcoded image string with no template, therefor there's no tempalte to update, therfor nothing updates

#

just output the image url from the template itself and the trigger should handle the updates

#

that's what he means by "rerender"

heavy crown
#

ok...I am slow in understanding...output-the-image form the template?

#

example?

mighty ledge
#

do you know what a template is?

heavy crown
#

yes....

mighty ledge
#

ok, do you know how to output with a template?

heavy crown
#

clearly not

mighty ledge
#

see the pins

#

2nd pin

heavy crown
#

very sorry, does not seem to be my day at all... ? pin ?

#

I wrote tens of template stuff, never used 'pin'

mighty ledge
#

I know you've written 10's of template stuff, i've helped you with alot

#

anyways read the 2nd pin

heavy crown
#

I know you did and.... I am sorry to say that I donot see any pins with my messages, is not my day ...hot / tired

mighty ledge
#

dude, it's a discord function

#

it's at the topofthe page

heavy crown
#

bloody hell....yeah....

mighty ledge
#

if you're on mobile, it might require you to click aroudn up there

#

on mobile its hidden behind the people icon

heavy crown
#

sigh...thanks....

marble jackal
#

for today

floral shuttle
#

having this template: {{states.geo_location |sort(attribute='state') |map(attribute='entity_id') |first}} and using that inside an auto entities give me the single strike just fine and clicking that shows all attributes of the entity_id. I also use it as an attribute on a template sensor as the image shows (btew note the entity_is attribute is not on the card)

#

however, I cant click that entity in a card for more-info )(as ifd it were the actual geo_location entity_id.. somehow I seem to not see how I should do that

marble jackal
#

note you are sorting on strings now. If there would be two strikes, this one 71.6 km away, and another one 9.2. km away, the one of 71.6 km away will be displayed on your auto entities card

floral shuttle
#

this is what I would love to do in the entities card:

marble jackal
#

try {{ [ "71.6", "9.2"] | sort | first }}

#

and {{ [ 71.6, 9.2] | sort | first }}

floral shuttle
#

a bit more than 2 😉

marble jackal
#

fine, but these are integers

#

states are strings

#

and you are sorting on states

#

and as your current output all has 2 digits before the . this will sort fine as strings

floral shuttle
#

a yes, I see what you mean

marble jackal
#

but not if theres a strike at 10.2 km and then at 9.9 km

floral shuttle
#

using this as template sensor {% from 'lightning.jinja' import strikes %} {{strikes().split(',')|reject('eq','') |map('states') |map('float',default=0) |sort|first}}

marble jackal
#

yes, but now you don't the entity_id available anymore

#

and if one of them is unavailable or unknown, you will get 0

mighty ledge
#

TLDR: You can't do this in a 1 liner

#

the strikes could return a list of dictionaries as json, then use |from_json

#

you could also just use all " and then use |from_json too

#

at least taht's what I would do

#

lists of dictionaries are easy to manage with generators. They turn everything into 1 liners

floral shuttle
#

that needs some more explanation for me.... Ive been able to manage this far, and now see there are even 2 strikes for the same distance.... {% from 'lightning.jinja' import strikes %} {% set distance = strikes().split(',')|reject('eq','') |map('states') |map('float',default=0) |sort|first %} {{states.geo_location|selectattr('state','eq',distance|string)|list }}

mighty ledge
#

what does strikes() look like?

floral shuttle
#
{%- macro strikes() -%}
{{- states.geo_location
      |selectattr('attributes.source','defined')
      |selectattr('attributes.source','eq','blitzortung')
      |map(attribute='entity_id')
      |join(',') -}}
{%- endmacro -%}```
mighty ledge
#

change that to

#
{%- macro strikes() -%}
{%- set ns = namespace(items=[]) -%}
{%- for so in states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','blitzortung') -%}
{%- set ns.items = ns.items + [ {'entity_id': so.entity_id, 'state': so.state | float(None)} ] -%}
{%- endfor -%}
{{- ns.items | to_json -}}
{%- endmacro -%}
#

then

#
{% from 'lightning.jinja' import strikes %}
{{ strikes() | from_json | sort(attribute='state') | first }}
floral shuttle
mighty ledge
#

and... if you want to find multiple close ones...

#
{% from 'lightning.jinja' import strikes %}
{{ strikes() | from_json | groupby(attribute='state') | sort | first }}
marsh cairn
#

I'm totally going to copy that

mighty ledge
#

its copywrited

#

NO SOUP FOR YOU

floral shuttle
#

my use case is check if the nearest is within x km, create binary for that and use that as conditional in Dashboard to show Map.... also, I need to be able to have the entity_id singled out, so I can show its attributes.... let me fiddle about with this

marsh cairn
floral shuttle
#

as this is my first to_json/from_json I need to read up on that

mighty ledge
#

not much to read up on

#

to_json takes the object and turns it into a string that looks like json

#

from_json takes a string and tries to turn it into an object, if it succeeds, you get the object

floral shuttle
#

right, sounds simple enough 😉

#

the groupby does this

mighty ledge
#

correct

#

if you want just the list and not the value

#
{% from 'lightning.jinja' import strikes %}
{{ strikes() | from_json | groupby(attribute='state') | sort | first | last }}
floral shuttle
#

and how do I select the entity_id in {{ strikes() | from_json | sort(attribute='state')|first }}?

mighty ledge
#

how would you do that with any object?

#

pretend it's a state object

#

how would you get the entity_id from a state object?

floral shuttle
#

you mean like:```
{{ (strikes() | from_json | sort(attribute='state')|first).entity_id }}

marble jackal
#

or {{ strikes() | from_json | sort(attribute='state') | map(attribute='entity_id') | first }}

mighty ledge
#

yep, either of those

floral shuttle
#

really nice indeed! thx a bunch

#

only thing left: how to get that as a clickable entity in the dash.... believe we can only do that using the map and a template filter in auto-entities... not in an entities card

mighty ledge
#

I mean, you can make a template sensor from it

floral shuttle
#

yeah I have that, but that wont open a more-info with the attributes if the geo_location entity

mighty ledge
#

Not sure I follow you

#

if you make a template sensor with all the attributes of the geo_location entity, then you essentially have a geo_location entity

#

just in the sensor domain

floral shuttle
#

I could build that yes, but that seems a bit overdoing it. currently have: - unique_id: lightning_strike_nearest state: > {% from 'lightning.jinja' import strikes_object %} {{ (strikes_object() | from_json | sort(attribute='state')|first).state }} attributes: entity_id: > {% from 'lightning.jinja' import strikes_object %} {{ (strikes_object() | from_json | sort(attribute='state')|first).entity_id }}

#

I would have hoped to be able to click that entity_id , but, it isnt even shown 😉

#

If I click it in the Map

#

it nicely shows all attributes. So that map turns the template back into the entity_id.

#

for that, we need to use the template filter in auto-entities, and it takes care of it.

marble jackal
#

you probably only need the longitude and latitude attrubutes

mighty ledge
#

I guess I don't understand what you mean by "click that" as it looks like the LS is the entity you'd click on.

mighty ledge
#

for it to show up on a map

marble jackal
#

apparantly it already shows up on the map becasue of the entity_id in the entity_id attribute

#

at least, that's how I understand it from these screenshots

mighty ledge
#

I'm not sure why that would work, but that could be the case.

marble jackal
floral shuttle
#

no, just the template```
filter:
template: >
{% from 'lightning.jinja' import strikes_object %}
{{(strikes_object()
|from_json|sort(attribute='state')|first).entity_id}}

{{states.geo_location

|sort(attribute='state')

|map(attribute='entity_id')

|first}}```

#

and as alway, when testing the lightning stopped....

#

btw, the sensor turns unavailable so I need a guard, I do want it to remain available, but show no strikes, or none

marble jackal
#

ah okay, so the map card shows the geolocated entity

floral shuttle
#

yes, and that is why I said we need Map/auto-entities/filter template and cant use an entities card with that template sensor entity.

marble jackal
#

okay, but it should display the more info dialog on your dashboard as well when you click it

#

do you have it in a browser mod popup maybe?

floral shuttle
#

yes, but that holds nothing, not even the attribute (no, not in browser mod)

marble jackal
#

I think there is an issue with tap actions in auto-entities

#

my updates card also doesn't work

floral shuttle
#

everything works fine here, I can tap/hold all auto-entities entities

marble jackal
#

you were just saying that you'd expect a more info dialog when clicking that entity in a auto-entities card and that it doesn't work

floral shuttle
#

no, in a regular entities card ... but, there is nothing to show on that template sensor, other than a possible entity_id (which is hidden)

marble jackal
#

ah, yeah sure, in a regular entites card showing just that template sensor you won't get a map on a more-info card

#

unless you provide a longtitude and latitude attriubte

floral shuttle
#

yes, I guess we would a new template entity entity for that 😉

mighty ledge
#

now I hope you understand my previous comment on that then 😉

floral shuttle
#

how do I check for that empty object? I tried {{strikes_object()|length }} but even when empty that equals to 2 ?? while {{strikes_object()}} is an empty list []

#

seems its counting the brackets too?

tight adder
#

hi, i'm trying to get the day of the week from my forecast weather :
`forecast:

  • datetime: '2023-07-21T05:00:00+00:00'
    cloud_coverage: 65
    precipitation_probability: 88
    ...my code is :day_of_week: "{{ ['LUN.', 'MAR.', 'MER.', 'JEU.', 'VEN.', 'SAM.', 'DIM.'][state_attr('weather.home', 'forecast')[0].datetime.weekday()]}}"`
    but it returns null. Any idea ?
mighty ledge
#

check your errors in the logs

tight adder
#

TemplateError('UndefinedError: 'str object' has no attribute 'weekday'') while processing template 'Template<template I should think more aboutr logs 🙂

marble jackal
mighty ledge
tight adder
#

so simple 🙂 thx

floral shuttle
# mighty ledge from_json 😉
         {% from 'lightning.jinja' import strikes_object %}
          {% set strikes = strikes_object() | from_json %}
          {% if strikes|length != 0 %}
          {{ (strikes| sort(attribute='state')|first).state }}
          {% else %} No strikes
          {% endif %}```
mighty ledge
#

Ya

#

or

#
{{ (strikes_object() | from_json | sort(attribute='state') | first | default({'state':'No strikes'})).state }}
#

you can also build no strikes into the strikes_object()

#

so first always works

floral shuttle
#

btw, can confirm the attribute entity_id to be filtered out in the Frontend, changing that to entity helps make it show

floral shuttle
gaunt peak
marble jackal
#

change {{ event.start }} to {{ as_datetime(event.start).strftime('%H:%M' }}

gaunt peak
#

Error rendering data template: UndefinedError: 'str object' has no attribute 'strftime'

marble jackal
#

oh sorry

#

fixed it

gaunt peak
#

Ok, that works. Thanks.
I also made an assumption and added a ) after the %M'

One thing I didn't realize is even though it's called event.start, it has the ending time as well and it cut that out even though I'd like to keep it but I think I can figure that one out. Or at least will try for a bit.

Thanks for your help.

pastel moon
#

Hi again. I'm struggling with some template triggers. Whatever I try only the topmost works. The other two should do the same thing, right? https://dpaste.org/Wqnrt

#

Thing is, I need a template as there's more to it than this, but simplified to isolate the issue (or tried to)

inner mesa
#

the last one is just bad syntax

pastel moon
#

oh. I see, missing a pipe, corrected

inner mesa
#

in the last two, you need to remove the surrounding quotes

#

sorry, didn't evaluate the templates properly. In any case, your problem is that you've surrounded a multi-line template in quotes

pastel moon
#

Noooo? Speant a good amount of time on this tonight... I'll try again, this time without them...

#

Thanks Rob, it now works as I need it again... Wonder why I added them... I always run the ha core check though, but it won't fail on things like that...

inner mesa
#

it will just be evaluated like any other string

pastel moon
#

True. Anyways, thanks, on to the next challenge! 🙂

tired sandal
#

I have an array of objects in this format:

[{ "date":"2023-02-20T00:00:00.0000000Z" }]

I'd like to iterate through the array and reformat every date to simply show the day of the week (i.e: "Monday, Tuesday" etc.). Is there a way to do that using pure functions? Normally, I'd use map in JavaScript, but Jinja2 seems to treat that a little differently.

#

Ideally there'd be a way to pass some kind of arbitary transform function into the map filter to act on each object on the way through but that seemingly isn't possible (as far as I can tell, anyway)

gaunt peak
#

Strftime might be able to help you too. I just learned about it for my use case. Try with a %A?

tired sandal
#

right but can you apply that as a filter to a list?

#
{{ data | strftime('%A') | list }}

TemplateAssertionError: No filter named 'strftime'.

Evidently not.

marble jackal
#

No, it's a python method, you can only use it like some_datetime.strftime('%A')

tired sandal
#

Bummer. Meantime - is there a native way to check in a template if a given date is between two other dates?

#
{% set end = (state_attr('calendar.trash_schedule', 'start_time') | as_datetime | as_local ).date() - timedelta(days=1) %}
{% set start = end - timedelta(days=6) %}

I want to check to see if a given date is between start and end

#

One thought I had was to write a loop to generate a list of dates manually, then use element in list to check. But there must be a better way, surely.

#

....I can just use < and >. Can't I.

#

🤦‍♂️

terse walrus
#

Could you convert to timestamps and then compare?

#

{{ end | as_timestamp }}

tired sandal
#

Probably, but it seems like I don't even need to do that.

#
{% set date = end_date - timedelta(days=3) %}

{{
  date > start and date < end_date
}}
#

that returns true.

#
{% set date = end_date + timedelta(days=3) %}

{{
  date > start and date < end_date
}}

that does not.

terse walrus
plain magnetBOT
#

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

marble jackal
topaz basin
#

is it possible to pad now().hour so I get the following?

00
01
02
03
...
12
13
14
...
22
23
mighty ledge
#

'%02d'%now().hour

topaz basin
#

right, thanks for the answer

#

btw is there any way to force it to return time in other timezone

mighty ledge
#

No

#

You’d have to do a bunch of math

topaz basin
#

why is that not a feature yet 🗿

mighty ledge
#

And it gets complicated with dst

topaz basin
#

nah don't have dst in that timezone

mighty ledge
#

Because no one added it

pastel moon
#

on the subject, there wouldn't be a way to translate Swatch Internet Time to local time and vice versa?

mighty ledge
#

There’s a way to do utc to local, that’s it

pastel moon
#

Ok. Nice beats are supported though, not many knowing about it 🙂

earnest cosmos
#

Hi, guys! I need to concatenate a string for a notification. This string should consist of which plants being watered at the moment. I was planning to build a template sensor like below, but my knowledge stopped when assembelling the new concatenated string.

#

I started with this; using the state for what valve is open, and was planning to use "If valve is open, then true, and use in contcatendated string.

template:
  - sensor:
      - name: "Irrigated now"
        state: >
          {% set lavendel = is_state('switch.vanning_k1_lavendel', 'on') %}
          {% set tomatoes = is_state('switch.vanning_k5_tomater', 'on') %}
          {% set herbes = is_state('switch.vanning_k6_herbes', 'on') %}    
## put togheter the string based on what valves are open (ON)
#

My final string should look like: Now watering lavendel, tomatoes, herbes...

lyric comet
#

I would add all your sensors you want to monitor into a group (in Helpers). Then use something like:

{{expand('light.hall') | selectattr('state', 'eq', 'on') |
map(attribute='attributes.friendly_name')| join(', ') }}

replacing light.hall with your group name. It will use the friendly name of your switches, so you might need to use replace to strip out any extra text you don't want.

floral shuttle
#

if only... this seems odd...

#

also in (half) translation..

marble jackal
#

One time event

haughty breach
marble jackal
#

My version

{% set w = states.switch
            | selectattr('object_id', 'search', '^vanning_k')
            | selectattr('state', 'eq', 'on')
            | map(attribute='entity_id')
            | map('regex_replace', 'switch.vanning_k.*_', '')
            | list
%}
{% if w | count > 0 %}
Now watering {{ (w[:-1] | join(', ') ~ ' and ' ~ w[-1]) if w | count > 2 else w | join(' and ') }}
{% endif %}
hazy yacht
#

Hi, I am simply trying to create a value in a template without any fractions (Android template Widget) . The value I get is a string in kWh and I want to display Wh as integer. I tried
Forecast:
{{states('sensor.energy_production_today') |float *1000 | int}} Wh<br>
Also different ways of using the round filter. However, what I noticed, as soon as I do the multiplication with 1000 I get some floatingpoint precision problem and whatever filter I apply after that, I can't get rid of it.
Example:
String:4.130
Float: 4.130
*1000: 4130.000000000005
Round(0): 4130.0000000005
Int: 4130.000000000005

#

So I run out of ideas what I am doing wrong here

inner mesa
#

you're rounding 1000

#

you need to add parentheses

hazy yacht
#

If I do, I get an error message in the Widget

#

I don't get why and I see your point

#

So to be more specific, in an android template Widget the following results in a error message and prevents to save the Widget

{{states('sensor.energy_production_today') |(float *1000) | int}} Wh<br>

inner mesa
#

your parentheses are in the wrong place

#

{{(states('sensor.energy_production_today') |float *1000) | int}}

#

you added an unmatched closing paren

#

(float*1000) doesn't make any sesnse

hazy yacht
#

Ahhh OK, I thought that (float * 1000) would force the result of that send down the filter

#

@inner mesa working now.... At least no error, need to wait to see if rounding works, as the PV system switched off a long time 😉

inner mesa
#

you can set the state of that sensor to whatever you want

hazy yacht
#

I know, I am just on my mobile at almost 1 am... Writing templates on mobile is a bit of a challenge, I leave the testing for later on my laptop 😜 Thanks again

jagged knoll
#

How would I create a template binary sensor for a automation that acts on a binary sensor trigger
this is the device (this outputs closed/opened)

{{ states('cover.z_wave_garage_door_controller') }}

dreamy sinew
#

if it only has 2 outputs, you don't really need an extra sensor do you?

jagged knoll
gaunt peak
#

I have a super basic template sensor that seems to have failed.
- name: Today or Tomorrow
state: >
{{iif(now() > today_at("17:30"),"Tomorrow","Today")}}
Then in an automation (or template page)
{% if is_state('sensor.today_or_tomorrow', "Today" ) %}
{% set n = 0 %}
{% else %}
{% set n = 1 %}
{% endif %}

If sensor.today_or_tomorrow = Today, I get an error if it's anything other than today (ie; tomorrow) I get a 1.

inner mesa
#

'An error'

gaunt peak
#

Right, my bad
ValueError: Template error: int got invalid input 'None' when rendering template '{{ states('sensor.time_of_day_greeting') }} {{ states('sensor.today_or_tomorrow') }}'
{% if is_state('sensor.today_or_tomorrow', "Tomorrow" ) %}
{% set n = 0 %}
{% else %}
{% set n = 1 %}
{% endif %}

#

Oh wait. I think I got it.

#

It's this chunk. It doesn't like the [0] but [1] works. I'll have to look at the sensor again.
{{ state_attr('weather.redacted', 'forecast')[0].temperature|int }}

#

Ah
"temperature: null"
That'll do it.

sonic sand
#

Hi, I'm getting this warning on Logs

Logger: homeassistant.helpers.template
Source: helpers/template.py:735
First occurred: 10:44:38 AM (1 occurrences)
Last logged: 10:44:38 AM

Template variable warning: 'dict object' has no attribute 'ir_code_to_send' when rendering '{{ value_json.ir_code_to_send }}'

Where is this template sitting and how can I fix this warning?
Thanks!

earnest cosmos
#

I really loved the "and" put in there when more than one item and commas otherwise 🙂

lofty timber
#

Is there a way to have an automatinon trigger, if any door opens and have it fll that doorname as text into the notification action without 100 if clauses?
Example.: Front door opens -> Notification: "{Doorname} is open"

inner mesa
#

How do you identify doors?

lofty timber
#

binary sensor from an aqara door sensor @inner mesa

inner mesa
#

I'm asking about how you know which entities are doors

marble jackal
#

There is a device_class: door for binary_sensor, but I guess it can be dependent on the Zigbee integration and other factors if they identify as door or window

lofty timber
marble jackal
#

Easy solution:
List all door sensors in a state trigger and use trigger.to_state.name in your message

lofty timber
#

ah that easy? lol Thanks!

#

That also works for device battery levels?

marble jackal
#

Yes, but you'll get one notification when it crosses your threshold (eg below 20 percent) per entity

plain magnetBOT
#

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

crimson sun
pastel moon
#

Thinking of doing a macro to return this data, is there a more efficient way of getting the same functionality? https://dpaste.org/FG0YJ

#

I'm trying to avoid having same or similar definitions spread all over the place...

inner mesa
#

Macro is fine

pastel moon
#

Thanks 🙂

pastel moon
#

Hm. Macro turned out fine, but where do I put the import in scripts? Can it be put in the variables section somehow?

#
{{ light_data('hallway','brightness','day') }}```
#

2nd row is what feeds the parameter, but the first, do I need it more than once for each file?

#

or better yet, perhaps in configurations.yaml?

inner mesa
#

Each template

pastel moon
#

Ok, so once for every use basically?

#

Ok, thank you

torpid crag
#

Hi All, I have a gas bottle sensor that converts weight into a percentage. How can set it so that 100% is the max?
state: > {{ (states('sensor.tasmota_hx711_weightraw') | float - 927) | float / 10000 * 100 }}

inner mesa
#

{{ ([(states('sensor.tasmota_hx711_weightraw') | float - 927) / 10000 * 100, 100]|sort)[0] }}

#

without going into that formula at all...

torpid crag
loud otter
#

Hi, can someone please help me to create a valid template to replace 2 words in a state name ?
This is working :

{{trigger.to_state.name|replace('Occupancy','')}}:{{as_timestamp(trigger.to_state.last_changed)|timestamp_custom('%X')}}

I want to replace not only the word "Occupancy" but also the word (EP1).

young laurel
#

How can I use state_attr for retrieve of media player shuffling status. this isn't working:
'{{ state_attr("media_player.spotify_nr", "shuffle") }}'

marble jackal
loud otter
marble jackal
marble jackal
young laurel
marble jackal
#

But sure what you mean with that

edgy flume
#

Hi all - I have a script that is giving me a weird result in return - am I allowed to paste it here for some support? It's fairly long...

plain magnetBOT
#

@edgy flume 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.

edgy flume
#

Alrighty - so I have a script that's supposed to return "There is audio is being playing [ROOM] [SPEAKER NAME(S)] " but something very strange is happening in the output: "There is audio playing upstairs from: [, U, n, d, e, f, i, n, e, d, ,, , U, n, d, e, f, i, n, e, d, ,, , U, n, d, e, f, i, n, e, d, ] https://dpaste.org/FXpC6

mighty ledge
#

you'll want to just use the states method in your test instead of selectattr

#

or is_state

#

selectattr('entity', 'is_state', 'playing') instead of that giant mess

#
{{ speakers | selectattr('location', 'in', ['upstairs']) | selectattr('entity', 'is_state', 'playing') | map('state_attr', 'friendly_name') | list }}
#

and because you don't have state objects, you can't map name

marble jackal
#

alternative would be to add them to your speakers variable, but this is a lot easier 🙂

mighty ledge
#

well, personally, I'd approach it differently all together

marble jackal
#

I would use groups I guess

#

or areas

mighty ledge
#

I'd probably stick with this but a single persistent_notification

marble jackal
#

I would create a media_player group in the GUI, eg media_player.main_floor and then use:

{{ expand('media_player.main_floor') | selectattr('state', 'eq', 'playing') | map(attribute='name') | list }}```
mighty ledge
#

I still don't fully utilize areas

#

missing a quote there

#

Huh, when did they add media player groups?

#

interesting

edgy flume
#

Thanks all I’m very new to this, will try it out and report back 🙂

hollow oar
#

Is it possible to set diffent device_class on different attributes in a template sensor? I have tried everything i can think of without success. Anyone know how to do it?

    sensor:
      - name: Time and temp
        state: ok
        attributes: 
          time: > ## I want this to be device_class timestamp
            {{ states('sensor.date_time') }}
          temperature: > ## I want this to be device_class temperature
           {{ states('sensor.openweathermap_temperature' }}
lyric comet
#

No, my understanding is device class is defined at the Entity level, so you will need to set up two sensors rather than one. What are you trying to achieve?

#

You can store a timestamp and a number in attributes.

marble jackal
#

attributes can't have device classes.

#

attributes can store native types though

#

so numbers will be numbers, and datetimes will be datetimes

hollow oar
#

I have a couple of rest sensors that extract time and date from a API that i got help with here a couple of days ago. This works fine when i have a separate sensor for every time. I am trying to achieve to extract this from the json sensor i have and but it in one sensor with attributes.

  - platform: rest
    resource: http://ergast.com/api/f1/current/last/results.json
    name: F1 - last race time
    device_class: timestamp
    scan_interval: 3600
    value_template: >
      {% set item =  value_json.MRData.RaceTable.Races[0] %}
      {{ (item.date ~ 'T' ~ item.time) | as_datetime | as_local }}
#

To minimize the amount of sensors and cals to the API

mighty ledge
#

don't use the rest platform

#

use the rest integration

#
rest:
- resource: http://ergast.com/api/f1/current/last/results.json
  scan_interval: 3600
  sensor:
  - name: F1 - last race time
    device_class: timestamp
    value_template: >
      {% set item =  value_json.MRData.RaceTable.Races[0] %}
      {{ (item.date ~ 'T' ~ item.time) | as_datetime | as_local }}

  - name: ...
    device_class: timestamp
    value_template: >
      ...

  - name: ...
    device_class: temperature
    value_template: >
      ...
hollow oar
#

Yes, did that before but that creates one sensor for every time. What I am trying to achive is to have all in one sensor with attributes, but if I understand it right it´s not possible

marble jackal
#

if it is to minimize api calls, the approach above achieves that, becuase it does one call, and then creates all the sensors

hollow oar
#

Yea that´s right, it minimizes the amount a lot. Thanks!

quiet kite
#

hello, i need to control fan speed over modbus, i want to do it by slider. My problem is that i need to map values to percents, for example i need to send 5 to set 30%, and 8 to set 40% speed. How can i do this slider?

mighty ledge
#

a template number

#

or an input_numer with an automation

#

does your modbus offer a sensor that provides the current slider setting? I.e. does it tell you that it's at 5 after you send 5 to it?

quiet kite
#

yes, this is read and write addresses

mighty ledge
#

ok, then a template number is the best route to go

#

if you post the entities, I can help you with the yaml and the templates inside the yaml.

#

also post the service you'll be using the send the command

quiet kite
#

hello i need to control fan speed over

plain magnetBOT
#

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

#

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

mighty ledge
#

It's because you aren't providing defaults for |float

bronze prawn
#

Actually I just looked at mqttexplorer and the issue is that my message is not being retained 😦

#

I am not sure what to say but my sensors/rainoffset is not there but sensors/rainhourlyoffset is. I'll have to check to see if weather station had a problem reporting and that value was unavailable

#

apologies please disregard. Deleting to avoid trouble to others

thin linden
#

hey there,
I have a sensor which returns 1, 2, or some other numbers, tried to convert it to on/off but it seems I've missed something (the return value is fine without value_template):

- platform: snmp
  name: "Holo Network Port"
  unique_id: holo_network
  host: 192.168.39.249
  icon: mdi:lan
  version: "2c"
  community: "private"
  baseoid: .1.3.6.1.2.1.2.2.1.8.7
  value_template: >
    {% if is_state('sensor.holo_network',1) %}on{% else %}off{% endif %}```
edit: value_template is always off
marble jackal
#

{{ 'on' if value | int(0) == 1 else 'off' }}

thin linden
#

@marble jackal thank you

bleak wolf
#

how do i access the time ago that a person changed zones? to be used as a condition: has this person been home for more than 5 minutes?

inner mesa
#

you don't need a template for that

bleak wolf
#

in the past i've used (now() > states.sensor.device.last_changed + timedelta(minutes=3)) but that doesn't seem to work for zones.

i'll be calling it via node-red, so i do 😦

#

... don't i?

inner mesa
bleak wolf
#

I'll take a look. Thanks RobC 🙂

#

It's not being used in an automation in home-assistant but the output is being judged via a node-red function. Do you/anyone know if it's accessible via a template? the condition is in node-red, not hass automations. got it figured... sigh. i had a typo as state.person.michael.last_changed instead of states.person.michael.last_changed

sonic pelican
#

Maybe you folks could help me out over here. I'm attempting to use the HA camera proxy (https://www.home-assistant.io/integrations/proxy/) to grab a thumbnail from a camera and send it as a notification. The proxy requires a rotating token, so I need to send it in my automation, but its not working. This is my test in dev tools. I get the message. I can see the token in the message data, but no image.
service: notify.mobile_app_zac_s_phone data: message: "{{ state_attr('camera.camera_proxy_camera_side_lanai_door', 'access_token') }}" data: image: >- "https://hahalol.ui.nabu.casa/api/camera_proxy/camera.camera_proxy_camera_side_lanai_door?token={{ state_attr('camera.camera_proxy_camera_side_lanai_door', 'access_token') }}"

warm sierra
#

How do you get Jinja macros to load from custom_templates?

warm sierra
#

Yeah that's what I was reading, but I can't find that homeassitant entity to execute

inner mesa
#

What does that mean?

warm sierra
#

I feel like I'm missing something basic but googling it just turns up results of people just as confused as me

inner mesa
#

It goes in whatever template where you're using the macro

#

Import it, use it. As in the last example

warm sierra
#

homeassistant.reload_custom_templates

#

How do I do this ^

#

I've got the macro defined in a jinja file and I'm importing it into a template script

#

but it says it cant find the template file, and I can't figure out how to get it to load the file

#
service: scene.turn_on
target:
  entity_id: |-
    {% from 'scene.jinja' import set_scene %}
    {{ set_scene('fluro') }}
#
Executed: July 25, 2023 at 5:12:14 AM
Error: Error rendering service target template: TemplateNotFound: scene.jinja
#
/docker/homeassistant/config/custom_templates$ cat scene.jinja
{% macro set_scene(name) %}
{% set state = states("sensor.last_alexa") %}
{% set device = state.replace('media_player.', '') %}
{% set arr = device.split('_') %}
{% if arr[1] == "s" %}
{%   set room = arr[0] ~ arr[1] ~ arr[2] %}
{% else %}
{%   set room = arr[0] %}
{% endif %}
{% set scene = "scene.fluro_in_" ~ room %}
{% if states(scene) is defined %}
{{ scene }}
{% endif %}
{% endmacro %}
#

I've tried random reload commands from the 'c' menu

marble jackal
#

Go to developer tools > services and call that service

plain magnetBOT
warm sierra
#

ahh thank you

#

might be an idea to put that in those docs, because I found lots of people just as confused as me

#

I hate having to resort to bugging humans for help

inner mesa
#

docs are editable via the buttons at the bottom

warm sierra
#

I think I got the Jinja template call right, but I'm not sure

#

it's formatted differently in various places

marble jackal
#

Press M while on developer tools > services, you will be redirected to a page which provides my links

#

I would use that 🙂

tired sandal
#

  trigger:
    - platform: time
      at: '19:00:00'
  condition:
    condition: template
    value_template: "{{ next_scheduled_trash_day == (now().date() + timedelta(days=1) ) }}"

could i turn this into a calendar trigger?

mighty ledge
#

no

tired sandal
#

I didn't think so, but figured it was worth a sanity check

#

Would it be more efficient to turn it into a template trigger instead?

#

i.e: 7pm the night before

#

So, I have the following:

- alias: 'Trash night reminder'
  id: trash_night_reminder
  variables:
    next_scheduled_trash_day: "{{ (state_attr('calendar.trash_schedule', 'start_time') | as_datetime | as_local).date() }}"
    next_trash_holiday: "{{ (states('sensor.next_trash_holiday') | as_datetime | as_local).date() }}"
    holiday_data: "{{ state_attr('sensor.next_trash_holiday', 'data') }}"
    trash_period_end: "{{ next_scheduled_trash_day - timedelta(days=1)}}"
    trash_period_start: "{{ trash_period_end - timedelta(days=6)}}"
  trigger:
    - platform: time
      at: '19:00:00'
  condition:
    condition: template
    value_template: "{{ next_scheduled_trash_day == (now().date() + timedelta(days=1) ) }}"
#

I have an error in my logs that says: Error rendering variables: TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

#

I'm presuming it's related to trash_period_end and my usage of timedelta somewhere in there...

#

I've tried pasting my code into the template debugger tab and it seems to work

#
{% set next = (state_attr('calendar.trash_schedule', 'start_time') | as_datetime | as_local).date() %}


{% set end = next - timedelta(days=1) %}
{% set start = end - timedelta(days=6) %}

{{ end }}
{{ start }}

{{ next == (now().date() + timedelta(days=1) ) }}
#

that returns

2023-07-24
2023-07-18

True
lapis hound
#

Hello, how do I make the following work? the \ is not escaping the quote for the ' mark in the final replace statement:

inner mesa
#

Is it really returning a list?

#

It looks like you're trying to parse a list represented as a string

lapis hound
inner mesa
#

You didn't answer 🙂

#

I don't have a Minecraft server

lapis hound
#

I am not entirely sure. This is only my second go at templates but yes, I think it is a list

inner mesa
#

I suggest putting {{ state_attr('sensor.minecraft_server_players_online', 'players_list') | join(', ') }} in devtools -> Templates

torpid crag
#

Hi All, How to i change the type of a mqtt entity to a number? I have two entities sensor.tasmota_hx711_weight which has device_class: weight and reports a number/graph in the front end, and sensor.tasmota_hx711_weightraw which does not have a device class and thus does not appear as a number.

tired sandal
#

I have an automation that was supposed to run this evening at 7pm but instead just threw

Error rendering variables: TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta' in the logs

lofty mason
#

unit_of_measurement is what determines if an entity is numeric or not.

plain magnetBOT
#

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

tired sandal
#

what am I doing wrong?

#

It's something to do with how I'm using those timedelta expressions but they all work in the templates tab

inner mesa
#

you haven't said what's wrong

lapis hound
tired sandal
inner mesa
#

yes

#

you posted something and asked "what's wrong?"

tired sandal
#

I looked in the traces and it didn't even run the first step.

#

I took the condition out, reloaded and press "Run" in the automations tab with the same result leading me to suspect it's something to do with those variables at the top

#

but I can't for the life of me see what's wrong with them

inner mesa
#

your problem is this: (now().date() + timedelta(days=1) )

tired sandal
#

oh?

#

what's wrong with that?

#

It works in the template page

#

also, if i take that out - it still doesn't work

lofty mason
#

From the error message it sounds pretty clear that it must be these lines? Those the only ones with a -

  trash_period_end: '{{ next_scheduled_trash_day - timedelta(days=1)}}'
  trash_period_start: '{{ trash_period_end - timedelta(days=6)}}'
tired sandal
#

ah maybe

lofty mason
#

I wonder do variables always coerce their result back to string? It seems to think that your LHS of that subtraction are strings.

tired sandal
#

Ah that could be what's going on...

#

maybe i need to convert trash_period_end and next_scheduled_trash_day back into dates before trying to use it with timedelta

lofty mason
#

I would try that

tired sandal
#

(next_scheduled_trash_day | as_datetime).date()

#

Yeup that did it!

#

thanks!

lapis hound
# inner mesa I suggest putting `{{ state_attr('sensor.minecraft_server_players_online', 'play...

One more similar issue: - type: conditional conditions: - condition: template value_template: "{{ state_attr('sensor.minecraft_server_players_online', 'players_list') is not none }}" card: type: 'custom:button-card' template: card_generic variables: ulm_card_generic_name: Player List ulm_card_generic_icon: mdi:account-group entity: sensor.player_list
I am getting the error conditions are invalid

inner mesa
#

I see no evidence that you can use a template there

#

that's supposed to be a card?

lapis hound
#

Yes

inner mesa
#

you could create a template binary_sensor with that and then use that entity in your card

amber oxide
#
  sensors:
    date_long:
      friendly_name: "Day of week, Date and Year"
      value_template: >
        {% set year = ["2023"] %}
        {% set months = ["Jan", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %}
        {% set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %}
        {{ {{ days[now().weekday()] {{ now().day }} months[now().month-1] {{now().year }} }} }}```
#

Trying to make a custom sensor that will display the Day, Date and Year like this for example: Tuesday 25 July 2023

#

But I get the error:
Cannot quick reload all YAML configurations because the configuration is not valid: Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token ':', got '{') for dictionary value @ data['sensors']['date_long']['value_template']. Got '{% set year = ["2023"] %} {% set months = ["Jan", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %} {% set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %} {{ {{ days[now().weekday()] {{ now().day }} months[now().month-1] {{now().year }} }} }}\n'. (See ?, line ?).

inner mesa
#

you nested templates a bunch of times 🙂

#

what's with the {{ {{ {{ {{

amber oxide
#

Uh I am honestly not sure...I modified this from elsewhere and tried to make it better but now have that error

#

Can I just remove all of those squiggly brackets?

inner mesa
#

no, you just need to have the right number in the right places

#

without really knowing what you're tyring to do....

amber oxide
#

Right...I am still rather new to templates so how can I fix it?

inner mesa
#

{{ days[now().weekday()] }} {{ now().day }} {{ months[now().month-1] }} {{ now().year }}

#

all of that is kinda unnecessary, really

#

use {{ now().strftime('xxxx') }} where xxxx is a format string comprised of things from https://strftime.org/

amber oxide
#

So that would enable me to remove the set year etc definitions and just use the strftime stuff

#

So the template output line is all that is needed

inner mesa
#

yes

amber oxide
#

I will give that a go, thank you

inner mesa
#

the only reason that you would need to do what you had earlier is if you were trying to translate into a different language, for instance

amber oxide
#

Ah true

#
  sensors:
    date_long:
      friendly_name: "Day of week, Date and Year"
      value_template: >
        {{ now().strftime('%A') }} {{ now().strftime('%-d') }} {{ now().strftime('%B') }} {{ now().strftime('%Y') }}```
#

Nice and short now

#

Very good

inner mesa
#

you can just put all that together

amber oxide
#

Remove all the { in between?

inner mesa
#

{{ now().strftime('%A %-d %B %Y') }}

amber oxide
#

Oh sweet even better

#

Great that works

#

The more you know

#

Seems like template newbies like me just add masses of unnecessary code everywhere lol

#

Not my first time doing that and not my last

inner mesa
#

first get it working, then optimize

torpid crag
#

Hi All, How to i change the type of a mqtt entity to a number? - Is this done with a template? I have two entities sensor.tasmota_hx711_weight which has device_class: weight and reports a number/graph in the front end, and sensor.tasmota_hx711_weightraw which does not have a device class and thus does not appear as a number. I would like sensor.tasmota_hx711_weightraw to be a devivce_class: weight

inner mesa
#

What do you mean by 'appear as a number'?

torpid crag
inner mesa
#

You got the answer the first time you asked

#

Add a unit_of_measurement

torpid crag
crimson lichen
#

Hi,
I have this template
{{ states.sensor
|selectattr('object_id', 'search', 'lqi')
|selectattr('state', 'eq', 'unknown')
|map(attribute='entity_id')
|list }}
I want to list the state values of LQI sensors with a value less than or equal to 10.
How should I modify my template?
Thank you.

mighty ledge
ember saffron
#

Hi, I seek assistance in order to understand fully the splitting of the config with "template: !include template.yaml"

mighty ledge
#

this is for templates

#

jinja templates

#

not template integration

floral shuttle
#

quick confirmation please: is this the shortest to picking a random light out of my light group entities? {{expand('light.party_lights') |map(attribute='entity_id') |list|random}}

#

found an ancient listing in a script :```
service: light.turn_on
data:
entity_id: >
light.{{['frontdoor','dining_corner','symfonisk','kist','serre_chair',
'lounge_chair_long','home_theater','world_map']|random}}

mighty ledge
#

yes

floral shuttle
#

cool, thx for confirming

mighty ledge
#

if the light group has an entity_id attribute, then you could make it shorter by using that

#

which it does

#

so...

marble jackal
#

{{ state_attr('light.party_lights', 'entity_id') | random }}

mighty ledge
#

{{ state_attr('light.party_lights', 'entity_id') | random }}

floral shuttle
#

hahaha

mighty ledge
#

sometimes he wins

#

SOMETIMES

marble jackal
#

hehehe

floral shuttle
#

you're the best. both of you 😉

mighty ledge
#

but who's bester?

floral shuttle
neat prairie
#

Walter Koenig. Obviously.

floral shuttle
#

now for the best of the bestest: on creating a scene on the fly, can I use the entity_id light.pary_lights and have all lights stored in their current state, or would I need the template {{ state_attr('light.party_lights', 'entity_id') }}: - service: scene.create data: scene_id: before_party_mode snapshot_entities: - > {{ state_attr('light.party_lights', 'entity_id') }}

mighty ledge
#

remove the - part and go with that

#
      - service: scene.create
        data:
          scene_id: before_party_mode
          snapshot_entities: >
              {{ state_attr('light.party_lights', 'entity_id')  }}
floral shuttle
#

aarghh, I see I had this for my Hue group scenes: {% set select = states('input_select.hue_group')|slugify %} {% set group ='light.' + select %} {{group}} which only outputs the Hue group, and not the lights inside that (cant remember it didnt work btw, but thats besides the challenge).. had to turn it into this {% set select = states('input_select.hue_group')|slugify %} {% set hue_group ='light.' + select %} {% set names = state_attr(hue_group,'lights')|join('|') %} {{states.light|selectattr('name','match',names) |map(attribute='entity_id')|list}} to get the list of individual entitiy_id;s for the scene create.

#

(because Hue doesnt list entity_id's but names)

#

btw, need this after all, to reject powered-off lights {{expand('light.party_lights') |rejectattr('state','in',['unavailable','unknown']) |map(attribute='entity_id')|list}}

#

because:```
Logger: homeassistant.components.light.reproduce_state
Source: components/light/reproduce_state.py:122
Integration: Licht (documentation, issues)
First occurred: 14:44:11 (8 occurrences)
Last logged: 15:09:01

Invalid state specified for light.symfonisk: unavailable
Invalid state specified for light.home_theater: unavailable

marble jackal
floral shuttle
#

o right, that would be a smart way to prevent that rejector indeed! nice.

worthy edge
#

i have a threshold sensor on/off and i'd like to calculate duty cycle based on it (lets say in the last 24h), is this even possible with a template only?

plain magnetBOT
haughty breach
marble jackal
#

that might do what you want

mighty ledge
#

I really dislike has_value

floral shuttle
mighty ledge
#

but that's a good use for it

worthy edge
floral shuttle
#

although using your template does do what I need 😉 and its shorter

#

might be a first...

inner mesa
#

Entities always have a 'value' (state) 🙂

#

does_it_have_a_state_that_i_like_in_this_particular_instance()

floral shuttle
#

yeah, but I only ever tried to use it eliminating in ['unknown','unavailable'] in its various forms

mighty ledge
#

That’s all it should do

#

The original function got politicized to death and we ended up with has_value that looks at the entity_id

crimson lichen
mighty ledge
inner mesa
#

regrettably not

#

oh how I wish there was

marble jackal
#

You can't because states are always strings, and because of that you will be comparing the string "9" against "10" and "9" < "10" is false

inner mesa
#

applying filters to the incoming value before a test would be really great

#

better if it could be an expression

#

anything to avoid loops 🤮

marble jackal
#

Wasn't Petro working on that?

inner mesa
#

"thinking about it", as far as I recall. But hadn't come up with a good proposal

#

unfortunately you can't modify objects, and other syntax is weird. Something like selectattr('state'|float, 'gt', 5) doesn't make sense, so then you're down the road of trying to coerce the incoming value to match the comparison value or similar. And then you have a very limited use case

mighty ledge
#

and I'd have to somehow pass tests to the test

#

it's all funky

#

unless I just make one that's for numbers only

inner mesa
#

that's probably the most common case and mistake

#

and ensuring that the types are properly comparable is probably only a good thing

stone bane
#

Hello, I could use a little bit of nudge in the right direction.. I have the below...

  - sensor: 
    - name: Lawn mower battery charging time
      state: >
        {% set x = states('sensor.time') %}
        {% set t = 0 if states('switch.lawn_mower_charger') == 'off' else now().timestamp() - states.switch.lawn_mower_charger.last_changed.timestamp() %}
        {{ t | timestamp_custom('%M minutes', false) }}

Questions:

  1. The above gets to 59 minutes and then once at 60, it flips back over to 00 minutes. To remedy this, I included %I for a 12-hour clock, but in a quick test, the output was "12" for the hour, while the minutes displayed correctly. How can I get it to continue counting and flip to "1 hour 00 minutes" once it gets to 60 minutes?
  2. Additionally, would I just use If/Elif/else statements to determine whether to output minutes or hours and minutes?
  3. Is there an easy way I can record the time it takes, maybe in minutes, so that I can perform a running average? For example, "On average it takes the lawn mower battery 47 minutes to charge". Currently once wattage for a smart plug gets low enough, I have an automation turn off the plug and send a notification that the battery is done charging and how long it took. However, when the plug turns off, the "Lawn mower battery charging time" goes back to "00 minutes" so I'm losing the value.
mighty ledge
#
- sensor:
  - name: Lawn mower battery charging time
    device_class: duration
    state: >
      {{ (now() - states.switch.lawn_mower_charger.last_changed).total_seconds() | int if is_states('switch.lawn_mower_charger', 'on') else 0 }}
    unit_of_measurement: s
stone bane
#

Thanks! That should give me some direction for my #1 and #2 above. For my #3, any idea what I'd need to use or look into?

mighty ledge
#

that covers 1 2 and 3

#

as the display in the frontend will be HH:MM:SS

#

OH, did you edit question 3?

#

anyways, you can use that duration sensor to get an average

stone bane
#

Yeah, sorry for the miscommunication. I did

mighty ledge
#

or use it w/ min/ max statistics

stone bane
#

The above didn't put it into HH:MM:SS.. it's in seconds. Furthermore, when I turn the switch from 'on' to 'off' it changes the charging time template back to 0. Not familiar with min/max function in HA; will have to look into that.

#

Apologies for what I'm sure is the obvious miss on my part, but how do I get it in a format other than "0"? And will min/max allow for averaging of all historical data prior to it flipping back to 0, while also ignoring 0?

mighty ledge
#

under the hood it will be seconds

#

i.e. the states page

#

it's so your device can have a history, as well show a meaningful state in the UI.

stone bane
#

Thanks for sharing! For some reason the "combine state for several sensor --> Arthimetric mean" is going back to zero immediately after turning the switch off. I'm guessing that's because the switch is off most of the time.. I think then this would apply to me "If you have spikes in your values (like 0 in my case?), it’s recommended to filter/equalize your values with a statistics sensor first." found here - https://www.home-assistant.io/integrations/min_max/

#

Do you agree with my assumption?

mighty ledge
#

just use the statistics sensor set to max over the past 24 hours if you charge once a day

#

that will give you the most time it took

#

then average the past x days

stone bane
#

Good stuff. Thank you

silent vector
#

How do you convert 2023-07-26T19:35:28.947351Z to 07-26-2023 3:35:28 PM? Or / instead of - for the output

crimson lichen
silent vector
#

Ansible api.. lol

#

It's awful.

inner mesa
#

is it a datetime object?

silent vector
#

I don't think so. | to_datetime doesn't work

inner mesa
#

that's not a thing

#

|as_datetime is

#

this works fine for me: {{ "2023-07-26T19:35:28.947351Z"|as_datetime }}

silent vector
#

Is as_datetime a Jinja thing or ha filter

inner mesa
#

I believe it's an HA extension

#

there are links to the docs in the topic

silent vector
#

I wish Ansible had an equivalent or a native jinja way

inner mesa
#

so...you're not asking about a template in HA?

silent vector
#

Not necessarily lol. Now it's more of a jinja question.

mighty ledge
#

remove the z and try again

#

ansible only has to_datetime

inner mesa
#

for whatever reason, I thought we were talking about HA 🙂

mighty ledge
#

dan doesn't follow the rules

silent vector
#

I only ask when it's quiet lol

silent vector
#

Better jinja people here than the Ansible server

edgy flume
# marble jackal I would create a media_player group in the GUI, eg `media_player.main_floor` and...

Okay - thank you - this actually really helped - now my script is working. I am however working on integrating the script into a sample automation. Here I have if a sensor detects presence, and the speaker in the room is not playing whatever is being played (if there is something being played elsewhere - it calls back to the script to see if there is a return) then office speaker join the rest of the group - wait 30s - stop music elsewhere. However, my office speaker does not seem to be joining the group. Any obvious flaws you (or anyone!) could point me to?

plain magnetBOT
#

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

crimson lichen
inner mesa
#

the point was this:
{{ '6' <= '50' }} -> false

#

so you didn't founded anything

crimson lichen
lapis hound
#

What is a better(and working) way to do the following?

sensors:
  player_list:
    friendly_name: Players on Server
    value_template: >-
      {% if is_state_attr('sensor.minecraft_server_players_online', 'players_list') %}
        {{ state_attr('sensor.eastern_edge_minecraft_server_players_online', 'players_list') | join(', ') }}
      {% else %}
        No Players Online
      {% endif %}```
tired sandal
#

I currently have a template condition that looks like this:

- condition: template
  value_template: >-
    {{
      (forecast | selectattr('temperature', 'le', freezing_temp)
      | selectattr('condition', 'in', conditions)
      | list
      | length) > 1
    }}
#

Is there a more elegant way to test if a list has a given length?

#

something like

['foobar'] | hasLength(1)
#

i thought about doing

forecast | selectattr('temperature', 'le', freezing_temp)
  | selectattr('condition', 'in', conditions)
  | list
  | length
  | first is defined

but I don't know if that's like to just cause more issues

inner mesa
#

You don't need the extra parentheses, but the way you did it is the way it's done

tired sandal
#

good to know, thanks

plain magnetBOT
#

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

tired sandal
marble jackal
#

{{ (upstairs_playing + main_floor_playing + basement_playing) | reject('eq', 'media_player.office') | join(', ') }}

bleak flame
#

hello, I have a question. I am transferring from yaml mode to storage mode. I don't know how to use ui-button-template.yaml in storage mode.

ember saffron
#

it seems im blind, but based on the docs I was not able to find the allowed properties of a template sensor, can anyone guide a blind guy x_x

marble jackal
ember saffron
#

a template sensor can have a attribute called: unit_of_measurement or device_class but not "fruit"

#

sorry it was missleading to say property instead of attribute

marble jackal
#

You can define and attribute you want

ember saffron
#

awesome!

#

Thanks

mighty ledge
plucky heron
#

can I use templates for the value field of zwave_bulk_set_params like this?

mighty ledge
#

yes

#

open needs to be in quotes

young jacinth
#

hi, i want to get a list of all entity ids that have a specific device class like humidity from an area. i know we can do something like this to print out all entity ids that are assigned to this area, but cant get the filter right. can anybody help me out?

{{ area_devices('wohnzimmer') }}
marble jackal
#

{{ area_devices('wohnzimmer') | select('is_state_attr', 'device_class', 'humidity') | list }}

young jacinth
#

amazing thanks alot

quiet kite
#

i have 2 slides, i want to control it by only one and set value from this one on the both slides, how can i do this?

mighty ledge
#

I only have one slide at my lakehouse

marble jackal
#

I have one in the garden for the kids

pastel moon
#

Whyyyyyy don't I get this... Why aren't all date/time "offset-aware"? What juggling would I need to compare these please?

TypeError: can't compare offset-naive and offset-aware datetimes```
#

Should I make timestamps of it and then compare? What would be the best way?

inner mesa
#

just add |as_local

#

|as_datetime|as_local is a typical idiom to generate a timezone-aware datetime

pastel moon
#

one of the few I didn't think of trying... thank you!

pastel moon
#

How can I make sure value I am setting is a datetime please? - service: input_datetime.set_datetime target: entity_id: input_datetime.morning data: datetime: >- {% from 'pod_macros.jinja' import pod_calc_morning %} {% if pod_calc_morning() not in ['invalid'] %} {{ pod_calc_morning() }} {% endif %}

#

my if statement here did not do any good...

#

macro seems to return a string which this does not take as a valid input... How can I convert it?

inner mesa
#

Impossible to say without seeing the mysterious string

pastel moon
#

It looks like this 2023-07-28 06:01:00

#

I have tested the macro, and as a safeguard I set it to always return at least input_datetime.morning, so it shall always have a value at least, just not an accepted one...

inner mesa
#

If it actually returns that, it should be fine

pastel moon
#

Thanks, I think it changed to the next now "day", will fix the rest, perhaps good now. Thanks for the help

marble jackal
#

Macros always return strings

#

You need to make sure you manage whitespace though

pastel moon
#

Thanks, I think I got it working for this use-case, but what about whitespaces?

marble jackal
#

if you'r not careful, the macro will return something like 2023-07-27 10:07:00.392705+02:00

#

so with whitespace in front of it, or empty lines

#

which will make it invalid input for something like as_datetime()

pastel moon
#

Ah, gotcha. I have taken care of that part. I thought you meant spaces in the string returned, ie the part that holds the info

wintry night
#

I want to get alerts when a specific integration (Unifi Network) when a new device_tracker entity is added. I can see the number of such entities using {{states.device_tracker|count}} - do you all know - if I make a template sensor using this template, will it work? I'm concerned that this won't get automatically updated because it doesn't include a specific device or entity for automatic triggers. I wouldn't know what trigger to write, for example. (Cross post from #general-archived, new here. Thanks)

marble jackal
#

That template will be rendered every second if I'm not mistaken

wintry night
#

thanks! i just discovered that i can listen to entity_registry_updated events

#
description: ""
trigger:
  - platform: event
    event_type: entity_registry_updated
    event_data:
      action: create
condition: []
action:
  - service: notify.persistent_notification
    data:
      message: "New entity added: {{trigger.event.data.entity_id}}"
      title: Entity registry updated
mode: queued
max: 10```
#

the same trigger could be used in a template sensor to limit the update churn.

inner mesa
#

that's a cool feature

silent vector
#

Is there an easy way to subtract time. 02 - 4 = 10 rather than 02-4 = -2

mighty ledge
#

datetime objects

#

also 2-4 would be 10

silent vector
#

Yeah that

#

Mistyped

#

I figured out the utc to est by the way. A bit of a challenge

#

This is a new one lol

#

Do you have an example of how that would work with just hours?

mighty ledge
#

you can't, you need to use datetime objects

#

otherwise you have to build the logic yourself

silent vector
#

Nevermind I do have the ability to use a datetime object

#

Doesn't this mean I need 2 datetime objects?

mighty ledge
#

Yes

silent vector
#

How do I get the second? If I only have 1 time reference and I need to go back 4 hours?

mighty ledge
#

use a time delta

#

datetime-timedelta

silent vector
#

Lovely not supported by Ansible

marble jackal
#
{% set m = 2 %}
{% set result = ((m + 12) - 4) % 12  %}
{{ result or 12 }}
silent vector
#

You're a legend

#

When would it ever need the or 12?

#

What time would that be

mighty ledge
#

0 or 12

silent vector
#

When result is 0?

#

Equivalent to false?

mighty ledge
#

try it out in the template editor

silent vector
#

Attempting to replicate lol

mighty ledge
#

literally just do 0 or 12

silent vector
#

Got it lol

silent vector
#

How did thefes even know how to do all that math

#

I didn't even know what a % did until just now

mighty ledge
#

it's modulo

#

it's a common math symbol in all coding languages

sonic nimbus
#

how to write this template condition instead I think it will be much more easier for me:

choose:
  - conditions:
      - condition: trigger
        id:
          - any-light-toggle
      - condition: state
        entity_id: input_boolean.vacation_mode
        state: "off"
#

conditions: "{{trigger.from_state.state == 'any-light-toggle' and states('input_boolean.vacation_mode == 'off'')'}}"

#

Or Im someone got wrong?

mighty ledge
#

trigger.id

silent vector
#

It's not conditions for a template

#
choose:
  - conditions:
      - condition: template
        value_template: "{{ foo }}"
    sequence: []
quasi seal
#

hey guys, im trying to do a sort of replacement for the ${name} / substitutions there is in ESP home. I want to chose a name for an entity e.g switch.person1_thingy and switch_person1_door and somewhere else just define the number of the person, so I dont have to change everything everytime.
As far as I can tell, this should be possible with a template to chose the correct entity, but I simply cannot catch a break. Any thoughts ?

so if I define a variable per the person number
variables: number: !input person_number

and then do a template for the entity id, that inserts the variable into it.
- service: switch.turn_on target: entity_id: "{{'switch.person'+number+'_thingy' }}"

Is this at all possible ?

mighty ledge
#
              entity_id: switch.person{{number ~ '_thingy'}}
#

or

#
              entity_id: switch.person{{number}}_thingy
#

if your number is a float, you need to convert it to an int

#

number | int

quasi seal
#

holy ********** that worked... wth man... thank you so much... spent three hours trying this /

torn meteor
#
service: scene.turn_on
target:
  entity_id: >
    {% if is_state('input_select.luxafor_effects', '🔴') %}
      {% set scene = "scene.luxafor_1_red" %}
    {% elif is_state('input_select.luxafor_effects', '🟡' %}
      {% set scene = "scene.luxafor_1_yellow" %}
    {% else %}
      {% set scene = "scene.luxafor_1_green" %}
    {% endif %}
    {{ scene }}
#

not working - is it because of the emoji?

#

or can you not use {% %} tags here

obtuse zephyr
#

Missing a closing ) in the elif

torn meteor
#

ah HA - this whole time

#

ty

heavy island
#

I have a fan that has a speed percentage. I want graph that speed on a chart, so I think I need a sensor entity with that value. How can I extract that value from a fan in a template sensor?

lofty mason
#

first go to developer tools and look at what attributes are there in the fan entity. something like "percentage" or "speed" is probably one of them. then you can use a template with state_attr()

heavy island
polar whale
#

Sorry, it‘s possible very simple, but I don‘t seem to get behind it. How can I display the state icon from a binary sensor group which is defined as window. The group don‘t have a defined icon, only the option display as window. I tried {{ state_attr('binary_sensor.wohnzimmer_fenster', 'icon') }} , but that don‘t seem to work

plain magnetBOT
#

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

oak cairn
#

the enties of my bulb are ...light.living_room_bulb
button.living_room_bulb_identify
select.living_room_bulb_start_up_behavior
number.living_room_bulb_start_up_color_temp
number.living_room_bulb_start_up_current_lev
sensor.ewelight_zb_cl01_|qi
sensor.ewelight_zb_cl01_rssi

lyric comet
#

If you want an easy way, create a light group (light.hall in the example) for your bulbs you want to count and use a template sensor value similar to:

#

If those are your only bulbs you can use
"{{ states.light | selectattr( 'state', 'eq', 'on') | list | count }}"
to count all of them. You also might want to consider using the modern formating for template sensors. See the Docs for more information.

template:
  - sensor:
  # ------------------------------------------------ Lights on Count
    - name:  Total Lights On
      icon: "mdi:lightbulb-group-outline"
      state: "{{ states.light | selectattr( 'state', 'eq', 'on') | list | count }}"
#

I can't help with the button card, you could set the icon colour in the template and set the icon differently depending on whats on.

next pasture
#

did you found solution to create image from graph?

steep raven
#

this prop could be done via the api i guess but didnt look into it

next pasture
#

that's shame

steep raven
#

i do not have my data in grafana :p

next pasture
#

that's easy to add 🙂

grim flicker
#

When clicking on an entity and select history in the ui you can see what triggered or changed the device or entity. When a user changed it you can see it in the history too at the very end. Is there a way with templates to get the last state change and check which user triggered it? or atleast if it indeed was a user or the system itself. The reason i ask is, i have an AC which is fully automated. but when we intervene in this proces i want an automation to pick it up and put on a boolean called manual. after which all ac automations will not met the condition. I have everything setup like this but at the moment i let every automation put on an boolean so i know its the automation that did something and an automation to check the state of the ac. when the state changes it checks if the boolean is on and if not it means a person did something and then a manual boolean is turned on. I want this to be more acurate. So i am wondering on a state change if there is a way to check if a user made a service call or an automation did. i use things like states.sensor.deurbel_action.last_changed and i wonder if i can also get the user from something like this

mighty ledge
#

it also only works when inside the action section

#

{{ states.person | selectattr('attributes.user_id', 'eq', context.user_id) | list | first | default("No user") }}

marble jackal
mighty ledge
#

you can, but the code changes

#

iirc you need to use the triggers context object instead

#

trigger.context.user_id

marble jackal
#

ah right

mighty ledge
#

and it might be the to_state

#

trigger.to_state.context.user_id

marble jackal
#

we came across that some time ago, now I understand a bit more why

mighty ledge
#

going off memory here

#

yeah

#

it's odd but makes sense

#

the context only gets passed to the action section for some reason

marble jackal
#

odd, but makes sense

mighty ledge
#

yes

#

But IMO, the object should be passed directly after the trigger

#

the object exists, but it's not updated

#

so 🤷‍♂️

wintry night
#

is it possible to get the device_id for a given entity_id (actually, i am tracking down a way to find out the integration that created an entity)

inner mesa
#

second link in the channel topic will be helpful for these questions

#

I don't have a straightforward answer to how to get back to the integration from an entity

wintry night
#
{% 
set device_id = ["light.primary_bathroom_shower",] | map("device_id") | list | first
%}
{%
set integration_name = device_attr(device_id, 'identifiers') | list | first | first
%}
{{integration_name}}
#

thanks RobC. i'll look at it. i was able to get the integration name for an entity that actually has a device. but some entities (i guess) don't have an associated device...

inner mesa
#

I was thinking about that, but I wasn't sure if that's always the case

#

and that, yeah

#

if you could get a list of integrations (which I don't think you can), then you could iterate over their entities looking for the one you want

wintry night
#

thank you, this is much better:

{{ device_attr(entity_id, 'identifiers') | list | first | first }}
#

unfortunately it still doesn't work for the entity i'm trying to track down (a device_tracker entity that i happen to know comes from Unifi integration)

inner mesa
#

it does look like identifiers is defined that way, so that's a good way, as long as there's a device:

identifiers Set of (DOMAIN, identifier) tuples. Identifiers identify the device in the outside world. An example is a serial number.

wintry night
#

but it also seems to rely on entities having device_ids

#

basically, i'm trying to write an automation that does something automatically when an entity is added by a specific integration