#templates-archived

1 messages Β· Page 9 of 1

lapis quarry
#

with a letter at the end

#

a b or c

#

aircons are also named that way

#

airconbr01a, or airconbr02b etc

mighty ledge
#

ok

lapis quarry
#

Ahh there is also 2 more scenarios to take in account, the physical sensor sends 3 codes:
1: on - off which is door open and closed
2: low battery signal
3: tamper switch if the sensor is removed from the door or window

So in HA I have 3 binary sensors for each phisical sensor following this naming:

#

So for intance door 01a has these 3 binary sensors:
doorbr01a
doorbr01abatt
doorbr01atamper

#

Dont know if that info is usefull but i thought its worth mentioning to make sense of the template

mighty ledge
#

is batt and tamper in the binary_Sensor window / door names?

lapis quarry
#

yes

#

all follow same naming

mighty ledge
#

can you show an example please

#

full name

lapis quarry
#

binary_sensor.doorbr01a
binary_sensor.doorbr01abatt
binary_sensor.doorbr01atamper
or
binary_sensor.doorlr01a
binary_sensor.doorlr01abatt
binary_sensor.doorlr01atamper
or
binary_sensor.doorkitchen01a
binary_sensor.doorkitchen01abatt
binary_sensor.doorkitchen01atamper

mighty ledge
#

ty

lapis quarry
#

binary_sensor.doorbr01a (last letter a in this case could be a b or c) and all sensors following same naming convention

#

for windows the same thing:

#

binary_sensor.windowbr01a
binary_sensor.windowbr01abatt
binary_sensor.windowbr01atamper
or
binary_sensor.windowlr01a
binary_sensor.windowlr01abatt
binary_sensor.windowlr01atamper
or
binary_sensor.windowkitchen01a
binary_sensor.windowkitchen01abatt
binary_sensor.windowkitchen01atamper

charred maple
#

can anybody tell me what is wrong with this?

        properties:
          "text": >
            {%- if is_state('weather.openweathermap','unavailable') %}
            (not available)
            {%- else %}
            {%- set con = state_attr('weather.openweathermap','forecast')[1]['condition'] %}
            {%- if con == 'clear-night' %}
            Clear night
            {%- elif con == 'cloudy' %}
            Cloudy
            {% endif}
            {%- endif %}
#

this is in configuration.yaml

mighty ledge
#

@lapis quarry what are your room numbers equal to?

#

doorbr, windowbr

#

br means bedroom but what does the number mean?

#

sensor number?

#

so not room number?

lapis quarry
#

Room number

mighty ledge
#

why do you have a room number when you already have a room name

lapis quarry
#

All rooms are named the same

#

Br

#

The number after is the room number

#

Br01 br02 erc

mighty ledge
#

same with kitchen?

lapis quarry
#

And the letter at the end is the sensor number

#

A b or c

mighty ledge
#

ok

lapis quarry
#

So room 1 might have 1 door and 2 windows

#

So doorbr01a and windowbr01a and windowbr01b

#

Same for kitchen and same for living room

mighty ledge
#

@lapis quarry what about the 'home' thing

lapis quarry
#

Where?

#

Ahh presence detection

mighty ledge
#

right, what's the entity_id for that?

lapis quarry
inner mesa
lapis quarry
#

inside those groups i have all entities that detect presence in that space and the group will be home or not_home

mighty ledge
#

wrenches I tell you, wrenches

lapis quarry
#

yes excatly as posted

lapis quarry
#

also this code was written 2019 many of the solutions you have now available where not implemented back then

mighty ledge
lapis quarry
#

im sure i would do it better if i stareted from scratch today (at least a little better)

mighty ledge
#

that's how you can use variables to not reuse code

lapis quarry
#

WTF 😯

#

you rwally telling me what you just sent does the same as i wrote?

mighty ledge
#

after alias add an id to it so you can trace the automation

  - alias: "Windows Automation"
    # mode: restart
    id: windows_automation
    mode: parallel
#

yes, it does

#

same thing

#

make the room a variable, the number a variable, the room name a variable, the sensor name a variable and then you don't repeat yourself

#

it would be alot less code if you named things better

lapis quarry
#

wait i need a few minutes to recover and read what you just sent if i can undestand anything LOL

mighty ledge
#

none of this lr crap means livingroom and living and living room

#

stick with 1 name

#

br = bedroom

#

lr = livingroom

#

kr = kitchen

#

if you did something like that and named everything in accordance to that it would be easier

#

also, if you had separated the identifiers out with _, you wouldn't need the fancy regex that I had to use

#

either way, that should work, but I can guarentee there are errors because i dont' have any of this stuff

#

you were constantly checking the same crap when you didn't need to

#

if you have the check in the beginning, it won't be needed in the middle

#

like the sensor name being door or window

#

you had that check everywhere

#

but it didn'tneed to happen in the middle of your script because that's not changing.

lapis quarry
#

i need some time to process all this

#

🀣

mighty ledge
#

take your time, I have to walk away anyways

charred maple
lapis quarry
mighty ledge
#

np, and thanks

lapis quarry
#

but i still need to grasp all this and understand it because i see a lot of dark magic going on there

#

ill be back with questions

mighty ledge
#

that's what the trace is for

#

so you can see the variables and their output when it triggers

lapis quarry
#

trace?

mighty ledge
#

automations have traces now

#

let me show you

#

you can look at the changed variables and see where things fail

#

changed variables are all the variables in the automation and how they resolved when a trigger occured

lapis quarry
#

Also honest and very serious question: is there any benefit to all this besides this being elegang code to you devs?

#

Because one primordial thing for me is understang the code, and the code i wrote i understood and worked and this i cant grasp, at least yet..

3 things for me are important:

  • Eficiency in the code, menaning im not using resources ineficiently
  • Scalability in the code meaning my templates should acomodate for expansion (which you allready sugested some more tips I just need to process everything)
  • And understading it and being able to maintain it
mighty ledge
#

if you take the time to understand it, you'll realize you don't have to add anything to this to make it work

#

i.e. if you add a new room and sensors, that's all you add. Just name them and this will work.

#

without touching the code

lapis quarry
#

yes that was the goal before when i wrote my crap LOL

#

cool

lapis quarry
mighty ledge
#

in the automation list, each automation will have a ...

#

in that list is the word traces

#

traces are only available if your automation has an id

#

it has to be unique

#
- alias: My automtion
  id:  my_unique_id_for_this_automation_to_enable_traces
  ... the rest of the owl ...
lapis quarry
#

Im laughing my ass off because all i wanted it to get rid of the warning in the logs and now im in this rabiit hole (again) seems there are infinite rabit holes every time i try to do something here 🀣 🀣 🀣 🀣 🀣 🀣 🀣

#

let me see if this passes config test

mighty ledge
#

chances are... medium

lapis quarry
#

if it does you are a fucking star

#

no it doesnt

mighty ledge
#

I'd have to see all the errors

#

post them in a dpaste and @ me. I'll have to look later

lapis quarry
#

sure, i also need to run, + i need some time to grasp all this, def ill be getting back

#

thanks again πŸ™ πŸ₯°

mighty ledge
#

np

mighty ledge
#

all fixed

marble jackal
#
      sensor: >
        {% set s, r, n, t = new_state.object_id | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z])') | first | default(['', '', '', '']) %}
        {{ {'name': s, 'room': r, 'room_number': n, 'sensor': t} }}

I guess I need to spend some time learning regex

mighty ledge
#

(window|door) -> the word window or door, capture this group of characters.

#

([a-z_]+) -> capture n length lowercase letters & underscore

#

([0-9]{2}) -> capture 2 numbers in a row

#

([a-z]) -> capture any single lowercase letter

#

and just spelling out that last one pointed to a bug, I need a + there

#

each () defines 1 item in the list, so theres 4 (), so you'll get 4 items

#

if htere's no capture, first will fail, but the default will catch it and put in empty strings

#

so [] basically means this character range

#

normal regex lets you assign names to groups so you get a dictionary out

#

but you can't do that in HA's regex, it just returns the values πŸ˜•

inner mesa
#

is that true? It uses Python's re library underneath

#

I guess there isn't a function that just returns what it returns - it always has a modifier

mighty ledge
inner mesa
#

I found that grouping works as you'd expect only when in a multi-line template

#

but I haven't tried naming the groups

mighty ledge
#

It’s been a while@since I used named groups, I thought it always returned a dictionary. Might be an object tho

chilly locust
#

Pardon my ignorance, but is moment.js incorporated into jinja? I'm trying to parse and humanize a timedelta (hh:mm:ss).

lapis quarry
#

Morning guys

#

Petro I kind of follow the code, still need some more time to process everthing and undestarnd it

#

the regex is black magic LOL

lapis quarry
#

also I noticed something here where you call the script:

          sequence:
            - service: script.turn_ac_on
              data: 
                location: bedroom
                room_number: "{{ sensor.room_number }}"```
#

location: bedroom (should be either "bedroom", "kitchen" or "living" based on what kind room that is triggering the automation)

#

so there needs to be a variable there

#

regarding the config checker i get this error: Error loading /config/configuration.yaml: expected '<document start>', but found '<scalar>'
in "/config/automations/Windows Automation Template Petro.yaml", line 59, column 1

#

also I think I confused you because i didnt explain well enough the aircon thing i mentioned:
My AC units follow the same kind of naming convention airconbr01a for instance, (but they are all regular sensors or switches, there is no binary_sensor for the AC unit itself) so its not needed in this template

lapis quarry
#

also another thing i noticed is the delay:

    - delay: "{{ room_delay }}"```
