#templates-archived

1 messages · Page 98 of 1

brisk temple
#

Or instead of != ?

inner mesa
#

can you write in English exactly the conditions you want? that usually helps

#

I mean 'and' these:

#
      - condition: template
        value_template: "{{  trigger.from_state != 'unavailable' }}"
      - condition: template
        value_template: "{{  trigger.from_state != 'unknown' }}"
#

and or these

#
      - condition: template
        value_template: "{{  states('sensor.live_hass_version') != states('sensor.current_version') }}"
      - condition: template
        value_template: "{{  states('sensor.live_hass_version') != states('sensor.beta_version') }}"
#

and 'and' them together

#

when from_state is not equal to 'unavailable' and from_state is not equal to 'unknown' and (hass version is not current or hass version is not beta version) alert

#

right?

brisk temple
#

I think your just reducing the code, which is great, but the conditions aren't hitting as I expect

inner mesa
#

I don't think your conditions are correct

#

for instance, if from_state is "unknown", your 'or' statement will pass because it's also not 'unavaialble"

brisk temple
#

Ah

#

I gotcha

inner mesa
#

you're just oring them all together

brisk temple
#

I'll reformat it with if, elif etc thanks

inner mesa
#

probably easier than wrestling with the YAML formatting, to be honest

brisk temple
#

Ya

buoyant pine
#

trigger.from_state also needs to be trigger.from_state.state

brisk temple
#

Thanks I'll move it back

inner mesa
#

you're just dying to get rid of .state, aren't you?

#

the docs will set you free

brisk temple
#

I have it set to read tomorrow

inner mesa
#

randomly adding or deleting things is one way to solve problems

#

it just may take infinite time

modern night
#

I'm looking for a way to check and see if all of our iphones are charging. Would a template be the correct way to do that?
sensor.tommys_phone_battery_state The value is either "Charging" or "Not Charging" for this sensor

warm isle
#

comeon bot..

modern night
#

thank you!

river saffron
#

looks like images aren't allowed here, but i'm trying to remove new lines using regex. this is my current markdown card code (had to remove weird = that appeared already).
`Hello, {{user}}

{{ state_attr('sensor.xxxx_email', 'body') |regex_replace(find='=', replace='', ignorecase=False)}}`

#

using the imap_email_content default config (which pulls the body of the email)

timid osprey
#
{{"test
test

=

test"

| regex_replace(find='=', replace='', ignorecase=False)
| regex_replace(find='\n', replace='', ignorecase=False)

}}
#

this worked for me

#

@river saffron did you see that?

river saffron
#

sorry, saw it now

#
{{"test
test

=

test"

| regex_replace(find='=', replace='', ignorecase=False)
| regex_replace(find='\n', replace='', ignorecase=False)

}}

@timid osprey didn't work, but restarting

#

yeah, that doesn't work

timid osprey
#

in your template tester?

river saffron
#

in the markdown card. the = part works (i removed it and the = reappeared) but the \n did nothing

timid osprey
#

okay, I know nothing about that card but markdown does line returns with double spaces

#
{{
"test
test

=

test"
| regex_replace(find='=', replace='', ignorecase=False)
| regex_replace(find='\n', replace='', ignorecase=False)
| regex_replace(find='  ', replace=' ', ignorecase=False)
}}
#

you could try that

river saffron
#

figured it out

#

\r\n instead of \n

timid osprey
#

okay, odd that it works on template editor

#

for me

ivory delta
#

The line break you're trying to remove is likely to care about which OS you typed it on.

timid osprey
#

yeah, I stepped away and realized what was going on

river saffron
#

i guess i'm confused how regex works. is it dependent on what OS it is being viewed on? or what OS HA is installed on?

#

per the link \r\n is for windows. i'm viewing it on windows but HA is installed on a debian machine

modern night
#

New to templating here. I'm trying to create a template that I can evaluate with "everyone_ready_for_bed". Here's the template, but I don't see it under Developer Tools -> States. This is in a file "bedtime.yaml"

- platform: template
  sensors:
    everyone_ready_for_bed:
      friendly_name: 'Everyone ready for bed'
      value_template: >-
        { % if is_state('sun.sun', 'below_horizon') and
               is_state('tommys_iphone_battery_state', 'charging') and 
               is_state('cindys_iphone_battery_state', 'charging') and 
               is_state('tylers_iphone_battery_state', 'charging') and 
               is_state('sarinas_iphone_battery_state', 'charging') %}
        'on'
        {%- else -%}
        'off'
        {%- endif -%}
chrome temple
#

Is that under sensor: or binary_sensor:?

#

Are you getting config errors? How is bedtime.yaml included? Is HA even seeing it?

modern night
#

Ah. I think that's the first problem. The file is in an ./includes folder, which I though was included automatically, but apparently it's not. So, I guess i need to move that to my automations folder.

#

Actually, I'm not sure. I'd like to set a binary sensor for the state, which I can check to automatically set my home alarm and turn off a few things.

chrome temple
#

Well where you put that YAML code depends on how you have your system configured. But assuming it ends up under binary_sensor:, then there are two problems. First, the entity_id's in the is_state() function calls aren't valid entity_id's. I'm assuming they should be sensor.blah. The second problem is a template binary sensor's value_template should evaluate to true or false. Putting these together I'd suggest:

      value_template: >
        {{ is_state('sun.sun', 'below_horizon') and
           is_state('sensor.tommys_iphone_battery_state', 'charging') and 
           is_state('sensor.cindys_iphone_battery_state', 'charging') and 
           is_state('sensor.tylers_iphone_battery_state', 'charging') and 
           is_state('sensor.sarinas_iphone_battery_state', 'charging') }}
past wigeon
#

how would you go about setting a templated automation to use a condition in the name.

#

something like this:

#
  • id: ikea_power_on_trigger
    alias: Turn on ikea light when heard join notification
    trigger:
    platform: mqtt
    topic: zigbee2mqtt/bridge/log
    action:
    service: light.turn_on
    data_template:
    entity_id: light.{{ trigger.payload_json.meta.friendly_name }}
#

which would only apply if the name contained _light

ivory delta
#

i guess i'm confused how regex works. is it dependent on what OS it is being viewed on? or what OS HA is installed on?
@river saffron regex will work the same on every system. The difference is the input. If I create a file in Notepad on Windows with line breaks in, Windows will add \r\n. If I save it, send it to you, and you open it on Linux, those line breaks are still \r\n. They're invisible characters in the file and don't change automatically just because you're viewing it on a different OS.

vast parcel
#

Hi, I'm trying to make a climate toggle switch and I'm tring to make a template switch

#
  • platform: template
    switches:
    aerconditionat_on_off:
    value_template: "{{ is_state('climate.mideaac', 'on') }}"
    turn_on:
    - service: climate.turn_on
    entity_id: climate.mideaac
    turn_off:
    - service: climate.turn_off
    entity_id: climate.mideaac
#

Now i'm here, but when i turn off, after 3 seconds it goes back to off

river saffron
#

@river saffron regex will work the same on every system. The difference is the input. If I create a file in Notepad on Windows with line breaks in, Windows will add \r\n. If I save it, send it to you, and you open it on Linux, those line breaks are still \r\n. They're invisible characters in the file and don't change automatically just because you're viewing it on a different OS.
@ivory delta ok so it's the source of the content. since it's the imap_email_content, it must be how the email is formatted then.

mighty ledge
#

@vast parcel does climate.mideaac go to the state 'on'?

onyx quest
#

Any guess why this isn't rounding at all? I want no decimal places:

#

value_template: >- {{ (float(states.sensor.jane_s_room_temperature.state) + float(states.sensor.gameroom_thermostat_temperature.state) + float(states.sensor.upstairs_thermostat_temp.state)) / 3 | round()}}

ivory delta
#

I think you're rounding the 3 at the end, then doing the division.

#

Put brackets around everything before the | round()

onyx quest
#

ok I tried

#

{{ (float(states.sensor.jane_s_room_temperature.state) + float(states.sensor.gameroom_thermostat_temperature.state) + float(states.sensor.upstairs_thermostat_temp.state)) / 3 }} | round()

#

but still geting 78.333333333

ivory delta
#

Uh... that's not what I said.

#

Brackets (), not curly braces {}.

onyx quest
#

Ah jeez ok I've always called those parentheses

ivory delta
#

That's another name. It just takes longer to type 😄

onyx quest
#

No worries!

#

At any rate, that worked like a charm - thanks!

timid osprey
#

[] brackets

ivory delta
#

Square brackets, yes 😉

timid osprey
#

😛 are you US?

ivory delta
#

When I'm not being lazy, I'll use the full 'parentheses' (), 'square brackets' [], 'curly braces' {}. Clarity of language matters when describing dev stuff.

#

No, I'm British. Happy to hear that the US also uses the correct terminology though.

timid osprey
#

we just default a "bracket" to square

#

parentheses = round

violet oyster
#

im american and just dont bother learning the names lol

jagged obsidian
#

good on you to keep propagating the stereotype

violet oyster
#

lol trying my best

#

we're awful.

dreamy sinew
#

"parens" "square brackets" and "curly brackets" for me

spark isle
#

I tried creating a template cover using a shelly 1 relay and wyze door contact sensor. I get it showing up in lovelace but only the open arrow is operational the close arrow is not. The icon also will not change depending on if the door is open or closed. Below is my info

#

cover:

  • platform: template
    covers:
    garage_door:
    value_template: "{{ is_state('binary_sensor.wyzesense_77a56ff3', 'on') }}"
    open_cover:
    service: switch.toggle
    data:
    entity_id: switch.shelly_shsw_1_e0980694eb47
    close_cover:
    service: switch.toggle
    data:
    entity_id: switch.shelly_shsw_1_e0980694eb47
    icon_template: >-
    {% if is_state('binary_sensor.wyzesense_77a56ff3', 'open') %}
    mdi:garage-open
    {% else %}
    mdi:garage
    {% endif %}
thorny snow
#

@spark isle
your states are off
binary sensor = on/off
not open

#

can I stick such a template in a single line?

    - condition: or
      conditions:
        - condition: template
          value_template: "{{ 'single' == trigger.payload_json.click }}"
        - condition: template
          value_template: "{{ 'double' == trigger.payload_json.click }}"
mighty ledge
#

@thorny snow

value_template: "{{ trigger.payload_json.click in ['single', 'double'] }}"
thorny snow
#

I realy should learn jinja - thanks a lot petro

mighty ledge
#

np

modern night
#

I'm working on an automation to test if all of our phones are charging, and just set an input_boolean to reflect that. This would require two automations, correct? One that would trigger if they are all charging, and another if not.

chrome temple
#

Why not just create a binary template sensor? No need for automations.

modern night
#

I've been messing with that to no avail. Thought I'd break it down. I hate to bug people, and I've read through the docs but I'm not understanding real well. You helped me with that some yesterday. Would that binary template sensor be considered an automation?

ivory delta
#

They're not triggered, as such. Their state just changes as needed as the underlying entities update.

modern night
#

so, I've got my config split out into a folder for automations, packages, and then one called "includes" which are directly reference from configuration.yaml. I'm just not understanding where to place it.

chrome temple
#

Well that's a separate issue. One thing at a time. Do you understand how to create a binary template sensor for this?

ivory delta
chrome temple
#

