#templates-archived

1 messages · Page 76 of 1

mighty ledge
#

you just want to create a text file?

#

with json?

unkempt hamlet
#

nah i didnt read it.

marble jackal
#

Better just use commas between the strings (without spaces)
Like a,b,c,d,e,f,g

{{ states('input.text.blah').split(',')[now().weekday()] }}

fiery umbra
fiery umbra
#

Hope this is ok, but I'm re-posting my question because it got converted and is difficult to read.
I'm trying to create a script that will set disable manual control of my lights, but not in certain areas based on other conditions. I have a template that returns the values correctly, but when I add it as a part of the script I get a message that says it's not a list that is being returned. I have attempted to follow the formats I've found in the docs and on the forums. Do I need to set a variable and return that? Or is there a cleaner way of doing this?

#
  sequence:
    - service: adaptive_lighting.set_manual_control
      data:
        manual_control: false
        entity_id: "{{repeat.item}}"
  for_each: >
    {% for switch in expand(integration_entities('adaptive_lighting')) if state_attr(switch.entity_id, 'manual_control') != None %}
      {% if not is_state_attr(switch.entity_id, 'manual_control', [])%}
        {% if switch.entity_id != 'switch.adaptive_lighting_basement' or (is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off')) %}
          {{ switch.entity_id }}
        {% endif %}
      {% endif %}
    {% endfor %}```
primal copper
#

I'm looking for some advice on how to handle a automation/template I'm hoping to add. I have all of our families calendars integrated into HA, but I don't want to have a big old calendar card on the dashboard because I'm not too fond of the extra stuff we don't need. What I'm wanting to do is run an automation each morning at 00:00 to get the calendar events for the day and put them into a list/array that can be access with a template on the front end. I have the automation part down, I just don't know where to store the data once I have it. I tried a template helper, but it doesn't allow for multiple values -- ideally I'd like a list output, ie: "Mom has 2 events today\n11:00am Pickup Kids\n1:00pm Lunch" and have only that information output on a dashboard/card -- any ideas on the best way to do this?

lofty mason
mighty ledge
#

you just gotta add the if statement for the guest mode and movie mode

fiery umbra
mighty ledge
#

your condition logic is only needed at the whole level

#

you can reject 'switch.adaptive_lighting_basement'

#
{% if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') %}
  {{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | reject('eq', 'switch.adaptive_lighting_basement') | list }}
{% else %}
 []
{% endif %}
fiery umbra
#
{% if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') %}
  {{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | reject('eq', 'switch.adaptive_lighting_basement') | list }}
{% else %}
  {{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | list }}
{% endif %}```
Ok so I can do this. I'll try it out. Is there a way to capture the output of {{}} statements?
mighty ledge
#

oh that's what you mean?

#

no, do this

fiery umbra
#

like:


someList =   {{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | list }}
{% if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') %}
{{ someList | reject(conditions) }}
{% endif %}```
mighty ledge
#
{% set remove = ['switch.adaptive_lighting_basement'] if is_state('input_boolean.guest_mode', 'off') and is_state('input_boolean.movie_mode', 'off') else [] %}
{{ integration_entities('adaptive_lighting') | reject('is_state_attr', 'manual_control', None) | reject('is_state_attr', 'manual_control', []) | reject('in', remove) | list }}
primal copper
sullen osprey
#

Hi, im trying to check if now are between 2 date and they give me True but supposed to be false {% from 'easy_time.jinja' import month_day %} {{ month_day(9, 11) | as_datetime > now() or now() < month_day(9, 30) | as_datetime }}

fiery umbra
mighty ledge
mighty ledge
mighty ledge
sullen osprey
#

Oh ok ! thanks !

fiery umbra
#

Is this something that we can always do? Or are there certain builtins that work with it and others that don't?

mighty ledge
#

an in-line if statement is <pass value> if <test> else <fail value>

#

so if your test is passing, you'll be rejecting ['switch.adaptive_lighting_basement'] entity_ids

#

otherwise you don't reject anything

fiery umbra
#

Ok, I think I understand now. we are setting remove to either [with value] or [] at runtime, not passing remove as is written to the function

#

I think I was confused on exactly when the evaulation was happeing.

red badge
#

is there any good way do access historic data of an entity from a template? i've got all changes recorded, so i could access them via the API and put them into variables somewhere else in an automation, so i have a workaround if needed, but would be nice if i could jsut say "hey give me this entity state from a different date"

mighty ledge
#

no

red badge
#

unfortunate. alright, will have to work my way around that limitation then

floral shuttle
#

so I confess being ashamed to ask, but what unit of measurement (or device_class for that matter) should I give a lightning counting template sensor to show a graph...... I did have a fake unit before ( ), and took that out again, but now have the wrong display in the more info

#

or should I simply state 'strikes' and be done with it, the flash works but seems really too un HA like

#

tbh, I was surprised we dont have a device_class: count, or number/numeric, but maybe I am overthinking now

bronze prawn
#

So doing a device_entities on the id 6c5687a52bab3a6380682cc904cd7f0b gives me:
['sensor.thinksmart_lr_wake','sensor.thinksmart_lr_stt','sensor.thinksmart_lr_intent','sensor.thinksmart_lr_tts','switch.thinksmart_lr_mic','sensor.thinksmart_lr_mic']
These are the sensors for one of my Stream Assist satellite devices. In a custom sensor device I have a sensor with attribute that matches one of these in the list:

'sensor.assistsat_viewlrthinksmart' attribute 'mic_device: sensor.thinksmart_lr_stt'

#

Each one of my satellite devices (eg sensor.assistsat_viewlrthinksmart) are in a group called group.viewassistsatellites .

What I'd like to do is have a template that searches that group for any member who's mic_device attribute matches the value from the device_id I receive back from the Assist response and return that member from group.viewassistsatellites

#

Challenging

lofty mason
bronze prawn
#
{% for sat in expand('group.assist_satellites') %}
  {{ sat }}
{% endfor %}```
produces:
```<template TemplateState(<state sensor.assistsat_audio_masterbath=; display_device=, browser_id=, view_timeout=, title=Annoucement, message=Washer is done, message_font_size=4vw, image=, timer=, alarm=, cycle_view=, type=audio_only, mode=normal, mic_device=binary_sensor.assistsatmasterbath_assist_in_progress, mediaplayer_device=media_player.assist_sat_master_bath_2, do_not_disturb=False, friendly_name=AssistSat_Audio_MasterBath @ 2024-05-22T07:33:42.510670-05:00>)>```
and a few more like this
#

In the loop I'd like to grab the value for mic_device, convert that entity to the device id then do an if statement that compared the devid variable I'm setting in the first line to that value. If true, it would return the 'sat' value name.

I think I can do the logic, but from the output above, how do I pull the mic_device value and the name (eg sensor.assistsat_audio_masterbath)?

inner mesa
#

{{ sat.entity_id }}
{{ sat.attributes.mic_device }}

bronze prawn
#
{% set devid = "6c5687a52bab3a6380682cc904cd7f0b" %}
{% for sat in expand('group.assist_satellites') %}
  {% if device_id(sat.attributes.mic_device)  == devid %}
    {{ sat.name }}
  {% endif %}
{% endfor %}

Thanks for the help. Got it working like this

plain magnetBOT
#

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

marble jackal
#

@willow wing {{ states.climate | selectattr('entity_id', 'search', '_klimaanlage$') | selectattr('state', 'in', ['auto', 'heat', 'cool', 'dry']) | list | count > 0 }}

charred zodiac
#

Hello everyone, I have a '3-way' type fan in my apartment. One is high, other is low. There are no such zigbee modules to handle this so I bought one for a curtain, so 'closing' is High, 'opening' is Low. However the position property of this curtain module in home assistant is messing things up. I do not know how it decides at what position the 'curtain' is, but once it goes to position closed, it stops, or if it arrives ad the fully open position 100, it also stops. However if you are already at position 100, and you start opening, it just keeps running (which I want).

Is there a way to just cut out the position property out of this template completely?

willow wing
#

Thank you @marble jackal

charred zodiac
# crimson lichen you can find SonOff iFan04

unfortunately it is too big, it has to be put into a standard wall socket, or at least behind the button. Can i somehow override in home assistant the 'code' behind the ifan04?

crimson lichen
#

it can put inside ceiling fan top cover and use normal switch for turnon power and control on HASS

crimson lichen
charred zodiac
hallow plover
#

inovelli makes a really nice zigbee ceiling fan controller that is smaller than the ifan04

frail dagger
charred zodiac
# frail dagger This is not possible. The cover position processing is hard coded. You're using ...

how about cover position 'time'. It takes x seconds from position 0 to position 100. I can kind of manipulate it so it will take 30 minutes or so. The fan is an inbuild exhaust fan on the roof so it should not run that much.

I mean when we are talking about an actual curtain opening or something, what if the curtain is very long or short, there must be a way to callibrate this right? I can 'misuse' this function.

I may order one of those fan controllers but i'd love to make it work as is.

frail dagger
charred zodiac
frail dagger
acoustic arch
#

instead of making 10x the same notification i would like to learn to make a more smart way. Is there a way to insert a variable into:
{{ state_attr('sensor.gas_station_euro95_lowest_price_1','brand') }}
say lowest_price_1 needs to be a a variable ranging from 1 to 10
possible?

marble jackal
#

not sure what you are trying to achieve here

#

what do you want as output from the template?

#

al list with all brand attributes of all those gas_station_euro95 sensors?

acoustic arch
#

A script with input fields. So I choose one when calling the script and use that selection as variable inside a sensor

#

Then I can make a notification with the right sensor attributes

charred zodiac
marble jackal
acoustic arch
#

Thx

upper matrix
#

When I filter a bunch of devices example {% for plant in states.plant | insert here %} is there someway to filter based on when the last sensor connected to the device was updated?

inner mesa
#

something like this?
{{ states.sensor|sort(attribute='last_updated')|map(attribute='entity_id')|list|last }}

#

that gives me the entity_id of the sensor that was updated most recently

upper matrix
#

Thanks the last_updated seems to be what i need 🙂

inner mesa
upper matrix
#

Is there someway to filter so that i only get plants that have been updated the last day?

mighty ledge
#

from midnight...

{% for plant in states.plant|sort(attribute='last_updated', reverse=True) | selectattr('last_updated', '>=', today_at()) %}
#

for last 24 hours...

#
{% for plant in states.plant|sort(attribute='last_updated', reverse=True) | selectattr('last_updated', '>=', now() - timedelta(days=1)) %}

upper matrix
#

Thanks that saved me alot of time 🙂

timid wind
#

Hi, i have a automation for play a text with alexa_media_player depending on a brightness value of a light. Everything is working as expected. Now i want to convert the Automation into a blueprint. i read the example and could successfully convert it to a working blueprint. i have one thing left that i could not figure out by myself. i have a !input trigger_value witch take the value in %. As example 3%. now the created automation should only do the action when the brightness of the entity is 3%. But the attribute value of brightness is in decimal 8 (3% = 8). i want to add a way of conversion the 3% into decimal and compare it in the conditions with the value of the attribute brightness of the entity. i think i need to convert the !input trigger_value into a template variables first and then multiply with 2.55. after that i need so condition. i found examples in the docs but can't figure it out by myself

mighty ledge
#

post what you have

timid wind
mighty ledge
#

so you want to use !input alexa_trigger_value in your turn_on service call?

#

or...

acoustic arch
timid wind
#

i want something like:

condition:
( when !input alexa_trigger_device.brightness = !input alexa_trigger_value * 2.55)

mighty ledge
#
condition: template
value_template: >
  {{ trigger.to_state.attributes.brightness != trigger_value * 2.55 }}
timid wind
#

so add trigger to variables. but why != should it not be ==?

mighty ledge
#

if you wonly want it to fire at the value then ==

timid wind
#

thx, i give it a try

plain magnetBOT
#

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

mighty ledge
#
service: notify.mobile_app_mob_xx
data:
  title: Gas
  message: Gases
  data:
    tag: brandstof_prijzen
    actions: >
      [{%- for i in range(1, 11) %}
          {%- set entity_id = 'sensor.gas_station_euro95_lowest_price_' ~ i %}
          {%- set lat = state_attr(entity_id, 'latitude') %}
          {%- set lon = state_attr(entity_id, 'longitude') %}
          {%- set uri = 'https://www.google.com/maps/search/?api=1&query=' ~ lat ~ ',' ~ lon %}
          {{ dict(action="URI", title=state_attr(entity_id, 'station_street'), uri=uri) }},
       {%- endfor %}]
alias: stuur navigatie naar xx
enabled: true
acoustic arch
#

thank you. and how can i call just one, for example 6 when using a variable as input?

mighty ledge
#

just make the 11 a variable

#

otherwise you'll need to provide more context

acoustic arch
#
{{state_attr('sensor.gas_station_euro95_lowest_price_[x]','station_street')}}```
like this-ish
#

but this doesnt work

mighty ledge
#

look at what I have

#

then compare it to what you wrote

acoustic arch
#

cool. thats completely new syntax for me

#
{{state_attr('sensor.gas_station_euro95_lowest_price_' ~ x,'station_street')}}```
works
#

thx

timid wind
# mighty ledge if you wonly want it to fire at the value then `==`

Thx for your help. it is working now.

variables:
trigger_value: !input alexa_trigger_value
trigger: !input alexa_trigger_device

condition:

  • condition: template
    value_template: >
    {{ trigger.to_state.attributes.brightness == ((trigger_value * 2.55) | round(0)) }}

i needed to add a round(0)

hidden cedar
#

Hi all, i have a problem with coloring the tile card depending on an entities' state.
from documentation / forum posts, I put together this code:

#
type: tile
entity: sensor.ladenetz_aachen
card_mod:
  style: |
    .tile {
      {% if states(config.entity)== 'Occupied' %}
        --tile-color: var(--rgb-red-color);
      {% elif states(config.entity) == 'Available' %}
        --tile-color: var(--rgb-green-color);
      {% else %}
        --tile-color: var(--rgb-blue-color);
      {% endif %}
    }
#

however, nothing changes with the card_mod added. the tile card still looks blue (like default), but the state is Available.
am I doing something wrong?

mighty ledge
#

are you sure your states are actually Occupied and Available? look in developer tools -> states page for the real untranslated states. @hidden cedar

hidden cedar
#

unfortunately yes:

Available options: Available, Unavailable, Occupied, Unknown

#

also, if I change the 'else' to e.g. red, the card still stays in default style

      {% else %}
        --tile-color: var(--rgb-red-color);
      {% endif %}

that's why I think it's a frontend problem and doesn't have to do with the exact state name

mighty ledge
#

it's not a frontend problem

#

you're using card mod, it's a problem with your config in some form.

#

rule out your selector first, then try other things.

#
type: tile
entity: sensor.ladenetz_aachen
card_mod:
  style: |
    .tile {
       --tile-color: var(--rgb-red-color);
    }
#

if that doesn't change your card to red, then your selector for the style is wrong, your variable is wrong, or your css tag is wrong

#

if it does, then your jinja is wrong

#

@hidden cedar ^

hidden cedar
mighty ledge
#

then it's not your code, it's your selector .tile, the field --tile-color or the variable --rgb-red-color

hidden cedar
#

in the HA core log, no error is shown. In my browser console there is a green 'CARD-MOD 3.4.3 IS INSTALLED'; i would suppose everything is set up correctly.

there is no log what exactly the selectors are doing (e.g. undefined), right?

mighty ledge
#

F12 may show you something, but it's unlikely. If you don't understand selectors, it's best to just search the forums for someone else who's done it already.

hidden cedar
#

thank you for pointing me in the right direction!

that here does it:

  style: |
    ha-card {
       --tile-color: red !important;
    }

for some reason, the '!important' is necessary, otherwise the color doesn't change at all. could be that I overlooked it out while experimenting because I didn't think it was so important (literally :D)

#

thanks again

lyric comet
hidden cedar
#

thanks for the explaination!

plain magnetBOT
#

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

cyan pendant
lofty mason
#

you're sure that's the right sensor? I would have expected it named "Garage Door State" (unless you already renamed it and gave it an icon)

cyan pendant
#

Do they have to be named the same?

#

The entity id looks correct

#

I did the trendy thing and asked chatgpt and it gave me the following:

template:
  - binary_sensor:
      - name: "Garage Door State"
        unique_id: "garage_door_state"
        state: >
          {{ is_state('binary_sensor.garage_door_outer_contact', 'on') }}

and that also doesn't seem to work

#

It also suggested to reload the YAML, so I went to the dev tools section and reloaded everything under 'YAML configuration reloading'

mighty ledge
#

not sure why it's not triggering for you but you're overly complicating that template

#
template:
  - binary_sensor:
      - name: garage_door_state
        unique_id: garage_door_state
        state: "{{ is_state('binary_sensor.garage_door_outer_contact', 'off') }}"
#

keep in mind, that what you're pasting needs to be put in configuration.yaml, not the UI

#

if you want to use the UI helpers, use just

{{ is_state('binary_sensor.garage_door_outer_contact', 'off') }}
#

templates are only the stuff between (and including) the {{ }}

cyan pendant
mighty ledge
#

no

cyan pendant
#

I guess that explains it then

#

Let me give it a go. Thanks for the help btw

mighty ledge
cyan pendant
#

Ahh

#

Gotcha

#

Let me give it a go

#

Thank you

cyan pendant
# mighty ledge

That works. I've been using HA for a while, but mostly for just simple automations that are configurable within the UI itself. But I wanted to start setting up some more complex stuff, so this is a good starting point. Thank you again!

#

And thank you too, @lofty mason!

tropic charm
#

👋🏻 i have finally (using python/appdaemon) managed to parse my battery/solar provider's site to get hourly energy info:
{'date': '2024-05-24T15:00:00', 'index': 22, 'pv_generation': 0.23, 'pv_serving_loads': 0.23, 'battery_serving_loads': 2.55, 'grid_serving_loads': 0.29, 'total_loads': 3.07, 'pv_export_to_grid': 0.0, 'battery_export_to_grid': 0.0, 'total_export': 0.0, 'pv_charging_battery': 0.0, 'grid_charging_battery': 0.0, 'total_battery': 0.0}
what is the best way to store that on an hourly basis in HA? i'm thinking of creating sensors for each, class energy, type measurement, unit kwh. is there a way to only take "one value" each hour? in case the script timing is off?

fossil venture
cyan pendant
fossil venture
umbral ridge
#

Hello...

#

I was sent here...

#

d_sellers1 — Today at 6:54 PM
@umbral ridge Try making one absolute value template entity and see if it is an issue with negative numbers. If that works, then the easy fix might be to wrap the bar-card with a decluttering-card and have it handle the absolute values so you don't have to make a ton of helper entities. I can look into that when I get home from work. ⁠templates can help with the helper entity.

#

Having issues with a bar card showing severity levels....it was suggested to make a helper to do absolute values as a test
Here is the bar card in it's current state...but I have no idea how to make a helper that shows absolute value
`type: custom:bar-card
entities:

  • entity: device_tracker.andrew_mug_warmer
    name: Andrew's Mug Warmer RSSI
    severity:
  • value: -100
    color: '#FF0000'
  • value: -80
    color: '#FFA500'
  • value: -60
    color: '#FFFF00'
  • value: -40
    color: '#00FF00'
  • value: 0
    color: '#0000FF'
    attribute: rssi `
tropic charm
tropic charm
hard sundial
#

Hi, i want to an display on my dashboard that shows how long its been between the previous and most recent trigger on an device if that makes sense. How would i do that? If its possible

red badge
#

{{ 14 * 1.609 | round(1) }} renders to 22.400000000000002.... is there anything sensible i can do about this? 😄

lofty mason
#

{{ (14 * 1.609) | round(1) }} ?

red badge
#

oh ffs, yeah that does it. i figured the * would bind stronger than the |

#

thanks

lofty mason
#

yeah jinja order of ops surprises me sometimes too

mighty ledge
#

Pedmas

#

Parenthesis exponents (division, multiplication) addition subtraction.

acoustic arch
#

i dont think anything is broken, but just to learn:
{{states('sensor.power_highest_peak_time_tomorrow')}} gives me 2024-05-27T10:00:00+00:00
So hour 10.

but using the same entity in this format i get hour 12. So why does this convert +2, my local?
{{ as_timestamp(states('sensor.power_highest_peak_time_tomorrow'))|timestamp_custom ('%H') }}

#

as_timestamp has build-in local conversion?

marsh cairn
#

timestamp_custom does use local is default

acoustic arch
#

thx!

marsh cairn
#

https://www.home-assistant.io/docs/configuration/templating/#time

Filter timestamp_custom(format_string, local=True, default) converts an UNIX timestamp to its string representation based on a custom format, the use of a local timezone is the default. If that fails, returns the default value, or if omitted raises an error. Supports the standard Python time formatting options.

acoustic arch
#

also in the docs!

acoustic arch
#
{{ now() | as_datetime }}```

The first is UTC, The second local (+2)
So how can i template this if NOW is before of after this sensortime (true/false)?
#

im tempted to just convert them to as_timestamp and do A>B...

#

but this set me on the wrong foot.

#

the Fes made me this the other day and works.

{{ now() >= alarm - timedelta(minutes=30) if alarm else false }}```

the sensor is also in UTC time but he is comparing NOW and the sensor straight away
#

so there is some magic here which accounts for the local conversion.. but where does this happen

marsh cairn
#

Datetimes have the timezone included

#

And timestamp is the UTC based UNIX timestamp

#

now() is already a datetime (with timezone data), which can be compared against another datetime

mighty ledge
#

As long as the object has a tz, the calc will be correct when comparing timezones

acoustic arch
#

Ok thank you both!

floral shuttle
#

how can we select/reject entities from devices with a certain manufacturer? I have this {% set actueel = states.sensor |selectattr('entity_id','search','_actueel') |map(attribute='entity_id')|list%} {{actueel}} but need to reject 'manufacturer','Fibargroup'

floral shuttle
#

could add a label and do {% set actueel = states.sensor |reject('in',label_entities('fibaro')) |selectattr('entity_id','search','_actueel') |map(attribute='entity_id') |list%} but do I have to?

inner mesa
#

is_device_attr, right?

bronze prawn
#
{{ sat.attributes.display_device }}
{% endfor %}```
I have a group of devices that have some attributes that point to other devices. This is the output from the above:

sensor.tabletmaster_browser_path
sensor.thinksmart_lr_browser_path
sensor.tabletfullkiosk_browser_path


I would like to be able to use the above as an automation trigger for when any one of these changes.  Is it possible to somehow pull those and determine if any have a state change?
bronze prawn
#

and if the answer is yes, I would also like to know which triggered which would be sat.name I'm assuming

mighty ledge
#

you'd need a template entity

bronze prawn
# mighty ledge you'd need a template entity

Correct me if I'm wrong, but can I provide a list from a template for entity_id that would replicate this?

platform: state
entity_id:
  - sensor.thinksmart_lr_browser_path
  - sensor.fire7hd_browser_path
  - sensor.tabletmaster_browser_path

Is the template entity you mentioned for determining which one of these changed?

vale osprey
inner mesa
#

What does it says if you put the template in devtools -> Templates?

#

My guess is that it created another entity called sensor.other_energy_consumed_2 or similar

vale osprey
#

no, there is only 1 entity, just checked again to make sure

#

Result type: string
sensor.

  • platform: template sensors:
    other_energy_consumed:
    friendly_name: "Other Energy Consumed (kWh)" unit_of_measurement: kWh value_template: >
    0.0
    This template listens for the following state changed events:
    • Entity: sensor.rcbo_fridge_freezer_energy_consumed
    • Entity: sensor.rcbo_main_energy_consumed
    • Entity: sensor.rebo_smarthome_energy_consumed
    • Entity: sensor.rcbo_solar_energy
#

Looks fine, no?

#

The value shouldn't be 0.0 ofc

inner mesa
#

But it is

vale osprey
#

found it

#

silly issue in the defined values

#

was referencing the wrong entities 🤦‍♂️

#

so it was always going to the else statement

#

let me try it in the helper

inner mesa
#

You should switch to the new template format and add a unique_id

#

And do a config check

vale osprey
#

in dev tools i'm getting a value of: 385.57, which is fine. but still doesn't work in the helper

#

I added the unique id as well

#

Before saying the helper im getting this notification:

Sensor None has device class 'energy', state class 'total_increasing' unit 'kWh' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'sensor: - platform: template unique_id: "ca0f8dd3-1ad4-4ccb-85ba-045a3745c30a" sensors: other_energy_consumed: friendly_name: "Other Energy Consumed (kWh)" unit_of_measurement: kWh value_template: > 385.58' (<class 'str'>)```
#

And when I enter the helper, in the modal there is this info box on top:
This entity is no longer being provided by the template integration. If the entity is no longer in use, delete it in settings.

lofty mason
#

ahhh you pasted the yaml in the template UI form

inner mesa
#

Put just the template in there

vale osprey
#

not sure I get what you guys mean, sorry quite new to templating

inner mesa
#

You copied all the YAML into the template box

#

You know which part is the template?

#

Did you write that?

vale osprey
#

got it

#

works now. Thanks 🙂

#

coz the template stuff is already handled by the helper UI right.

lofty mason
#

I was thinking the other day about proposing a warning to the template selector. Would it be enough to just look for the string template: or platform: template in the input? Or would those strings ever be likely to appear in some valid template.

inner mesa
#

It could do what devtools -> Services does and parse what you type in the text box

#

I don't think it's necessary, though

#

You should know what the template part is. It could explain that there

vale osprey
#

if you see it from a dev perspective yes 🙂

#

for 'not so technical people' I feel there is a big gap between what the UI allows you to do to the endless possibilities of templating

#

if HA manages to bridge that gap, it would be the best thing ever done

inner mesa
#

It does that by trying to avoid non-technical people from having to write templates

vale osprey
#

yes, and it improve a lot since it started

inner mesa
#

In any case, I'm sure that box could be made more friendly for this case

marble jackal
lofty mason
#

also maybe state: and sensor:

#

(value_template covered by template)

inner mesa
#

I would just add some explanatory text there that templates have {{}} or {%%}

marble jackal
#

would it be possible to somehow check if there is anything not between { and }

lofty mason
marble jackal
#

what would be a correct jinja template which isn't between curly brackets?

lofty mason
#

Can't it include extra characters? Like ${{ dollars }}.00

#

Like if you want the sensor value to be $100.00 from 100.

marble jackal
#

yeah, you're right

#

for a text based sensor that would work

#

didn't think of that

edgy umbra
#

How can i get a vertical list? my sensor have a attribute that shows like below but my template shows it as x, y, z.

  - y
  - z```
#

{{ state_attr('sensor.node_proxmox_containers_running', 'lxc_on_list') |list|join(', ') }}

marble jackal
#

the top one is a list in yaml

#

your output is a comma separated string

#

you could do:

{% for container in state_attr('sensor.node_proxmox_containers_running', 'lxc_on_list') -%}
- {{ container }}
{% endfor -%}
vale osprey
mighty ledge
bronze prawn
mighty ledge
#

You output the last updated or last changed to the state and use that as the trigger. Make an attribute that outputs the last changed entity id

#

You can add a second attr for state

bronze prawn
mighty ledge
#

You’ll get both separate triggers

#

They won’t happen on the same microsecond

#

And if they do, you can choose the first or last

#

Or make it a list

bronze prawn
#

Okay. Thanks for the tips. I'm not sure my brain will guide my hands to type this correctly so I may put it off for v2.

inner mesa
#

I really feel like this could be made simpler in some way. It's a common request, and leads people to want to use a state trigger with a template-generated list

bronze prawn
bronze prawn
#

Can one of you tell me how to get "last updated or last changed" in template?

bronze prawn
#
{% for sat in expand('group.assist_satellites') %}
  {% set browserpath = sat.attributes.display_device %}
  {{ browserpath }}
  {{ states(browserpath) }}
{% endfor %}

Forgive me. I know this is far from correct. I can't figure out the syntax to get state.last_changed

inner mesa
#

Literally sat.last_changed

#

You have a state object, so follow the guidance at the link I posted

#

Just like you did with the attributes. Note that it's also in that list

bronze prawn
# inner mesa Literally sat.last_changed

Hmm.. So I may be misunderstanding but to recap, I have a group of custom sensor devices (group.assist_satellites). Each one of those has an attribute called 'display_device'. That attribute holds an entity_id of a different device. I am trying to get the last_changed for that device referenced by the group member. Convoluted.

#

sat.last_changed is actually the template device containing the reference to the device I'm interested in but not the actual device so it may go unchanged while the device I'm interested in chages. That's why I'm setting that variable browserpath . How do I get the last changed on that guy is what I'm after

inner mesa
#

states[browserpath].last_changed

bronze prawn
inner mesa
#

I can only go on what you've told me

#
{% set browserpath = 'sensor.aarlo_battery_level_family_room' %}
{{ states[browserpath].last_changed }}
#

-> 2024-05-26 23:58:26.355315+00:00

bronze prawn
# inner mesa I can only go on what you've told me

Understood. Apologies.

{% for sat in expand('group.assist_satellites') %}
  {% set browserpath = sat.attributes.display_device %}
  {{ browserpath }}
{% endfor %}

this produces this:

sensor.tabletmaster_browser_path
sensor.thinksmart_lr_browser_path
sensor.tabletfullkiosk_browser_path
#
{% for sat in expand('group.assist_satellites') %}
  {% set browserpath = sat.attributes.display_device %}
  {{ browserpath }}
  {{ states[browserpath].last_changed }}
{% endfor %}

this produces the error I posted above

inner mesa
#

Not sure what to tell you. You can test this in devtools -> Templates

#

{{ states['sensor.tabletmaster_browser_path'].last_changed }}

bronze prawn
#

Right. That's where I'm doing it

#

ah ok.

inner mesa
#

just like I did

bronze prawn
#

Alright. So manual entry like that gives me a time. I guess it doesn't like something about the way the attribute return value of that entity is formatted.

#

display_device: sensor.thinksmart_lr_browser_path

This is how that attribute shows up for one of the group members.

#

I can copy paste in your example above and it works fine. I cannot use the states[browserpath].last_changed though.

#

So this works:

{% for sat in expand('group.assist_satellites') %}
  {% set browserpath = 'sensor.thinksmart_lr_browser_path' %}
  {{ browserpath }}
  {{ states[browserpath].last_changed }}
{% endfor %}
#

Am I doing something wrong in the way I am defining the variable in the version that doesn't work?

#
{% set browserpath = sat.attributes.display_device %}

I think this assignment is the problem

bronze prawn
#

I'm going up and down with this and I can't figure out why that line breaks things, if it does break things. All seems well but I get that error

inner mesa
#

no idea

#

this works fine for me:

{% for sat in expand('group.downstairs_lights') %}
  {% set browserpath = sat.entity_id %}
  {{ browserpath }}
  {{ states[browserpath].last_changed }}
{% endfor %}
#

my guess is that one of the entities doesn't have that attribute, or it's empty or something

inner mesa
mighty ledge
#

He has an item in his list that’s an empty string

inner mesa
#

Right

#

Would be easy to know

#

Nothing much I can do with the info available

rich moss
#

if you are writing a template that incorporates a problem binary sensor using is_state would you use 'problem' or 'on' or even 'On'? if that makes sense

frail dagger
rich moss
#

i mean device_class problem

mighty ledge
rich moss
#

got it

#

also if using configuration.yaml to write a binary sensor can you use delay_on: true?

#

oh i mean delay_on: 00:00:00

#

if thats even correct

inner mesa
bronze prawn
rich moss
#

Does the indentation of delay_on look right here? - binary_sensor: - name: Staff Entrance Light Left On All Night device_class: problem state: > {{ is_state('binary_sensor.staff_entrance_light_might_be_on', 'on') }} delay_on: 00:04:00

#

also can auto_off be used to automatically turn off at a given time. the doc says it "requires a trigger" but also says "how much time until" it turns off. If it could be triggered by a set time that would be cool

#

alternatively I could use an automation but it would be more elegent if i could write it into the templates especially since there will be quite a few

#

Im trying to understand what it means by requires a trigger.

#

ooo I just realised it makes no sense because it will turn off on its own anyway. Im trying to make an entity that stays on all day if a sensor state is on for 4 hours straight

bronze prawn
#

Confirmed what the problem is. I use the same config for all satellites and some do not have video displays. That's the ones causing the error. So I guess I need to add an if in there to check if the browserpath variable is not null before trying to pull the last_changed. Apologies for the headache

bronze prawn
#
{% for sat in expand('group.assist_satellites') %}
  {% if sat.attributes.display_device != '' %}
     {{ sat.name }}
     {% set browserpath = sat.attributes.display_device %}
     {{ browserpath }}
     {{ states[browserpath].last_changed }}
  {% endif %}
{% endfor %}

So adding in that check is what I needed. So now I can create the template sensor, set state to the last_changed value and store the sat.name as an attribute. I can then create an automation that triggers on the template sensor change and use the satellite name attribute to know which one needs attention.

#

Thanks for your patience. This should simplify things.

willow wing
#

Hey, can i give them sensor an alias?

  name: "Restabfall"
  details_format: "upcoming"
  date_template: '{{value.date.strftime("%d.%m.%Y")}}'
  value_template: '{{value.types|join(", ")}}{% if value.daysTo == 0 %} Heute{% elif value.daysTo == 1 %} Morgen{% else %} in {{value.daysTo}} Tagen{% endif %}'
  types:
    - Restabfall```
#

alias and friendly_name are not working, i wanna set for example an "ä" in the name

mighty ledge
hard vale
#

I seek some help regarding the following:
Have a template file for capacity tarif sensors.
These sensors should update every 15 minutes to see if the new quarter consumption is higher than the one before.
what i'm experiencing is that on restart of HA or impelenting a new YAML file the sensors lose their value and are reset to 0.
Code: https://dpaste.org/4gJeU

marble jackal
#

add availability templates for the first two sensors. Then this line {% if is_number(states('sensor.max_kwartierpiek_dag_in_kw')) %} will actually do something

#

because currently sensor.max_kwartierpiek_dag_in_kw will either be 0 or it will have the state you expect

#

oh wait, sorry, I misread (as the names are simliar)

hard vale
#

the sensor.elektriciteits_verbruik_15min is a utility meter which is resetted every 15 mins

marble jackal
#

you should let your trigger based template sensors refer to the current state in the else part, not to 0

hard vale
#

Than it will still refer to something wrong, since the value is not numeric according to the if statement

marble jackal
#

The value of that sensor should always be numeric

#

as it restores state after restart

hard vale
#

So in the else i just let it refer to it's own? I don't see the problem in the original code tho. Does the trigger gets activated on restart of the YAML config?

marble jackal
#

not sure

#

@mighty ledge do you know if time_pattern triggers are triggered after a restart?

mighty ledge
#

No idea. I don't believe so.

marble jackal
hard vale
#

Invalid config for 'template' at template.yaml, line 10: 'availablity' is an invalid option for 'template', check: sensor->0->availablity

hard vale
mighty ledge
hard vale
#

Indeed type in availability
the updated code is this: https://dpaste.org/YSDgi
still issues, one sensor is now not available (dag)
the other keeps at unknown (Maand)

mighty ledge
#

timepattern one will be unknown until it gets a state

#

as for the one that's not available, verify the source entities are available.

hard vale
#

Did a full restart for YAML
both sensors are now unknown

marble jackal
#

Wait 2 minutes

mighty ledge
#

/15 minutes means it will only update the state on 0, 15, 30, 45, minute mark

#

If you want it to update on restart, you need to add that trigger.

plain magnetBOT
#

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

marble jackal
#

Oh sorry, I mixed up, it should have been the other sensor

#

Without max

hard vale
#

Yes already fixed that part. now i adjusted the timeframe so it updated every minute but it seems like it is now not setting the source value in the sensor. The sensor stays at: 'Unknown'. Link to latest code: https://dpaste.org/vUiyd

hard vale
#

The original sensor where it should copy values from is updating good and correctly.

mighty ledge
#

icon has the wrong indentation

#

You should see an error in your logs about the value being non-numerical

#

and it's because icon has the wrong indentation

hard vale
#

Correct, i'm now testing with the template in development tools and it looks like 'this' is undefined.
when i put it to this it is giving me a value
{% set source = states('sensor.kwartierpiek_dag_in_kw') %} {% set current = states('sensor.max_kwartierpiek_dag_in_kw') %} {% if source | is_number and current | is_number %} {% if now().hour == 0 and now().minute < 15 %} {{ source }} {% else %} {{ [ source | float, current | float] | max }} {% endif %} {% else %} {{ current if current | is_number else source }} {% endif %}

mighty ledge
#

This will be undefined in the template editor

fickle sand
#

this is a local reference to the template sensor itself. Before the first trigger this.state is undefined, and it does not work in the template editor

hard vale
#

hmm i guess i found the issue
it has to do with the original sensor. it is giving me an 'uknown' state, even when removing the availability.
Pretty weard since i am able to receive values from this sensor in my faceplate

mint hazel
#

Hey, I could use some help with following template.

{{ integration_entities('mqtt') | map('device_id') | unique | list }}

I get a list of strings and 1 null value, which I want to remove from the list. Seems trivial, but for the life of.me I can't find out how to do so 😄

mighty ledge
#

| reject("none")

mint hazel
#

Thank you! 😄

#

I was going insane

#

I tried undefined and none

mighty ledge
#

put it between map and unique

#

you can put it after unique but you'll be using more memory every time it runs

mint hazel
#

Good to know

#

Had it after unique

wary yew
mighty ledge
#

you're looking at an old error

wary yew
#

oh crap, that could be

#

hmm will clear and check later then

mighty ledge
#

it definitely is

#

because your config is...

#

{% set value = states('sensor.electricity_current_demand') | int %}

#

but the error is

#

{% set value = (states('sensor.electricity_current_demand') | float %}

#

note the additional (

wary yew
#

ahh yeah, I remember removing that one after pasting it

mighty ledge
#

oh and you apparently changed float to int

wary yew
#

perfect, thanks @mighty ledge

#

yep, it was a paste from another card

#

also, since I have you here, is it normal that I need to repeat the variable statement on every piece of the card that uses it?

#

{% set value = states('sensor.electricity_current_demand') | int %}

mighty ledge
#

Yep, if they are in separate fields

wary yew
#

why can't I set value once and then just use the variable in all the YAML?

#

ah ok, it's normal behaviour then

#

got it. Just a bit annoying. Liked it cleaner.

slate fossil
# wary yew why can't I set `value` once and then just use the variable in all the YAML?

Variables are limited to their scope. Roughly speaking, if you set a variable in icon: then icon_color: will not be able to see it.
You could wrap a card in a custom:configuration-template-card. The custom:button-card is capable of applying variables throughout the card. You could also change the dashboard from Storage mode to YAML mode. You wouldn't be able to use the UI editor and would have to handle all the code manually but then you could use YAML headers and !includes.

zenith comet
#

How do I replace certain parts of a multi line string?

#

This for some ungodly reason converts the json data into yaml

#

If I leave out the template brackets it works fine

marble jackal
#

Please don't post images of YAML

plain magnetBOT
#

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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

marble jackal
#

Just post the code like that

plain magnetBOT
#

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

zenith comet
zenith comet
#

I was able to do what I wanted now because the webhook custom component has an alternaticve field for "jsonObj" which accepts whatever the template is turning the json string into

forest pagoda
#

Guys Need help with something....
` ## Desktop Power Status

  • platform: gpio
    pin: D7 ## Power detect input pin (readback from Power Led)
    name: "${upper_devicename} Desktop Power State"
    id: ${devicename}_desktop_power_state
    device_class: power
    publish_initial_state: true
    on_state: ## Binary Sensor Automation
    if:
    condition:
    binary_sensor.is_on: ${devicename}_desktop_power_state
    then:
    - logger.log: "Desktop Is On!"
    else:
    - logger.log: "Desktop Is Off!"`
    this the Binary Sensor
    I want to measure On time In a day
    I want to measure On time In a week
    I want to measure On time In a year
    Total power on time
    data should be persistence
    how to this any idea..
marble jackal
plain magnetBOT
marble jackal
#

@forest pagoda oh wait, use history stats for the daily sensor. Then use utility meters for weekly, yearly and all time

plain magnetBOT
chilly hemlock
#

Hey all, I use this template sensor to check all motion sensors

{{ states | selectattr('attributes.device_class', 'eq', 'motion') | rejectattr('attributes.attribution', 'defined') | rejectattr('entity_id', 'contains', 'global') | selectattr('state', 'eq', 'on') | list | count}}

It occasionally gets stuck on 'on', normally reloading templates resolves it but it is still stuck. Any ideas?

#

I edited it to update it. All good now. Any ideas on how to optimise it though? Thanks

mighty ledge
#

templates like that can't get stuck on unless it's from a trigger

#

also keep in mind that it's throttled to at most one update per minute

#

because you're just using the states object, not a sug broup of entities.

chilly hemlock
#

Hmm it certainly seems to be getting stuck on. What do you mean by 'unless from a trigger'?

mighty ledge
#

If this isn't a trigger based template entity, it's not getting stuck on. Its being throttled to at most 1 update per minute.

#

because you're only using the states object

marble jackal
#

If you start with states.binary_sensor it will be updating a lot faster. It's throttled to once per second then

weary drift
#

How do the template helper works? Does it pick the last output value as the state?

#

I could be able to use variables and other sensors in there right?

mighty ledge
#

the template you use for the template helper determines the state. It has full access to all template methods, including getting other sensor states and the use of variables.

weary drift
#

Hm, so i copied a template i made in the developer options but the helper is "Unavailable"

mighty ledge
#

post the template

weary drift
#

Ah nevermind. I picked "date" when i had another formatting 🙂

silver dagger
#

Can someone help me? I just want a card with my unchecked shoppinglist items. I dont want to delete all the checked items because the checked items are for me a reminder to check if I have them in stock. That whole list however, checked and unchecked itens, is to long. I now that i can use a servicecall to get the unchecked items. but how should I proceed? How do I just get a card with those items? thanks in advance!

bronze prawn
#

Struggling again. I have this:

{% for sat in expand('group.assist_satellites') %}
  {{ sat }}
{% endfor %}

which produces this:

<template TemplateState(<state sensor.assistsat_viewlr=; title=Annoucement, message=Dryer is done, image=, timer=, alarm=, cycle_view=, type=view_audio, mode=hold, mic_device=sensor.firehd_7_stt, mediaplayer_device=media_player.tabletfullkiosk, display_device=sensor.tabletfullkiosk_browser_path, browser_id=Tabletfullkiosk, view_timeout=20, message_font_size=4vw, do_not_disturb=False, friendly_name=AssistSat_ViewLR @ 2024-05-26T19:57:02.800807-05:00>)>
#

I want to actually print the display_device attribute. How do I do that?

fickle sand
#

{{ sat.attributes.display_device }}

bronze prawn
#

ahh thanks.. was missing the attributes piece

inner mesa
#

I feel like we've been through that a few times now 🙂

#

You keep starting with the same thing

fickle sand
#

Hahah I guess it would be wise to do some sort of free cursus to learn how (python) objects and dicts are structured and can be accessed

inner mesa
#

🔁

fallow gulch
#

I'm having trouble with a command_line switch. For some reason even though the value_template is rendering true, the switch shows as 'off' until I turn it on. What am I doing wrong here?

command_line.yaml
- switch:
    name: Media VM
    unique_id: media_vm
    command_on: "ssh -i /config/ssh/id_rsa_vmhost -o StrictHostKeyChecking=accept-new user@vmhost.33h.lan sudo /usr/bin/virsh start media"
    command_off: "ssh -i /config/ssh/id_rsa_vmhost -o StrictHostKeyChecking=accept-new user@vmhost.33h.lan sudo /usr/bin/virsh shutdown media"
    value_template: >-
      {% if is_state('binary_sensor.media_vm', 'on') %}
        true
      {% else %}
        false
      {% endif %}
bronze prawn
fallow gulch
#

Just blank?

obtuse zephyr
#

No, :

#

command_state: ":"

#

Also, your value_template can just be {{ is_state('binary_sensor.media_vm', 'on') }}

#

That already returns a boolean

fallow gulch
#

Yeah I’ve picked up on that whole troubleshooting today 🙂

mortal harbor
#

I think this is a "templates" thing. I have a 120v car charger hooked up through a shelly current monitoring plug. I'm wanting to calculate roughly how many miles have been added the last charge cycle. I easily made a template that output miles as a function of kWh as reported by the Shelly, but I want this kWh number to reset any time the plug's power goes from 0W to >0W, so I have a persistant number of the last cycle's added range until I plug it in again

#

I don't appear to be able to manipulate the shelly "energy" sensor directly, and am not sure what triggers it to reset in the first place.

lofty mason
#

Use a Utility Meter helper if you want a energy entity you can reset at your own chosen interval.

mortal harbor
#

Can I set a utility meter to reset with an automation?

lofty mason
#

yep, with a service call (utility_meter.reset)

mortal harbor
#

ah, excellent.

plain magnetBOT
#

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

mighty ledge
#

well for 1, fix the templates

#

they are overly verbose

#

All your time stuff is using really old style code and can be reduced.

elder moon
#

hmmm it may be old style, i am pretty sure that i once found a solution to some problem on the HA forums years ago and been replicating from an automation to an automation ever since

#

im a 'stackoverflow' type of coder 😉

mighty ledge
#

you mean copy/paster

elder moon
#

not necessarily copy and paste, you would be surprised how many typos i just found and fixed in the template above

#

but generally speaking all the presence sensing templates in my home look like that (i have more than one presence sensor in each room, for example in bedrooms there are mmwave and pressure sensors on the bed, to minimize chance of vacuum starting making noise in the middle of someones nap)

mighty ledge
#
{% set entities = [
    'binary_sensor.baby_room_bed_presence_pressure',
    'binary_sensor.private_office_presence_sensor_occupancy',
    'binary_sensor.paulina_bed_occupancy',
    'binary_sensor.michal_bed_occupancy',
    'binary_sensor.master_bedroom_presence_sensor_presence',
    'binary_sensor.baby_room_person_occupancy',
  ] %}
{{ entities | expand | selectattr('last_updated', '>=', now() - timedelta(minutes=15)) | selectattr('state', 'eq', 'off') | list | length == entities | length }}
#

might need to flop the >=

#

if you're loooking for things that haven't changed in over 15 minutes, then yes you do

#

if you don't like that code, change all your time comparisons

#

to
now() - states.binary_sensor.michal_bed_occupancy.last_updated >= timedelta(minutes=15)

elder moon
#

ohhh dear. it looks smooth, but need to wrap my head around it

#

ie understand it

mighty ledge
#

expand -> expands the entity_ids into state objects so you can access attributes and properties

#

| selectattr('last_updated', '>=', now() - timedelta(minutes=15)) -> filters the list of entities to only things that have changed in the last 15 minutes

elder moon
#

list | length == entities | length puzzles me

mighty ledge
#

| selectattr('state', 'eq', 'off') -> filters the list to only things that are off

#

| list | length -> gets a count of everything after all the filters are applied

#

entities | length -> gets a count of everything before the filters are applied

#

| list | length == entities | length -> checks if the 2 are equal in count

#

i.e. it simulates x and x and x and x and x and x

elder moon
#

aaaahhh i was not parsing it in right order in my head

#

really smooth templating!

#

hmm are you sure its "selectattr('last_updated', '>=', now() - timedelta(minutes=15))" not "selectattr('last_updated', '<=', now() - timedelta(minutes=15))"?

mighty ledge
#

your old template is taking the current time, subtracting the last changed, and checking to see if it's greater than 15 minutes.

#

now() - timedleta(minutes=15) will give us a datetime that's 15 minutes ago

#

i.e. you probably want <=

#

i.e. over 15 minutes ago

#

if that's not what you want, then reverse it

elder moon
#

thanks!

#

sorry one more question, while the above works fine in template editor in developer tools, there's some syntax error when i put it in wait_template: >

#

i guess that's because we've got actually two templates here one with {{ }} and one with {% %} ?

#

how can i make it work in wait_template:

mighty ledge
elder moon
#

`action:

  • wait_template: >
    {% set entities = [
    'binary_sensor.baby_room_bed_presence_pressure',
    'binary_sensor.private_office_presence_sensor_occupancy',
    'binary_sensor.paulina_bed_occupancy',
    'binary_sensor.michal_bed_occupancy',
    'binary_sensor.master_bedroom_presence_sensor_presence',
    'binary_sensor.baby_room_person_occupancy',
    ] %}
    {{ entities | expand | selectattr('last_updated', '>=', now() - timedelta(minutes=15)) | selectattr('state', 'eq', 'off') | list | length == entities | length }}
  • service: vacuum.set_fan_speed`
mortal harbor
marble jackal
# elder moon `action: - wait_template: > {% set entities = [ 'binary_sensor.baby_ro...

you need to indent the template with 2 spaces

action:
  - wait_template: >
      {% set entities = [
      'binary_sensor.baby_room_bed_presence_pressure',
      'binary_sensor.private_office_presence_sensor_occupancy',
      'binary_sensor.paulina_bed_occupancy',
      'binary_sensor.michal_bed_occupancy',
      'binary_sensor.master_bedroom_presence_sensor_presence',
      'binary_sensor.baby_room_person_occupancy',
      ] %}
      {{ entities | expand | selectattr('last_updated', '>=', now() - timedelta(minutes=15)) | selectattr('state', 'eq', 'off') | list | length == entities | length }}
  - service: vacuum.set_fan_speed
#

BTW, I guess you want <=

#

assuming you want every room to be empty for at least 15 minutes before the vauum starts

coral garden
#

hello

#

I have a vacuum that outputs json data as a sensor. Sometimes the json data has the battery level of the vacuum and sometimes it does not. I made a helper template to parse out the battery level:

#
{%set pos = (state_attr('vacuum.downstairs_vacuum_2','sensor')| base64_decode) | from_json %}
{% if pos.data.elec is defined %}
  {{ pos.data.elec }}
{% endif %}
#

the vacuum battery level is pos.data.elec but sometimes there is no pos.data.elec and the template returns and empty string, which home assistant doesn't like because it is expecting an int for the battery level

#

Sensor sensor.downstairs_vacuum_battery has device class 'battery', state class 'measurement' unit '%' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: '' ()

inner mesa
#

What do you want it to be in that case?

coral garden
#

the last known value

#

should I just save the previous state of the sensor? is that circular?

inner mesa
#

Is this a template sensor?

coral garden
#

yes

#

the code block is the template i'm using

inner mesa
#

Use a trigger and reference the current value as 'this.state'

#

You have to write that YAML manually

#

If you're trying to do it in the UI

coral garden
#

99% of my code is manual YAML and this is the one thing I tried to do in the UI and I was going insane because I couldn't fine the template sensor in my YAML and then remembered that I did it in the UI

#

anyway

#

how to I have a template sensor using a trigger?

#

is it an automation?

#

*do

coral garden
#

when did this become a thing? new to me

inner mesa
#

Years ago

coral garden
#

huh

#

missed it

#

so I trigger on the vacuum updating the json sensor

inner mesa
#

for your template, this may help:

{% set something = {} %}
{{ something.nothing|default('foo') }}
#

-> foo

#

you can use this.state in place of foo

coral garden
#

can the default be the previous state of the template sensor that is

#

I see

#

but it has to be in yaml not UI

#

?

#

I can't use "this" in UI

inner mesa
#

I guess you don't need a trigger (anymore)

#

I suggest reading the page and trying it

coral garden
#

nice

#

side question: when I make a template helper, where does home assistant write that down? I was going insane trying to find my template in my yaml files because I forgot I made it in the UI. Where is UI helper data stored?

inner mesa
#

in /config/.storage somewhere

#

don't mess with that

coral garden
#

okay.

inner mesa
#

if you want to mess with the the YAML, write the YAML yourself

#

almost everything that HA writes is in .storage

coral garden
#

HA is still angry about the sensor

#

is it 'this.state' or this.state?

#
{{ pos.data.elec|default(this.state) }}```
inner mesa
#

it's a variable, not a string

coral garden
#

{{ pos.data.elec|default(this.state) }}) renders=4>' for attribute '_attr_native_value' in entity 'None'

#

that's the only error

mighty ledge
#

is that the full error?

inner mesa
#

depending on what parts of that structure actually exsist, you may need to do what you did earlier

#
{% set pos = {'data':{}} %}
{{ pos.data.elec|default('foo') }}
``` -> `foo`
mighty ledge
#

FYI filters are applied left to right, you don't need the parenthesis there

inner mesa
#

if it's really none, then you may need to use default(this.state, True)

mighty ledge
#
{% set pos = state_attr('vacuum.downstairs_vacuum_2','sensor') | base64_decode | from_json %}
coral garden
#

I have removed the extraneous parens

#

the helper template sensor is unhappy. Renders Unavailable with {%set pos = state_attr('vacuum.downstairs_vacuum_2','sensor')| base64_decode | from_json %} {{ pos.data.elec|default(this.state,True) }}

inner mesa
#

You should test it in devtools -> Templates and debug

coral garden
#

everything works in the template debug page, but how do I debug the this.state?

inner mesa
#

'Foo'

#

Unavailable means something is broken

coral garden
#
{{ pos.data.elec|default('Foo') }}``` outputs Foo or the battery percent as expected on the template debug page
#

logs are quiet so it seems to be working

#

not sure what I did wrong in the interim, but thanks for the help!

#

also it's good to know about the self-referencing

mighty ledge
#

can you post the actual error?

inner mesa
#

It needs to have a valid value before you can start referencing it and expecting to get something useful

mighty ledge
#

pos.data.elec|default is not immune to issues with the dictionary

coral garden
#
{{ pos.data.elec|default(this.state) }}) renders=4>' for attribute '_attr_native_value' in entity 'None'```
#

that's the whole line in my logs

mighty ledge
#

this is your actual error

#

'AttributeError: 'NoneType' object has no attribute 'lower''

#

which is why I was asking for the full error

#

so pos or data in pos.data are a None object

#

Or

#
state_attr('vacuum.downstairs_vacuum_2','sensor')
#

is returning None

coral garden
#

should I do an if state_attr() is not None or something like that?

inner mesa
mighty ledge
#

well, if sensor is a real attribute, it should not return None

#

go to developer tools -> states page and take a screenshot of your vacuum with attributes enabled.

#

Use Imgur to share the screenshot

coral garden
mighty ledge
#

ok

#

what does

coral garden
#

The vacuum is integrated using Tuya Local so there could be weirdness in the data polling or something

mighty ledge
#

{{ state_attr('vacuum.downstairs_vacuum_2','sensor') | base64_decode }} return in the template editor?

coral garden
#

it's hard to capture as it changes every .5 seconds

#

it's json

mighty ledge
#

yah but just capture one of them

coral garden
#

{"data":{"phi":-1519,"pos":[-3271,-3730]},"infoType":20001}

#

got one

mighty ledge
#

ok

#

this should always work then...

coral garden
#

{"data":{"cleanArea":16,"cleanTime":740,"elec":69,"elecReal":69,"mode":"sweep","subMode":"smart","timeStamp":1717084361},"infoType":20001}

#

I think that None error might be a weird one

#

There were others

mighty ledge
#
{% set pos = state_attr('vacuum.downstairs_vacuum_2','sensor')| base64_decode | from_json %}
{{ pos.data.elec if pos is not none and pos.data is defined and pos.data is not none and pos.data.elec is defined and pos.data.elec is not none else this.state | default(0) }}
#

that should init at 0, then always maintain a state

coral garden
#

that's intense

mighty ledge
#

well, if you don't know the data will always be there, you have to check at each .

#

pos will always be defined

#

data will not, you also don't know if data is null or not. So you have to check for both. Same goes for elec

coral garden
#

not to bug but why isn't it enough to test for just pos.data.elec if that's all I'm looking for? data is null then there is no elec and I should just use this.state, ya?

inner mesa
#

This is where the JavaScript ? comes in handy

mighty ledge
#

because you're asking for items in a nested dictionary

#

if the second nest fails, you get an error

coral garden
#

<-- not a programmer

#

^--

mighty ledge
#

| default only checks the last dictionary item

coral garden
#

oh

mighty ledge
#

| default only ensures data has elec nothing else before that

#

another way to do this with defaults would be....

#
{{ (pos.data | default({'data': {}})).elec | default(this.state | default(0)) }}
coral garden
#

that exceeds my brains obfuscation parser

mighty ledge
#

or

coral garden
#

jeebus

mighty ledge
#
{{ pos.get('data', {}).get('elec', this.state | default(0)) }}
coral garden
#

I've never seen .get in a template

#

is this jinja-fu or json-fu?

mighty ledge
#

this is jinja

#

all jinja

coral garden
#

what is {} doing?

mighty ledge
#

that's a dictionary

coral garden
#

so get data or return empty dict, get elec or return this.state and if the whole thing fails default(0)

#

or is it just if this.state fails default(0)

#

parens

inner mesa
#

isn't the {}.get() part actually calling a Python method?

mighty ledge
inner mesa
#

anyway, not to further confuse things...

mighty ledge
#

so it's both jinja and python

#

I think the Jinja one is slightly different because it's not exactly the same as the python built-in, I could be wrong on that though

inner mesa
#

I thought it was literally using the Python data structure and its methods, but I don't know for sure

mighty ledge
#

confirmed

#

hmm wtf is cycler

#

and joiner

#

what in the shit is that class

#

cycler is a counter though... nice

coral garden
#

are you guys like black-belt level jinja/python people?

mighty ledge
#

🤷‍♂️

#

it's just interesting to see how things work

coral garden
#

every jinja-related post of yours that I've seen on the forums is a pretty slick piece of code

mighty ledge
#

well, i've been doing this for 8 years, rob somewhere between 4 and 8 years.

coral garden
#

this being HA or jinja-fu?

mighty ledge
#

HA

#

for me

#

I've been using python for 16/17 years

coral garden
#

so beginner level, then

mighty ledge
#

right

coral garden
#

jeebus

mighty ledge
#

🤏

coral garden
#

well, thanks for the help

mighty ledge
#

np

#
{%- set x = cycler('a','b','c','d') %}
{%- for i in range(10) %}
  {{- x.next() }}
{%- endfor %}
{%- for i in range(10) %}
  {{- x.next() }}
{%- endfor %}
#

outputs
abcdabcdabcdabcdabcd

inner mesa
#

hmm, I'll have to think of a better use case than that 🙂

mighty ledge
#

I cna't think of any

#

lol

#

well, right now I can't

#

you could use it in place of modulo

#

cycler(True, False, False, False) for every 4th item

#

e.g.

floral oxide
#

hey there! I'm trying to work with flightradar data to google sheets. I have it "working" but I have to run the same loop for each piece of data on multiple lines of code to output the values I want. I have a trial and error understanding of templates.

#

this works:

#

Craft: " {% set data = state_attr('sensor.flightradar24_current_in_area', 'flights') %}{% for flight in data %}{{ flight.aircraft_model }}{% endfor %}"
Flight Number: " {% set data = state_attr('sensor.flightradar24_current_in_area', 'flights') %}{% for flight in data %}{{ flight.flight_number }}{% endfor %}"
From: " {% set data = state_attr('sensor.flightradar24_current_in_area', 'flights') %}{% for flight in data %}{{ flight.airport_origin_city }}{% endfor %}"

#

but if there are 2 or more flights, I get a mess 😉

#

i tried cleaning up the loop, and it "works" in the dev template area

#

{% set data = state_attr('sensor.flightradar24_current_in_area', 'flights') %}
{% for flight in data %}
Flightid: "{{flight.id}}"
Craft: "{{ flight.aircraft_model }}"
Flight Number: "{{ flight.flight_number }}"
From: "{{ flight.airport_origin_city }}"
Altitude: "{{ flight.altitude }}"
{% endfor %}

#

BUT - I can't seem to jam this into the Data field of the automation

#

in fact, it'll often not even show the "Save" icon

#

I think I'm mentally mapping templates incorrectly

#

am i asking in the right place, and do I make any sense? 😉 Thanks!

#

hmm, can't paste in a screen grab...

mighty ledge
#

you can't template yaml fields

#

you can output a dictionary to a yaml field, but you can't template something like this:

something: >
{% for i in range(8) %}
- x: {{ a }}
  y: {{ b }}
{% endfor %}
mighty ledge
#

you can only template something: if you output a list of dictionaries and something: has to support it.

floral oxide
#

k, so the "data" box only wants yaml...

mighty ledge
#

I don't knwo what you mean by databox

floral oxide
#

on the automation page, in the Then Do secion, there's a data field that I can put yaml into, but not templates... unless they are inside the Label: "{{ value }}"?

mighty ledge
#

You can't template those fields in that box

floral oxide
#

thanks for helping! I'm sorry i'm clueless 😉

mighty ledge
#

you can if you output a dictionary

floral oxide
#

ok, will google dictionary and yaml

mighty ledge
#

but a for loop would output a list

#

not a dictionary

#

so, i'll need more info from you

#

googling probably won't help because this is not normal

floral oxide
#

heh

#

I'm pretty yaml ignorant. is my approach that works above the "normal" way of jamming templates into yaml, or is what I'm doing clearly a dictionary thing I have to go understand?

mighty ledge
#

everything you're saying is something you need to explain more

#

you keep saying data box, but there's 09287402850382094385 data boxes in HA

#

so, all I can say is what I've been saying

floral oxide
#

sorry!

#

getting a screenshot

#

crude, I know 😉

mighty ledge
#

right, so you have to output a dictionary as your template result

floral oxide
#

i'm very happy to go watch videos or rerad blogs if you need me to get some basic background before bugging the discord!

mighty ledge
#

you can't output yaml

floral oxide
#

k

mighty ledge
#

there are no videos for this

#

this is high level templating

#

there are no docs for this

floral oxide
#

gotcha

#

i'm old too, so "dictionary" is the same as a perl hash? 😉 key-value pair set

mighty ledge
#

yes

#

but you're outputting a list of dictionaries at the moment

#

well, you're attempting to output a list of dictionaries

#

data needs to be a dictionary

#

so you need to decide what to do when you have more than 1 flight.

floral oxide
#

i wish they'd limit to one flight at a time, but that proposal was rejected 😉

#

right- was hoping to write a line per flightid in the google sheet

#

I'm also messing with a display for the flight going over

#

this also uses the messy, loop per line of text approach

#

i'll go learn about dictionaries - thanks!

sleek trail
#

Is it possible to create a template sensor that can retain state over restarts so you can cover up for a binary sensor turning to unknown?

inner mesa
#

I think if it has a trigger

#

I think I mentioned that earlier 🙂

#

That + unique_id

#

From the docs:

The state, including attributes, of trigger-based sensors and binary sensors is restored when Home Assistant is restarted. The state of other trigger-based template entities is not restored.

#

Otherwise, you'd have to write to some other helper in the action and read it in the state

#

Pretty convoluted

sleek trail
#

Right

open vapor
#

Guys, remind me what functionality the semicolon has in the template sentence syntax

inner mesa
#

nothing?

open vapor
inner mesa
#

that's not a jinja template

mighty ledge
#

Definitely not templates

marble jackal
rich quarry
#

does ... | max(100) .... work in jinja in home assistant?

#

don't have an instance i can test it on rn

marble jackal
#

it does something, but probably not what you think

#

the first parameter of the max filter is a boolean to set case_senstive to False (=default) or True

#

100 is considered True, so this will set case_sensitive=true

silent vector
#

Is there a way to get the current notifications in ha via template? I'm referring to the side bar "notifications"

shell current
#

Hi all, Is there a way to get the "time_since" filter to only output in days?

#

or, might there be another way to get nr of days that I'm not yet aware of 😄

quaint matrix
shell current
#

aaawesome! Much appreciated!

rich quarry
quaint matrix
#

[stuff, 100] | min

marble jackal
#

That's not a parameter of the filter, that's the input

{{ [100, value] | min }}
#

Or, when used as function

{{ min([100, value]) }}
#

But from the snippet you shared, you were using it as filter

quaint matrix
#

(should be min not max if you want to cap it at 100 @marble jackal)

marble jackal
#

Ah right, he asked about max in his initial question

#

But indeed, to cap it at a maximum value, you need to use min

rich quarry
#

i did this for now but might change it if u fully understand this lol

#
{% if omvormer_kW * 10 <= 100 %}
  {{ name * 10 }}
{% else %}
  100
{% endif %}
quaint matrix
#

value being whatever your value is, so name * 10 in this case

rich quarry
#

ah

#

oki thanks

marble jackal
#

why do you have omvormer_kW and name?

#
{{ [omvormer_kW * 10, 100] | min }}
rich quarry
#

oh oops

#

good call

remote void
#

Guys, can somebody give me a quick hand, I'm sure this has been solved before but I fail finding the solution.

I want to create a tempalte helper that substracts the value of one sensor from another, and track the result in a sensor. I have my total power consumption from directly from my smartmeter, and I have the sum of all my consumption trackers in a helper sensor. I want to track how much energy I consume that I am not aware of.

#

Ah, sometimes it just helps posting in here without anybody replying 🙈, I guess this should do the trick:
{{ states('sensor.smart_meter_active_power_plus')|float(2) + states('sensor.solar_power_total')|float(2) - states('sensor.smart_meter_active_power_minus')|float(2) - states('sensor.total_power_consumption')|float(2) }}

I hope I am not wrong about the formula, trying to take solar production into account. If anybody spots a problem, please let me know! 🙏

#

alright I already found a problem. If one entity goes unavailable I suddenly have a huge negative untracked value. How can I skip the value if one entity is unavailable?

lofty mason
lunar crater
#

can i create a template sensor with multiple attributes, all of which are getting a statistics?

inner mesa
#

Do you mean LTS?

lunar crater
#

yes

#

i would like to calculate an output factor for my solar panels but dont want to create a sensor for each

inner mesa
#

I'm pretty sure that LTS only include the state. Lots of attributes would make no sense as statistics

#

And you have to add attributes to enable LTS in the first place

#

And it applies to the state

lunar crater
#

hm i see, guess if thats the case i may use this as an excuse to not care about it and try doing nodered stuff for it

inner mesa
#

There's not much love for using attributes like that

kind silo
#

I am trying to format a template sensor with a trigger, but i am not sure i understand the formatting

inner mesa
#

Why are you not sure?

kind silo
#

so i have been using yaml files for sensors, so a normal template sensor would look like this
- platform: template sensors: ev_total_power: friendly_name: Total EV Charger Draw unit_of_measurement: "kW" value_template: >- {{ (float(states.sensor.tesla_east_ev_power.state) + float(states.sensor.tesla_west_ev_power.state)) | round(1) }}

#

i don't know how to start the sensor with a trigger, all the things i have tried have thrown errors

#

this is what i am trying to figure out
`template:

  • trigger:
    • platform: state
      entity_id: sensor.east_ev_charger_daily
      not_to:
      • unavailable
      • unknown
        sensor:
    • name: 'East EV Charger Historical Max'
      unit_of_measurement: 'kWh'
      device_class: energy
      state: >
      {% set t_new = states('sensor.east_ev_charger_daily') | float(-99) %}
      {{ [t_new, this.state | float(-99)] | max if trigger.platform != 'state' else t_new }}
      attributes:
      power_updated: "{{ now() | as_local }}" `
inner mesa
#

What errors?

#

Where did you put that?

kind silo
#

in a sensor.yaml file

inner mesa
#

That's the wrong place

#

It goes in configuration.yaml

kind silo
#

it has to go there? Wasn't the whole point years ago to not have the config.yaml completely filled with stuff?

inner mesa
#

You can include a file if you want

#

It's a template: not a sensor:

kind silo
#

ok, that is different than a template sensor, that resides with sensors. i would just include it like anything else in the configuration.yaml?

inner mesa
#

They're both template sensors. You were using the legacy format and now you're using the modern format

#

Yes, same way

kind silo
#

got it, so is there any value to migrating the old sensors? i have like 500

inner mesa
#

If you want the features of the new format

#

unique_id, for instance

#

It's not hard to do

#

You don't need to. Unlikely that the old format will go away

kind silo
#

i am largely out of the modern development, what is the benefit of unique_id? sorry for the dumb questions

inner mesa
#

Let's you configure parts of the sensor in the UI, like the name

#

I suggest reading the docs that you clearly have to see the new stuff

kind silo
#

ah ok, thats why template sensors show up weird that way

inner mesa
#

Since you're already using one, the trigger

kind silo
#

I got it, is there a way to auto generate a unique_id like if you leave the field blank on the first startup or some other way?

inner mesa
#

No, but VSCode, for instance, has a UUID generator extension

#

HA never modifies your files

kind silo
#

ok, i use VS code, so ill check that out.

marble jackal
#

state_class and of course triggers and actions are only supported in the modern format

covert salmon
#

How do I aggregate a daily sensor for a whole year? I have a sensor that gives me the daily produced energy from my solar panels and resets every day. I want to see how much energy was produced in total and then calculate how much money was saved

marble jackal
#

use a utility meter on that sensor

plain magnetBOT
covert salmon
ivory torrent
#

I'm having a bit of trouble with date/time in a template. I am trying to compare today's date to the date of the next NY Rangers game by using:

{{ now().date() | string == state_attr('sensor.team_tracker_rangers', 'date')[0:10] }}

This was working fine for a bit

When I go to look at the sensor, the attribute displays the date/time in my local time zone which is currently UTC-4 but when I use

{{ state_attr('sensor.team_tracker_rangers', 'date') }}

it returns the date/time in UTC. So when a game is supposed to start at 8PM local time, it shows tomorrow's date because four hours after 8PM is midnight.

So all this is to say that when it calls

now().date() it returns 2024-06-01

but when it calls

state_attr('sensor.team_tracker_rangers', 'date')[0:10] it returns 2024-06-02

because of the time zone difference.

How do I have it spit out the date/time in my local time instead of UTC?

lucid thicket
#

What does state_attr('sensor.team_tracker_rangers', 'date') show in the template editor?

ivory torrent
#

Right now it returns 2024-06-02T00:00Z

#

the next game is today at 20:00

#

If I look at it in the GUI, the Date attribute is displayed as June 1, 2024 at 8:00:00 PM

lucid thicket
#

You can try this:


{{ (state_attr('sensor.team_tracker_rangers', 'date') | as_datetime | as_local).date() == today_at().date()}}
ivory torrent
#

Nice! That appears to be working. It also fixes my bootleg way of pulling only the date to compare the strings. Thanks for the help

chilly hemlock
#

Hey all, is there a way I can exclude lights with a label id of don_t_count_as_light from this template? Thank you

{{ lights | count | default() }}```
marble jackal
#
{{
  states.light
    | selectattr('entity_id', 'in', label_entities('don_t_count_as_light'))
    | rejectattr("attributes.entity_id", "defined")
    | selectattr("state", "eq", "on")
    | list
    | count
}}
chilly hemlock
#

Thank you - however I think this includes lights with that label rather than excludes

#
  states.light
    | rejectattr('entity_id', 'in', label_entities('don_t_count_as_light'))
    | rejectattr("attributes.entity_id", "defined")
    | selectattr("state", "eq", "off")
    | list
    | count
}}```

This does the trick I think 😄 thanks a lot!
marble jackal
#

Yeah, that was to test you 😜

bronze prawn
#
if:
  - condition: template
    value_template: |-
      {% if target_display_device %}
      true
      {% else %}
      false
      {% endif %}

I am setting the variable target_display_device in part of my automation before this block. I want to test if this device has a value. I thought this would do it but I am getting a return as false (I think) as the code is not executing in the then portion. I want to know that this variable is not null/empty/none

#

for context this is how I am setting the variables:

variables:
  target_satellite_device: |-
    {% for sat in expand('group.assist_satellites') %}
      {% if device_id(sat.attributes.mic_device)  == trigger.device_id %}
        {{ sat.name }}
      {% endif %}
    {% endfor %}
  target_display_device: "{{ device_id (state_attr(target_satellite_device, 'display_device')) }}"
#

I do know that target_display_device is being set correctly as without the condition the service call does route to the correct device

#

I guess it only takes me posting to find the right answer. This appears to work:

{% if target_display_device is defined %}
lucid thicket
#

Put this in the template editor:


{% set target_display_device = None %}
{{ target_display_device is defined }}
bronze prawn
lucid thicket
#

It should equal None if that attribute or sensor or device isn’t found, so just test for != None

bronze prawn
#

that didn't work. I will rethink this

lucid thicket
#

What did it do that you didn’t want it to do?

bronze prawn
#

I'm working on a project called View Assist. This ties a bunch of voice satellites together. Some of these devices have displays and some do not. I am trying to check if a device is configured to have a display and if it does it should then show something on the screen. If it doesn't it should just skip the display service call. I use the variable definition above on my automations and I thought I would be smart in checking if the target_display_device had a value in it and use that in the if statement

#

Looks like I am having problems setting those variables. They are all none. Back to the drawing board.

sacred sparrow
#
    - name: "NAS Status"
      icon: phu:nas-v2
      delay_on:
        seconds: 10
      delay_off:
        seconds: 10
      state: "{{ states('sensor.server_smartplug_power')| float(0) >= 30 }}"```
#

whats the best way to make the on status stay on when HA is restarting?

bronze prawn
lucid thicket
#

You can use a state trigger with

not_to:
  - "unavailable"
  - "unknown"
winter forge
#

I'm trying to pull the media players located in the room in which I am located, ( To start rain sounds where I'm sleeping)

I have a sensor called 'sensor.where_is_maxi_sleeping' whose current value is "bedroom"

But when using

    select('match', '^media_player.') | select('is_state','off') | unique | list }}```

I do not get the media players in the area called bedroom.

Any idea if this is supposed to work?
#
    {{ [states('sensor.where_is_maxi_sleeping') | capitalize ]  | map('area_entities') | sum(start=[]) |
    select('match', '^media_player.') | select('is_state','off') | unique | list }}

This worked!

#

I was missing square brackets

winter forge
#

Update on that code

How can I also check that they are unmuted

    sum(start=[]) | select('match', '^media_player.universal') | selectattr('attributes.is_volume_muted', 'eq', false) |
    select('is_state','playing') |  unique | list }}```

Does not work and returns: UndefinedError: 'str object' has no attribute 'attributes'
inner mesa
#

right, you're just working on a list of entity_ids

winter forge
#

How ca n I pull the corresponding objects?

inner mesa
#

you need to add |expand

winter forge
#

At which position? 🙂

inner mesa
#

or, you can just use is_state_attr() there

winter forge
inner mesa
#

yes, there's a whole page

#

I think it works as a test

#

indeed it does. example:
{{ area_entities('Downstairs Hallway')|select('search', 'aarlo')|select('is_state_attr', 'device_brand', 'Arlo')|select('is_state', 'armed_home')|list }}

winter forge
#

Let me try that!

#

{{ area_entities('Office')|select('search', 'media_player')|select('is_state_attr', 'is_volume_muted', false)|select('is_state', 'playing')|list }}

worked! Thanks!

#
    'media_player.universal')|select('is_state_attr', 'is_volume_muted',
    false)|select('is_state', 'playing')|list }}``` Doesn't seem to work tho
#
Executed: June 1, 2024 at 9:05:51 PM
Result:

params:
  domain: media_player
  service: volume_up
  service_data: {}
  target:
    entity_id: []
running_script: false
#
service: media_player.volume_up
metadata: {}
data: {}
target:
  entity_id: >-
    {{ area_entities(trigger.entity_id)|select('search',
    'media_player.universal')|select('is_state_attr', 'is_volume_muted',
    false)|select('is_state', 'playing')|list }
inner mesa
#

you appear to be passing an entity_id into area_entities()

winter forge
#

Derp.. I need to use the area_id thing

#

Should this work?

    'media_player.universal')|select('is_state_attr', 'is_volume_muted',
    false)|select('is_state', 'playing')| list }}

Or I can't concatenate functions?

#

Worked, nnoice

lucid thicket
# sacred sparrow not_to?

Yes, you want your template sensor to get updated on every state change except for when the sensor becomes unavailable or unknown which is what happens on restart. So your template sensor will update just like it does today except it won’t update on restart. Which is exactly what you asked for.

sacred sparrow
#

I mean - I didn't think not_to was a thing haha

nocturne chasm
#

in reference to the latest beta, i am struggling a bit to understand variables and wonder if someone could help

willow wing
plain magnetBOT
#

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

marble jackal
#

Did it already trigger?

willow wing
#

@marble jackal i think this does when i reboot?

marble jackal
#

No, you have an hourly trigger, it triggers every hour on the hour

marble jackal
willow wing
crimson lichen
#

i have try template
{{ now() == today_at('08:01')}}
But it alway false
i have changed minutes

haughty breach
#

It's accurate to microsecronds...

crimson lichen
#

Thanks

haughty breach
#

What are you trying to do with the comparison?

crimson lichen
#

i want to use it as trigger to given time

haughty breach
#

Will a Time trigger not work for your use? Generally, when using now() in a template trigger it is best to use >= instead of == so you avoid the issue you showed earlier.
{{ now() >= today_at('08:01')}}

crimson lichen
#

Thanks
I changed to
{{((now().hour == 6) and (now().minute == 30) and now().day == 1)}}

fallow gulch
#

For some reason this template sensor keeps dropping to 0, but the source sensor doesn't. I presume it has something to do with the "availability:"... Is there a way to tell it to use the last sane value, instead of dropping to 0 when the availability renders false?

template.yaml
sensor:
    - name: "Grid Consumption"
      unique_id: grid_consumption
      unit_of_measurement: "W"
      device_class: power
      availability: "{{ is_number(states('sensor.solaredge_m1_ac_power_2')) }}"
      state: >-
        {% set grid = states('sensor.solaredge_m1_ac_power_2') | float %}
        {{ ((grid * -1) if (grid < 0) else 0) | round(0) }}
marble jackal
#

if the availablity renders false the sensor will report unavailable, not 0

#

that's the whole idea of the availability parameter

#

the sensor drops to 0 because you tell it to do that when the value is positive

#

BTW, you could also do

sensor:
    - name: "Grid Consumption"
      unique_id: grid_consumption
      unit_of_measurement: "W"
      device_class: power
      availability: "{{ 'sensor.solaredge_m1_ac_power_2' | has_value }}"
      state: "{{ [0, states('sensor.solaredge_m1_ac_power_2') | round(0)] | min | abs }}"
pearl grail
#

Hello,
I'm trying to make a template sensor that will calculate the rainfall/day so I know if I deactivate the irrigation system for the next day.
I've used the OpenWeatherMap rain value (mm/h), created an aritmetic mean of that and then multiply by 24.
The problem is that I'm not entirely sure what the result represents. My best guess is rolling average 24h of rainfall. Am I right?
Thanks.

pearl grail
#

Actually....I don't know what is the period the aritmetic mean is applied on 🫤

mighty ledge
#

well we don't know either because you haven't shared the templates

#

@pearl grail ^

pearl grail
#

{% set o1 = states('sensor.average_precipitation_rate')|float %}
{%set o2 = 24 %}
{{ (o1 * o2) | round(3) }}

#

And sensor.average_precipitation_rate is median of openweathermap rain

mighty ledge
#

use open weather map and that integration doesn't provide that

pearl grail
#

That sensor.average.... is a median of this : sensor.openweathermap_rain

fickle sand
#

Median is statiscally something different than an average

pearl grail
#

I've tried before aritmetic mean, but I reached 0mm of rain today so I realized that is no good either.

#

I've tried to plot the sensor.openweathermap_rain using statistical graph and that works perfectly. I just need to multiply it with 24 to get the value o want:

chart_type: bar
period: day
type: statistics-graph
entities:

  • sensor.openweathermap_rain
    stat_types:
  • mean
    title: Daily rainfall
    days_to_show: 7
mighty ledge
#

Do you want rainfall in the past or the future?

pearl grail
#

In the past 24h

fickle sand
#

Just use an utility meter

#

set to daily

mighty ledge
#

well that would be from midnight not past 24 hours

#

the stats integration can sum the past 24 hours of rainfall

fickle sand
#

or what petro is propossing indeed if you want 24h relative from now

mighty ledge
#

it's a rolling 24 hours and it would be a sum

#

if you go average, it's going to be low because rainfall will likely be 0 at most times.

#

where as sum will add all the values together, then you can use a simple threshold

pearl grail
mighty ledge
#

No, statistics

plain magnetBOT
mighty ledge
#

You can also just buy a rain sensor

#

which is 100% accurate

#

they are cheap(ish)

#

I got mine for like $70 but it was part of rainbirds setup. If you go with a non-proprietary sensor, they can be very cheap

pearl grail
#

I'm not interested in being 100% accurate. I just need to know if it's raining when the electric pump is starting (depending on raining direction there might be water on it)

#

And if the soil is too wet already, I don't want to add even more water.

mighty ledge
#

right, you should really get a rain sensor then

#

they essentially have "soil" in them and the sensor reads that

frail dagger
#

If you need to do something that involves rain and electricity, you'll want a rain sensor (as petro said). Weather integrations that rely on the internet aren't always updated and there's a chance of it not even connecting sometimes. This is something I would not trust to the cloud.

pearl grail
#

Understood, thanks. I'll look into what sensor options do I have.

fickle sand
pearl grail
#

Any recommendations then of a rain sensor that can be integrated into Home assistant? 😁

pearl grail
frail dagger
random basalt
#

Can't get this formatted correctly. If anyone can help.

Days until harvest: {{ ((as_timestamp(states('input_datetime.petunias')) + states('input_number.petunias') * 86400) - as_timestamp(now)) }}
#

The date Planted works.

sharp frigate
#
    data:
      entities:
        light.tv_back_light:

How would I make light.tv_back_light: a template (script field) like {{entity}}

marble jackal
thorny snow
mighty ledge
#

{{ states('sensor.ender_5_plus_print_eta') | as_datetime - timedelta(hours=4) }}

#

why "4 hours earlier"?

thorny snow
#

datetime! It's reporting the job will be finished at 1600 but when I check the device directly it's actually finishing at 1200

#

so, I'm not sure if it's a timezone issue ...

mighty ledge
#

that is the correct time

thorny snow
#

I figured it was a timezone, but I thought -4 would be easier than figuring out how to change the tz?

mighty ledge
#

No, you don't want to change it

#

you want to keep it the way it is, where are you trying ot use the time?

thorny snow
#

I'm using it in a notification to my phone, so I want that to be in my current tz

mighty ledge
#
{{ states('sensor.ender_5_plus_print_eta') | as_datetime | as_local }}
thorny snow
#

damn, you make it look so easy

#

the beauty of experience

#

works perfectly, thanks petro!

limpid python
#

Hi, any idea how to convert all options of a input_select into a yaml list with a yaml template?

input_select:

  • Options:
  • 1
  • 2
  • 3

into a yaml list

`- yaml_lst:

  • 1
  • 2
  • 3`
inner mesa
#

It already is

#

The options attribute is a list

limpid python
#

aha, ok. thx

limpid python
#

@inner mesa

I've tried:

`action:

  • service: vacuum.send_command
    target:
    entity_id: vacuum.adoracion
    data:
    params:
    - segments:
    - {{ state_attr('input_select.reinigung_segmente', 'options') }}
    repeat: 1
    command: app_segment_clean`

But it replaces the yaml templete with a null:

`action:

  • service: vacuum.send_command
    target:
    entity_id: vacuum.adoracion
    data:
    params:
    - segments:
    - null
    repeat: 1
    command: app_segment_clean`

What I'm doing wrong?

haughty breach
#

You likely need to template the entire value for params

mighty ledge
#

Just segments

#

But you maybe right if the segments needs to be a string

#

Which some vacuums require

limpid python
#

If I run it manually the segments are integers'

service: vacuum.send_command target: entity_id: vacuum.adoracion data: params: - segments: - 17 repeat: 1 command: app_segment_clean

That is the way I'm currently using it. But this approach only works for a fix set of segments. Which is why I want to replace it by a input_select, which allows me to add and remove options.

haughty breach
#
     params:
        - segments: "{{ state_attr('input_select.reinigung_segmente', 'options') }}"
          repeat: 1
limpid python
#

Almost there. It seams that it does not accept segments of strings. So I need to convert them to integers.

mighty ledge
#

| map('int') | list

limpid python
#

wohooo, its working. Thanks

humble mortar
#

Is this a templating issue?

charred dagger
#

@stoic sable It's an unfortunate side-effect of the python value coersion of templates.
Your template evaluates to 123,456.789 which is then re-parsed through python as 123, 456.789 or [123, 456.789].
The only way around it is to add something to the string which cannot be parsed as a number.
E.g. {{ "{:,} km".format(123456.789) }}

stoic sable
#

Tyvm for the clear explanation!!

charred dagger
stoic sable
charred dagger
#

It's a HA thing, and there's nothing that can be done as far as I know.
It's actually very helpful for things like data in service calls but every now and then there is a problem like yours.

mighty ledge
stoic sable
mighty ledge
#

Is there any reason you’re not letting the ui format it for you?

#

And what do you mean “template card”?

stoic sable
stoic sable
stoic sable
#

I was also surprised I had no access to type() or str() functions within a template - is there a reason why not (?)

fickle sand
#

The mushroom template card ignores the display_precision. The generic mushroom card does apply it

mighty ledge
#

Yes that’s where I’m going bas, to me it seems like you shouldn’t be using a template at all. Just a regular card that formats things for you in combination with a template sensor if needed

fickle sand
#

Yeah seems also more confient to me, let HA handle the precision globally for an entity

mighty ledge
mighty ledge
#

So it doesn't matter what you do in the template, the resolver will apply a type after and you have no control over it.

#

Anyways, if you post your full mushroom template, I can offer a path of less resistance that will potentially do what you want.

sly quiver
#

Hey guys I've done some research but I can't seem to find an answer I have two power readings one input into an inverter and one output I'm trying to make a sensor value for efficiency as a percentage loss IE 100w input 80w output = 20% efficiency loss any ideas how I would go about this?

stoic sable
stoic sable
mighty ledge
#

simply click on the entity, and set the precision

stoic sable
mighty ledge
#

if there isn't make a template sensor from the number

#

I just noticed that the entity in question is a volume, why is it a number entity?

#

it should be a sensor

#

anyways, to make a sensor from it, make a template helper using {{ states("number.variables_rainwater_tank_max_storage_volume") }} . Set the device_class or display as to volume and set your unit of measurement to the proper units. Then you can modify the precision there and use that in your UI.

#

As a sidebar, I highly doubt that the number entity is created by a normal integration, I'd reach out to the integration owner and ask why this isn't a sensor to begin with.

stoic sable
#

It's an integration with a lighting control system - it maps a variable in it, to a number in HA. I can change the integration no problem - what is a 'number' meant to be used for; is it for unitless values whereas this one (with some real world meaning, units etc.) maps more to a 'sensor'; even if it is just a variable?