#templates-archived

1 messages · Page 157 of 1

young jacinth
#

hey i got a problem again,
i want to filter all my entities by domain and by any desired filter "words"

i can get it working with only one word but not with a list of words....
somebody has a solution or can help me out?

https://pastebin.com/V6uuJDtS

inner mesa
#

you can't use a template to construct another template like that 🙂

#

luckily, it's much easier

young jacinth
inner mesa
#

yeah, that's what I was building

young jacinth
#

thank you anyway 🤘

fringe temple
#

Wondering if there is a simple way to track users in zones after they've left to report who was last in zone such that if a new person or persons enter a zone, it shows them all, but once the last person leaves, it shows who was last there. Triggers work as expected when the last person leaves, but I'd like additional context to know who was last to leave in order to route notifications.

rose scroll
#

Try this?

  • Use an input_text to store a person ID
  • An automation that triggers whenever a person's state changes to not_home, whose action is to update the input_text
  • Then you can use another automation that triggers when the zone state goes to 0, whose action is to send a notification to whoever's ID is in the input_text
quaint flame
#

hello, im looking for a way to track the previous 24hrs of a sensor to find the difference between its current state and its state 24hrs ago. i was using a SQL sensor, but after i updated my system the SQL sensors are basically worthless

marble jackal
frank gale
#

Is there a particular reason why the | default(<value>,true) filter doesn't work with the state() method?
It doesn't return the <value> if the state object returns None
With the state_attr() it works...

#

So it returns the <value> only if the method returns null and state() returns None. Am I missing something?

manic onyx
#

Hi everyone. I am using feedparser to get fuel prices for today/tomorrow for my local petrol stations. I is parsed as an array?
``entries:

  • title: '148.3: United'
    price: '148.3'
  • title: '184.9: Coles Express'
    price: '184.9'
  • title: '185.9: 7-Eleven South'
    price: '185.9'
    ``
    I want to get an average/min/max prices for the day, so that when tomorrow's prices are available, I want to compare and alert if there is a major price difference
#

guess I need to use a loop, but still struggling with yaml syntax

mighty ledge
mighty ledge
#

Default is only possible when the method returns none

frank gale
mighty ledge
#

Check for unknown and unavailable

marble jackal
mighty ledge
#

Or make an availability template on your entity

frank gale
mighty ledge
#

There’s a resolver that changes it to unknown or unavailable

#

You have to check for those.

frank gale
#

Will do thanks

marble jackal
frank gale
manic onyx
#

@mighty ledge I tried to do something like this, but in template tester I get an error - says append is not safe:
{% set avprice = [] %} {% for num in state_attr('sensor.fuel_watch_today_ulp', 'entries') %} {% if avprice.append(num.price) %}{% endif %} {% endfor %} Average price: {{ avprice | sum / avprice | count }}

mighty ledge
manic onyx
#

@mighty ledge - how! 🙂 looks so easy when its done and it works 🙂

young jacinth
#

hey, how would i add a string as an item to a list?

{% set x = ['a1','b2','c3'] %}
{% set y = 'd4'|list%}
{{ x + y }}

i tried this one but 'd4' is get ripped appart. this is the output:
['a1', 'b2', 'c3', 'd', '4']

inner mesa
#

because it's a string. you can do

{% set x = ['a1','b2','c3'] %}
{% set y = ['d4'] %}
{{ x + y }}
young jacinth
#

mhh is there no way to achieve this with a string?

inner mesa
#

you turn it into a list, just like I did there

#

not like you did, which pulls it apart, as you discovered

#

a Jinja filter takes an iterator, and when you treat a string as an iterator, you get individual characters

#

with a list, you get individual list items

merry delta
#

i believe this fits in here. i want to combine my door contact sensor with my door lock, so that one icon can show state if door-closed-locked vs door-closed-unlocked vs door-opened. i have rarely dabbled in templates. if wrong place then let me know

young jacinth
#

i will have to find another solution for my needs here then

merry delta
#

i dont want to use conditional card because everything is already nested in button card - vertical card - popup card. so it would be too much

merry delta
#

i found it, google was my friend

marble jackal
#

Result: [ "d4" ]

rigid chasm
#

Hi all it's me again with silly questions. How do i create counter sensor with devices on, by value over 30w ? . Examble. If washer and dryer are running, counter sensor shows me..2 devices on😁

inner mesa
#

How can you identify which devices you care about, specifically the entities that measure power?

#

if you just want to list them, then it's simple

#

{{ ['sensor.foo_power', 'sensor.bar_power']|expand|selectattr('state', 'gt', '30')|list|length }}

rigid chasm
#

This just what i was l looking for. Thanks again

solar hemlock
#

Quick and probably silly question I have started to work on a simple template. The template is outputting my alarm volume as 51.0 and I need to convert to decimal so .51 Can someone point me in the direction to change the output number in my template? "{{states('number.bedroom_speaker_alarm_volume')| default(0) | float }}"

#

And I see that its as simple as diving by 100 😆

#

"{{states('number.bedroom_speaker_alarm_volume')| default(0) | int /100}}"

marble lily
#
  sensors:
    power_outage:
      icon_template: mdi:power-plug-off
      value_template: >-
        "{{ is_state('switch.bathroom_fan', 'on') }}"```
#

I don't get why the sensor template isn't on, because the bathroom fan it;s on

marble jackal
#

What does the template return if you enter it in devtools > Templates

#

Oh wait, I see it, you shouldn't quote your template if you use multi-line notation

#

Either use:

      value_template: "{{ is_state('switch.bathroom_fan', 'on') }}"

or

      value_template: >-
        {{ is_state('switch.bathroom_fan', 'on') }}
marble lily
#

thank you!

#
            and is_state('switch.switch_speakers', 'unavailable') }}```
#

i'm making a template sensor for power outage

marble jackal
#

Okay, and is there a question about this template you posted?

marble lily
#

it's working fine, thanks for help.

main gulch
#

Please help I want to enumerate my sonarr sensor to return the missing episodes, however it does not have keys?

{{ states.sensor.sonarr_queue }}

It returns the below:

<template TemplateState(<state sensor.sonarr_queue=3; Beat Shazam S04E05=97.74%, Beat Shazam S04E06=47.70%, Deadliest Catch S18E01=43.16%, unit_of_measurement=Episodes, icon=mdi:download, friendly_name=Sonarr Queue @ 2022-04-21T13:17:11.814043+02:00>)> 

I would like to return the list:
Beat Shazam S04E05: 97.74%
Beat Shazam S04E06: 47.70%
Deadliest Catch S18E01: 43.16%

Not sure I understand how to return atributes without keys.

inner mesa
#

Well, they do have keys, they're just the names of the shows

#

That's pretty annoying, though

mighty ledge
#
{{ states.sensor.sonarr_queue.attributes }}
``` will show you the keys
inner mesa
#

And if you want to filter that for just the shows, you'd need to look for something identifiable, like a % in the value

#

Or ' S'

main gulch
mighty ledge
#

Where is that coming from? I don’t know why they wouldn’t plop the episodes into a list

#

Stupid entity design imo

#

Sry on mobile, can’t really write out code

main gulch
mighty ledge
#

What integration?

mighty ledge
#

It should make a select entity

#

Seems like that integration needs some love

inner mesa
#

this will return a list of shows, assuming they conform to SxxEyy:

#
{% set data = {'Beat Shazam S04E05': '97.74%', 'Beat Shazam S04E06': '47.70%', 'Deadliest Catch S18E01': '43.16%', 'unit_of_measurement': 'Episodes', 'icon': 'mdi:download', 'friendly_name': 'Sonarr Queue'} %}
{{ data|select('search', 'S\d+E\d+')|list }}
#

-> ```
[
"Beat Shazam S04E05",
"Beat Shazam S04E06",
"Deadliest Catch S18E01"
]

#

I don't know if it's possible to reference the value of a dict item in selectattr. Couldn't figure it out

main gulch
analog mulch
#

Hi. I'm trying to set up a numerical sensor which will sometimes have infinite values (let's say it's inverse power when something is off). What should I make the sensor report in this case, so that the history charts look fine. Is returning an empty string fine?

mighty ledge
#

But you have to map(attribute='0') too

inner mesa
#

but then you can't get back to the name

#

as we've discussed in the past, I want to be able to apply a function to each item to modify it, before the comparison

#

this.value()

mighty ledge
#

Cause that’s what it will do. The kvp is 0 for key, 1 for value

inner mesa
#

I want to make a decision based on the value and return the key

#

ah, so '0' and '1' will do that

mighty ledge
#

Yeah, you can do that as long as the decision is a filtering of the list with select or selectattr

inner mesa
#

that's totally unintuitive, BTW 🙂

mighty ledge
#

If you need to do a if statement or something, it won’t do it

inner mesa
#

will file that away. I'm pretty sure that it's come up before now that I think about it, but completely forgot

mighty ledge
#

Yeah I’ve brought it up a few times. I use it a lot to get around dynamic length dicts limitations

inner mesa
#

would you expect this to return the first key?

#
{% set data = {'Beat Shazam S04E05': '97.74%', 'Beat Shazam S04E06': '47.70%', 'Deadliest Catch S18E01': '43.16%', 'unit_of_measurement': 'Episodes', 'icon': 'mdi:download', 'friendly_name': 'Sonarr Queue'} %}
{{ data|selectattr('1', '==', '97.74%')|map(attribute='0')|list }}
mighty ledge
#

Yea

inner mesa
#

alas it does not

mighty ledge
#

Oh it needs data.values()

#

Er

inner mesa
#

but then

mighty ledge
#

No .items()

inner mesa
#

ah

mighty ledge
#

Yah my bad

#

Items is kvps

inner mesa
#

there ya go

#

awesome

mighty ledge
#

Yeah I meant .items the whole time

#

Oops

inner mesa
#

so I think that

{% set data = {'Beat Shazam S04E05': '97.74%', 'Beat Shazam S04E06': '47.70%', 'Deadliest Catch S18E01': '43.16%', 'unit_of_measurement': 'Episodes', 'icon': 'mdi:download', 'friendly_name': 'Sonarr Queue'} %}
{{ data.items()|selectattr('1', 'search', '%')|map(attribute='0')|list }}

is a better solution to the OP's problem

#

TIL

keen abyss
#

Hey, is there any way in jinja to get the opposite of a boolean? E.g if it's 0 then I'd get 1 and the other way around?

inner mesa
#
{{ (not 0)|int }} -> 1
{{ (not 1)|int }} -> 0
atomic blade
#

Is there a filter/function to take a value, evaluate an expression, and pass that value along if true, and another specified value if false?
Like f(val, cond, fallback) e.g. f('a', true, 'f') == 'a' and f('a', false, 'f') == 'f'

quaint flame
#

@mighty ledge hey man i was lookin on the forums and saw you were responding a ton on recalling a sensors state from 24hrs ago. lots of what i saw showed using a SQL sensor, and i had it working, however i did a large jump in updates and now the sensor no longer works. i've tried everything including rolling back, with no luck. do you know of a way to do this? here is the SQL sensor i was using before my update. ```

  • platform: sql
    queries:
    • name: Crypto Total Yesterday
      query: "SELECT * FROM states WHERE entity_id = 'sensor.crypto_total' ORDER BY ABS(strftime('%s', created) - strftime('%s', datetime('now'), '-1 day')) LIMIT 1;"
      column: 'state'
atomic blade
#

Is it possible to define your own filter/functions that will be globally accessible in your templates just like the custom ones HA gives you?

young jacinth
#

{% set weather = 'rainy' %}
how would i test if "rain" is part of weather?

inner mesa
#

{{ 'rain' in weather }}

quaint flame
#

