#templates-archived

1 messages · Page 163 of 1

nimble copper
#

I have a template that averages a bunch of sensor values. When list of entities is 0, fmean throws out an error in the log saying it needs one datapoint to calculate the average.

#

So I'm trying to stop the error from happening by checking the list isn't empty before running the average.

{{ expand(area_entities('kitchen')) | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'temperature') | map(attribute='state') | select('is_number') | map('float') | average | round(1) }}

charred dagger
#

I think you need to do that in two steps: yaml {% set values = expand(...) ... | map('float') %} {{ iif(values | length, values | average | round(1), 'unknown' }}

nimble copper
#

Ah ok! That makes sense. Thank you.

charred dagger
#

Actually, that will just give you the same error.

nimble copper
#

Yeah I've just noticed that.

#

{% set values = expand(area_entities('kitchen')) | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'tempserature') | map(attribute='state') | select('is_number') | map('float') | list %}

{{ iif(values | length, values | average | round(1), 'unknown') }}

charred dagger
#

iif evaluates both arguments regardless, so you need a full if: {% if values | length %} {{ values | average | round(1) }} {% else %} unknown {% endif %}

marble jackal
#

You could also add an availability template using something like:

{{ expand(area_entities('kitchen')) 
    | selectattr('attributes.device_class', 'defined')
    | selectattr('attributes.device_class', 'eq', 'temperature')
    | map(attribute='state') 
    | select('is_number') 
    | list
    | count > 0
}}
sacred sparrow
#

how do I take 1 minute away from {{ as_timestamp(now()) }} ?

storm canyon
#

Not sure this is the location but it's a best guess. How do I make a binary sensor that acts like a coin toss? True and false presenting heads and tails (not necessarily respectively).

#

I'm thinking something like
is_int(Time.Milliseconds /2)

#

However that's nonsense in yaml

silent seal
silent seal
floral shuttle
#

that is cool, never new that existed .... now got to find a nice reason to use it 😉 somehow feel my mockupancy config could benefit from this.

novel crystal
#

Hey!

#

I'm reading breaking changes and noticed tat "Defining manually configured MQTT entities directly under the respective platform keys (e.g., fan, light, sensor, etc.) is deprecated, and support will be removed in Home Assistant Core 2022.9."

#

Does the same also applies/ will be applied to Template?

silent barnBOT
novel crystal
#

lol, ty BOT

sacred sparrow
silent seal
tidal heart
#

Hi!
I want to pull the data from the hour that is current hour from the weather forcast. More specifically I want to get the precipitation. I just can't figure out how to do it

#

For some reason the met.no integration's hourly forcast does not show precipitation as of right now as an attribute but the forcast attribute contains the precipitation for current hour

#

So If I would like to select precipitation from 12:00. How can I do that?

marble jackal
#

Oh, had a look at your link as well now

#

You should have a look at the new format, that is totally different as what you are trying to put in now

#

It should be something like:

template:
  - binary_sensor:
      - name: is DST
        state: "{{ now().timetuple().tm_isdst > 0 }}"

Furthermore, these templites reside under the template integration, and not under the sensor integration, so you can't place them in your sensors.yaml

silent vector
#

Is there a clean way to check after a certain time if the target_sensor value is equal to the value sent in the command? Such as whether the sensor mode is equal to active if the command sent in the previous action was active or the temperature is equal to 65 if the temperature sent was 65. If not after 5 seconds then resend the command (in the event the API timed out and never processed the command). Then recheck and if it still isnt equal send a notification (presumably API Issue).
https://www.toptal.com/developers/hastebin/buguwimuso.less

mighty ledge
#

or a wait_template

#

depends on how fast the API responds.

#

both are covered in the script section of the documentation

novel crystal
#

tyvm for your answer

silent barnBOT
silent vector
#

And then what would the template be to see if it equals what was sent in the rest command?

mighty ledge
#

you'd look at the sensor

#

you update the entity, and then check the sensor

silent vector
#

And see if the target_sensor == service_data?

mighty ledge
#

what's the state of the sensor that you're updating

silent vector
#

It's going to be either on/off or a number (temperature). 2 different templates sensors.

mighty ledge
#

ok, and you want to look at your temperature sensor, right?

#

basically, you want to check whatever the state is going to be

#

you know how to do that, you've done it before

silent vector
#

I was overthinking it. It's simply is the state equal to the variable temperature or mode if it was a mode change.

sacred sparrow
#

{{ as_timestamp(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) }}

doesnt seem to work

mighty ledge
#

don't use as_timestamp, change it to as_datetime

#

that attr should already be a datetime, so you probably don't even need that.

#

Lastly, if you're on 2022.6, you can use the offset calendar triggers so you don't even need a template if you're trying to make a notification automation.

sacred sparrow
#

Oh thanks - I am using this as trigger in a bigger automation

#

{{ as_timestamp(now()) > as_timestamp(state_attr('calendar.gmail','start_time')) and is_state('calendar.gmail', 'on') }}

#

this didnt work:
{{ as_timestamp(now()) > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}

#

but this alone does
{{ as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) }}

mighty ledge
#

with a condition that checks to see if the calendar is on

mighty ledge
sacred sparrow
#