Ah. I had that channel muted so I didn't notice. 😅

chrome temple
thorny snow
#

how do I test properly in an if else template?

- service_template: >-
        {% if (trigger.payload_json.click, 'off') and
                   is_state("switch.relay", "off") %}
       light.turn_off
        {% else %}
          script.turn_on
        {% endif %}
``` I got the feeling that I'm close
chrome temple
#

You can put that in the template editor, after:

{% set trigger = {"payload_json": {"click": "off"}} %}

But I can tell you (trigger.payload_json.click, 'off') isn't right. It should probably be trigger.payload_json.click == 'off'.

thorny snow
#

that makes things faster - I restart here over and over

hexed wing
#

@thorny snow You can also avoid template altogether and sue the new choose action 🙂

calm grove
#

hi there! I am a newbie and ask me how to set conditional icon according my roller shutter state. I use shelly relay to manage the shutters. I got on dashboard a card with inside my shutters, I can change icon but how to ser mdi:window-shutter icon when state is close or up to 80% close and mdi:window-shutter-open when it's open ?

inner mesa
#

I do this for my garage door:

#
- platform: template
  sensors:
    garage_door_state:
      value_template: '{% if is_state("binary_sensor.garage_door_sensor", "on") %}Closed{% else %}Open{% endif %}'
      friendly_name: 'Garage Door'
      icon_template: '{% if is_state("binary_sensor.garage_door_sensor", "on") %}mdi:garage{% else %}mdi:garage-open{% endif %}'
calm grove
#

thanks @inner mesa

thorny snow
#

Thanks Frenck, pnbruckner pointed me already to it, but I dont like the structure to much.
I actualy prefere the template syntax.

marsh thunder
#

Hi all, still prett fresh to this; I’ve been trying for hours now to set up 2 x template sensors and can’t work out where they go.
I’ve built an ultrasonic level sensor for a tank and by default it measures distance to object. Using a lambda filter I can get it to return either percentage or litres, however I would like both % and L displayed in lovelace. I think I do that using template sensors and the default distance output and a maths equation.
I’m struggling to find where I put the template sensors and how to build the value_template from my formula. I’ve tried putting it in my sensor.yaml and it faults and I’ve tried putting it in my config and it faults. Feel like I’m missing something. I’m using supervisor hass

thorny snow
#

~template

inner mesa
#

bot is dead

thorny snow
#

oooh

#

skalavana left?

inner mesa
#

need to see your config and your errors

dreamy sinew
#

Nah, discord changed something and he hasn't had time to work on it

thorny snow
#

pff 😄 at least.
(just get the deam emojis back 😛 )

marsh thunder
#

@inner mesa so it’s meant to be in config rather than the sensor.yaml?

#

@thorny snow man I tried reading that, it’s so far above my head haha 😦

inner mesa
#

it can be in either location, but it depends on what you're doing

#

need to see your config

thorny snow
inner mesa
#

if you have a sensors.yaml or similar, then do that

#

I'm guessing that you probably put sensor: in there, and that's your problem

#

but random guessing without seeing what you alredy have

marsh thunder
#

I’ll take a screenshot

inner mesa
#

no

#

share text

thorny snow
#

no screenshots here

inner mesa
#

screenshots of text are worthless

thorny snow
#

little bit better then unformated text

#

not much, but a little

marsh thunder
#

Was just to show error

thorny snow
#

I guess youre missing the first step
go to your frontend and into developer-tools/template

marsh thunder
#

Oh yeh where you can try it out. Sorry I must sound like the biggest noob but I couldn’t figure out that either

thorny snow
#

in there delete everything and start with this

{{ states("sensor.NAME_OF_YOUR_SENSOR_FIND_IN_STATES") }}

(the button 2 left of template)

marsh thunder
#

Brb I’ll goto computer, trying to copy text on my phone isn’t ideal

thorny snow
#

just use the one you got already in there

  Anne Therese is at {{ states("device_tracker.anne_therese") }}
  Paulus is at {{ states("device_tracker.paulus") }}
#

thats the start of almost every template,

marsh thunder
#

Thanks mate, from there I should be able to get the equation sorted. Then I gotta figure out where to put it all

thorny snow
#

thats a little tricky too,
I advice you to create a package folder, its realy waaay easyer in the start, but you ll hate you later when you want to tidy it up

#

then you can have a file with content like this

silent barnBOT
thorny snow
#

rly bot.. 😄 just check the link

#

take care that you dont mix " and ' in the variables (line 8)

#

use one inside and anotherone outside

#

you ll need both things here, templates wont update themselfs without an entety

fierce hornet
#

Still getting started with template. What do I need to use to grab the entity's friendlyname?

thorny snow
#

nah - head over to states

#

friedly name is just for humans

#

you ll need the Entity ID

marsh thunder
#

@thorny snow thanks heaps i'll check it all out and have a crack

inner mesa
#

friendly_name is an attribute, so follow the instructions here using is_state_attr()

#

here's the trigger in one of mine:

#
- alias: 'fr_yttv_started'
  initial_state: true
  trigger:
    - platform: template
      value_template: >-
        {{ is_state_attr("remote.family_room", "current_activity", "Watch Shield") }}
fierce hornet
#

Thanks, I will take a look at it!

#

Sadly it looks like my friendly_name doesn't actually change, there is a attribute called sonos_group that has the value of ['media_player.beam', 'media_player.one'] What would be the correct format to use that? just putting that between the "" doesn't do the trick.

coarse tiger
inner mesa
#

"doesn't work"?

coarse tiger
#

yeah before i got a nice list of device_tracker entities out of this template... now it stays empty :/

inner mesa
#

did you look at sensor.wifi24devices in dev->States?

fierce hornet
#

Sadly it looks like my friendly_name doesn't actually change, there is a attribute called sonos_group that has the value of ['media_player.beam', 'media_player.one'] What would be the correct format to use that? just putting that between the "" doesn't do the trick.
Nevermind, it works but for some reason it reports false

coarse tiger
#

yep both loops return their devices, but the comparison fails for some reason

inner mesa
#

@fierce hornet I'm sure there's a more elegant way, but this would work:

#
{% set attr = state_attr(sensor.xxx, "attr") %}
{% 'media_player.beam' in attr and 'media_player.one' in attr %}
fierce hornet
#

What would go into the place of sensor.xxx? I'm using a template switch. So would that become the template switch itself?

inner mesa
#

whatever the entity is

fierce hornet
#

ohh

inner mesa
#

that's an attribute of something, right?

#

looks like "attr" should be "sonos_group'

#

just piecing things together from your messages

#

point is, I don't think it'll work as just a string comparison

fierce hornet
#

Trying it now using sonos_group as attr

inner mesa
#

try it in dev->Templates

#

first

fierce hornet
#

Yea I was already working there

#

I get the error tag name expected

inner mesa
#

share your template?

fierce hornet
#

Using

{% 'media_player.beam' in attr and 'media_player.one' in attr %}```
inner mesa
#

screenshot of the entity in dev->states?

fierce hornet
inner mesa
#

oh, sorry

#

it'll work in dev->templates if you just add "if" to the second line:

marsh thunder
#

@thorny snow i havent gone through packages yet but as far as adding it to my water_tank_level.yaml i get the following error, gets caught up at sensors:

#

mapping values are not allowed here in "/config/esphome/water_tank_level.yaml", line 49, column 10: sensors: ^

fierce hornet
#

No need for sorry, wouldn't have been able to figure this out myself

inner mesa
#

this should work in a template trigger:

#
{% set attr = ['media_player.beam', 'media_player.one'] %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%endif%}
fierce hornet
#

Gives true now, looks like it working

#

let me see if it changes to false

inner mesa
#

I had it working and then made some changes that I thought would get it closer to what you need. And I broke it 🙂

fierce hornet
#

Uhh it seems to be always true now? 😅

inner mesa
#

@fierce hornet not for me

#

what does the attribute look like in your failing test case?

fierce hornet
#
  - media_player.beam
marsh thunder
#

thanks rob, i'll try over there

inner mesa
#

this returns nothing for me, while the previous one returns true:

#
{% set attr = ['media_player.beam'] %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%endif%}
#

you could put an {%else}false in there if you want "false"

fierce hornet
#

Maybe we are not on the same page. I want it to display true when the sonos_group attr contains the beam & one entity and false when it only contains the beam entity

inner mesa
#

so just add {%else}false in there

fierce hornet
#

I'll try that

inner mesa
#
{% set attr = ['media_player.beam'] %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%else%}false{%endif%}
#

works for me

fierce hornet
#
{% set attr = ['media_player.beam'] %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%else%}false{%endif%}

This doesn't do it for me

#

But

#
{% set attr = state_attr('media_player.beam', 'sonos_group') %}
{% if 'media_player.beam' in attr and 'media_player.one' in attr %}true{%else%}false{%endif%}

this does

inner mesa
#

you're saying that adding a random newline breaks it?

#

probably

fierce hornet
#

No idea

#

But that last template works

inner mesa
#

don't do that

#

that's what I pasted above 🙂

#

you added a random newline 🙂

fierce hornet
#

But when using your template it always displays false

inner mesa
#

you're right, it will. it was a test case to return false

#

I see the diff now. I was explicitly testing for both when only one was present to test false because you said that your test always returned true

#

anyway, you have a solution now?

fierce hornet
#

Yea seems like it

#

Not sure how it works haha but it does the job

inner mesa
#

that's what I was afraid of

#

think through it and it'll help you in the future

#

['xxxx', 'yyy', 'zzz'] is an array in Python/Jinja and 'xxx' in array just tests whether 'xxx' is one of the elements in the array

#

make sense?

fierce hornet
#

It does yea

#

Thanks for your help!

inner mesa
#

np

fierce hornet
#

It fully works now! A switch that disables / enables the speakergroup of those 2 sonos speakers 🙂 with correct state!

inner mesa
#

and you learned about arrays and some conditional syntax. all in all, a productive day

fierce hornet
#

Never had such a productive day before

thorny snow
#

@marsh thunder
were already in the bed. thing ist that you cant mix up esphome syntax and home assistant syntax.
they work togeter but are effectly complete diffrent things.
The way I shown you would take the output from your sensor in home assistant and do the maths, but you could defenitly do all this in esphome itself.

marsh thunder
#

@thorny snow Yeh I think that’s where I went wrong. I was trying to use home assistant template sensor in esphome config.
I’ve got it working for now, using HA templates. I’ll work our the esphome side later, computer is playing up after I installed some drivers whoops.
Cheers for all your help

thorny snow
#

np, lurking around here to offer and get help 😛

oak mason
#

Good day, a question from a simple person. I would like to check whether there has been a power cut to a Raspberry Pi in my cellar. The RPi measures electricity consumption and feeds the data via MQTT to my HA controller. So the set up I have come up with is that every 5 seconds the RPi sends a timestamp via MQTT. And I have created a sensor on the HA controller that records the RPi timestamp, and a template sensor that compares the HA controller timestamp with the RPi timestamp. If there is a difference of more then 10 seconds the output is "false" (and if there is not the output is "true"). To trigger the template I have used sensor.time. However this has not worked in spite of the template showing the correct output when I run it on the Developer Tools/Template page. I now realise that sensor.time triggers once every minute so it will not pick up a power cut until a minute has passed. While this is not a deal breaker, I would like to know within a few seconds. So my question is: Is there a way of triggering the sensor template more frequently than 1 minute? TIA.