trying to run this sql sensor and getting an error saying that created dosent exists in my logs. anyone know a better syntax for the query? ```

  • platform: sql
    queries:
    • name: Investment Total Yesterday
      unit_of_measurement: "$"
      query: "SELECT * FROM states WHERE entity_id = 'sensor.investment_total' ORDER BY ABS(strftime('%s', created) - strftime('%s', datetime('now'), '-1 day')) LIMIT 1;"
      column: 'state'
young jacinth
#
{% set list1 = ['rainy','lightning-rainy','snowy-rainy','pouring','hail'] %}
{% set list2 = ['cloudy','cloudy','rainy'] %}

how do i test if one item of list1 is equal to atleast one item of list2

muted geode
#

I have an entity for my Oven's cooknig completion time coming in like this:
2022-04-22T00:56:46.954Z
What format is this currently in so I can convert it to my local time? And what template syntax would I use to display that?

inner mesa
opal estuary
#

I'm trying to make a binary sensor indicating i'm working at home. Here's the template code I've got which works fine in the template dev tool...

on
{% else %}
off
{% endif %}```

But for some reason when I build the template sensor with it its always "off". Any ideas?
#

My sensor code is....

    binary_sensor:
    - name: Working At Home
      state: > 
        '{% if is_state('person.name', 'home') and is_state('binary_sensor.workday_sensor', 'on') and (now().hour > 8 and now().hour < 18) -%}
        True
        {%- else -%}
        False
        {%- endif %}'
buoyant pine
#

Just make the value template

{{ is_state('person.name', 'home') and is_state('binary_sensor.workday_sensor', 'on') and (now().hour > 8 and now().hour < 18) }}
#

So

state: "{{ is_state('person.name', 'home') and is_state('binary_sensor.workday_sensor', 'on') and (now().hour > 8 and now().hour < 18) }}"
``` or

state: >
{{ is_state('person.name', 'home') and is_state('binary_sensor.workday_sensor', 'on') and (now().hour > 8 and now().hour < 18) }}

opal estuary
#

Thanks! Yeah that seems like its working. Aside from being much simpler why is that working?

inner mesa
#

any time you feel compelled to return True or False, you really just need to return the boolean result of the test you're doing

opal estuary
#

Fair enough!

silent barnBOT
untold zodiac
#

I'm not very good on templates....for this one, I'm getting the Away/Home that I want, but why am I also getting the word off in the notification?:

#

For the notification I get:
off

Away

#

most of it is checking if it's actually been triggered by something.

#

when the home condition fires, then I actuaally get the word On instead, so I don't think it's a line like {{ iif(triggerstate is none, "off", triggerstate) }}

rose scroll
#

What is this template for?

#

Anyway I would say defined is undefined.

untold zodiac
#

for an notify action as part of an automation

#

so a switch is thrown when one of 3 devices come home (they're controlled by homekit as they're apple devices as I don;t have teh home assistant app on all 3 devices, and dont' have my home assistant exposed.

grim geyser
#

Hello. Im trying to make a template that if the thermostat, room temperature, and room humidity is present to show all 3 else only show the thermostat. The below works for showing all 3 but I cant get it to switch from 3 to 1 in the cases that the room doesnt have the temp and humidity. How can I make that if statement?

#

secondary: |-
Set: {{ state_attr('[[thermostat]]', "temperature") }}°c |
Current: {{ states['[[temperature]]'].state |
round(1)}}°c | Humidity: {{
states['[[humidity]]'].state | round(0)}}%

untold zodiac
#

Ok so it is this line

{{ iif(triggerstate is none, "off", triggerstate) }}

I put a # in front of it, and the notification changed to #off #on

rose scroll
#

Think your problem is is not defined in line 7. What is the purpose of this statement? Think it is not doing what you intend.

untold zodiac
#

I've stripped a lot of it down now.

#
message: |
    {% set triggerstate = trigger.to_state.state %}
    {% if triggerstate == "on" %}
     Home {{ trigger.to_state.name }}
    {% else %}
    Away {{ trigger.to_state.name }}
    {% endif %
#

Which gets me that someone is home, and who the someone is. Pity I can't update a device tracker, or person with an automation.

inner mesa
#

device_tracker.see

untold zodiac
inner mesa
#

The device_tracker.see service can be used to manually update the state of a device tracker:

untold zodiac
#

Hmm maybe I need to rn2readbetterers

stuck dock
#
template:
  - sensor:
      - name: "Percentage of energy produced"
        unit_of_measurement: "°%"
        state: >
          {% set daily yield = states('sensor.daily_yield') | float %}
          {% set Estimated production today = states('sensor.energy_production_today') | float %}

          {{ ((daily yield /Estimated production today ) * 100) | round(1, default=0) }} 

#

tried this too in templates ```
template:

  • sensor:
    • name: "Percentage of energy produced"
      unit_of_measurement: "°%"
      state: >
      {% set daily yield = states('sensor.daily_yield') | float(0) %}
      {% set Estimated production today = states('sensor.energy_production_today') | float(1) %}

      {{ ((daily yield /Estimated production today ) * 100) | round(1, default=0) }}
      availability: >
      {{ states('sensor.daily_yield') not in [ unknown, unavailable, none ] and
      states('sensor.energy_production_today') not in [ unknown, unavailable, none ] }}

#

Got this error ```TemplateSyntaxError: expected token 'end of statement block', got 'yield'

marble jackal
#

Don't set variables with spaces in them

#

{% set yield = whatever %}

stuck dock
#
template:
  - sensor:
      - name: "Percentage of energy produced"
        unit_of_measurement: "°%"
        state: >
          {% set daily_yield = states('sensor.daily_yield') | float(0) %}
          {% set Estimated_production_today = states('sensor.energy_production_today') | float(1) %}

          {{ ((daily_yield /Estimated_production_today ) * 100) | round(1, default=0) }}  
        availability: >
          {{ states('sensor.daily_yield') not in [ unknown, unavailable, none ] and
             states('sensor.energy_production_today') not in [ unknown, unavailable, none ] }}
#

tried this in demo and got this ```
template:

  • sensor:
    • name: "Percentage of energy produced"
      unit_of_measurement: "°%"
      state: >

      33.2
      availability: >
      True

marble jackal
#

Okay, that seems fine then

rose scroll
stuck dock
#

how do I do that?

#

can it display % as units?

rose scroll
#

{{ states(...) not in ['unknown', 'unavailable', 'none'] }}

#

Just do {{ ((daily_yield...default=0) }} % to make it display a % after 33.2 scratch that, you already indicated unit of measurement as %.

stuck dock
# rose scroll ~~Just do `{{ ((daily_yield...default=0) }} %` to make it display a % after 33.2...
#percentage of enrgy produced 
template:
  - sensor:
      - name: "Percentage of energy produced"
        unit_of_measurement: "%"
        state: >
          {% set daily_yield = states('sensor.daily_yield') | float(0) %}
          {% set Estimated_production_today = states('sensor.energy_production_today') | float(1) %}

          {{ ((daily_yield /Estimated_production_today ) * 100) | round(1, default=0) }}  
        availability: >
          {{ states('sensor.daily_yield') not in [ unknown, unavailable, none ] and
             states('sensor.energy_production_today') not in [ (unknown), (unavailable), (none) ] }}
#

this is how it should be?

rose scroll
#

Quotes, not brackets. And you should do that for both lists.

marble jackal
marble jackal
#

You already corrected that while I was typing this 😀

young jacinth
stuck dock
# rose scroll Quotes, not brackets. And you should do that for both lists.
#percentage of enrgy produced 
template:
  - sensor:
      - name: "Percentage of energy produced"
        unit_of_measurement: "%"
        state: >
          {% set daily_yield = states('sensor.daily_yield') | float(0) %}
          {% set Estimated_production_today = states('sensor.energy_production_today') | float(1) %}

          {{ ((daily_yield /Estimated_production_today ) * 100) | round(1, default=0) }}  
        availability: >
          {{ states('sensor.daily_yield') not in [ 'unknown', 'unavailable', 'none' ] and
             states('sensor.energy_production_today') not in [ 'unknown', 'unavailable', 'none') ] }}
#

this is how it should be?

rose scroll
#

Yes, that looks alright.

marble jackal
#

@stuck dock suggestions, check if the state of your source sensors is a number, and not if it is an invalid state. And with that availability template in place, there is no need for defaults.

      - name: "Percentage of energy produced"
        unit_of_measurement: "%"
        state: >
          {% set daily_yield = states('sensor.daily_yield') | float %}
          {% set Estimated_production_today = states('sensor.energy_production_today') | float %}

          {{ ((daily_yield /Estimated_production_today ) * 100) | round(1) }}  
        availability: >
          {{ states('sensor.daily_yield') | is_number and states('sensor.energy_production_today') | is_number }}
marble jackal
#

I know, but in your availability template you were checking if the state is neither unavailable, unknown or none. My version checks if it is indeed a number, which it will not be if it is any of these states

#

added a pipe in the template above

stuck dock
#

simple logic

floral shuttle
#

just to nail that availability sensor: the states('sensor.xxx') will never be none, but only unavailable or unknown. It's the states.sensor.xxx that can be none. If that happens the states('sensor.xxx') will be unknown. Hence the trigger conditions like:```
condition:
- >
{% set x = ['unavailable','unknown'] %}
{{trigger.to_state.state not in x and
trigger.from_state.state not in x}}
- >
{{trigger.to_state is not none and
trigger.from_state is not none}}

fossil venture
marble jackal
fossil venture
#

Huh. Well TIL.

marble jackal
#

You can also use it in like this {{ states.sensor | selectattr('state', 'is_number') | map(attribute='state') | map('float') | sum }}

floral shuttle
#

thats nice. however, I just tested: {{ states.sensor | map(attribute='state') | map('float') | sum }} and that returns an identical outcome....

#

seems the |map('float') filters the non floats too? or maybe floats them to 0...

mighty ledge
floral shuttle
#

was just adding a count to prove that..

marble jackal
#

Yes, I should have used average because it is a better use case for the filter 🙂

final lark
#

Hi all, I'm searching a way to count number of motion within a time windows of 5min. my sensor is binary_sensor.hue_motion_sensor_cuisine which give 3 values (on,off,unavailable). I don't know if a template could do that

mighty ledge
#

It cannot

#

History stats

silent barnBOT
final lark
#

okay 🙂 I will look into that direction , thank you @mighty ledge

analog mulch
#

I am using an API to return a time period string, which is formatted either as "35 min", "1 h 45 min" or "3.5 h", depending on some unclear boundaries. What would be a good template to convert this to, say, minutes which wouldn't fail when I try to split it on a non-existent term like "h" or refer to a second element when it's not there.

tired gyro
#

I've tried to search the community and Discord, but apologies if I've overlooked something. I have a template to count the number of lights that are turned on, but I would like to be able to filter out hidden entities, rather than having to add a separate rejectattr filter for each light separately. Is there a filter that would accomplish that?

#
  | rejectattr( ## if entity_id is hidden in entity registry ## )
  | map(attribute='entity_id') | list | count }}```
rose scroll
#
{% set timestring =  '1 h 45 min'.split(' ') %}
{% set ns = namespace(minutes = 0) %}
{% for i in range((timestring | length / 2) | int) %}
  {% if timestring[i * 2 + 1] == 'h' %}
    {% set ns.minutes = ns.minutes + (timestring[i * 2] | float) * 60 %}
  {% else %}
    {% set ns.minutes = ns.minutes + (timestring[i * 2] | float) %}
  {% endif %}
{% endfor %}
{{ ns.minutes }}
#

You can modify that to assign your api output to the timestring variable.

floral shuttle
#

hmm, this is new. I get a template default error when using {{distance('device_tracker.myphone_app')|round(2,0)}}

#

I figured the example at ```

returns rounds 1.23 down precision of 0, if fails returns 0

