#templates-archived

1 messages Β· Page 143 of 1

cinder basin
#

i cannot find configuration for the light

#

to fix value_templeta

jagged obsidian
#

have you tried doing what it tells you to do?

cinder basin
#

Logger: homeassistant.components.mqtt.light.schema_basic
Source: helpers/config_validation.py:761
Integration: MQTT (documentation, issues)

cinder basin
#

where are this configs?

jagged obsidian
#

by navigating to that light's yaml configuration

cinder basin
#

ok

jagged obsidian
#

you should know that if you created it

cinder basin
#

i think its the part of the integration

jagged obsidian
cinder basin
#

thats way i have problem finding it

jagged obsidian
#

What kind of light is it? What firmware

cinder basin
#

tasmota

#

its bassicly shelly rgbw

#

flashed with tasmota

#

and i can find entitie under mqtt broker integration

#

I found device debug info

#

i can see how its configured, just dont know, where is it saved

dense kayak
#

I just updated to the current release and noted the state trigger changes, but can't find help on how to update templates. I have a custom template that calls a service, but it grabs the name of the entity. This no longer works after the update, and assume there's a syntax change needed. Here is my YAML template. The "{{trigger.to_state.name}}" is giving me the error "Template variable error: 'dict object' has no attribute 'to_state' when rendering '{{trigger.to_state.name}} speakers are playing. Volume reset.'".

Current template: https://www.toptal.com/developers/hastebin/atokosidoh.less

buoyant pine
#

@cinder basin if you didn't manually configure the light in YAML, then it sounds like you're using SO19 1 in Tasmota. If that's the case, I'd upgrade to tasmota 9.2 or newer, install the tasmota integration in HA, and do so19 0 on the tasmota device

cinder basin
#

Im runing 9.3.1

#

And i didnt configure it in yaml

buoyant pine
#

Cool cool. I'd install the tasmota integration and do SO19 0 on the tasmota device to move it to the tasmota integration

cinder basin
#

O ok

#

I just need to do s019 0

buoyant pine
#

HA MQTT discovery isn't being developed in Tasmota anymore, so you'll want to switch to the tasmota integration (which still uses MQTT, but with different discovery)

#

It will prevent issues like the one you experienced from occurring again

mighty ledge
glacial matrix
#

Not sure which channel to ask this question, but at the moment i'm using the integration Garbage Collection and created sensors like Child1 dishwasher, Child2 Dishwasher, Adult1 Dishwasher etc. The outputs are today, tomorrow date etc, If I want to create a new sensor "Dishwasher:" and have the output as the child's name is the best way to achieve this with a template?

mighty ledge
#

Use a template sensor, set the friendly_name in attributes using the friendly_name from the other sensor.

glacial matrix
#

How do i create a template sensor to read the attributes from other sensors? Is the method above the best way of assigning daily chores to a person? It's set so that the responsibility changes daily, but repeats every X (number of people involved) days.

mighty ledge
#

Test out your templates in the template editor. Dev Tools -> Templates

#

Lastly, check out the pins at the top of the page for information about Jinja and frequently asked questions

glacial matrix
#

Great thanks, I think i might have something to work with.

arctic sorrel
glacial matrix
#

If i want to string if statements, do i just put them on a new line?

{% if is_state('sensor.child1_dishwasher', 'today') %}
  child1
{% elif if is_state('sensor.child2_dishwasher', 'today') %}
  child2
{% elif if is_state('sensor.adult1_dishwasher', 'today') %}
  adult1
{% else %}
  ERROR!
{% endif %}

becuase i'm getting the error expected token 'end of statement block'

#

dw. being a dumbass!

buoyant pine
#

It's just elif, not elif if

glacial matrix
#

I realised as i rewrote it. Thank you.

brazen stone
#

If it helps anybody, I figured out what I was doing wrong with the template based on statistics changes in 2021.12 and I was still treating it as an attribute of the sensor, when it was appearing as a (pseudo?) sensor in it's own right:

{{ (state_attr('sensor.plusnet_rx_stats','change_second')|float*8/1000000)|round(2) }}

needs to become

{{ (states('sensor.plusnet_rx_stats')|float*8/1000000)|round(2) }}

under 2021.12

#

Sorry Petro, I see what you mean now. Yes, you're right.

mighty ledge
#

however SNMP has a mind of it's own and it could very well be bytes

hybrid yacht
#

Is it possible to create a binary on/off sensor based upon the mean value over 5 minutes of the power from a switch?

pallid ibex
#

hi, anyone have any idea how to format it into number???

hybrid yacht
#

I want to create an entity that tells me when a switch is in use but the devices (curling iron, etc.) that are plugged into it have the wattage going in a square wave, so on/off/on/off.

#

so I'd like to get the average from the last 5 minutes to determine the state

inner mesa
#

I would normally say that you should use a statistics sensor

hybrid yacht
#

@inner mesa So I have one setup, but I can't find it to use

inner mesa
#

Can’t find it?

#

How did you set it up?

hybrid yacht
#

in sensors.yaml loaded from configuration.yaml

silent barnBOT
inner mesa
#

Those don’t make any sense together

hybrid yacht
#

I have the template that I was testing directly from the switch (Shelly1PM btw), but the "Vanity power over last 5 miuntes" is the one I was playing with for statistics

inner mesa
#

You can either use a statistics sensor directly with the power sensor, or make a template sensor that checks the power, reports on or off, then use history_stats

hybrid yacht
#

I created Vanity Status first, found in flapping because of the device being going through a power cycle causing vanity_power to be a nice square wave

inner mesa
#

Using a statistics sensor on something that reports a string won’t work

hybrid yacht
#

ok

#

I grabbed that from an example I found online as a starting place

inner mesa
#

The average of β€˜off’ and β€˜running’ πŸ™‚

hybrid yacht
#

right but I didn't think I was using statistics on that sensor, I thought I had both of them going to the primary device sensor.vanity_power

inner mesa
#

Oh, never mind

#

Sorry, looking at it on the phone and I assumed that both were related

hybrid yacht
#

Scenario I'm trying to deal with. Shelly1pm always shows as on for the outlet, I want to show it only as On if there is a load on it (i.e. one my of wife's styling devices plugged in). I want to be able to tap on that entity in Lovelace and shut it off, i.e. we've run out of the house and forgot to turn them off

#

The first device in the code wall "sort of" worked, it just flipped on/off constantly because the load wasn't constant.

inner mesa
#

You also have some extra spaces and poor syntax in the first sensor

hybrid yacht
#

wouldn't surprise me, just learning and I pulled it from a power draw example from a blog post about washing machiens

inner mesa
#

I’m sure

pallid ibex
#

no one? really? πŸ™‚

inner mesa
#

Pictures of text don’t go over well, and are unreadable on a phone

glacial matrix
#

Is it possible to use templates to create a list of chores? I.e.
i.e.
input_boolean_dishwasher_child1
input_boolean_feedpets_child1
inputboolean_brushteeth_child1
inputboolean_makebed_child1

input_boolean.bins_child2
input_boolean.brushteeth_child2
input_boolean.makebed_child2

as they do the chores they can press a button or scan a nfc tag /QR code to turn off the input boolean and remove the chore from the list?
I'm trying to integrate the chore lists into a MagicMirror i'm running, so ideally need them to display as a sensor rather than filter by state in lovelace.
Thanks in advance.

glacial matrix
#

I think i have the start of it, but struggling to figure out the logic on the seperator (the comma in this case)

{% set do_bins = is_state('input_boolean.child1_bins', 'today') %}
{% set do_dishwasher = is_state('input_boolean.child1_dishwasher', 'today') %}
{% set do_fridge = is_state('input_boolean.Child1_fridge', 'today') %}
{% set bins = 'Bins' if do_bins else '' %}
{% set dishwasher = 'Dishwasher' if do_dishwasher else '' %}
{% set fridge = 'Fridge' if do_fridge else '' %}
{% set x = '\n' if do_bins or do_dishwasher or do_fridge else '' %}
{% set y = '\n' if do_bins or do_dishwasher or do_fridge else '' %}
[{{bins}}{{x}}{{dishwasher}}{{y}}{{fridge}}]
inner mesa
#

First, you have a capital letter in your entity

atomic blade
#

I have an adjustable bed I want to create a template entity for. I'm a little new to templates, but is it correct that I will need to use an existing entity type? There's no way of like defining your own type, correct? If so that's fine, just curious. The "cover" entity seems like it would be the best fit, but it seems more proper to define my own "class" of entity if that's a thing.

inner mesa
#

You can only create template entities of the types described in the docs

crude prism
#

hi after the update to 2021.12.1 my sensor does not work min max temperature I do not know why? - platform: template
sensors:
teplota_vonku_max:
value_template: "{{ state_attr('sensor.teplota_vonku', 'max_value') }}"
teplota_vonku_min:
value_template: "{{ state_attr('sensor.teplota_vonku', 'min_value') }}"

marble jackal
crude prism
#

I did not find the cause - platform: statistics entity_id: sensor.teplota_vonk state_characteristic: mean name: Teplota vonku 24h sampling_size: 1000 max_age: "24:00:00" precision: 2 #default=2.

mighty ledge
pallid ibex
#

Please helped me with this... I'm sending through MQTT (from node red) this data...

#

and on HA i'm receiving this.

#

into config.yaml i have this and on entity value is into "" like string

#

how the hell I can change it to number value?

#

i used float etc.. but it doesnt work!

#

anyone?

#

any ideas?

hexed wing
#

Don't use the fancy curly ones

#

use the straight " ones

pallid ibex
#

" im using straight ones...

#

omg...

#

got it!

#

Thank you Frenck!

crude prism
cinder lotus
#

Have this template:

  • sensor:
    - name: dagverbruik_diepvries
    state: "{{ (float (states.sensor.diepvries_energy.state) - float (states.input_number.24h_energy_diepvries.state)) | round(3) }}"
    unit_of_measurement: "kWh"

Generates this error:
Invalid config for [template]: invalid template (TemplateSyntaxError: expected token ',', got 'h_energy_diepvries') for dictionary value @ data['sensor'][0]['state']. Got '{{ (float (states.sensor.diepvries_energy.state) - float (states.input_number.24h_energy_diepvries.state)) | round(3) }}'.

No idea what's wrong. expected taken ',' ...

cinder lotus
#

Have for example also below code in template.yaml and that doesn't give any error:

  • sensor:
    • name: dagtotaal_injectie
      state: "{{ (float (states.sensor.dagtotaal_injectie_dag.state) + float (states.sensor.dagtotaal_injectie_nacht.state)) | round(3) }}"
      unit_of_measurement: "kWh"
