#templates-archived

1 messages · Page 144 of 1

solar field
#

I've been looking through the tempating docs but my brain is a bit fried so I'm waving a bit of a white flag for a while lol

dreamy sinew
#

feed count is an entity right?

median citrus
#

I'm struggeling with the parametrization of a time condition. I have a string with a time 08:00:00 that im parsing into a template sensor
"{{ as_timestamp(today_at(states('sensor.alarm_clock_we_end'))) }}"If i read the value of the template sensor i get 1640073600.0 which seems ok

However when i put this sensor into a time condition the automation does not work. I don't get an error but the condition always returns false... and i don't see any values in the trace. Anyone an idea on what I'm doing wrong? If i use input_datetime it woks flawless so the automation logic seems ok.

inner mesa
#

what condition?

median citrus
#
          weekday:
          - mon
          after: 00:00:01
          before: sensor.my_template_sensor
inner mesa
#

does it have a device_class: timestamp?

median citrus
#

if i check the values of sensor.my_template_sensor it only has 1640073600.0 as its state

#

i tried to define device_class: timestamp in the template but then HA was giving a lot of errors during template initialization

inner mesa
#

you'll need to fix those

median citrus
#

... but i dont know what I'm doing wrong...

#

but how do i define the device class?

inner mesa
#

there's an example further down the page

median citrus
#
        device_class: timestamp
        value_template: "{{ 
as_timestamp(today_at(states('sensor.alarm_clock_we_end'))) }}"`.```
#

like this?

inner mesa
#

should be

median citrus
#

hmm the moment i add device_class: timestamp to this one sensor i get a lot of errors in the log and the sensors disappear

#

hmm the error messages are related to other integrations, but still the sensors does not load after adding the device_class

#

for "{{ as_timestamp(today_at(states('sensor.alarm_clock_we'))) |timestamp_custom('%H:%M:%S')}}" i can define device_class: timestampbut for as_timestamp(today_at(states('sensor.alarm_clock_we'))) }}"
the same fails. but if i put the first one into the time condition I again end up with always false

inner mesa
#

looking through the docs, it says this:

#

timestamp: Datetime object or timestamp string (ISO 8601).

#

so I guess it's not actually a timestamp as an integer

median citrus
#

i don't understand 😢

inner mesa
#

you need a datetime or a string

#

and you have a string

#

just stop turning it into a timestamp

#

{{ today_at('06:00').isoformat() }}

#

do that

median citrus
#

i have three templates: sensors:

  1. the original string containing 08:00:00
  2. timestamp_custom wich also renders as 08:00:00
  3. the timestring wich reads 1640073600.0 as its state

neither works if i input this in the before:XXXXX section of the condition

#

if i manually enter a fixed value of an input_datetime it works

inner mesa
#

did you do what I suggested?

median citrus
#

I'm on it, give me a sec 😄

#

i created the sensor as you suggested and i can read its content as
2021-12-22T09:00:00+01:00

#

but if i put this sensor into the before field on my condition it again only returns false

#

and what i realy dont understand: if i check the step details: for conditions with fixed values and input_timedate i can see details of the check

after: input_datetime.motion_night_mode_arbeitszimmer
before: '23:59:59'``` ```Result:
after:
  __type: <class 'datetime.time'>
  isoformat: '23:00:00'
now_time:
  __type: <class 'datetime.time'>
  isoformat: '00:42:42.235567'
before:
  __type: <class 'datetime.time'>
  isoformat: '23:59:59'
result: false```
#

for conditions having the template sensor i only get

before: input_datetime.motion_night_mode_arbeitszimmer
result: false```
#

HOLY SHIT! it works, i forgot to define the deice_class on the new sensor

#

THANK YOU @inner mesa !!!

low blaze
#

I'm attempting to imitate a "breaker panel" on my lovelace dashboard.

#

I have made template switches, and they work great. I have made matching input_booleans that are tied to the template switch so that if the input_boolean is off, the turn on command is ignored. This accomplishes part 1.

#

However. Is there a simple way (without making a separate automation) to have the switch also turn off if the input_boolean is turned off?

#

This is my template switch: rm_air_con: friendly_name: "Air Conditioner" value_template: "{{ is_state('switch.rmaircon','on')}}" turn_on: service: switch.turn_on data_template: entity_id: > {% if is_state('input_boolean.rmaircon_breaker', 'on') %} switch.rmaircon {% else %} switch.null {% endif %} turn_off: service: switch.turn_off data: entity_id: switch.rmaircon

#

can I add something to that template switch to make it turn itself off if the input boolean is off?

heady crow
#

Hi, to convert some attributes from minutes to hours, do i need a template?

#

I have an entity for vaccum that shows its Brush usage, filter usage etc but its reading in minutes and i need to convert to hours

#

i think i need to make a sensor for each attribute first?

silent seal
#

Where do you need to see this? You could use a template in the markdown card in the front end rather than create sensors.

heady crow
#

i have a vaccuum card

#

shows the hours but looks like minutes, in my vac app they show as 84 hours, 236 hours and 56 hours

silent seal
#