#

should be 0 when switching AC on, delay only applies when group is not_home it should wait before switching the AC off

marble jackal
thorny snow
#

I have a problem with template covers in the configuration.yaml.

#

Only 1 cover is shown but I have three.

lapis quarry
#

it my 2 year old daughter birthday today so will be kind of busy, will checking when i can πŸ˜…

ornate patio
#

Can I configure a universal media players enitity state like this: state_template: switch.monitor?

#

Where switch.monitor is just a smart plug which can be either turned on or off

marble jackal
#

No, you need to use a template

marble jackal
mighty ledge
marble jackal
dusty grailBOT
mighty ledge
marble jackal
#

I was wondering how you solved it now

ornate patio
#
      select_source:
        service: input_select.select_option
        data_template:
          entity_id: input_select.monitor_arne_source_list
          option: >
            {{ source }}
        if:
          entity_id: input_select.monitor_arne_source_list 
          option: "HDMI1"
          service: switch.turn_on
            entity_id: switch.hdmi1
        else:
          service: switch.turn_off
            entity_id: switch.hdmi1``` Why does homeassistant throw a mapping error at the line before the else statement?
marble jackal
#

You need to add a - before every action in the sequence

#

And you if is missing a condition

#

And the then

dusty grailBOT
ornate patio
#

Now I'm asking myself why it doesn't trigger the switch

ornate patio
#

Does it have sth to do with no "" around HDMI1 and HDMI2?

marble jackal
#

This at least looks like valid code

#

Is this a script? What does the trace show?

lapis quarry
#

I have another question related the state_changed trigger:

#

I did this small change to my old working install:

#

Old working install: ```yaml
trigger:
- platform: event
event_type: state_changed

#

I added this yesterday:

#
    trigger:
    - platform: event
      event_type: state_changed
      event_data:
        domain: binary_sensor```
#

so basicaly adding the domain to the trigger so it only triggers on binary_sensors

#

But started getting calls today AC where not switching on πŸ™„ πŸ˜…

#

My question is: Are you guys sure this is right? and if yes, was this allways like this or was it added sometime after 2021.4.6 (the release im running there)

#

because when i add the event data and domain the automation stops trigering, removed it and its working again

marble jackal
#

Hmm, I'm checking the state changed event data, and I don't see it

#

So, I might have been wrong he m there πŸ˜…

#

Think I had it mixed up with the service_call event

lapis quarry
#

ok... no big deal it was a esay fix, but would have been cool to be able to filter out events like that

#

this is why im hesitant to chang to much in the code, my bunch of crap might not look nice but it works and i cant really afford to break anything πŸ˜…

#

and I also guess that means petros code might need some changes because there needs to be a check to make sure its triggering from a binary_sensor

#

i guess its easy enough just adding it to the first condition before any action

#
{{ new_state.state not in ['unavailable', 'unknown'] and (enabled and (auto_on or auto_off)) and new_state.entity_id in room_sensors }}```
#
{{ new_state.state not in ['unavailable', 'unknown'] and new_state.domain == 'binary_sensor' and (enabled and (auto_on or auto_off)) and new_state.entity_id in room_sensors }}```
#

right?

lapis quarry
# mighty ledge ok, more changes <https://dpaste.org/1EeSQ>

Still getting this error when trying to load the code to test it:

Error loading /config/configuration.yaml: expected '<document start>', but found '<scalar>'
in "/config/automations/Windows Automation Template Petro.yaml", line 60, column 1

obsidian lintel
#

Is there a possibility to check if an area exists with templates, and if it does, markdown shows exist for example?

#

So like check if the Area name "Living Room" exists

lapis quarry
#

ok, fixed that and the config checker keeped complaining about other lines, i think i fixed a few adding quotes here and there but cant find this one now: expected '<document start>', but found '<scalar>' in line line 58, column 1

obsidian lintel
#

Ah wait I think i got it

lapis quarry
mighty ledge
#

gotta add the domain check though

lapis quarry
#

yes and the id i also had added πŸ˜‰

mighty ledge
#

yah sure

lapis quarry
#

still complaining line 59

mighty ledge
#

I don't see anything wrong

lapis quarry
#

i cant see it either πŸ˜…

mighty ledge
#

I'm not sure what text editor you are using but there's hidden characters in your paste

#

they aren't added from the software I was using

obsidian lintel
#
    True
{% else %}
    NONE
{% endif %}```

Im getting a syntax error, cant seem to find the issue...
rugged laurel
#

"{{ 'True' if area_id('Living Room') else 'NONE' }}"

lapis quarry
#

im using notepad++

mighty ledge
#

πŸ€·β€β™‚οΈ not sure where they came from

obsidian lintel
#
entity: template
template: "{{ "True" if area_id('Living Room') else "False" }}"
states:
  True:
    type: markdown
    content: Area Detected
  False:
    type: markdown
    content: No Area```

Hmmm, it has to be {% %}
#

How would I approach this

mighty ledge
#

{{ }} means output value

#

{% %} means don't output, just execute

inner mesa
#

you're using the same quotes inside and out

mighty ledge
#

your problem is your interior quotes

#

what rob said

rugged laurel
#

" inside and outside the template make πŸ”₯

mighty ledge
#

inside should all be '

lapis quarry
#

cool your last paste passed the config test πŸ‘Œ

obsidian lintel
#

Got it!

#

Thanks guys!

frank ferry
#

I know in Automations you can get what caused it to run by referencing the trigger variable. Is there a variable in Scripts that will provide what called it, like an Automation or another Script? I have several Scripts that are called from Automations or Scripts that expects variables to be passed. I want to test if a needed variable was not provided and provide a message that includes the calling Automation or Script name.

frank ferry
# mighty ledge `var is defined`

I know I can test if the var is defined. I want to know what Automation or Script called the Script so I can log a message and know where to make the correction.

mighty ledge
#
service: script.xyz
data:
  var: 1
#

Oh, I missed that

#

context.parent_id

#

Or the context object

#

But you have to take the id and match it back to the automation.

#

Or script

frank ferry
mighty ledge
#

E.g. {{ states.script.airplay_through_receiver_on.context.id }}

#

That’s how you get the id from an entity

#

Then you match it with the context id provided by the script which is just context.parent_id

#

Sorry on mobile, but that’s all you need to do

frank ferry
obsidian lintel
#

Does running like 100 lines of template on frontend make it extremely slow?

mighty ledge
#

Only if it’s bad code

obsidian lintel
#

I created an auto generating mushroom card

mighty ledge
#

πŸ€·β€β™‚οΈ

obsidian lintel
#
    style: |
      ha-card {
        background-color: rgba(20,20,20,0);
        padding: 10px;
      }
    card:
      type: vertical-stack
      cards:
        - type: custom:state-switch
          entity: template
          template: '{{ "True" if area_id("Foyer") else "False" }}'
          states:
            'true':
              type: vertical-stack
              cards:
                - type: custom:button-card
                  show_icon: false
                  entity: input_boolean.1autogen_expand_foyer
                  name: Foyer
                  styles:
                    name:
                      - text-align: start
                      - justify-self: start
                      - font-size: 22px
                      - font-weight: 600
                      - text-shadow: 2px 2px rgb(0,0,0)
                    card:
                      - padding-left: 15px
                      - background-color: transparent
                      - padding-bottom: 13.5px
                      - padding-top: 18px
                - type: custom:state-switch
                  entity: input_boolean.1autogen_expand_foyer
                  transition: swap-up
                  transition_time: 350
                  states:
                    'off':
                      type: vertical-stack
                      cards:
                        - color_type: blank-card
                          styles:
                            card:
                              - width: 0px
                              - height: 0px
                          type: custom:button-card
                    'on':
                      type: vertical-stack
                      cards:
                        - type: custom:auto-entities
                          card:
                            square: false
                            columns: 2
                            type: grid
                          card_param: cards
                          filter:
                            include:
                              - domain: light
                                area: Foyer
                                options:
                                  type: custom:mushroom-light-card
                                  use_light_color: true
                                  show_brightness_control: true
                                  show_color_control: true
                                  show_color_temp_control: true
                                  collapsible_controls: true
                                  card_mod:
                                    style: |
                                      ha-card {
                                        background-color: rgba(20,20,20,0.8);
                                      }
            'false':
              type: vertical-stack
              cards:
                - color_type: blank-card
                  styles:
                    card:
                      - width: 0px
                      - height: 0px
                  type: custom:button-card```
dusty grailBOT
obsidian lintel
#

How could I optimize it

mighty ledge
#

There’s no template there

obsidian lintel
#

Its repeated like almost 30+ times so the entire code is like 5000ish lines

mighty ledge
#

That small template won’t cause issues

obsidian lintel
#

template: '{{ "True" if area_id("Foyer") else "False" }}'

mighty ledge
#

It’s likely the card itself

obsidian lintel
#

Which cards

#

All of em?

mighty ledge
#

Could be any one of them

obsidian lintel
#

Ive never lagged so hard hahaha

#

Damn im horrible

obsidian lintel
#

Is it possible to check if an area has a domain?

#

And print true, if it does

inner mesa
#

What does that mean?

waxen lynx
#

hi is this right place to ask about apexchart formatter code?

inner mesa
vocal imp
#

really simple but stupid question
hey can someone tell me if a LOGICAL AND is valid in jinja?
or rather - can someone tell me HOW to do a logical AND in jinja