{{ 1.43 | round("floor", 0) }}``` to be the exact case? or do I need default=0 as second argument after all

marble jackal
floral shuttle
#

must say the app currently is not correctly found by the mobile_app integration, so yes, there is actually an issue with the data, forcing it to use the default for the first time (which would explain I never saw the error before..)

fallow sand
#

Hey everyone! Having an issue with what I think is a rather straightforward template condition for sun elevation. The following condition:

condition: template
value_template: '{{ state_attr('sun.sun','elevation') < 2 }}'

Evaluates as true/false in the template editor dev tool, but is giving me an error if I attempt to use it in an automation:

template value should be a string for dictionary value @ data['value_template']. Got None

Not sure why this is throwing that error - any help is appreciated!

inner mesa
#

You need to replace the outer single quotes with "

delicate kelp
#

Can someone point me in the right direction, I have sensors that give their reading in Celsius but I want to see it in fahrenheit. I am using ha in docker compose. The sensors are using mqtt.

tired gyro
fallow sand
inner mesa
#

what does the condition look like now?

fallow sand
#

using the UI and switching over to YAML mode, the system automatically puts double-single quotes on the attributes and if I try to wrap the whole thing in double quotes, it will automatically change those to single quotes:

value_template: '{{ state_attr(''sun.sun'',''elevation'') < 2 }}'
#

seems like it should work. I have other similar ones that work just fine. I was wondering if it has something to do with the sun component tho, since my other value_template conditions are for general sensors.

#

I don't get how it is erroring out to template value is None for dictionary value @ data['value_template']

silent barnBOT
fallow sand
#

that was a pony wall, at best, hass bot!

marble jackal
#

You can just use a numeric state condition there, no need for a template condition

#

provide the attribute elevation as well

fallow sand
#

actually @marble jackal you're 100% correct. I didn't put the attribute in ...but that template SHOULD work, no? I'm wondering if that is a bug in the condition test

marble jackal
fallow sand
#

🙂
anyone else seeing condition tests fail using value_template?

marble jackal
#

No, they work fine here

#

Your condition in the code wall can easily be done without a template as of next month, as you can provide state_not then

#

Is your template accepted if you enter it manually in automations.yaml?

#

And can you save the automation? Is it only the test button which gives this error?

#

I suspect it is just a bug in that test button

#

Confirmed

fallow sand
#

I think so too. I haven't tried saving it directly in automations.yaml yet (truth be told, your suggestion was easier!)
In looking at a different/working automation, the test fails if using the test button in the automation editor, but troubleshooter shows that the step evaluated the condition properly as true
bug

#

bingo! - thanks for finding that one so quickly!

#

OK so I feel better now lol

sacred sparrow
#

with {{ trigger.from_state.attributes.friendly_name }} is there a way to remove characters at the end of the friendly name? I want to remove "battery level" from the friendly name

#

is there a trim?

inner mesa
#

there's replace()

#

{{ "foobar"|replace('foo', 'blah') }} -> blahbar

#

{{ "foobar".replace('foo', 'blah') }} does the same with a Python string method

sacred sparrow
#

{{ trigger.from_state.attributes.friendly_name.replace('battery level', '') }}

#

would that work? I don't know how I would test it

inner mesa
#

It should. You would test it by replacing trigger.from_state.attributes.friendly_name with whatever the string is and testing in devtools ->Templates

#

Or write an automation

sacred sparrow
#

what is a rest automation?

inner mesa
#

Autocorrect/typo for 'test automation'

opaque creek
#

trying a template sensor that give me a timestamp when my camera noticed movement last time. But this one only give me a long wierd number as timestamp.
- trigger: - platform: state entity_id: binary_sensor.baksidagarage_person_detected to: 'on' sensor: - name: "Last Movement Garage" state: "{{ as_timestamp(states.binary_sensor.baksidagarage_person_detected.last_changed) }}"

mighty ledge
#

Remove that

opaque creek
#

Right! I tried this then:
- sensors: kamera_garage_last_movement: entity_id: binary_sensor.baksidagarage_person_detected friendly_name: "Kamera Baksida Garage Senast Movement" value_template: "{{ states.binary_sensor.baksidagarage_person_detected.last_updated }}" device_class: timestamp
And now it seem to show the exact time! But when I add it to Dashboard it wont show the exact time but only "33 minutes ago" hm

#

So I just moved that secondary info that was below "person detected" to its own sensor 😛 Cool.. but I still want an exact timestamp in Dashboard hm

#

Maybe I need some HACS frontend card for that

pastel moon
opaque creek
#

Cool ! Well that does the job! It do give me this:
2022-04-23 10:06:23.993805+00:00

Dont know what those last ".993805+00:00" is? Can I remove that?

marble jackal
#

Yes, you can format it how you want using strftime

earnest cosmos
#

I have this defining two binary sensor. They get recreated showing up as binary_sensor.dishwasher_can_run_nn, now in the count of tens (1-19). What is happening?

template:
  - binary_sensor:
      - name: "Dishwasher Can Run"
        state: "{{ is_state('input_boolean.power_best_save', 'on') }}"
      - name: "Dishwasher Running"
        device_class: power
        delay_off:
          minutes: 5
        state: "{{ states('sensor.bry_dishwasher_power')|float > 1 }}"
marble jackal
earnest cosmos
earnest cosmos
floral shuttle
#

and I found another oddity, i have longtime had a sensor: {{expand('sensor.zp_actuele_opbrengst','sensor.netto_verbruik') |map(attribute='state')|rejectattr('state','in',['unknown','unavailable']) |map('float',0)|sum|round(2,none)}} whihc has a fine state in the frontend, and no config error in the checker. However, the order of things is incorrect, which the dev template tools indirectly tell me: UndefinedError: 'str object' has no attribute 'state'

#

isnt this strange? how come the config checker doesnt notice this?

marble jackal
floral shuttle
#

yeah I tried that too, but the result is still 'nan'

#

and check the other real life template above, it also uses the |map('float',0) as has a correct outcome

marble jackal
floral shuttle
#

but isnt that because that has a possible 3 arguments, and when only using 2, we need the default=? float would only ever have 2 arguments, so ,0 would suffice ?

marble jackal
#

Yes, but you are not using float, you are using map

floral shuttle
#

right, you're right! but then why doesnt this error anymore, it would still need a default in that case, and, more interestingly, the 0 is the second argument now, so ho to explain that.. hmmm

marble jackal
#

Not sure

floral shuttle
#

well, if using the | selectattr('state', 'is_number') we can a) leave out the default because it will always be a number, and b) leave out the |rejectattr('state','in',['unknown','unavailable']) because of the same reason...

marble jackal
#

👍🏼

floral shuttle
#

I suppose we can even leave put the final default in the round here: {{expand('sensor.zp_actuele_opbrengst','sensor.netto_verbruik') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='state') |map('float',0)|sum|round(2,none)}} and make that: {{expand('sensor.zp_actuele_opbrengst','sensor.netto_verbruik') |selectattr('state', 'is_number') |map(attribute='state') |map('float')|sum|round(2)}} ?

marble jackal
#

I would say so indeed, you will always have only numbers

#

But also in the first one, the sum would have thrown an error if there were still incorrect states included

floral shuttle
#

agree, but these are always number entities, and only could have gone unknown/unavailable. Its way less risky then with the states.sensor iteration

earnest cosmos
#

This binary_sensor don´t seem to change status on state change. What am I missing?

template:
  - binary_sensor:
      - name: "Dishwasher Running"
        unique_id: 'F1E94D22-84F0-415F-88EE-31D73F3D5792'
        state: "{{ states('sensor.bry_dishwasher_power') | float > 0 }}"

The state of sensor.bry_dishwasher_power is indeed 0.0, still the binary_sensor reders to false

inner mesa
#

If it's zero, false is correct

earnest cosmos
#

Seems there is the GUI that lags/don´t update

#

It did so after some minutes, though

#

Not entirely true, it seems, testing again: Flipping the power button on: State for the binary sensor was changing to true, but turning off the power the binary sensor remains on

#

This is also the status in the States view

#

Meaning Power is off, and binary sensor state is still on

#

Is it some trigger interval for template updates?

earnest cosmos
inner mesa
#

you didn't say "0.1"

#

The state of sensor.bry_dishwasher_power is indeed 0.0, still the binary_sensor reders to false

earnest cosmos
#

I know, just had to check if my knowledge of > 0 was correct 🙂

#

Seems there is some delay for turning the binary sensor to false after there is no power (0.0), while turning on power consumption imediatelly returns "on"

inner mesa
#

that would only happen if the sensor itself is slow to respond. you can test it by changing the value manually in devtools -> States

earnest cosmos
#

Then it updates fine. The binary_sensor seems slow updating, though, which is defined as above, and the state for sensor.bry_dishwasher_power changes immediatelly

#

I can live with the delay in real life, just now, when defining everything and testing it is not good to have the delay there, and it seems odd too 🙂

#

I restarted HA and now it updates as expected. Must have been something hanging somewhere. 🙂

low blaze
#

is it possible (or smart) to define "helpers" with a .yaml instead of 1 at a time with the gui. I have a lot to make and I feel like it would save a ton of time

#

(basically I want to make maybe 100 input_number helpers maybe 200)

buoyant pine
#

Yes

silent barnBOT
low blaze
#

awesome and what would the line in config.yaml look like for the !include statement (with this many I'm going to dedicate a .yaml to them)

#

input_number checks: !include checks.yaml

buoyant pine
#

input_number: !include /path/to/file.yaml assuming you just want one file for it

low blaze
#

right?

opaque creek
marble jackal
#

'{{ states.binary_sensor.occupancy_1_occupancy.last_changed.strftime("%H:%M") }}' for example

opaque creek
#

Or should I just change the Dashboard card with that code , is that enough?

#

I looks like this now:

- sensors: kamera_garage_last_movement: entity_id: binary_sensor.baksidagarage_person_detected friendly_name: "Kamera Baksida Garage Senast Movement" value_template: '{{ states.binary_sensor.baksidagarage_person_detected.last_updated.strftime("%H:%M") }}' device_class: timestamp

marble jackal
#

You could just put it in the markdown card. You could also include the date, have a look at the link I posted for the codes to use

opaque creek
#

Ok will try, thanks!

opaque creek
#

Learn something new each day here hehe

low blaze
#

@buoyant pine I didn't say thankyou earlier. Thank You 🙂

mental violet
#

Hello, I just want to take a random element from an array and use it like this: service: rest_command.jarvis_say_something data: text: mytestarray[line1,line2,line3,line4,...] | randomelement

fossil venture
#
data:
  text: "{{ [line1,line2,line3,line4,...] | random }}"
ruby peak
#

Is it possible to do this?

template:
  - sensor:
      - name: "Plant Moisture"
        unit_of_measurement: "%"
        state: {{ states('input_number.moisture') }}
inner mesa
#

As long as you surround the template in quotes, sure 🤷

#

Why do you ask?

opaque creek
#

So I want a template sensor that show me the current dew point out of my Aqara temp/humidity sensors. How should that code look like? Hm

opaque creek
#

But you need some kind of calculation, maybe someone already have a working sensor and would like to share their code? :)

inner mesa
#

Maybe, but the math is probably googleable. I assumed you were looking for syntax

opaque creek
nocturne chasm
#

Or at least a little google-foo 😉

ruby peak
gentle ivy
#

Hello All, lets say i want to create a template sensor of type Select. and i want to push some data onto mqtt when such enttity changes. I could use the select_option key to run an action when an option is selected right?

#

the documentation is not very clear to me

marble jackal
#

The state of the entity will change to the selected option. So as trigger for an automation you could use a state trigger. But this is more a topic for #automations-archived if you are not asking about the actual Jinja templates

gentle ivy
#

ok thanks

#

I hoped I could define the "action" to run when an option was selected

#

directly withn the select template.

marble jackal
#

Oh right, seems you can do that

#

@gentle ivy Sorry, haven't used one of those yet, but you are right

gentle ivy
#

can't find a single example.

#

can't even set options with template

marble jackal
#

You can just use the same actions as in a script or automation

#

Use choose to determine actions based on the set option

stuck remnant
#

hi, I have an adaptive lighting integration that takes its brightness and temperature values from a circadian sensor

#

problem is, it also adjust brightness but I don't need it to do that since the sleep mode already handles that

#

I need a template to invert the values of brightness from the circadian sensor because atm when it's bright it makes it very bright and vice-versa

#

(already turned the integration's brightness adjusting off so that won't get in the way - it just adjusts the temperature of the lights now)

orchid oxide
#
platform: state
entity_id: sensor.pixel_4a_bluetooth_connection
attribute: connected_paired_devices
from: |
  {{'00:02:5B:01:5F:D1' in state_attr('sensor.andreas_bluetooth_connection',
    'connected_paired_devices') }}```
#

Why's it adding the | followed by the line break and the line break before connected_paired_devices') }}, and is that syntax ok?

rose scroll
#