#

Actually even if I leave the RPi off for more than a minute the template sensor continues to result in "true". Which is odd. Here is the template:
check_cellarpi_running:
friendly_name: "Cellar power check"
entity_id:
- sensor.time # required to update now()
- sensor.cellar_pi_timestamp
value_template: >-
{% set t = now().timestamp() *1000 %}
{% set c = states('sensor.cellar_pi_timestamp') |float %}
{{ (t-c) < 10000 }}

lyric sun
#
        value_template: >-
          {% if state_attr("sensor.smarter_kettle_status", "sensors")["base"] == "On" -%}
          on
          {%- else -%}
          off
          {%- endif %}
#

can anybody se an error here

#

working in dev tools but always of as a template sensor

oak mason
#

@lyric sun I'm sorry Icould you tell me

#

@lyric sun I'm sorry I'm too far down the food chain to answer your question (unless it is something to do with needing sensor.time to trigger your calculation). But please could you tell me how you put in the red line showing the new thread? Thank you.

lyric sun
#

thats there automatically if somebody posts while you don't look at the chat window

oak mason
#

OK thank you.

brave root
#

I'm trying to get a list of entities that have a certain attribute 'node_id'... I am trying this:

{{ states.light|map(attribute="node_id")|list }}

but I just get a list of 'undefined' entries

ivory delta
#

Are you sure they all have that attribute? I get the same problem with your example but it works if I use the attribute entity_id.

brave root
#

no, they do not all have that attribute

#

that's what i am trying to do: build a list of entities that do have that attribute

#

I found a for loop that will do it, but I'm struggling with how to build a list in a template... it seems .append() is not allowed

#
{% set my_list=[] %}
{% for state in states %}
  {% if state_attr(state.entity_id,'node_id') != None %}
    {{ my_list.append(state) }}
  {% endif %}
{% endfor %}
dreamy sinew
#

Yeah, that's a pain point

#

What do you intend to do with the list?

brave root
#

make it an input_select

dreamy sinew
#

Look at |rejectattr() in the jinja docs

lyric sun
#
        value_template: >-
          {% if state_attr("sensor.smarter_kettle_status", "sensors")["base"] == "On" -%}
          on
          {%- else -%}
          off
          {%- endif %}
silent barnBOT
dreamy sinew
#

Could shorten that to
'{{state_attr("sensor.smarter_kettle_status", "sensors")["base"] == "On"}}'

brave root
#

@dreamy sinew I think the issue is that state attributes are not considered attributes in the jinja sense

dreamy sinew
#

Just have to drill down more

#

states.entity_id.attributes.node_id

ivory delta
#

Those ones aren't state attributes though, right? So it's right that they're not accessible in the same way.

#

It's like the last_changed stuff.

dreamy sinew
#

Hmm

#

Not something I've attempted

#

But it's best to try to use select/selectattr/reject/rejectattr rather than do it yourself

lyric sun
#

Could shorten that to
'{{state_attr("sensor.smarter_kettle_status", "sensors")["base"] == "On"}}'
@dreamy sinew thanks, sure, that should work

dreamy sinew
#

There is a way but it's a bit obnoxious

#

@lyric sun when your desired output is a bool, no need to overcomplicate with an if block

lyric sun
#

I just found it wired that binary sensor seems to need true/false although documentation says "The state of a Template Binary Sensor can only be on or off" however I just read the template part and it says "The sensor is on if the template evaluates as True and off otherwise."

dreamy sinew
#

It's a boolean. Why overcomplicate it?

#

Plus different classes can show other values in the UI for it's state

#

Open/closed etc

ivory delta
#

Binary is always just boolean. Let HA figure out how to display it.

lyric sun
#

sure just changed it

#

a bit wired is that in the automations you then need to use off/on instead of true/false

#

Binary is always just boolean. Let HA figure out how to display it.
@ivory delta sure, i didn't want to change the display that way I just wanted to change the value, which I now know needs to evaluate to true/false instead of on/off

brave root
#

I'm not sure it can be done: {{ states.light | selectattr('friendly_name') | list }}

#

for example, does not work

#

they all have that for sure

dreamy sinew
#

You need a test

#

Or a list comprehension

#

{{ [x.friendly_name for x in states.light] }}

brave root
#

I also found this works: {{ states | selectattr('attributes.node_id') }}

kindred trench
#

hey guys whats a proper way to debug and troubleshoot homeass? Im trying to get entity_picture_template to work but it doesnt.. And i'm not sure what the issue is

#

I have a sensor.al and im trying to update the entity_picture depending on the value. I have found a couple of threads and examples and i try to follow them. I've check the templating engine that it does return the /local/img/image.png and that it is accessible from a browser... But still the god damn image doesnt change

inner mesa
#

/local is cached

agile bobcat
#

I've got the following thing for my action.

data:
  clickAction: https://myhome{state_attr('camera.mycamera','entity_picture')}}
message: https://myhome{state_attr('camera.mycamera','entity_picture')}}