#
          {% if states("sensor.clt_pump_status") | float < 1386 and states("sensor.clt_pump_status") | float > 1000 %}
          value 1
          {% elif states("sensor.clt_pump_status") | float > 12245 and states("sensor.clt_pump_status") | float < 18000 %}
          value 2
          {% else %}
          {{ states("sensor.clt_pump_led_status") | float }}
          {% endif %}
inner mesa
#

That looks fine

vocal imp
#

thx rob

inner mesa
#

you can test any template in devtools -> Templates

lapis quarry
#

I simplified the condition down to only testting ```yaml
- condition: template
value_template: {{ new_state.entity_id in room_sensors }}

#

I also noticed in the regex you are using the word sensor twice:yaml sensor: > {% set s, r, n, t = new_state.object_id | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z_]+)') | first | default(['', '', '', '']) %} {{ {'name': s, 'room': r, 'room_number': n, 'sensor': t} }}

#

in the begining and also use the same name at the end 'sensor': t
I guess it should be something like```yaml
sensor: >
{% set s, r, n, t = new_state.object_id | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z_]+)') | first | default(['', '', '', '']) %}
{{ {'name': s, 'room': r, 'room_number': n, 'sensorletter': t} }}

#

Not sure but im suspecting that might be a problem, i tried the above but didnt make a difference

spring zenith
#

Is there anyone who can help me with a sensor that counts the days to a certain date?

vocal imp
#

anmyone knows why logical 'OR' doesnt work in a template but AND does (obvioulsy with a different result)?
{{ (states("group.p1_p2") or states("group.p1_p3") or states("group.p2_p3")) }}
The only time the output is true is when group.p1_p2 is true. When group.p1_p3 is true the output is false

This works tho
{{ (states("group.p1_p2") and states("group.p1_p3") and states("group.p2_p3")) }}
When all three are true the output is true

mighty ledge
lapis quarry
#

give me a sec i suspect i found the reason, im managing to figure your code out digesting it bit by bit and commenting everything so i can read it easier πŸ˜…

#

where can i find the trace variables?

#

it fails here acording to the traceyaml condition: template value_template: | {{ new_state.entity_id in room_sensors }}

mighty ledge
sly urchin
#

Bit random everyone, but my template switches are all unavailable (not even showing in dev tools) since a 2022.9 update. Also my wake on lan and broadlink switches have become unavailable too. Really stumped and nothing in logs, any ideas? Thx

lapis quarry
#

ok give me a sec to restore your code and i will send

mighty ledge
sly urchin
#

Cant see any new unknown switches

mighty ledge
sly urchin
#

I have found it I think, two switch: entries in my config πŸ€¦β€β™‚οΈ

mighty ledge
#

that would also do it

#

🀣

sly urchin
#

It just dawned on me that none of them were working, WOL, broadlink, template...

#

So found a late night copy paste that wasnt observed well enough, and we're fixed. Thanks for entertaining me πŸ‘

lapis quarry
#

I restored your code but dont know what the heck is is going on now the automation is not executing when i open or close a window and traces are not updating either, I even rebooted HA

mighty ledge
#

that doesn't make sense

lapis quarry
#

i know

mighty ledge
#

You're doing something wrong πŸ˜‰

lapis quarry
#

fount it

lapis quarry
#

those lines need to be removed 🀦

#

corrected the link

#

i can see the regex sensor is not being populated acording to this, right?

mighty ledge
#

yep, but it should be

#

working on my end, what version of HA are you using?

lapis quarry
#

it does when i test it in the template editor

#

latest release

mighty ledge
#

change it from new_state.object_id to new_state.entity_id

#

then try it again

lapis quarry
#

same result

mighty ledge
#

that doesn't make any sesne

lapis quarry
#

its weird

mighty ledge
#

change the sensor line to

#

      searching: "{{ new_state.object_id }}"
      regex_result: "{{ searching | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z_]+)') }}"
      sensor: >
        {% set s, r, n, t = regex_result | first | default(['', '', '', '']) %}
        {{ {'name': s, 'room': r, 'room_number': n, 'sensor': t} }}
#

and run again

lapis quarry
#

still unpopulated

mighty ledge
#

show me trace

#

variables

lapis quarry
mighty ledge
#

interesting

#

ok

lapis quarry
#

hang on this one triggered by wrong entity, let me send you a good one trigered by a door

#

corrected link above, still ame result

mighty ledge
#

change


      searching: "{{ trigger.event.data.new_state.object_id }}"
      regex_result: "{{ searching | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z_]+)') }}"
      sensor: >
        {% set s, r, n, t = regex_result | first | default(['', '', '', '']) %}
        {{ {'name': s, 'room': r, 'room_number': n, 'sensor': t} }}
#

and

#

    
      # Only continue if we have a valid state, we are enabled or automatic and we ahve a window or door sensor.
    
      - condition: template
        value_template: >
          {{ trigger.event.data.new_state.state not in ['unavailable', 'unknown'] and (enabled and (auto_on or auto_off)) and trigger.event.data.new_state.entity_id in room_sensors }}
#

run again, post trace

lapis quarry
#

but this is weirder, i run it like 10 times and every time the trace says it was triggered by automation.windows_automation instead of the binary_sensor.doorbr01a im testing with

mighty ledge
#

that last trace is not the correct sensor

#

so it won't run with that.

#

you can't press the run button

lapis quarry
#

but that is what i just said

mighty ledge
#

you have to actually have the automation run

#

naturally.

lapis quarry
#

i closed/opened the door 10 times i allways get this trace

#

with the last change

#

ill keep trying

mighty ledge
#

look at previous traces

#

you have 5 spooled traces

#

the automation will be in there because the state is changing

#

this is why using state changed events is frowned upon BTW

#

because every state change will cause the automation to fire

#

the good news is that it seems like it's working now

#

because the automation state is changing

lapis quarry
mighty ledge
#

yes i forget how tho

lapis quarry
#

ok found it, let me see

#

i think its

  trace:
      stored_traces: x
mighty ledge
#

you can trigger the automation and turn it off so it doesn't fire on other state changes too btw

#

so open the door then disable it quickly

#

or try to catch the trace

lapis quarry
#

for debuging you mean right? yes might be better idea

#

but i would have to do it in the code im not quick enough

mighty ledge
#

uh what do you mean?

#

there's a ... menu next to the automation and then a disable button

#

all from the ui

lapis quarry
#

im triggering the automation witrh the set state meny, by the time i move the mouse over the trace is gone

#

was thinking first action when it triggers true would be a line of code to switch off the automation and be able to see the trace with the variables

#

you dont happen to know the code to do that ?

mighty ledge
#

what do you mean "set state meny"

#

set state menu?

lapis quarry
#

Developer tools - states - set state

#

of the binary sensor im testing

mighty ledge
#

if yes, have 2 browsers open. 1 with the automation page, one with set state page. Set the state, then disable the automation.

lapis quarry
#

its what im doing but im not fast enough, as you said this trigger multiple times per second

mighty ledge
#

how many traces do you have?

lapis quarry
#

it only seems to populate the last 2 or 3, if i go any further back it shows nothing

mighty ledge
#

change your trigger to only have the entity_id you're testing

#
    - platform: event
      event_type: state_changed
      event_data:
        entity_id: ...
lapis quarry
#

like this?

#
    trigger:
    - platform: event
      event_type: state_changed
      event_data:
        entity_id: binary_sensor.doorbr01a
#

ok

#

there seems to be some weird behaviour in the trace menu

mighty ledge
#

you can't stay in the trace page

#

it always shows the trace based on it's ID

#

so you have to refresh the page or go backward/forward

lapis quarry
#

i see

lapis quarry
mighty ledge
#

πŸ€·β€β™‚οΈ this is something you’ll have to figure out. I have no idea how you got the first traces but can’t get the current ones.

#

Increase your traces to 100

#

Disable then search.

lapis quarry
#

ok

mighty ledge
#

Just @ me when you figure it out

lapis quarry
#

πŸ‘

mighty ledge
#

All the variables look good

lapis quarry
#

is room_number: '01' supposed to be in quotes?

mighty ledge
#

Yep

#

It’s a string and you want it that way

lapis quarry
#

ok

mighty ledge
#

Your timers and delay seem like the wrong entity

#

So figure that out and the rest should work

#

Gonna be MIA for a bit

lapis quarry
#

ok ill keep testing things, thanks for the help, i also need to go for lunch πŸ˜‰

lapis quarry
#

It doesnt get past the first choose condition, i think its this line but cant figure out how to write it:

            - condition: template
              value_template: >
                {{ 
                  enabled and auto_on
                  and expand(room_sensors) | selectattr('state','eq','on') | list | count > 0
                  and expand(room_aircons) | selectattr('state','eq','off') | list | count > 0
                  and is_state(group, 'home')
                }}````
#

What I would to happen is this:
All the room_sensors should be off for the condition to be true.
If any of the room_aircon switches is off the condition should also be true.

#

and the template should also pass if group is 'home' but also if group is 'on'

#

as groups can either be home or not_home but also on or off based on what kind of entities it contains

solar hemlock
#

{{ is_state_attr('sensor.detroit_lions', 'kickoff_in', "in 33 minutes") }} How could I do math on the number potion, so let's say anything less than <10?

marble jackal
solar hemlock
#

@marble jackal The formatting of the text changes. pre game it shows as "in XX minutes" after the game has started the text portion changes to say "XX minutes ago". But for my purposes I would only care about the pregame format of in XX minutes.

marble jackal
#