dreamy sinew
#

its because of the 24

#

causing issues

#

also you should be using states('entity') instead of states.domain.entity.state notation

#

also probably need to add defaults

#

{ (states('sensor.diepvries_energy')|float(0) - states('input_number.24h_energy_diepvries')|float(0)) | round(3) }}

cinder lotus
austere relic
#

how do I get a datetime with timezone from a datetime without timezone? (input_datetime has none, template sensor deviceclass timestamp needs one).

#

converting using as_timestamp also needs a timezone

dreamy sinew
#

try using as_datetime instead

#

which should set it as UTC

austere relic
#

it remains the same.
converting as _timestamp works, but could not feed it as state to a template sensor
but as_datetime(as_timestamp()) works, wrong timezone and time, but since I only need it as relative time it doesn't matter. will get fixed at some point but not for now it seems.
second solution I found is to just add the timezone manually to the string.

cinder lotus
# dreamy sinew ```{ (states('sensor.diepvries_energy')|float(0) - states('input_number.24h_ener...

I've put

      - name: dagverbruik_diepvries
        state: { (states('sensor.diepvries_energy')|float(0) - states('input_number.daily_energy_diepvries')|float(0)) | round(2) }}
        unit_of_measurement: "kWh"```
but got error:
```Error loading /config/configuration.yaml: while parsing a block mapping
  in "/config/template.yaml", line 174, column 9
expected <block end>, but found '}'
  in "/config/template.yaml", line 175, column 132```
dreamy sinew
#

missing all sorts of things

#

look closer

cinder lotus
#

Are you willing to help me? I'm not a programmer...

dreamy sinew
#

compare that one to your other one and it should stand out

cinder lotus
#

compare? Your 'new' code is completely different to 'my original code'

dreamy sinew
#

we're talking basic template structure

#

look at the start and end of both of them

cinder lotus
#

My code was:

      - name: dagtotaal_injectie_nacht
        state: "{{ (float (states.sensor.energy_returned_tariff2.state) - float (states.input_number.teller_nacht_injectie_nacht.state)) | round(3) }}"
        unit_of_measurement: "kWh"```
You told me to 'use it as':
``` - sensor:
      - name: dagverbruik_diepvries
        state: { (states('sensor.diepvries_energy')|float(0) - states('input_number.daily_energy_diepvries')|float(0)) | round(2) }}
        unit_of_measurement: "kWh"```
Many changes but if you (I) don't know the correct syntax, I can try and retry many times. 1 space , ) or bracket wrong and you get errors
dreamy sinew
#

one was a copy paste failure on my part

#

look at the literal start of the original and the new one

#

notice they're different

frank gale
dreamy sinew
#

look at the end of both, notice they're different

#

make those bits the same and it'll work

cinder lotus
#

Thanks for your words but that doesn't help me. Once more there are to many differences and I don't know when to use which option...

frank gale
dreamy sinew
#

trying to teach a man to fish here

cinder lotus
dreamy sinew
#

the HA template docs

frank gale
#

i dont have... it's jinja2 try their documentantion

dreamy sinew
#

templates must be in quotes

#

also i typo'd the first {{

#

if you looked at the beginning of yours and of the one i posted you would have noticed the missing "{

cinder lotus
frank gale
dreamy sinew
#

probably integrations

frank gale
#

thnx I'll try there

cinder lotus
#

Thanks @dreamy sinew and @frank gale !

frank gale
graceful widget
#

Hello, today I have a question regarding template or how can I take a created button style as a basis for upcoming. So that I only have to change the values in one place and then my button design changes?

silent barnBOT
graceful widget
silent vector
#

How would I combine these 2 templates? I want to know if an Automation ran in the last 5 seconds and I would want it to be... It ran in the last 5 seconds and today is Monday = false. I tried literally just putting a comma at the end and combining them that way but its result type is a list and I'm not sure what to do with that? For it to work I can't just use "time" and then the days because this automation still "triggers" even during the days it will not actually run 100% if there was a last run as in completed vs last triggered that would help. Its one big choose automation with every day for the week for simplicity but now I know there's a chance on off days it gets messed up because of the triggering of the Automation. So the template itself would need to know the day so it doesn't change to false because with using just "time" the condition value of true is required and then if it's false it won't run which it will be on off days lol.

#

"{{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}"

"{{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered'),as_timestamp(now(),0)) ) > 5 }}"

fossil venture
#

"{{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.winter_daniels_thermostat', 'last_triggered'),as_timestamp(now(),0)) ) > 5 and now().weekday != 0 }}"

hexed wing
#

That can be done shorter

{{ (now() - state_attr('automation.winter_daniels_thermostat', 'last_triggered')).seconds > 5 and now().weekday != 1 }}

No need to juggle with epoch timestamps

floral shuttle
#

rewriting several templates, I can not help but hoping we can at sometime see template variables that are available per sensor, but scope for all configuration variables. There's has been talk before, just wondering if this would be in the works?

silent vector
floral shuttle
#

imagine we could replace the days=0 here - unique_id: dark_sky_forecast_0 name: > {{as_timestamp(now() + timedelta(days=0),none)|timestamp_custom('%a %-d %b',default='Not yet set')}}: {{ states('sensor.dark_sky_forecast_icon_0d').replace('-',' ')|capitalize}} state: > {{- states('sensor.dark_sky_forecast_daytime_high_temperature_0d')|round(0)}}Β°/ {{- states('sensor.dark_sky_forecast_overnight_low_temperature_0d')|round(0)}}Β°/ {{- states('sensor.dark_sky_forecast_precip_probability_0d')|round(0)}}% picture: > {{'/local/weather/icons/' ~ states('sensor.dark_sky_forecast_icon_0d') ~ '.png'}}

#

and then simply jot the whole template in an anchor and be done with it for days 0 - 5 ....

#

like: - unique_id: dark_sky_forecast_0 variables: day: 0 name: >

silent vector
hexed wing
#

multiple not in? Or multiple in?

#
{{ (now() - state_attr('automation.kitchen_lights', 'last_triggered')).seconds > 5 and now().weekday not in (1, 2, 3) }}
#

And change the not in -> in if you want it to be those days

silent vector
#

Oh I see not meaning not Monday or Tues and if I want it to be Monday or Tuesday then I would use in?

hexed wing
#

πŸ‘ You got it

silent vector
#

Thank you!

silent vector
hexed wing
#

ik think the > should be <

#

πŸ˜„

silent vector
#

I tried "{{ (now() - state_attr('automation.winter_daniels_thermostat', 'last_triggered')).seconds < 5 and now().weekday in (1, 4) }}" and it's still false. As in no matter where the arrow points the result is still false it's not changing and it should? I even tried every day of the week still false

hexed wing
#

So, go to the template debugger in the developer tools, and start small

#

For example check the output of
{{ (now() - state_attr('automation.winter_daniels_thermostat', 'last_triggered')).seconds }}

#

figure out what values there are and that way You'll discover where it went wrong

hexed wing
#

Ok
so, this would be false:

{{ (now() - state_attr('automation.winter_daniels_thermostat', 'last_triggered')).seconds < 5 }}

As you wrote: " It ran in the last 5 seconds"

silent vector
#

But even when I change the arrow > it should be true

#

It stays false

#

"{{ (now() - state_attr('automation.winter_daniels_thermostat', 'last_triggered')).seconds > 5 and now().weekday in (1, 4) }}" shows false

hexed wing
#

I cannot reproduce that on this end

#

:S

silent vector
#

As in its something wrong on my end lol?

hexed wing
silent vector
#

So that works I get a number and when I change the arrows I get true or false.

hexed wing
#

well that is good right?

silent vector
#

Except it doesn't change when I use this "{{ (now() - state_attr('automation.winter_daniels_thermostat', 'last_triggered')).seconds > 5 and now().weekday in (1, 4) }}"

modest sparrow
#