Problem is: in the message field, template is executed just, but it is not in clickAction (I've got state_attr literally)... I'm very confused

dreamy sinew
#

Rule 1 of templating

silent barnBOT
dreamy sinew
#

Also missing a { on both

agile bobcat
#

(sorry bad cc)

#

i see

#

so... it is mandatory to use the file editor instead of the automation page when doing so?

dreamy sinew
#

Hmm, I don't remember as I don't use the ui

#

Or HA automation either for that matter

timid osprey
#

under the kebab/hamburger, you can edit things as yaml in the automation page

agile bobcat
#

that's very useful, thanks

slim sage
#
        friendly_name: 'Edith On Time'
        value_template: '{{ (as_timestamp(states.sun.sun.attributes.next_setting) + (states("input_number.edith_sunset_offset") | int)  * 60)  | timestamp_custom("%I:%M %p", True) }}'
        hour: ?
        minute: ?
      edith_off_time:
        friendly_name: 'Edith Off Time'
        value_template: "{{ (state_attr('input_datetime.edith_off_time', 'timestamp') | int | timestamp_custom('%I:%M %p', False)) }}"
        hour: ?
        minute: ?```
Can anyone help me figure out how to format the hour and minutes for both of those sensors?
timid osprey
slim sage
#

Oh, that is helpful thank you

slim sage
#

Is there a way in a template to set a state that doesn't exist? I have that "edith_on_time" and off_time and I want to set a state "hour" and "minute" for each of them. I believe I understand the formatting now (thanks BUSheeZy!)

mellow swift
#

I'm a beginner with HA, not sure what's the right place to ask. I want to make a card that lets me specify a wakeup time and duration, and an 'enabled' switch then send those commands to my tasmota light

slate tundra
#

how do i template an event trigger

#

as an example:

#
  - platform: event
    event_type: zha_event
    event_data:
      unique_id: "00:17:88:01:04:e4:db:43:2:0xfc00"
      command: "down_hold"
#

this

#

in relation to this:

#
  action:
    - choose:
        # IF motion detected
        - conditions:
            - condition: template
              value_template: "{{ trigger.to_???.???? == 'down_hold' }}"
          sequence:
            - service: light.turn_on
              entity_id: light.ikea_tradfri_balcony
              data:
                brightness: 225
                color_temp: 250
#

nvm i found what i needed

green wasp
#

im just not sure where its expecting a decimal. if i try the data values in developers tools for the service it works fine, so i know its not the service that wants a decimal value

#

the turn off functionality works fine

mighty ledge
#

You'll need to convert the hex to an int

green wasp
#

hmm, definitely something something the logic there as if i try to just pass the static code, its fine

#

@mighty ledge why?

mighty ledge
#

well, it's expecting an int and you're feeding it a string

green wasp
#

what is expecting an integer? not the service

mighty ledge
#

Yes the service is

#

that's what the error is saying

#

expected int for dictionary value @ data['code']

green wasp
#

then why would the office_fan_off script work perfectly or simply taking out the if statement and putting 'code: 0xE4EB82' work?

mighty ledge
#

because yaml converts it silently

#

it does not with templates

green wasp
#

ok, so something like {{ '0xADAF07' | int(0,16) }}

#

yep, that was it. thanks!

mighty ledge
#

np

mighty hawk
#

Does anyone have any good examples/cookbook/tutorials on how to use templates in automations? I've been trying to figure out how to activate a switch based on a sensor and just can't quote get there.

scenic solstice
#

i have good luck googling for what im trying to do and reading the docs

dreamy sinew
#

forums can be a good place to look too

mighty hawk
#

Thanks. Yeah, googling helps. Just thought I'd ask if anyone had some good examples that are proven work, don't have tons of threads going back and forth, and possibly were tutorials or had lots of cases covered.

dreamy sinew
#

templates are just Jinja so there's nothing too specific there. First identify what you want to do, then see how you can do it in HA with templates

silent barnBOT
mighty hawk
#

@dreamy sinew That is exactly what I was looking for. Thank you!

scenic solstice
#

the docs get me pretty close unless i want to do something a little maybe out of the norm.

#

like right now i want to track how much time my hvac is on cooling, heating, or fan. i can easily do one of them, and i can do each individually with separate template/history sensors, but id love to find a way to combine it all with template

dreamy sinew
#

a 4th sensor adding them together?

scenic solstice
#

if the history sensor could be templated for the state it cares about, or give it multiple states to track. but then it would need attributes or something to track each state's time

#

it was a fleeting thought i had while mowing last night 🙂

thorny snow
#

How convert all word in French please , it’s for my dad

#

??

mighty ledge
#

@thorny snow under his profile change the language to French.

#

@mighty hawk sounds like you want an automation, not a template.

quiet current
#

Hi, not sure if this is the correct place. I have added a snmp sensor for uptime for my pfsense. Its coming in 1/100 seconds. But I want to show it as days, hours, minutes. I was able to get into minutes from this: '{{((value | int) / 6000) | int}}'

ivory delta
quiet current
#

Wil datetime work? Uptime is showed like this 340994900, what means 39 Days 11 Hours 13 Minutes 15 Seconds

#

I do not have any date

mighty ledge
#

@quiet current this is what I used to use:

      {%- set time = value | int // 100 %}
      {%- set minutes = ((time % 3600) // 60) %}
      {%- set minutes = '{}min'.format(minutes) if minutes > 0 else '' %}
      {%- set hours = ((time % 86400) // 3600) %}
      {%- set hours = '{}hr '.format(hours) if hours > 0 else '' %}
      {%- set days = (time // 86400) %}
      {%- set days = '{}d '.format(days) if days > 0 else '' %}
      {{ 'Less than 1 min' if time < 60 else days + hours + minutes }}
#

will have format 39d 11h 13m and omit seconds

#

I now use

  - platform: snmp
    host: !secret unifi_closet_ac_lite
    name: Hall Closet AC Lite Uptime
    baseoid: 1.3.6.1.2.1.1.3.0
    value_template: >
      {{ (now().timestamp() - (value | int / 100)) | timestamp_custom('%Y-%m-%dT%H:%M:%S.%f+00:00', False) }}
#

this will display in the UI as a 'relative' time. So it will only work on entity or entities cards

#

and your result will be 5 weeks ago instead of the exact timing

quiet current
#

Ok, thanks, will give it a try. Still trying to get it to work

mighty ledge
#

both templates work out of the box

#

just copy and paste template into your value temlate section and it will work.

quiet current
#

Boom. Worked perfect. thanks 😄

mighty ledge
#

np, which one did you use?

quiet current
#

Used the first one

#

Quite new to this code thing, but getting my HA like I want step by step. Even if it feels like baby steps sometime 😛

slate osprey
#

I'm a template beginner, need help! I currently have this code: https://paste.ubuntu.com/p/NWW2Y8h6tF/ but i want to modify it to start my lights at full brightness. Where do I add the attribute for brightness?

daring musk
#

`
action:

  • service_template: "{% if is_state('group.bedroom_lights','off') %}light.turn_on{% else %}light.turn_off{% endif %}"
    data:
    entity_id: group.bedroom_lights
    brightness: 105
    mode: single
    `
#

you can change something like this

#

@slate osprey

slate osprey
#

Thank you!

#

It didn't work for me. Config is valid but the automation doesn't do anything.

daring musk
#

@slate osprey remove the space before light.turn_on

slate osprey
#

Oh gotcha

#

Still doesn't work for me

hollow bramble
#

check the HA logs, it will tell you why

slate osprey
hollow bramble
#

extra keys not allowed @ data['brightness']

#

you can't add brightness to a light.turn_off service call

daring musk
#

you can combine service_template with data_template

#

to make it more complex 😄

hollow bramble
#
action:
  - service: light.turn_on
    data_template:
      entity_id: group.bedroom_lights
      brightness: "{{105 if is_state('group.bedroom_lights','off') else 0}}"

this should accomplish what you need

slate osprey
#

Gee what a crash course in templating haha

#

Maybe I bit off more than I can chew

#

Thanks Villhelm I'll try that!

#

It worked! I'm so proud of myself haha!

#

Thank you so much

spiral imp
#

I have this switch.bhyve_standard_program with this as an attribute start_times: 06:00. The template editor returns the value as ['06:00'] for {{ states.switch.bhyve_standard_program.attributes.start_times }}

mighty hawk
#

@mighty ledge last time I used an automation without a template, I remember getting an error in HA about something related to not having all the cases covered. Let me test this real quick and see what I get.

next coyote
#

What's my_pypi_package?

chrome temple
#

@hollow bramble I don't think you can use the light.turn_on service with a group entity. In fact, I'm sure I just saw someone else saying that in a recent post somewhere. Anyway, I think that would work if the service was changed to homeassistant.turn_on.

#

But, honestly, I haven't tried it myself, so I don't really know.

hollow bramble
#

🤷 apparently it worked, but I don't know either. I was just working with what they had. If it still didn't work I would have suggested a light group

mighty ledge
#

@mighty hawk that doesn't make sense

#

not sure what 'cases' wouldn't be covered. My guess is you were missing a key.

next coyote
#

What's my_pypi_package?
@next coyote Anyone?

#

I'm having trouble setting up an integration

dreamy pivot
next coyote
#

No replies there unfortunately

mighty ledge
#

@next coyote what's it in reference to

next coyote
#

Unable to import component: No module named 'my_pypi_package'

mighty ledge
#

that could be hundreds of different things

next coyote
#

I used scaffold to build up the structure

mighty ledge
#

that's a lazy programmer. They didn't change the name of the package they created

#

so, it literally could be anything

mighty ledge
#

that's a template

#

you're supposed to use your code

#

object oriented language, that'd be you making a subclass from that specified class. Which will change depending on what you want to use. What are you trying to do? You should be asking these in the dev channel, but it seems like this might be a bit over your head?

spiral imp
#

How can I round a properly formatted time to the nearest hour?

mighty ledge
#

that's a loaded question. We'd need to know the input format

next coyote
#

object oriented language, that'd be you making a subclass from that specified class. Which will change depending on what you want to use. What are you trying to do? You should be asking these in the dev channel, but it seems like this might be a bit over your head?
@mighty ledge So sorry for that. I was new here and thought that all the channels are for devs.

ivory delta
#

Most channels here are for support, regardless of your background or programming knowledge. The ones that start with dev_ are for questions about the code itself - whether it's because you want to contribute or just because you're curious about how things work.

#

There's no need to apologise for posting in the wrong place. Now you know where to go for better help 🙂

next coyote
#

There's no need to apologise for posting in the wrong place. Now you know where to go for better help 🙂
@ivory delta Thanks for the support 🙂

silent barnBOT
keen crater
#

I have an issue with an icon_template which doesn't work. I set up the if elif else but it doesn't show the correct icon. Search the forum and adjusted to the examples but it still doesn't work.
https://paste.ubuntu.com/p/DZ6h4wKXQS/

#

what i want to do is check how many persons are at home and adjust the icon to the number

radiant aspen
#

I don’t think you can access entity states by just specifying the entity ID. I think what your looking for is something like states(‘sensor.personen_thuis’) | int > 2

keen crater
#

I don’t think you can access entity states by just specifying the entity ID. I think what your looking for is something like states(‘sensor.personen_thuis’) | int > 2
@radiant aspen that works! I thought it could done it both ways 🥴

#

thanks!

spiral imp
#

I have this template that adds 4 days to the base sensor, how can I round the time to the nearest hour?
{{ (as_timestamp(states('sensor.bhyve_front_central_zone_history')) + (4*24*3600)) | timestamp_custom('%a at %-I:%M %p', True) }}

mighty ledge
#

@spiral imp it's painful

#
{% set t = as_timestamp(states('sensor.bhyve_front_central_zone_history')) %}
{% set dt = t % 3600 %}
{% set t = t - dt %}
{% set dt = (dt / 3600) | round(0) * 3600 %}
{{ (t + dt + 4*24*3600) | timestamp_custom('%a at %-I:%M %p', True) }}
spiral imp
#

haha, thanks. No wonder I couldn;t figure it out

spiral imp
#

I have a similar sensor that has an attribute frequency:. There seem to be sub-attributes. I am trying to extract the interval: attribute from the following.
{{ state_attr('switch.bhyve_standard_program', 'frequency') }} returns this:
{'type': 'interval', 'interval': 4, 'interval_start_time': '2020-07-27T12:00:00.000Z'}

hollow bramble
#

{{ state_attr('switch.bhyve_standard_program', 'frequency')['interval'] }} likely

spiral imp
#

bingo! Thanks. Learned something new. I hadn't dealt with "sub-attributes" before

compact charm
#

can sensor templates do pythony things like create a list and then index into that list dynamically?

#

i'm gonna guess no, but thought i would ask

mighty ledge
#

yes

#

but you have to use namespace. And you can't use appending, you have to add lists together

#
{% set ns = namespace(my_list=[]) %}
{% for i in range(5) %}
{% set ns.my_list = ns.my_list + [ i ] %}
{% endfor %}
compact charm
#

what about maps, which i just realized was my real question

mighty ledge
#

well... what are you trying to do

compact charm
#

eg

LOCK_NOTIFICATION = {
    "1": "Manual Lock",
    "2": "Manual Unlock",
    "5": "Keypad Lock",
    "6": "Keypad Unlock",
    "11": "Lock Jammed",
    "254": "Unknown Event",
}
#

then index into LOCK_NOTIFICATION with alarm_type

dreamy sinew
#
{%- set LOCK_NOTIFICATION = {
    "1": "Manual Lock",
    "2": "Manual Unlock",
    "5": "Keypad Lock",
    "6": "Keypad Unlock",
    "11": "Lock Jammed",
    "254": "Unknown Event",
} -%}
{{ LOCK_NOTIFICATION["1"] }}```
mighty ledge
#

yah that

compact charm
#

ooh, that looks very sexy. let me try that out. thanks!

mighty ledge
#

fyi, that's not dynamically creating

#

that's just a declaration

compact charm
#

the new ozw integration doesn't do the fancy string building for lock_status, so i'm trying to emulate it

#

i wasn't trying to dynamically create, i was trying to dynamically index into it 🙂

mighty ledge
#

gotcha

compact charm
#

yeah, i guess i wasn't clear

#

my question could be interpreted either way

mighty ledge
#

I thought you wanted to create and add to list items, which is outside the scope but you can get there with work arounds

dreamy sinew
#

you can also do fun stuff like this

                states('sensor.living_room_temperature')|float,
                states('sensor.office_temperature')|float,
                states('sensor.thermostat_temperature')|float
              ]
            %}
            {{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}```
compact charm
#

haha, impressive. i might just snip that and file it away 🙂

mighty ledge
#

@dreamy sinew you can skip the | floats in the sensor list and add {{ sensors | map('float') | sum ...

dreamy sinew
#

XD

compact charm
#

does this work?

{% set level = states('sensor.front_lock_alarm_level') | int %}
{%- set LOCK_NOTIFICATION = {
    "1": "Manual Lock",
    "2": "Manual Unlock",
    "5": "Keypad Lock",
    "6": "Keypad Unlock",
    "11": "Lock Jammed",
    "254": "Unknown Event",
} -%}
{{ LOCK_NOTIFICATION[{{level}}] }}
mighty ledge
#

nope, get rid of the internal {{ }}

#

they aren't needed

#

also, your keys are not ints

dreamy sinew
compact charm
#

aha, gotcha. thanks

mighty ledge
#

{% set level = states('sensor.front_lock_alarm_level') %}

#

remove the int in that line

compact charm
#

ok

mighty ledge
#

your other option would be to keep the int in that line but change all your dictionary keys to ints 1: "Manual Lock"

compact charm
#

ah, i see. just a type mismatch. i could go either way

dreamy sinew
#

id keep the strings

compact charm
#

yeah

dreamy sinew
#

also, to be safe you should do this instead

#

actually, even better .get(level, level)

#

that will translate it if it matches and output it as is if it doesn't

#

that'll cover Uav/Unk from the state and also if it returns some other number for some reason

compact charm
#

nice. thanks

#

there's still more to integrate, but it should follow the same pattern

echo dew
#

Hi all. I have a BME280 in each room. These calculates the temperature, humidity and pressure. I think the windchill in the room must be a best value to check the confort of this room. Any of you have the formula to check this inside a room? In Internet I only find the outdoor formula that counts the wind velocity.

honest mauve
#

Hello

#

how can I write in Jinja a for each of all my switches?

mighty ledge
#

@honest mauve We'll need more of an explanation. Also, what have you tried?

#

@echo dew use the outside formula with a wind velocity of zero.

thorny snow
#

@mighty ledge you are a funny guy. youre the master of templates and while I checked out your repo i can hardly find used templates (maybe I just not found them 😛 )

mighty ledge
#

Lol, i don't use them much 😉

#

There are a few files that have them, but for the most part, i've moved away from complex jinja. Most of my stuff is appdeamon

#

I do have 4 coronavirus templates that are complex.

#

look in sensor.yaml for most of it

#

Also, check the sensor.yaml history. It has things i've removed.

thorny snow
#

nice nice, but already seeing an issue when the responses are bigger then 255(?) letters
But been a time since I last used such a monster API
😄 Transition from Mercurial to Git

mighty ledge
#

Yeah, I still use Mercurial. But I've been transiting to Git with GitKracken

#

I used tortoiseHG for most of my previous work

dry matrix
#

Hi all...so I have a vacuum.xiaomi_vacuum_cleaner entity with a cleaned_area attribute (which is expressed in square meters).

I'd like to set up a value template to convert the cleaned_area to square feet (rounded to the nearest whole number). So far I know I need to multiply the cleaned_area value by 10.76391 to get the square feet, but I can't figure out the syntax to make that calculation and the rounding happen. Thanks for your help!

chrome temple
#

{{ (state_attr('vacuum.xiaomi_vacuum_cleaner', 'cleaned_area') * 10.76391)|round(0) }}

#

That will work if the attribute is a number. If it's a string representation of a number, then:
{{ (state_attr('vacuum.xiaomi_vacuum_cleaner', 'cleaned_area')|float * 10.76391)|round(0) }}

dry matrix
#

Thanks @chrome temple!

eternal basalt
#

been searching on and off for a couple weeks, reddit/forums/other since i got my zwave thermostat (GoControl) for hints on setting the fan mode, lovelace thermostat doesn't have the fan button, but the thermostat does allow control of it, and i can manually set it if use the lovelace edit screen, any suggestions what terms to search for or if there are any guides out there ?

chrome temple
#

Not sure what you mean by "i can manually set it if use the lovelace edit screen." Please go to the STATES tab of the Developer Tools page. Find the climate entity that corresponds to that thermostat. What do you see for its attributes? Specifically supported_features, fan_mode & fan_modes?

eternal basalt
#

by "manuall set it" i mean in the overview tab, config UI, when edit the default lovelace icon i can set the fan to on/off, sorry, can't paste screenshot here, in developer tools supported_features: 75 ```fan_modes:

  • Auto Low
  • On Low```
chrome temple
distant heart
#

Hi all, long story short - learned a big lesson... My SD card bit the dust the other day. Lost everything - backups included - Decided to come back with a Linux PC running HA and I'm glad. my issue is I had some ESP8266 with temp and motion sensors. They are back running but is there a way to read the installed config? I used ESPHome to initially set them up and I want to use that setup to make some new ones. They do not show up in ESPHome but do in HA for what they were set up to do

eternal basalt
#

hadn't downloaded backups anywhere?

chrome temple
#

@eternal basalt did you click on the three dots in the upper-right hand corner? For my Nest that brings up the "more info" window, and it has a drop-down for fan mode.

#

Mine also has a power icon. I have no idea what it does, and I'm afraid to click on it. There's no tool tip, and the doc page doesn't say either.

eternal basalt
#

ya, that brings up advanced options and that's where i can change the fan mode, was just looking to include it in the main card like the tutorial shows

#

the power button is the same as if you hit off on the thermostat, as in heat/cool/off

chrome temple
#

Ah, ok, I guess that makes sense. I wonder what the first icon means??? Must mean away mode or something.

#

BTW, you said "config UI, when edit the default lovelace icon." Just to be clear, I mean the three little dots in the thermostat card, not going off to some UI config page.

hasty escarp
#

Dear all, I have template sensor:
{{ (( as_timestamp(now()) - (states.input_datetime.nachalo.attributes.timestamp)) / 86400 ) | round(2) }}
the value is correct only after HA restarted, and the value is not updating at all, only after HA restart. What should be changed/updated ? It looks like as_timestamp(now()) returns the permanent value

silent barnBOT
serene merlin
#

Hi All
A question to gurus:
is there a way to pass on a 'calling' entity id into the the script? Like {trigger.entity.id} section example above?

ivory delta
#

A script isn't triggered, so not the way you've done it. If you're calling a script from an automation, the automation would have access to the trigger object and could pass it in as a parameter.

serene merlin
#

@ivory delta thank you. But how about a cover? I have a bunch of covers and I would love to avoid a need to create open/close/stop scripts for each of them. Is there a way to make the code neater?

#

I found trigger.entity_id could I use that like:
script: open_kitchen_blind1: sequence: - service: esphome.roller_blinds_controller_control_stepper data_template: target: "{{state_attr('trigger.entity_id', 'max') | int}}"

#

also, i'm struggling a bit with the trigger.to_state part where I need to do some math. I'm doing this:
data_template: target: '{{ ( trigger.to_state.state | int ) * ( state_attr('input_number.kitchen_blinds_extreme_positions', 'max') / 100 | int )}}'
but I get errors than 'colon' is missing after /100 part

ivory delta
#

You don't have access to the trigger object in a script...

#

And you need mixed quotes.

serene merlin
#

oh, i see.. that sucks 😦 thank you very much @ivory delta

ivory delta
#

It doesn't suck. A script can only do what it's told. You're expected to provide all the necessary information.

#

How do you call these scripts?

serene merlin
#

script.open_kitchen_blind1
script.close_kitchen_blind1
script.stop_kitchen_blind1
script.open_kitchen_blind2
...

#

@ivory delta where do I need mixed quotes? I'm sorry

#

i didn't mean to be annoying, sorry, coming here was my last resort after hours of research

ivory delta
#

You're not being annoying.

#

The mixed quotes thing is because you're starting your template with a ' and then using a ' within the template. When HA reads the template, it thinks the second ' is the end and everything after that is garbage.

#

If you're using ' inside your template, surround your template with " instead.

#

And I know what your entity names will look like. Where are you using those?
If it's from a button on the frontend, the button will need to tell it the entity - buttons aren't triggers.
If it's from an automation, there is a trigger and you can dynamically pass in an entity ID. But you still wouldn't have the logic for trigger.xxxxx in the script, that would move to the automation.

serene merlin
#

@ivory delta I think I got you confused somewhat, sorry. So scripts and the trigger.to_state part are 2 different things.

  1. I'm using scripts to control window blinds positions from template cover and since I have a few of those covers I was hoping I could avoid coding multiple scripts for each.
  2. I'm using 2 input_numbers: 1 to store min and max values for the position of the blind and the other one (a slider) to control their position. The position is controlled by automation that sends value of required position to esphome like so:
    `automation:
  • alias: Send Kitchen Blind 1 Position to ESP
    trigger:
    platform: state
    entity_id: input_number.kitchen_blind1_stepper_control
    action:
    • service: esphome.roller_blinds_controller_control_stepper
      data_template:
      target: {{ trigger.to_state.state | int}}`
      So since the since input_number.kitchen_blind1_stepper_control is set to values from 0% to 100% I need to convert the % value into actual steps by '{{ trigger.to_state.state | int * ( state_attr('input_number.kitchen_blinds_extreme_positions', 'max') / 100 | int )}}' and that's where I ran into 'trigger.to_state' syntax problems (i think)
#

problem also is that it looks like dev tools don't validate trigger.XX states/entities (or at least I couldn't make it work) so I'm in the dark

ivory delta
#

You can still test most of your template in devtools > Templates. Just replace the first part (trigger.to_state.state) with a reference to your input_number instead.

#

They mean the same thing. The information just gets plugged into your template from a different source.

serene merlin
#

right.. I thought of that but the difference was that in case of actual input_number value states platform will be used while I thought that trigger.XX is different

#

maybe mistakenly.. hence I ended up here 🙂

#

states('trigger.to_state') | int does the job but I wasn't sure at all it's the same thing

ivory delta
#

Well to be honest, you could probably use states('input_sensor.your_sensor_name') instead of using the trigger in your automation and it'd still work the same. I doubt there's even a difference in performance. It's just handy to use the trigger object so you can 'see' where it comes from.

serene merlin
#

From what I understand with latest update to Automations I can achieve the same thing for all covers with just 1 automation though?

ivory delta
#

You could probably do it with the old automations too 😄 But that's a question for #automations-archived

#

Once you're happy with your template, take it over there to finish the automation itself.

serene merlin
#

This whole process of reworking this was triggered by this automations update if i'm honest 😅

#

oh yeah? lol, okay 😃

#

@ivory delta I'm sorry, just to confirm. So would target: {{ trigger.to_state.state | int}} do the same thing as target: '{{ states('trigger.to_state') | int ?

ivory delta
#

I don't think that's valid, no. You can try it...

#

But like I said, if you're happy that your template works and converts from your percentage to an integer, the rest of your problem is for #automations-archived.

serene merlin
#

damn.. I mean this is so silly.. sigh.. i hate feeling dumb like that
dev tools validate this just now target: "{{ 'trigger.to_state' | int * (state_attr('input_number.kitchen_blinds_extreme_positions', 'max') / 100 | int )}}"
only '' were missing around trigger.to_state.. jeez

#

@ivory delta thank you so much for all your help and taking time to explain all this to me ❤️

rancid copper
#

Hi guys, i have this automation for my window https://paste.ubuntu.com/p/36MNXRP76m/ for a few days, when I close the window and the thermostat should activate in hot and not cold mode as it should if the boolean is on, could you help me understand what is wrong?

#

maybe a problem with the template?

ivory delta
#

You haven't told us what's wrong yet. What happens?

rancid copper
#

when i close the window and the boolean is on it should turn on the thermostat in cool mode

ivory delta
#

That's what should happen. What actually happens?

rancid copper
#

set the termostat in heat mode

ivory delta
#

Ok. And you posted 3 automations in that link. Which one is the problem?

rancid copper
ivory delta
#

Well first check your template at devtools > Templates. Does it return 'cool' or 'heat'?

rancid copper
#

yes i check and works

#

i also tried the service and it works

mighty ledge
#

your template is fine, seems like your automation chain is overly complicated. Also, nothing points to you 'closing the window' in any of those automations.

rancid copper
#

the window is a switch

mighty ledge
#

ok, is the window on when open or closed

rancid copper
#

switch on = window on

mighty ledge
#

it's odd that it's a switch and not a binary_sensor

rancid copper
#

i try the automation and works good

ivory delta
#

It's still odd 😄

#

Switches are things you control. Sensors are things that provide information.

rancid copper
#

yes, i make this choise because with binary_sensor when i restart HA don't have the retain function

#

and now i use a sensor 433 with espurna

mighty ledge
#

first thing I notice is that when the window is open you turn off the automation that does everything

rancid copper
#

yes

ivory delta
#

If you turn it off, it won't run again...

rancid copper
#

to prevent it from being activated if the thermostat is off

ivory delta
#

You normally shouldn't turn automations on/off. It's enough to use the triggers and conditions to decide if the actions should run.

mighty ledge
#

but that's what doesn't make sense, if you just open the window, you turn off the other automation. Making it's trigger 100% pointless and it will never fire.

#

your trigger in the other automation looks for the switch being on for 45 seconds, but you just turned that automation off.

#

it will never fire.

#

ever.

#

and that's what starts the 3rd automation.

#

so, you have flawed logic.

rancid copper
#

we had developed these automations with a channel moderator that I don't remember the name now, but until a few days ago everything worked perfectly.

mighty ledge
#

that doesn't mean the logic is correct.

ivory delta
#

Turning off automations = bad. If you can't ensure they're turned back on properly, you have problems like this.

rancid copper
#

i see

mighty ledge
#

you can turn them on/off all you want, you just have to understand when an automation is off, it's off. When you turn it off, it cancels currently executing actions.

rancid copper
#

so the first automation it is not necessary

mighty ledge
#

All you want to do is turn on cool when you shut the window? And you only want to run it once if it's set to heat?

rancid copper
#

the automation is designed to turn off the air conditioner if the window is open, if the last mode is cold, when you close the window you must turn the thermostat back on and set it to cold, otherwise hot. If the thermostat is off, no automation must be activated.

#

since the thermostat does not remember if it was hot or cold or rather it always sets it hot, I had implemented a bolean to remedy this problem.

#

as I said everything worked perfectly, after updating to the latest version I had this problem

mighty ledge
#

Yes because actions cancel now

rancid copper
#

i see

#

how could I solve this problem?

mighty ledge
#

Add a condition to the automations checking the state of the thermostat.

#

or input boolean if that's what stores the on/off

rancid copper
#

i have this is action

#

and in condition when the window is open

#

but it seems that the automation does not put in the proper state, it only turns on the thermostat in heating mode

#

even if the bolean is on to remember the cooling state

mighty ledge
#

you'll probably have to rewrite your automations with your goal in mind, and with the intention of the automation being active at all times

rancid copper
#

Can you help me on this? 😊

mighty ledge
#

Nope, you gotta learn on your own. It seems like someone already fed you the answer and you're unable to debug it. You should learn how to do this yourself so you can fix it.

rancid copper
#

Ok thanks

keen crater
#

Does anybody know how to get the delay_time from the alarm_control_panel to use in an automation? I have this now states(alarm_control_panel.armed_away.delay_time) but the template editor says alarm_control_panel is undefined. If i look at the states it's clearly there tho.🤷‍♂️

rancid copper
#

so...I just had to move the sequence of actions, because it turned off automation before it did the important things.

#

now all works good

#

evidently in the previous version it didn't matter

mighty ledge
#

Yes that’s new in this version. When you turn off an automation it cancels the actions currently running

#

Does anybody know how to get the delay_time from the alarm_control_panel to use in an automation? I have this now states(alarm_control_panel.armed_away.delay_time) but the template editor says alarm_control_panel is undefined. If i look at the states it's clearly there tho.🤷‍♂️
@keen crater is delay_time in the attributes?

ivory delta
#

You need quotes around entity names inside states()

keen crater
#

Like so: message: "Alarm active in {{ states('alarm_control_panel.armed_away.delay_time') }} Seconds"

#

still doesnt work 😦

#

also tried it like this: 'Alarm active in {{ states("alarm_control_panel.armed_away.delay_time") }} Seconds'

ivory delta
#

Use state_attr() to extract the value of a state.

fierce void
#

How do I use MQTT topics to satisfy the actions in a cover template? I have an MQTT garage door that I can read and change the state with successfully from HA. I was trying to hierarchically add a platform:mqtt under the cover template in my yaml, but that seems to be the wrong way to go about it. Do I need to define the mqtt somewhere else and use reference that somehow in the cover template?

inner mesa
fierce void
#

I think that is exactly what i was looking for, thank you!

brisk temple
ivory delta
#

You have an array with one entry, a string.

#

The value inside the double quotes isn't an object/dictionary.

#

Unless I'm being dense. It's been known to happen.

#

Yeah... this template complains that 'str object' has no attribute 'get':
{{ test[0].get('datetime') }}

#

Whatever you're doing to generate test is definitely making an array of strings, @brisk temple

brisk temple
#

ok thanks, i'll work on it

chrome temple
#

Why |map('lower')? That's definitely converting the dictionary into a string.

brisk temple
#

map attribute didn't give me all the line i wanted

mighty ledge
#

you'd want to use | map(attribute='datetime') or not use map at all.

#

not using map at all would result in {{ test[0].datetime }} working

#
{% set test = (state_attr('weather.openweathermap', 'forecast') | selectattr('datetime', '>=', start) | selectattr('datetime','<=', end) | list)%}
{{ test[0] }}
{{ test[0].datetime }}
brisk temple
#

yup it was that map

#

thanks!

opaque orchid
#

hey i'm having an issue with using a template in an automation for the first time and I am wondering if someone can point me in the correct direction. what have I done wrong here?

...
action:
  - data:
      brightness_pct: >
        {% if (now().hour) > 20 %} 70
        {% elif (now().hour) < 7 %} 50
        {% else %} 100
        {% endif %}
      color_name: >
        {% if (now().hour) > 20 %}'slategray'
        {% elif (now().hour) < 6 %}'coral'
        {% else %}'palegoldenrod'
        {% endif %}
      entity_id: light.2nd_floor_2
    service: light.turn_on
dreamy sinew
#

Rule 1 of templating

#

.templates

#

Damn bot is dead again

opaque orchid
#

well dang

#

sorry, and thank you.

dreamy sinew
#

Np, easy fix

opaque orchid
#

figured it was going to be a "we get this question a lot" situation

dreamy sinew
#

Haha there's a handy bot command usually

silent barnBOT
dreamy sinew
#

Helps if I use the right one

lapis quarry
#

Hey guys, im trying to figure out how to get a template to output the time a entity has been in a certain state

#

specificaly:

 {{ states('device_tracker.xxx') }} 

Would like to get the output in minutes or hours this entity has been home

#

any tips?

ivory delta
#

And from there, you just need to use some strftime magic to get it looking how you want.

mighty ledge
#

@lapis quarry you can't with just a template

lapis quarry
#
{{ states.device_tracker.keyring06a.state }} for {{ (as_timestamp(now()) - as_timestamp(states.device_tracker.keyring06a.last_changed) ) | round(0) }} 
mighty ledge
#

unless you are specifically looking for the last state only.

#

Then you can.

#

But if you are looking for the 'total time on today', you'll need to use the history stats integration

lapis quarry
#

since last change is fine

mighty ledge
#

Ok, then the first order of business is to integrate sensor.time, date_time integration.

lapis quarry
#

now just strugling to convert it to minutes as outpuit is in seconds 😅

mighty ledge
#

without it, your sensor will not update properly.

lapis quarry
#

have sensor time allredy

mighty ledge
#

ok, what format are you expecting after for?

#

Also, where are you placing this in the UI or is it for a message

lapis quarry
#

its for a message

#
{{ states.device_tracker.keyring06a.state }} for {{ ((as_timestamp(now()) - as_timestamp(states.device_tracker.keyring06a.last_changed) ) /60)| round(0) }} this is working
#

its for a notification

mighty ledge
#

yeah that would be seconds

lapis quarry
#

ok think I got it working now

#

🙂

lapis quarry
#

this is what i have ended up with:

            - service: notify.notifier_name
              data_template:
                title: >
                  {{ states('input_text.house_number') }} 
                message: >
                  No Keyring or Phone Detected in Room 07 for 
                  {% if (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed)) | round(0) < 60 %} 
                    {{ (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed)) | round(0) }} seconds 
                  {% elif (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed)) | round(0) < 3600 %}
                    {{ ((as_timestamp(now()) - as_timestamp(states.group.room07.last_changed) ) /60)| round(0) }} minutes
                  {% elif (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed)) | round(0) > 3600 %}
                    {{ ((as_timestamp(now()) - as_timestamp(states.group.room07.last_changed) ) /3600)| round(0) }} hours 
                  {% endif %}
mighty ledge
#

why not just use the last_changed secondary info?

#

or device_class: timestamp for a sensor

lapis quarry
#

because I barelly know what im doing 😅

#

took me 3 or 4 hrs to figure this out

#

😩

#

im sure they are better ways but at least it seems to work

mighty ledge
#

No, you did it the right way, I keep thinking you want this as a sensor. Not in a message.

dreamy sinew
#
{% if ts_delta < 60 %} 
{{ ts_delta }} seconds 
{% elif ts_delta < 3600 %}
{{ (ts_delta /60)| round(0) }} minutes
{% elif ts_delta > 3600 %}
{{ (ts_delta /3600)| round(0) }} hours 
{% endif %}```
#

change your entity back and you're good

mighty ledge
#

Lol, I was just typing that up but got side tracked by work

dreamy sinew
#

lol

lapis quarry
#
{% if ts_delta < 60 %} 
{{ ts_delta }} seconds 
{% elif ts_delta < 3600 %}
{{ (ts_delta /60)| round(0) }} minutes
{% elif ts_delta > 3600 %}
{{ (ts_delta /3600)| round(0) }} hours 
{% endif %}```
@dreamy sinew 👍
dreamy sinew
#

just makes it a bit cleaner

#

saves a dash of processing too

lapis quarry
#

this is local right? meaning it is only used inside that particular template

#

?

dreamy sinew
#

yes

lapis quarry
#

ok cool

dreamy sinew
#

if you want it to be accessible elsewhere you need to make a sensor like petro suggested

lapis quarry
#

no need, just wanted to confirm I can use the same name in diferent templates

dreamy sinew
#

ah gotcha

#

then yes, totally safe

lapis quarry
#

👍

merry flame
#

apologies for the wrong channel, i can never seem to get it quite right

#

APIs are fun. Anyone know how to parse out specific words from grabbing JSON - eg, parsing out "Round Up" and then moving on to grab the next option in the array?

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

x-post for prosperity

#

I've tried some IF statements but they never seem to take

dreamy sinew
#

so you're wanting the roundUp property for each?

merry flame
#

Not quite - I want to not parse anything with the description of Round Up "description": "Round Up",, and instead move on to other transactions

dreamy sinew
#

what do you want the final output to be?

merry flame
#

ignore the one with Round Up and move on to the following transaction

#

I... don't think it's quite possible because I've hardlinked the array numbers with [0] etc

dreamy sinew
#

are there n number of transactions at any given moment?

merry flame
#

no, but I can make that happen

#

integer

The number of records to return in each page.
e.g. ?page[size]=30```
#

just need to add that to my query

#

i have now limited it to 5 transactions on a query (which honestly makes more sense as I only have 5 transactions being required)

dreamy sinew
#
[x['attributes']['amount']['value'] for x in d['data'] if not x['attributes']['roundUp']]

['0.10', '0.31']
merry flame
#

oh boy

dreamy sinew
#

but that would only give you things you can use in one sensor

merry flame
#

unfortunately it also wouldn't work because the Round Up value changes depending on purchases

#

aka it could be any value from 0.01 to 0.99

dreamy sinew
#

this drops out anything that has the roundUp dict populated

merry flame
#

where should this go? sorry

dreamy sinew
#

eh, you can only get a sum

#

it really depends on what you want the ultimate output to be

#

do you want multiple sensors here?

#

or do you want a total?

merry flame
#

Yeah, I currently have 5x most recent transactions

dreamy sinew
#

ok and what do you want the value of that sensor to be?

#

amount unless roundup is populated?

merry flame
#

I'm showing each transaction as a sensor, so the value_template corresponds to the amount spent and the friendly_name_template is the description of the transaction

#

so if description = "Round Up", move on to the next transaction

#

i understand that this is like jamming a square in a round hole, so I understand if I should bugger off and figure it out myself/make a custom integration

dreamy sinew
#

oh i get it

merry flame
#

I can attach a photo if that will make more sense with what I currently have going on

#

my if statement inside of the templates created 'Round Up', instead of ignoring it and moving on

dreamy sinew
#

ok, here's this

#
{{parsed}}```
#

replace rest['data'] with states.sensor.up_transactions.attributes["data"]

#

add that to the top of each template and all the roundups will be dropped

#

proceed as you have with your indexing

merry flame
#

above friendly_name_template?

dreamy sinew
#

parsed[0]
parsed[1]

#

etc

merry flame
#

lemme give it a whack ty

#

where should this belong? replace anything? above the friendly?

#

oh i get it, im dumb

dreamy sinew
#

that one

merry flame
#

omg

#

you absolute legend

#

i could kiss you, ive spent a couple days on and off trying to sort this and it keeps going to the back of the queue

#

buy you a beer or anything like that mate?

dreamy sinew
#

there might be something you could do on the rest sensor to pre-reject but i'm less handy there

#

all good man, just pass it forward

merry flame
#

unfortunately its not my rest api - it's direct from my bank

#

I can definitely raise an issue on their github though

dreamy sinew
#

i mean in the rest sensor

#

it supports some templating

merry flame
#

oh boy, here we go deeper

dreamy sinew
#

i just haven't touched it much

merry flame
#

HA is very similar to a hydra

#

you think it's good and you're fine to leave it alone but then you think "ah wait, that could be done cleaner"

dreamy sinew
#

ehh looks like you can't there unfortunately. you can template the value but not the json attribs

merry flame
#

it's all good - it worked somewhat but you've basically given me the keys and I can nut the rest out

dreamy sinew
#

that's about as clean as i can get it for now

merry flame
#

nah it's all good! I never even found anything about set parsed in my searches so that's opened pandoras box for me

dreamy sinew
#

only way to make it cleaner would be to add another template sensor in the middle to do the parsing but that might get ugly within HA

#

since you still need the list

merry flame
#

realistically, i should do an integration at this point

dreamy sinew
#

could be a good project if you're handy with python

merry flame
#

somewhat - jack of all trades, master of none and all that

mighty ledge
#

making an integration that does that would be super easy.

dreamy sinew
#

its a bit of a lift to get started but you have a lot more control

merry flame
#

well, it is the weekend now, so i mean, there's nothing really stopping me :p

mighty ledge
#

just modify whatever's currently creating the sensor you're getting now

#

make it a custom integration and you're good to go, just give it a new name

merry flame
#

rad, i'll have to take a geeze. appreciate the help phnx!

#

thanks petro :)

#

oh my god, im dumb. it DOES work perfectly - I just didnt realise Uber took a double payment today

#

🤦‍♂️

silent barnBOT
lapis quarry
#

a wall of code lol

#
            - service: notify.notifier_name
              data_template:
                title: >
                  xxx
                message: >
                  No Keyring or Phone Detected in Room 07 for 
                  {% set ts_delta = (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed))|round %}
                  {% if ts_delta < 60 %} 
                    {{ ts_delta }} seconds 
                  {% elif ts_delta < 3600 %}
                    {{ (ts_delta /60)| round(0) }} minutes
                  {% elif ts_delta > 3600 %}
                    {{ (ts_delta /3600)| round(1) }} hours 
                  {% endif %}
#

Outputs this:

No Keyring or Phone Detected in Room 07 for

                27 minutes

Could you tell me what I need to do to join all the message so there is no spacing and the output is all 1 line?

#

do i need to write it all in one line? makes it dificult to read:

#
No Keyring or Phone Detected in Room 07 for{% set ts_delta = (as_timestamp(now()) - as_timestamp(states.group.room07.last_changed))|round %}{% if ts_delta < 60 %} {{ ts_delta }} seconds {% elif ts_delta < 3600 %} {{ (ts_delta /60)| round(0) }} minutes {% elif ts_delta > 3600 %}{{ (ts_delta /3600)| round(1) }} hours {% endif %}
#

this way it works, i guess I can write a message any other way?

dreamy sinew
#
                    {{ (ts_delta /3600)| round(1) }} hours 
                  {% endif %}
                  {% if ts_delta < 60 %} 
                    {{ ts_delta }} seconds
                  {%endif%}
                  {% if ts_delta < 3600 %}
                    {{ (ts_delta /60)| round(0) }} minutes
                  {%endif%}```
#

if you want all 3

#

oooooh wait, i see

#

sec

#
                  {%- set ts_delta = (as_timestamp(now()) - as_timestamp(states.binary_sensor.living_room_occupancy.last_changed))|round %}
                  {%- if ts_delta < 60 -%} 
                    {{ " {}".format(ts_delta) }} seconds 
                  {%- elif ts_delta < 3600 -%}
                    {{ " {}".format((ts_delta /60)| round(0)) }} minutes
                  {%- elif ts_delta > 3600 -%}
                    {{ " {}".format((ts_delta /3600)| round(1)) }} hours 
                  {% endif %}```
#

try that

lapis quarry
#

Error rendering template: TemplateSyntaxError: unexpected '}', expected ')'

dreamy sinew
#

check your copy paste, this is working in the template tester

#

also make sure you swap your entity back

lapis quarry
#

ok yes sorry you are right

#

that works

#

awesome!

dreamy sinew
#

the - remove white space

#

needed to add the .format() statements to add the space you want back in

lapis quarry
#

i see

#

cool

#

thanks

merry flame
#

is there a way to have rejectattr('eq', 'example removed') read from a list at the top? rather than having multiple 'example removed's?

#

ive been trawling the Jinga documentation and cant find anything

daring musk
#

what's more pretty in ur opinion

{% for json in value_json.metrics if json.tags.model == "SAMSUNG HM321HI" %} {{json.fields.temp_c }} {% endfor %}

or

{{ (value_json.metrics|selectattr('tags.model', 'eq', 'SAMSUNG HM321HI')|first).fields.temp_c }}

ivory delta
#

The second one. Not only is it a single line, it reads in order too.

#

And I wouldn't call either 'pretty'. The second is more elegant.

merry flame
#

is there a way to put something like vars: list_of_dicts: into home assistant for a sensor to read?

ivory delta
#

What are you trying to achieve?

merry flame
ivory delta
#

What's the full config? That doesn't show the type of integration you're creating.

ivory delta
#

Okay. So you're trying to extract information from the REST sensor to make other sensors?

#

To answer your initial question, no, I don't think you can do that. You can only define things in YAML that are an integration or HA won't validate it.

merry flame
#

that's it, everything works great, im just trying to make the one line with rejectattr look a little cleaner and easier for other people to add exclusions

#

i thought so. i should make an integration, but it's terrifying so i'm trying as much as i can in a sensor.yaml first :p

ivory delta
#

I'll be honest, I'm not great with templates... others might be able to suggest a cleaner way but your current approach might be as good as it gets.

merry flame
#

that's all good! I appreciate the lookin' anyhow. Phnx seems to be the God of Templates

mighty ledge
#

@merry flame

{% set parsed = states.sensor.up_transactions.attributes["data"] | rejectattr('attributes.description', 'in',['Round Up', 'Interest', 'Cover from rent n bills', 'Cover to Spending']) | list %}
#

and technically, you can map each one.

#
{% set parsed = states.sensor.up_transactions.attributes["data"] | rejectattr('attributes.description', 'in',['Round Up', 'Interest', 'Cover from rent n bills', 'Cover to Spending']) | map(attribute='attributes.description') | list %}
#

then the result would be

{{ parsed[0] }}
#

but you'd have to make sure to map properly because some of the values you're trying to get would need | map(attribute='attributes.amount.value')

#

and, you'd probably want to add safety to the templates to avoid errors at startup:

friendly_name_template: >
  {% set parsed = state_attr('sensor.up_transactions', 'data') %}
  {% set filter = ['Round Up', 'Interest', 'Cover from rent n bills', 'Cover to Spending'] %}
  {% set parsed = parsed | rejectattr('attributes.description', 'in', filter) | list %}
  {% set descriptions = parsed | map(attribute='attributes.description') %}
  {{ descriptions[0] }}
value_template: >
  {% set parsed = state_attr('sensor.up_transactions', 'data') %}
  {% set filter = ['Round Up', 'Interest', 'Cover from rent n bills', 'Cover to Spending'] %}
  {% set parsed = parsed | rejectattr('attributes.description', 'in', filter) | list %}
  {% set values = parsed | map(attribute='attributes.amount.value') %}
  {{ values[0] }}
merry flame
#

sadly the last one doesn't work, first does though!

#

Any chance using something like I mentioned above is possible in sensors? list_of_dicts

#

actually, I may not need to if I can use beginning of phrases, such as "Cover from", "Cover to" etc

#

if i can use wildcards, that would be great

flat parrot
#

Hopefully correct area, but just wondering if anyone knows if you can you have multiple universal media players? I'm guessing I've messed up the config, but I have two configured, and only the second one seems to stick?

ivory delta
#

Templates are all that curly brace nonsense you can see up above.

flat parrot
#

Sorry, just figured because the config does have templates in it, might be relevant. will pop over there.. thanks!

ivory delta
#

If your problem is the templates within your config, someone here can help out. You'll want to check that your config in general is correct first though.

flat parrot
#

thanks. I've probably stuffed the YAML

hazy surge
#

I'm trying to setup a template binary sensor but I would like to have it on a "set/reset" behavior, is that possible ? I tried to use the state of the sensor itself in the value_template but that generates an error on restart.

#

The way it would work would be to use 2 automations to set the binary_sensor ON and OFF. I am hoping that a cleaner way to accomplish this exists.

#

Oh I found a mistake in my template, you can use the state of the sensor itself to accomplish a "set/reset" function as in "set_trigger or sensor_itself and not reset_trigger"

hard apex
#

Hi all, I'm experiencing a behavior I don't understand

#

if I put the "{{ states('binary_sensor.updater') or (states('sensor.custom_hacs_pending_updates') > 0) }}" in devtools ->Template it shows "on"

#

but creating a binary_sensor with the same code it shows "off"

ivory delta
#

.share the config of your sensor

silent barnBOT
hard apex
charred dagger
#

Your template evaluates to "on" when binary_sensor.updater is on.

#

and "off", otherwise.

#

Both of which is not True and thus sets the binary_sensor to off

#

You probably want {{ is_state('binary_sensor.updater', 'on') or (states(...) > 0) }}

hard apex
#

damn, I always forge that on != true

#

thx once more for your help

charred dagger
#

It's extra annoying because on IS True in yaml, but not in jinja.

hard apex
#

exactly

opaque orchid
#

is there a way that i can do this in an automation data template?
{{ (homeassistant.util.convert.color_temperature_to_hs(3000)) }}

inner mesa
#

no

opaque orchid
#

dang. ok

inner mesa
#

are you just trying to set a color for a light?

opaque orchid
#

nah but I'm (probably obviously) overcomplicating something, gonna fix that

#

thanks

wintry socket
#

Hi, I'm looking for how to create an alert using Node Red. In this case I have a Tesla PowerBall, if the power grid goes off, I would like it to turn on a red light bulb in my room, but when the power returns, the light bulb returns to its previous state. That state can be off or on with the color and brightness that have it before.

dreamy sinew
velvet glen
#

Quick help/scan of my sensors.yaml file? I'm 'trying' to tidy up by adding a secrets.yaml and pulling the sensors into a config.yaml. I've done this and syntax seems to pass, but my influxdb sensors have disappeared from frontend - so clearly something daft I'm doing. Would someone mind scanning this file and letting me know if there's something wrong here? https://paste.ubuntu.com/p/7v5NKkVrXp/

bronze horizon
#

Not completely sure this is the right place to ask, but I'm having trouble with a for loop in a template I'm trying to use inside a Lovelace markdown card. I have a bunch of sensors for my recent bank transactions, where the amount is the state and additional details like the time, description etc are state attributes. My goal is to loop through these sensors and print out the relevant attributes.

{% for transaction in expand('group.up_transactions') -%}
  {{ transaction.name }} is ${{transaction.state}} and
{% endfor %}

This template works fine for the name and state, however I can't figure out how to get the other attributes. I thought something like state_attr(transaction,"description") would work, but it breaks the template. {{ state_attr('sensor.up_transaction_1','description') }} displays the attribute as expected, though.

little gale
#

I need some help in creating a switch that, when switched on, sets the color and brightness of a lamp to something specific and when switched off reverts to the color/brightness set earlier and turns off the lamp

ivory delta
#

It sounds like you want a script for the 'on' action. The script would capture a scene, then set the new states. The 'off' action could then just restore that scene.

little gale
#

ok, so a scene inside a script. Scripts and scenes is new territory for me 😅

ivory delta
#

Well what happens when you try?

little gale
#

The RGB state attr apparently has braces in it

#

I'm guessing its because of the commas

#

{{ state_attr('light.tv_lamp','rgb_color') }}
returns (0, 0, 255), but states shows
rgb_color: 0, 0, 255

ivory delta
#

Yeah, this is why you'll probably need to record/set scenes. RGB is a tuple, not a string.

little gale
#

oh

thorny snow
#

Hi guys, I'm trying to round an output in my template, but it doesnt do anything. Maybe someone of you got a hint for me? 1
"{{ states.sensor.fritz_netmonitor.attributes.uptime | int / 3600 | round(2) }}" The output is "20.25111111111111", no matter what number I'm inserting in round(??)

ivory delta
#

Order of operations. You're rounding 3600.

little gale
#

"{{ (states.sensor.fritz_netmonitor.attributes.uptime | int / 3600) | round(2) }}"

ivory delta
#

"{{ (states.sensor.fritz_netmonitor.attributes.uptime | int / 3600) | round(2) }}"

#

Snap 😄

little gale
#

😅

thorny snow
#

awesome, thx guys

little gale
#

Yeah, this is why you'll probably need to record/set scenes. RGB is a tuple, not a string.
Can you walk me through it mono? I've set a scene with the light in it.

thorny snow
#

Is there a way to display the time like this: 1d 2h 3m for this template? Its the uptime of my Internet Connection. Now its just displayed in Hours

ivory delta
#

I don't know much about scenes, sorry. Check the docs for how to capture one on the fly.

#

Em_Cee - you'll probably want to use strftime. There's plenty of guides on the internet for it, it's just a Python function that takes a time and spits it out in another format.

#

You can try searching the Discord for examples too.

thorny snow
#

thx m8

cerulean cipher
#

@thorny snow very simple example

#

import time
hours = time.time()
days = hours / 24
print(days)

#

states.sensor.fritz_netmonitor.attributes.uptime is hours?

thorny snow
#

seconds

cerulean cipher
#

oh that's easy

#

import time
seconds = time.time()
days = seconds / 60 / 60 / 24
print(days)

thorny snow
#

where do i insert the code?

cerulean cipher
#

that code isn't exactly to paste it, it's to give you an idea on how to accomplish what you wanted in python

sinful bison
#

hello :)
I couldn't find any doc on selectattr, the only mention i found was in the 'expand()' section of the template doc, but nothing else.
I can't quite make it work, does someone have a link ?

sinful bison
#

i have try a lot of thing to work around my issue, but homeassistant jinja limit the append function, and i can't set a variable in a for loop to retreive it afterward ...
i can't find how to simply make {{ expand('group.battery') | selectattr('state', 'lt', '15') | list | count > 0 }} work, because my state return an string but i need an int to compare number :(

late mesa
#

I have a rather complicated sensor template that hits someone's api endpoint. It updates every 10 seconds. The problem is that sometimes their api returns a value that is inaccurate resulting in a sensor value of 0. This happens anywhere from about once an hour on the best of circumstances or like once every 2 minutes on the worst of times. This leads to an inaccurate sensor value.

Long story short, is there a way for me to make the template sensor skip updating the value if value is not desired (0 in this case)?

dreamy sinew
#

Depends. Can you detect it logically?

#

I don't think you can skip but you could probably default it somehow

late mesa
#

could I default it to its previous state?

dreamy sinew
#

Not sure, probably not there

#

Could have an automation update an input value whenever the sensor changes and pull from that input value

late mesa
#

great idea, working on that now.

silent barnBOT
lapis quarry
#

I was using 8 automations before to do this, if i can do it in 1 template it would be awesome

inner mesa
#

You can simplify further

#

Just get rid of to the to: line and use a single trigger block. It will trigger on both

lapis quarry
#

but then I can do this for the off :

        for:
          seconds: 20
inner mesa
#

True

#

Also, the last lines are wrong. Get rid of the quotes and use trigger.to_state.state, not ‘name’

lapis quarry
#

something like this?

    - data_template:
        dev_id: >
          {{ trigger.to_state.entity_id }}
        location_name: >
          {% if trigger.to_state.state == ‘on’ -%}
            home
          {%- elif trigger.to_state.state == ‘off’ -%}
            not_home
          {%- endif %}
      service: device_tracker.see
inner mesa
#

Not quite

#

trigger.to_state.state == ‘on’

lapis quarry
#

like that?

inner mesa
#

Get rid of is_state()

#

Just what I put there

lapis quarry
#

ok think i got you, like that should work?

inner mesa
#

You probably want trigger.to_state.entity_id for dev_id

#

Or maybe not. Maybe ‘name’ is what you want

#

Try it and see

lapis quarry
#

i just want motionlr01x from binary_sensor.motionlr01a

inner mesa
#

Right

lapis quarry
#

gues name is what i want?

#

let me try it and see

#

Invalid config for [automation]: invalid template (TemplateSyntaxError: unexpected char '‘' at 32) for dictionary value @ data['action'][0]['data_template']['location_name']. Got None. (See /config/configuration.yaml, line 45).

#

need to hit the bed, 3am allready, will give it another shot tomorow 🥱

mighty ledge
#

@lapis quarry you copied that from the forums? It has the invalid quote type. Replace all your quotes with the non-fancy quotes

green wasp
#

I could really use some help here with mqtt fans and openmqttgateway. The topic is the same for all fans, i simply have different values to check. Also, not 100% sure how i should be handling payload_on as its pretty much that if any of the low, medium, or high speeds are set, then its on. And of course, none of the speeds even show up in the entity ui for each fan. When I do use a remote to set it to low, it is correctly the fan as off or on though. https://hastebin.com/ujeyetexip.bash

north helm
#

I'm pulling start times via an API and unfortunately it's coming in as Eastern Time (I'm in Mountain, which is two hours behind) and having a really hard time finding how to subtract the 120 minutes from either the time itself or a timestamp.

#

tcm_starttime:
friendly_name: Start Time
value_template: '{{ states.sensor.tcm.attributes["time"] }}'
tcm_starttimestamp:
friendly_name: Start Timestamp
value_template: '{{ states.sensor.tcm.attributes["timestamp"] }}'

#

Any pointers?

#

The attributes are coming across as:

#

time: '08:00 pm'
timestamp: '2020-08-02T20:00:00'

dreamy sinew
#

Is it not returning the timezone in the timestamp?

north helm
#

It's not...

dreamy sinew
#

That blows

north helm
#

I agree. And there's no way to specify the timezone in the call...

dreamy sinew
#

You can add one but you're going to have to touch it every 6 months for dst adjustments

north helm
#

That wouldn't be too terrible.

dreamy sinew
#

Is it an API that you have to use an account for?

north helm
#

No. It's Turner Classic Movies' free one.

dreamy sinew
#

Lame

north helm
dreamy sinew
#

Maybe take the time, convert it to the integer timestamp, subtract 2 hours and then turn it back into a time string

north helm
#

That could work. It's a little kludgey, but it's just for me, so who cares? 😛

dreamy sinew
#

(as_timestamp()|int - 10800) I forget the rest

#

HA template docs should have something though

north helm
#

That's a great jumping off point. I can work with that! Thank you!

dreamy sinew
#

Np!

north helm
#

{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}

gives me the right value, so now I all need to do is turn that back into realtime.

#

Something like

#

tcm_starttimestamp:
friendly_name: Start Timestamp
value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'
tcm_realtime:
friendly_name: Start Time
value_template: '{{ as_timestamp(states.sensor.tcm.tcm_realtime) | timestamp_custom("%H:%M", 0) }}}}'

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

inner mesa
#

you have a whole bunch of } at the end of the last line 🙂

north helm
#

Even without the extras.. 😉

#

Still coming up as as "Unavailable"

#
tcm_starttimestamp:
        friendly_name: Start Timestamp
        value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'
tcm_realtime:
        friendly_name: Start Time
        value_template: '{{ states.sensor.tcm.tcm_starttimestamp | timestamp_custom("%H:%M", 0) }}'

#
Error rendering template: UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'tcm_starttimestamp'
inner mesa
#

Well, does it?

north helm
#

I barely know my way around templates. That error is uninteligible to me.

inner mesa
#

You’re trying to reference an attribute and it’s telling you it doesn’t exist

#

Go into devtools -> States, search for sensor.tcm

#

Make sure it exists. If it doesn’t, you’ll need to figure out what entity you’re actually looking for

#

If it does, look in the right column and see what attributes it has and what they’re called

#

If you don’t understand it, where did it come from?

north helm
#

I'm calculating tcm_starttimestamp from a real attribute on sensor.tcm to subtract 7200 seconds

inner mesa
#

The code, I mean

north helm
#

Learning on the fly. 🙂

inner mesa
#

Did you copy it from somewhere?

north helm
#

Wanna see the whole thing?

inner mesa
#

Ok, follow the instructions above

#

No, let’s find the right sensor and attribute and go from there

#

And test your templates in devtools -> Templates

cerulean cipher
#

so tcm_starttimestamp = sensor.tcm - 7200

#

basically

#

?

#

I'm guessing that isn't being passed to the template

north helm
#

Yes. I'm taking sensor.tcm.attributes["timestamp"] - 7200

cerulean cipher
#

@inner mesa would he have to pass that to the template also?

#

(i know sweet FA about templates)

north helm
#

The original attribute is coming over from an API

cerulean cipher
#

that part won't really matter

#

as long as you can pass it to the template

inner mesa
#

He/She needs to follow the instructions I wrote above

north helm
#

It's called timestamp

cerulean cipher
#

@inner mesa I see what you're getting at, I guess we wait

north helm
#

OK. I'm not communicating this well.

#

sensor.tcm exists.

cerulean cipher
#

what are its attributes

north helm
#

It has the following attributes

#
  • name
    - releaseYear
    - tvParticipants
    - tvDirectors
    - description
    - runtimeMinutes
    - time
    - timestamp
cerulean cipher
#

OK

inner mesa
#

You just weren’t answering

north helm
#

That timestamp is 2 hours ahead of my local time.

#

I'm sorry.

inner mesa
#

I don’t see ‘tcm_starttimestamp’ in that list

#

So I agree with the error message

cerulean cipher
#

so do I

north helm
#

tcm_starttimestamp is created in:

#

        value_template: '{{ states.sensor.tcm.attributes["time"] }}'
      tcm_starttimestamp:
        friendly_name: Start Timestamp
        value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'