But also when it's like days in the future, it will show minutes?

marble jackal
solar hemlock
#

I'm pretty sure it would change from " in X days" "in X hours" and then " in X minutes"

marble jackal
#

No, I forgot to put set in front of it

lapis quarry
#

how can i make this trigger with home state and also with on state?

#
is_state(group, 'home')```
#

i would do yaml - condition: template value_template: > {{ enabled and auto_on and expand(room_sensors) | selectattr('state','eq','on') | list | count == 0 and expand(room_aircons) | selectattr('state','eq','off') | list | count > 0 and is_state(group, 'home') or enabled and auto_on and expand(room_sensors) | selectattr('state','eq','on') | list | count == 0 and expand(room_aircons) | selectattr('state','eq','off') | list | count > 0 and is_state(group, 'on') }}

#

but again im repeating code there must be a better way to write it

#

πŸ˜…

solar hemlock
#

@marble jackal It's giving a syntax error: Encountered unknown tag 'time'.

#

@marble jackal I see now the attribute has switched over to an hour ago. Perhaps that is causing trouble because there is no number to interpret.

marble jackal
lapis quarry
#
              value_template: >
                {{ 
                  enabled and auto_on
                  and expand(room_sensors) | selectattr('state','eq','on') | list | count == 0
                  and expand(room_aircons) | selectattr('state','eq','off') | list | count > 0
                  and (is_state(group, 'home') or is_state(group, 'on'))
                }}```
#

is the above right?

marble jackal
hollow rampart
#

Hello everyone . I need help with a cover template. I’m converting a light entity to a cover using the cover template. When I turn the cover off the entity becomes unavailable. I’m testing the brightness int for > 0 else closed but the brightness attribute disappears when the cover is completely turned off.

dusty grailBOT
inner mesa
#

That's the way lights work

marble jackal
#

Add a default to the int filter

lapis quarry
# lapis quarry ```yaml value_template: > {{ en...

can someone point me in the right direction with this please because if been banging my head for an hour and cant seem to figure out how to write it correctly , the last part how to make it trigger both with 'home' and 'on' πŸ™

hollow rampart
#

@marble jackal what do you mean by adding default to int filter.

mighty ledge
lapis quarry
#

yes that workedπŸ‘Œ πŸ₯°

#

ok so first condition to switch ac on done and working, the second condition to switch ac off is not working either

marble jackal
hollow rampart
#

I’m sorry I’m trying to follow. Is there any specific link you are referring to?

inner mesa
mighty ledge
#

Maybe explain what you actually want

lapis quarry
#

im trying to digest it pc by pc and undertand it and test everything, but my code worked 100%

#

so the second condition is pretty simple

#

when group becomes either not_home or off delay should aply based on what room it is and after that switch ac off

mighty ledge
#

I don’t know how it did, there was a bunch of undeclared variable use when I went through it

lapis quarry
#

to be fair variables didnt exist when i wrote it almost 3 years ago

#

πŸ˜…

#

but you example has been really helpfull to see the new posibiulities the current releases offer

#
        - conditions:
            #> Check window function is enabled window auto_off is enabled for this room
            - condition: template
              value_template: >
                {% set ns = namespace(result = []) %}
                {% for x in expand(room_sensors) | selectattr('state', 'eq', 'on') %}
                  {% set lc = now() - x.last_changed %}
                  {% if 'window' in x.object_id and lc.seconds > window_timeout or 'door' in x.object_id and lc.seconds > door_timer %}
                    {% set ns.result = ns.result + [ x.object_id ] %}
                  {% endif %}
                {% endfor %}
                {{ 
                  enabled and auto_off and ns.result | length > 0
                  and states.switch | selectattr('object_id', 'search', aircon_search) | selectattr('state','eq','on') | list | count > 0
                }}```
#

this portion i cant figure out yet

#

and it doesnt trigger

mighty ledge
#

It’s literally the code you had

#

With all the unnecessary rechecking of the same things removed

#

The only thing that’s new is the selections at the bottom

#

If you remember I told you that door and window timer were probably wrong based on the last traces you sent. They didn’t have a value meaning the entity id is not what your old code claimed it was

lapis quarry
#

i fixed that it was a typo in your code

mighty ledge
#

The name space loop counts sensors and doors that have been open longer than the timer

lapis quarry
#

and its not literally the same code you changed a few things and naming, but hey not complaining, the oposite im blown away from the help received

mighty ledge
#

It’s intent is the same

lapis quarry
mighty ledge
#

No, neither did your old code

#

It’s momentary

lapis quarry
#

my code did because it was a delay

#

it waited there for x seconds and then continued

#

if this loop checks in the monent it triggers if time is greater than timer of course it wont be because we havent waited it to be

mighty ledge
#

Your old code didn’t wait, your old loop was calculated exactly when it was executed. We aren’t talking about the delay that’s applied in another service

lapis quarry
#

so wehy are you checking lc.seconds > window_timeout i dont quite understand

mighty ledge
#

That loop simply counts sensors that are on beyond the specified duration

lapis quarry
#

hmmm

inner mesa
#

#hotel-management

mighty ledge
#

Lc

inner mesa
#

or, perhaps, a thread?

lapis quarry
#

up to you mods i dont know how to do that

#

should i continue the conversation there? btw its not a motel LOL

mighty ledge
#

Yea, rob is fearful of the bates motel support

lapis quarry
#

sorry you lost me 🀣

#

how can i see old threads?

hollow rampart
#

Ok I'm not a coder but I tried to make a change per attached but it is still not working. I understand that my cover entity must never go unavailable.

#

value_template: "{{ 'open' if state_attr('light.dining_room_blind_isy', 'brightness' ) | int(default=0) > 0 else 'closed' }}"

#

i'm having trouble understanding adding default to int filter.

hasty basin
#

hi all, any suggestions how i can setup this template to ignore 0 values?
specifically sensor.met_eireann_solar_today as it will update at night to 0 and ruin the calculation for the day. 😦

  - name: "Solar Forecast Accuracy"
    unique_id: sensor.solar_forecast_accuracy
    unit_of_measurement: "%"
    state: "{{ ((states('sensor.solis_daily_generation') | float /  states('sensor.met_eireann_solar_today') | float) *100 ) | round (3) }}"
#

i looked at filter but i couldn't figure out how to add it

marble jackal
#

Before the template would return an error

marble jackal
hollow rampart
#

Yep that worked like a charm. Thanks for your help!!!

hasty basin
#

@marble jackal I think I got it sorted now, thanks

ancient lynx
#

Hi all. Trying to figure out the simplest way to do this. I would like to have a button I press to set a datetime for when the button is pressed, then have a sensor that is counting the days since that button was pressed. I have already created a button helper, and noticed that the state just sets to a datetime of the last time the button was pressed. I tried to do a {{ now() - states('input_button.appliances_cleaned') }} template, but that gives an error that I'm trying to compare a datetime to a string. How do I convert the state of the button to a datetime to be compared?

#

Tried to do an as_timestamp too, but get a number that is way too large.

hasty basin
#

a few of my sensors go to unknown value on restart of HA. I've searched but cannot figure out how to stop this.

sensor.meteireann_solar_radiation_today which is used in the calculation is updated twice a day by a python script. I don't really want to call it each time HA reboots as this is for a forecast - so don't want a current value.

How can I get HA to update the sensor on reboot? the underlying sensor for solar radiation has a value. If I put the template into developer tools then it will return a value... but still I have unknown. :/

  - name: "Met Γ‰ireann Solar Today"
    unique_id: sensor.meteireann_solar_today
    unit_of_measurement: "kWh"
    device_class: energy
    state: "{{ ((states('sensor.meteireann_solar_radiation_today') | float )*(0.185*23.104/1000)) | round(2) }}"
thorny snow
#

sorry for a total noob question, but i have a MQTT sensor which shows me numerical number. In home assistant IΒ΄d like to se them as the text instead of numbers . How do use templating to show me the state in text instead? the is 4 different numbers depending in the states, starting, running, stopped, stopping. i have found in the templating documentation how it can be done but i have no idea where and how i do implement it

hasty basin
#

@ancient lynx I think DST may mess this up though. Something to consider if you have that in your location...

{{ ((as_timestamp(now()) - as_timestamp(input_button.appliances_cleaned.last_changed)) / 86400) | int }}

ancient lynx
#

That seems to have completely glitched out my HA. The Template page in developer tools just has a pinwheel that won't stop while trying that template.

hasty basin
#

never seen that, sounds weird. it's working for me on an input

#

try restart HA

ancient lynx
#

I did. Same result.

hasty basin
#

@ancient lynx sorry missing states. I guess when I swapped out my switch it got lost

{{ ((as_timestamp(now()) - as_timestamp(states.input_button.appliances_cleaned.last_changed)) / 86400) | int }}

ancient lynx
#

That was it! Thank you.

neon laurel
#

I have the following variable in my template:
{% set lightgroup = 'light.bedroom' %}
I want to pull the name of the room from that variable. How can I use the replace function inside a variable? Something like this
{% set room = lightgroup.replace('light.',) %}

inner mesa
#

you're missing the thing to replace that string with

#

but this is easier: {{ lightgroup.split('.')[1] }}

#

if you wanted to replace with nothing, you have to say that. You can't just put a comma and then nothing

#

it's a string replacement, so you would need {% set room = lightgroup.replace('light.','') %}. But anyway, see above for a better option

neon laurel
#

thank you. I actually need to remove more than what's before the dot, just used that as a quick example since I had to translate to english, so I think replace works better since I'm going to remove the same text for every template

#

but won't calling replace or split on "light" affect the light variable itself?

#

I need it to stay the same

inner mesa
#

no

#

it has no effect on the variable

neon laurel
#

I think it's working, thank you

inner mesa
#

you might consider adding an attribute to each entity via customization that you can reference directly

#

that's a tactic that a lot of folks use

neon laurel
#

encountered another problem, replace is case sensitive

#

I'm trying to grab the room name from the entity_id but the room name in the entity name is capitalized

#

I could grab it from the name instead of the entity I guess

inner mesa
#

or you can just do |lower

neon laurel
#

is there a command to capitalize the first letter?

inner mesa
#

the entity_id can't be capitalized

neon laurel
#

I mean after I extract the room name and assign it to a variable

inner mesa
#

{{ "foo bar"|capitalize }}

#

or {{ "foo bar"|title }} if you want each word capitalized

neon laurel
#

thank you ❀️

inner mesa
#

or, as you say, just use the entity name

neon laurel
#

one more thing

#

I need to join an empty space to the room name

#

tried "join" on its own but it says it's undefined

inner mesa
#

hmm

neon laurel
#

{% set room = join(' ', light.replace('light.','')|capitalize) %}

inner mesa
#

yeah, that's not how to do that

neon laurel
#

I understand why it's saying that but I don't understand what to call join on

inner mesa
#

you just want to add a space?

#

you don't

neon laurel
#

yes, before the room name

inner mesa
#

join is a filter that acts on an interator

#

{{ "foo" ~ " " ~ "bar" }}

#

like taht?

#

if you really wanted to use join, you would do this {{ ['foo', 'bar']|join(' ') }}

#

both result in foo bar

neon laurel
#

I have another idea

#

I'm just gonna call another replace at the end

#

replacing space comma with just comma

inner mesa
#

ok, you clearly know more about the strings you're using

#

you have the tools

neon laurel
#

yeah sorry for not giving an example

#

it was spitting out Bedroom , Kitchen ,

#

works great now

gaunt dirge
#

Has WoL switch configuration changed massively in the last few versions?

inner mesa
#

with regard to templates?

gaunt dirge
#

I tried to update my config yaml with a MAC address that had changed when I replaced a PC motherboard. Now I'm getting errors telling me that the WoL integration is no longer providing the switch

#

I don't think I'm using a template for it, just the simple toggle switch with the wake_on_lan as the platform called

inner mesa
gaunt dirge
#

Oh .. okay. I didn't even think of checking in that room. Thanks. Would it be better to use a template for something that is simply an on switch and an indicator to show that it's on?

inner mesa
#

no, you just picked the wrong channel

gaunt dirge
#

Cool. Thanks for the nudge to the right channel

half pendant
#

I’m using a template to detect when some zigbee sensors over mqtt stoppes working (which they do somethimes) and the template itself works however i’ve noticed that the counter (time since last change) resets everytime HA restarts. Is there anyway to change this so it looks at if the actual value changes or similar?

#

Full template
{{ expand(integration_entities('mqtt')) | selectattr('domain', 'eq', 'sensor') | selectattr('last_changed', 'lt', now()-timedelta(days=2)) | rejectattr('entity_id', 'search', 'batteri') | rejectattr('entity_id', 'search', 'lamplage') | rejectattr('entity_id', 'search', 'luftfuktighet') | rejectattr('entity_id', 'search', 'tryck') | map(attribute='name' ) | join('\n ') | default('none', True) }}

marble jackal
#

For all entities the last_updated object changes to the HA start time after a reboot

#

what is your full yaml for this sensor

half pendant
#
      state: >
        {{ expand(integration_entities('mqtt')) | selectattr('domain', 'eq', 'sensor') | selectattr('last_changed', 'lt', now()-timedelta(days=2)) | rejectattr('entity_id', 'search', 'batteri') | rejectattr('entity_id', 'search', 'lamplage') | rejectattr('entity_id', 'search', 'luftfuktighet') | rejectattr('entity_id', 'search', 'tryck') | map(attribute='name' ) | join('\n ') | default('none', True) }}
#

That’s it

marble jackal
#

So, if I understand correctly, you want to only select those mqtt-sensors which did not have a state change in the last two days. But currently you are unable to do so because the last_changed is updated after a HA reboot?

half pendant
#

Correct

patent harness
#

Hello

Can someone tell me how to have a variable that shows what minute of the current time we are?

Thank you

charred dagger
#

{{now().minute}}

patent harness
charred dagger
#

Variable in what context?

#

Yaml: {% set minute_now = now().minute %}
Automations:yaml variables: minute_now: "{{now().minute}}"

patent harness
charred dagger
mighty ledge
#

pretty sure you can get this info in node red

charred dagger
#

Though I find it hard to believe NR wouldn't have some kind of current time functionality built in.

patent harness
#

I'm also interested in having her in HA

#

How would I create a sensor with this information?

charred dagger
patent harness
marble jackal
#

@half pendant I don't think there is an easy solution for this, especially not if you want to have it dynamically, and not use a fixed lists of sensors to keep track of.

half pendant
#

@marble jackal i see. That's a shame. Would it be possible if I had a group of all sensors i wanted to mange? Or would I have to set it up per sensor?

marble jackal
#

Probably, with a trigger based template sensor you could keep track of the datetime there is an actual state change

half pendant
#

But I'd have to do that for each sensor I wanna track. Does not seem scalable unfortunately

marble jackal
#

you can do it in one template sensor

#

but I was trying to do it dynamically, could not get that working yet

marble jackal
rigid lichen
#

Oh derp... Thought i clicked on frontend

half pendant
marble jackal
#
trigger:
  - platform: state
    entity_id:
      - sensor.1
    not_from: 
      - unavailable
      - unknown
    not_to:
      - unavailable
      - unknown
sensor:
  - state: "{{ 'OK' }}"
    attributes:
      last_changed: "{{ this.attributes.get('last_changed', []) | rejectattr('entity_id', 'eq', trigger.entity_id) | list + [ dict(entity_id=trigger.entity_id, last_changed= states[this.entity_id].last_changed) ] }}"```