Hey, did anything change in the last few months regarding template sensors using device_class: timestamp? My timestamp sensors seem to be broken (and I'm not sure since how long) and I didn't change anything in the configuration

#

The input_datetime I'm using has a value of '2021-12-16 12:54:00'

mighty ledge
#

and it needs to be TZ aware

modest sparrow
#

Thanks @mighty ledge, I already saw log-messages like "sensor.door_bell_last_rang rendered timestamp without timezone: 2021-12-10 16:29:19" but I'd discarded them so fast apparently.

marble jackal
#

I have a timer, and want to send the remaining hours and minutes as a TTS message.
Using {{ state_attr('timer.vaatwasser_timer', 'finishes_at') | as_datetime - now() }} I can get the remaining time (eg 03:25:05.997985) . But I can't seem to get the number of minutes and seconds out of it.

#

I also tried this, but that is off by one hour (it comes back with 4 hours and 25 minutes

            {% set remaining = state_attr('timer.vaatwasser_timer', 'finishes_at') | as_timestamp - now() | as_timestamp %}
            {% set hours = remaining | timestamp_custom('%H') | int %}
            {% set minutes = remaining | timestamp_custom('%M') | int %}
mighty ledge
modest sparrow
#

Thanks a lot, I'm already trying to figure out all this time to make it an TZ aware object

mighty ledge
#

as_datetime makes a datetimestring a utc aware datetime object, as_local makes the object local to your tz

modest sparrow
#

Jup, just tested it out in the developer tools, works great. Rebuilding my config now, also switching to timestamp: '{{ now().timestamp() }}' for my automations..

silent vector
modest sparrow
#

Also, shout-out to you @mighty ledge, you've already helped me multiple times here. Also to @hexed wing and all the other guys here working hard on Home Assistant and helping the community. Happy holidays to you guys, you make my life (and I'm sure lots of others too) happier with Home Assistant! πŸ™‚

mighty ledge
#

if your number is 1 and you want to know if 1 is inside a list of items....

#

1 in (1,2,3)

#

true

#

1 in (2,3)

#

false

hexed wing
#

4 not in (1, 2, 3)

#

true

#

almost got that wrong πŸ™ˆ

mighty ledge
#

read it like english and it'll make sense

silent vector
#

But if I wanted it to be Thursday then Thursday is 4 right? And if I use in it should change the values. What I'm saying is the values don't change for some reason with "in"

#

Even if I use 1 - 7 lol. As in 1,2,3,4,5,6,7

mighty ledge
#

I believe thursday is 3

hexed wing
#

I'm not sure what you mean by "values not change"

silent vector
#

It's not changing from false to true when I change the arrows

#

It just stays false.

mighty ledge
#

monday = 0, tuesday=1, wednesday=2, thrusday=3

#

I could be wrong, i'd have to look at it

hexed wing
#

Oh

#

I see the issue

#

weekday is not a property, but a method

marble jackal
#

probably because your second part is false , the now().weekday in (1, 4) part

hexed wing
#

now().weekday() in (1, 4)

mighty ledge
#

ah yes, weekday is a func

#

Also, thursday is 3

#

just checked that out too

hexed wing
#

@silent vector weekday needs a couple of extra ()

silent vector
#

Ok so I'm not crazy lol

hexed wing
#

What does you not in (crazy) has to do anything with this @silent vector ?

mighty ledge
hexed wing
#

πŸ˜›

mighty ledge
#

today is Thursday where I am

silent vector
#

"{{ (now() - state_attr('automation.winter_daniels_thermostat', 'last_triggered')).seconds > 5 and now().weekday() in (1, 3) }}" lol that's a good one and this would work?

#

It worked

mighty ledge
#

yah, if you're looking at tuesday/thursday

silent vector
#

I also wasn't sure what the numbers equated to days wise. So that helped as well. I thought Monday was 1 lol.

#

Thank you to both of you.

marble jackal
#

Ah, already found something. I tried .hours and .minutes but after some googling it seems only .days and .seconds work on a datetime.timedelta

mighty ledge
marble jackal
#

But I can work with the seconds

mighty ledge
#

what is finishes_at? I don't use timers

#

is it a datetime or string

#

@marble jackal

marble jackal
#

It's finishes_at: '2021-12-16T16:00:15+00:00'

#

So it seems to be a datetime between quotes, so a string..

#

But this seems to work

            {% set remaining = state_attr('timer.vaatwasser_timer', 'finishes_at') | as_datetime - now() %}
            {% set hours = (remaining.seconds / 3600) | int %}
            {% set minutes = (((remaining.seconds / 3600) - hours) * 60) | int %}
            "De vaatwasser is over {{ hours ~ ' uur' ~ ' en' if hours != 0 }} {{ minutes }} {{ 'minuut' if minutes == 1 else 'minuten' }} klaar."
mighty ledge
marble jackal
#

Made it change, it would say something like The dishwasher is ready in and 50 minutes, included the and in the template now when there are 0 hours. And 2 hours and 0 minutes is fine πŸ™‚

#

Now I think of it, it might be better to only use this when it's below one hour, otherwise it might be easier to report just the time

#

Will do some more tinkering, but I can move further now πŸ™‚ Thanks!

mighty ledge
#
          {%- set word_for_and = 'and' %}
          {%- set up_time = (state_attr('timer.vaatwasser_timer', 'finishes_at') | as_datetime - now()).seconds %}
          {%- macro phrase(name, plural_name, divisor, mod=None) %}
            {%- set value = ((up_time // divisor) % (mod if mod else divisor)) | int %}
            {%- set name = plural_name if value > 1 else name %}
            {{- '{} {}'.format(value, name) if value | int > 0 else '' }}
          {%- endmacro %}
          {%- set values = [ 
                     phrase('hour', 'hours', 60*60, 24),
                     phrase('minute', 'minutes', 60), 
                 ] | select('!=','') | list %}
          {{ values[:-1] | join(', ') ~ ' ' ~ word_for_and ~ ' ' ~ values[-1] if values | length > 1 else values | default | first }}
marble jackal
#

Will have a look at that.
I tried to make the template to report the time it finishes, but I run into a timezone issue there:
"The dishwasher finishes at {{state_attr('timer.vaatwasser_timer', 'finishes_at') | as_timestamp | timestamp_custom('%H:%M') }}." gives 17:00 as result, though the timestamp is 2021-12-16T16:00:15+00:00 which is correct in local time

#

Guess it assumes the timestamp is in UTC

hexed wing
#

all times in HA are UTC (or at least it should be, in this case it is)

#

You can use the as_local filter to convert it

mighty ledge
#

I think we need to add datetime_custom, datetime_local, datetime_utc veriations of timestamp_custom, etc

hexed wing
#

why?

mighty ledge
#

because peopel are shifting towards the easier to work with option, which is datetimes

marble jackal
hexed wing
hexed wing
mighty ledge
#

yah, but it's strftime

#

ask a non coder what that does

hexed wing
#

it is linked in the docs

mighty ledge
#

I understand

hexed wing
#

making it separate functions are not making things more logical imho.

mighty ledge
#

I'm just giving my 2c because I help people with time daily

hexed wing
#

having multiple ways to do things, does not help

#

explaining and examples do

mighty ledge
#

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

hexed wing
#

That is a frontend concern

mighty ledge
#

if that's really the case, then make timestamp_* work with datetimes

#

This channel is only for templates. I.e. code inside {{ }} or {% %}

hexed wing
#

in general, most timestamp_* methods are not really needed anymore

#

as_datetime also swallows a unix timestamp btw

marble jackal
#

oh wait, I'm dumb.. The timestamp is in UTC

mighty ledge
#

Yah, I was just trying to think of ways to make time easier in templates. I keep coming across many posts about time and anything that will make it easier for people to understand the better IMO.

#

it doesn't help that the forum has 90248309823948 old time posts

#

Right, that's atemplate though

#

asking about the notification on the other hand, is not a template

hexed wing
#

You don't need to. As sensor should return a device_class timestamp and the frontend will handle that

#

it takes care of timezone conversions as well

#

for push notifications, always use the as_local filter to convert any datetime object to the HA timezone set by the user.

mighty ledge
#

good rule of thumb: Does the question I have, have to do with the template inside xyz yaml? If yes, ask here, if no, not here

marble jackal
#

Well, at least this works for me πŸ™‚ Thanks guys!

            {% set remaining = (state_attr('timer.vaatwasser_timer', 'finishes_at') | as_datetime - now()).seconds %}
            {% set hours = (remaining / 3600) | int %}
            {% set minutes = (((remaining / 3600) - hours) * 60) | int %}
            {% if hours == 0 %}            
              "De vaatwasser is over {{ minutes }} {{ 'minuut' if minutes == 1 else 'minuten' }} klaar." 
            {% else %}
              "De vaatwasser is klaar om {{state_attr('timer.vaatwasser_timer', 'finishes_at') | as_timestamp | timestamp_custom('%H:%M') }}."
            {% endif %}
hexed wing
#

good rule of thumb: If you are hacking timezones, you are doing it wrong πŸ˜„

mighty ledge
#

if you're unfamiliar with YAML and JInja, check out the 3rd pin

marble jackal
#

Had a look at your template as well petro, works fine, but it is more code, so I just went with this πŸ™‚

hexed wing
#

Well yes, if you don't specify the format, it will be the default object string conversion, which is an iso format.

mighty ledge
#

Most copy/paste monkeys can just adjust the names and delete the stuff they don't want

hexed wing
#

That isn't available, because you are backend. There is no browser context

mighty ledge
#

isn't local set though? So using %c, %x or %X should work

#
{{ now().strftime('%c') }}
hexed wing
#

Yeah that will do probably

#

however, that is still not based on timezone, but locale

#

which we don't handle

mighty ledge
#

right

#

well, a notification wouldn't have the context of who's getting it anyways

#

that's on the notification's endpoint's side

hexed wing
#

Make a nice option list for users in your Blueprint to choose from πŸ™‚

mighty ledge
#

and what ahppens if you're in the US but HA is in the UK?

#

HA doesn't know where you are

hexed wing
mighty ledge
#

well, you as in your notification endpoint

hexed wing
#

True

mighty ledge
#

so, no matter what, it will be in HA time, not endpoint time. Which means this whole conversation is a moot point.

hexed wing
#

Anything time and translations are just 😠

#

always

#

no matter the piece of software

mighty ledge
#

yep

hexed wing
#

we all should just go use UTC, the metric system and settle on a number and time formatting.

mighty ledge
#

so anyways, back to your question... it's not possible because of what I said anyways, unless your endpoint can handle isoformat timestamps

#

then you'd just leave it as "{{ now().isoformat() }}"

marble jackal
#

.beat time?

mighty ledge
#

it already does that

#

if you're referring to what's set in HA on your user page, then no it does not do that. But that's user dependent, not system IIRC

#

and templates and notifications are user agnostic

#

so, catch22

#

no....

#

{{ now().strftime('%X') }}

#

not only that you're removing seconds

#

which isn't what you're asking anyways

#

that's a completely different thing

#

and there is no 'system time setting'

#

its per user, hence the issue.

#

you'd still have to specify which user

#

going in circles here

#

Then what's the problem? Make a script and specifiy it once and call that script to pass the info

#

you don't need to do the template every time. wrap your notification in a script and call that.

#

I'll give you mine, which does that.

#

again, it won't work because there is no system time

#

are we suppose to pick a random user?

#

round and round we go

#

You can simply make a variable for the blueprint that specifies the format

#

or you can make a dropdown of formats

#

many ways to do this

tacit arch
#

Hello, I've a diy tasmota powermeter. I added as sensor on mqtt platform. The problem is sometimes chenge its entity id with _0 and _1 so if I log sensor.power_home_energy_power, It changes on sensor.power_home_energy_power_0, and I have no idea why this happens. Can you help me?
I tried assigning a unique id but didn't works
https://www.toptal.com/developers/hastebin/rivuyawuji.yaml

merry swallow
#

Is it possible to have a list off binary_sensors and return the number of binary_sensors that are on?

#

i have a notification to my phone when there is a update for HA and i would like to also add the number off addons that have an update

glacial matrix
#

Hi guys and gals,
when I put the following template into the dev tools, i get line breaks, but when i impliment it, Ha just creates a list, is there a way of fixing that?

{% set do_child1bins = is_state('sensor.child1_bins', 'today') %}
{% set do_child1dishwasher = is_state('sensor.child1_dishwasher', 'today') %}
{% set do_child1fridge = is_state('sensor.child1_fridge', 'today') %}
{% set do_child1tablet = is_state('input_boolean.child1_tablet', 'on') %}
{% set child1bins = 'Empty Bins, \n' if do_child1bins else '' %}
{% set child1dishwasher = 'Dishwasher Duty, \n' if do_child1dishwasher else '' %}
{% set child1fridge = 'Refill Fridge, \n' if do_child1fridge else '' %}
{% set child1tablet = 'Take Tablet, \n' if do_child1tablet else '' %}
{{child1tablet}}{{child1bins}}{{child1dishwasher}}{{child1fridge}}
#
Result type: string
Take Tablet, 
Empty Bins,
sensor.child1_chores
Xander's Chores
Take Tablet, Empty Bins,
mighty ledge
glacial matrix
#

I want each result to be on a different line, as it shows in the template test, but it looks like HA doesn't parse the /n when implemented as a sensor. it's going to basically form a list, that i'm hoping to display on a magic mirror.

mighty ledge
#

whitespace is stripped from sensor states

#

If you want a list in HA, you have to use the markdown card. Otherwise, all states are single line only.

glacial matrix
#

That's frustraiting. it looks like other have tried it too searching online. it shows as expected when using the template testing. Is there another way round it? I have three children, and want to create a list for each of them bassed on input booleans, so that when they have completed them, they scan a QR code or an NFC tag, and it switches the input off, so it is removed from the list.

glacial matrix
#

I wont be displaying this in lovelace, it will be displayed using magicmirror.

mighty ledge
#

And what are you displaying on the magicmirror? Is it just a state from HA?

#

Change how you are getting the data from HA to Magic mirror

glacial matrix
#

At the moment in a region they show in a region using a modified version of the HomeAssistant module for magic mirror. The plan was to put each child in their own region, i tried to add a screen shot, but cant past images to this channel

#

what other way can i get the information into HA?

mighty ledge
#

it's the other way around

#

you need to get data from HA to magic mirror

glacial matrix
#

pmsl. sorry. what other way can i get the info to MM?

mighty ledge
#

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

#

I have no idea how magic mirror works

#

It's surprising that it doesn't have the ability to be casted to.

glacial matrix
#

it runs on a raspberry pi, and is basically a webserver\page that pulls information from other sources.

mighty ledge
#

Right, and there's no way to configure the source?

#

there's no way to configure the display of the source?

#

you only get sensor states?

glacial matrix
mighty ledge
glacial matrix
#

sorry, modify which code? The home-assistant-sensors module?

mighty ledge
#

Yes

#

it's a rigid definition

#

attributes can be used, however it's not clear if a list will be properly formatted if the attribute is a list.

glacial matrix
#

ok, thanks. I'll need to learn how to do that. I guess all i really need it to do is replace ',' from the attributes with '\n'? Think this might be a little beyond my current skill set.

#

Just looking at this now, and i have no clue what which files i need to modify, or how they even work at the moment.

young jacinth
#

hi, i want to get the temperature information of a weather entity at a certain time

{{ state_attr('weather.home', 'forecast').1.temperature }} Β°C"

this is how i would solve this if the forecast would be at a fixed place in the attribute list
but i always want to have to forecast for this datetime:
datetime: '2021-12-17T06:00:00+00:00'

so i have to filter the time first and then iam lost

#

the datetime is given in the attribute of the list entry

inner mesa
#

something like this:

#

{{ state_attr('weather.home', 'forecast')|selectattr('datetime', 'eq', '2021-12-20T20:00:00+00:00')|map(attribute='temperature')|first }}

#

-> 59.7

#

@young jacinth

young jacinth
#

today+1 could do it

inner mesa
#

your requirements are changing πŸ™‚

hexed wing
#

πŸ‘† That is how software development works πŸ˜„

inner mesa
#

but yes, you can use something like today_at('06:00') + timedelta(days=1), but that sadly removes the "T"

hexed wing
#

{{ (today_at('06:00') + timedelta(days=1)).isoformat() }}
πŸ‘† Solves the T

inner mesa
#

{{ (today_at('06:00') + timedelta(days=1))|string|replace(' ', 'T') }}

#

or that

young jacinth
#
{{(today_at('06:00') + timedelta(days=1)).isoformat()}}

output is 2021-12-17T06:00:00+01:00

#

i need 2021-12-17T06:00:00+00:00

#

πŸ™ƒ

#

is this a timezone information?

inner mesa
#

yes

#

did you try mine?

young jacinth
inner mesa
#

🀷

#

oh, you want to get rid of teh timezone?

#

I recommend reading the templating docs

neon frigate
#

So I have an zwave_js_notification event. How can I turn that in to a binary sensor (or something else) which would then give me historical records of when the event was triggered? E.g. "Matt was the one who unlocked the door" -- I would probably like to have this "delayed" for, like, I don't know -- 1-2 minutes? "Delayed" as in activated so I can easily see it in the history record

ivory pawn
#

hey guys, is this the right place to get some help for sensors?

#

i prefer not to go the automation route unless needed. thanks

young jacinth
#

i actually dont see how the ha template docs would help me here

young jacinth
# inner mesa or that

as i have to change the output of the utc timezone from +01:00 to +00:00
oh wait... i have to change this output to the utc tinmezone format
but i dont really get how
i dont see a matching filter in the docs

neon frigate
lament fjord
#

how do you add a binary_sensor to configure.yaml

dreamy sinew
#

That is covered in the docs for that integration

lament fjord
#

im trying to get my zigbee button work with a blueprint, but the input required is a Binary_sensor

bleak ridge
#

using "Power calculation" which create power and energy sensors for all light entitites automatically.. attempting to sum the power without success.. Ideas appreciated. Result = 0.0 {% set domain = 'light' %} {% set entities = states[domain] | map(attribute='entity_id') | list %} {% set samlet = 0 %} {% for entity_id in entities %} {% set komponenter = entity_id.split('.') -%} {% set power = states('sensor.' ~ komponenter[1] ~ '_' ~ 'power') | float %} {% set samlet = (samlet + power)| float %} {% if loop.last %} {{ samlet }} {% endif %} {% endfor %}

dreamy sinew
#

That's a namespace problem. You can't alter something that is outside of a loop from inside one

#

Unless you use a namespace object. Should be covered in the jinja2 docs

bleak ridge
#

ty, I'll look into namespace objects

dreamy sinew
#

I'd type out an example but I'm on mobile

silent barnBOT
thin vine
#

my bad I though it was within the limit

tawny coral
#

Hi, I'm trying to make a timer that starts every time a binary sensor changes state

 - platform: template                                                                        sensors:                                                                                    atlas_sleep_timer:                                                                          friendly_name: Atlas sleep timer                                                          icon_template: mdi:clock-outline                                                          value_template: >                                                                           {% set t = states('sensor.time') %}                                                       "{{ relative_time(states.binary_sensor.openclose_33.last_changed) }}"```
#

However it seems to update randomly, and not every minute as expected

mighty ledge
silent barnBOT
neon frigate
#

Ops - please help πŸ™‚

mighty ledge
#

list out your triggers in the template section and remove the 2nd template key

#

i.e.

template:
- trigger:
  ..
- trigger:
  ..
neon frigate
#

Aha, sweet - thanks, it worked!

austere zenith
#

hi there, simple question

#

just wanna create a switch template.

#

how do i create icons for when its 'on' and when its 'off'?

#

i understand i should use the icon template

#

i tried googling a bit, but ended up being more confused than before. Can someone direct me to the correct page?

mighty ledge
#

there won't be a '1 solution fits all' example for templates that solves your problem. Templates are unique and purely depend on your input entity and your desired goal

austere zenith
#

{% if is_state('switch.door', 'on') %}
mdi:door-open
{% else %}
mdi:door-closed
{% endif %}

mighty ledge
#

Your best option is to post what code you've tried and explain what you are trying to do.

austere zenith
#

is it jsut something like this?

#

im not entirely sure.

mighty ledge
#

if those are teh correct icons and switch.door is the source entity (not the entity you are creating), then that is correct

austere zenith
#

oh ok, i'll give it a go. sorry, i wasn't very confident. still kinda new to using jinja

#

i suppose i was confident i was wrong.

mighty ledge
#

what's the worse that will happen? Try until it works

#

you'll only lose time, but you'll learn in the process

austere zenith
#

i searched online initially, and just got very confused.

mighty ledge
#

bad configs will not break your system. You can always remove what doesn't work

unique lichen
#

I have an MQTT template defined as a timestamp device class but my state value is always shown in UTC time and I am sending a local time. I have tried to add | timestamp_local but this doesn’t change. Is a state always in UTC time?

mighty ledge
dense kayak
#

Hopefully this is posted for the right channel. I'm trying to see if I'm able to send into my REST notify call, besides just "message" and "title", the value for priority. I currently have this defined in the configuration.yaml, but would like to be able to control this per-action, instead of using the hard-coded 10. can this be done? the top is my notify config, the bottom is one of my action scripts.

https://www.toptal.com/developers/hastebin/yuyaqazana.yaml

mighty ledge
#

do you have alink to the github repo?

dense kayak
#

it's not custom. i have nothing for it in custom_integrations, or whatever it's called

mighty ledge
#

that notify platform doesn't exist

#

nevermind i'm being dumb

dense kayak
#

lol

#

all i want to do is be able to pass in the value for "priority". specifically, this is calling Gotify, so i believe "priority" is part of the root JSON payload

mighty ledge
#

I'll reply shortly, work calls

dense kayak
#

same!

mighty ledge
#

follwed by

#
# action script
data:
  message: '{{trigger.to_state.name}} is now {{trigger.to_state.state}}'
  title: Light Switch Alert
  data:
    priority: 10
service: notify.gotify
dense kayak
#

i actually tried that, but it didn't actually send the priority

mighty ledge
#
notify:
  - name: Gotify
    platform: rest
    method: POST
    resource: "my rest url"
    message_param_name: message
    title_param_name: title
    data:
      priority: "{{ priority }}"
dense kayak
#

thank you. i'll try this shortly

mighty ledge
#

action will be

#
# action script
data:
  message: '{{trigger.to_state.name}} is now {{trigger.to_state.state}}'
  title: Light Switch Alert
  data:
    priority: 10
service: notify.gotify
#

or

#
# action script
data:
  message: '{{trigger.to_state.name}} is now {{trigger.to_state.state}}'
  title: Light Switch Alert
  priority: 10
service: notify.gotify
#

not sure which without looking at the code

dense kayak
#

thank you so much! i'll try this and post back.

marble jackal
#

I have a bit of a challenge (well at least for myself and my template knowledge.
I have a dictionary called speaker_groups with media_player entities, which are Google Home speakers groups. Each key has a list with the media_player entities which are members of that speaker group.
Now, for my script to work properly, I would need to know if there are key values of speaker_groups of which all members are also part of a larger group. e.g. the 2 speakers which are part of media_player.kitchen_group, are also both included in the media_player.house_group.
That would define media_player.kitchen_group as a sub group of media_player.house_group

I have an example here: https://www.codepile.net/pile/dBPPYrBL

I tried it myself, but at some point I had 3 nested for loops and did not know what I was doing anymore..

mighty ledge
#

how about showing an input

#

and then showing what you want as an output

#

Like, are you trying to make a bunch of nested groups and then return a list of only single media_players?

#

basically, you have groups but in the end you only want the actual media players that the groups represent

marble jackal
#

Input and wanted output are in the link

mighty ledge
#

yeah, I didn't scroll up

#

I was only looking at the end

#

lol

#

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

marble jackal
#

Ah okay, no problem πŸ™‚

mighty ledge
#

So why do you want this info

marble jackal
#

Well, I have this script to resume a stream after a TTS is sent to a speaker group. But in case a TTS is sent to the house group, and the kitchen group is playing, it will resume the individual entities of the house group, and not the kitchen group media_player

#

The sub groups solve that

#

rubber_duck maybe I can solve it by simply including the sub group as a member in speaker_groups

mighty ledge
#

Well, there's no easy way to do your looping

#

It would be easier to nest your groups and write a recursive macro that returns your speaker_groups

#

i.e. Your setup is:

{% set speaker_groups = {
              ...
              "media_player.kitchen_group": [
                "media_player.bedroom_speaker",
                "media_player.dining_group"
              ],
              "media_player.dining_group":[
                "media_player.kitchen_speaker",
                "media_player.dining_table"
              ]
            } %}
#

then you can get both

#

going the opposite way will take alot of work because you have to iterate each item and see if each item of your current list resides in another element. It could easily get complicated fast

marble jackal
#

Thanks, I will look into it!

mighty ledge
mighty ledge
#
{%- set ns1 = namespace(current=[]) %}
{%- for k, v in speaker_groups.items() %}
  {%- set ns2 = namespace(current=[]) %}
  {%- for k2, v2 in speaker_groups.items() if k != k2 %}
    {%- set shared = v | select('in', v2) | list %}
    {%- if shared == v2 %}
      {%- set ns2.current = ns2.current + [ k2 ] %}
    {%- endif %}
  {%- endfor %}
  {%- if ns2.current %}
    {%- set ns1.current = ns1.current + [ (k, ns2.current) ] %}
  {%- endif %}
{%- endfor %}
{%- set reduced = dict(ns1.current) %}
{%- set ns = namespace(current=[]) %}
{%- for k, v in reduced.items() %}
  {%- for k2, v2 in reduced.items() if k != k2 %}
    {%- set ns.current = ns.current + [ (k, v | reject('in', v2 if k2 in v else []) | list ) ] %}
  {%- endfor %}
{%- endfor %}
{{ dict(ns.current) }}
#

without altering anything

young jacinth
#
{{ (today_at('06:00') + timedelta(days=1)).isoformat() }}
{{ utcnow().isoformat() }}

output:
2021-12-18T06:00:00+01:00
2021-12-17T18:18:00.009959+00:00

how do i convert the timezone from the first to utc?

#

2021-12-18T06:00:00+00:00
this should be the output

mighty ledge
#

why do you want utc?

young jacinth
#

my wetaher entity attribute has this timeformat

mighty ledge
#

so?

#

explain what you want, nto what you think you need to do

#

x/y problem

silent barnBOT
#

The XY problem is asking about your attempted solution rather than your actual problem.

This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.

mighty ledge
#

thanks booboo @buoyant pine

young jacinth
#

i want the forecast of my weather entity for 6am on the next day

mighty ledge
#

what's the format and entity?

young jacinth
#

datetime: '2021-12-18T06:00:00+00:00' this is the format

mighty ledge
#

FYI, you would have been off by an hour if you converted that to UTC

#

is it a string or is it a datetime object?

young jacinth
#

iam not sure

mighty ledge
young jacinth
#

okay, but how do i get the forecast for temperature now?

#

for example

#

forecast is an attribute of weather.home
forecast:

  • datetime: '2021-12-17T21:00:00+00:00'
    temperature: 7.9
mighty ledge
#

Sorry have to step away for a bit

marble jackal
mighty ledge
young jacinth
#

yay that worked

#

thanks alot

sonic nimbus
#

how can I overcome this: entity_id: > {% if trigger.entity_id == 'binary_sensor.office_closet' %} light.office_closet_lights {% elif trigger.entity_id == 'binary_sensor.office_wardrobe_left_door' %} light.office_wardrobe_left_left,light.office_wardrobe_left_right {% elif trigger.entity_id == 'binary_sensor.office_wardrobe_left_door' %} light.office_wardrobe_right_left,light.office_wardrobe_right_right {% else %} #DoNothing {% endif %}

#

Im receiving an error saying that entity_id is not correct..

#

I've read somewhere sometime, that we cant decalre entitiy_id from trigger_tos_state.entity_id

mighty ledge
#

condition to stop it

#

before it gets there with no entities

sonic nimbus
#

what should that condition should be holding?

mighty ledge
#

that logic, but specifically loking for do nothing

sonic nimbus
#

but erorr type is quite different?

#

Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['entity_id']. Got None.

#

can I put fore example sun.sun entity in my else part?

mighty ledge
#

my man, a condition for the automation

#

literally can copy/paste that template and change the outputs to True, True, True, False and you'll have what you want for the value_template of the template condition

sonic nimbus
#

Im afraid I dont understand πŸ™‚ I dont know what to put in that condition for my automation..

mighty ledge
#

what's your template?

sonic nimbus
#

this is my automation

mighty ledge
#

no

#

i'm not looking at it

#

what's your template that you literally just posted

mighty ledge
#

what does it output?

sonic nimbus
#

yes?

#

it checks my if-else statements

mighty ledge
#

ok

sonic nimbus
#

so basically, it looks for trigger name entity

#

and if trigger was one sensor, then corresponding light is for it

#

so I need to alter entities based on triggers names

mighty ledge
#

and if you were to change that to output true/false

#

what would it look like?

#

instead of entity_ids

sonic nimbus
#

well I would be having something entity_id: true ?

mighty ledge
#

no

#

Just the template

#

do you know the difference between yaml and a template?

sonic nimbus
#

yes

#

it's basically ninja template for python scripting

mighty ledge
#

ok, so what would your template be if it were to output True or false with your same logic

#

instead of outputting the entity_ids it outputs true or false...

sonic nimbus
#
{% if trigger.entity_id == 'binary_sensor.office_closet' %}
         True```
You mean like this ?
mighty ledge
#

you're almost there

#

just need the rest of the template

#

but you're still including yaml

sonic nimbus
#

Im trying to understand..

mighty ledge
#

i'm not convinced you know the difference

sonic nimbus
#

template always begins with {{ or {% and ends also with parenthesis. I never think of what is actually here is yaml, but obviosly the yaml is entitiy_id:

mighty ledge
#

ok, then what is your template when you replace your output lines with True and False. True where you're outputting entities false where you're not

sonic nimbus
#
          True
        {% elif trigger.entity_id == 'binary_sensor.office_wardrobe_left_door' %}
          True
        {% elif trigger.entity_id == 'binary_sensor.office_wardrobe_left_door' %}
          True
        {% else %}
          False
        {% endif %}``` I think still that my entity will be always `True` in this particular case, when automation kicks in
mighty ledge
#

ding ding ding

#

that's your template

#

now, use that template as a template condition on your automation

#

you know what a condition is for automations right?

sonic nimbus
#

ofc..Im .net developer πŸ™‚

mighty ledge
#

Ok, then all you need to do is add the yaml for a condition: template using that template.

#

to your automation

sonic nimbus
#

and Im not really new to HA environment..I have HA for like 2 and half years, Im having so much automations and templates..some part of those templates were stolen from you answering on other peoples questions πŸ™‚

mighty ledge
#

I know you 've been here a while, which is why i'm not writing this for you and having you write this yourself

#

you have all the pieces you need to add this to your atuomation, you just need to add it

sonic nimbus
#

just didn't know for this "hack" to put condition with true/false in order to work entity_id templating..

mighty ledge
#

you aren't templating the entity_id

#

you're templating a conditon for the automation

#

so that it doesn't run your actions when you don't have an entity_id

sonic nimbus
#

yes, but I need entity_id part right? πŸ˜„ let me check πŸ™‚

mighty ledge
#

you aren't changing anything int hat automation. You're just adding a conditon.

#

that condition has the template you just wrote out

sonic nimbus
#

still I have same error when I hit check config

#

πŸ™‚

#

probably I dont see something that Im missing..

mighty ledge
#

You added the condition wrong. Compare to any other automation you have with a condition

sonic nimbus
#

I fixed, but this is aint my night, still error πŸ˜„

young jacinth
#

how would i add a substring to max_temp?

{% set max_temp = state_attr('weather.home', 'forecast').0.temperature %}

so if i do {{ max_temp }} i would get 7Β°C

#

i dont want to do it like this {{ max_temp }}Β°C

mighty ledge
#

Why?

sonic nimbus
#

this condition is maybe better written: ``` condition:

  • condition: template
    value_template: >
    {% if trigger.to_state.entity_id in ('binary_sensor.office_closet','binary_sensor.office_wardrobe_left_door','binary_sensor.office_wardrobe_left_door') %}
    True
    {% else %}
    False
    {% endif %}```
#

so, any trigger with naming of my binary_sensors, will return true, so my automation will proceed

young jacinth
# mighty ledge Why?

iam building a weather notification
it's {{ states('weather.home') }} Β· {{ secondary_info }}
i want to choose the secondary_info based on time conditions and with different wording

#

like
todays maximum temperature will be {{max_temp}}

mighty ledge
#

~ 'C'

young jacinth
#

thanks

sonic nimbus
#

definitely it's something due to if statements

#

I testes with persistent notification for trigger.entity_id

#
     condition: template
     value_template: >
        {% if trigger.to_state.entity_id in ('binary_sensor.office_closet','binary_sensor.office_wardrobe_left_door','binary_sensor.office_wardrobe_left_door') %}
          True
        {% else %}
          False
        {% endif %}
  action:
    service: persistent_notification.create
    data:
      title: >
         {{trigger.entity_id}}
      message: "Test indeed."```
fossil venture
#

This should evaluate to true or false: ```
value_template: "{{ trigger.to_state.entity_id in ('binary_sensor.office_closet','binary_sensor.office_wardrobe_left_door','binary_sensor.office_wardrobe_left_door') }}"

sonic nimbus
#

still I have no luck

silent barnBOT
sonic nimbus
#

I started with only this: - service: > light.turn_{{trigger.to_state}} entity_id: > {{trigger.to_state.entity_id}}

fossil venture
#

Use only the single line I wrote for the template.

sonic nimbus
fossil venture
#

delete this:```
True
{% else %}
False
{% endif %}

sonic nimbus
#

here is my udpated script, but still I have error

fossil venture
#

and the error is...?

sonic nimbus
#

Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['entity_id']. Got None. (See /config/configuration.yaml, line 71).

#

it looks that trigger.to_state.entity_id is empty?

fossil venture
#

You need to test the automation by setting off the movement sensors. Manually triggering the automation wont supply any trigger variables.

sonic nimbus
#

that eror is coming up when I hit check config

fossil venture
#

Also looking at your automation you don't need the condition.

sonic nimbus
#

I didnt run script manually

#

funny thing is that, if I put for entity_id some real entity for example light.office_main_light it will work wihout issue

#

just I cannot figure it out why I cant use templating for entity_id

fossil venture
#
  action:
    - service: >
        light.turn_{{trigger.to_state}}
      target:
        entity_id: >
          {{trigger.to_state.entity_id}}
sonic nimbus
#

it works πŸ˜„ hahah I can't believe it!

#

what the hell is target now? πŸ˜„

fossil venture
#

The same thing as data: but specifically for specifying what to apply the service to. You can only use templates directly under service:, data: or target:

#

you may also be able to do this (though don't):```
action:
- service: >
light.turn_{{trigger.to_state}}
data:
entity_id: >
{{trigger.to_state.entity_id}}

sonic nimbus
#

yes, Im familiar with some my other automations, that I need to provide data:

#

but I didnt use target: at all to this moment

fossil venture
#

It has been around for quite a few updates now. Easy to miss these things though.

#

You can target more than just an entity id. You can target an area for example.

sharp dirge
#

I have trouble with creating a sensor, based on a smart power plug. I include all sensors by loading a folder with sensor: !include_dir_list ../entities/sensors
It currently gives me a weird error, complaining that platform is missing? What could/should I add?
The sensor can be found here: https://www.codepile.net/pile/7MLW1zjD

#

The error: Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See ?, line ?).

sonic nimbus
#

thanks @fossil venture and petro for help! I learn a lot today πŸ™‚

fossil venture
#

If you want to have the sensor under sensor: use the old template sensor format.

buoyant pine
fossil venture
#

Sure, it's backward compatible, but this is "the new way" β„’

sharp dirge
#

Don't really see what I'm doing incorrectly

fossil venture
#

template: must go hard against the margin of your configuration.yaml file. Just like sensor: . The way your are trying to do it puts template: indented below sensor:

#

this is what your configuration.yaml file should look like:```
sensor: !include...

template:

  • sensor:...
#

This is what you will end up with what you are trying by putting template: in your sernsor: !include... (once the includes are resolved):```
sensor:
template:
- sensor:...

#

Template is a whole new integration, just like Sensor but separate from it. You can still use the old template platform under the sensor integration though, see the legacy link I posted earlier.

mighty ledge
#

That’s why that thread doesn’t work

#

You’d have to have a separate file for each triggered section

#

Or you use template: !include_dir_merge_list templates and put your 3 files in the template folder: sensor.yaml, triggers.yaml, and binary_sensors.yaml

fossil venture
#

Yep, but as I said in the topic I wanted a flat !include structure.

mighty ledge
#

Ya

fossil venture
#

On an unrelated note. What happens to this template when the uptime is > 24 hours?

mighty ledge
#

I don’t think it can be done

fossil venture
#

{{ ( now() - states('sensor.uptime')|as_datetime + today_at()).hour > 2 }}

mighty ledge
#

I’m trying to think of ways but include doesn’t allow for a merge @ different levels of the yaml

fossil venture
mighty ledge
#

Yah they are rare for me too

mighty ledge
#

Today_at resets at midnight

#

So at most it’ll be 23:59:59.999999 away from midnight

#

Well wait a minute

#

I might be reading that template wrong, on mobile

fossil venture
#

Yeah I'm not convinced it is correct. The .hour will reset every 24 hours.

mighty ledge
#

I have to wrap my head around it. Uptime could be really far in the past

#

What’s uptimes state? A datetime string?

#

I overwrote mine in my system

fossil venture
#

Yes, current state: 2021-12-17T15:14:22+00:00

#

If I just do this: {{ ( now() - states('sensor.uptime')|as_datetime ).hour > 2 }} I get UndefinedError: 'datetime.timedelta object' has no attribute 'hour'

mighty ledge
#

Ah yea

fossil venture
#

Oh I see what I'm doing wrong

mighty ledge
#

.seconds is available on time deltas

fossil venture
#

This is what I want: {{ ( now() - states('sensor.uptime')|as_datetime ).seconds > 7200 }}

mighty ledge
#

Ya

fossil venture
#

Thanks.

#

Why is there no .hours (or minutes for that matter) ? That would be handy.

mighty ledge
#

It’s just the built in timedelta object

#

For python

#

No clue why hours isn’t on it

fossil venture
#

Do you feel like submitting some more datetime PRs? 😁 It was you that added timedelta() and today_at() wasn't it?

#

Very handy additions.

mighty ledge
#

I added today_at

#

I’m thinking about adding hours, minutes, and seconds filters

buoyant pine
#

@mighty ledge you should add deez_nuts()

fossil venture
#

LOL. Save it for an April 1st PR next year.

buoyant pine
#

Solid idea. I know what I'm doing this time

wise citrus
#

https://pastebin.com/J3yjxVXf can anyone tell me it keeps returning 0 instead 0f 0.241 ? Not sure what i am doing wrong i except a value under 0 is returned

fossil venture
#

This will never be true: {% if is_number(states('sensor.daily_energy_offpeak')) and is_number(states('sensor.daily_energy_peak')) %} as states() returns strings.

#

States are always strings.

#

Ignore what the template editor says. The editor interprets the type results. Templates don't actually do that though. I have raised this as an issue but was told it is working as expected.

#

You're probably going to have to do something like this: {% if states('sensor.daily_energy_offpeak') not in ('unknown', 'unavailable') and states('sensor.daily_energy_peak') not in ('unknown', 'unavailable') %}.

#

Also you are not converting the states to numbers here: {{ (states('sensor.daily_energy_offpeak') + states('sensor.daily_energy_peak')) | float(0) | round(3) }} It should be like this: {{ ( states('sensor.daily_energy_offpeak')|float(0) + states('sensor.daily_energy_peak')|float(0) ) | round(3) }}

wise citrus
#

I picked the code from official documentTion strange

fossil venture
mighty ledge
#

technically, the template is only missing a float

#

for it to be correct

#

because is_number checks the state for numbers

#

which filters out unknown, unavailable, and other strings

#

and the parenthesis are wrong

#

anyways, making a PR for it

hexed wing
#

Thanks, @mighty ledge Approved and merged

pastel moon
#

Noticed this warning Template warning: 'int' got invalid input 'unknown' when rendering template '{{ (states('sensor.avg_illumination') | int) | default(0) }}' but no default was specified. Currently 'int' will return '0', however this template will fail to render in Home Assistant core 2022.1 and added | default(0) in hope to not see this again, but... So could someone please enlighten me... What default is missing? Fort the template is obvious, but if what I did was not it, then how?

mighty ledge
pastel moon
#

Will do. thx πŸ™‚

pastel moon
#

I have this type error also, from rendering a template for a sensor in configuration.yaml, happens after a restart https://pastebin.com/peLTPGeS I get that it probably is because it hasn't got it's value (or type) at time of render, but what can I do to prevent the error? It works fine just moments after when it has populated.

atomic python
#

trying to increase an input_number by using set value (cannot use the increment as the value is always different) inside a script like this but I know this is wrong:

service: input_number.set_value
target:
  entity_id: input_number.left_open_perc
data:
  value: {{ value | float + 50 }}

Can anyone pls help with the correct syntax, thx

buoyant pine
#
"{{ states('input_number.left_open_perc') | float + 50 }}"
atomic python
#

hmm expected float for dictionary value @ data['value'] says this

buoyant pine
#

I forgot the double quotes on the outside

#

Try it with my correction @atomic python

atomic python
#

I think something is still wrong:

service: input_number.set_value
target:
  entity_id: input_number.left_open_perc
data: '{{ states('input_number.left_open_perc') | float + 50 }}'
#

still complains

buoyant pine
#

Double quotes...

hexed wing
#
service: input_number.set_value
target:
  entity_id: input_number.left_open_perc
data: 
  value: "{{ states('input_number.left_open_perc') | float + 50 }}"
buoyant pine
#

You have single quotes on the outside, not double like I showed

atomic python
#

I saved as double and it just changes when I get back into edit of the script

buoyant pine
#

Wut

atomic python
#

yup what @hexed wing said, forgot the value under data

#

works now, many thanks

buoyant pine
#

Oh i didn't even notice you left it out heh

wise citrus
vagrant monolith
#

How do I do this to a type datetime.datetime?

            {{strptime(states.sensor.sunset.attributes.today - timedelta(hours=1), default)}}
mighty ledge
vagrant monolith
#

I need to add the attribute today

#

But how?

#

Because this happens

{{ state_attr('sensor.sunset', 'today') | as_datetime | as_local - timedelta(hours=1) }}

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

Worth saying is that sensor.sunset has this value as attribute

today: 2021-12-18T15:37:03.134698+01:00
dense kayak
thorny snow
#

Hi guys

#

does light template support templates in the entity_id whithin the turn_on service?

#

I think it doesn't.. it doesn't allow me to restart

#

oh it does

#

it requires data_template: though

dense kayak
#

the one that used

data:
  priority: 4
mighty ledge
#

Nice, good to know

mighty ledge
#

you can template anything inside the data field. Same with target.

meager spire
#

I need some help, something broke!

sensor:

  • platform: statistics
    name: Estadisticas Potencia
    sampling_size: 86400
    entity_id: sensor.medidor_energetico_power

    potencia_max:
    value_template: '{{ states.sensor.estadisticas_potencia.attributes.max_value }}'
    unit_of_measurement: 'W'
    potencia_min:
    value_template: '{{ states.sensor.estadisticas_potencia.attributes.min_value }}'
    unit_of_measurement: 'W'

#

Now it only shows 0

inner mesa
#

Read the statistics docs. Those attributes no longer exist

meager spire
#

ops... look that I usually read the "break changes"

#

I'm going to read to see if the translator helps me;)

THANK YOU

inner mesa
#

No, for the integration that you’re using.

#

You’ll see that the attributes are no longer there if you check in devtools -> States

meager spire
#

It cost me a lot because I could not find the page and then I did not see the example.

But once seen it seems more "logical".

#

Delete the template and add:
state_characteristic: value_max

hollow plinth
#

Hey everyone, I'm trying to create a template binary sensor that would go on when I use a switch and go off by itself after some time (45sec). I'm not familiar with the value template and I dont really understand the documentation about it.

#

Can someone give me a hand on that?

inner mesa
#

that would typically be done by an automation, but I think you could do with it a triger-based template sensor

#

to be clear, you want the binary_sensor to turn off even if the switch is still on?

#

@hollow plinth

hollow plinth
#

Yes, the switch turn off automatically already.

#

its my gate control, it is done by a shelly 1, when i press it it turn it on for 0.5s and go back to off

#

I need that binary_sensor to estimate if my gate is open or not, atm with a timer.

#

(I got a sensor on the way but it'll take few weeks to arrive)

inner mesa
#

ok, that's easier

hollow plinth
#

I created the sensor, i'm building the automation now, what action should I use? Call service?

inner mesa
hollow plinth
#

Ohhh

inner mesa
#

the binary_sensor will turn on when the template becomes true, and turn off after some period of time that you specify after the template becomes false

hollow plinth
#

Like this? ```template:

  • binary_sensor:
    • name: "Portail"
      device_class: garage_door
      state: "{{ is_state('switch.shellyplus1_441793a3b6a8_switch_0', 'on') }}"
      delay_off: 45s```
inner mesa
#

yes, but you need to properly format the delay_off

#

I believe that just "45" is interpreted as seconds, or you can use the format that it shows in the docs

hollow plinth
#
  - binary_sensor:
      - name: "Portail"
        device_class: garage_door
        state: "{{ is_state('switch.shellyplus1_441793a3b6a8_switch_0', 'on') }}"
        delay_off:
          seconds: 45```
#

Ill try like this

#

Now i just have to make an automation to turn it on when I use the switch?

#

oh, maybe just add ".state."on my switch

#

Nope, it doenst work

thorny snow
inner mesa
#

you don't need an automation - that's all you need right htere

hollow plinth
#

Ah, no, what doenst work is the add of .state to get thet sensor triggered by my switch sorry

inner mesa
#

yes, don't do that

hollow plinth
#

But it doenst trun on when i use the switch

#

I see the switch turning on for 0.5 sec but it doenst affect the binary sensor

inner mesa
#

no idea. it works fine me

hollow plinth
#

:/

inner mesa
#

maybe you're using the wrong entity name

hollow plinth
#

Can it be too short 0.5s?

inner mesa
#

no

#

perhaps you didn't reload template entities or restart HA

hollow plinth
#

wait, it is working !

inner mesa
#
- binary_sensor:
  - name: "Portail"
    device_class: garage_door
    state: "{{ is_state('switch.fr_table_lamp', 'on') }}"
    delay_off:
      seconds: 10
#

ok

hollow plinth
#

I just triggered the button manually on dev tools and switched back off, now it is ok!

#

Thanks a lot for your help πŸ˜„

trail ginkgo
#

Air quality is a real issue where I am, so I've had a traffic light next to my balcony door for quite a while. Until now, I've used a source which is for the entire city. But as I've implemented notifications for AQI at the location of my mobile, I realised I can get AQI at an exact location too.

#

So I'd like to change the city-wide metric I use for my traffic light, with one that is exact for my location. I've set the lat/lon in my configuration.yaml.

#

How do I use those lat/lon values in a template?

inner mesa
#

They’re attributes in zone.home

trail ginkgo
#

Awesome, that worked! Thanks πŸ™‚

#

Now the most important job: what icon do we use for AQI metrics! πŸ˜„

inner mesa
#

mdi:dude-coughing

trail ginkgo
#

Is that an actual thing? haha

#

The WAQI integration uses a cloud icon

#

hm, nothing for pm, particle, particulate, dust

#

cloud it is!

#

Ah, the MDI icon set does have icons for it. But Home Assistant is using an old version of the MDI icons.

#

When creating an icon_template, and if I want to use an if-statement based on the value of the sensor itself, would you happen to know how to reference this value? I ran into the same problem yesterday and gave up. I'd like to have the AQI icon change depending on the value of the sensor.

#
icon_template: >- 
  {% if sensor_value > 100 %}
    mdi:cloud-alert
  {% elif sensor_value <101 AND sensor_value >50 %}
    mdi:cloud
  {% else %}
    mdi:cloud-outline
  {% endif %}
#

something like that

#

Oh, you cant actually set the icon for a REST sensor. Odd.

inner mesa
#

You may be able to choose an icon from the picker in the settings for the entity in the UI

#

If it provides a unique id

#

Or via customize otherwise

trail ginkgo
#

the latter indeed

#

no icon_template unfortunately

inner mesa
#

But it won’t be dynamic

trail ginkgo
#

yeah

#

oh well

inner mesa
#

You’d need to use a better card

trail ginkgo
#

it would have been cute, but i send notifications to the mobile app when the AQI is (un)safe ... that'll do

inner mesa
#

Or card mod

trail ginkgo
#

I've never messed with custom cards before. One day! πŸ™‚

inner mesa
#

Custom button card will change your life

trail ginkgo
#

Integrations breaking already annoys the hell out of me (less common these days, to be fair) .... I'd rather not add custom stuff to the list of things that require maintenance.

pine echo
#

Is there a way to get the last non-undefinted value for an attribute?

trail ginkgo
#

A non-undefined value. So, a defined value?

pastel moon
#

Hi, I'm getting a TypeError (NoneType) when this template renders. It works moments later. Can that be avoided somehow? https://www.codepile.net/pile/ZJXRvrGl I have tried testing if the variable is defined, but didn't help

inner mesa
#

Probably an availability template. Your sensors don’t seem to render consistently

pastel moon
#

They do render consistently. It's during the initial render after a restart this happens. Not really a big thing, but if I understand how (if possible) to avoid this, I'd get one less unnecessary error in the log πŸ™‚

fossil venture
fossil venture
pastel moon
pastel moon
#

as the as_datetime according to the 4th pin don't seem to have a default, I tried this (as_datetime(cTime)|default(0)), but was not it either...

pastel moon
#

ah well, whats a log if nothing in it? πŸ˜„ I'll just have to keep clearing it Thanks for the hints tho

fossil venture
#

You've still got the availability template option that Rob mentioned.

sonic nimbus
#

Hello, I have a warning Template warning: 'timestamp_custom' got invalid input 'None' when rendering template '{{as_timestamp(states.binary_sensor.bedroom_bed_motion_sensor_left.last_changed) | timestamp_custom('%A %d-%b-%y, %H:%M:%S')}}' but no default was specified. Currently 'timestamp_custom' will return 'None', however this template will fail to render in Home Assistant core 2022.1

#

for this sensor

#
  sensors:
    bedroom_bed_motion_sensor_left_last_occured:
      value_template: "{{as_timestamp(states.binary_sensor.bedroom_bed_motion_sensor_left.last_changed) | timestamp_custom('%A %d-%b-%y, %H:%M:%S')}}"```
#

So, what I need to change, to avoid this warning regarding None value

pastel moon
pastel moon
#

I traded one error for another using availability_template: TemplateError('UndefinedError: 'cTime' is undefined')

#

This is what I tried ```
period_of_day:
friendly_name: 'Period of day'
availability_template: >-
{% set cTime = now().strftime("%Y-%m-%d %H:%M:%S%z") %}
{%- if not cTime == 'undefined' %}
true
{%- endif %}

    value_template: >- ```
#

I must look for docs in the wrong place, did not know of this type before, but looks promising πŸ™‚

fossil venture
#

I doubt that it is now() that is undefined. But assuming it was, your template would be better constructed like this:```
availability_template: "{{ now().strftime("%Y-%m-%d %H:%M:%S%z") != 'undefined' }}"

#

As it will resolve to true or false. Your template has no else case for false.

young jacinth
#

hi i want to create a template binary_sensor that is on between 12-24 15:00:00 and 13-01 23:59:00

hexed wing
#

Cool πŸ™‚

pastel moon
young jacinth
#

got it πŸ™‚

{% set start = '12-24 15:00' %}
{% set end = '14-09 00:00' %}
{% set today = as_timestamp(now())|timestamp_custom('%m-%d %H:%M') %}
{{ today }}
{# dezember 12 + januar 1 = 13 ... #}
{{ today > start and today < end }}
pastel moon
#

Hm. Still get the error about TemplateError('TypeError: '<=' not supported between instances of 'NoneType' and 'datetime.datetime'') Just to be on the safe side I test all sensors for 'not undefined' which it passes... Would there be a better way to do this kind of comparison?

mighty ledge
#

specifically the left item

pastel moon
mighty ledge
#

as datetime returns None when it's an invalid date

pastel moon
#

Oh. @fossil venture suggested I create default values for the Β΄as_datetimeΒ΄ entries earlier, but I never found a way to do that...

mighty ledge
#

You're doing it

#

you're just not checking to see if it's valid

pastel moon
#

Well, I am better understanding the issue, but really thought my sensors were producing proper datetime output. Sounds like I need to debug them too then. Is there a way to make sure they only submit proper formatted datetime's?

mighty ledge
#

no, convert it and verify it's a datetime by checking it

#

use set to set it as a variable, then check it with if

pastel moon
#

Something like 'if var == datetime' ?

mighty ledge
#

If var is all you need

pastel moon
#

Great! Thanks, will dig into it πŸ™‚

#

Worked out nicely! Thanks @mighty ledge

median citrus
#

Hi all, it would be great if someone could help me out: I have a string containing a time e.g. 09:00:00 which i want to use as input for a time condition via a template. However if i put the string into my configuration i get an error that it does not fit the expected datetime format

#
- condition: time
  weekday:
  - mon
  before: input_datetime.motion_night_mode
  after: "{{ states('sensor.my_time_string')}}"```
#

i think i have to use strptime() but i dont fully understand how to create the right format

inner mesa
#

this doesn't look like an entity_id: my_time_string

median citrus
#

sorry my bad, its sensor.my_time_string since i use a template sensor

#

i corrected it in the example

inner mesa
#

it looks like that field doesn't support a template. If you want to use the time from a sensor, then this applies:

#

For the after and before options a time helper (input_datetime entity) or another sensor entity containing a timestamp with the β€œtimestamp” device class, can be used instead.

#

so it looks like you would need to make a template sensor with state: "{{ as_timestamp(today_at(states('sensor.my_time_string'))) }}"

#

then use that sensor entity_id

median citrus
#

ah ok i see, thanks, will test it!

median citrus
#

... but how do i call the sensor without a template in the yaml?

inner mesa
#

There are examples in the docs

median citrus
#

ah ok will check them out, thanks!

sonic nimbus
#

is it ok to put choose statement in another choose statement with value of the variable true/false?

#
    - conditions:
        - condition: template
          value_template: "{{ chromecast_device == 'media_player.system_chromecast' }}"
      sequence:
        - choose:
          - conditions:
              - condition: template
                value_template: "{{ no_snapshot_before }}"
          sequence:
            - service: scene.create
              data:
                scene_id: before
                snapshot_entities: "{{ speaker }}"```
#

and how to add a negation to check the variable is it false? like no_snapshot_before == 'false' ?

median citrus
fossil venture
#

Though that particular example you have shown could be simplified by just having one choose action with both conditions. It's only if you have a default (else) case or other set of conditions (elif) that you would need to nest them.

unique elm
#

When creating a sensor and setting up a value template can you make it that it only calculates a new value every minute, or even better, only when one of the input variables changes?

#

So for example if you want c = a x b and 'a' changes every 10 minutes and 'b' changes every 5 minutes can you get the calc to run once every 5 minutes?

inner mesa
#

It already reevaluates when an input changes

unique elm
#

I am actually seeing it calculate flat out, using 100% of my cpu and changing 'c' as fast as my screen can keep up

unique elm
#

Thank Rob, knew it would be documented somewhere

inner mesa
#

Then you have a wacky sensor

unique elm
#

actually the calculation is more like c = c + axb

inner mesa
#

If you have no entities or it can’t find them, it updates every minute

unique elm
#

where c is a dummy sensor

inner mesa
#

That will create an infinite loop

unique elm
#

it did

inner mesa
#

If you really want to do that, define specific triggers as per the docs

unique elm
#

I rewrote it as two sensors and that seems to be working, but my poor HA seems to be at 100% cpu, when it used to be at 1%

inner mesa
#

You’re updating an entity and that’s causing it to retrigger

unique elm
#

So if the template references say 5 other sensors, does it know to recalculate if any of the 5 change?

inner mesa
#

Yes

unique elm
#

awesome

#

I think it is my calculation. I have a value in watts for power, and integer for example 5437, and a value for voltage, also an int and usually 230 to 250. I want to calculate amps (as a rounded int) so I wrote

     Value_template: {{ (states(sensor.watts_incoming) | float / states(sensor.voltage) | float ) | int }}
#

I thought maybe doing the calc using floats first then changing to an int would be best?

unique lichen
mighty ledge
#

would be better if you just showed the result of the state topic

unique lichen
mighty ledge
#

or whatever the value of value_json.timestamp is

unique lichen
mighty ledge
#

that's already local time

#

so what's the problem

unique lichen
# mighty ledge that's already local time

When I view the state in HA, it's converted to UTC time. I can see other entities have attributes in local time. I do not have any other entities where the state is a timestamp to compare if this is the standard.

mighty ledge
unique lichen
#

In the Developer -> States window, the time shows up as 2021-12-17T13:56:06+00:00

mighty ledge
#

ok, so it's converted correctly and you're using the timestamp device_class. So when you put it into the frontend, it will show up correctly

#

all time items are set to utc under the hood, this is one of them

unique lichen
mighty ledge
#

lovelace will convert it to a relative time

#

that's the whole point of device_class: timestamp

unique lichen
mighty ledge
#

so it will show up as "X minutes ago"

mental violet
#

Hi I want to get the ratio from a sensor.state variable and the same variable but 24h earlier. How do I do that?

inner mesa
#

You’d need to store the earlier value in an input_number when it happens

#

You can’t easily go back and get historical data

mental violet
#

But if I wanna update that secondly that would be ressource expensive?!

#

doesnt the history graph does that allready? Can I extract the data from there?

inner mesa
#

You could use the SQL sensor

#

And no, you just pick a point in time, calculate the result based on the new value and last one, then update the last one

mental violet
#

so it would be fine:
"ratio = new_value/old_value"
and I update new_value AND old_value each second?

inner mesa
#

You want to update it every second based on the value 24h earlier every second?

mental violet
#

yes, so the variable is the most current ratio from the sensor based on 24h

inner mesa
#

I don’t know an easy way to do that. Maybe look at the statistics integration

mental violet
#

yes it is exactly what I need πŸ˜„ πŸ‘

bronze tide
#

Hi guys! Can one create sensors with attributes in YAML? I found https://www.home-assistant.io/integrations/template/#attribute_templates but this is a deprecated method as it seems.
Here is my setup atm: 2 rest sensors (text and number), another sensor who puts those sensors together for displaying.
Goal: one sensor with the number as value, the following as attributes: text rest sensor and the sensor for displaying
Is there any way to get this done? TIA!

barren jungle
thorny snow
#

Hi, i have made a timestamp that checks de next alarm. My goal is that it start 30 min for the next alarm. what i am doing wrong in my template ? 'service: input_datetime.set_datetime
target:
entity_id: input_datetime.alarm
data:
timestamp: '{{ as_timestamp(states(''sensor.petras10_volgende_alarm''), - 60 * 30) }}''

marble jackal
#

I'm trying to debug an automation which is not working properly. To debug I'v set some variables to see if the results are as I would expect.
This works fine in the template editor

timestamp: "{{ now() + timedelta(hours=3, minutes=30) }}"

But if I put in in my automation, I get Error: TypeError: 'str' object is not callable
(BTW I know this is not a timestamp, but for debugging purposes I left it as simple as possible. It gives no error if I only leave {{ now() }}

mighty ledge
marble jackal
vast juniper
#

guys, I'm trying to make a template that would state true when sun is above horizon, but not sure what I'm doing wrong.
{% if state_attr('sun.sun', 'above_horizon') %} true {% else %} false {% endif %}

glacial matrix
#

Morning All, this template is throwing a "KeyError:" Could you tell me where I have gone wrong please.

{%- for state in states.group.security -%}
            {%- if state.state == 'on' -%}
            {{ state.name }} status is {{ state.state }}.{{- '\n' -}}
            {%- endif -%}
            {%- else -%}
            Nothing is open
            {%- endfor -%}
glacial matrix
vast juniper
marble jackal
#

That is way overcomplicated @vast juniper
{{ is_state('sun.sun', 'above_horizon') }} gives the same result

marble jackal
#

Furthermore, you first check for the state, and then put the state in your template. If you already checked if the state is on, it does not make a lot of sense to use a template again

mighty ledge
mighty ledge
#

you can also filter the list down and make it phonetic

#
{% set items = expand('group.security') | selectattr('state','==','on') | map(attribute='name') | list %}
{% if items %}
  {{ items | join(" and ") if items | length <= 2 else items[:-1] | join(', ') ~ ', and ' ~ items[-1] }} {{ 'are' if items | length > 1 else 'is' }} open.
{% else %}
  Nothing is open.
{% endif %}
marble jackal
#

I guess you want something like this.

{% set switch_on = expand(state_attr('group.all_switches', 'entity_id')) | selectattr('state', 'eq', 'on') | list %}
{% set on_count = switch_on | count %}
{% if on_count > 0 %}
  {{ switch_on | map(attribute='attributes.friendly_name') | join(', ') }} {{ 'are' if on_count > 1 else 'is' }} on
{% else  %}
  Nothing is on
{% endif %}
mighty ledge
#

πŸ•Ί i win

marble jackal
#

😦

mighty ledge
#

slightly before you πŸ˜‰

#

lol, same code though

#

although I added an 'and' in there

marble jackal
#

I wanted to be sure I was right, so I tested with a group of my own πŸ™‚

mighty ledge
#

Oh I never test 🀣

marble jackal
#

You have a lot more experience in these templates I guess πŸ™‚

#

Is there any difference between length and count?

mighty ledge
#

It's python and I'm at year ~16 as a dev and year ~6 in HA

#

they are the same essentially

#

I'm sure there's some caveats to count

#

length is what I'm used to

marble jackal
#

Well, I moved into a new house in 2019 and started using HA for about 1,5 years now. At some point templates became "needed" and I learned a bit while doing πŸ™‚

mighty ledge
#

actually, it's an alias for length

#

so they are the same

#

Templates can take your setup from thousands of lines down to hundreds

#

I have 30 automations. All using templates. Without them, I would probably have upwards of 200 automations

#

templates + automations using parallel = less automations to manage

marble jackal
#

Yes, I try to do the same. If I need to do the same think for multiple similar entities (e.g. lights) I create one automation and template based on the trigger values

#

For example to decrease color_temp when brightness increases.

mighty ledge
#

yep

#

and utilize scripts too

#

you can have scripts that run parallel and automations that run restart

#

2 other tips

#

scripts when using script.turn_on do not wait until they are completed

#

scripts when using script.xyz wait until they complete

#

in action sections

#

it's useful to know the distinction

marble jackal
#

I know πŸ™‚ I always forget which one does what, but I know that particular difference πŸ™‚

glacial matrix
#

Thank you. is it possible to change open to detected if it is a motion sensor rather than a door sensor?

#

Would I need to create two groups and have the template from both groups to get:
Motion detected in "room"
Door / Window is/are open

mighty ledge
#

Personally, I would separate them or separate them in the template. Otherwise your sentence won't make sense

#

especially if this is for TTS

#

or text msg/notification

#

you can filter on the device_class

glacial matrix
#

How can I filter the above by device class?

mighty ledge
#

selectattr('attributes.device_class', '==', 'blah')

glacial matrix
#

thank you. Where can i find the arguements for chaning the params? i.e. i assume == is equal, if i wanted to replace that with or, not etc.

marble jackal
#

Check the pinned post to the jinja docs

glacial matrix
bronze tide
dreamy sinew
#

selectattr('attributes.device_class', 'in', ['door', 'window'])

glacial matrix
#

Great! Thank you.

solar field
#

Trying to figure out something with an automation template.

I got a Petkit feeder for my cat recently and someone's made a custom integration for it. I've got that set up and able to communicate with HA and I'd like to set up an automation when the feeder dispenses food to send me a push notification letting me know along with the amount of food that's been dispensed for the day.

When the "feeding" switch is toggled on it will dispense 1 serving of food, so my thought was that I could just use the switch as the trigger to send the notification. This worked while testing, but when the feeder kicks off on its own schedule and not via me telling it to via Home Assistant, I guess that switch never gets flipped and thus my notification never gets sent.

My next idea was to try and find a way to use the "feed count" going up as the trigger to send the notification but I haven't quite figured out how that would work yet. Am I able to see the value both before and after the food dispenses within the automation, or would I also need to create a separate time-based action to watch for that value and then check again after the scheduled feeding time passes?

#

Here are the things available to me in HA through the custom integration just for reference, and I'll throw the code for the automation below though it's not much