Seems fine. The | is just one of the possible ways to indicate that the value assigned to the key (in this case from:) should be the result of a Jinja block over multiple lines. And sometimes the code editor in the UI will add in line breaks to make the code more readable. As long as the indentation is correct, there should be no issue.

high olive
#

I wanted to create an "other consumers" energy sensor by having my main consumption total and subtract my measured consumers total.
I get this error in the sensor template:
https://pastebin.pl/view/b8f40003

This is the preferences of the sensor:

      device_class: energy
      state_class: total_increasing```
Any ideas how I should approach this?
#

Please mention with notification on the above question. Thanks! 🙇‍♂️

rose scroll
#

The point of specifying a default is to avoid such an error, so specify a number instead of 'invalid number' as default.

high olive
#

Thanks DanielLeong, that's fine..
Did you notice the last line (47) in the log?

#

To me, it looks like that makes the template sensor not be able to be used in Energy dashboard... ?

rose scroll
#

Yes, because the value of your sensor may decrease if the other consumers consume less energy today vs yesterday. But total_increasing requires the sensor's value to only increase over time. You probably want to change your state_class to total.

high olive
#

Humm, but consumption can't be total as I'm always consuming. (I have no energy producers in my setup).

#

Do you understand what I want to achieave with this template sensor?

rose scroll
#

Are all the sensors involved in your template of class total_increasing?

#

What the error indicates is that the sensor that takes the template had a value that decreased.

high olive
#

I have a 3phase sensor meashuring my consumed energy on my mains.
I also have several other energy consumer sensors for individual devices connected.
Now I want do deduct the individual devices from the mains so I get an "other individual devices" that aren't directly measured themselves.

high olive
rose scroll
#

Yes I was thinking that was the case. Some inaccuracy in your sensor readings.

high olive
#

Or the sensor reports just come in and every time it comes in, it recalcs the template.
If the Mains sensors aren't updated but an individual sensor does the template will have a decreasing value.

rose scroll
#

Yup exactly.

high olive
#

Can this be recalculated every e.g. 5/10 min ?

little forge
#

I've looked at this from all angles now, trying to use below in a condition, but it won't accept it. any clue?

value_template: {{ states('sensor.envoy_current_power_production') > (states('input_number.blinds_wattage_threshold')) }}

#

it says template value should be a string for dictionary value @ data['value_template']

rose scroll
# high olive Can this be recalculated every e.g. 5/10 min ?

I would advise to put in a condition to check that the new value is not less than the old value before updating the sensor's value. Because even if you set the update frequency to some value, the desync in individual sensors update times could still occur.

high olive
#

Humm, I was not aware of condidions in template sensors... ?

silent barnBOT
floral shuttle
#

trying my first trigger template select:```

  • select:
    • name: Mode selector
      unique_id: mode_selector
      state: >
      {{states('input_select.mode')}}
      options: >
      {{state_attr('input_select.mode','options')}}
      select_option:
      service: script.turn_on
      data:
      entity_id:
      - script.mode_{{option|slugify}}_select```
#

I get an error, not in the logs, but in the popup failed to call service. Service not found. but I can not check the template or the service it is trying to turn on. wondering if the template in the entity_id is parsed at all tbh, so please could anyone check with me?

mighty ledge
#

what's the actual error

#

@floral shuttle

floral shuttle
#

well, it says it can not find the option. that can be because of some other backend logic though. (i think i can fix that) whats more, I need it to parse both of these```
select_option:
service: script.turn_on
data:
entity_id:
- script.mode_{{option|slugify}}select
- script.scene
{{option|slugify}}

#

would that be correct?

mighty ledge
#

I don't want a 'translated error via marius', I'd like to see the actual error in the logs

floral shuttle
#

hehe. its a bit hard to screenhot those popups, there fast than me (I am..?)

mighty ledge
#

they appear in your logs

floral shuttle
#

well, they dont. But the cause for that was found so no need to focus on that toaster error popup. I just want to make sure both of these scripts are turned on in the select_option, and I dont think we can trace that? nor can we check in in the dev tools template

#

about the popup, just try a non existing service in a service call on a button

mighty ledge
#

script.turn_on is an existing service

#

so this is why I'm questioning waht the error is

#

because what you're saying doesn't make sense

floral shuttle
#

let me reiterate: I have these buttoins in the frontend, with an underlying script call to a script. These scripts I am now trying to replace with this new (for me) trigger template select. I commented the original scripts in the yaml. so they no longer exist. The buttons however still use them. So clicking those buttons made the error popup....

mighty ledge
#

So then what's the problem

#

I guess I don't understand your question

#

Are you just trying to ensure that the slugified is giving you the correct result?

floral shuttle
#

I can not trace the execution of the 2 scripts, so I must presume they are not..

#

but there's no indication anywhere of an error

#

thats why I want to make sure the syntax I used is correct in the templates of the option field

mighty ledge
#

alright, then you should be looking at sluggifying your sections from the input select

floral shuttle
#

{{ state_attr('input_select.mode', 'options') }} returns ['Regular', 'Full house', 'Kiosk', 'Developer']

mighty ledge
#

{{states('input_select.mode') | sluggify}}

floral shuttle
#

so for the service calls I need them to be script.mode_{{states('input_select.mode')|slugify}}_select

mighty ledge
#

or making a for loop on those options and outputting that and seeing if your script name is correct

floral shuttle
#

typo!!

#

or? is it sluggify.., you got me confused now.... 😉. nope, no typo, its slugify .

mighty ledge
#

I don't have it memorized

floral shuttle
#

well this is correct: script.mode_{{states('input_select.mode')|slugify}}_select

mighty ledge
#

then it should be running

#

the only thing I see is that you're using the old 'entity_id inside data'

floral shuttle
#

so I guess the question is, can we write: select_option: service: script.turn_on data: entity_id: - script.mode_{{option|slugify}}_select - script.scene_{{option|slugify}} or should we write those as 2 separate services

mighty ledge
#

no

#

target

floral shuttle
#

yes, I use them inside the data field, because they are templates, and not entity_id's directly

#

you mean like: select_option: service: script.turn_on target: entity_id: - script.mode_{{option|slugify}}_select - script.scene_{{option|slugify}} ?

mighty ledge
#

Yes

#

that's the current method you should try to use if you're creating something new. Although the old method should still work.

#

regardless, I don't see how your stuff isn't working.

floral shuttle
#

Ok, thanks!. I'll leave like that (target) for now. Still, none of the scripts are traced, so I guess I need to see that as proof of an issue. Quite difficult not to be able to check if those templates are in fact seen by the backend. It's a bit like with the new This variable in self referencing templates: only way to find out if they are correct is by reloading and simply trying

#

right, so I made another conceptual mistake.... I was still using the regular input_select. entity to change modes, and not the new select. entity. Using the new select, I can in fact see the modes happening 😉

#

Still have to very much get used to using a trigger template instead of automations. I do notice an issue on reloading the template platform though, but have to investigate if thats because of restore or not, or some other error in my config.. anyways, thanks for now!

mighty ledge
#

You’re using a normal template entity.

floral shuttle
#

right, you're spot on. I meant template select...

mighty ledge
#

They work the same way as any other template entity

#

The state is defined by the template and the actions are performed based on the current state. With a select entity, the action isn’t actually executed via the state because it’s always the same. Select option. So its easier to understand

floral shuttle
#

yes, and its very nice that I can now do away with many verbosely written subscripts, and have them all executed via 1 simple new template entity select. (I could maybe have done that before, but never had a trigger (....) to do so. This new functionality pushes me in the back just enough to want to try and experience that)

floral shuttle
pastel moon
#

I made this hideous thing, which works, but also gives empty brackets ("[]"): {% set areas = ["Hallway", "Kitchen", "Closet", "Living room", "Bathroom"] %} {% for area in areas -%} {{expand(area_entities(area)) | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list}}{{", " if not loop.last }} {%- endfor %} How can I prune these in a good way? They can be in front or behind, or both...

silent seal
#

What are you actually trying to do? Get all the lights that are on in each area?

pastel moon
#

Yes, and returned in one variable

silent seal
#

You need a | join(', ') after the list most likely... but right now you're combining arrays

pastel moon
#

Oh, that's where the brackets come from then...

silent seal
#

Yup

#

What do you want to do with the data?

pastel moon
#

for now use to display which lights, and how many

#

I will reuse this in my automations, or that's the plan 🙂

#

I think I'd like to have the output as an array if possible. Would it be possible to join those?

smoky idol
#

Hi guys, how can I calculate a power of 2 in a template? thanks!

inner mesa
#

{{ 2**2 }}

#

-> 4

#

Pretty sure it's in the docs

smoky idol
#

ok. so would something like this work:
{{ (trigger.from_state.state - trigger.to_state.state)**2 }}
?

inner mesa
#

States are strings

#

So add |float to each

marble jackal
#

Combine all entities in a big list, and join that in a comma separated string

orchid oxide
#