#

add an name and unique_id under sensor

#

and all entities under the trigger

#

it will fill itself on every change

half pendant
#

Add all entities under entity_id:? Or one trigger per entity?

inner mesa
#

I don't think that attribute will work

#

You're not starting with state objects

half pendant
marble jackal
#

I didn't test it though

#

Now I did, and it seems I did make a mistake somewhere, however, I have to pick up the kids from daycare now

#

Will have a look later today

quiet lagoon
#

Is there a template that can list all entity ids within a given domain? For example if I wanted all the lights in my house listed out, is there a template that will list them out?

inner mesa
#

sure

#

{{ states.light|map(attribute='entity_id')|list }}

marble jackal
#

Just realized that you can make ik dynamic using a state_changed event trigger and then use the template you were already using to determine if the entity_id should be added/updated in the attribute

#

But it's bedtime here, so that will be for another day

half pendant
waxen meadow
#

Hi, someone help me im need, when is timer bedrom active = 1, timer boiler active = 2, when both active = 3, timer bedroom + boiler idle = 0

{% if is_state('timer.heating_timer_bedroom_radiator', 'active') %}
1
{% elif is_state('timer.heating_timer_boiler', 'active') %}
2
{% else %}
0
{% endif %}

inner mesa
#
{% set radiator = iif(is_state('timer.heating_timer_bedroom_radiator', 'active'), 1, 0) %}
{% set boiler = iif(is_state('timer.heating_timer_bedroom_radiator', 'active'), 2, 0) %}
{{ radiator + boiler }}
waxen meadow
#

thx so much

toxic raptor
#

what are "templates"?

dusty grailBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use https://www.codepile.net/ or https://paste.debian.net/ to share code or logs

toxic raptor
inner mesa
#

yes

#

the 3 links in the beginning

toxic raptor
torn talon
#