hmm I tried both
{{ now() > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
&
{{ as_datetime(now()) > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}
still cant get it to work

mighty ledge
#

Now is a datetime

#

Triggers have to resolve false then resolve true for it to trigger

#

If you’re restarting and you’re past the time, it won’t trigger

sacred sparrow
#

I meant just in developers > templates

#

I'm trying to get it work there before taking it to the automation

mighty ledge
#

Now() is local timezone, what’s the timezone on your cal? If it’s local you need to add as_local as well

marble jackal
#

What error does devtools > templates give?

sacred sparrow
#

for: {{ as_datetime(now()) > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}

TypeError: float() argument must be a string or a number, not 'datetime.datetime'

#

so i tried: {{ now() > as_datetime(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}

mighty ledge
#

Dude, remove the as_datetime on now and add as_local on the as_datetime(state_attr

sacred sparrow
#

{{ as_local(now()) > as_local(state_attr('calendar.gmail','start_time')) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}

#

gets me: AttributeError: 'str' object has no attribute 'tzinfo'

mighty ledge
#

🤦‍♂️

#

Why’d you add as_local on now?

sacred sparrow
#

oh lord haha

marble jackal
#

and keep as_datetime on the start_time attribute

mighty ledge
#

Now does not need to change

marble jackal
#

but add as_local as well

mighty ledge
#

Like, read what I’m writing

#

It’s very frustrating to help a person who is not reading what you’re writing

marble jackal
#

as_local(as_datetime(state_attr()))

#

or, maybe more readable: state_attr() | as_datetime | as_local

sacred sparrow
#

I really appreciate the help - I am sorry it is frustrating you but I am just trying to wrap my head around it

#

{{ now() > as_local(as_datetime(state_attr('calendar.gmail','start_time'))) - timedelta(minutes = 1 ) and is_state('calendar.gmail', 'on') }}

marble jackal
#

does that work in devtools >templates?

tidal heart
#

How can I get the precipitation from the current hour from a weather sensor? The [0] is usually 1-3 hours in the past

silent vector
#

What does the sensor show in developer tools?

tidal heart
#

I’m using my phone at the moment but it’s the regular weather.home_hourly so the forecasts have a datetime attribute. I’m guessing I somehow can loop trough the forecasts, select the one that matches current hour and then use that precipitation state.

marble jackal
#
{%- set w = 'weather.climacell_hourly' %}
{%- set h = today_at(now().hour ~ ':00') %}
{%- for f in state_attr(w, 'forecast') %}
  {{ f.precipitation if as_datetime(f.datetime) == h }}
{%- endfor %}
#

Change the weather entity in de first line

#

Could be done easier if I knew how to convert a datetime in local time to utc 🙂

silent vector
#

On a side note I used to use the regular home_hourly until I realized how inaccurate it was in comparison to AccuWeather or openweathermap at least for me it was inaccurate by a few degrees and sometimes more. Openweathermap also let's you get an hourly forecast if you want to know hour by hour vs 3 hours. Openweathermap also updates more frequently than the regular one.

tidal heart
#

Thanks for trying to help guys! I’ll have a look at it

marble jackal
#

@tidal heart Better version

#
{%- set w = 'weather.climacell_hourly' -%}
{% set u = utcnow().strftime('%Y-%m-%dT%H:00:00+00:00') %}
{{ state_attr(w, 'forecast') | selectattr('datetime', 'eq', u) | map(attribute='precipitation') | join }}
tidal heart
#

Updating to 2022.6.0 😄

marble jackal
#

Not needed anymore with the last version

tidal heart
#

I have been so frustrated that the weather sensor in general seem to just skip the precipitation and precipitation_chance in the "current" attributes (not in the forcast list)

#

Trying now, can it be so that if it returns 0 it actually does not show at all?

#

Or wait utcnow() is the right timezone for me

#

now() seem to work though!

marble jackal
#
- condition: cloudy
  precipitation: 0
  precipitation_probability: 16.7
  temperature: 13
  datetime: '2022-06-02T13:00:00+00:00'
  wind_bearing: 260.4
  wind_speed: 23

This is the part of the current hour, and precipitation is 0 here. So 0 seems to be correct

tidal heart
#

Wait what! This gives me 0.0 and if I change the mapped attribute to datetime it's the right hour as well

{%- set w = 'weather.home_hourly' -%}
{% set u = now().strftime('%Y-%m-%dT%H:00:00+00:00') %}
{{ state_attr(w, 'forecast') | selectattr('datetime', 'eq', u) | map(attribute='precipitation') | join }}
#

Damn, how do you make the formatting so nicely here on discord? Mine looks like shait

marble jackal
#

add yaml directly after the 3 backticks

#

for yaml that is, for jinja add jinja

tidal heart
#

Nice!

marble jackal
#
{{ now() }}
{{ now().strftime('%Y-%m-%dT%H:00:00+00:00') }}
{{ utcnow().strftime('%Y-%m-%dT%H:00:00+00:00') }}

result:

2022-06-02 15:23:00.008942+02:00
2022-06-02T15:00:00+00:00
2022-06-02T13:00:00+00:00
#

at least for me, as I'm on GMT+2

tidal heart
#

Yeah I'm as well

marble jackal
#

okay

#

then with now() you wil get this part

- condition: cloudy
  precipitation: 0
  precipitation_probability: 1.5
  temperature: 13.4
  datetime: '2022-06-02T15:00:00+00:00'
  wind_bearing: 266.3
  wind_speed: 26.3
#

which is also 0, so it seems to be correct as well, but that will not always be the case of course

#

That time there is not the right time, because it is in utc

tidal heart
#

Hold on now... so you mean that if I use now() it might not get the right data in the template? Like it could go for the next hour or what?

#

If I tried utcnow() it renders nothing

marble jackal
#

Our current time is 15:27 which is 13:27 utc

#

so currently you need the block with the datatime of '2022-06-02T13:00:00+00:00'

tidal heart
#

Oh my! So you mean that everytime I'm looking at those forecasts it's actually not in my timezone!? (at least the attributes I guess the UI sorts it out)

marble jackal
#

The last part +00:00 shows in which timezone it is

tidal heart
#

Ah!

marble jackal
#

if that shows no offset, it is in utc time

tidal heart
#

Now I get it! And when I try your code it renders nothing because this met.no does not actually have information on the current hour

charred dagger
#

... and then there's daylight savings time... as you can imagine programming this stuff is an absolute joy.

tidal heart
#

What country are you in?

marble jackal
#

Netherlands

tidal heart
#

Ah ok, the met.no is close for me as I'm in Sweden

#

Is there a way to like store the last hours info so I can access that as a "current" hour sensor? Like when 15 switch to 16 it stores the 15's info?

#

It does the same thing for the current day on the main sensor as well. I guess it kinda makes sense as they are forcasts but for some reason it does not use precipitation at all in the current attributes

#

I mean on the current day it would be nice with a "X% chance of rain"

marble jackal
#

You could make a trigger based template sensor which updates it on a time pattern (10 seconds before the whole hour for example) and stores the whole forecast attribute in an own attribute

tidal heart
#

Sounds good as long as I'm not rebooting/reloading at the wrong time 😄

marble jackal
#

correct 🙂

tidal heart
#

Thanks a lot for teaching me this! I was about to give up on it haha

#

The timezone trolled me bad

marble jackal
#

👍

tidal heart
#

Can I add an hour to your initial code to pull the hour after current hour?

Also I'm not sure if the weather forcasts switch to the next hour on for example 15:59:59 or if it can vary a couple of minutes

marble jackal
#

yes, but that will basically the first item in the list

#

{{ state_attr('weather.entity', 'forecast')[0].precipitation }}

wooden tusk
#

btw how to handle state triggers from MQTT button? I got the command to work but not how to catch the button state. It will just carry the date/time

marble jackal
#

A button doesn't have a state like on and off. The state is the last time it was pressed.

karmic prism
#

basically have the url and .mp3 after it and that needs to be part of the url

wooden tusk
floral shuttle
#

obv use an mqtt_event

wooden tusk
# floral shuttle use a trigger based template and template all you need? like:``` template: - t...

For my lights i use the following template, how to do the same for a button a catch the trigger?````

  • platform: mqtt
    name: "Garage Roof"
    schema: template
    state_topic: "pt:j1/mt:evt/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:8_0"
    command_topic: "pt:j1/mt:cmd/rt:dev/rn:zw/ad:1/sv:out_lvl_switch/ad:8_0"
    command_on_template: '{"corid":"","props":{},"serv":"out_lvl_switch","type":"cmd.binary.set","uid":"1d5a45b0-d2bd-11ec-901b-194ce6613fff","val":true,"val_t":"bool"}'
    command_off_template: '{"corid":"","props":{},"serv":"out_lvl_switch","type":"cmd.binary.set","uid":"1d5a45b0-d2bd-11ec-901b-194ce6613fff","val":false,"val_t":"bool"}'
    state_template: "{{ 'on' if value_json.val == true else 'off' }}"
#

equalent to the state_topic and state_template

floral shuttle
#

what exactly do you want to catch? As Fes says, the state of a button is merely the last_changed

wooden tusk
#

I want to catch the trigger aka state date/time. When the fysical button is pushed the MQTT payload is sent. I want to read that to HA so i can trigger my nodered event.

#

When pushing the button it works, so the command payload is fine.

abstract hatch
#

hi all, I'm currently trying my first template sensor, as I want to get some entity attributes as sensor, which I could implement accordingly. from the dev git of this integration I got {{ states.sensor.2minersinfo_miner_address.attributes['unpaid'] }}
as this is my first template I'm not 100% sure if the include in my configuration.yaml is working as expected too ``template:

  • binary_sensor: !include_dir_merge_list templates/binary_sensor/
  • sensor: !include_dir_merge_list templates/sensors/
  • trigger: !include_dir_merge_list templates/trigger/ ``

after the restart I get the following error Invalid config for [template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'minersinfo_ETH_Wallet') for dictionary value @ data['sensor'][0]['state']. Got "{{ states.sensor.2minersinfo_ETH_Wallet.attributes['unpaid'] }}". (See /config/configuration.yaml, line 29).

floral shuttle
#

so arent you in fact talking about a regular mqtt sensor? that sensor picks up the payload, and changes state. You can then trigger based on that state change?

wooden tusk
#

Yes i guess you are correct, the sensor might be right. But the then i cant trigger the sensor in HA, i will be forced to the fysical button.

#

Of course i could create a local button that changes the sensor locally

#

I was hoping that the MQTT button could be used both locally in HA so as the fysical button.

floral shuttle
#

you could write that trigger based template and use both the state change of the physical button (regular mqtt sensor) and a virtual button. Just start with the first, see if it works, and then add the virtual button

abstract hatch
#

you mean the name of the sensor? no the name of the sensor is - name: "Unpaid ETH Balance"

floral shuttle
#

entity_id starts with 2

abstract hatch
#

but the integration itself startes with 2 (2miners)

floral shuttle
#

try:{{ states.sensor['2minersinfo_miner_address'].attributes.unpaid }}

#

(cant test myself because dont have the entity)

abstract hatch
#

tried it .. currently restarting 😦 everytime these restarts 😦

floral shuttle
#

just reload templates....hit c key, type template and click the reload Template entities in the quickbar

abstract hatch
#

"nothing found"

floral shuttle
#

really sorry but I have to go.. again try in the dev template page, and maybe even {{ state_attr('sensor["2minersinfo_miner_address"]','unpaid')}} though again, I can not test myself

abstract hatch
#

ok will play around with that thank you

floral shuttle
#

this works locally:{{ states.automation["2v12_alarm"].attributes.last_triggered}} so if 'unpaid' is a regular attribute in your sensor, that format should work

karmic prism
#

i'm trying to build a string and failing its basically url, number, extension with the number being a variable so url/number is ok but the extension is separate so the link fails

abstract hatch
wooden tusk
orchid oxide
#

Are trigger.to and trigger.from available in trigger based template sensors

#

Just asking because they're not super easy to debug..

karmic prism
#

hi would anyone be able to help with what i thought was a simple template ?

ripe valley
#

Hello everyone

floral shuttle
ripe valley
#

I am struggling with a simple template for an automation:
condition: template
value_template: {{(now().day|int % ((states('input_select.watering_repeat'))|int) == 0)}}

#

and I am getting this:
Invalid condition configuration
template value should be a string for dictionary value @ data['value_template']

what's wrong with the above ?

#

input_select.watering_repeat contains numbers, from 1 to 7

thorny snow
#

Hi guys

floral shuttle
#

you need to set defaults on the |int , see the Pinned posted in the header here (this is besides any logical check, and purely syntax)

orchid oxide
inner mesa
floral shuttle
#

I get this in that template, because I dont have the entities: ValueError: Template error: int got invalid input 'unknown' when rendering template '{{(now().day|int % ((states('input_select.watering_repeat'))|int) == 0)}}' but no default was specified

ripe valley
#

the template is working fine in the devtools

thorny snow
#

Hi guys

#

how can I create a custom array in HA?

floral shuttle
ripe valley
#

@floral shuttle and @inner mesa : thank you, I'll check this

thorny snow
#

I want to create a weather template entity and in the forecast_entity field it needs to be an array.. how can I set a custom array?

floral shuttle
#

you should really search the commmunity for that, there are many examples and suggestions available, did you have a look?

orchid oxide
#

works fine in dev tools but, something like this wont recursively update, will it?

#
{%set alldistance = 20 %}
{%set alldistance = distance+alldistance %}
{{alldistance + distance}}```
#

uh in a template sensor

inner mesa
#

what part of that is recursion?

#

you're just referencing the current status of a sensor in the definition of the sensor?

orchid oxide
#

yeah, idk, im not sure if its going to see the status change and try and update it again

karmic prism
inner mesa
#

I see

karmic prism
#

it seems easy to add mystring ((trigger.json.message)) but adding a third part has me totally stuck

inner mesa
#

you've only included part of the definition, but I would expect it to be based on the value of another sensor, and the template sensor will only update when that other sensor updates

orchid oxide
#

yes, yeah

#

am i going to have to make a seperate sensor so that doesnt happen

inner mesa
#

It's not inherently a problem to reference the current value of a sensor, and in fact that was made easier via this in the last HA release. It will be a problem if you then trigger an update to the sensor based on updating the sensor

orchid oxide
#

ok, ill try to take this one step at a time. this template sensor doesnt appear to be triggering. what did i do wrong?

      platform: state
      entity_id: sensor.lexus
      attribute: Trip Distance(miles)
      to: '0'
  - sensor:
      - name: Old Day Distance
        state: >
          {{trigger.from_state.attributes[Trip Distance(miles)]|float+(states('sensor.old_day_distance'))) }}
#

sensor doesnt even show up with an unknown value

opaque creek
#

Hey! Could someone help me out here. I have this template here. Show me what I want to see, a simple time!

state: "{{ state_attr('sun.sun', 'next_rising') | as_datetime | as_local - timedelta(minutes = 45) }}"

But it turns out like this: 2022-06-03 03:33:26.128445+02:00
What do I need to add in the code to just show me the time in hours : minutes ? 😛

inner mesa
#
template:
  - trigger:
      platform: state
      entity_id: sensor.lexus
      attribute: Trip Distance(miles)
      to: '0'
    sensor:
      - name: Old Day Distance
        state: >
          {{trigger.from_state.attributes['Trip Distance(miles)']|float+(states('sensor.old_day_distance'))) }}
#

(note that I removed the extra "-" and you need to have it all nested under template: (or in an included file), which you didn't show)

#

Always:

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

inner mesa
#

also, you need to quote the attribute name

marble jackal
karmic prism
dreamy sinew
#

what is the value of trigger.json_message?

karmic prism
#

60149

#

the idea is to finish up with server/file .mp3 all the file names are numbers since its minidlna that serves them

dreamy sinew
#

seems like this works

karmic prism
# dreamy sinew

actually it kinda does , in an unexpected way see the filename should be 60149.mp3 so i wanted to concatanate the 60149 and .mp3 together along with the server path. serverpath and filename not a bother but i was getting url .mp3 so the extension wasn't part of the url. however i just tested something minidlna doesn't care 60149 and 60149.mp3 are the same as far as its concerned

dreamy sinew
#

lol

karmic prism
#

so i have just spent all afternoon trying to add an extension that isn't actually needed to make it work

#

it must be possible to template it with the extension i have done it before for a rest sensor

#

that i basically created 3 variables a , b, c and just assigned to d = a + b + c

orchid oxide
#

Is it possible to have multiple triggers for a template sensor and then use trigger ids with it? Not sure how that would be formatted if it works, don't really see much of anything about template triggers in the docs

#

something like

      platform: state
      entity_id: sensor.lexus
      attribute: Trip Distance(miles)
      to: '0'
      id: update
    trigger:
      platform: time
      at: '00:00:00'
      id: reset
    sensor:
      - name: Old Day Distance
        state: >
          {{trigger.from_state.attributes['Trip Distance(miles)']|float+
          (states('sensor.old_day_distance')|float(0)}}```
#

or would i just make 2 different templalte sensors for that

inner mesa
#

You make a list of triggers. It's exactly like an automation

orchid oxide
#

if theres something like an input number that doesnt allow manual adjustments, that would be cool to avoid an accident

silent seal
#

Mqtt sensors

inner mesa
#

A template number?

silent seal
#

Or that

orchid oxide
#

Template numbers remember their state after a reboot?

inner mesa
#

Hmm, I guess not:

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.

silent vector
#

What would a template be to pull all of this in as attributes? It's a rest sensor. Here's the api documentation too, scroll to the bottom for what a response is. I thought if it was application/json it would be read in automatically. It isn't doing that as I got an error it exceeded 255 characters meaning it attempted to pull it into the state.
https://dpaste.org/SOtzr
https://docs.developer.sleep.me/docs/

silent vector
#

Would this work?
{{ value_json | list }}

inner mesa
#

where do you plan to put that?

rose scroll
inner mesa
#

but you may be able to provide json_attributes_path to have them all pulled in without specifying each top-level key

tough linden
inner mesa
tough linden
#

ok sorry and thanks

silent vector
#
- platform: rest
    name: Left DockPro
    resource: 'https://api.developer.sleep.me/v1/devices/<DEVICE_ID>'
    scan_interval: 30
    headers:
      Authorization: !secret sleepme_api
      Content-Type: application/json
rose scroll
#

Try following the example Rob posted above to generate the attributes from the JSON output.

silent vector
#

Alright I'll do that, thank you.

coral sleet
#

I worked out a template that adds circuit 1+2 for my AC. I have 1 day and 1 mon total increasing values. I tried to add state_class: total_increasing to my sensors. However home assistant says platform:template state_class isn't valid any way I can resolve this

#

I am trying to get my AC to show up in my energy dashboard.

#

I already added device_class: energy

#

Invalid config for [sensor.template]: [state_class] is an invalid optopn for [sensor.template]

coral sleet
#

to save hours of fustration how would I convert the attached sensor

inner mesa
#

Please give it a try

coral sleet
#

I still get state_class is invalid for [template]

#

I have spent hours in fustration please help

#

is this even remotely right

inner mesa
#

There are clear differences between that and the very first example

coral sleet
#

well you said rewrite in some modern form

#

so I guessed at it

#

I have literally NO idea what I am doing wrong

inner mesa
#

alright

#

here's the example:

#
template:
  - sensor:
      - name: "Average temperature"
        unit_of_measurement: "°C"
        state: >
          {% set bedroom = states('sensor.bedroom_temperature') | float %}
          {% set kitchen = states('sensor.kitchen_temperature') | float %}

          {{ ((bedroom + kitchen) / 2) | round(1, default=0) }}
#

here's what you did:

#
template:
    sensors:
      name: "Air_Conditioner_Day"
#        state_class: total_increasing
      device_class: energy
      friendly_name: "Air Conditioner Day"
      unit_of_measurement: "kWh"
      state: >
        {{ ( (float(states('sensor.air_conditioner_2_16_1d')) + float(states('sensor.air_condition_1_15_1d')) )) }}

      name: "Air Conditioner"
      device_class: energy
#      state_class: measurement
      unit_of_measurement: "wh"
      state: >
        {{ ( (float(states('sensor.air_conditioner_2_16_1min')) + float(states('sensor.air_condition_1_15_1min')) )) }}
#

you have "sensors:" where the example has "- sensor:"

#

you have "name:" where the example has "- name: xxx"

#

Despite appearances, I am generally happy to help. But I do look for some effort to match examples that are very close to what you want

coral sleet
#

is this what you mean

inner mesa
coral sleet
#

rebooting to see if its right

#

the sensor does not appear in developer tools

#

I guess I have to delete friendly_name

#

and rebot

#

now they exist again but have unknown values

#

ok they came back

orchid oxide
#

i have a template sensor that gets confused after midnight , it uses today_at('00:00'). i dont really understand why this happens, or h ow i can tell it not to get confused

                {%set time = (strptime(pretime, "%d-%b-%Y %H:%M:%S.%f"))%}
                {% set triptime= state_attr('sensor.lexus', 'Trip Time(Since journey start)(s)')|float%}
                {%set offset = (((as_timestamp(time))-as_timestamp(today_at('00:00'))-triptime-(triptime/20))/3600)|round(2)%}
                {{'+'~offset if offset > 0 else offset}}```
#

works fine in dev tools template

#

the sensor is showing 19.71 which is what it would be showing at about midnight, likely 11:59

#

the template is showing -4.29 which is right

orchid oxide
#

do i just have to add somet hing extraneous in there that gets it to pay attention t o time like now()? why doesnt today_at() update at midnight, since, yknow, today changes at midnight

#

is there something that updates less frequently than every minute, like every hour?

thorny snow
#

Hi guys

#

I have this forecast data attribute whithin a sensor, it's an array:

#

I'd like get this array, select only the values whose date is the same as today or after today, and then, whithin every datetime, replace 22:00 with 00:00

#

how can I do that?

hollow jay
#

Hi
I Am trying to setup a template with a trigger but it seem that i miss some thing I am on 2022.6.1 in my configuration.yaml is the following

template:

  • trigger:
    • platform: time_pattern
      minutes: "/2"
      sensor:
    • name: "Estimate Inverter Runtime left"
      state: "{{ ((states('sensor.rct_ac_output_rating_active_power') | float * (((states('sensor.sunsynk_soc') | float) - 20) / 100) )/ states('sensor.inverter_load_avg') | float ) | round(2)}} "

but this do not trigger every 2 min. Without the trigger this sensor update about every second and i want to limit this

If I look at the logbook this sensor update vary between 6 min to 9 min update inverval
Any suggestion what I am doing wrong?

marble jackal
#

Note that these timestamps are in utc, so you are probably in GMT +2, so these timestamps are at midnight local time

#

Exactly what you seem to want :)

silent vector
marble jackal
silent vector
#

That was fast and it worked thank you.

tidal heart
#

I have an automation to notify when a new iOS release is out via an RSS feed using feedparser. It uses a template sensor that get's the information that I'm looking for looking like this https://www.toptal.com/developers/hastebin/aliwifucuc.kotlin

Everytime I reload the template entities it triggers though, what can I do to prevent that? Automation is looking at the state so I guess it gets unavailable or something. Heres the automation https://www.toptal.com/developers/hastebin/ubodopazug.less

#

It does not trigger on reboot, only on reloading template entitites

mighty ledge
tidal heart
#

Can I somehow stop an automation from triggering when state has been unknown anytime in the last 1 min?

#

It seems it moves from correct state to unknown and then back to that first state.

mighty ledge
charred dagger
#

A second automation that disables and enables the first?

#

Just reading the words of the question. Not considering any A/B-problem.

#

It's probably not the best solution for whatever you actually need.

marble jackal
#

A template binary sensor which turns on when the sensor state is unknown with a delay_off of one minute

mighty ledge
#

🤷‍♂️ I think the simplest solution is to just use not_from, it was specifically added to filter out state transitions on startup

tidal heart
#

I tried:

platform: state
entity_id:
  - sensor.apple_ios_latest
not_from:
  - unknown
not_to:
  - unknown

But that did not work

mighty ledge
#

are you sure your sensor is 'unknown'?

marble jackal
#

Or indeed not_from in combination with for

mighty ledge
#

you have to look at the from_state in the trace after a reload

#

I'd wager it's unavailable based on your code.

#

not unknown

tidal heart
#

Also tried a

condition: not
conditions:
  - condition: state
    entity_id: sensor.apple_ios_latest
    state: unknown
mighty ledge
#

99% sure templates go unavailable during reload. I'ts been a long time since I reloaded though.

tidal heart
#

This is still triggering it. I can't see what the state it changes to in the history tab, it's so small I can't select it and the logbook actually don't register any change at all.

platform: state
entity_id:
  - sensor.apple_ios_latest
not_from:
  - "unknown"
  - "unavailable"
  - "null"
not_to:
  - "unknown"
  - "unavailable"
  - "null"
for:
  seconds: 5
mighty ledge
#

did you reload the automation?

#

null isn't a valid option btw, you won't get that either.

tidal heart
mighty ledge
#

it's going to be unavailable or unknown, and drop the for

#
platform: state
entity_id:
  - sensor.apple_ios_latest
not_from:
  - "unknown"
  - "unavailable"
not_to:
  - "unknown"
  - "unavailable"
#

you can look in your history what the state is as well

tidal heart
#

I can't select them small breaks in the history tab

mighty ledge
#

change your timespan

#

you can go as small as 1 minute

tidal heart
#

Already tried that

#

Can I? It's like 5 min interval

mighty ledge
#

Ah, you can't type it

#

either way, you should still be able to see 5 seconds of state in 5 minutes, if you aren't then it's a smaller window than 5 seconds and the for: is your problem

tidal heart
#

Yeah they are to small

mighty ledge
#

then use the trigger I posted above

tidal heart
#

Already tried it, still goes trough

mighty ledge
#

reloads and to circle back for the 10th time, what does the trace show

#

it will literally show you what the before and after state is

marble jackal
#

Let it trigger on every state change and write trigger.to_state.state to a persistent notification

mighty ledge
#

you don't even need to do that, just look at the trigger trace data

#

it'll be on his last trace

marble jackal
#

👍🏼

mighty ledge
#

Click on the trigger, then click on changed variables

tidal heart
#

Step details?

mighty ledge
tidal heart
#

null

mighty ledge
#

in quotes?

tidal heart
#

Without

silent barnBOT
#

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

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

mighty ledge
#

Ah, the whole state is missing

#

so

#

add:

#

to conditions:

#
- condition: template
  value_template: "{{ trigger.to_state is not none and trigger.from_state is not none }}"
marble jackal
#

I always use iif for such checks

mighty ledge
#

I wouldn't use iff for checking none

#

when checking for none, you want to use is, not ==

tidal heart
#

That seems to have worked!

#

The condition stopped it from going trough

mighty ledge
#

TBH, I thought HA got rid of all those trigger events

#

I still have them in all my automations, but it's because I was too lazy to remove them.

#

So, I won't be removing them I guess

tidal heart
#

Hehe nah it seem to be a good idea to stick with them

mighty ledge
#

They must only be suppressed at startup

tidal heart
#

Thanks a bunch for the help! Learned to dig deeper into trace tab and that I can use trigger.to_state

marble jackal
#
{% set test = none %}
{{ test is not none }}
{{ iif(test) }}

both return False here

mighty ledge
#

yes, but that's because if test will return false, however if test is 0, which is valid, it will also return false.

#

if 0 -> false

#

if none -> false

#

if '' -> false

#

if you want to check for none, you have to use if is none

marble jackal
#

Yeah okay, or []

mighty ledge
#

right, same with {}

#

basically any "empty" object

#

will be false

#

for the built in objects

#

int, float, str, dict, list, etc

#

granted, those variables won't be thte built in objects so I guess you could use it

marble jackal
#

Yes, but in there is actually a from_state it will return True. So I agree you are not only checking for none

#

If you really want to know if something is none you can not use it

mighty ledge
#

well i think iff(x is none) would work

#

but that's just extra steps

#

when you could do x is none

#

it depends on what you want to catch. I use if x when don't want empty objects or none, and i use if x is none when explicitly looking for none

#

python isn't strongly typed, so in reality if you use x alot inside a method and you assign random objects to it, you'd want to explicitly search for none.

#

That's just me, you're welcome to handle it however you want. I like to make my stuff strongly typed, and always check for none to avoid exceptions.

marble jackal
#

I'll keep it in mind! Thanks for the advice

slate tundra
#

@marble jackal you are the right man for the job for sure. how can I make a list with all my light that is turned on but exclude from this list some lights that have certain names (I want to exclude some groups of lights that I've made) because at the end i want to count all the lights that are turned on (but only the lights not the groups too)

marble jackal
#

No need to tag me, other people here can help you as well

#

And there is a pinned post which explains how to get a list of lights which are on and are not a group

slate tundra
#

excellent man, thank very much

#

thanks both of you

bronze thunder
#

Hello fellow coder... I have a "I dont see it problem" here... damned. I need to add the matching "default=0" to the following line: value_template: 'Noch {{ ((as_timestamp(states("sensor.octoprint_estimated_finish_time",0)) | int /60/60) - (as_timestamp(now()) | int /60/60)) | round(0)}} Stunden'

mighty ledge
#

your parenthesis are wrong for states("...")

#

you have the ,0 inside the wrong parenthesis

bronze thunder
#

Ah, okay

#

Thats my eror - where do I have to set it here?

mighty ledge
#

the 0 should be for the as_timestamp(

#

as_timestamp(arg1, default)

#

arg1 is your states()

bronze thunder
#

WAAAAAAH

#

yes!

#

Thank you!

#

So, this is they ...? 'Noch {{ ((as_timestamp(states("sensor.octoprint_estimated_finish_time"),0) | int /60/60) - (as_timestamp(now(),0) | int /60/60)) | round(0)}} Stunden'

mighty ledge
#

sure, seems a bit verbose but it should work

bronze thunder
#

cool

mighty ledge
#

you could always just do this

#
Noch {{ ((as_timestamp(states("sensor.octoprint_estimated_finish_time"), 0) - as_timestamp(now())) / 3600) | round(0) }}
tidal heart
#

I'm trying to figure out how to make an heavy rain alert using an hourly forecast. I'm trying to pull if there will be more than 10 precipitation between two hours the current day and what datetime it will start.

thorny snow
# marble jackal What is your goal here? Normally all values in the forecast are today or later, ...

that array is the stock info from the weather integration. As you can see, according to the data, every day starts at 22:00. What happens is, when I set the weather card in Lovelace, the day won't start until 22:00, so in lovelace until 22:00, Tuesday's forecast shows up as Wedensday's forecast. At 22:00 it does what it's supposed to but at 00:00 it's crapped again, Wednesday's forecast shows up as Thrusday's forecast. I want to create a weather template correcting that error

marble jackal
#

Which is 22:00 UTC time

thorny snow
#

nope

#

I'm telling you the problem is that. I have already built the new array and it's working as expected, but I built it using Node Red

#

I want to know how to achieve the same using YAML

marble jackal
#

And I'm telling you the timestamps are in UTC. As your were using pastebin.pl, I assume your are in Poland, which is GMT +2

#

So 22:00 + 2 hours is midnight

thorny snow
#

You mean I should set a +2 instead of replacing the 22:00?

tidal heart
marble jackal
mighty ledge
thorny snow
#

I'm sorry I wish I understood you but I'll look into in further..

#

I don't get did

mighty ledge
#

+00:00 at the end means that the timestamp is in UTC

thorny snow
#

I do know however doing what I did has worked. Why?

#

even though that might be midnight in myu local time

#

for some reason when I set the card

#

the card doesn't interpret it as it should..

mighty ledge
#

time is hard when you dont understand it

thorny snow
#

^^

mighty ledge
#

you have to convert time depending on that timezone it's in for comparisions

tidal heart
#

Oh this again... time zone's trolled me bad yesterday

thorny snow
#

the integration is Spanish and I'm from Spain

mighty ledge
#

so what

#

the time in the datetime attribute is UTC

thorny snow
#

oh I got it now

mighty ledge
#

UTC is UNIVERSAL TIME COORDINATE

thorny snow
#

I see I see

mighty ledge
#

so what time is it where you live?

thorny snow
#

15:04

mighty ledge
#

it's 9:04 here

#

is it the same time?

#

Yes, it's the same time. However we are in different timezones.

#

UTC is agnostic of what timezone you're in

#

it's the same for everyone

#

in the world

tidal heart
#

Where UTC is 15:00
GMT +2 is 17:00

thorny snow
#

yeah I gort it

#

that's exactly it

#

then it's supposedly right, at 22:00 it's midnight here as TheFes suggested

mighty ledge
#

in python, whenever you see +00:00 at the end of your timestamp, it's UTC

thorny snow
#

why isn't the card doing a good job then?

mighty ledge
#

what card

thorny snow
#

weather card

mighty ledge
#

is this the basic weather card or what?

thorny snow
#

basic

mighty ledge
#

is your timezone set in HA?

thorny snow
#

let me check

#

Yes it is

mighty ledge
#

ok, so what's wrong on the weather card then?

#

also keep in mind that your browser will come into play

thorny snow
#

forecast info from today

#
  - condition: rainy
    precipitation_probability: 100
    temperature: 20
    templow: 12
    datetime: '2022-06-03T22:00:00+00:00'
    wind_speed: 10
    wind_bearing: 315```
#

lovelace card sets this values as tomorrow's forecast

#

at 22:00 local time, it does shows this values as today's forecast

mighty ledge
#

well that is tomorrow

thorny snow
#

that is today sir

mighty ledge
#

no it's not

thorny snow
#

06-03

mighty ledge
#

and converted into local time, its 6-4

thorny snow
#

oh my

mighty ledge
#

😉

thorny snow
#

xD

mighty ledge
#

what's 22 + 2?

#

24

thorny snow
#

lol

mighty ledge
#

also known as 0

#

which is tomorrow

thorny snow
#

thanks for your time...

#

oh my

#

it doesn't get sillier than this

tidal heart
#

Your not alone m8, had that kind of a problem yesterday as well

thorny snow
#

thanks for your time petro and TheFes, I appreciate

mighty ledge
#

np

tidal heart
#

Can I somehow get the object number to use to pull all the information from whatever is in the same object as my | first

mental violet
#

Hi, I dont really know the right syntax:

data: 
  entitiy_id: >
    {% set entities = states.input_boolean |selectattr('object_id', 'search',
    'is_lovelace_allgemein')|selectattr('state', 'eq',
    'on')|map(attribute='entity_id')|remove input_boolean.this_explicit_entity_id|list %} 
    {{entities}}
#

so I have 2 problems:

  1. This whole template doesnt run with "service: input_boolean.turn_off"
  2. how do I remove 1 exactly entry in that template list
mighty ledge
sacred sparrow
#

is anyone able to tell me why this is showing as "true"

{{ as_timestamp(state_attr('calendar.kls_sync','start_time')) | timestamp_custom('%A %B %-d, %Y')
!=
as_timestamp(now()) | timestamp_custom('%B %-d, %Y') }}

Even though:
calendar.kls_sync = June 6, 2022
now = June 3, 2022

#

basically I just want to show it as true if start_time is today

mighty ledge
#

they'll never be the same

#

so that will always be true

sacred sparrow
#

is there a better way to do it?

#

start_time format is "2022-06-06 09:30:00"

mighty ledge
mighty ledge
#

'%A %B %-d, %Y' format is not the same as '%B %-d, %Y'

sacred sparrow
#
{{ as_timestamp(state_attr('calendar.kls_sync','start_time'))
| timestamp_custom('%D')
!=
as_timestamp(now())
| timestamp_custom('%D') }}

Same format now but still getting True

mighty ledge
#

because %D isn't valid

sacred sparrow
#

I also tried

{{ as_timestamp(state_attr('calendar.kls_sync','start_time'))
| timestamp_custom('%d/%m/%y')
!=
as_timestamp(now())
| timestamp_custom('%d/%m/%y') }}
mighty ledge
#

ok, and what does each one say?

#

I'm guessing you didn't read the conversation that occured directly before this one and you're start time is in UTC

sacred sparrow
#

06/06/22
03/06/22

mighty ledge
#

alright, those aren't equal so..

#

that will be true

sacred sparrow
#

oh I see. I meant == not !=

#

thanks for your help 🙂

mighty ledge
#

np

tidal heart
mighty ledge
tidal heart
#

If it today will rain more than 10mm, when does it start and how much will it rain

#

Ideally I would like it to check if there will be more than 10mm rain over two hour periods but that seems much harder

mighty ledge
#
{% set forecast = state_attr('weather.dark_sky', 'forecast') %}
{% set midnight = today_at().astimezone(utcnow().tzinfo) %}
{% set tomorrow = midnight + timedelta(days=1) %}
{% set next_rain = forecast | selectattr('datetime', '>', midnight.isoformat()) | selectattr('datetime', '<', tomorrow.isoformat()) | rejectattr('precipitation', 'eq', none) | selectattr('precipitation', '>', 10) | list | first | default(none) %}
{% if next_rain is not none %}
  {{ next_rain.datetime }}: {{ next_rain.precipitation }}
{% endif %}
#

@tidal heart

tidal heart
#

Wow!

#

I need to try an understand the flow here

#

Thank you for taking the time to help!

bleak wolf
#

part 2: if that's indeed just a user-id... there a way to translate that to a name?

marble jackal
#

You need context.user_id and that is indeed only an id

bleak wolf
#

i guess i gotta figure out how to translate to a name now.

bleak wolf
#

thank you! oh man.

#

figures that it's not even a hass article.... leave it to ludeeus

#

oh man that works great. thank you TheFes 🙂
Notify Discord of Door/Window Open/Closed has been Disabled by Michael

frank gale
#

Is there a filter to sum up the states of a given entities? like:

{{ states.number 
     | rejectattr("state","in",["unavailable","unknown"]) 
     | sum(attribute="state") }}

( this fails because state = string and expects int )
Or should I do that with a for loop?

inner mesa
#

Use map(attribute='state')|map('float')|sum

dreamy sinew
#

yeah, literally called sum 🤣

frank gale
floral shuttle
#

heck, what did I miss? Passing templates to notify service is deprecated and will be removed in 2021.12. Automations and scripts handle templates automatically

#

is it complaining about things like: service: notify.system data: message: > {% set message = state_attr('persistent_notification.httplogin','message') %} {{now().timestamp()|timestamp_custom('%d %b: %X')}}: {{message}} Track offending ip on http://www.ip-tracker.org/locator/ip-lookup.php?ip={{message.split('from ')[1]}} title: > {% set title = state_attr('persistent_notification.httplogin','title') %} Ha Rpi4:{{title}} ?

inner mesa
#

Maybe if you call it via devtools -> services

#

It's saying that the service itself doesn't render templates

mighty ledge
#

I'm still using them, no error here. Must be specific to whatever nofity.system is sending to

inner mesa
#

The data: block of a service call handles it for the service

floral shuttle
#

I mean, all my notifications are using templates.... but they are in the scripts and automations, so I just dont get the message here

#

At Rob: yeah, so my example above would be correct according to that wouldnt it?

inner mesa
#

devtools -> Services doesn't render templates, so it passes them straight to the service. Then the service itself either just sees the text or actually renders them

floral shuttle
#

it might have been this text message selector: intercom_message: name: Intercom message options: - Komen jullie allemaal aan tafel, het eten is klaar! - Wie laat George even uit, hij heeft er echt zin in. - Alles staat klaar voor de volgende aflevering van 2 voor 12 - > {{states('input_text.message')}}

#

I may have fluked that into an error by pressing the Send button before the template was actually displayed

#

let me test once again

#

hmm, cant make it happen again, though interesting errors are logged when sending an empty message via the input_text

#

also, its really odd,because those messages are all used in tts.cloud_say services, and not in a notify service.... so it must have been something else I figure

#

making this really an integration issue I now notice... sorry for the wrong #

manic onyx
#

hi everyone. A simple one - how do I output current date with timezone?

mighty ledge
#

{{ now().date() ~ ' ' ~ now().tzinfo }}

silent vector
#

How would I add is_state_attr to this?

Result from this is 67, how would I say is_state_attr 67 for example.

"{{ state_attr('sensor.left_dockpro', 'control').set_temperature_f }}"
frank gale
silent vector
#

Worked, thank you.

frank gale
#

Is there any way to check the last_changed from an entity_id in a variable?
Like this:
{{ states. ~ var ~ .last_changed }}
var contains an entity_id but it doesn't work ( expected name or number )

marble jackal
#

{{ states[ var ].last_changed }}

frank gale
#

Yes! Thank you!
I was so far, only I had an extra '.'
{{ states.[ var ].last_changed }}

bronze tide
#

Hi guys!

#

Is there a way to define the order of execution of templated attributes assigned to one entity?

whole marsh
#

just updated to 2022.06 and getting this now in the startup log:

TemplateError('ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ 'True' if states('sensor.washer_current') | float > 0.041 else 'False' }}' but no default was specified') while processing template 'Template("{{ 'True' if states('sensor.washer_current') | float > 0.041 else 'False' }}")' for attribute '_state' in entity 'binary_sensor.washer_running'

guessing it's related to the breaking change for templates. I've read it but don't understand the issue. can someone help? Here's the template: {{ 'True' if states('sensor.washer_current') | float > 0.041 else 'False' }}

buoyant sapphire
#
{{ states('weather.home') == 'sunny' }}
or
{{ states('weather.wetter_von_accuweather') == 'sunny' }}

I am using two weather services for my arena, because sometimes only one states "sunny", while the other says "cloudy".
How can I logically connect those two in a template, so that the entire template is "true" if only one of the two is "true"?

lunar osprey
#

Hello

#

{%- for state in states.light -%}

#

how is it possible to remove the Browser Mod lights?

#

how can I get the integration from "state" ?

buoyant sapphire
marble jackal
# whole marsh just updated to 2022.06 and getting this now in the startup log: `TemplateError...

Your sensor.washer_current was not ready when the template was rendered, and therefore the float filter got an invalid input.
You can resolve that by providing a default for the float filter float(default=0) or simplyfloat(0) or by providing an availability template in your template sensor config like {{ states('sensor.washer_current') | is_number }} ensuring the value template will only be rendered when the source sensor is providing a valid result

marble jackal
marble jackal
whole marsh
dark sparrow
#

hello all, I have a question for template-experts 😉

#

I have this:

#
  • platform: mqtt
    name: Helium
    state_topic: "helium/86acb131-b25d-48b1-920c-e920e67c1997/rx"
    value_template: '{{ value_json["decoded"]["payload"]}}'

The data I get is this:
{'BatV': 3.001, 'Ext_sensor': 'Temperature Sensor', 'Hum_SHT': '43.1', 'TempC_DS': '327.67', 'TempC_SHT': '25.44'}

#

I need the 3 sensors inside HomeAssistant: BatV, Hum_SHT' and TempC_SHT, how can I do that?

wicked rune
#

Hi all, can anyone tell me how I can display the state of a switch without the ability to turn it on or off? I have an automation that controls an HRV fan, I'd like to display whether the fan is running without the user being able to turn it on or off.

inner mesa
#

A template binary_sensor

wicked rune
#

thanks, i'll look into that!

inner mesa
wicked rune
#

worked perfectly!

wicked rune
#

With an input select, is it possible to get it to turn a switch on based on the state of the input select without building an automation? i have an input_select with three options: on, off and auto. if the input_select is on, i'd like to turn a switch on. if the input_select is off, i'd like to turn the switch off. if the input_select is auto, i'd like to control the switch from automation.

bronze tide
#

Hi all!

#

Is there a filter which can calculate any kind of checksum on a string? Goal would be to store the output in another attribute.

orchid oxide
#

can i do a for each in an automation like, for each entity whos id contains trip, do x?

#

the documentation examples only cover pre-defined lists of entities

orchid oxide
#
    if (
          (state.entity_id.startswith("sensor.trip_") if 'yesterday' not in state.entity_id and "Device Time" in state.attributes)
        )  -%}        
        {%- if loop.first -%}{% elif loop.last -%} {% else -%}  {% endif -%} 
           {{state.entity_id}} {% if state.name.startswith('trip_1')%}  {%else%}  {%endif%}
{% endfor%}```
i wanna use this in a for each in an automation
inner mesa
#

This repeat form accepts a list of items to iterate over. The list of items can be a pre-defined list, or a list created by a template.

orchid oxide
#

do i just put a template in there?

#

like i just go

            {%-for state in states 
    if (
          (state.entity_id.startswith("sensor.trip_") if 'yesterday' not in state.entity_id and "Device Time" in state.attributes)
        )  -%}        
        {%- if loop.first -%}{% elif loop.last -%} {% else -%}  {% endif -%} 
           {{state.entity_id}} {% if state.name.startswith('trip_1')%}  {%else%}  {%endif%}
{% endfor%}```
#

figiured it out i think, not sure if it works, but its valid lol

#

my list is outputting as a string, not a list..

#

how do i convert the result, which is a string, into a list...

#

the result is a string

sensor.trip_2```
#

i cant slice because it's a foreach

#

and even adding {{', ' if not loop.last}} doesnt work

inner mesa
#

I don't understand the logic there, but you need to use a namespace and add each item to a list

#

like:

#

{%- if loop.first -%}{% elif loop.last -%} {% else -%} {% endif -%}

#

🤷

orchid oxide
#

ive never used namespace before 😅

inner mesa
#

ok

orchid oxide
#

im sure thats simple, but i dont understand it lol

inner mesa
#

why do you have that useless line in there?

#

it literally does nothing

orchid oxide
#

tbh i copied the code from a random post on the forum

inner mesa
#

excellent

orchid oxide
#

lol

#

im looking into namespace and im not really understanding how to use it to return a list...any examples would be super helpful, i learn best when i see someone else do things

marble jackal
#

Why are you adding all these empty if statements? Lijkt Rob also pointed out above

#

Furthermore it looks like you also don't need to use a loop here

orchid oxide
#

i've reduced the useless garbage

#

{%for state in states if state.entity_id.startswith('sensor.trip_') if 'yesterday' not in state.entity_id and "Device Time" in state.attributes%}
{{state.entity_id}}
{%endfor%}```
#

but i dont understand how to do this really at all, moreso without a loop

marble jackal
#

Does this work?
{{ states | selectattr('entity_id', 'match', '^sensor.trip_') | rejectattr('entity_id', 'search', 'yesterday') | selectattr('attributes.Device Time', 'defined') | map(attribute='entity_id') | list }}

orchid oxide
#

except that it adds entities with 'device time' that dont contain 'trip' in the entity_id

marble jackal
#

I've added that now

orchid oxide
#

yeah that works. thanks. now ill try to understand whats new to me here so i can do it my own next time

#

appreciate the patience, most of this is new to me, just learning as i go along..

marble jackal
#

@orchid oxide
states get all state objects
selectattr('entity_id', 'match', '^sensor.trip_') select only those objects for which the entity id matches the regex for begins with sensor.trip_
rejectattr('entity_id', 'search', 'yesterday') reject those objects for which the entity id contains the word yesterday
selectattr('attributes.Device Time', 'defined') selects those objects which have the attribute Device Time defined
map(attribute='entity_id') take the entity id out of the selected state objects
list create a list from these entity ids

orchid oxide
#

oh wow, thanks for the in depth explaination. really appreciate it

#

im a little on clear on the proper syntax for a template in 'for each' in an automation ive tried a number of things, but its coming back with none rather than the list

  for_each: >-
    {{ states | selectattr ('entity_id', 'match', '^sensor.trip_') | rejectattr('entity_id',
    'search', 'yesterday') | selectattr('attributes.Device Time', 'defined') |
    map(attribute='entity_id') | list }} 
  sequence:```
#

i tried - {{ states... too, comes back none

marble jackal
#

If that template works in devtools > templates, it should work in the for_each as well

orchid oxide
#

ill try to pull it up in a persistant notification, maybe im just calling it imporperly

marble jackal
#

.share your whole script/automation

silent barnBOT
#

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

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

orchid oxide
#

i figured it out. i was using 'repeat.item' instead of repeat.item

#

so it works now, ty for the help

marble jackal
#

👍🏼

bronze tide
#

Can anybody tell me whether there is a filter available to create a checksum like MD5 on a string? I found a filter called hash, but this does not seem to be part of HA.

manic onyx
#

Hi everyone. Can someone please suggest a way to display the largest water use times for a day? I have a sensor that increments for each liter use. I use it to increment the utility sensors for hour, day etc. But I want to know not the largest use hour (that I have already) but also when the largest use started, ended and how much water was used

wicked rune
#

With an input_select, is it possible to get it to turn a switch on based on the state of the input select without building an automation? I have an input_select with three options: on, off and auto. If the input_select is on, i'd like to turn a switch on. If the input_select is off, I'd like to turn the switch off. If the input_select is auto, I'd like to control the switch from automation. Maybe the best solution would be a dummy template switch that gets it's state from the input_select and then has an action to control the physical switch?

modern torrent
#

Hey i hope someone can help me, have been trying for a while but something about my syntax seems to be off

I am trying to access a url inside a still_image_url section but i need the info from a diffrent sensor
still_image_url: http://xxx.xxx.xxx.xxx/server/files/gcodes/.thumbs/{{ states((‘sensor.3d_printer_current_print’)) }}-400x300.pngthe sensor i am using for this looks like this:

  friendly_name: "Current Print"
  value_template: ‘{{ states.sensor.3d_printer_current_print.attributes[“print_stats”][“filename”][:-6]}}’```
the :-6 should remove the last six charakter since they are not needed

probably is something silly but i cant seem to figure it out
marble jackal
#

You have some fancy quotes there..

marble jackal
wicked rune
wicked rune
#

Is there an example anywhere? I'm having a hard time googling it, since the term "select" is fairly generic.

marble jackal
#

Something like:

template:
  - select:
      - name: Some name
        state: "{{ option }}"
        options:
          - petunia
          - whale
         select_option:
           - if: "{{ option == 'petunia' }}"
             then:
               - do something
             else:
               - do something else
#

But then using the right indentation 😅

wicked rune
modern torrent
# marble jackal You have some fancy quotes there..

Okay so i got further, i am getting the correct value into my sensor, but my url ends up being
http://xxx.xxx.xxx.xxx/server/files/gcodes/.thumbs/shelly + door hinge-400×300.pngbut when i type that into the browser i gethttp://xxx.xxx.xxx.xxx/server/files/gcodes/.thumbs/shelly%20+%20door%20hinge-400%C3%97300.pngBut what i want is http://xxx.xxx.xxx.xxx/server/files/gcodes/.thumbs/shelly%20+%20door%20hinge-400x300.png

#

i assume %20 is spacebar, can i somehow turn all spaces into %20 in a template?

marble jackal
#

| replace(' ','%20')

modern torrent
#

thanks....it would have worked without...the probem was the "400×300.png"

...you see the x? its not a regular x 🤣
but thank you for the help, will still replace the spaces

#

well thanks to whoever wrote this damn blogpost from where i copied this...

wicked rune
# marble jackal But then using the right indentation 😅

So I've tried to create the template, but I'm getting an error when I restart Home Assistant.

template:
  - select:
      - name: "HRV Mode"
        state: "{{ option }}"
        options:
          - On
          - Off
          - Auto
        select_option:
        - if: "{{ option == 'On' }}"
          then:
            - service: switch.turn_on
              entity_id: switch.shelly1_3c6105e37612
wicked rune
modern torrent
#

you should always check your config files with the developer options yaml checker instead of restarting or atleast i would highly recommend that

wicked rune
modern torrent
#

oh really? interessting then i have said nothing 😄

wicked rune
#

So I guess the syntax is right

marble jackal
#

Hmm, guess you should use options: {{ [ 'yes', 'no', 'maybe' ] }}

wicked rune
#

Okay I'll try that

marble jackal
#

And you know you don't need to reboot right? You can reload template entities in devtools > YAML

wicked rune
#

Even when they're in configuration.yaml? I thought any time entries were changed in configuration.yaml, you had to restart.

inner mesa
#

Where they are doesn't matter. Everything starts from configuration.yaml

wicked rune
#

Oh amazing, I didn't know that.

#

This seems to work well now, but I notice when I reload the template entities it starts in an unknown state. Is there a way for it to remember it's previous state?

  - select:
      - name: "HRV Mode"
        state: "{{ option }}"
        options: "{{ [ 'On', 'Off', 'Auto' ] }}"
        select_option:
        - if: "{{ option == 'On' }}"
          then:
            - service: switch.turn_on
              entity_id: switch.shelly1_3c6105e37612
        - if: "{{ option == 'Off' }}"
          then:
            - service: switch.turn_off
              entity_id: switch.shelly1_3c6105e37612
marble jackal
#

optimistic: true maybe?

wicked rune
#

I tried that, but it doesn't look like that works. When I reloaded it immediately went to unknown. This error shows in the log, which I guess is because the variable isn't defined when the template is loaded. Template variable warning: 'option' is undefined when rendering '{{ option }}'

silent barnBOT
floral shuttle
#

with all of these efforts preventing the unkown's in the template configs, what would be the advantage over a single input_select and a small automation? they are very robust, and are restored, so never turn unknown..

wicked rune
#

The template select seems to work well except for the initial state.

floral shuttle
#

yeah, maybe. though my question was an honest one. I always try to follow the new HA core options, and havent come to terms yet with many of these new template integrations... 😉 so was hoping for a direct and positive answer tbh. Without all the hassle of setting defaults and preventing the consequences of the broader templating quirks, these formats seem very attractive. Getting to silence the logs, makes them more complicated, and then the 'advantage' over the ancient techniques become less obvious

wicked rune
#

or rather, i'd like the start up value to be the previous state.

floral shuttle
#

so you dont have an action for the option Auto yet? not sure if that would work, but you could test that ofc. Still, if you have anther automations for the option Auto, why not add:{% if trigger.to_state.state in ['on','off'] %} service.turn_{{trigger.to_state.state}}

wicked rune
#

I meant to have an Auto in the template select that would turn the switch off initially. Then any automations I built would only run under the condition that Auto is selected.

floral shuttle
#

right, I see. well, as I have made abundantly clear above, I am no expert on the template select at all, so not the best person to advise you there. Seems a bit contrived tbh. if possible, keep things simple. as possible.

marble jackal
#

I also never used it myself, but if the state doesn't restore I would also suggest to go for the input_select and an automation

wicked rune
#

My concern with the automations is that they can terminate before being executed completely. In my automation, I want to run the HRV so many minutes per hour if the selector is Auto. So in my automation, at the top of the hour I turn the HRV on, then wait X minutes, then turn it off. So what happens if I reload the automations before they're complete (during the wait period?). The HRV doesn't end up getting turned off. So I thought with the template select, I'd be able to have the switch automatically turned off when the template loads.

marble jackal
#

Use a time pattern trigger with the state of the input_select as a condition

wicked rune
#

You mean separate the automations between on and off?

marble jackal
#

Or add triggers on automation reload and home assistant start

#

What you also could do instead of an input_select and automation is an input_select and a template select

#

Set the input_select to the same state as the template select in the actions, and use the state of the input_select for the state of the template select

wicked rune
#

Hmmm, yes I can see how that could work. Ideally I'd only have the automations trigger if the input_select is Auto. I'm having enough trouble with Auto already because I have a few different conditions there. I want to run the HRV a certain number of minutes per hour, but then if the bathroom humidity gets above a certain value I also want it to run until the humidity drops. So even those two conditions can create conflicts.

#

Ah, no that won't work. The input_select changes the state of the template select, but the template select actions don't run.

#

I guess I just need to figure out how to do this with input_select and automations, and maybe have an automation that turns the switch off when it loads initially.

silent barnBOT
manic tartan
#

Can you help with the above problem. Don't get it (template newbie). What am I doing wrong :-)?

#

It works perfectly as a template, but not in the automation.

silent barnBOT
inner mesa
#

Seems clear - the string exceeds 64 characters

#

You're also missing an 'else'

manic tartan
#

Thanks, sure 'else' fixed. Why it works in HA GUI in template section? I understand the message (MaxLengthExceeded), but what characters counts?

#

It seems event_type string is too long, but why?

inner mesa
#

Because the template editor doesn't care how long it is

#

I'm just reading the error message

#

It's quite clear

#

Many things have a maximum length

manic tartan
#

OK, so how to evaluate this within 64 characters :-)? The limit is for jinja2 syntax (300 characters), not the result itself?

inner mesa
#

The string that results is too long

#

Oh, the real problem is that it just sees the whole template as the event string and isn't evaluating it at all

#

You would have to use an if/then or choose: to conditionally fire a different event

manic tartan
#

Thanks. Will try this, but it so long syntax works like a charm for service:, and why not for events: ...

inner mesa
#

I don't think custom events are used very often, and it takes somebody that cares

manic tartan
#

action:
- service: >
{% if is_state('input_boolean.livingroom_music_mode', 'off') %}
input_boolean.turn_on
{% else %}
input_boolean.turn_off
{% endif %}
data:
entity_id: input_boolean.livingroom_music_mode

#

this works fine, and it is 175 character long

inner mesa
#

Because it supports templates

manic tartan
#

ok, so event don't? OK

inner mesa
#

You're welcome to file a feature request on the forum

manic tartan
#

Thanks for help.

bronze tide
#

I was wondering whether there is a jinja filter available which can provide a simple check sum on a string like sha or md5 . I saw a filter called hash, but this was outside the HA scope.

inner mesa
#

Answer hasn't changed

bronze tide
inner mesa
#

You asked if there was a filter, and there isn't

#

Your problem will continue to exist

bronze tide
#

So now two people told me 'no' and as you mentioned my problem will continue to exist.... What a solution!

peak shoal
#

Take a step back, and detail your actual problem. What is the actual problem at the higher level that has resulted in your checksum approach. The solution to your problem might be a lot simpler than needing a checksum if the problem is solved a slightly different approach than the one you are currently on.

bronze tide
#

I want to have a short representation of a string ( made of a sorted list containing device names) which might be longer than an ordinary state can hold to compare it later on.

peak shoal
#

templates are probably not the best for that, in node-red you could implement a basic substitution approach in a function node for something like that

mint crane
#

Hello, I'm struggling to get the right mix of value_templates to get the first 'power' value from my json (in this case 530.44). Is it possible to retrieve this without an iterator?

The value of states.sensor.shelly_em.state is ...
[{'power': 530.44, 'reactive': -406.79, 'voltage': 245.44, 'is_valid': True, 'total': 20020.7, 'total_returned': 0}, {'power': 0, 'reactive': 0, 'voltage': 245.44, 'is_valid': True, 'total': 0, 'total_returned': 0}]

inner mesa
#

like {{ value_json[0].power }}?

mint crane
#

I've been trying to work it in the Developer Templates page using something like {{ states.sensor.shelly_em[0].power }} but it claims "object has no element 0"

#

your answer shortcuts where I'm heading anyway.. so thanks! I'll give that a go.

inner mesa
#

That's just the state object

#

And states are strings anyway

mint crane
#

ahh i see

inner mesa
#

Is that really the state?

mint crane
#

it was someone down a few layers, but not quite far enough

#

value_template: "{{ value_json.data.device_status.emeters[0].power }}" is what i'm needing

#

thank you. you got me where i needed to be

sacred sparrow
#

its very long at the moment

marble jackal
#
{% set ns = namespace(count = 0) %}
{% set start = states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_appointments_event_`) | map(attribute='attributes.start') | list %}
{% for item in start  %}
  {% if as_datetime(item).date() == now().date() %}
    {% set ns.count = ns.count + 1 %}
  {% endif %}
{% endfor %}
{{ ns.count > 0 and is_state_attr('sensor.ical_work_appointments_event_0','summary',"Busy") }}
sacred sparrow
#

I would have never been able to figure that out! Thank you - I’ll give it a go

#

Is there a way I can set a input.number to the number of how many events come back as true? I want to do a text to speech to say “you have x events today”

#

I’m guessing setting the count as input.number

marble jackal
#

Well, you don't need to set an input number, the ns.count is what you're looking for if I understand you correctly

sacred sparrow
#

I currently have that for another calendar but want to change it for the one listed first

orchid oxide
#

is it possible to use this.entity_id inside a config template card which has been nested in an auto entities card

#

or some other way to pull the attribute state of this.entity_id

#

Using this.entity_id within the card, same way you would to call any other state, doesn't work. Soon as I put this.entity_id in a template the whole thing just renders blank

sacred sparrow
# marble jackal ```jinja {% set ns = namespace(count = 0) %} {% set start = states.sensor | sele...

I changed the name of the entity but I am getting an error - Do you see anything wrong after I've changed the entity?:

{% set ns = namespace(count = 0) %}
{% set start = states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_appointments_event_`) | map(attribute='attributes.start') | list %}
{% for item in start  %}
  {% if as_datetime(item).date() == now().date() %}
    {% set ns.count = ns.count + 1 %}
  {% endif %}
{% endfor %}
{{ ns.count > 0 and is_state_attr('sensor.ical_work_appointments_event_0','summary',"Busy") }}
#

Developer tools > templates says:
TemplateSyntaxError: expected token ',', got 'attributes'

inner mesa
#

you have a funky quote:
'^sensor.ical_work_appointments_event_)`

sacred sparrow
#

ah If I change that I get:
TypeError: float() argument must be a string or a number, not 'datetime.datetime'

orchid oxide
#

javascript question. how do i get hh:mm from a timestamp? using the config taemplate card ive got

${(Date.parse(states[this._config.entity].attributes['Device Time']))} which returns a timestamp 1654457964877. I'd like to extract hh:mm from this

inner mesa
#

All your config template card questions should be in #frontend-archived . This channel is for Jinja

orchid oxide
#

ok, thanks

sacred sparrow
#

I changed from as_datetime to the below and it's showing up as FALSE when its meant to be true:

{% set ns = namespace(count = 0) %}
{% set start = states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_calendar_event_') | map(attribute='attributes.start') | list %}
{% for item in start %}
{% if as_timestamp(state_attr('sensor.ical_work_calendar_event_0','start')) == as_timestamp(now()) | timestamp_custom('%d/%m/%y') %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count > 0 and is_state_attr('sensor.ical_work_calendar_event_0','summary',"Busy") }}

This works though but its long:
https://www.toptal.com/developers/hastebin/ugizekubix.java

marble jackal
manic onyx
#

hi everyone. I am using template sensor and want to set the state value to be a value of another state's attribute, which is integer. But I also want to set the attribute of that new sensor to be a text explaining what that attribute is.
This is what I have and it works fine, but sets the verbal state. I want state value to remain the integer
verbose_vacuum_state: friendly_name: "Verbose Vacuum State" value_template: > {% set index = state_attr('vacuum.viomi_v18_04fb_robot_cleaner', 'vacuum.status')|int %} {{ ('Sleep', 'Idle', 'Paused', 'Go Charging', 'Charging', 'Sweeping', 'Sweeping and Mopping', 'Mopping')[index] }}

#

Is that json_attributes_template?

#

reading the docs. Looks like I am using old config 🙂

#

so its "state" and "attributes"?

marble jackal
#

You are, but this works in legacy template sensor format as well

manic onyx
#

thank you!

marble jackal
#
      verbose_vacuum_state:
        friendly_name: "Verbose Vacuum State"
        value_template: >
          {{ state_attr('vacuum.viomi_v18_04fb_robot_cleaner', 'vacuum.status') }}
        attribute_templates:
          verbose_state: >
            {% set index = state_attr('vacuum.viomi_v18_04fb_robot_cleaner', 'vacuum.status')|int %}
            {{ ('Sleep', 'Idle', 'Paused', 'Go Charging', 'Charging', 'Sweeping', 'Sweeping and Mopping', 'Mopping')[index] }}
manic onyx
#

did not like that attributes part

#

Invalid config for [sensor.template]: [attributes] is an invalid option for [sensor.template]. Check: sensor.template->sensors->verbose_vacuum_state->attributes. (See ?, line ?).

sacred sparrow
# marble jackal This doesn't work because you only applied the custom timestamp on now() and not...

this still gives me "false"

{% set ns = namespace(count = 0) %}
{% set start = states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_calendarevent') | map(attribute='attributes.start') | list %}
{% for item in start  %}
  {% if as_timestamp(state_attr('sensor.ical_work_calendar_event_0','start')) | timestamp_custom('%d/%m/%y') == as_timestamp(now()) | timestamp_custom('%d/%m/%y') %}
    {% set ns.count = ns.count + 1 %}
  {% endif %}
{% endfor %}
{{ ns.count > 0 and is_state_attr('sensor.ical_work_calendar_event_0','summary',"Busy") }}
manic onyx
#

rewrote it under the template > sensor instead of sensor > template

marble jackal
marble jackal
sacred sparrow
#

will {{ ns.count > 0 and is_state_attr('sensor.ical_work_calendar_event_0','summary',"Busy") }} also check for event_1 and event_2 etc?

#

because that needs to count up as well

marble jackal
#

It doesn't in your original template

#

Oh wait, it does in the last version you posted

#

Try this:

{% set ns = namespace(count = 0) %}
{% for item in states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_calendar_event') %}
  {% if item.attributes.start.date() == now().date() and item.attributes.summary == 'Busy' %}
    {% set ns.count = ns.count + 1 %}
  {% endif %}
{% endfor %}
{{ ns.count > 0 }}
sacred sparrow
marble jackal
#

Fixed.

sacred sparrow
marble jackal
#

Stop tagging me please, I'm in the channel

sacred sparrow
#

Sorry about that

marble jackal
#

And please check if the updated version works

sacred sparrow
#

It says "true" so looks like its working 🙂

marble jackal
#

👍🏼

sacred sparrow
#

is there a way of using that code to give me a number of how many events are today that have "busy"? for TTS?

marble jackal
#

Yes, ns.count will contain that number

#

How are you using this template?

sacred sparrow
#

thats the part I think I am struggling with:

marble jackal
#

Why not simply create a template binary sensor using the template you have now instead setting an input boolean in an automation?

#

You can set the number of events in an attribute as well, so you can use that in your tts

sacred sparrow
#

oh thats a good idea - I didnt think of that!

#

thank you 🙂 let me work on that

#
    number_of_appointments:
      friendly_name:  Number of Appointments
      availability_template: "{{ not is_state('calendar.ical_work_calendar', 'unavailable') }}"
      value_template: >-
        {% set ns = namespace(count = 0) %}
        {% for item in states.sensor | selectattr('entity_id', 'match', '^sensor.ical_work_calendar_event') %}
          {% if item.attributes.start.date() == now().date() and item.attributes.summary == 'Busy' %}
            {% set ns.count = ns.count + 1 %}
          {% endif %}
        {% endfor %}
        {{ ns.count }}
marble jackal
#

Legacy template format, but looks fine

sacred sparrow
#

works a treat - legacy how?

marble jackal
#

You're using the legacy format which is at the bottom of that page

sacred sparrow
#

ahh I see

bronze tide
# peak shoal Take a step back, and detail your actual problem. What is the actual problem at ...

Thanks for the support!
Here the long story which I did not publish so far as I had no feedback on lenghty explanations of any of my problems. In the "fully blown up solution" I want to have an automation which checks every x minutes whether a certain type of device is unavailable and sends out notifications. The code for finding the device is up and working. I do want to have the automation to send notifications only if there are still devices unavailable. I do not want a message telling me every x minutes that devices foo and bar are not available. So somehow I need a mechanism which tells me whether a change occurred.
Looking at the States tab of DevTools I noticed that last_changed might hold the solution to my problem, but can it be that the solution is to use a state trigger in the automation mentioning just the entity id like in https://www.home-assistant.io/docs/automation/trigger/#state-trigger ???

Edit: So far it works! I should mention that the sensor the automation is screening is a template sensor which is setup with a time trigger.

marble jackal
#

I would suggest to create a template binary sensor which is on if there are such devices unavailable and use that binary sensor for the alert integration

mighty ledge
#

Unfortunately, there is no checksum func in templates, that would make a hash of your template sensors that's unique. Would be really great for this situation.

#

You could just have the main state as a counter that updates when the count changes

bronze tide
bronze tide
mighty ledge
#

FYI, it's the first link when you google search home assistant cookbook

bronze tide
# mighty ledge FYI, it's the first link when you google search `home assistant cookbook`

You are right. The idea of having a solution made me focus on the solution and nothing else. I also thought that I would find some menu entry of the HA web site like in ESPHome where I spent more time reading the docs. The bare text "Examples" didn't trigger anything in me as a lot of examples within the HA docs are simple and often too simple. Maybe time for a change at the HA website to call the the Examples rather Cookbook???

marble jackal
#

There used to be a cookbook section

#

But that looks a lot like the examples page 😎

mighty ledge
#

It was renamed examples

#

because more people looked for examples opposed to cookbook

bronze tide
#

I hope it stays "cookbook" on the ESPHome site as I as a none native speaker of English relate "Cookbook" with solutions who are beyond simple examples which are found in the docs where a function is explained.

edgy umbra
#

Everytime at startup i get some errors because the sensor and/or attribute is not yet available. Is there anything i can do/add to avoid this? I get the following errors: Error while processing template, TemplateError('UndefinedError: 'None' has no attribute 'split'') while processing template and Template variable error: 'None' has no attribute 'split' when rendering. Thx in advance for any help. https://paste.ubuntu.com/p/QdkxDHBtpH/

marble jackal
#

Yes, add availability templates to your template sensors

#

Or defaults to your templates

mighty ledge
#
          {% set variable1 = state_attr('sensor.backup_state', 'size_in_google_drive') or  "0 GB" %}
          {% if variable1.split(' ')[1] == 'MB' %} 
            {{(variable1.split(' ')[0] | float(default=0)/1024 )| round(1)}}
          {% else %}
            {{(variable1.split(' ')[0])}}
          {% endif %}
#

or you could probably remove the redundancy

{% set value, units = (state_attr('sensor.backup_state', 'size_in_google_drive') or "0 GB").split(' ') %}
{% if units == 'MB' %}
  {{ (value | float / 1024) | round(1) }}
{% else %}
  {{ value }}
{% endif %}
edgy umbra
#

{% if states.sensor.backup_state is defined %}

#

So i can leave this part out?

mighty ledge
#

you shouldn't ever use states.xxx.xxx unless you know what you're doing. state_attr was built so you don't need all these checks

edgy umbra
#

Thats the problem sometimes, not know what i'm doing. 🙂

#

Greatly appreciate your help Petro!

mighty ledge
#

Just try it out for a few days, some safety was removed and you might get an error with the float. Otherwise you can do an availability template like thefes said

edgy umbra
#

Will sure do, for know the errors seems gone after restart!

#

Thanks Petro and TheFes for the support!

marble jackal
#

TIL that you can use or in combination with set

mighty ledge
#

and and

#

or with set is VERY goofy

#

it depends on what the first and second value is

marble jackal
#

Ah, I was just about to ask what foofy means

#

If the first is falsy it takes the second?

mighty ledge
#
{% set items = [ 0, 1, '', 'x', False, True, {}, {'x':1}, [], [0], none ] %}
{%- for i in items %}
{{ i }}
  {%- for j in items %}
    {{ i }} or {{ j }}: {{ i or j }}
  {%- endfor %}
{%- endfor %}
#

run that

#

specifically look at the interactions with none

#

has a mind of it's own in some cases

marble jackal
#

I'll have a look at that when I'm not on mobile

lapis lynx
#

Is there a way to do < or > or == to in a statement like this
{% if is_state_attr('sensor.blue_bin', 'days', <12) %}

inner mesa
#

not like that

#

{% if state_attr('sensor.blue_bin', 'days') < 12 %}

lapis lynx
#

Ah thank you!

stuck remnant
#

is there a template to apply inverted values to a sensor?

#

like for instance if there were a sensor going from 1 to 100 would it be possible to have it show 100 when the value was 1

#

and vice-versa, as well as for every subsequent value? basically inverting the curve

mild mica
#

hey friends, i ran a across this yaml that helps track heating and cooling times over the day
part is a template, other part is sensor. should i be trying to convert the sensor in to a template sensor?
https://www.codepile.net/pile/dbPWj8Zx

marble jackal
#

That will onder invert 0 to 100 though

inner mesa
#

with |float

marble jackal
#

You're right

#

I thought I accidentally added yaml to the code tag 😅

floral shuttle
#

on a template with state: state: > {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='state') |map('float')|sum)|round(2,none)}} my sustem seems to sometimes choke, and throw 0 for this sensor, which messes with the energy panel, because on the next state change it jumps back, with a then huge total increase...

#

what would be the best way to set availability on this, not being total 0? To prevent it from being included in the energy panel calculations, Do I repeat the template

#

like: {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='state') |map('float')|sum)|round(2,none) != 0}} ? Dont think it can be done with the this variable?

#

cause that wouldn have been elegant: availability: > {{this.state != 0}} ... although it seems to work, no error, and a value is calculated..

marble jackal
#

I would not check on the sum being 0 because of one of them is unavailable you will also see a decrease.

I would suggest this:

{{ expand('group.switches_total_device_energy') | selectattr('state','is_number') | list | count == expand('group.switches_total_device_energy') | list | count }}
floral shuttle
#

my check on 0 is for the total value (energy) not for the individual items. if only 1 would be 0, the total would still never be 0. so the full check != 0 would be the (system error) check to do?

inner mesa
#

I wouldn't expect that to ever be true, since states are strings

marble jackal
#

But if some of them are unavailable that could cause a drop in the total value and will mess up your energy panel

floral shuttle
#

Rob: thats a good point... I'd need {{this.state|int(default=0) != 0}} in that case

floral shuttle
marble jackal
#

That's not what I mean. Let's assume there are 5 values there, all being 5. That's a total of 25

floral shuttle
#

coming to think of that: I could aslo do {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable','0.0']) |map(attribute='state') |map('float')|sum)|round(2,none)}} maybe 😉 simply reject the total sensors with a 0 value

marble jackal
#

If one of them becomes unavailable your total is 20, which is lower than 25

#

The energy dashboard will then assume it has been reset, so it was 0 at one point which was missed by HA, and it's now 20 again

#

So for the energy dashboard the value will be 45 (25 + 20)

#

That's why you don't want it to drop below a previous reading

#

And you want to make sure all source sensors are available

floral shuttle
#

you're right. we need all sensors there, and they all should be total_increasing... so, if it glitches on a single sensor, the rejectattr will catch that. And if the complete sensor is messed up, the availability template catches it? the count being equal, ensures that if a single sensor would turn 0, and be rejected because of that, the availability is false

silent seal
#

Why would a sensor be messed up in the first place?

#

Seems to me like that's your real problem

floral shuttle
#

yeah, well they sometimes simply are. eg when the MQTT source has a hiccup

marble jackal
#

If there is a single sensor glitching, it will be excluded from your state template, causing the state template to decrease, but still it will still be above 0

floral shuttle
#

and you're right that should be guarded, but unfortunately we can not add an availabiltiy template to the mqtt sensors

floral shuttle
marble jackal
#

Yes, because it checks if all members of the group are providing a number for their state

floral shuttle
marble jackal
#

Ah okay, guess I missed the combine part

#

Time for bed I guess

floral shuttle
#

thanks !

floral shuttle
#

number check could also be: {{(expand('group.switches_total_device_energy') |rejectattr('state','in',['unknown','unavailable','0.0']) |selectattr('state','is_number') |map(attribute='state') |map('float')|sum)|round(2,none)}} probably... let's test

vagrant monolith
#

Hey, could anyone help me with this? ```
Error rendering icon template for sensor.times_of_the_day: TypeError: '<' not supported between instances of 'str' and 'datetime.datetime'

silent barnBOT
silent seal
#

You're comparing the string returned by the attribute.today with a date time.

#

What are you trying to do? There's likely a better way than updating every single minute.

vagrant monolith
#

I'm trying to compare against these for examples

silent seal
#

Your image doesn't load, but I guess you're answering the wrong question

#

What is your goal, not "how are you trying to solve your problem", but what do you want/need to do with this data?

#

You can parse a string to a time, but I really suspect you've taken a wrong turn there, this seems very inefficient

orchid oxide
#

i have a sensor that outputs a currency amount, so i have it rounding to the 2 decimals, but when the number is x.x0 (ex 2.20), it will trim the zero. can i stop this?

sonic ether
#

I am trying to create a template that sum 4 sensors, 4 ACs kwh from emporia sensors, where do I add a template?

inner mesa
#

With a template sensor

sonic ether
#

I have a draft, I just don't know where I add the code... which file does it go, or is it on the interface?

inner mesa
#

Sensor, binary sensor, button, number and select template entities are defined in your YAML configuration files, directly under the template: key and cannot be configured via the UI.

#

configuration.yaml

sonic ether
sonic ether
fleet viper
#

hey all, struggling with an automation script for setting a input_datetime. I'm trying to just add an hour to now for my lovelace to pick up and show once the automation runs for when it will turn off. I have this now but I see errors in the logs

inner mesa
#

The last 3 have sensor.sensor

fleet viper
#

service: input_datetime.set_datetime
target:
entity_id: input_datetime.attic_fan_turn_off_time
data:
datetime: '{{ now() + timedelta( hours=1 ) }}'

inner mesa
#

What...errors...

fleet viper
#

sensor.attic_fan_turn_off_timestamp rendered invalid timestamp: 2022-05-16T02:15:43+00:00Z

#

i may be mixing up what's wrong too 😄

#

yep so this is the problem, what i linked above is what gets generated

#
  • platform: template
    sensors:
    attic_fan_turn_off_timestamp:
    device_class: timestamp
    value_template: "{{ as_timestamp(states('input_datetime.attic_fan_turn_off_time')) | timestamp_utc | replace(' ', 'T') }}Z"
inner mesa
#

Please use a code share site

fleet viper
inner mesa
#

The docs tell you exactly what format you need to use

sonic ether
#

how do we delete a entity that I created by a template that I no longer want to use?

inner mesa
#

If you already removed it from your config file and it's showing as restored in the UI, configuration -> Devices & Services -> Entities

sonic ether
inner mesa
#

Then reload templates or restart HA

sonic ether
#

did both but the entity is still there

stuck remnant
#

@marble jackal sorry to have to bring this up again but I think I figured out what was wrong with the template sensor we talked about

#

binary_sensor.heat:

{{ is_state('binary_sensor.outside_heat', 'on') and now() - timedelta(hours=72) > as_local(as_datetime(states('input_datetime.heat'))) }}

#

the first sensor must also be on in order for the stamp to trigger, so if it changes now, it won't matter that it hasn't been 72 hours yet - it will stamp, so the second binary sensor will switch off

#

(yes I changed the time value to test further)

marble jackal
#

Yes, indeed the first sensor has to be on, otherwise this template will also render true if it the first sensor has been off for 72 hours

#

If it just changed, it just changed, so it will not be on for 72 hours

stuck remnant
#

so then it defeats the purpose

#

isn't there a way to write the template for the attribute of the weather sensor?

#

so as to avoid all of this binary sensor and timestamp nonsense

#

this is the binary_sensor.outside_heat :
{{ state_attr('weather.home','temperature') > 17 }}

#

isn't there a way to make this template for 72h ?

marble jackal
#

Sorry, you lost me here

#

You want to know if it has been cold or warm for a period of 72 hours

#

but you also want that to be true when it just changed

#

those two are in confict

stuck remnant
#

no

#

it's like that atm

floral shuttle
stuck remnant
#

nevermind this, I don't wanna waste your time anymore with it, just think if there's a way to write the template above so that the outside heat sensor turns on/off after the attribute has been above 17 for 72h (without resorting to additional binary sensors and helpers)

marble jackal
stuck remnant
#

yes

marble jackal
#

binary_sensor.heat will turn on after 72 hours, unless binary_sensor.outside_heat turned to off in that period again

#

even for a second

marble jackal
stuck remnant
#

but 'heat' will turn off if outside heat turned to on even if it hasn't been 72h

#

sensor2: sensor1 AND sensor1for72h

#

the only reason we went with the timestamp was to avoid the restart issue that HA only calculated the value of the first binary sensor (outsideheat) since the last restart. Now I'm asking that considering the attribute of the weather sensor is stored in the integration, and not lost along with restart, isn't it more wise to just use that ?

marble jackal
stuck remnant
#

ok, put it another way: it changed twice in the last 6hours. I can show you the logs

#

from on to off then to on again

floral shuttle
#

btw Fes, we can not reverse that is_number can we?, so we could so something like:```
{% set items = 'group.switches_total_device_power' %}
{{expand(items)|selectattr('state','not','is_number')|list|length == 0}}

marble jackal
#

what is it? Is that binary_sensor.heat or binary_sensor.outside_heat?

floral shuttle
#

sure, but then we still can not count those?

marble jackal
#

that would make it easer yes

floral shuttle
#

comp: ```
{% set items = 'group.switches_total_device_power' %}
{% set x = ['unavailable','unknown'] %}
{{expand(items)|selectattr('state','in',x)|list|length == 0}}

marble jackal
#

That would work with rejectattr

stuck remnant
marble jackal
#

['5', '7', '9' ] | reject('is_number') | list | count == 0 will be true

marble jackal
marble jackal
stuck remnant
#

yes it was

floral shuttle
stuck remnant
#

heat turned on - 1:47:14 PM - 2 days ago
heat turned off - 12:36:52 AM - 10 hours ago

marble jackal
marble jackal
stuck remnant
#

(it seems it didn't turn on off in the past six hours, I just got the notification that it turned off twice and didn't fully read it. But it's weird that it recorded when it turned from off to off)

marble jackal
#

and if it then changes back to on the count starts from there

stuck remnant
#

yeah IDK, it's way more trouble than its' worth

floral shuttle
#
{% set items = 'group.switches_total_device_power' %}
{{expand(items)|rejectattr('state','is_number')|list|length == 0}}
``` for full disclosure 😉
marble jackal
floral shuttle
#

which offers 2 scenarios: either only count the entities from given set, and ignore the non-numbers, and use: - unique_id: switches_total_device_power name: Switches total device power state: > {{(expand('group.switches_total_device_power') |rejectattr('state','in',['unknown','unavailable']) |selectattr('state','is_number') |map(attribute='state') |map('float')|sum)|round(2,none)}} unit_of_measurement: W icon: mdi:label-multiple device_class: power state_class: measurement only. Or use it with the availability template, change to state_class: total_increasing, and be able to use it in the energy dashboard

stuck remnant
#

okay. I'll keep it like this and I'll make a separate sensor for the template I asked about, but can you please tell me how to write it? It will then make it less confusing for me and if you are right (which you probably are and I just didn't get the entire thing clearly) the two sensors will match up

#

with the added caveat that it will keep me from coming back to ask about it ^^

#

this one: {{ state_attr('weather.home','temperature') > 17 }}
how to add 'for 72h' to it?

marble jackal
#

So that's why I proposed to use the method you are doing now

stuck remnant
#

argh

#

I see

marble jackal
#

Maybe using an SQL sensor you could, by getting the data of the last 72 hours out of your database, and check if they are all above 17

stuck remnant
#

would I need a server for that?

marble jackal
#

but I don't know what that SQL query would be, I don't have a lot of experience with SQL

#

No, you don't need a server, you are using the HA database

stuck remnant
#

ok, please pardon my frustration then, I just happened to receive that notification twice in six hours and just presumed it wasn't functioning well. Didn't bother checking the actual values of the state change, as I didn't even factor it changing from OFF to OFF

marble jackal
#

You could add that to the notification

#

or add a condition that it should only send the notification if the state from is different from the state to

stuck remnant
#

okay

marble jackal
#

I didn't even know that you were talking about the notification here..