state_attr is "[DE:63:AD:73:7A:D1, E8:7F:6B:65:C9:2A]" so why does this return false

  {{"E8:7F:6B:65:09:2A" in state_attr("sensor.pixel_4a_bluetooth_connection",  
  "connected_paired_devices") }}```
inner mesa
#

Because it's false 🙂

marble jackal
#

your attribute result looks like list, but it is a string

inner mesa
#

One has a C9 and the has a 09

marble jackal
#

but that should not matter though indeed

orchid oxide
silent barnBOT
noble fractal
#

It seems I posted too many lines of code to the above posting. I'm having a little trouble with a template sensor, I'm trying to assign a value of 0.0 if no other if of elif conditions are met, yet I still get an "Unavailable" value.

mighty ledge
#

{{ state_attr('sensor.fireboard_one', 'latest_temps') | selectattr('channel', 'eq', 1) | map(attribute='temp') | list | first | default(0.0) }}

#

if your list is more than 5, then it'll still work. If you want to truncate it to 5...

#

{{ state_attr('sensor.fireboard_one', 'latest_temps')[:5] | selectattr('channel', 'eq', 1) | map(attribute='temp') | list | first | default(0.0) }}

noble fractal
#

I think I see, some of this templating is new to me. the channel value should be anywhere from 0 to 5 so I think this should be great

mighty ledge
#

then just use the first one

noble fractal
#

Much thanks, this will certainly shorten my config since there are 6 of these in total, one for each possible channel value of 0-5.

mighty ledge
#

you might want to test it, I have no idea if it works

#

it should work

noble fractal
#

yes checking now

mighty ledge
#

try it in the template editor

noble fractal
#

The second one you provided does it perfectly. The first one seems to return 0 no matter the channel.

#

Again thank you very much I'll have to research the jinja to learn from this

#

@mighty ledge I was mistaken, the values are not 0-5, but 1-6 instead. Would it be correct to do it like this:

{{ state_attr('sensor.fireboard_one', 'latest_temps')[:6] | selectattr('channel', 'eq', 1) | map(attribute='temp') | list | first | default(0.0) }}
mighty ledge
noble fractal
#

Currently it is:
[
{
"channel": 4,
"created": "2022-04-25T16:36:04Z",
"temp": 82.4,
"degreetype": 2
},
{
"channel": 6,
"created": "2022-04-25T16:37:05Z",
"temp": 82.4,
"degreetype": 2
}
]

mighty ledge
#

the first template is what you want then, but channel 1 doesn't exist

noble fractal
#

It will only have values if a temperature probe is plugged into the associated channel

mighty ledge
#

this:

{{ state_attr('sensor.fireboard_one', 'latest_temps') | selectattr('channel', 'eq', 1) | map(attribute='temp') | list | first | default(0.0) }}
#

that will traverse all temp sensors and return a value if it see's channel 1, otherwise it will be 0.0

#

if you want another channel, just change the channel number next to the 'eq',

noble fractal
#

That works! I'm testing them all now (takes 60 seconds for a full test of each channel).

#

Much thanks again

orchid oxide
#

I'm a little confused here. I'm trying to make it so that when the device attribute's "from" includes "DE:63:AD:73:7A:D1" it triggers the automation.

I'm using from: ' {{"DE:63:AD:73:7A:D1" in state_attr("sensor.pixel_4a_bluetooth_connection", "connected_paired_devices") }}' which evaluates to true, but I'm not sure how to make it so that that triggers the automation, since the automation triggers when from matches the previous attribute state, rather than matching true

inner mesa
#

you should change the automation so that it triggers on any change to that sensor's attribute, and use a condition that checks that the value was in the "from" attributes and isn't in the "to" attributes

#

something. like:

#
trigger:
  platform: state
  entity_id: sensor.pixel_4a_bluetooth_connection
  attribute: connected_paired_devices
condition:
  condition: template
  value_template: >-
    {% set prev_devices = trigger.from_state.attributes.connected_paired_devices %}
    {% set new_devices = trigger.to_state.attributes.connected_paired_devices %}
    {{ "DE:63:AD:73:7A:D1" in prev_devices and "DE:63:AD:73:7A:D1" not in new_devices }}
action:
  ...
winter path
#

Trying to make a light template. In its most basic mode it works. However, I tried adding a transition to the set level, but that ens up breaking the template when I use the light it creates on a dashboard. Is there a way to make one light that includes transition ability, but does have to use it? IE, want to be able to use it in a dashboard (currently doesnt like it becuase doesnt pass transition), but also use it in an automation which may include transition

mighty ledge
winter path
#

this is something im trying to figure out here:

#

set_level: service: light.turn_on data_template: entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" {% if {{ transition != none }} %} transition: "{{ transition | float }}" {% endif %}

mighty ledge
#

use choose

winter path
#

im not a jinja guru

mighty ledge
#

you don't need jinja

#

use choose or template the entire data section

winter path
#

ah ok i see. BTW, how would the condition work to see if transition was passed?

mighty ledge
#

{{ transition is defined }}

winter path
#

cool

winter path
#

set_level: service: light.turn_on data_template: {% if {{transition is defined}} %} entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" transition: "{{ transition | float }}" {% else %} entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" {% endif %}

mighty ledge
#

you can only template a single field

inner mesa
#

unless you get all tricky about it

mighty ledge
#

right

#

choose is the way to go if you don't understand templating

winter path
#

I guess is choose the next level after set_level?

mighty ledge
#

your choose would have the default without a transition as your action sequence

#

and with transition defined, it would contain your transition

silent barnBOT
abstract cape
#

okay.. not sure why the bot called that a code wall..

mighty ledge
#

@winter path this would also work, but if you don't understand code, you'll have issues changing it.

        set_level:
          service: light.turn_on
          data: >
            {%- set d = {'brightness': ((brightness) / 1.429) | int, 'transition': transition | float(0.0) } %}
            {%- set kvps = d.items() | rejectattr('0', 'eq', 'transition') | list if transition is defined else d.items() | list %}
            {{ dict.from_keys(kvps) }}
winter path
#

I know some code, but that is a little above my level. may use it because what I have with choose isnt working yet

#

set_level: choose: - condition: template value_template: "{{ transition is defined }}" sequence: data_template: entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" default: service: light.turn_on data_template: entity_id: light.living_room_lights brightness: "{{ ((brightness) / 1.429) | int }}" transition: "{{ transition | float }}"

mighty ledge
inner mesa
#

gack

mighty ledge
mighty ledge
autumn veldt
#

I have this sensor that pulls data from a googlecal which is already integrated into HA then selects the start time atrribute but the date format is not what I want. Can someone help me with the timestamp_custom syntax to get it to display %d/%m/%Y
It is displaying the data like this atm 2022-04-30
My code for the template is here - https://paste.debian.net/1239004/

inner mesa
#

you can do this:
{{ state_attr('automation.alarm_notifications', 'last_triggered').strftime("%d/%m/%Y") }}

#

or this:
{{ state_attr('automation.alarm_notifications', 'last_triggered')|as_timestamp|timestamp_custom("%d/%m/%Y") }}

orchid oxide
swift veldt
#

Can anyone maybe give me a hint how I can get a comma separated sequence/list/array of all „input_datetime“s that have „has_date: false“ ?

orchid oxide
#

with the "test" button in the conditions section of the automation

autumn veldt
#

@inner mesa like this - {{ state_attr('calendar.aston_villa_fixtures', 'start_time')[0:-9].strftime("%d/%m/%Y") }}

inner mesa
#

I don't know why you're doing this: [0:-9].

autumn veldt
#

to remove the time

inner mesa
#

don't

#

you can test it in devtools -> Templates

autumn veldt
#

i need to this is the point of making this value template to just get the date and nothing else

inner mesa
#

and if it's really a string, then you need to may need to use strptime() on it first

#

I know, that's what the last part does

#

it takes a datetime and formats it to just output the date

#

try it

orchid oxide
#

ohh, okay, thanks

inner mesa
marble jackal
silent barnBOT
obsidian lintel
#

For some reason, I cant seem to set the color

silent barnBOT
obsidian lintel
#

Full code is here ^^

tawny wedge
#

I can't seem to find any documentation on how to change the icon color in the modern template sensors. Under legacy there was icon_color. I currently have a template.yaml with the following contents. I want to make the icon Red if off and Green if on.

    name: "Alarm Status"
    state: "{{ states('input_boolean.alarm_status') }}"
    icon: mdi:shield-home-outline```
#

Can anyone point me in the right direction?

obsidian lintel
#

I am trying to create a demo light entity

tawny wedge
#

Okay, I figured out how to do this using themes instead

obsidian lintel
#

I will legit pay somebody to help me out been trying this for months

silent barnBOT
obsidian lintel
#

I have updated the code, this seems to work but I cannot use the color radio selector as set_color: does not seem to be working

#

Hence I am not able to update the values of Hue and Saturation through set_color to my input_numbers.

#

Means I have to use 2 entities to control the color hahaha

mighty ledge
obsidian lintel
mighty ledge
#

why do you need more than 6...

obsidian lintel
# mighty ledge why do you need more than 6...

Hence I just decided to do templates. I managed to get something working by cheating a little but set_color: doesnt seem to update my input numbers.

I need more than 6 because I am trying to build a demo floorplan which have color sync. I need some more because I happen to have a lot of lights in this floorplan hahaha, that includes lamps!

#

Wish I could send a video here to show what I am going through now haha

obsidian lintel
#

Is it possible?

mighty ledge
#

you can copy the whole demo integration as a custom integration and then just add lights to this section

inner mesa
#

I'll save you the Picard meme...this time...

manic onyx
#

Hi everyone. Need a hand with template to get the time when the probability of rain is high. I have a weather sensor that lists probability % in a hourly array (list?) like that:
``
forecast:

  • datetime: '2022-04-26T02:00:00Z'
    temperature: 21
    condition: sunny
    precipitation: 0
    precipitation_probability: 10
    wind_bearing: WNW
    wind_speed: 24
    ...
    What I want to do use it in an automation with say an hourly trigger and a condition of rain probability in this hour (when automation is triggered) > 80%. I just dont understand how to filter the info 😦{{ state_attr('weather.hocking_hourly', 'forecast') | map(attribute="precipitation_probability") | list }}``
    will give me a list of %, but how do I just filter for the current hour?
rose scroll
#

Is the current hour just the first item in the list? You can just index into the list with [0]

#

I.e. {{ (state_attr(...) | list)[0] }} or something similar, if the current hour's forecast always appears in a predictable position in the list.

orchid oxide
#

trying to figure out why this evaluates to "false"

condition: template
value_template: >-
  "None" in trigger.from_state.attributes.error and "Dust collector missing" in
  trigger.to_state.attributes.error```

im almost positive the state is changing from "none" to "dust collector missing"
manic onyx
# rose scroll Is the current hour just the first item in the list? You can just index into the...

Unfortunately not, as it depends on the time when it updated the forecast. So need to get the time as well
``forecast:

  • datetime: '2022-04-26T03:00:00Z'
    temperature: 21
    condition: rainy
    precipitation: 0
    precipitation_probability: 20
    wind_bearing: WNW
    wind_speed: 22
  • datetime: '2022-04-26T04:00:00Z'
    temperature: 21
    condition: rainy
    precipitation: 0
    precipitation_probability: 20
    wind_bearing: WNW
    wind_speed: 22``
orchid oxide
#

you mean the other way around?

inner mesa
#

Nope

orchid oxide
#

oh, i changed it to see if that would make a difference

inner mesa
#

The part above doesn't match your link

orchid oxide
#

it was in before

inner mesa
#

How do you know that that's the condition blocking the automation?

orchid oxide
#

the debug shows that it makes it past the first conditions but evaluates false to the second

#

then says "Stopped because a condition failed at April 25, 2022, 11:34:08 PM (runtime: 0.00 seconds)

inner mesa
#

I suggest using a persistent_notification to display what the value is each time it changes

orchid oxide
#

like make a simple automation that shows the status in a persistent notification?

inner mesa
#

Sure, or just remove the condition and add a persistent_notification in the action

orchid oxide
#

i think its the fact that the value of the attribute is "none"

#

when the state is dustbin whatever, the notification shows fine, but when its "none" it errors out

manic onyx
#

OK, I mostly figured it out. But now need to somehow get the current time/date 🙂
{{ state_attr('weather.hocking_hourly', 'forecast') | selectattr("datetime", "eq", "2022-04-26T05:00:00Z") | map(attribute="precipitation_probability") | float > 20 }}

orchid oxide
rose scroll
#

Then you just manipulate the string to get the next hour, if that's what you're looking for.

manic onyx
rose scroll
manic onyx
#

yes, thank you. Found it

#

the further I go, the more issues I get 🙂
Stupid, I know, but how do I combine and compare strings? Like if I wanted to compare 12 characters of one string to another?

rose scroll
#

somestring1[x:y] == somestring2[x:y], where x and y denote the positions of the first and last characters to extract from a string. Zero-indexed of course.

manic onyx
#

nice and easy 🙂

rose scroll
#

So if you want say the date part of your UTC timestamp, you'd do '2022-04-26T05:00:00Z'[0:10], or for similar effect, '2022-04-26T05:00:00Z'[:10]

manic onyx
#

problem I have is that I need to compare something like this from UTCNOW 2022-04-26T05:34:13.957763+00:00
to something like this from the sensor value 2022-04-26T05:00:00Z

#

I get the right string with this utcnow().isoformat()[0:14]~"00:00Z" (2022-04-26T04:00:00Z), but when I use this like below, it does not work
{{ state_attr('weather.hocking_hourly', 'forecast') | selectattr("datetime", "eq", utcnow().isoformat()[0:14]~"00:00Z") | map(attribute="precipitation_probability") | float > 20 }}

orchid oxide
manic onyx
#

ok, done 🙂
{{ state_attr('weather.hocking_hourly', 'forecast') | selectattr("datetime", "eq", utcnow().isoformat()[0:14]~"00:00Z") | map(attribute="precipitation_probability") | join | int > 70 }}

round mica
#

When I create a sensor for the thermometer of an AC unit, do I have to specify a trigger in order to have it updated at state changes?

#
    - name: "Temperatura Outdoor"
      unit_of_measurement: "°C"
      state: "{{ state_attr('climate.midea_ac_xxxxxxxxxxxx', 'outdoor_temperature' ) | float }}"
      icon: mdi:thermometer```
#

with this template it seems not updating at all

#

I'm not ever sure whether I should use a template or a sensor ... this thing confuses me quite a lot:

    sensors:
      outdoor_temperature:
        friendly_name: "Temperatura Outdoor"
        unit_of_measurement: "°C"
        value_template: "{{ state_attr('climate.midea_ac_xxxxxxxxxxxx', 'outdoor_temperature' ) | float }}"
        icon_template: mdi:thermometer```
These two approaches seems like bringing the same result.
marble jackal
#

The first one is the new format, the 2nd one the old legacy format

#

both have the same result

#

the new format supports state_class for example, which is not supported by the legacy format. And the new format has the option to provide triggers

#

But both should update on state changes of the entities used in the template used for the state

round mica
#

At this point I suppose that the climate entity does not update unless manually triggered. It's a custom integration that works through a local api over LAN.

round mica
#
    - platform: time_pattern
      minutes: "/1"
  sensor:
    - name: "Temperatura Outdoor"
      unit_of_measurement: "°C"
      state: "{{ state_attr('climate.midea_ac_xxxxxxxxxxxx', 'outdoor_temperature' ) | float }}"
      state_class: measurement
      icon: mdi:thermometer```