hey guys. I have an entity with an attribute containing a date (it's a string) in the '2022-10-02 16:00:00' format. how can I template the number of days from now() until that date?

waxen lynx
#

hi how can i create a template than can be used in autoentities card?

jagged obsidian
#

what are autoentities?

mighty ledge
waxen lynx
mighty ledge
waxen lynx
torn talon
#

it's the start_time attribute from a calendar entity

mighty ledge
marble jackal
#

the date was in the future (at least the example)

mighty ledge
mighty ledge
#

unless i'm remembering wrong

#

remembering wrong, just reverse them then

torn talon
#

TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime' looks like it's a string afterall

mighty ledge
#

{{ (state_attr('calendar.xyz', 'start_time') | as_datetime | as_local - now()).days }}

torn talon
#

that's it

#

thanks

marble jackal
#
trigger:
  - platform: state
    entity_id: input_boolean.test
sensor:
  - name: TEST sensor
    unique_id: 70d778bc-f1d9-48bf-85fd-d4b475e842d3
    state: >
      {{ now() }}
    attributes:
      test: " {{ { 'test': now().isoformat() } }}"
      test2: "{{ now() }}"
#

can I somehow save the date in the attribute of this example as a datetime?

#

test2 works fine, but the attribute test only works as a string

#

Result of current version```yaml
friendly_name: TEST sensor
test:
test: '2022-09-20T15:22:36.765224+02:00'
test2: '2022-09-20 15:22:36.765779+02:00'

#

result without .isoformat()

friendly_name: TEST sensor
test: >-
  {'test': datetime.datetime(2022, 9, 20, 15, 24, 44, 436604,
  tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam'))}
test2: '2022-09-20 15:24:44.436795+02:00'
#

test is not even a dict anymore

mighty ledge
#

you can set test to a datetime, but it won't persist over shutdown

#

whatever you're using to view the information (assuming it's the states page) can't recognized unformatted objects so it it doesn't validate correctly

waxen lynx
#

just use a state filter for the

north locust
#

got my doorbel sounds in an automation with an input_select.doorbell , i want to disable that automation to add seasonal/birthday doorbell sounds, bit baffled that there is no date trigger ... what's the best way to approach this ?ΒΏ

#

like on birthdays/halloween/x-mas disable default input_select.deurbel automation and run doorbell with seasonal sounds

dusty grailBOT
north locust
#

seems correct .. ?

#

hmm have to make multiple automations for my doorbell on all specific dates like halloween, all birthdays , can i put it into one automation somehow

marble jackal
#

You can use them template in the trigger, there is no need to let this automation trigger every day at 1:00

north locust
#

ah was just about to ask add multiple dates in template triggers, assign them trigger ids then change doorbell automation according to trigger id

#

like this but how do i change automation according trigger id

north locust
north locust
#

can i assign the same trigger id like birthday to multiple date templates ?

mighty ledge
#

yeeeeeeeeeeeees

north locust
#

nice thank you

#

like 4 birthday templates tied to one action

#

hmm how do i revert back to the default doorbell automation when those dates are over ΒΏ

versed lava
#

hey everyone, I have a template sensor, that receives a phone number. Only problem: When using the sensor in the frontend, it is displayed with decimal points (eg. 123.456.789.000, when it should be +123456789000. HOw do I change that?

mighty ledge
#

you'll never get it to display + then the number

#

well, actually, the way youre doing it, you will be able to get it in the attribute as + then the number

#

but you wont be able to get it as the state as it will remove the +

#
    - trigger:
        - platform: event
          event_type: sms.incoming_sms
      sensor:
        - name: newest_sms
          state: '{{trigger.event.data.text}}'
          attributes: 
            phone: "{{ {'number': '+' ~ trigger.event.data.phone.replace('.','')} }}"
            date: '{{trigger.event.data.date}}'
#

then to access it

#

{{ state_attr('sensor.newest_sms', 'phone').number }}

#

the problem is, templates will resolve the type, and it will resolve a number. Which means it'll treat it like a number without the +

#

so you have to get around that.

#

the only way to get around that is to output a complex object that contains your value, which is what I just showed you.

#

your other option is to replace the .'s with - and add the + before it. If you're trying to make it clickable.

versed lava
#

Thank you very much!

dusty grailBOT
thorny snow
#

It wasn't a code wall lol

#

Anyway, this is the view

class WarehouseDetailView(DetailView):
    model = Warehouse
    context_object_name = "warehouse"
mighty ledge
#

it's a text wall

#

the bot counts the number of lines

#

over 15 lines -> codewall

#

anwyays, what your posting with the python code doesn't help

#

are you sure you're on the right server?

thorny snow
#

No XD

mighty ledge
#

ok, this is home assistant server

#

not 'general django/python' help

thorny snow
#

lol my. I just the search bar and thought it stayed on the server xD

#

Nana it's Django

#

Totally my bad haha

mighty ledge
#

@thorny snow your product doesn't have an ammount

#

the product class only has name on it

thorny snow
#

Yeah it's the m2m field

#

Don't know how to access it from the template tho. I might just do a custom query

mighty ledge
#

right, but it returns the product

#

.all would most likely return a list of products

#

which doesn't have that attribute

#

property*

thorny snow
#

Yeah, I have to figure out how to use m2m in templates

mighty ledge
#

just do this

#
class Product(models.Model):
    name = ...
    amount = models.IntegerField()
#

you're passing the model into that object

#

or you have to make a new class for

class ProductWarehouseAmount(models.Model):
    product = models.ForeignKey(Product, related_name="product", on_delete=models.PROTECT)
    warehouse = models.ForeignKey("Warehouse", related_name="warehouse", on_delete=models.PROTECT)

    amount = models.IntegerField()

    def __str__(self):
        return f"{self.warehouse} has {self.product} ({self.amount})"
#

a class where products have ammonts

#

and you call that object there for procduct=

#

then again, i've never used that api

#

so I could be wrong

versed lava
#

short (maybe dumb question): In order to clean up my config, I moved all templates to a templates.yaml file, but now all template sensors stopped working. Is it not possible to move the templates?

mighty ledge
#

it's possible to move anything anywhere for the most part, so you did something wrong with your configuration

versed lava
#

yeah, found the bug just as you wrote πŸ™‚

marsh cairn
#

I have some trouble with parsing a template value to a service.

service: fritz.set_guest_wifi_password
data:
  device_id: 123456789123456789
  password: > 
    "{{ states('input_text.password') }}"

The string in input_text.password is e.g. abcd1234.
The service is triggered, but in my FritzBox the password "abcd1234" (with quotes) is set.
If I remove the quotes I get the error "invalid value or type for dictionary value @ data['password']. Got None".
Can anyone give me a hint, what I have done wrong or how to get rid of the quotes?

inner mesa
#

remove the surrounding quotes. You don't need them

#

and use >- instead of >

#

or...just put it on a single line

#
service: fritz.set_guest_wifi_password
data:
  device_id: 123456789123456789
  password: "{{ states('input_text.password') }}"
marsh cairn
#

I tried both. In both cases I get that error message.

mighty ledge
#

fyi device_id doesn't need to be hidden from us, it's unique to you and it's meaningless for security to hide it

inner mesa
#

the only guidance that I can give is that you shouldn't include quotes surrounding the template in a multiline template

#
  1. Use the single-line form with surrounding quotes or
  2. Use the multiline form with >- and no surrounding quotes
marsh cairn
#

It works, if the string contains at least 1 character. If those are just numbers, it throws that error.

inner mesa
#

it probably interprets it as an integer

mighty ledge
#
service: fritz.set_guest_wifi_password
data: >
  {{ {'device_id': '123456789123456789', 'password': states('input_text.password') } }}
marsh cairn
#

That one is working. Thanks a lot!

marble jackal
#

You can probably move the device id to target to simpify it a bit

#
service: fritz.set_guest_wifi_password
target:
  device_id: 123456789123
data: >
  {{ {'password': states('input_text.password') } }}
waxen lynx
#

can someone vouch me how to create a day counter?
from now - 1/12/2022 and output as number of days ( like "25")

inner mesa
#

{{ (now() - "2022-01-12 00:00"|as_datetime|as_local).days }}

waxen lynx
#

thanks for quick response...it shows as -72 days for 2022-12-01..how to remove that "- " value?

#

also i want to use date helper to set the countdown....

#

is it possible to use something like this?(this does not work ..sorry Im newbe )
{{ (now() - {{ states('input_datetime.date')}}|as_datetime|as_local).days }}

inner mesa
#

that negative is correct, since you're starting in December

#

while I was starting in January

#

and yes, as long as you don't nest your templates like that

#

{{ (now() - states('input_datetime.date_test')|as_datetime|as_local).days }}

waxen lynx
inner mesa
#

you have a bunch of examples right there πŸ™‚

#

it's just math with two values

waxen lynx
inner mesa
#

yes, you don't understand

waxen lynx
inner mesa
#

{{ (states('input_datetime.date')|as_datetime|as_local - now()).days }}

#

the point of that is to modify the state

waxen lynx
#

yeah

#

one last question..instead we use date with time ("2022-01-12 00:00") cant we use just date("2022-01-12")?

inner mesa
#

as_datetime wants a particular format

mighty ledge
#

it should work

inner mesa
#

I don't think it did for me

mighty ledge
#

as long as the order is the same

inner mesa
#

which is why I added tat

#

oh, I'm wrong. musta been doing something else

#

oh, I remember. I was using slashes as delimiters and it didn't like that

#

so I added a time, then changed the delimiters

inner mesa
#

yes, that was the previous several messages

#

you could also just try it πŸ™‚

waxen lynx
#

Tried with just date but no luck

inner mesa
#

{{ (now() - "2022-01-12"|as_datetime|as_local).days }}

#

-> 251

#

what were you doing?

#

and my input_datetime entity just had a date as well

waxen lynx
#

Really no idea i just tried the same thing and it showed me error ": missing " something let me try again

inner mesa
#

this is all about attention to detail

waxen lynx
ancient lynx
#

Based on some advice I got here, I have an automation based off of {{ ((as_timestamp(now()) - as_timestamp(states.input_button.appliances_cleaned.last_changed)) / 86400) | int }}. However, it seems that sensor resets every time I start Home Assistant. Is there a way to get the time I press the input button to stick and keep counting up across restarts?

inner mesa
#

HA doesn't know what may have happened while it wasn't running, so that property resets on a restart. You can use an automation to store the current time in an input_datetime whenever the state changes and use that instead

#

or, even better, you can use a trigger-based template sensor

#

even better, the state of an input_button is a timestamp of the last time it was pressed 🀷

#

so just use that

ancient lynx
#

Yeah, is that not what states.input_button.appliances_cleaned.last_changed gives?

#

What you say is exactly what I was trying to do, but that seems to be what resets every time HA restarts.

inner mesa
#

no, states.input_button.appliances_cleaned.last_changed is not the state

#

it's the last_changed property

waxen lynx
#

@inner mesa can you explain ms this part "2022-01-12"|as_datetime|as_local
I under now() generate somthing like 20220921004318

inner mesa
#

it takes a string, turns it into a datetime object, and then assigns it the current timezone

#

I don't know what you mean by

I under now() generate somthing like 20220921004318

#

that's not at all what it reports

#

{{ now() }} -> 2022-09-20 17:45:03.651568-07:00

waxen lynx
#

Okay ... I did some google and took me to mysql funtions console page and it showed output somthing like that

woven folio
#

quick question:
is it possible to define a sensor template with one or more attributes?
I mean, other than the state value, for writing less code i need to have also another value in the same sensor (ie: a string with an html color)

is that possible, or i need 2 sensor templates (value and html color)?

marsh cairn
#

You can have multiple attributes in a template sensor.

north locust
#

how would i add a time to this ?

{{ now().month == 4 and now().day == 11 }}
mighty ledge
north locust
#

specific time on that date

#

like 12:00

mighty ledge
#

now() >= today_at(12:00) and now().month == ...

#

probably easier to just do a time condition.

#

seeing that you have all those template triggers.

north locust
#

ah thank you !

marsh cairn
#

@woven folio

template:
  - sensor:
    - name: ...
      unique_id: ...
      state: ...
      icon: ...
      attributes:
        attribute1: {{ template }}
north locust
#

hmm cannot save this in automation...

"{{ now() >= today_at(14:30) now().month == 9 and now().day == 21 }}"
mighty ledge
#

my mistake

#

You're also missing the and

north locust
#

hmm

"{{ now() >= today_at(14:30) and now().month == 9 and now().day == 21 }}"

still not accepting it πŸ˜›

mighty ledge
mighty ledge
#

single quotes btw, because you have double quotes as the exterior quotes

north locust
#

ahh

#

thank you , templating wizard !

torn talon
#

hey guys, when doing a value.split the first part is index [0], correct?

mighty ledge
#

yes

north locust
#

can i # out conditions or triggers in automations ?

mighty ledge
#

In yaml, yes

north locust
#

nice thnks

#

got my seasonal doorbell switching doorbell sounds now , but how would i get it to switch back to the default bell automation after a certain date ?

half pendant
#

If i wanted to aggregate a couple of energy sensors how would i do that?

marble jackal
#

Oh, that works for conditions as well

marble jackal
inner mesa
marble jackal
#

I found it in the automation trigger docs

#

Seems it is not added to the condition docs

#

But I could add it in the GUI

north locust
#

overthinking it πŸ˜›

#

is a thing

marble jackal
neon laurel
#

I have this template:
{{ expand('group.bedroom_lights')|map(attribute='entity_id')|list }}
I'm trying to remove one entity_id from that list, what's the correct way to do it?

#

I could use replace but that doesn't seem right

#

I'm looking at the jinja docs and it seems like I need to use rejectattr

marble jackal
#

depends where you place it

#

Before the map filter you can use rejectattr('entity_id', 'eq', 'light.not_this_one')
After the map you can use reject('eq', 'light.not_this_one')

proud cradle
#

When should I encapsulate variables in a namespace?

inner mesa
#

If you need to reference it both inside and outside of a loop

proud cradle
#

So if I set a variable outside a loop, then try to modify it inside and then access it after the loop it wont work?

inner mesa
#

Correct

proud cradle
#

Ahh, cool. I didn't know that, thanks πŸ™‚

#

Another question. I have a feeling this could be done with a filer somehow?
Instead of creating a new list, just filter the original one?

{% for price in prices %}
{%   if price.end > now() %}
{%     set ns.prices = ns.prices + [price.value] %}
{%   endif %}
{% endfor %}```
inner mesa
#
{% set items = [
  {"price":1, "end": now() + timedelta(minutes=1)},
  {"price":2, "end": now() + timedelta(minutes=1)},
  {"price":3, "end": now() - timedelta(minutes=1)}
] %}
{{ items|selectattr('end', 'gt', now())|map(attribute='price')|sum }}

-> 3

proud cradle
#

I knew it πŸ™‚ I'm coming from the traditional (php) style of coding, where can I find a reference for the template language?
It's Jinja2 right? Like the map() you're using, where I can read how that works?

inner mesa
#

in the channel topic

dusty grailBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use https://www.codepile.net/ or https://paste.debian.net/ to share code or logs

proud cradle
#

πŸ‘ŒπŸ»

#

Is there any way to write several commands/lines within a single {% %} block or do I have to wrap everything?

inner mesa
#

you need to wrap each logic statement with {% %} and each output statement with {{ }}

proud cradle
#

I can't do this somehow?

{% set prices = states.sensor.nordpool.attributes.raw_today + states.sensor.nordpool.attributes.raw_tomorrow
    | rejectattr('value', 'in', [None])
    | rejectattr('end', 'lt', now())
    | list
%}```
inner mesa
#

You can. That's just logic, and it's one line

proud cradle
#

Hum, but it outputs values older than now too?

#

Must be an error in my code?

inner mesa
#

No, it outputs nothing

#

It sets the prices variable

#

I didn't check your logic

#

I don't know what's in that attribute

proud cradle
#

A string like this: 2022-09-21 01:00:00+02:00

inner mesa
#

there's no "end" or "price" in that

#

or "value"

#

I'm talking about this: states.sensor.nordpool.attributes.raw_tomorrow

proud cradle
#
    'start': datetime.datetime(2022, 9, 21, 0, 0, tzinfo = zoneinfo.ZoneInfo(key = 'Europe/Stockholm')),
    'end': datetime.datetime(2022, 9, 21, 1, 0, tzinfo = zoneinfo.ZoneInfo(key = 'Europe/Stockholm')),
    'value': 2.77
}
#

That's one element from the prices array

inner mesa
#

this works fine for me:

{% set items = [{
    'start': "2022-09-21 00:00"|as_datetime|as_local,
    'end': "2022-09-21 01:00"|as_datetime|as_local,
    'value': 2.77
}] %}

{% set prices = items
    | rejectattr('value', 'in', [None])
    | rejectattr('end', 'lt', now())
    | list
%}
{{ prices }}
#

I suggest breaking down the expression on your system to see what's wrong

#

I get an empty list, and if I change the "end" date to '2022-09-23 01:00' I get that entry

proud cradle
#

Could it be that my list have the datetme.datetime() as a string and you're converting it to an object?

inner mesa
#

that is an object

#

from my example (which you can also try)

#
{% set items = [{
    'start': "2022-09-21 00:00"|as_datetime|as_local,
    'end': "2022-09-23 01:00"|as_datetime|as_local,
    'value': 2.77
}] %}
{{ items }}

->

[{'start': datetime.datetime(2022, 9, 21, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles')), 'end': datetime.datetime(2022, 9, 23, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles')), 'value': 2.77}]
proud cradle
#

Found the issue.. I was merging two lists: list1 + list2 | .... Of corse it applied the filters to the last list then merged. Wrapped in () it works πŸ™‚

inner mesa
#

oh, yeah

#

I should have spotted that

half pendant
inner mesa
#

clear

#

if by "aggregate" you just mean "add them together", it's easy

#

{{ states('sensor.foo')|float + states('sensor.bar')|float }}

half pendant
#

Yeah i mean add the values together. And get history for it

inner mesa
#

make a template sensor out of that

half pendant
#

So that i can use it in my energy dashboard as well

inner mesa
#

if you add the proper fields when you create the template sensor, yes

half pendant
inner mesa
#

creating a template sensor with a variant of that template is straightforward

#

ensuring that it has the right units and class and such is something that #energy-archived can help with

half pendant
#

Ok

dusty grailBOT
inner mesa
#

you didn't actually use the optimization I provided initially

#

so...

#

and you have a ton of stuff in that namespace that doesn't need to be there

proud cradle
#

Just thought I should keep all variables in one place but that's bad practice with the namespace

inner mesa
#

you don't need the namespace at all if you do what I suggested in teh beginning

#

you asked, then didn't actually use it

dusty grailBOT
inner mesa
#

you don't need both "prices" variables - you can just add the two filters to the first one

#

I don't understand what "threshold" is doing there

proud cradle
#

Tried but it really do not like that:
UndefinedError: 'float object' has no attribute 'value'

inner mesa
#

you did something wrong

proud cradle
#

That's for sure πŸ˜‰

inner mesa
#
{% set rawPrices = (states.sensor.nordpool.attributes.raw_today + states.sensor.nordpool.attributes.raw_tomorrow)
    | rejectattr('value', 'in', [None])
    | rejectattr('end', 'lt', now())
    | map(attribute='value')
    | sort
%}
proud cradle
#

Ahh it was the | list that was the problem

#

The threshold variable is the 25 percentile of the list

inner mesa
#

ok

proud cradle
#

Thanks for all the help @inner mesa πŸ™‚

toxic raptor
#

whats wrong here

{{float((('sensor.energi_data_service','today_min')+(('sensor.energi_data_service','today_mean')--('sensor.energi_data_service','today_min')) / 2 )) }}

marble jackal
#

A lot

#

You are not getting the state of these sensors

#

And you are only applying the float filter once, while all states are strings

mighty ledge
#

multiple minus signs

#

in a row

#

{{ (state_attr('sensor.energi_data_service','today_min') + state_attr('sensor.energi_data_service','today_mean') - state_attr('sensor.energi_data_service','today_min')) / 2 }}

marble jackal
#

Ah wait, these area indeed attributes, no float filter needed

toxic raptor
mighty ledge
#

also, if you're getting that error, that means the values you're trying to add aren't numbers

#

take a screenshot of sensor.energi_data_service in the developer tools -> states page in the grid below. Make sure to include the attributes.

dusty grailBOT
#

@toxic raptor Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

toxic raptor
toxic raptor
# mighty ledge take a screenshot of `sensor.energi_data_service` in the developer tools -> stat...

That wont fit on my screen, nor as text in this text box, and it appears i cant attach a document or image either?

edit; these should be the important bits:
today_min:
hour: '2022-09-21T04:00:00+02:00'
price: 2.765
today_max:
hour: '2022-09-21T19:00:00+02:00'
price: 5.344
today_mean: 3.534
tomorrow_min:
hour: '2022-09-22T13:00:00+02:00'
price: 2.566
tomorrow_max:
hour: '2022-09-22T19:00:00+02:00'
price: 5.581
tomorrow_mean: 3.608

mighty ledge
#

That’s why the bot had a link to the share site πŸ˜‰

#

Really?

#

Why tf should I help you if you’re gonna be an ass

toxic raptor
analog mulch
#

I have a template trigger with multiple sensors. Is it possible to get the area name of the device which actually triggered and should be stored in the trigger variable?

marble jackal
#

yes

#
trigger:
  - platform: state
    entity_id:
      - sensor.sensor_1
      - sensor.sensor_2
    to: ~
    variables:
      area: "{{ area_name(trigger.entity_id) }}"
analog mulch
#

great thank you

tepid onyx
#

I'm trying to create a variable where the first characters is an *
yaml does not appear to like this. How can I escape it. I've tried using single, double and backslashes

dkim_line: "*@{{ dkim_domain }} {{ dkim_date }}._domainkey.{{ dkim_domain }}"

marble jackal
#

does this maybe work?
dkim_line: "{{ '*@' ~ dkim_domain ~ ' ' ~ dkim_date ~ '._domainkey.' ~ dkim_domain }}"

vocal agate
mighty ledge
#

"{{ (states('sensor.arbeit_start') | as_datetime - states('sensor.arbeit_ende') | as_datetime).seconds / 60 }}"

vocal agate
#

that easy?

round pecan
#

How can I get all light entities from MQTT integration ? Is that possible ?

mighty ledge
mighty ledge
vast juniper
#

Hello people from templates πŸ˜€ Can someone point it out what in doing wrong here? I want to write the value that is in the template to helper in automationservice: input_number.set_value data: value: | {{ (state_attr('sensor.new_home_to_work_2', 'duration') |string).split('.')[0] }} target: entity_id: input_number.slider

round pecan
#

@mighty ledge thanks a lot, this I have been searching for 1 hour
Β΄integration_entities('mqtt')Β΄

mighty ledge
round pecan
#

I have but must have missed it

mighty ledge
#

it's got it's own section

#

albeit it's a whole wall of text

round pecan
#

Need new glasses 🀣

mighty ledge
#

the template docs need to be broken out by method

mighty ledge
vast juniper
half pendant
#

I have this template

        unique_id: livingroom_heater_daily_consumption
        unit_of_measurement: kWh
        device_class: energy
        state_class: total
        state: >-
          {% set a= (states('sensor.livingroom_left_day_consumption') | float(0) ) %}
          {% set b= (states('sensor.livingroom_right_day_consumption') | float(0) ) %}
          {{ '%0.3f'|format(a+b) }}
        availability: >-
          {% set sensors = ['sensor.livingroom_left_day_consumption', 'sensor.livingroom_right_day_consumption' ] %}
          {{ expand(sensors)|rejectattr('state', 'is_number')|list|length == 0 }}```

That i want to re-use for a bunch of different energy sensors. The problem is that i will add a lot more sensors in the template and since they are both used in the `state` part and the `availiability` part that’s gonna mean i have to repeat a lot of code. Is there anyway to move them to a variable somehow, so that they can be reused in both parts of the template sensor?

Obviously it works inside of the `state`part (since i do it with a and b) but i’m not sure if it works for the whole sensor?
#

(Also how do you do inline code blocks in discord?)

mighty ledge
#

1 tick

#

`

#

like this

versed lava
#

is it possible to only update a template sensor if one attribute of a certain event has a specific value (reason: I'm receiving status updates from different devices vis sms and sort those messages into different template sensors) I'm currently using a trigger template sensor to store the newest received sms message but of course that's not very device specific

mighty ledge
#
- trigger:
  - platform: state
    entity_id: &xyz_entities
    - sensor.x
    - sensor.y
    variables:
      entities: *xyz_entities
  sensor: 
  - state: &state >-
      {% set value = expand(entities) | map(attribute='state') | map('float', 0) | sum %}
      {{ '%0.3f'.format(value) }}
    availability: &availability >-
      {{ expand(entities)|rejectattr('state', 'is_number')|list|length == 0 }}
      
- trigger:
  - platform: state
    entity_id: &abc_entities
    - sensor.a
    - sensor.b
    variables:
      entities: *abc_entities
  sensor:
  - state: *state
    availability: *availability
versed lava
mighty ledge
#

you can only do it with a trigger template sensor

half pendant
mighty ledge
#

those are yaml anchors

versed lava
mighty ledge
#

makes a variable, plops in in another spot. & declares it, * plops it

mighty ledge
half pendant
#

But in the rest of your code you don’t write xyz, you just write entities?

#

Also are yaml anchors specific to a sensor or to a file?

mighty ledge
#
- trigger:
  - platform: template
    value_template: "{{ state_attr('sensor.xyz', 'attr') == 4 }}"
  sensor:
  - name: ...
    state: >
      {{ your template }}
mighty ledge
#

trigger variables have nothing to do with yaml anchors

#

are you able to distinguish yaml from templates?

half pendant
#

Not sure πŸ€·β€β™‚οΈ

#

Yaml is the code-ish?

mighty ledge
#

no

#

yaml is a formatting language, it's not code

half pendant
#

Right, thats what i meant

mighty ledge
#

{% jdalfkjsal %} {{ }}

half pendant
#

Ish

mighty ledge
#

that's the code

#

&something and *something are yaml only items, and they do not affect templates (Jinja, i.e. {{ }} and {% %})

#

all they do is copy the contents from the & and paste the contents where the * is

#

essentially

#

the trigger itself has entities variable

#

that's where the entities in the code is coming from

versed lava
mighty ledge
#

no

#

you said entity attribute

versed lava
#

yeah, that was a mistakt sorry

mighty ledge
#

if you want event data, you'd have to go a different route

versed lava
#

Rn, I would think Trigger Template Sensor that reacts to every event (S1, storing Message and Phonenumber) -> Trigger template sensor that only reacts if the "phonenumber" attribute of S1 is a specific one would be a good way accomplish my goal?

#

or would there be a better way?

versed lava
#

So, I'm trying to use this here "{{state_attr('sensor.newest_sms', 'phone') == !secret phone_sprinter }}" template but it doesn't work because of the whole !secret part. Is it possible to a secret here?

inner mesa
#

No

marble jackal
#

Where are you using this? If it's an automation, script or trigger based template sensor, you can put the secret in a variable

inner mesa
#

That's true. You can only use a secret in a value for a key

versed lava
#

in the end, I settled on just using# the value, not a secret. However, it still doesn't work. https://hastebin.com/bowabuceve.yaml is the code I'm using but I don't really find any miskates and no error logs

inner mesa
#

Is the attribute a string or an integer? I'm guessing it's a string

#

So you need to surround it in quotes

versed lava
#

well, I'n not quite sure actually but yesterday I had a problem, where the phone number was displayed with decimal points (eg. 123.456.789 instead of 123456789)

inner mesa
#

I dint know what to say about that

marble jackal
#

You can test it in devtools > templates

#

{{state_attr('sensor.newest_sms', 'phone') is string }}

versed lava
#

it seems like the number is stored as an integer

inner mesa
#

Representing a phone number as an integer would be weird

versed lava
#

{{state_attr('sensor.newest_sms', 'phone') is integer }} -> true

marble jackal
#

Then it's a string

versed lava
#

oops, wrong

marble jackal
#

And you need to use quotes around it in your comparison

versed lava
#

there should be integer, not string

#

{{state_attr('sensor.newest_sms', 'phone') is integer }} -> true
{{state_attr('sensor.newest_sms', 'phone') is string }} -> false
would be the correct thing

marble jackal
#

Ah, okay

versed lava
#

sorry

marble jackal
#

Did the attribute change, or was the previous sms from the same number?

versed lava
#

previous sms was from the same number

marble jackal
#

Then it won't trigger, as the template was already true

versed lava
#

oooh

marble jackal
#

It has to change from false to true

versed lava
#

well, then sadly the whole thing doesn't fit my need. See, I'm trying to receive gps position data from certain devices over sms (there is only a 2G network and no wifi where these devices are located and mobile data is kinda expensive compared to an sms flat). Location data comes in from multiple devices and I'd like to update a sensor for each device if new location data comes in from that specific device (but like every time new data comes in, even if there's data two times in a row from the same device)

marble jackal
#
  - trigger:
      - platform: state
        entity_id: sensor.newest_sms
        attribute: date
        variables:
          number: !secret phone_number
    sensor:
      - name: sms_sprinter
        state: "{{ trigger.to_state.state if trigger.to_state.attributes.phone == number else this.state }}"
        icon: mdi:message-text
        attributes:
          date: "{{ trigger.to_state.attributes.date if trigger.to_state.attributes.phone == number else this.attributes.get('date') }}"