(Or written such that it's calculating the times wrong.)

heady crow
#

Oh ok, I can check into that i guess, im a little bit of a noob

mighty ledge
silent seal
#

I have a problem this morning: My netatmo devices are unavailable which is a pain as I am using them as my sensor for my generic thermostats. What I would like to do is use a template to use that sensor, and if it's not available, fallback to getting all the sensors in the area and filtering them for availability/none and then averaging them out.
Currently I have this: https://paste.debian.net/1224418/. I'm hardcoding the sensors though, and wondering if I can/should dynamically get the other sensors? And/or is there a better way to do this?

mighty ledge
#

There's trade offs to dynamically getting a list of sensors

#

first and foremost, you need to understand how templates work

#

if you use just states in your template without a domain, i.e. states.xyz, the template is throttled to at most 1 update per minute

#

if you use states.sensor you have the same restriction

#

if you use states.anyotherdomain you're throttled to at most 1 update per second

#

so whenever you dynamically look for sensors, you're going to cause that template to update less frequently

#

unless you make an automation that creates a group

#

using a list of entities has no throttled updates

silent seal
#

Aha, that is really useful to know!

last basin
#

Hi, I'm trying to get a button to start a timer based off of the (minute) value of a slider in a card. The template i have is testing correct in the template test tool, but i'm getting error when pushing the button to start it . can someone advise please?

#
  - type: button
    tap_action:
      action: call-service
      service: timer.start
      service_data:
        duration: >-
          {% set t = states('input_number.heating_timer') | int %} {{
          '{:02d}:{:02d}:{:02d}'.format(t // 60, (t % 60) , (t % 60) // 60) }}
      target:
        entity_id: timer.heating_timer
    entity: timer.heating_timer
    name: Boost
    icon: mdi:radiator
#

error is
'''
Failed to call service timer/start. offset {% set t = states('input_number.heating_timer') | int %} {{ '{:02d}:{:02d}:{:02d}'.format(t // 60, (t % 60) , (t % 60) // 60) }} should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['duration']
'''

mighty ledge
#

Then in templates I use expand on the group

silent seal
mighty ledge
#

Specifically its in...

#

actually I don't use it

#

hahah

last basin
#

does this mean that templates don't work in service requests?

mighty ledge
#
  - platform: time
    at: '00:00:00'
  - platform: homeassistant
    event: start
  - platform: event
    event_type: call_service
    event_data:
      domain: template
      service: reload
#

with group.set

#

in an automation

#

The closest I have are counters for domains that behave the same way

#

in your case, you'd be making an automation

mighty ledge
#

Well you can, just only in the markdown card.

#

tap actions do not accept templates

silent seal
mighty ledge
#

I'd just make a temperature sensor list

#

Also, change the trigger to reload on groups

#
  - platform: time
    at: '00:00:00'
  - platform: homeassistant
    event: start
  - platform: event
    event_type: call_service
    event_data:
      domain: group
      service: reload
#

and the service woudl be something like

#
- service: group.set
  data:
    object_id: my_temperature_sensors
    entities: >
       {{ states.sensor | selectattr('name', 'search', 'temperature') | map(attribute='entity_id') | list }}
last basin
silent seal
mighty ledge
silent seal
#

Excellent, and I can easily filter out window sensors with this too (those tend to be a lot colder than the other sensors so skew the average)

silent seal
#

I use scripts and/or input booleans/numbers/selects for this sort of thing. Then I set the input_XXX to whatever which triggers an automation.

mighty ledge
#

then call it in lovelace...

  - type: button
    tap_action:
      action: call-service
      service: script.start_timer
      service_data:
        timer: timer.heating_timer
        number: input_number.heating_timer
    entity: timer.heating_timer
    name: Boost
    icon: mdi:radiator
silent seal
#

So some of my buttons are like this:

type: button
tap_action:
  action: call-service
  service: input_select.select_next
  service_data: {}
  target:
    entity_id: input_select.electric_blanket_time_off_options
show_icon: true
show_state: true
entity: input_select.electric_blanket_time_off_options
show_name: false

And then an automation watches the input (select) in this case and adjusts things to that.

last basin
mighty ledge
#

ah, let me editit

last basin
#

no, its fine. sorry i didnt mean for you to do more work. . i just didnt know if using the other terms would be replaced from the calling it in lovelace or not.

mighty ledge
#

there's a million different ways to do what you want

#

I tend to script everything

#

because I like buttons and don't like dropdowns

#

scripts are easy to call from buttons, but you have to put your logic in the scripts

#

case in point, @silent seal does something different than i

silent seal
#

In the example above, the input select has None, 5, 10, 15, 20 as the options, if it's set to anything other than None then the automation sets input_datetime.electric_blanket_off to {{ now() + timedelta(minutes=(states('input_select.electric_blanket_time_off_options')|int)) }}, which works perfectly for me. But that's because I created it for my use case. Elsewhere I might do what Petro does and call a script.

low blaze
silent seal
#

What is the problem you're trying to solve? This sounds complex, and there might be an easier way.

low blaze
silent seal
#

It might be better to use events for those.

low blaze
#

I also want a “panel” where I have a “toggle” that prevents switch.rmaicon from being functional, and when it’s turned off i would like it also to turn off

silent seal
#

What changes that toggle?

low blaze
#

Like walking over to a breaker panel and flipping a breaker to off. I want to hard kill the switch until it’s re enabled.

low blaze
silent seal
#

You only change that manually?

low blaze
#

When I’m servicing something like my fish tank need to turn off the pump and make sure nodered can’t turn it back on when my face is in the tank

silent seal
#

That makes sense to have as an input boolean that you use as a validation check then.

low blaze
#

And then when I’m done in the tank I will turn back on the toggle

#

I also will take advantage of the template switch if equipment is being replaced

#

If I change pumps, all of the instructions can be fixed by changing just the entity Id referenced in the template switch with one adjustment and no reason to change nodered flows

#

But like a breaker, flipping the validation check should also turn it off. But flipping validation switch back to on, should not turn the template switch to on, only allow it to be functional going forward

#

(It’s ok if it were to resume the previous state but that doesn’t matter, my flows makes sure the pump is always on if it’s off when it shouldn’t be)

#

Just not sure how to make the template switch become off and not just(only) “incapable of sending a turn_on” when I flip the input Boolean

#

If I’m about to work in the tank turning off input Boolean should turn off the pump as well if it’s on, but I don’t want to write flows to do this, it will take hours

#

(I have about 40 diff entities)

silent seal
#

Well, automations are likely easier for this sort of thing to be honest.

mighty ledge
#

with everything you've said, I'm not sure where 'turning off the boolean ' comes into play if you're manually turning it on. Wouldn't you manually turn it off too?

low blaze
#

Yes but it (the template and actual switch) might be on currently

#

It should shut off when the input Boolean is disabled too

low blaze
silent seal
#

You're not disabling it, you're setting it to true or false

low blaze
#

Correct

#

But I would like to be disabling it

#

But I am currently just disabling the turn_on service

silent seal
#

You can't. You need to check after the trigger is received if it should be run

#

So:

  • trigger
  • can I do this?
  • Yes: do the thing
  • No: Don't do the thing.
mighty ledge
#

Well you technically can disablei t

silent seal
#

With an automation you'd make it a condition that your override has to be on.

mighty ledge
#

by making it unavailable

low blaze
#

Correct but also trigger received, was the room already in an on state? Also Turn the state to off

#

Currently I use an ovveride input Boolean but a single one for the entire room

silent seal
#

But before you do that, check if it should be running, and if not, just end.

low blaze
#

So when I flip it to ovveride none of the flows can trigger - but I don’t want to make new overrides for every switch and also add specific overrides for each flow use if I don’t have to

#

And this also wouldn’t add the turning off if on either

silent seal
#

How are you triggering the flows again?

low blaze
#

Different sensor values, temp goes above this threshold, etc

#

real world example.

#

If water temp goes above 67, turn on switch.pump1

silent seal
#

So that's reading directly from a device?

low blaze
#

If water level goes below “ok”, turn off switch.pump1

#

If water level is above “low” (ok or optimal) , turn on switch.pump1, things like this

#

State:event flows. <those are my flow examples>

#

So it seems the template switch can’t react to the status change of the input Boolean unless it’s being done by a secondary automation

#

(Yes react would be an automation, but it’s more like state being forced to off due to the input Boolean being false that i would prefer)

#

That’s why I thought at the top of the template switch I could set (override) it’s value based on the input Boolean if false

#

(The disabling of the turn on service works great, by dead ending it)

silent seal
#

You might have better luck asking in #node-red-archived, but I think your first action in any of those flows ought to be to check if your override boolean should prevent the flow from running.

low blaze
#

Yes I do that

#

But that’s not the part I’m working on, that is essentially solved

#

It’s the turning off or forcing the status to be off (of the template switch), when the Boolean is false

#

But making 40 flows just to support this function is a lot of extra work that I would hope the template can accomplish on its own

mighty ledge
low blaze
#

Correct - how can I accurately do that, my attempts haven’t worked

mighty ledge
#

just add it as part of the logic, but only you'll know the logic

low blaze
#

I assume right after >- and before the defining of the turn_on service, I can use an If statement

mighty ledge
#

yes, add it to the template

low blaze
#

Let me show you my attempts

mighty ledge
#

do you want the switch to be on when both the input boolean and source switch are on?

#

and off otherwise?

silent barnBOT
mighty ledge
#

value_template resolves to on

#

or true

#

for it to be on

#

so you're telling it to be on never

#

youre trying to tell it when to be off, you need to tell it when to be on

low blaze
#

My template switch does not tell the real switch to be or become on

#

it only prevents the service turn_on from being functional or is off due to the boolean being false

mighty ledge
#

your previous example showed you using a switch.aircon something or other

#

if the state of your switch is identical to the the state of the input boolean, then just grab the state and output that.

#

"{{ states('input_boolean.xyz') }}"

#

you're over complicating it

low blaze
#

well i dont want my boolean being on to effect the template switch's status

#

only the template switch's turn_on ability

mighty ledge
#

you just said you did

low blaze
#

sorry i didn't meant o confuse

mighty ledge
#

what do you want the state of the switch to be

low blaze
#

Let me try to make it a simpler explanation, sorry

#

water pumps are a better example.

mighty ledge
#

if you're just trying to disable all functionality to a switch, then all you need to do is add a condition to the turn_on/turn_off services

low blaze
#

I'm about to go into my tank. I don't know if the pump is on or off (that's a decision the tank makes all day long for different reasons). I want to flip the boolean to off, and when I do that - the pump should both not be able to be turn on, and also become off, if on.

#

So real switch.pump

#

template switch.thisisthetemplateswitch_pump

#

and boolean.thepump are the 3 entities

#

all day long, different flows send turn_on service calls to template switch.

#

template switch does its normal job unless I flip the boolean to false.

mighty ledge
#
- platform: template
    switches:
      wrapped_pump:
        value_template: "{{ states('switch.pump') }}"
        turn_on:
        - condition: state
          entity_id: input_boolean.enabler
          state: 'on'
        - service: switch.turn_on
          target:
            entity_id: switch.pump
        turn_off:
        - condition: state
          entity_id: input_boolean.enabler
          state: 'on'
        - service: switch.turn_off
          target:
            entity_id: switch.pump
low blaze
#

yes that is what i have works great

#

just that turning boolean to false does not change switch.pump to be off

#

(also). it does and I want it to correctly do what you put there

#

just need the additional part

#

oh

#

I see

#

you did put it ther

#

its the condition line

#

thank you let me try that

mighty ledge
#

that won't turn it off though when it turns off

low blaze
#

wait sorry I'm confused

mighty ledge
#

that's a separate automation

#

always

last basin
low blaze
#

ugh I am trying to avoid a separate automation

#

because it will be a lot of them

mighty ledge
low blaze
#

is the condition use better than the if and dead end of the entities way I did it?

mighty ledge
#

it's a reaction

last basin
mighty ledge
#

either that or you remove the boolean and replace it with a template switch

low blaze
#

ah ok. I think I understand. I can't both allow the switch to be "toggle/used" to chang it's own state - and also tell it what state (off sometimes) to be

last basin
#

do they take different formats?

mighty ledge
#

no, script is the location it goes in configuration.yaml

low blaze
#

If I remove the boolean and replace it with a template switch, would I lose he validation or no?

mighty ledge
#

if you're using the UI, it's not needed

low blaze
#

so I would have 1 switch, and 2 template switches

#

that's fine, even preffered - less helper creation

mighty ledge
#

you'll still need the boolean to store the state of the template switch, you'll just use the template switch as the boolean instead and have it linked to the boolean

low blaze
#

so 4 entities

#

1 switch, 2 template switches and 1 boolean

mighty ledge
#
- platform: template
  switches:
    enabler:
      value_template: "{{ states('input_boolean.enabler') }}"
      turn_on:
      - service: input_boolean.turn_on
        target:
          entity_id: input_boolean.enabler
      - service: switch.turn_off
        target:
          entity_id: switch.pump
      turn_off:
      - service: input_boolean.turn_off
        target:
          entity_id: input_boolean.enabler
low blaze
#

ah and the second template switch will turn off the 1st AND change the boolean

#

GREAT IDEA

mighty ledge
#

ih ave lgoic reversed

#

there, edited

#

but you can turn the pump back on if you want in the turn off of the enabler

#

Personally, I'd create a single automation using templates that does all of that without the wrapper for each switch

low blaze
#

I don't need to turn the pump on when I re enable

#

Just turn off if on when I disable

#

one of my pumps might be off when i disable it, I don't want to turn it on when i Re enable

mighty ledge
#

if you name your switch pumps and enablers the same

#

1 automation can do everything without the need for a new wrapped switch

low blaze
#

yes but I'd need to make 40 automations

mighty ledge
#

no..

low blaze
#

and a new one each time i add a switch/device

#

(I have at least 40 of these "pumps")

#

(they are not all pumps)

#

I'm ok with creating 1 boolean and 2 helper template switches for each real switch, just would like to do that rather than make 1 boolean, 1 helper template switch AND a flow/automation for each real switch

#

as template switches are easier to make than an automation

mighty ledge
#
- alias: My turn offer
  mode: parallel
  trigger:
  - platform: state
    entity_id:
    - list
    - input_booleans
    to: "on"
  action:
  - service: switch.turn_off
    target:
      entity_id: switch.{{ trigger.entity_id.split('_')[-1] }}
#

that will do everything if you name your input booleans

#

input_boolean.enable_pump

#

if your switch is named

#

switch.pump

low blaze
#

so i'm on your page. That single automation will do this function for all booleans/template switch combinations

#

🙂

mighty ledge
#

this why node red is bad IMO. It takes away your ability to think in bulk and forces you to think like '1 automation per entity`

low blaze
#

agreed, thats why i came here because it was clear that node red was not the efficient way to accomplish this function even though an automation was the correct logic for doing it

mighty ledge
low blaze
#

(I haven't made any of the 40 I need, so a proper naming scheme was intended anyway)

mighty ledge
#

example: You bought a pump for your living room... input_boolean.enable_livingroompump and switch.livingroompump

#

if you want to use _ in the names of the entities, then you might want to use something else as the separator

#

e.g.

#
- alias: My turn offer
  mode: parallel
  trigger:
  - platform: state
    entity_id:
    - list
    - input_booleans
    to: "on"
  action:
  - service: switch.turn_off
    target:
      entity_id: switch.{{ trigger.entity_id.split('enable_')[-1] }}
low blaze
#

I only used _ in the name of the entity so that I could differntiate between the template switch and the actual switch easily when making flows

#

this automation doesn't elminate the use of the template switches, only assists them right

mighty ledge
#

it removes the need for the second template switch

low blaze
#

got it yes.

mighty ledge
#

so, i'd use the one I just posted

low blaze
#

I'm reading it to see if I understand how it works (I understand what it does)

mighty ledge
#

then name everything input_boolean.enable_x_y_z with switch.x_y_z

#

then you can use _ in your entity_ids and it'll work regardless of the number of _ you use

low blaze
#

awesome

#

so triggered by a state change of any of these input booleans, in this "list" - turn off matching switch

#

list is defined as input booleans that contain 'enable_'

#

and switch to turn off (entity) is defined by the name of the boolean

mighty ledge
#

Yeah just list out every input boolean

low blaze
#

oh in this automation? I add them

#

and then come back to them each time I make one and add it? I thought above you meant it will be dynamic

mighty ledge
#

You only have to list the booleans, the switch is dynamically chosen based on the input booleans name

low blaze
#

got it

#

can you show me what the list would look like with 2 on it

#

oh

#
  • list
mighty ledge
#

Yep

low blaze
#
  • input_booleans
#

would be

#
  • input_boolean.x_y_z1
#
  • input_boolean.x_y_z2
#

and so on, not the word "list"

mighty ledge
#

Yes but they need to be named input_boolean.enable_x_y_z

#

For the automation to work

#

You can name them the same too if you want

#

But the automation changes

low blaze
#

so ```- alias: My turn offer
mode: parallel
trigger:

  • platform: state
    entity_id:
    • input_boolean.enable_t1_pump1
    • input_boolean.enable_t1_airconditioner2
    • input_boolean.enable_t2_pump3
      to: "on"
      action:
  • service: switch.turn_off
    target:
    entity_id: switch.{{ trigger.entity_id.split('enable_')[-1] }}```
mighty ledge
#

No

low blaze
#

sorry

#

I left out the enable

#

the entire piece you meant?

#

fixed

mighty ledge
#

Yes but you need to understand that the enabled needs to be in the entity id of the input boolean

low blaze
#

and switch.t1pump1 would exist (real switch) and switch.t1_pump1 is the template switch

mighty ledge
#

So when you create the helper, that needs to be included

#

if you think that's too much, you can name them exactly the same

#

but the automation will change

low blaze
mighty ledge
#

if you want to not deal with naming them 'enable_'

low blaze
#

naming them enable is fine, because it also helps identify the function of these booleans from a bunch of others

mighty ledge
#
- alias: My turn offer
  mode: parallel
  trigger:
  - platform: state
    entity_id:
    - input_boolean.t1_pump1
    - input_boolean.t1_airconditioner2
    - input_boolean.t2_pump3
    to: "on"
  action:
  - service: switch.turn_off
    target:
      entity_id: switch.{{ trigger.entity_id.split('.')[-1] }}
low blaze
#

I have other uses for booleans, this makes them easier to filter for when working in the entities list, etc

mighty ledge
#

as long as the switches are named
- switch.t1_pump1
- switch.t1_airconditioner2
- switch.t2_pump3

low blaze
#

yup

mighty ledge
#

notice how the template is changing

#

don't confuse that

low blaze
#

yes I see

#

curious tho

#

why does it need to split anyway? wouldn't splitting after the . be just as functional if the word enable is used in the name or not?

#

or does the re-use of "enable_" throw off the template unless it is accomidated for

mighty ledge
#

Enable is in the object id for the inputboolean it’s not in the switch

#

Hence why it’s removed

low blaze
#

oh

#

got it

#

perfect I follow

#

the switch's identity is being generated, so it has to drop the "enable_"

#

to be accurate

#

when enable_ isn't used as a prefix, there is nothing to drop

#

(the switch being instructed, not the creation of the identity)

#

Thanks I think this is perfect

#

when adding a switch later on, I'll

#
  1. let HA have a new switch as usual
#
  1. Make an input boolean and template switch
#
  1. update the name of the input_boolean into this single automation
mighty ledge
#

yep

low blaze
#
  1. add the input_boolean to my "breaker panel"
#

in lovelace

#

This is so helpful @mighty ledge thank you very much

#

is the way you did the template switch above (using condition) instead of my method (using an if) more efficient?

#

this is how I did it before I was trying to shoe-horn an automation into a template switch.

#
        friendly_name: "Air Conditioner"
        value_template: "{{ is_state('switch.rmaircon','on')}}"
        turn_on:
          service: switch.turn_on
          data_template:
            entity_id: >
              {% if is_state('input_boolean.rmaircon_breaker', 'on') %}
                switch.rmaircon
              {% else %}
                switch.null
              {% endif %}
        turn_off:
          service: switch.turn_off
          data:
            entity_id: switch.rmaircon```
mighty ledge
#

like what I had above

low blaze
#

(For purpose of learning) can you explain why 1 is better than the other?

#

Is it just less legwork for the template? (Or is it that it allows for the template switch to automatically not work until the Boolean is created)

mighty ledge
#

well, you don't need a dummy switch

#

which will error if the dummy switch doesn't exist

low blaze
#

I thought I wasn’t confused

#

But now not sure

#

Both ways there are 3 entities

#

1 real switch, 1 template switch

#

And 1 Boolean

#

Or by dummy you mean the entity.null

#

Yea

#

Technically that dummy/null switch is a failure of some kind, where the conditional is more accurate of a job

#

No need to make a dead end when you can just not drive to the place you are avoiding

mighty ledge
low blaze
#

Cool. We are on the same page thanks 😀

thorny snow
#

how can I convert a hex value e.g. 0x44175704 to a float (should be 605.359619141) inside template (value | float) does not work

mighty ledge
thorny snow
#

float nicht int

mighty ledge
#

you can't then

thorny snow
#

da kommt 1142380292 raus

mighty ledge
#

i can't read non-english

thorny snow
#

sorry if I do your conversion its the wrong result

mighty ledge
#

you can only convert hex to ints

#

I suggest using a python script and use the proper conversion methods

#

all the functions/methods you need to convert an int to a float don't exist in templating

thorny snow
#

ok thnaks

#

thanks

silent barnBOT
median citrus
#

I (again) have a issue with the parametrization of an automation. i use an identical template in both a trigger and a condition in an action to parameterize the time. For the trigger it works but for the condition i get an error, why is that?

silent seal
valid mist
silent seal
valid mist
#

ok

mighty ledge
mighty ledge
thorny snow
#

does anyone know whether it is possible to dynamically pick a scene based off of (for instance) a template sensor which outputs the name of the scene within a regular automation?
Or is this more a script thing?

#
- service: scene.turn_on
  target: 
    entity_id: {{ states('sensor.day_and_night_lights_office1') }}
#

for example like so, where the sensor returns a string with the name of the scene I want it to use

#

I feel this might be a bit too complicated for an automation to do but I can't really find any information

valid mist
inner mesa
#

that's a fine way to do it as long as you surround your template in quotes

thorny snow
#

ah. of course...

inner mesa
#

as long as your sensor is something like scene.xxxx

thorny snow
#

the sensor currently outputs the string scene.gaming_room_low_white

#

it depends on the time, which is why I wanted to do it with a template sensor and not with another set of nested choose levels

#

it's already getting hairy

valid mist
#

@mighty ledge just looking for a way that ha knows what echo to use in which room that a person is in

thorny snow
#

lessee

inner mesa
#

that's fine, templates are great

thorny snow
#

yep that did it 🙂

valid mist
#

if that is possible

thorny snow
#

awesome, thank you!

mighty ledge
valid mist
#

yep i have 9 of them

thorny snow
#

I have an automation that is giving me issues: https://pastebin.com/h0GEuzgs It usually fires and notifies me fine but in the logs it's showing: Template warning: 'float' got invalid input 'unknown' when rendering template '{% if states.sensor.wrens_bedroom_temperature.state | float < 21 %} true {% endif %}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1

dreamy sinew
#

probably a red herring to the actual issue but something you should still address

median citrus
median citrus
#

selecting an ID for a trigger is a concept i was not familiar with but its super handy!

mighty ledge
median citrus
#

😉

mighty ledge
#

Well it’s the truth

#

There’s no technical reason it can’t be added

median citrus
#

ok i was expecting a more technical reason which was was not aware of 😄

#

your proposal works beautifully, thanks for thelp!

mighty ledge
#

Np

mint whale
#

Is the relative_time function broken at the moment when combined with device_class: timestamp in a template? it just seems to show as unknown in the frontend, but works correctly in the template editor. I'm not sure if I am interpreting this issue report correctly: https://github.com/home-assistant/core/issues/61035

manic epoch
#

Hi all. I'm working with generic thermostat. I understood that by setting it up (mine is nearly identical to the example in the documentation) that I would have a climate entity be made available, but when I add the thermostat card it does not see any climate entities as being available. Did I miss a step?

silent seal
#

Did you reload climate integrations or restart?

warped hornet
#

Hi! I

silent barnBOT
warped hornet
#

I've tried with trigger.json.values[0].value and trigger.json.values.0.value which does not work

template:
  - trigger:
      - platform: webhook
        webhook_id: YULL90-data
    sensor:
      - name: YULL90 Data
        state: "{{ trigger.json }}" # <- works
      - name: YULL90 Temperature
        state: "{{ trigger.json.values.2.value }}" # <- does not work
        unit_of_measurement: °C
      - name: YULL90 Humidity
        state: "{{ trigger.json.values[3].value }}" # <- does not work
        unit_of_measurement: "%"
manic epoch
#

@silent seal restarted

fossil venture
silent barnBOT
#

@warped hornet Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

Please take the time now to review all of the rules and references in #rules.

warped hornet
#

Ah nice, I'll try that, thanks

dreamy sinew
#

don't edit your message to circumvent the bot

warped hornet
#

Sorry, didn't mean to cicumvent it

warped hornet
warped hornet
#

Ah, it is same case for plural of value.. in the array key - now it works. Thanks!

deft quartz
#

So, i want to change a person's picture via template, is that not possible (anymore) ?

marble jackal
mighty ledge
#

Did not know that

marble jackal
#

Never too old to learn 🙂

mighty ledge
#

speak for yourself 🤣

mighty ledge
#

Unless you used CustomUI

deft quartz
#

i though you could through customize

mighty ledge
#

If you stumbled upon forum posts claiming you can, they are using CustomUI or they are wrong. CustomUI was widely used at one point before it was abandoned, so I would assume that you're just stumbling upon CustomUI posts.

deft quartz
#

that might be it

#

well i can try to make a template sensor for it though

#

and use custom icons instead of a picture

mighty ledge
#

you just can't template in the customize section. So if you're going to create a template sensor to template the icon, you can jus ttemplate the picture instead.

deft quartz
#

yeah that was what i was thinking

umbral pond
#

When using the time trigger in an automation , is there a way to have the entity_id that did the time trigger? I tried accessing {{ trigger.entity_id }} but it didn't seem to do the trick

neon dove
#

Are template entities pushed onto the HASS homekit bridge?

mighty ledge
mighty ledge
buoyant pine
umbral pond
umbral pond
#

I think I understand ... there goes my hope of making a unified automation to control both the start time and end time of my boiler within the same piece of code

#

I'll have to write a second one

mighty ledge
#

Then condition off the trigger id

umbral pond
#

I'll look into it! Thanks!

stuck remnant
#
template:
  - binary_sensor:
      - name: "Outside cold"
        state: >
          {{ state_attr('weather.home','temperature') < 11 }}
        delay_on:
          hours: 24
        delay_off: 
          hours: 24
dreamy sinew
#

you're comparing a string to a number

stuck remnant
#

I need this switch to only trigger after the temp stayed below 11 for 24 straight hours

#

but I suspect it just adds a delay for when the temp dips below 11

#

like it dipped for just 1 hour and now my switch triggered after 24 h

dreamy sinew
#

probably better to use 2 automation and 2 input bools

stuck remnant
#

ok but

#

about the delay

#

how does it work

#

does it just delay

#

or does it need the temp to stay below 11 for 24 h

dreamy sinew
#

1 automation to turn on the bool when it goes below 11. another to turn it back off when it goes above.
a third automation to turn on a 2nd bool when the first bool is on for 24h

inner mesa
dreamy sinew
#

could simplify to a template sensor without the delay and then automation + bool for "cold"

#

yeah, i forgot that attributes can be other things

stuck remnant
#

but that way the switch display won't be relevant, I'll sww it turning on and off whenever the temp just dips below

dreamy sinew
#

then don't display it

stuck remnant
#

lol

dreamy sinew
#

just display the input bool that gets toggled by automation

stuck remnant
#

hmm, could work

#

but will it toggle after the temp stayed below 11 for 24 whole hours?

#

or just trigger after a delay of 24 hours after the temp dipped

dreamy sinew
#

you would trigger off that binary sensor going:

to: "on"
for: "24:00:00"
#

if it turns off the trigger resets

stuck remnant
#

delay_on time (Optional)

The amount of time (ie 0:00:05) the template state must be met before this sensor will switch to on. This can also be a template.

#

I remember reading this before asking

#

I found it ambiguous, otherwise I wouldn't have

#

in my mind, it makes sense, which is why I wrote the template like that

#

but maybe I got it wrong

#

right now my sensor is off even though it's -5 outside

#

24 hours ago, the temp went above 11 for like one hour

#

so there, that's why I'm asking, because it ties in with my second explanation

silent barnBOT
buoyant pine
#

the problem is all states are stored as strings. try

"{{ states('sensor.pv_current_quantiles_5m').split(',')[0] }}
#

@gritty stratus

#

oh that will have the brackets still. ew

gritty stratus
#

So quantiles stores as strings internally? That feels pretty icky to me. I'm wondering if there is a percentile-like thing that doesn't do that?

The problem on trying to solve is trying to figure out what my solar power is generating x% of the time so I can charge my EV at a sensible rate, but I found mean had the opposite problem

buoyant pine
#

home assistant stores all entity states as strings

#

out of curiosity, what version of HA are you on?

gritty stratus
#

Oh, even numbers? Heh.

buoyant pine
#

i'll say it again

#

home assistant stores all entity states as strings 😛

gritty stratus
#

2021.12.2-full

buoyant pine
#

got it. HA was changed about a year (?) ago where templates would output proper data types, so i was wondering if maybe you were on an older version. but... you're not

young jacinth
#

hey i get the following error with this template sensor

  template:
    - binary_sensor:
        - name: "People Home"
          unique_id: "4d3004f9e7514ecb947715b5de3356c5"
          state: >
            {{ is_state('person.sam', 'home')
              or is_state('person.melli', 'home') }}

2021-12-24 12:34:29 ERROR (SyncWorker_8) [homeassistant.util.yaml.loader] while parsing a block mapping
in "/config/packages/presence.yaml", line 106, column 5
expected <block end>, but found '-'
in "/config/packages/presence.yaml", line 110, column 5

#

i dont get whats wrong here

fossil venture
#

template: should be hard against the margin of configuration.yaml and it should only exist once.

young jacinth
#

i use oackages here

#

in this package template only exist once

#

this is the package @fossil venture

mighty ledge
young jacinth
#

this is super weird
i converted from the legacy template format to the new one
the old one worked without problems

mighty ledge
nocturne chasm
#

I keep getting the no default error on this template

{% if states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') %}
   {{ (states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') | int / 3600 ) | round(0) | int | default(0) }} 
{% elif states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') == 0 %}
    0 Hours (0%)
{% else %}
    starting.....
{% endif %}

how can I fix it?

silent seal
#

Try using is_state instead.

{% if is_state('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left', 'unavailable') %}
    starting…
{% elif is_state('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left', '0') %}
       0 Hours (0%)
{% else %}
    {{ ((states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') | int) / 3600 ) | round(0) | int | default(0) }}
{% endif %}
#

Also, you needed to wrap the casting the states to an int in brackets most likely.

nocturne chasm
#

I think the error is when the state is unavailable though and something to do with not being an int

silent seal
#

I’ve added that check. A warning: Some of those quotes are not straight so that will 100% cause an error, but I’m on my iPad and Discord got picky

silent seal
olive rover
#

My embarrassing first attempt at doing an IF ELSE statement in an automation seems to be failing with Message malformed: Service (code line 12) does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']
https://pastebin.com/GCXG3L4t

#

I find the templating docs a little hard to see through 😦

#

What's the thing I'm misunderstanding?

marble jackal
#

@nocturne chasm
Some additions/comments:

  • the last statement now only gives a number, shouldn't it inlcude hours?
  • why treat 0 differently? The result of the formula would be 0 anyway.
    I would probably do it like this:
{% if states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') | is_number %}
    {% set dirty_left = ((states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') | int) / 3600 ) | round(0) | int | default(0) %}
    {{ dirty_left ~ (' hour' if dirty_left == 1 else ' hours') }}
{% else %}
    starting.....
{% endif %}
silent seal
#

I think your intent is off on the first if, are you using spaces or tabs?

marble jackal
#

@olive rover your template returns switch.turn_off(downstairs_lights) or switch.turn_on(downstairs_lights) which is not a valid service

#

you should only return switch.turn_off or switch.turn_on and put the light you want to turn off/on under target:

olive rover
#

but it yields the same error message

#

homeassistant generic turn off / on is the one I actually want. Sorry about the typo.

marble jackal
olive rover
#

They are actually switches and not lights. Does that matter?

#

(I call them lights as they are physical lights attached to a power outlet switch to control them)

#

Maybe it would be important for me to describe what I want to achieve.

marble jackal
#

there is also a homeassistant.toggle

olive rover
#

I have a physical button I want to use as an on/off switch for this group of outlets. It is possible that one or more of the outlets is manually turned off. This means that a simple toggle does not achieve turning them all on/off when the button is pressed.

#

So - I want to see what the majority state of the lights are, then do the opposite

#

If 2 of 3 lights are on, button press turns them all off.

silent seal
marble jackal
#

ah okay

#

I understand the problem now, in that case you do need a template, because both the group or light.group will be on when any light is on

olive rover
#

Always useful to describe the desired outcome 😄 Sorry, I should have formulated my issue better.

honest slate
#

How to format simple template in my notification , e.g My room temperature is (entity value) ?

marble jackal
marble jackal
olive rover
honest slate
#

@marble jackal Thanks . As a noob i typed state instead of states

honest slate
#

Other question is why on my frontend weather state is in my own language , but on messeges send to tv it's in English

marble jackal
#

That's becasase the frontend automatically translates it

cobalt umbra
#
rest:
  - resource: http://192.168.xxx.xxx/meas.xml
    binary_sensor:
      - value_template: "{{ value_json.meas.O1.HN }}"
        # state: "{{ value_json.meas.O1.HN }}"
        device_class: running

I'm trying to re-do my sensors in the non-deprecated way, but with this HA complains that value_json is not found
where am I going wrong?

mighty ledge
#

It’s also not valid on the sensor level

cobalt umbra
#

Thanks
fixed that
but I still get an erro in the logs:

Logger: homeassistant.helpers.template
Source: helpers/template.py:1791
First occurred: 16:59:45 (135 occurrences)
Last logged: 17:33:15

Template variable error: 'value_json' is undefined when rendering '{{ value_json.meas.O1.HN }}'
mighty ledge
#

Verify that your resource is correct

acoustic arch
#

all info is in the pastebin

#

is it syntax? i cannot find whats wrong

inner mesa
#

Is it during startup? The time of the error and the Tasmota time stamps are quite different

acoustic arch
#

no its all the time. got 100+ msg now. Timings is different because i just copy pasted some stuff

#

my automation is working fine using the ON an OFF provided by the sensor

acoustic arch
#

got it: Tasmota uses RESULT for more chatter: stat/v1-badkamer-shelly1L/RESULT = {"POWER":"ON"}

#

which cannot be parsed ofcourse

nocturne chasm
#

I prob should have also posted the rest of the template, it was just a percentage wrapped in parentheses and very similar to the first, so I just duplicated the changes from the first.

#

I struggle with templates so clean is not the goal, working is 😜

silent barnBOT
bronze dirge
#

Please let me know if I am posting on the wrong channel.
I have that ^ template switch. Bascially turning the relay on and off with 300ms cooldown

#

I notice recently that after clicking the switch. There could be a huge delay before the relay gets triggered

#

Or that the relay could turn on then stay for much longer than 300ms (like 5s)

#

It used to work perfectly but it developed this issue.

#

I am not sure where that delay comes from.

silent seal
#

When did it develop the issue? What changed?

bronze dirge
#

Not sure...sorry
it could be HA update but it could be before the update

#

I didn't touch HA for a while

#

I wonder if the delay is

  1. after I click the template switch button but before it reaches HA thru internet
  2. after it execute the template "script"
  3. zigbee mesh connection issue
    I am not sure how to distinguish between them
sonic nimbus
#

can I use templating for entity_id in condition part as condition-state?

#
          target:
            entity_id: "{{trigger.to_state.entity_id}}"
          state: 'not_home' ```
#

it shows me an error in my logs: Invalid config for [automation]: Entity {{trigger.to_state.entity_id}} is neither a valid entity ID nor a valid UUID for dictionary value @ data['condition'][0]['conditions'][0]['entity_id']. Got None.

silent seal
sonic nimbus
#

I assume, that condition need to be type of template

bronze dirge
bronze dirge
silent seal
#

What kind of switch is it? How is it connected to Home Assistant? There should be logs in that.

bronze dirge
#

It's a zigbee sonoff. I used z2b to connect to home assistant

#

z2m

silent seal
#

I don’t think this is a templating issue (at least, more troubleshooting required). So for now you might be better off in the #zigbee-archived channel.

silent barnBOT
#

If you're having problems with your updates to your configuration:

  • Check the troubleshooting steps
  • Check your log file - remembering you may need to set logger to info or debug
  • Explain what the problem you're having is - sharing configuration, errors, and logs
silent seal
#

This should help!

bronze dirge
#

ok

#

Thank you for pointing me to the right direction!

silent seal
#

You’re welcome!!

floral shuttle
#

can I write this shorter? {%- for s in states.scene if select == s.object_id.split('_')[:-1]|join('_') or select == s.object_id.split('_')[:-2]|join('_') or select == s.object_id.split('_')[:-3]|join('_')%}

inner mesa
#

What are you trying to do?

mighty ledge
floral shuttle
#

though it already does what Petro says, cast a bit wider than desired

#

short story: I want to strip of the group names (which can be 1 to 4 words) and only list the scene names (which now can be up to 3 words)

#

having groups like Dining, and Dining table, doesnt make things easier,.... or Living, and Living ceiling spots 1... might have to change those for easier templating

#

my thought btw for the current template were to shorten something like [:{-1,-2,-3}], replacing the 3 or's.

silent seal
#

Why not just replace the select in the name?

#

Usually replace will just not do anything if it doesn't match a substring.

floral shuttle
#

Will try that after some sleep ;> thanks

pastel moon
#

Hi, I am converting dates back and forth to get rid of the milliseconds. Is there a "correct way" to handle this? I usually use now().strftime('%Y-%m-%d %H:%M:%S%z') to format the string I need, which is almost what as_local produces. Why are milliseconds shown in those commands? Is it possible to define own, custom macros? 🙂

marble jackal
#

It shows milliseconds because you tell it to, if your remove %z in the template it won't.

pastel moon
#

What I meant to ask if why as_local shows milliseconds. There should be a filter to remove just the unwanted parts... (know there isn't, but it's christmas... :D)

marble jackal
#

I don't understand. You can format it as you want using .strftime Just change the part between the brackets to your needs

#

Or convent it to a timestamp and use | timestamp_custom()
You can use | int on the timestamp to remove ms

pastel moon
#

Question is why as_local shows the milliseconds... I know I can format it as I want, just wondered if there was an easier way

marble jackal
#

as_local only converts a datetime object to local time, it doesn't change how it is displayed

pastel moon
#

Ok, got it. Thanks

pastel moon
#

How would I modify this {{ states | map(attribute='entity_id') | select('match', 'light') | list }} to also include entities with the word outlet in it's entity_id? I have tried adding another select('contains', 'outlet') statement, but have had no luck so far

#

Goal is to get a list of entity_id's of all my lights + one light that is actually a dumb one on a switch (outlet)

floral shuttle
# silent seal Why not just replace the select in the name?

you made me rethink! thank you for that: filter: template: | {% set hue_group = states('input_select.hue_group_v2')|lower|replace(' ','_') %} {% set ns = namespace(scenes=[]) %} {%- for s in states.scene if hue_group == s.attributes.group_name|lower|replace(' ','_')%} {% set ns.scenes = ns.scenes + [{'entity':s.entity_id, 'name': s.object_id.split(hue_group +'_')[1]|capitalize|replace('_',' ') }] %} {%- endfor %} {{ns.scenes}}

#

trying the new 'slugify' filter, I can do this:``` filter:
template: |
{% set hue_group = states('input_select.hue_group_v2')|slugify %}
{% set ns = namespace(scenes=[]) %}
{%- for s in states.scene
if hue_group == s.attributes.group_name|lower|replace(' ','')%}
{% set ns.scenes = ns.scenes + [{'entity':s.entity_id,
'name': s.object_id.split(hue_group +'
')[1]|capitalize|replace('_',' ') }] %}
{%- endfor %}
{{ns.scenes}}

#

but can not use it in the if hue_group == s.attributes.group_name|lower|replace(' ','_') line, resulting in TypeError: decoding to str: need a bytes-like object, LoggingUndefined found

#
        filter:
          template: |
            {% set hue_group = states('input_select.hue_group_v2') %}
{{hue_group}}
            {% set ns = namespace(scenes=[]) %}
            {%- for s in states.scene
              if hue_group == s.attributes.group_name%}
                {% set ns.scenes = ns.scenes + [{'entity':s.entity_id,
                  'name': s.object_id.split(hue_group|slugify +'_')[1]|capitalize|replace('_',' ') }] %}
            {%- endfor %}
            {{ns.scenes}}
``` is better though, and yet less code 😉
pastel moon
blazing burrow
#

good morning and happy holidays!

i'm trying to figure out how to make this call correctly, but keep getting a value_json does not exist error 🤔

      - service: mqtt.publish
        data:
          topic_template: "homeassistant/sensor/bug_report/{{ bug_number }}/config"
          retain: true
          payload_template: >-
            {
              "name": "Bug Report #{{ bug_number }}",
              "unique_id": "bug_report_{{ as_datetime(float(time)) | as_timestamp }}",
              "state_topic": "bug_report/{{ bug_number }}",
              "json_attributes_topic": "bug_report/{{ bug_number }}",
              "value_template": '{{ "{{ value_json.message }}" }}'
            }
#

i'm thinking it's trying to render that last template, when i actually need to send the template itself... any ideas?

#

actually, i just had the idea to use '{{ "{{ " + "value_json.message" + " }}" }}'

#

and that avoids the error, but that isn't actually publishing anything to that topic 🤔

#

haha i got it!

      - service: mqtt.publish
        data_template:
          topic: "homeassistant/sensor/bug_report/{{ bug_number }}/config"
          retain: true
          payload: >-
            {
              "name": "Bug Report #{{ bug_number }}",
              "unique_id": "bug_report_{{ as_datetime(float(time)) | as_timestamp }}",
              "state_topic": "bug_report/{{ bug_number }}",
              "json_attributes_topic": "bug_report/{{ bug_number }}",
              "value_template": "{{ '{{ ' + 'value_json.message' + ' }}' }}"
            }
pastel moon
blazing burrow
#

hey great!

fossil shore
#

Since the winter solstice has passed I wanted to make a sensor showing me the change in daylight each day and I've made a custom sensor that uses this

value_template: "{{( state_attr('sensor.sunset', 'tomorrow') - state_attr('sensor.sunrise', 'tomorrow') ) - (state_attr('sensor.sunset', 'today') - state_attr('sensor.sunrise', 'today') )}}"

and it gives me a sensor with a timestamp like 0:01:11.942851 but how can I change that to something more readable like 1m12s or atleast 1:12

pastel moon
blazing burrow
#

you can't really have the past ones unless you set it into an input_datetime or something else

#

i have a pretty complicated sunrise/sunset based automation that waits until sunSET of the current day, and then sets input_datetimes with the times for the NEXT day

pastel moon
#

Ah, figures 🙂 I saw them in the Logbook, but getting them from there proves a challenge... 🙂

blazing burrow
#

that way i can work with them even after sunRISE of the next day

fossil shore
toxic dome
#

Oh NVM. Forgot how last works. It's not the previous value, it's the value of the latest entity to update of those watched. My bad

#

Yea getting a sensor with the previous value of another entity to when it updates is tricky. You could do it by listening for and triggering off the state_changed event directly since it contains current and previous values in it. But then it won't restore correctly after a restart

clever fable
#

Can anyone help me convert this template, from equals Multivitamin to an contains Multivitamin?

#

{{"Multivitamin" in trigger.to_state.attributes.friendly_name}}

mighty ledge
clever fable
#

Ok then the automation must have a different problem Thanks

marble jackal
#

@low cypress This will give you a count of all unavailable entities, it might help provide a start for what you want to achieve:
{{ states | selectattr('state', 'eq', 'unavailable') | list | count }}

#

Off to bed now 😴

inner mesa
#

Specifically, {{ states | selectattr('state', 'eq', 'unavailable') | list | length > 0 }}

low cypress
#

but this template gives me only number.
I want to create an alert "<triggered_entity> is unavailable"

marble jackal
#

I currently have 83 unavailable entities, I would not want to get notified about that

#

😅

#

But you can also create a template for that

inner mesa
#

That template can also be modified to output the list

low cypress
inner mesa
#

How you define ‘new’ becomes the problem

low cypress
#

yes, i get your point

glacial matrix
#

Evening all! Merry Christmas!

{% set do_child1bins = is_state('sensor.child1_bins', 'today') %}

could someone tell me how I modify this so that that it check's to see if the sensor child1_bins is today (as above), AND input_boolean.chore_bins is true please.

inner mesa
#

Pretty straightforward

#
{% set do_child1bins = is_state('sensor.child1_bins', 'today') and is_state('input_boolean.chore_bins', 'on') %}
glacial matrix
#

Thank you. I really appreciate that!

#

literally an and is all i needed. So sorry. I was working with another and statement in templates the otherday and it was not that straightforward!

inner mesa
#

Make sure to use the right quotes. My iPad is changing them to the wrong ones

#

And an input_boolean is never “true”, they’re always either “on” or “off”

glacial matrix
#

does it need to be double spaced after the first close bracket?

inner mesa
#

Makes no difference

glacial matrix
#

cool. Thank you.

marble jackal
# low cypress yes, i get your point

Been giving your question some more thought. You could create a template sensor with the number of unavailable entities as state, and the list of unavailable entities as it's attribute. Then create an automation triggering on a state change of this sensor.
You can then determine which are new by taking the new state of the attribute, and rejecting everything in the old attribute state. What remains you can put in your message.

silent vector
#

Is there a way to get an Automation to trigger every 2 weeks. Other than using the time pattern at 336 hours

terse yoke
#

Hi guys. Is someone experienced in mood to help me with templating, I'm really not good with this?

#

And would like that Alexa not speak entity IDs in response, but rather some friendly device name.

#

I would be glad to provide any additional info required, and not sure at all could this be done some simple way or it is too much complicated 🙂

marble jackal
silent vector
marble jackal
#

{{ now().strftime('%U') | int is even }}

silent vector
#

I would make this a template sensor or can this be a value template as a condition?

marble jackal
#

This returns True or False so you can use it in a template condition

silent vector
#

Sounds good thank you.

marble jackal
#

The only issue is that sometimes a year has 53 weeks

#

In that case it will not run in week 53 and in week 1 of the year after, so there will be a three week window. If that is a big issue, you can use odd weeks in a year with 53 weeks. The template becomes a bit more complicated then.

silent vector
#

I see and yes 2023 will have that

silent seal
#

What is your goal? If it's something like checking for rubbish collection or similar there's a great HACS integration which I'm misusing for tracking lots of things!

terse yoke
marble jackal
silent vector
marble jackal
#

In the same automation in which you run your biweekly actions.
trigger: 06:00
condition: Monday
action:
choose:
- boolean is off: run biweekly actions and turn boolean on
- boolean is on: turn boolean off
Biut if you want to discuss it further I suggest we move to #automations-archived

tawny coral
#

Hi I'm trying to make a timer but it doesn't seem to work at all. The code looks like this.

sensor:
  - 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) }}
#

Can't share images on here but it essentially just says "0 seconds" for some reason

marble jackal
#

maybe a typo in your entitiy_id? The template itself should work

#

or it could be that your trick to refresh it does not work 🙂

#

So it only refreshes on a change of the enttiy, and

#

then it sticks on 0 seconds

buoyant pine
silent vector
tawny coral
inner mesa
#

Where are you checking the value to determine that it never updates?

#

That template reports the right value for one of my entities

inner mesa
#

The frontend doesn’t always update regularly

blazing burrow
#

trying to figure out how to get all the sensors i have with a specific entity "pattern"... like sensor.issue_*

#

i think this should be a selectattr, but i'm not quite sure how to accomplish it

#

{{ states.sensor | selectattr('entity_id', 'in', 'sensor.issue_*') | list }} doesnt work lol

inner mesa
#

no

#

match

blazing burrow
#

mmm

inner mesa
#

or search, depending on whether the pattern starts at the beginning

blazing burrow
#

yes, match works

#

thank you!!

inner mesa
#

keep in mind that it's a regex and not just a glob

blazing burrow
#

ok wait, how do i get the entity_id from those?

#

just trying to get a list of the ids

#

oh got it

#

map(attribute='entity_id')

flint bison
#

Newbie here, just installed version 2021.12.5. Installed integrations for all devices on my network, HACS. Most of the integrations were simple, Roku card works really well. The DirecTV integration has minimal function, trying to trying to get one of the remote cards to work with DirecTV. Tried TV remote card and Generic Remote Card and tinkering with the config using the information on Home Assistant site, but not making much headway. Does anyone have a template for DirecTV that I can use as a starting point or if complete even better.

blazing burrow
#

['binary_sensor.issue_10', 'binary_sensor.issue_5', 'binary_sensor.issue_6', 'binary_sensor.issue_8', 'binary_sensor.issue_9']

#

but how can then sort those properly by their number?

#

so 5,6,8,9,10

#

or whatever the case may be

inner mesa
#

Not easily, since they’re not zero-filled. Fix that, and I think you can use |sort

marble jackal
#

Your list is actually already sorted alphabetically now

blazing burrow
#

hmm, what if there were over 99? zero padding there would be even trickier

inner mesa
#

Zero padding is zero padding

#

Maybe tedious, but not really tricky

marble jackal
#

I was up for a challenge during a Christmas movie, this seems to work, even over 99. But i agree zero padding would be better

#
{% set ns1 = namespace(d = []) %}
{% set ns2 = namespace(d = []) %}
{% set ns3 = namespace(d = []) %}
{% for sensor in sensors %}
  {% set d = sensor.split('_')[-1] | count %}
  {% if d == 1 %}
    {% set ns1.d = ns1.d  + [ sensor ] %}
  {% elif d == 2 %}
    {% set ns2.d = ns2.d  + [ sensor ] %}
  {% elif d == 3 %}
    {% set ns3.d = ns3.d  + [ sensor ] %}
  {% endif %}
{% endfor %}
{{ ns1.d | sort + ns2.d | sort + ns3.d | sort }}```
#

And it can probably be done with less code, but it works 😅

inner mesa
#

I guess you could do the zerofill in real time

olive lagoon
#

value_template: {{ state_attr('sensor.electricity_price', 'Price level') in ['NORMAL','CHEAP'] }}

Can anyone spot the mistake it says i should add commas

inner mesa
#

What does?

mighty ledge
mighty ledge
inner mesa
#

Oh, yeah

#

Needs commas?

#

And cowbell

toxic dome
#
{% set sensors = ['binary_sensor.issue_10', 'binary_sensor.issue_199', 'binary_sensor.issue_102', 'binary_sensor.issue_8', 'binary_sensor.issue_9'] %}
{{ sensors
  | map('regex_replace', '^.+_(\\d+)$', '\\1')
  | map('int') | sort | map('string')
  | map('regex_replace', '^(\\d+)$', 'binary_sensor.issue_\\1')
  | list }}
#

I was kinda mad I had to use regex_replace again at the end but I couldn't figure out any other way to do concat as a filter lol

toxic dome
#

Side note, template challenges are fun. If there was a newspaper that had jinja puzzle of the day instead of a crossword I'd be all for it lol

inner mesa
#

The Geek Times

olive lagoon
#

@mighty ledge Thanks

blazing burrow
#

@marble jackal @mighty ledge @toxic dome thanks! will try these out!

floral blaze
#

does someone know what im doing wrong here?

#

template:

  • sensor:
    • name: sensor.storage_capacity
      unique_id: unique_id_for_Tb_sensor
      unit_of_measurement: "Tb"
      state: "{{ (states('sensor.sabnzbd_disk') |float / 1000 }} | round(2)"
buoyant pine
#

Your round filter is outside of the template

floral blaze
#

if i put it inside i cant get it to work either

inner mesa
#

Parens

floral blaze
#

state: "{{ (states('sensor.sabnzbd_disk') |float / 1000 | round(2)" }}

#

like that

inner mesa
#

Not like that

#

You’re missing a paren after the 1000

#

And you have “ inside the template

floral blaze
#

state: "{{ (states('sensor.sabnzbd_disk') |float / 1000 ) | round(2) }}"

#

like this?

inner mesa
#

Yes

floral blaze
#

lets see

inner mesa
#

You may need to add a default to float() if it will ever not be a number

floral blaze
#

great rob! its working

#

Thanks for helping me out good person

olive lagoon
buoyant pine
#

Yep

blazing burrow
eager reef
#

I think i'm having an issue with leading numbers in sensor names (which have been given by the homematic integration).

working: {{ state_attr('binary_sensor.office_power', 'friendly_name') }}

not working: {{ state_attr('binary_sensor.00095be98bXXXX_illumination', 'friendly_name') }}

BUT if i use this entity-id in an automation it works fine.

Is there any workaround I am not aware of?

blazing burrow
#

need to use states.binary_sensor['00095be98bXXXX_illumination'].attributes.friendly_name I think

loud otter
#

Hi all, does anyone knows if it is possible to use a input boolean in a template inside a blueprint?

I have created a input_boolean named "studio" and then a blueprint with an input to recall this blueprint

boolean_name: name: Room Name description: Name of the room in which are the lights default: false selector: text:

#

I then created variable:
variables: boolean_name: !input boolean_name

and a condition but it doesn't work:

   ` - condition: template
      value_template: '{{ states(input_boolean.[boolean_name]).state == off }}'`
#

any hint?

floral blaze
#

Hey guys, i was wondering if these sensors, state: "{{ (states('sensor.sabnzbd_disk') |float / 1000 ) | round(2) }}" and state: "{{ (states('sensor.sabnzbd_free') |float / 1000 ) | round(2) }}" could be subtracted in order to gain a new sensor ie: sensor.sabnzbd_used ?

buoyant pine
#
"{{ ((states('sensor.sabnzbd_disk') |float - states('sensor.sabnzbd_free') |float) / 1000) | round(2) }}"
floral blaze
#

im going to try this, i was already well on my way (i think :))

#
  - sensor:
      - name: sensor.storage_capacity_used
        unique_id: unique_id_for_Tb_sensor2
        unit_of_measurement: "Tb"
        state: "{{ ( ('sensor.storage_capacity') | float) - ( ('sensor.storage_free') | float) }}"
toxic dome
floral blaze
#

hmmm, for some reason it puts out the same value as 'sensor.storage_capacity'

#

i saw this thanks, ive corrected that

toxic dome
#

And if you want to use the state of an entity in a template then you need to do states(<entity id>)

pastel moon
toxic dome
#

You just have the name as a string

floral blaze
#

im going to fench with this thanks

buoyant pine
#

Or

#

Use what I shared above 😄

floral blaze
#

i did that, but it seems to put out the same value as 'sensor.sabnzbd_disk'

  - sensor:
      - name: sensor.storage_capacity_used
        unique_id: unique_id_for_Tb_sensor2
        unit_of_measurement: "Tb"
        state: "{{ ((states('sensor.sabnzbd_disk') |float - states('sensor.sabnzbd_free') |float) / 1000) | round(2) }}"
eager reef
floral blaze
inner mesa
eager reef
warm burrow
#

hello friends, im very new at this stuff so i need some help

i managed to get my one rf remote working to toggle a light, now i have another one that im kinda stuck with

i have the code needed, it gets detected when i listen with mqtt, but i cant get it to work in an automation, when i toggle the automation normally then the light toggles, just not with the RF remote

this is the binary sensor that worked for the other remote, as well as automation (not in the same file of course) https://www.codepile.net/pile/wv5q81v8

#

am i missing a step somewhere

mighty ledge
#

For what

glossy aurora
#

How can i concat or short a string ?
wanna compare these strings:
2021-12-29T09:30:00+00:00
2021-12-29T06:20:00+00:00

#

so first i gotta compare year , month , day , time

#

is there a faster way then just comparing them one by one ?

late island
glossy aurora
#

currently i am checking if the person with the set alarm is home, if not i get a big value, then i readout the sensor alarm timer (2021-12-29T09:10:00+00:00) and remove everything till i get the yearmonthdaytime

#

as int

#

compare them and then take the alarm thats earlier

#

now i want to set that time 5 minutes before

#

do i have to first cut the string down to the time substrate 5 and then build it with concat ?

#

is there no easier method knowing its a device_typ: timestamp

livid adder
inner mesa
glossy aurora
#

ohh

#

i will try that

#

ty as always senpai :D

#

{{ as_timestamp(states.sensor.kobito_next_alarm)}}

#

this returns "None"

inner mesa
#

That’s bad syntax

#

Please do read the templating docs

glossy aurora
#

{{ as_timestamp(states.binary_sensor.garage_door.last_changed) }}
thats from the doc

inner mesa
#

That’s not what you have or what you want

#

You want the state and there’s a whole section for that

glossy aurora
#

ok so just {{as_timestamp(states('sensor.kobito_next_alarm'))}}

inner mesa
#

That looks better

glossy aurora
#

so as_timestamp give me Time in Milliseconds: 1640769000000

#

how does that work ?

#

what kind of time is that ?

#

1640769000000

#

is a pretty big number

#

312160 years o.O

inner mesa
#

It’s in seconds

glossy aurora
#

then its even bigger o.O

#

2996838 years

mighty ledge
#

what's the actual state of your sensor.kobito_next_alarm

glossy aurora
#

states('sensor.kobito_next_alarm') returns 2021-12-29T09:10:00+00:00

mighty ledge
#

Then you're reading the number wrong

#

1640769000

#

not sure where you're getting 3 extra zeros

glossy aurora
#

its the output from devtool when i use {{as_timestamp(states('sensor.kobito_next_alarm'))}}

#

1640769000.0

mighty ledge
#

exactly...

#

notice the decimal

#

😉

glossy aurora
#

? thast why i didnt include the last 0

mighty ledge
glossy aurora
#

wait what :O

#

<-- retard i guess

mighty ledge
#

hence the confusion.

glossy aurora
#

i still get 312 years

mighty ledge
#

your math is off

#

its about 50 years

glossy aurora
#

it should be 01.01.1970

mighty ledge
#

divide it by 60 / 60 / 24 / 365

#

52 years

#

2022 - 52 = 1970

glossy aurora
#

so its seconds

inner mesa
#

big note in the docs:

#

UNIX timestamp is the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970. Therefore, if used as a function’s argument, it can be substituted with a numeric value (int or float).

glossy aurora
#

its so weird that its says time in milliseconds:

inner mesa
#

where?

#

milliseconds are the fractional part

glossy aurora
#

works like a charm

#

the nextalarm entity got an anttribute named:
Time in Milliseconds: 1640769000000

#

oh

#

well it is

#

thats where i got the 3 0´s from

#

lul well not my day i guess i cant even go from seconds to years ... yickes

uneven pendant
#

Can someone assist me in writing a template a service call can use? I need to update an input_number. (input_number_lifetime_earned_ava) using a value stored as a counter, do some math on it (to show allowance earned) then add that number to an existing number helper.

#

{% set value = states('counter.chore_ava_counter') | int %}
{% set prevalue = states('input_number.number_lifetime_earned_ava') | float %}
{% set newvalue = (value / (70) * 15) | round(2) %}

You Earned ${{ (value / (70) * 15) | round(2) }} Last Week
You've earned ${{ newvalue + prevalue }} total from chores

#

Thus far i can throw that in the developer template. but i have no idea how to translate that into a service call.

#

I want to add newvalue and prevalue, then post that to a service call to set the input_number

inner mesa
#

Pretty much exactly what you gave there

uneven pendant
#

service: input_number.set_value
target:
entity_id: input_number.number_lifetime_earned_ava
data: {
{% set value = states('counter.chore_ava_counter') | int %}
{% set prevalue = states('input_number.number_lifetime_earned_ava') | float %}
{% set newvalue = (value / (70) * 15) | round(2) %}
{{ newvalue + prevalue }}
}

#

doesn't seem to like this

inner mesa
#

You added some extraneous { }

#

And you need to format it as a multi line template

slender sage
#

How could I create a virtual light to represent my 433MHz light that does not report its state to HA, but is controlled by multiple "light switches" (rocker buttons) that HA can see sending their state? I'd want the virtual light to update its state based on the latest on/off event from any of the switches. I'm using tellstick add-on to let HA know what the switches are doing. I've tried FAQ, google and working myself on the templates and groups, but I just can not get my head around the logic how to build this.

uneven pendant
#

Failed to call service input_number.set_value. Error rendering data template: Result is not a Dictionary

#

service: input_number.set_value
target:
entity_id: input_number.number_lifetime_earned_ava
data: >+
{% set value = states('counter.chore_ava_counter') | int %}
{% set prevalue = states('input_number.number_lifetime_earned_ava') | float %}
{% set newvalue = (value / (70) * 15) | round(2) %}
{{ newvalue + prevalue }}

inner mesa
#

You’re not calling the service properly

uneven pendant
#

I wish i knew what that meant

inner mesa
#

Just the docs

#
service: input_number.set_value
target:
  entity_id: input_number.number_lifetime_earned_ava
data:
  value: >-
    {% set value = states('counter.chore_ava_counter') | int %} 
    {% set prevalue = states('input_number.number_lifetime_earned_ava') | float %}
    {% set newvalue = (value / 70 * 15) | round(2) %}
    {{ newvalue + prevalue }}
uneven pendant
inner mesa
#

first, you can't use templates in devtools -> Services. Second, did you see what I just posted?

uneven pendant
#

welll that would be why that's not working.

inner mesa
#

it wasn't the only problem

uneven pendant
#

input_number

#

services whatever

#

that one?

inner mesa
#

?

uneven pendant
#

should i throw it into an automation to test?

inner mesa
#

if that's where you planned to use it

uneven pendant
#

it is.

#

will try, bb soon

#

still failing, result not a dictionary.

inner mesa
#

I think you didn't add it properly

uneven pendant
#

what does it mean "not a dictionary"

inner mesa
#

it means that your formatting is broken

#

this works for me:

#
set_test:
  sequence:
    - service: input_number.set_value
      target:
        entity_id: input_number.test2
      data:
        value: >-
          {% set value = 1 %} 
          {% set prevalue = 2 %}
          {% set newvalue = (value / 70 * 15) | round(2) %}
          {{ newvalue + prevalue }}
uneven pendant
#

What is :
set_test:
sequence:

#

where'd that come from?

inner mesa
#

it's a script that I wrote to test what I posted

uneven pendant
#

maybe i could just call a script as the action

#

if it works as a script

#

i'll test

#

it works fine as a script but errors as a service call.

#

makes perfect sense.

uneven pendant
#

oh well, have automations that call the script. Good to go, thanks for your help. it was valuable.

dense stream
#
- platform: template
  sensors:
    rhys_phone_rounded:
      friendly_name: Rhys phone battery rounded
      unique_id: e7847441-896c-4d59-bd72-8e165c116f8c
      value_template: >
        {% set batt = states('sensor.rhys_phone_battery_level') %}
        {% if batt >= 0 and batt < 10 %}
        {% set rounded = 0 %}
        {% elif batt >= 10 and batt < 20 %}
        {% set rounded = 10 %}
        {% elif batt >= 20 and batt < 30 %}
        {% set rounded = 20 %}
        {% elif batt >= 30 and batt < 40 %}
        {% set rounded = 30 %}
        {% elif batt >= 40 and batt < 50 %}
        {% set rounded = 40 %}
        {% elif batt >= 50 and batt < 60 %}
        {% set rounded = 50 %}
        {% elif batt >= 60 and batt < 70 %}
        {% set rounded = 60 %}
        {% elif batt >= 70 and batt < 80 %}
        {% set rounded = 70 %}
        {% elif batt >= 80 and batt < 90 %}
        {% set rounded = 80 %}
        {% elif batt >= 90 and batt < 100 %}
        {% set rounded = 90 %}
        {% elif batt >= 100 %}
        {% set rounded = 100 %}
        {% endif %}
        {{ rounded }}

Can anyone tell me whats wrong with this, works fine in developer tools but shows as unavailable when implemented

inner mesa
#

You’re missing |float in the initial set

dense stream
#

ffs i had that in earlier must have misplaced it

inner mesa
#

It could also be simplified greatly

dense stream
#

any pointers im happy ive tried a few things but couldnt get them to work

inner mesa
#

{{ (batt/10)|int * 10 }} to start

dense stream
#

wow ok that's embarrassing

inner mesa
#

Special case 100

#

Or even that would work up to 110, if that’s a thing

dense stream
#

haha yeah i have never got over 100 but will let you know if i do.

#

thanks @inner mesa

amber zodiac
#

i needed numbered form of month & days in an automation script and have a template for it (below) .But get this error all the time in logs. Though everything seems fine i wonder whats the issue
Template variable warning: list object has no element 28 when rendering '{% set days = ["Mon", "Tue", "Wed", "Thu", "Wed", "Thu", "Fri", "Sat", "Sun"] %} {{ days[now().day-1] }}' 1:44:00 AM – (WARNING) helpers/template.py
Template
`sensor:

  • platform: template
    sensors:
    month_long:
    value_template: >
    {% set months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] %}
    {% set days = ["Mon", "Tue", "Wed", "Thu", "Wed", "Thu", "Fri", "Sat", "Sun"] %}
    {{ months[now().month-1] }}
  • platform: template
    sensors:
    date_padding:
    value_template: >
    {% set days = ["Mon", "Tue", "Wed", "Thu", "Wed", "Thu", "Fri", "Sat", "Sun"] %}
    {{ days[now().day-1] }}`
inner mesa
#

well, now().day is 28

#

Because it's the 28th day of December. Did you want the index of the day of the week?

#

If so, you want {{ days[now().weekday()] }}

#

or just {{ now().strftime("%a") }}

#

same with the month: {{ now().strftime("%b") }}

sage thunder
#

How to use template to display name of a user on Lovelace card?

inner mesa
#

there's an example of exactly that on the markdown card

rain geode
#

Hello all, I found a template to calculate Vapor Pressure Deficit:

- platform: template sensors: vapor_deficit: friendly_name: 'vpd in kilo pascals' value_template: >- {% set T = states('sensor.itc_308_temperature')|float %} {% set RH = states('sensor.ihc_200_humidity')|float %} {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %} {% set VPD = ((100-RH) / 100) * SVP %} {{-VPD | round(2) -}} unit_of_measurement: 'kPa'

It works but sometime trigger a lot of this error and make spikes in Grafana graphs:

Template warning: 'float' got invalid input 'unavailable' when rendering template '{% set T = states('sensor.itc_308_temperature')|float %} {% set RH = states('sensor.ihc_200_humidity')|float %} {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %} {% set VPD = ((100-RH) / 100) * SVP %} {{-VPD | round(2) -}}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1

Is there something I can do to avoid this error? I have last version of HA. Thank you

floral shuttle
#

anyone with a count down template sensor to new year?....

plush willow
#

I have a question about a kWh sensor and m3 gas sensor. The value is 3.787 kWh. I use the next sensor for playing it on my smart speaker:

  • platform: template
    sensors:
    summary_smart_house:
    friendly_name: "Overzicht huis"
    value_template: >
    You have today: {{ states('sensor.daily_energy') | float }} kWh used.......

The problem is that is pronounced not correctly because it is no comma (the system thinks that it is a thousand seperator). How can I replace the dot with a comma so that it is pronounced correct?

floral shuttle
#

haha, yess, thanks. Id still need the template sensor though... i am using The Python script (birth)date count downer... but that doesnt account for hours,minutes.sec,, changing that would be somewhat overkill though

silent seal
floral shuttle
#

thx! ```{% set newYear = as_timestamp(strptime('31/12/' ~ now().year, '%d/%m/%Y')) %}
{% set now = as_timestamp(now().astimezone())%}
{% set New = newYear-now %}
{%- macro phrase(name,divisor,mod=None) %}
{%- set value = ((New//divisor) % (mod if mod else divisor))|int %}
{%- set end = 's' if value > 1 else '' %}
{{- '{} {}{}'.format(value,name,end) if value|int > 0 else ''}}
{%- endmacro %}

{%- set values = [phrase('week',6060247),phrase('day',606024,7),phrase('hour',6060,24),
phrase('min',60),phrase('sec',1,60)]|select('!=','')|list %}
{{values[:-1]|join(', ') ~ ' and ' ~ values[-1] if values|length > 1 else values|first}}

#

hmm, 1 day off I guess...

#
{% set newYear = as_timestamp(strptime('01/01/' ~ Year, '%d/%m/%Y')) %}
{% set now = as_timestamp(now().astimezone())%}
{% set New = newYear-now %}
{%- macro phrase(name,divisor,mod=None) %}
{%- set value = ((New//divisor) % (mod if mod else divisor))|int %}
{%- set end = 's' if value > 1 else '' %}
  {{- '{} {}{}'.format(value,name,end) if value|int > 0 else ''}}
{%- endmacro %}

{%- set values = [phrase('week',60*60*24*7),phrase('day',60*60*24,7),phrase('hour',60*60,24),
                  phrase('min',60),phrase('sec',1,60)]|select('!=','')|list %}
{{values[:-1]|join(', ') ~ ' and ' ~ values[-1] if values|length > 1 else values|first}}
cinder lotus
#

I have a config template card. Found this example with 2 states:

        ${ states['cover.rolluik_achterdeur'].state  === 'open' ?
        'mdi:window-shutter-open' : 'mdi:window-shutter' }

That works fine, so far but I'd like to extend with 5 different icons based on the attribute current_position: xxx. Could someone help me how to change the code?

#

'Full' lovelace card yaml is:

entities:
  - cover.rolluik_achterdeur
card:
  type: entities
  entities:
    - entity: cover.rolluik_achterdeur
      icon: >-
        ${ states['cover.rolluik_achterdeur'].state === 'open' ?
        'mdi:window-shutter-open' : 'mdi:window-shutter' }```
#

I changed states['cover.rolluik_achterdeur'].state === 'open'to `` states['cover.rolluik_achterdeur'], 'current_position' === '100' just to see if the open mdi remains but that doesn't work

#
        ${ states['cover.rolluik_achterdeur.current_position'] = '100' ?
        'mdi:window-shutter-open' : 'mdi:window-shutter' }```
seems to work, for a while... (to keep the shutter-open icon when the current_position is 100 but how create 4 more if's...
inner mesa
cinder lotus
#

Asked question there but nobody replied...

#

Just tried:

  variables:
    covstate: |
      covstate => {
        if (covstate = 19) {
          return 'icon = csi: shutter-O';
        }
        else if (covstate >= 20 && temp <= 40) {
          return 'icon = csi: shutter-1';
        }
          return 'icon = csi: shutter-2';
      }
    covstate: states['cover.rolluik_achterdeur'].attributes.current_position
  entities:
    - cover.rolluik_achterdeur
  card:
    type: entities
    entities:
      - entity: cover.rolluik_achterdeur
        icon: covstate'```
No luck
#

The code is used in lovelace frontend but the yaml is templating no?

inner mesa
#

Please don’t just move to an unrelated channel

#

.topic

#

Well, see the topic

cinder lotus
#

template-card...

#

I struggle with template code syntax...

#

topic sais: we are here to help! 😉

inner mesa
#

This channel is for Jinja templates. That’s JavaScript for a card

cinder lotus
#

The contributor mentions Typescript... I really don't know

inner mesa
#

Typescript is a form of JavaScript

cinder lotus
#

You want me to remove my posts here?

inner mesa
#

No need

plush willow
inner mesa
#

There’s some extra stuff in there and it’s a bit heavy for what you’re doing

#

{{ states(‘sensor.daily_energy’).replace('.', ',') }}

plush willow
#

okay i didn't now there is a replace method. This is much easer indeed. Thanks

inner mesa
#

Jinja uses Python objects, so Python methods work on them

plush willow
#

okay

#

another question: Is it right that a template sensor value has a limit of 254 characters?

inner mesa
#

255, I think

#

All states do

plush willow
#

okay

#

maybe a crazy thing 🙂 But i was creating an overview sensor of my whole house with all kind of information in it and then use TTS to play it on my sonos speaker.

I noticed that from 254/255 characters the speaker was given: "unknown"

#

So i think the solution will be seperate sensors for this goal

meager relic
#

Hi
How to work with static and dynamic lists of sensors?

dreamy sinew
#

need more details

meager relic
#

https://community.home-assistant.io/t/how-to-work-with-static-and-dynamic-lists-of-sensors/372675
What i’d like to do is in case one or some of them are open - to notify me when i get back home.
My trigger for that automation is when my phone geo sensor tracks that im entering home and them the door opens.
The speakers then welcome me home.
What i’d like it to do is also let me know if some of those contact sensors are open.
For example:
“Welcome Ziv, the Coffee and Shower cabinets are open”.

In order to do that, i’d need:

To provide a static list of contact sensors to go over and see if they are “open” - how do i do that?
Create new dynamic list only with the “open” contact sensors - how do i do that?
Pass the list to the tts service - how do i do that?
I tried to search in the template syntax and in the forum with little to no luck (to my surprise BTW)

dreamy sinew
#

make a group of the sensors

#
{{ "Welcome Ziv, the following cabinets are open: {}".format(', '.join(on_sensors) if on_sensors else "Welcome Ziv. All cabinets are closed." }}```
#

can get more complex than that if you want to add an and in there but should suffice

meager relic
#

thank you @dreamy sinew!

Let me see if i get that right.

  1. I need to use a group first. is there a way to list the sensors in this specific automation? or do i have to do it in the YAML file?
  2. attribute='name', what is that mean?

I think all the rest i got

floral shuttle
#

just to be sure and not miss out on a maybe recently added option: we can only update template sensors each second by using an automation with - alias: Second updater id: Second updater trigger: platform: time_pattern seconds: '/1' action: service: homeassistant.update_entity ?

#

no other option in the template itself would trigger an automated update? (asking because I have this count down I like to see the seconds tick away #templates-archived message)

silent seal
#

I have what I am sure is a simple issue, my trigger template sensor is not showing anywhere (e.g. I can't see it in dev tools). It's at the top of the file, the other (binary) sensors in the file are working 🤔
https://www.codepile.net/pile/1ra5eXrB
This is my template.yaml file which I have included in the configuration with template: !include template.yaml. Can anyone spot the obvious mistake?

silent barnBOT
#

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

silent seal
#

The validator says it's fine, which is why I'm so puzzled!

#

(And rebooting works without an issue, but the core check says it's all ok 🤔 )

buoyant pine
#

change trigger.id to trigger.entity_id

floral shuttle
#

and take out platform: state in the sensor config.

silent seal
dreamy sinew
floral shuttle
#
  - trigger:
      - platform: state
        entity_id:
          - binary_sensor.master_bedroom_sensor_motion
          - binary_sensor.guest_room_sensor_motion
        to: "on"
    sensor:
      - unique_id: last_occupied_room
        name: Last Occupied Room
        state: >
          {{trigger.to_state.name}}
``` doing the job.
charred badge
#

Hi, I am trying to replace the fixed value for kwh with a variable that I declared using the HACS Variable integration in the code below

#
  - platform: template
    sensors:
      media1_cost:
        friendly_name: Media1 Cost £/day
        unit_of_measurement: £
        value_template: "{{ (states('sensor.fridgefreezer_energy_today')|float*0.1838)|round(2) }}"
#

This works fines, but I have about 20+ sensors with power monitoring and dont want to keep changing it every time my tariff changes.

#

So I tried to replace the "0.1838" with the variable I created called var.electric_tariff in the template editor and get this error TypeError: can't multiply sequence by non-int of type 'float'

silent seal
floral shuttle
#

must be yes, because Ive explored it a but further, with:```
sensor:
- unique_id: last_motion_sensor_triggered
name: Last motion sensor triggered
state: >
{{trigger.to_state.name.split(' sensor Motion')[0]}}
attributes:
entity_id: >
{{trigger.entity_id}}

silent seal
#

So, I rebooted, and now it shows 🧐
I shall put this under "quirks"

floral shuttle
#

how odd. you needn't reboot though, simply reload template entities suffices...

silent seal
#

Yup. I did that several times. But #beta gave me a reason. (I should have said restarted HA, not rebooted.)

floral shuttle
#

ha ok, well, as long as you got it working 😉

meager relic
eager reef
#

I am confused about how to access the last_updated property of given sensor state in the preferred way.
It's usually works like
states.sensor.xyz.last_updated.

But it fails for some entity-ids (auto-generated by homematic integration):
states.sensor.00095be98bXXXX_illumination.last_updated => invalid template (TemplateSyntaxError: expected token ')', got 'integer') for dictionary value @ data['binary_sensor'][0]['state'].

I got it working like
states.sensor['00095be98b5fb8_illumination'].last_changed

Then I got the hint, that I should not use states. at all. I can't use state_attr as I'm looking for a property, I tried states('sensor.sensor.00095be98bXXXX_illumination')
in different ways but couldn't figure out how to access properties.

marble jackal
#

last_changed is not an attribute, so state_attr() won't work in this case. You'll have to use states.entity_id.last_changed

#

I think it doesn't work without the square brackets because your object_id starts with a number

eager reef
#

so nothing to improve 🙂 thanks

silent barnBOT
rain geode
#

I did not post code, sorry.

silent barnBOT
rain geode
#

Well, sorry but my copy paste is not working.