This won't work either. Is syntax correct?
marble jackal
#

define won't work

#

it shows a state but not the right one? This won't update your climate entity, it will just update the template sensor every minute, but if your climate entity doesn't update, so won't the template sensor

#

You might be better off leaving your template as you had it, and create an automation with a time pattern to update your climate entity every minute using homeassistant.update_entity

round mica
# marble jackal define won't work

At the moment when I check the sensor history it says "last updated 1 hour ago" and "last changed 1 hour ago" and keep showing the value of when I saved and reloaded the template, 1 hour ago.

marble jackal
#

but did the state of the outdoor_temperature in the climate entity change?

floral shuttle
#

fear This https://github.com/home-assistant/core/issues/70359 is going to be an issue during the beta tomorrow..... currently there's no way we can prevent it from happening, nor should we have to (add a default to the This variable imho). This ought to be taken care of in core natively

round mica
little forge
#

refered from #automations-archived , I'm trying to get this condition to work: value_template: "{{ (states('sensor.envoy_current_power_production')|float) > (states('input_number.blinds_wattage_threshold')|float) }}"
but it keeps telling me template value should be a string for dictionary value @ data['value_template']. Got None
Now I'm sure I'm doing smth stupid, but can't see it anumore

sonic nimbus
#

hello, how can I put different actions under one event_data

#
    - platform: event
      event_type: mobile_app_notification_action
      event_data:
        action: 'LOCK_FRONTDOOR'
    # - platform: event
    #   event_type: mobile_app_notification_action
    #   event_data:
    #     action: 'UNLOCK_FRONTDOOR'```
#

I want something like: ```event_data:
action: 'LOCK_FRONTDOOR','UNLOCK_FRONTDOOR'

#

maybe templating can help here..

marble jackal
little forge
marble jackal
#

And the condition should look like this:

- condition: template
  value_template: "{{ template }}"
little forge
#

Yes it is formatted like that

marble jackal
#

.share the whole automation

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
inner mesa
little forge
#

yeah the unnecessary stuff was UI created. lemme check doing it manually...

marble jackal
#

Well you most probably added the and condition yourself, the GUI doesn't do that magically.

little forge
#

I have to admit I cheated and pasted that condition in 😉 now I just added it directly in YAML and indeed it seems to work. thanks guys

sonic nimbus
#

The idea is to have just one trigger platform, not the same xy triggers with different actions

silent barnBOT
chilly locust
#

I'm working on a "daylight remaining" sensor but I'm having some trouble with my value template. Overnight I want it to show the total daylight calculation for the coming day. I'm not super familiar with the jinga2 so help is appreciated!

  • Line 6 doesn't like the &&. How do I put 2 parameters together for the if statement in Jinja2 format so it only counts down between dawn and dusk?
  • Line 9 (the else statement) doesn't like the " - " operator because it thinks that "tomDawn" is null and "tomDusk" is "1651108901.21984". So I guess I'm not setting the variables correctly, because neither of those are a timestamp like they should be.
  • My < and > operators only work opposite of what I think they should, which I'd like to understand.

https://pastebin.com/ui2HiHz7

orchid oxide
#

Do i have a syntactical error here with my GPS coordinates? I'm getting the error "None for dictionary value @ data['gps']. Got None"

#
service: device_tracker.see
data:
  dev_id: buds_live
  location_name: '{{states(''device_tracker.pixel_4a'')}}'
  gps: "{{state_attr('device_tracker.pixel_4a', 'latitude' )}}", "{{state_attr('device_tracker.pixel_4a', 'latitude' )}}"
  gps_accuracy: '{{ state_attr(''device_tracker.pixel_4a'',''gps_accuracy'')|int }}'
atomic blade
#

I'm trying to have a template entity report it's last value if the underlying sensor it uses is reporting unknown, but what I have seems to fail after a restart:

{% set current = states('sensor.logitech_g_pro_mouse_power_level') %}
{% set previous = states('sensor.logitech_g_pro_mouse_battery') %}
{{ ((states('sensor.logitech_g_pro_mouse_power_level')|int - 3500|int) / 740 * 100) | round(2) if current != 'unknown' else previous }}

What am I doing wrong here?

#

I assume I'm missing something about the behavior after restart, but I'm not sure what the correct solution looks like

silent seal
#

Though I should note, I only use that in the the template editor when I’m debugging my lux sensors

#

There’s a few Jinja links in the pins, but Python uses and rather than &&

chilly locust
low blaze
#

I want to craft an if statement that checks a value within 2 boundries. what do I add to this {% if (tent - ambient) > (-100) %}

#

I want it to be if (tent - ambient) is > -100 and <100

#

think i got it

#

{% if ((tent - ambient) > (-100)) and ((tent - ambient) < (100)) %}

orchid oxide
#
true
{%else%}
false
{%endif%}
#

can i do something like this?

#

in the template, this is evaluating to false, when it should be trice

#

so im not sure if this isnt allowed, or if i did something wrong

inner mesa
#

you have extra quotes

#

and it's too compliated

#
{{ is_state_attr('device_tracker.buds_live', 'latitude', state_attr('device_tracker.pixel_4a', 'latitude')) }}
orchid oxide
#

thanks, didnt realize that

marble jackal
marble jackal
frank gale
#

Hi,
Trying to replace an item in list from a namespace like:

{% set list = namespace(l=[ "test", "two", "three" ]) %}
{% set list.l[0] = "one" %}

But of course it doesn't work :P
How should I do it?

marble jackal
#

@frank gale

{% set list = namespace(l=[ "test", "two", "three" ]) %}
{% set list.l = [ "one" ] + list.l[1:]  %}
#

{% set list = namespace(l=[ "test", "two", "three" ]) %}
{% set list.l = list.l | replace("test", "one")  %}
{{ list.l }}

This also like like it seems to work, but then {{ list.l[0] }} returns [ so it is actually a string.
If you store it in a variable in your script or automation though it will work as a list

frank gale
#

Nice, thanks!

orchid oxide
#

how do i use state.attributes? i used it yesterday but i cant find any documentation and cant remember how to use it for the life of me

marble jackal
#

state_attr(entity, attribute)

orchid oxide
#

Oops, that's not the one i was thinking of. I'm looking for the one that lists all attributes got state

marble jackal
#

Please be more clear then, I don't understand what you mean

silent barnBOT
marble jackal
#

I would advice to not turn off automations, but use the state of the binary sensor as a condition in the automation instead

silent vector
#

That's interesting I never thought of that. It's for when my cameras go offline (blue iris) and frigate would then see a gray screen and if someone is there suddenly the lights would turn off on them. The hallway motion sensors are an example I'm in the process of setting up mqtt sensors as I currently just listen for a specific payload for each camera if they go offline

fossil venture
#

I thought adding default would prevent this? ```
Template variable error: 'value_json' is undefined when rendering '{{ value_json.wifi_sta.connected|default(false) == true }}'

#

What is the correct way? Something like this? {{ if value_json value_json.wifi_sta.connected else false }}

mighty ledge
#

if value_json is not populated because the incoming data is not json, it will fail at the first .

#
{% set data = value_json | default(none) %}
{{ data.wifi_sta.connected | default(false) if data else false }}
#

you also don't need == true as true/false resolve to true/false

fossil venture
#

Thanks petro

winter path
#

hey was hoping someone can help me. How can I modify this {{ is_state('input_select.status_' ~ name, 'Just Left') }} to determine if input_select.status_ ~name is 'Just Left' and previous state is not 'Just Arrived'?

marble jackal
#

This would also work I guess

{% set data = value_json | default({}) %}
{{ data.get('wifi_sta', {}).get('connected', false) }}
willow rapids
#

I have data coming in from a rest sensor, but since the data contains {"title":null,"note":"cooked shrimp }

#

instead of {"title":"null","note":"cooked shrimp } the data isn't being read in correctly. is there an easy way to ignore null or replace them if they exist with correct values?

#

there is double quotes around all other values, although as I see not in my pasted example, but the data appears otherwise correct to me.

#

should actually read {"title":null,"note":"cooked shrimp" }

#

I've used a file editor and manually done a replace on all and then used that in the template editor in dev tools.... works beautifully.

tepid citrus
#

Hi everyone. The docs say: LIMITED TEMPLATES Templates for some triggers as well as trigger_variables only support a subset of the Home Assistant template extensions. This subset is referred to as “Limited Templates”.
and TIME now() and utcnow() are not supported in limited templates.
so I thought that to trigger an automation 15 minutes before a time helper, I was going to need to do something complicated....
BUT, this works:
`alias: '!a light on for morning'
description: Turns on at boys morning time unless the late morning toggle is activated
trigger:

  • platform: template
    value_template: |-
    {{ now().strftime("%H:%M:%S") ==
    (today_at(states("input_datetime.boys_morning"))-timedelta(minutes=15)).strftime("%H:%M:%S")
    }}`
    so, what am I misunderstanding about the docs? or are the docs wrong?
marble jackal
#

template triggers are not limited to limited templates

frozen kite
#

Hi all, I'm looking for a bit of help translating a template that works in Developer Tools -> Template into a condition for use in an automation. I'm trying to find out if my phone has received a new notification in the last 60 secs. How do I reformat the following: {{as_timestamp( now()) - as_timestamp( states.sensor.phone_last_notification.last_changed) < 60 }} ?

#

condition: template
value_template: >
"{{(as_timestamp( now()) - as_timestamp( state_attr('sensor.pixel_3_xl_last_notification','last_changed'))) < 60 }}"
gives me "template value should be a string for dictionary value @ data['value_template']. Got None" when I Test it.

willow rapids
#

'''

marble jackal
#

The test button doesn't work for template conditions, it's bugged

#

If the template works in devtools > templates, your condition should be fine this way

willow rapids
frozen kite
#

@marble jackal Thanks 🙂 That kept me 'entertained' for a few hours!

mental violet
#

how can I start an automation when any input_boolean with that filter: {{states.input_boolean |selectattr('object_id', 'search', 'is_mitv_on_')|map(attribute='entity_id')|list }} is switched from off to on ?

willow rapids
#

something like this? ``` alias: input boolean changes
description: ''
mode: single
trigger:

  • platform: template
    value_template: |-
    {{states.input_boolean |selectattr('object_id', 'search',
    'is_mitv_on_')|map(attribute='entity_id')| count | >1 }}
    condition: []
    action:
  • delay: '' ```
tepid citrus
mighty ledge
#

You’d literally see the phrase: limited template in the description of the trigger if it was a limited template

tepid citrus
#

Thank you... There must be a more clear way to describe these cases of limited templates on trigger fields than just template triggers, when there is an entire trigger platform that is template.

#

It would also be nice if you could use a template to specify a time for a time platform trigger, but I couldn't get that to work even if a template was properly rendering a formatted HH:MM:SS string

mighty ledge
orchid oxide
#

bit stumped here on why this wont work here

{% set brightness = (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round) %}

{%if is_state('sensor.light_sensor_illuminance', "<2") %}

75
{%else%}

{{brightness}}

{%endif%}
#

it always evaluates to false

#

and its got something to do with the < sign im prety sure, but i dont exactly understand what

#

also it seems i cant set variables in call service, or im doing it wrong, how can i simplify this?

service: light.turn_on
data:
  transition: 0
  brightness_pct: {{75 if (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round) > 75 else (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round)}}
target:
  entity_id: light.fan_lights_group
#

what i wanted to do was this, but like i said, variables didnt seem to work how i did it:

{{75 if brightness > 75 else brightness}}```
marble jackal
marble jackal
# orchid oxide also it seems i cant set variables in call service, or im doing it wrong, how ca...

The error here is that you should place quotes around your template if you use a single line format.

service: light.turn_on
data:
  transition: 0
  brightness_pct: "{{75 if (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round) > 75 else (75-(((sqrt("states('sensor.light_sensor_illuminance')" | float - 2))/75)*75) | round)}}"
target:
  entity_id: light.fan_lights_group
orchid oxide
#

gotcha, thanks

marble jackal
#

No idea why the bot thinks it is not valid yaml though

orchid oxide
#

so, can you use variables in there, or no? cause its much harder for my eyes to parse without variables 😅

marble jackal
#

yes

orchid oxide
#

same way, just quotes around it?

marble jackal
#

Use the > to indicate you are using multiple lines

service: light.turn_on
data:
  transition: 0
  brightness_pct: >
    {% set brightness = ( 75 - ((( sqrt('states('sensor.light_sensor_illuminance')' | float - 2)) / 75) * 75) | round) %}
    {% if states('sensor.light_sensor_illuminance') | float < 2 %}
      75
    {% else %}
      {{ brightness }}
    {% endif %}
  entity_id: light.fan_lights_group
#

Oh, I see what is wrong in the other code as well now

#

You use both single quotes and double quotes in your template, and that doesn't work if you also need to put quotes around it because of the single line notation

#
service: light.turn_on
data:
  transition: 0
  brightness_pct: "{{75 if (75-(((sqrt(states('sensor.light_sensor_illuminance') | float - 2))/75)*75) | round) > 75 else (75-(((sqrt(states('sensor.light_sensor_illuminance') | float - 2))/75)*75) | round)}}"
target:
  entity_id: light.fan_lights_group
#

Don't know why you placed those double quotes there BTW, they were not needed at all, and I would even expect they were causing the calculation to fail

orchid oxide
#

i guess im still a bit unclear on when to use single and double quotes

marble jackal
#

Doesn't matter which one you choose, but use the one you've chosen consistently in your template

#

So you can use the other one around the template in case of the single line notation

orchid oxide
#

got it

ruby peak
#

Does anyone know how to add custom attributes to sensors etc, using templates?

marble jackal
#

you can add them to a template sensor, but not to an existing sensor coming from another integration

ruby peak
#

Yeah I've got template sensors, but ideally wanted them as part of the attributes of another sensor

marble jackal
#

You can add attriubtes using customize.yaml, but I don't see template support mentioned in the docs

#

So if you want to use templates for your attributes, the only way is to create a template sensor out of the existing sensor, and add the attributes there

gentle ivy
#

Can someone shred me some light on why this is happening?

hexed wing
#

this?

gentle ivy
#

gimme a sec 🙂

#

can't really post pictures.

hexed wing
#

You can now

silent barnBOT
hexed wing
#

Well

#

Your else 'None' kicks in

#

thus None = nothing = empty

#

Meaning select.prism_garage_wanted_status != Charge

gentle ivy
#

Iol didn't know that "None" is a keyword

hexed wing
#

Yeah is it

#

BTW, bit unrelated, but please don't do:
states.select.prism_charge_priority.state

#

Use states('select.prism_charge_priority') instead

gentle ivy
#

ok thanks

#

❤️

marble jackal
#

This statement states.select.prism_garage_wanted_status.state == 'Charge' is already false, so it already doesn't care about the rest

#

that's why it mentions it only listens to that one entity

#

And the other "issue" is that the HA template engine converts None to null, but in the template editor it only does that when it doesn't show anything else

#

It also converts strings which look like a list to a list

#
{% set test = "None" %}
{{ test }}

Returns null

hexed wing
#

That is intentional behavior though

warm venture
#

I got an entity that returns a list of values (next departures of a tram), so far I got this in a Mushroom template (is there an easier way than referring to the specific sensor? The Mushroom thing allows you to pick an entity within the GUI but the documentation doesn't mention anything about it.

Następny o {% for state in state_attr('sensor.rozkladzik_poznan_2977', 'list') %} {{ state[2] }}
{% endfor %}

However, this returns all the values from the list, and I'm only interested in the [1-2] range. Is there any way to go about it?

marble jackal
#
{% set test = "None" %}
Result: {{ test }}

Returns: Result: None

mint drift
#

Hi Guys when playing with History_stats is there anyway of previewing it before you add it to configuration.yaml?

marble jackal
# hexed wing That is intentional behavior though

I know, but it can be a bit confusing. The template editor might show a list as result, and also reports the result is a list, but when you then try to take a list item out of it by use of list[0] your get [

hexed wing
#

Hmm right, although in that case it tries to modify a collection, which is disabled in general

marble jackal
#
{% set list = [ "test", "two", "three" ] %}
{% set list = list | replace("test", "one")  %}
{{ list }}

This does return:
Result type: list

[
  "one",
  "two",
  "three"
]
#

But then list[0] returns [

#
{% set list = [ "test", "two", "three" ] %}
{% set list = list | replace("test", "one")  %}
{{ list.replace('[', '').replace(']', '').replace("'",'').split(', ')[0] }}

Returns one, but is of course a bit ugly 😛

hexed wing
#

interesting

#

That is not an Home Assistant output parsing issue though

#

lol that is actually correct

#

replace() is a string method

#

it returns a string

#

not a list

marble jackal
#

But if you would put it in a variable in an automation or script, you would have a valid list to work with 🙂

hexed wing
#

Sure, as the result of a template is parsed again

#

but that doesn't mean inside the template you have to work with the restrictions there

#

the results of replace() is a string, getting the [0] of a string returns the first character of that string

#

in the case above its a [

marble jackal
#

Yes, I understand what is happening, but because the template editor already shows it is a list, while it actually is a string, can be a bit confusing 🙂

charred dagger
#

I agree. It makes the template editor a less useful tool.

marble jackal
#

First one is a string, 2nd one a list.

hexed wing
#

Depends on the scope

#

within the template: Yes

#

Jinja doesn't retain types in its result, not much we can do about that

#

(would love to see they added that though)

mighty ledge
#

Maybe we can add a dropdown on the left hand side to disable the resolver or not. Either way, if it looks like a list it's always going to look like a list. Not much you can do about that

#

the old template editor had that problem as well

#

any string that looked like an object fooled the user.

#

it's a damned if you do, damned if you don't situation IMO

#

at least in this mode, we can always see what HA will see when you supply just the template without extra fluff

#

maybe we should add a note that says something like: "For the best results, only use a template here, do not paste your entire YAML"

#

Or maybe add a few modes to the template editor: single template, multi line template, yaml included template.

#

Single will behave like it does now

#

Multi line will treat every yaml output as a separate template to resolve

#

And yaml included will take any shape yaml and resolve all endpoints as templates

silent vector
#

How would I get this sensor to update to off when the server is down. Right now when I tested it all I got was an erorr because timed out when ideally it would actually update the sensor to off because a timeout would mean the server is offline.

- platform: command_line
    name: Blue Iris Status
    scan_interval: 8
    command: /bin/bash -c "(echo > /dev/tcp/192.168.1.246/81) > /dev/null 2>&1 && echo on || echo off"

Error:

Timeout for command: /bin/bash -c "(echo > /dev/tcp/192.168.1.246/81) > /dev/null 2>&1 && echo on || echo off"
#

Warning:

Updating command_line sensor took longer than the scheduled update interval 0:00:08
silent vector
peak juniper
#

is there any way to set a certain value for counters the same way you could variables? Is there a way to use them in a template sensor to have counter.yyy + input_number.xxx

marble jackal
#

you can only increment a counter, you can not set it to a value

#

you can set an input_number to a value, and you can use templates for that

#

oh wait, you can probably use counter.configure

peak juniper
#

ah I see, yes I missed that in the docs but I see it now

#

I can probably use that as a value template

#

I'll have a play around - thanks 🙂

silent barnBOT
lime olive
#

oops

orchid oxide
#

What are the parameters value and default here: as_timestamp(value, default)

I'm trying convert Now() to a Unix timestamp and i don't know which one that is and what the other one is supposed to be

marble jackal
#

now() would be the value then, and the default would be a default in case it is not possible to convert the value to a timestamp

#

as_timestamp(now(), 0)

#

as_timestamp('this is a string', 'hello') would return hello

orchid oxide
#

thanks

#

its not possible to add comments to automations, is it

hard garnet
#

I'm trying to make a binary sensor to read out if the garage door has been used in the past # seconds. Unfortunately I can't use the "last_change" thing because that generates a lot of false positive. How do I format it so it focuses on specific states like "open" and "closed"?

inner mesa
inner mesa
hard garnet
orchid oxide
#

if i had a note, will it show up in step details? i'd like the step to show me one of the variables used, for debugging purposes

inner mesa
#

I'll settle for one that can just tell me if the garage door's state has been "open" in the past # seconds

orchid oxide
#

also can i add variables at the start of the automations yaml, and have it use them throughout?

inner mesa
#

that should be a simple state trigger with for: '00:00:05'

#

but if it's flipping state to other things, that's going to cause problems. Hence my suggestion to make a template sensor that reflects exactly the state you want, and use that

clever fable
#

Can someone help me I know this is super simple but templates baffle me. I am trying to set a date time sensor to the current date

#
data:
  date: {{ now().day }}
target:
  entity_id: input_datetime.last_hair_cut```
#

This isn't working its just what I have at the moment

charred dagger
#

Try date: "{{ now().day }}"

inner mesa
#

The first rule of templates is...don't talk about templates. And always surround single line templates in quotes.

clever fable
#

LOL thanks @inner mesa really appriate it.

#

And @charred dagger

hard garnet
inner mesa
#

a binary template sensor with this:

charred dagger
#

It should start and end with a quote at least.

inner mesa
#

{{ is_state('sensor.whatever', 'open') }}

clever fable
#

Ok hate to beat a dead horse to death but uhhhh still not working??? This is what I have

data:
  date: "{{ now().day }}"
target:
  entity_id: input_datetime.last_hair_cut```
inner mesa
#

and you can even add delay_on: 5 or whatever to that if you only want it to be true if it's been that way for x seconds

hard garnet
#

Thanks man

clever fable
#

Ok does that mean I need to interpret that into an actual date?

inner mesa
#

all in the docs

#

if you just want a number, use an input_number

charred dagger
#

Note to self: Check what it takes to make date: now valid for that service call.

inner mesa
#

yeah, I feel bad for others and often myself when needing to figure out how to format a datetime using a template to get it into a usable format

#

we really need a non-template way to do normal things

#

the easiest way to just get today's date into an input_datetime is maybe with this:

data:
  timestamp: "{{ as_timestamp(now()) }}"
clever fable
#

I needed strftime in there.

#

date: '{{ now().strftime(''%Y-%m-%d'') }}'

inner mesa
#

that's because you used "date: "

#

was trying to avoid the string nonsense

clever fable
#

That would be great @inner mesa but just to make it clear I'm grateful for the people who take the time to develop and support what we have.

marble jackal
#

now().date() instead of now().day

inner mesa
#

oh, hey, that formats it properly

#

still, I try to avoid anything that relies on specific string formatting if I can

marble jackal
#

But it would be nice if we could simply input now as @charred dagger suggested

orchid oxide
#

can i do

condition: state
entity_id: light.fan_lights_group
attribute: brightness
state: {{is not '79'}}```
#

or != 79

#

or something of the sort

inner mesa
#

you'll get a not: directive in the upcoming 2022.5, but you can use this in the interim:

condition: template
value_template: "{{ not is_state_attr('light.fan_lights_group', 'brightness', 79) }}"
hard garnet
#

how do you put yaml code in that box in discord

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

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

inner mesa
#

It's pretty universal now. Slack supports it, too

hard garnet
#

I'm trying to set up template sensors but as soon as I create more than one, my YAML editor says "duplicate key" next to template

#
template:
  binary_sensor:
    - name: "occupancy patio"
      state: >
        {{((((as_timestamp(now()) - as_timestamp(states.binary_sensor.patio_contact_sensor_contact.last_changed)))) < 300) }}

template:
  binary_sensor:
    - name: "occupancy button"
      state: >
        {{((((as_timestamp(now()) - as_timestamp(states.sensor.aqara_button_action.last_changed)))) < 300) }}
inner mesa
#

right, you can't have duplicate keys

#

luckily, you don't need them

hard garnet
#
template:
  binary_sensor:
    - name: "occupancy patio"
      state: >
        {{((((as_timestamp(now()) - as_timestamp(states.binary_sensor.patio_contact_sensor_contact.last_changed)))) < 300) }}

    - name: "occupancy button"
      state: >
        {{((((as_timestamp(now()) - as_timestamp(states.sensor.aqara_button_action.last_changed)))) < 300) }}
#

Now it says "incorrect type. expected "array".

inner mesa
#

you're not following the example

#
template:
  - binary_sensor:
      - name: "Has Unavailable States"
        state: "{{ states.sensor | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"
hard garnet
#

yeah I don't understand the example other than the fact that I don't need template and sensor for each new one

inner mesa
#

it's right - you need to provide an array

#

you have

#
template:
  binary_sensor:
#

the example has

#
template:
  - binary_sensor:
hard garnet
#

ah

inner mesa
#

the first says that template is a dict, and the second says that it's an array/list

orchid oxide
#

this is evaluating false, even though i have the template tool open and its evaluating true there

https://dpaste.org/RaoWJ

#

step details say

conditions/2
Executed: April 28, 2022, 7:18:04 PM
Result:
result: false
entities:
  - sensor.light_sensor_illuminance
  - light.fan_lights_group```
#

i have the exact same thing plugged into the template editor and it say true

inner mesa
#

where did you put the Jinja code in the link you posted?

#

the quotes are almost certainly misplaced

orchid oxide
#

where in the automation? right below 2 other conditions

inner mesa
#

you just provided a bunch of Jinja code

orchid oxide
#

its a condition within the action section, if thats what youre asking. i can post the whole thing if thats what youre asking, its a bit messy..

inner mesa
#

without knowing what's actually returning "false", I can't help much

orchid oxide
#

the code i posted was the section thats returning false. ill paste the whole step config

silent barnBOT
inner mesa
#

quotes only belong around single-line templates

orchid oxide
#

got it, my bad. thanks

inner mesa
#

np, I wanted to see the context to make sure I was right without guessing

hard garnet
#

Trying to write a template so that it returns "true" if at least one of these three conditions returns true:

#
{{ is_state('binary_sensor.occupancy_button', 'true') }}
{{ is_state('binary_sensor.occupancy_garage_door', 'true') }}```
orchid oxide
#

its still evaluating false. i moved it to the condition section now, so this is the whole step config https://dpaste.org/fNQPr

hard garnet
#
or
{{ is_state('binary_sensor.occupancy_button', 'true') }}
or
{{ is_state('binary_sensor.occupancy_garage_door', 'true') }}```
inner mesa
#

no

#

it's one template

#
{{ is_state('binary_sensor.occupancy_patio', 'true') or
   is_state('binary_sensor.occupancy_button', 'true') or
   is_state('binary_sensor.occupancy_garage_door', 'true') }}
#

just like you're writing a sentence

hard garnet
#

ah sweet

orchid oxide
#

might have fixed my problem

inner mesa
#

I would do:

#

{{ state_attr('light.fan_lights_group', 'brightness') != (bright*2.55)|round) }}

orchid oxide
#

wait, actually i think that did it

inner mesa
#

it's probably trying to do a string comparison or something silly like that

orchid oxide
#

actually, it didnt work..

inner mesa
#

testing for equality with floating point numbers is usually a bad idea, anyway

orchid oxide
#

yeahh...idk why it wont work

#

i wish it showed me the output instead of just saying false

#

oh well, guess ill jsut remove it for now. maybe itll work better when "not" is available in the full release

inner mesa
#

I think you'll be better off with > or < than == or !=

#

and you can always display the components and result of the calculation with a persistent_notification to see what they really are

orchid oxide
#

ok well so far ive figured out that > and < both are still false, so theres somethings wrong

#

i dont really get this. the peristent notification shows them as not equal 176 and 191, but the template sees the equation as false

lime olive
#

Hi all,

I'm trying to build an automation that will trigger when the garage door has been "forgotten" open.

Sensors in the garage:

  • Espresense that detects the wife's or my phone
  • Motion sensor
  • Garage door reed switch

Conditions of the automation would be that we haven't been in the garage for 15mins

#

I'm confused over how I would build this. If the garage has been open for 14 mins and I go in to get something, I don't want it to close.
So every time we go into the garage, the trigger has to be reset

Here are the sensors and states:

  • binary_sensor.garage (garage door - on/off)
  • binary_sensor.garage_motion4_occupancy (motion sensor on/off)
  • binary_sensor.rani_or_yara_in_garage (on/off) - Based on phone BLE presence, either phone within range will turn it on
marble jackal
analog nova
young shadow
#

is it possible to have a jinja as the result of a jinja if?

{% if value_json.cmd == "rx" %}
{{ value_json.data }}
{% endif %}```
#

this would be an mqtt sensor, that is receiving a json on the proper mqtt topic

young shadow
#

figured out, value_template: accepts the template above

mighty ledge
mighty ledge
analog nova
#

@mighty ledge well, the only thing that I know/can say is that because it is a proprietary field, I am trying to map it in the notify service config but I am not fully sure how to do that. WHat I need to basically say is "this field should hold a json payload.

From the docs:
Sets the post props, a JSON property bag for storing extra or meta data on the post.
Mainly used by other integrations accessing posts through the REST API.
The following keys are reserved: “from_webhook”, “override_username”, “override_icon_url”, “override_icon_emoji”, “webhook_display_name”, “card”, and “attachments”.
Props card allows for extra information (Markdown-formatted text) to be sent to Mattermost that will only be displayed in the RHS panel after a user selects the info icon displayed alongside the post.

#

they also provide an example with

{
  "channel": "town-square",
  "username": "Winning-bot",
  "text": "#### We won a new deal!",
  "props": {
    "card": "Salesforce Opportunity Information:\n\n [Opportunity Name](http://salesforce.com/OPPORTUNITY_ID)\n\n-Salesperson: **Bob McKnight** \n\n Amount: **$300,020.00**"
  }
}
thorny snow
#

https://imgur.com/a/ZpncZHh I am trying to produce a template which can sense when a charger has <.1A for a particular amount of time, but it occasionally spikes above that value. Any suggestions on how to accomplish this? Maybe an average for X amount of minutes?

#

You can see how variable the charge acceptance is when you zoom in....

inner mesa
thorny snow
#

I looked at statistics, but I keep seeing "Average sensor has been built in since XYZ" when I try to search for help

#

Is this because statistics has the "window", since I am averaging the same sensor?

inner mesa
#

I'm not sure what you mean. It seems like providing a max_age and appropriate state_characteristic (like the default of 'mean') would be enough

#

And the sensor you want to monitor, of course

thorny snow
#

So I need 2 sensors.... one for the mean, and one for the binary of that when it's <.1A??? Since the Max_age is 5 minutes, the binary doesn't really need a time-based template??

inner mesa
#

you'll have the sensor that's reporting the current measurement and a sensor that provides a statistical analysis of the first one. You can use the latter directly in an automation as a trigger or condition if you like

thorny snow
#

Ok, I made the mean sensor, and now I must have the formatting wrong?

#

{{ states('sensor.house_battery_current_mean') < '-.1' }}
{{ states('sensor.house_battery_current_mean') }}

False
-0.08

#

Okay this is interesting.. my charging is a highly negative number, but my discharging is a positive number...

#

-.08 is more positive than -.1, so it's false.

#

Gonna have to put more logic into this

inner mesa
#

states are strings, and turning the compared value into a string isn't going to help 🙂

#

you want this comparison:

thorny snow
#

WHen I flip the comparator, it is true though

inner mesa
#

{{ states('sensor.house_battery_current_mean')|float < -0.1 }}, but perhaps you do still need to think about the logic you want

thorny snow
#

OH.. float that.. good point

inner mesa
#

Ok, maybe there's some casting logic going on in the background. But better to be explicit

thorny snow
#

LOL now it's not happy: TypeError: '<' not supported between instances of 'float' and 'str'

#

With: {{ states('sensor.house_battery_current_mean')|float(0) < '-.1' }}

#

I thought ' was for numbers and " for strings in my '-.1'

#

Its's now calling my -.1 a string?

marble jackal
#

Everything between quotes is a string

#

There is no difference in how single or double quotes are handled. Just remove the quotes around the number

thorny snow
#

{{ states('sensor.house_battery_current_mean')|float(0) < -.1 }} gets me TemplateSyntaxError: unexpected '.'

#

I quoted due to this error

#

in my -.1

inner mesa
#

please, just use what I gave you

#

I made it 0.1 on purpose

thorny snow
#

Ahhh.. I missed that detail

#

Thank you!

orchid oxide
#

last night it was giving me values that should show true, ie brightness is lower than command to set brightness, but it was still evaluating false

calm burrow
#

Hello, I have an automation with a condition that uses this template_value: {{ (now().timestamp()) >= (state_attr("input_datetime.open_blinds_phone_alarm", "timestamp")|int + (16060)) }} . Since the last update I get an error on the condition (template value should be a string for dictionary value @ data['value_template']. Got None). Even state_attr("input_datetime.open_blinds_phone_alarm", "timestamp") evaluates to none, but the helper is available and has a value. In the template editor it works as expected. Did I miss a deprecation?

inner mesa
#

You need to surround your template in quotes

#

And it's value_template

calm burrow
#

condition: template
value_template: >-
'{{ (now().timestamp()) >=
(state_attr("input_datetime.open_blinds_phone_alarm", "timestamp")|int +
(16060)) }}'

#

that was a typo

inner mesa
#

Well, not if you're using a multi line template

#

That wasn't what you posted first

calm burrow
#

lol, it auto generated that 🙂

inner mesa
#

You have quite a lot of unnecessary parentheses

calm burrow
#

I know, it was for visual grouping, that's all

#

So, I tried to change it to the next:
condition: template
value_template: '{{ now().timestamp() >= state_attr("input_datetime.open_blinds_phone_alarm", "timestamp")|int + 16060 }}'

#

without any luck. Same error

inner mesa
#

what error, exactly?

#

please format the YAML properly:

calm burrow
#

template value should be a string for dictionary value @ data['value_template']. Got None

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

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

calm burrow
#

The 'input_datetime.open_blinds_phone_alarm' is a helper, has a datetime value

inner mesa
#

seem unlikely that you'd still get that same error

calm burrow
#

I know, it worked till recently and is still working in the template editor

#

I even recreated this on another instance

inner mesa
#

not sure what to tell you

calm burrow
#

Actually now I'm trying other things and whatever I enter in a condition template, It gives me the error 🙂

inner mesa
#

your problem was clearly the quotes, but you could very well have others

calm burrow
#

even

condition: template
value_template: '{{ now().timestamp() }}'
#

The quotes shouldn't be the problem. That was from copying it from the value template field. I wasn't in yaml mode when I copied the first text. I wanted to post a screenshot, but I don't think I have the rights to do so

marble jackal
#

If you are using the test button for the condition in the GUI, that doesn't work for template conditions

#

It gives an error, quite similar as the one you are posting 😅

#

It's not fixed in the beta yet

calm burrow
#

ah, that could explain the error here, but on the other end, the condition is skipped in my automation. I want my blinds to open 1 hour after my phone alarm sets. The last couple of days they open before my alarm sounds (the automation is also dependend on the height of the sun)

marble jackal
#

.share the whole automation

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

calm burrow
#

ok

marble jackal
#

Oh, and you said the condition is skipped. You are not pressing the RUN ACTIONS button in the Automation section in the GUI right? Because, in that case only the action part is performed, and conditions are skipped

silent barnBOT
#

To test an automation there's three stages you can follow. Testing the action, the condition and action, and the whole automation:

  1. Use Configuration -> Automations to find the automationand then push Run Actions. If this fails your problem is in the action: section, and details should be found in your log file
  2. Use Developer tools -> Services and call automation.trigger on the automation with skip_condition: false. If the first passes but this fails then the problem is in your condition: block
  3. Use Developer tools -> States to find the trigger entity, click the name, then change the state (at the top) to something that'll trigger the automation before pushing Set State. If this fails then the problem is with your trigger: section, or the automation is turned off (you can check that in Developer tools -> States).

You can also see this section in the docs and with HA 2021.4 onwards debug automations.

calm burrow
#

I can't upload the file. And no nitro account for copy paste.
No, I didn't use run actions. This automation stopped working right. It did work as expected before :). I used the TEST button to check what was wrong.

#

part 1```