#templates-archived

1 messages ยท Page 1 of 1 (latest)

topaz cave
#

Hi there, I'm trying to pull in data from a rest API - the returned Json format has no parent ie. '0':, '1:', '2:' what json_attributes_path should I use? https://dpaste.org/3qHnM I've tried "$.*", "$.." but it's only returning the first record. Thanks in advance.

marble jackal
#

state_attr('weather.met_no_nowcast_buskogen', 'forecast')[0].precipitation

simple edge
#

Thank you, do you know if there is way to store those into a template helper, or better a template variable that resolves based on a boolean set

marble jackal
heavy crown
simple edge
#

How can you get when the sun will rise im trying The sun will rise at {{ (now()-as_timestamp(state_attr("sun.sun", "next_rising")) | timestamp_local).hour()}}. But i dont think I understand how this works

inner mesa
#

Sounds like you're looking for "how long until sunrise"
Number of hours until the next sunrise: {{ (state_attr('sun.sun', 'next_rising')|as_datetime - now()).total_seconds()//3600 }}

rose ether
simple edge
inner mesa
#

In that case it is. It's invoking a Jinja filter

civic cargo
#

HA seems to have a default state that climate entities are set to when they turn on.
I am trying to create a switch that will turn on my heat pump to the most recent state it was in (except off)

I've created a template sensor which does this effectively

value_template: |-
  {%
    if states('climate.office_heatpump') != 'off'
      and states('climate.office_heatpump') != 'unknown'
  %}
    {{ states('climate.office_heatpump') }}
  {% else %}
    {{ states('sensor.office_heatpump_last_state') }} <- this exists so the state doesn't go blank when the heatpump is off
  {% endif %}
#

I've created a script which effectively uses this sensor to turn on the heatpump to the latest state
toggling this script directly works as intended

alias: 'Heatpump Turn On: Office'
sequence:
  - service: climate.set_hvac_mode
    data:
      hvac_mode: '{{ states(''sensor.office_heatpump_last_state'') }}'
    target:
      entity_id: climate.office_heatpump
mode: restart
icon: mdi:thermostat-auto
silent barnBOT
civic cargo
#

Why doesn't the switch work

#

The sensor and the script work independently
The switch isn't playing ball and I'm not sure why

simple edge
#

I think you can kind of do that but believe you need to put it under the state in template sensor

  - binary_sensor:
      - name: "Has Unavailable States"
        state: "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"```
like that. But Ill let someone else confirm.
civic cargo
#

I'm not familiar with selectattr, but I'm doing some investiagting.

Thanks for the guidance.

simple edge
# marble jackal Put it in a template sensor attribute (not the state)
   - sensor:
    - name: Vacuum Map Numbers
      {"input_boolean.kitchen_d_vacuum": 21, "input_boolean.family_room_d_vacuum":19, 
      "input_boolean.dining_room_d_vacuum":17, "input_boolean.dining_room_d_vacuum":16, 
      "input_boolean.downstairs_bedroom_d_vacuum":23, "input_boolean.downstairs_bathroom_d_vac>
      "input_boolean.washing_room_d_vacuum":18 }```
like this? Because that didnt seem to work
civic cargo
#

@simple edge Thanks for the insight, my guy
Got it going

marble jackal
inner mesa
#

rejected by hassbot. that's sad

marble jackal
#

Can't see what's wrong on mobile, even on the second try

inner mesa
#

is that last bit all one line?

marble jackal
#

Should be, but it wasn't, pasting it on dpaste helped

#

Corrected:

template:
  - sensor:
      - name: Vacuum Map Numbers
        state: "{{ 'ok' }}"
        attributes:
          map_numbers: >
            {{ {"input_boolean.kitchen_d_vacuum": 21, "input_boolean.family_room_d_vacuum":19, "input_boolean.dining_room_d_vacuum":17, "input_boolean.dining_room_d_vacuum":16, "input_boolean.downstairs_bedroom_d_vacuum":23, "input_boolean.washing_room_d_vacuum":18 } }}
#

Not sure what he wants to do with this, could be a classic ๐Ÿฅ

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.

rose ether
#

Hey guys, I'm still looking for some help with setting up a temperature slider.

What I'm trying to do at the moment, is set up a temperature slider (or something equivalent), that then sends the correct up and down commands to my IR controlled Air con unit.

The unit control is all handled through harmony, and I have the scripts set up in HA to send these commands, but I cant for the life of me figure out how to hook those commands into some kind of temp setter. I have created an input number, and I can trigger things to happen when it changes, but i cant figure out how to do the correct commands (correct number of up or down commands to reach the new set temp)

I think this should be possible, but im not sure how to go about it. Any help would be appreciated! Thanks!

simple edge
scarlet sapphire
#

how can I best compare temperatures from sensor.weather.external, temperature (attribute) with sensor.temp.internal (no attribute)? Not sure how to mix that

inner mesa
#

those aren't entity_ids

#

it doesn't really matter whether they're states or attributes

scarlet sapphire
#

hmm

inner mesa
#

just use the right function to access the value you want

scarlet sapphire
#

I have used state_attr for attributes but not for states

inner mesa
#

see that link

scarlet sapphire
#

will do, thanks

thorny snow
#

i'm trying to calculate the energy cost of an individual device per day, i have a sensor (sensor.electricty_price) which is my cost of electricity per kwh and another sensor which is the daily usage using utility_meter.

I figured it would be something as simple as multiplying the two numbers together but that's giving completely the wrong sum

{{ ((states.sensor.electricity_price.state | float) * (states.sensor.pow1_usage.state | float)) }}

#

oh wait i think one is kWh and one is Wh

undone shard
inner mesa
#

a markdown card?

#

make a template sensor out of it and then use any card that displays an entity state?

undone shard
#

ok .. so I need to turn it into a template sensor, then display it

inner mesa
#

it's pretty wordy

#

you can use the template directly in a markdown card

undone shard
#

Thanks Rob, I'll give it a whirl

inner mesa
#

you could also simplify the template like this:

{% set strings = ['Standby', 'VENT Low', 'VENT Med', 'VENT High', 'VENT Turbo', 'RECIRC Low', 'RECIRC Med', 'RECIRC High'] %}
{% set state = states('sensor.hrv_state')|int(0) %}
{{ 'unknown --- sensor.hrv_state' if state not in range(2,10) else strings[state - 2] }}
undone shard
#

Thanks again Rob, I tried the markdown card and it worked. Now I'm trying to turn it into a template sensor...

#

to reload the template sensors, I should be using the 'Developer Tools/YAML/YAML configuration reloading/template entities'...right?

inner mesa
#

Yes

undone shard
#

Ok... I got the template sensor working now and I'm 2 for 2 tonight!!

#

onto your suggestion for the template....

inner mesa
#

Made a small fix

undone shard
#

that's 3 for 3!!! Thanks Rob!

fiery rock
#

Just want to check my understanding on something: If I used i = sensors | map('bool', false) it would take the list sensors and look for the boolean value of the items in the list then output a boolean list with the default option being false?

inner mesa
#

I would think, yes

#

Depends on what 'sensors' actually is

#

If it's a list of the names of sensors, no. If it's a list of the state of a bunch of sensors, yes

fiery rock
#

Yeah, i is a list of the state of the sensors achieved by set i = expand('binary_sensor.digit2_a', 'binary_sensor.digit2_b', 'binary_sensor.digit2_e', 'binary_sensor.digit2_f', 'binary_sensor.digit2_g') | map(attribute='state'). There is a whole bunch more to the code block and I'm trying to break it down little by little so I can wrap my head around it.

#

On that, is the expand() function a Home Assistant specific function? I could only find a reference to it in the HA docs but not the jinja docs.

inner mesa
#

Yes, it is

#

See the links in the channel topic

#

It's an HA extension

fiery rock
#

The link is what led me to it ๐Ÿ™‚. I had spent a good amount of time looking through the jinja docs losing hope. Just wanted to check I hadn't missed it somewhere over there. Thanks.

marble jackal
simple edge
#

Hmm how would it be solve easier?

marble jackal
simple edge
#

I created a vacuum interface, that I can select a bunch of rooms to vacuum at a time and these are tracked by those boolean. Unfortunately these rooms inside these vacuum are not map normal they have a random room ID. I need to create a list of room id's that are based on what switches are toggled on when clicking a single clean room button

simple edge
marble jackal
#

Okay, if that works fine ๐Ÿ‘๐Ÿผ

simple edge
#

I would love to learn if there is a better way

marble jackal
#

You're not on the Dutch Discord now ๐Ÿ˜…

dark sparrow
#

oeps..

#

How must I create a sensor in HA in correct YAML:

#

`{% set data = "20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;" %}

{% set ns=namespace(fields={}) %}
{% set fields = data.split(';') %}
{% if fields[2] == "Cresta" %}
{% for item in data.split(';') %}
{% if '=' in item %}
{% set keys=item.split('=') %}
{% set ns.fields = dict(ns.fields.items(), **{keys[0]: keys[1]}) %}
{% endif %}
{% endfor %}
{% endif %}
{{ ns.fields|to_json }}`

#

I have these MQTT sensor:

#

mqtt: sensor: - name: Cresta #{% set data = "20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;" %} state_topic: "/ESP00/msg" value_template: "{{% set ns=namespace(fields={}) %} {% set fields = data.split(';') %} {% if fields[2] == "Cresta" %} {% for item in data.split(';') %} {% if '=' in item %} {% set keys=item.split('=') %} {% set ns.fields = dict(ns.fields.items(), **{keys[0]: keys[1]}) %} {% endif %} {% endfor %} {% endif %} {{ ns.fields|to_json }}}"

#

But it's not accepted.. I need a multiline format I think... Any help with this would be nice (I tried to add | allready, didn't work)

marble jackal
silent barnBOT
#

[Rule #6](#rules message): Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

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

For sharing code or logs use https://dpaste.org/ (pick YAML for the language) or https://www.codepile.net/ (pick YAML for the language).

dark sparrow
#

that helps a lot...

marble jackal
#

@dark sparrow It was not intended as help, just explaining the rules here

#

For multi line format use:

        value_template: >
          {% set whatever %}
          {% set even more %}
          {{ foo }}
#

You also need to check how you can refer to the state_topic. In the examples this is normally value_json but your payload is not json. I'm not completely sure how to refer to it, but I don't think data will be valid

#

And you added an additional { and } to the template which shouldn't be there

royal trail
#

Do I need to define value_json? When adding a mqtt sensor i get the values in HA but also a lot of error in logs saying " 'value_json' is undefined when rendering". The payload is: {"temperature":"30.00" } and value_template: "{{ value_json.temperature }}" is used in configuration.yaml.

marble jackal
#

value_json is the data you get in the state topic

#

I guess you need to prevent errors like that using the availability templates

#

availability_template: "{{ value_json is defined }}" might do the trick

#

But I'm not an expert on MQTT sensors

royal trail
#

Thank you! Will try!

#

Well, the fault in the log are still there and the sensordata is being read. Will try to google some more.

marble jackal
#

Are you sure the log messages are not old? Did you clear the logs?

royal trail
#

The counter for the logs ticks up every secound, same as mqtt message interval

marble jackal
#

But does is have 30 as it's state?

royal trail
#

Right now it sends random data between 0 and 50 every second. I added the sensor to a guage on dashboard and it shows values between 0 and 50 every second.

simple edge
#

Hi do you know why this doesnt work?

entity_id: '{{input_boolean}}'
state: 'on'```
#

as in it wont let me save giving me Message malformed: Entity {{input_boolean}} is neither a valid entity ID nor a valid UUID for dictionary value @ data['sequence'][2]['if'][0]['entity_id']

#

It a variable passed in to the script

#

Interesting, but this works above it

data: {}
target:
  entity_id: '{{ input_boolean }}'```
inner mesa
#

You cannot provide a template there. If you want to use variables in a condition like that, you need to use a template condition

simple edge
#
value_template: '{{is_state(input_boolean,''off'')}}'```
#

ahhhh im sorry, it just abnormal to me

#

but this didnt work

inner mesa
#

assuming that input_boolean is the name of an actual input_boolean.xxxx entity, I would replace the '' with "

#

then...

simple edge
#
        | selectattr('state', 'eq', 'on') | list| count)| str, "0")}}```
how would i do something like this?
inner mesa
#

like what?

#

{{ states.input_boolean | selectattr('entity_id', 'search', '_d_vacuum') | selectattr('state', 'eq', 'on') | list| count == 0 }}?

#

just guessing from the mess ๐Ÿ™‚

vast rapids
#

hi, how dangerous is the mode "restart" ? my automation checks if the outdoor temp is lower then the indoor. If its below HA sends a notification after them he waits 12hrs again until sunset goes down.

inner mesa
#

what do you mean by "dangerous"?

#

it's not dangerous at all

simple edge
#

Ahhh I do need to explain more, so im looking for a way to check if all booleans are false, This is way i found online states.input_boolean | select('search', '_d_vacuum') | selectattr('state', 'eq', 'on') | list| count
which give me all of vacuum boolean that are on, but when I put
{{ states.input_boolean | selectattr('entity_id', 'search', '_d_vacuum') | selectattr('state', 'eq', 'on') | list| count == 0 }} (yea i changed it to yours because you somehow from my mess got what I wanted)
into a conditional template like so >

value_template: >
  {{ states.input_boolean | selectattr('entity_id', 'search', '_d_vacuum') |
  selectattr('state', 'eq', 'on') | list| count == 0 }}```
But give me back
 `template value should be a string for dictionary value @ data['value_template']. Got None`
not sure why?
vast rapids
#

I mean, like
check temp lower then 79
if not, restart

simple edge
inner mesa
simple edge
silent barnBOT
vast rapids
silent barnBOT
inner mesa
#

well, it will fight the delay

#

the delay means nothing with mode: restart

#

again, "dangerous"?

vast rapids
#

hm I've set the delay to 12hrs bc to wait to the next sunset and send it once a day

simple edge
# vast rapids i share my code here before I screw everything up https://hastebin.com/igotojilu...

I think you have the right code, but remove the delay. The trigger will tell it when to fire and will only happen once a day being passive otherwise. mode is not going to impact unless the trigger are close together and the script run that long. An example would be checking if a light is on wait 20s and text the phone. Say the light changes in 10s. You might want to put it to restart so it only text you the light was turned off. Since it will stop in the middle of the 20s to text the phone the light would be on and wait another 20s to tell you that the light is off.

#

- platform: sun event: sunset offset: minutes: -10 this only run 1 a day

marble jackal
#

Oh sorry, should have read everything

vast rapids
#

thanks to all, hadn't considered that it will only run once

#

np ๐Ÿ™‚

civic cargo
#

My complexity radar is going off, so this may be a bad idea to pursue as a programming challenge, but I'm curious so I'm going to ask anyway.

#

I've have created a sensor which remembers the last state the heat pump was running in, so it can be turned on back to the same state.
(There is some added complexity to make an educated guess if the sensor has no data, which occurs after Home Assistant is restarted)

See code below -it's working as intended:
https://www.toptal.com/developers/hastebin/osizubujaw.php

My questions are:

  • How would I write one chunk of code to be usable for all 3 heat pumps I own?
    As it is now, I have 3 identical blocks, except the entities being referenced are changed.
    This rejects complexity which is very good.
  • Would it become significantly more complex to make a change like this?
    How many more elements would I need to create and reference to make that happen, or is this something that can be done fairly simply?
    What I'm imagineing sounds simple to explain, but I don't know what tools I'd need to implement it.
silent seal
#

And use a template to set the name with the entity_id being a input_text.{{heat_pump_id}}_state or similar?

civic cargo
silent seal
#

Bonus, you can skip all the recalculating when HA restarts

civic cargo
#

Oooo
Are those values persistent after a restart?
That's rad

silent seal
#

Yup, they are. Unless you set a default in which case it will revert to that.

scarlet sapphire
#

Hello, what did I do wrong here?

value_template:
  {{ state_attr('weather.dwd_weather', 'temperature')|float(0) > states('sensor.temperatur_10'|float(0)) }}
#

getting a AttributeError: 'int' object has no attribute 'lower'

#

I do get valid numbers for each on their own

inner mesa
#

You put float(0) inside the states() function call

#

I don't know why folks do that

scarlet sapphire
#

ahhh, I see. thank you very much. got it

ashen isle
#

hi, short question, when i run this automation (and according script): https://dpaste.org/VEsKc
i get this error:
Error: Stream already recording to /media/12:23:40-24.07.2022.mp4!
looking at the trace confirms, that the filename have not been updated with the second iteration:
https://dpaste.org/34jOE
so why {{ now().strftime("%H:%M:%S-%d.%m.%Y") }} have not been evaluated in every iteration of the loop, or what am i misunderstanding here ? thx!

marble jackal
#

now() is only evaluated once per minute

ashen isle
#

oh, ok wow thanks

#

is ther a documentation to this ?

#

and is there an alternatvie which is evaluated with a shorter cooldown ?

marble jackal
#

You could add repeat.index to your filename to make it unique

ashen isle
#

i do believe your words ... i was just wondering if i overlooked something

#

โ˜บ๏ธ

#

oh, it seems that i am facing another issue as well ... i assume that there is not more than one stream at a time allwoed from a camera

#

because now the file names di differ thanks to your recommendation with reperat.index but on the second iteration it still says Stream already recording to /media/13:00:08-24.07.2022_r1.mp4!

#

do you have an idea how to record contiguously from a camera entity with the service camera.record and save it to clips, one after another ?

marble jackal
signal dome
#

is anyone running a dynamic weather template or integration? Ideally, I'd like to see the current weather based off of the location of my phone. If it helps, I use the iOS companion app...

pastel moon
#

Hi guys! Is there a way to get number of seconds since HA was restarted? I would need that for a comparison in a condition. Normally I want to wait 15 minutes, but when restarted, and conditions are right, I want it to pass. This is what I would need to compare it against {{ (((as_timestamp(now()) - (as_timestamp(states.sensor.weather.last_changed))) | int) > (60 * 15)) }}

pastel moon
#

something like homeassistant.restart.last_changed? or is there a better way to do this please?

inner mesa
pastel moon
#

That is perfect, thanks @inner mesa !

scarlet sapphire
#

I would like to create a new sensor that depends on two others. New sensor state = if sensor a=true then state 1, if sensor b=true then state 2, if a+b true = state 3. is this something that can / should be done through a template? if yes, what would be my approach?

inner mesa
#

sure

#

you could write exactly that logic

#

I suggest just trying it

marble jackal
#

It's most easy to start with state 3, then you don't need to check if the state of the other sensor is false

inner mesa
#

and sensor states are unlikely to be "true"

marble jackal
#

For the other states

scarlet sapphire
#

yeah they are on and off, that is correct

marble jackal
#

Ah, you changed it ๐Ÿ‘๐Ÿผ

scarlet sapphire
#

it's a different scenario than yesterday and I just used true as an example to illustrate my goal but thanks for spotting it

#

it would still be a value_template, correct?

marble jackal
#

Depends on where you use the template

scarlet sapphire
#

congiguration yaml --> - platform: template sensors:

#

is where I would start

marble jackal
#

Oh wait, it was a new sensor, if you use the legacy template format it is value_template

scarlet sapphire
#

but not sure if that's the best place

marble jackal
#

And what you just posted is the legacy format

scarlet sapphire
#

yes, a new sensor, relying on two existing ones

#

it's the only format I know so far I guess, as I do have many value_template sensors in my config

marble jackal
#

Well, they are still valid

scarlet sapphire
#

I have 3000 lines of value_templates

#

so I do hope they stay valid for a while

#

so should I start with something different then?

marble jackal
scarlet sapphire
#

thanks, will try to come up with a first draft

scarlet sapphire
#

my first try, it says "missed comma between flow collection entries"

inner mesa
scarlet sapphire
#

sounds like me

#

thanks

scarlet sapphire
inner mesa
#

You quoted the sensor name in the first one, but not the second

scarlet sapphire
#

yeah missed the entry one, fixed

inner mesa
#

It's better, but a) you should use is_state(), b) you need >- to introduce a multi line template

marble jackal
#

There is also is_state(entity, state)

#

Me == too slow

inner mesa
#

and iif() for a more concise statement

scarlet sapphire
scarlet sapphire
marble jackal
scarlet sapphire
#

yeah those will come, you suggested to start with one though

marble jackal
#

From the current state I can see that he attached two door/window sensors to a window to detect how it is opened

scarlet sapphire
#

my windows has two different "open" positions and one closed

marble jackal
#

Yes, because your elifs will be easier if you already checked for this one

scarlet sapphire
#

yes, more or less (they are builtin, not attached)

marble jackal
#

But normally they are on when open, so both off them being off would mean the window is closed

scarlet sapphire
#

yeah I agree mine are a bit weird, they are "on" in the closed position coming from "magnets are connected=1" etc

marble jackal
#

Okay

#

Well, I'm off to bed, do no need to tag me the coming 8 hours or so :)

scarlet sapphire
#
  - name: fenster_buero
    state: >
      {% if is_state('binary_sensor.buro_2_auf', 'on') and is_state('binary_sensor.buro_2_kipp', 'on') == 'on' %} Fenster zu
      {% elif is_state('binary_sensor.buro_2_auf', 'on') and is_state('binary_sensor.buro_2_kipp', 'off') == 'on' %} Fenster gekippt
      {% elif is_state('binary_sensor.buro_2_auf', 'off') and is_state('binary_sensor.buro_2_kipp', 'off') == 'on' %} Fenster auf
      {% endif %}
#

like this?

scarlet sapphire
marble jackal
#

Remove the == 'on' in every statement

scarlet sapphire
#

oh yes

#

makes sense

#

thanks

#

well, I don't want to keep you away from your sleep ๐Ÿ™‚

marble jackal
#

And putting this one first was to avoid the check for off, it is not needed as you already know they are not both on

marble jackal
#

Binary sensors have two states on or off

scarlet sapphire
#

agreed

marble jackal
#

You already check in your first statement if they are both on

scarlet sapphire
#

agreed

marble jackal
#

If that results in false, it will move to the next statement

scarlet sapphire
#

agreed

marble jackal
#

If you check for a sensor being on then, and that is true, you know the other must be off

#

As you already know they are not both on

scarlet sapphire
#

ahhh, I see what you mean, thank you

marble jackal
#

That is why I suggested to start with that one

scarlet sapphire
#

that's smart, thank you

marble jackal
#

Now I'm really off to bed

scarlet sapphire
#

enjoy!

#

holy wow it works!

#

so, now I have a few of these and would like to count how many windows are in each state. what would be the best approach todo this?

fossil hearth
#
  binary_sensor:
    - name: "pir1"
      state_topic: "tele/B_Kitchen/MotionBedroom/SENSOR"
      value_template: "{{value_json.MotionBedroom.Occupancy}}"
      payload_on: "1"
      payload_off: "0"
      availability:
        - topic: "tele/B_Kitchen/LWT"
          payload_available: "online"
          payload_not_available: "offline"
      qos: 0
      device_class: motion
#

can anyone tell me why this won't work ?

#

MQT: tele/B_Kitchen/MotionBedroom/SENSOR = {"MotionBedroom":{"Device":"0x7184","Name":"MotionBedroom","Illuminance":81,"Occupancy":1,"Endpoint":1,"LinkQuality":24}}

fossil hearth
#

turns out on 1 and 0 don't need quotations

inner mesa
#

Try removing the quotes around payload_on and payload_off?

fossil hearth
#

yes!

#

is there a way to auto discovery entitties in my sonoff zigbee bridge just through mqtt ?(without ZHA)

marble jackal
fiery rock
#

How would I go about creating a key:value set of entities and their states? I can create a list of the entities using integration_entities() but I'm struggling to find a way to transform that in to key:value pairs. I've considered using map() but I don't think that is going to produce the end result I'm after as I think, if I understand it correctly, it just produces a list of the requested attributes. I also looked at dictsort() but, again if I understand it correctly, it will only sort a set of key:value pairs, not create one.

#

I then though items() might be the go but that hasn't worked out either.

marble jackal
#

do you want this (example using media players):

media_player.living_room: playing
media_player.bedroom: paused

or this:

- entity_id: media_player.living_room
  state: playing
- entity_id: media_player.bedroom
  state: paused
fiery rock
#

Hmm... I think I am after option A. Ultimately I want the template to return the key from the list that has a particular value.

marble jackal
#

you might be better of with option 2 then, you could do somethingl like {{ template_result | selectattr('state', 'eq', 'paused') | map(attribute='entity_id') | list }}

#

which would return media_player.bedroom in the example above

#

You can do the same with option 1, but the template would be more complicated

fiery rock
#

I think your example is pretty close to where I'm headed. I'll play around a bit in the Dev Tool and try and sus it out. Thanks.

marble jackal
#

You know how to work with namespaces and for loops?

fiery rock
#

Not really. I think I understand how a for loop works but I don't get what you mean by namespaces.

#
{{ p | selectattr('state', 'eq', 'Open') | map(attribute='entity_id') | list}}```
results in `UndefinedError: 'str object' has no attribute 'state'`
marble jackal
#

you need to expand p

#

you are only intereted in those with state Open?

#

you don't need the complete overview with all input_selects and their states, like above?

#
{% set p = integration_entities('input_select') %}
{{ expand(p) | selectattr('state', 'eq', 'Open') | map(attribute='entity_id') | list}}
fiery rock
#

I have 15 roller shutters I want to control for Open, Shut and Partial. I am trying to avoid the need for 45 separate automation's and figured I could compress it down to 3 by using a template to pass the id of the shutter that called for it.

#

Jumping back to your example of selectattr('state', 'eq', 'paused') how did you know to use 'eq' in there? I can't find that kind of information in the jinja2 template docs.

marble jackal
#

you can also use '=='

fiery rock
#

So I do I know what can be used in the position? Is there a list somewhere?

marble jackal
fiery rock
#

Ah.... of course ๐Ÿคฏ

marble jackal
#

@mighty ledge I just had a look at these tests, do you by any chance know why this {{ [ 3, true, '3' ] | select('number') | list }} also returns true in the result.
The same when I use select('is_number') instead of number. In that case it also includes '3' (as expected)
select('boolean') works as expected and returns only true

scarlet sapphire
#
  - name: anzahl_fenster_zu
    state: {{ states.sensor | selectattr('state', 'eq', 'Fenster zu') | list | count }}
#

tryng this as template sensor, doesn't seem to be complete yet as the sensor below this one is now getting errors

#

ah it works with a linebreak in between

#

thank you

marble jackal
#

You need to put quotes around your template if you use single line notation

scarlet sapphire
#

hah that explains it, thank you

marble jackal
#

and you don't need to lowercase and underscore your name

scarlet sapphire
#

thanks again

marble jackal
#

You can use Anzahl fenster zu, it will determine the friendly name of the sensor

#

and HA will lowercase and underscore it to use as entity_id

#

if you add a unique_id you can change it yourself in the GUI

scarlet sapphire
#

ah nice, thank you

#

you are great ๐Ÿ™‚

#

I do have template covers that have status of the cover and open/close etc. commands. since those are attached to the same windows that I am checking for opening state, what is the best practice to group those together? I would prefer to have a window entity with cover status, control and opening state of the window (not cover). is this possible?

marble jackal
#

If you want control of the covers, you need to have a cover entity, I don't think you can add the window state to that

scarlet sapphire
#

I see, so the best practice would be to align them close on the dashboard?

marble jackal
#

That'll be something for #frontend-archived but I would say a vertical-stack, or maybe custom:vertical-stack-in-card if you don't want borders between the cards

scarlet sapphire
#

got it, just wanted to check if there is another approach. thank you

silent vector
#

I'm getting

Error: dictionary update sequence element #0 has length 1; 2 is required

I googled and it may be related to target? I am trying to use a single service call to do everything. The second (hard coded Boolean) will be removed soon.
Target will default to target: {} if it is not a service call of set Boolean or switch.turn_on/off. I tested calling a service from developer tools such as calling a script with

service: script
data: {}
target: {}

And it worked.
https://dpaste.org/sg6vF

#

I'm also having a funky issue where my condition is evaluating to false when it should be true and I tested it in the template editor. The
liights variable should be true when the trigger entity id is either of the 2 and in template editor it is. The entire condition evaluates without errors I tested piece by piece and all together. For some reason it evaluates to false every time for either trigger.

marble jackal
#
  target_condition: |
    {{ {entity_id: target_data  } }}

entity_id needs to be quoted here, as it is not a variable

silent vector
#

Yep I just did that. When I noticed it said undefined.

Same trigger as before and now I get

Error: Template rendered invalid entity IDs: "{}"
marble jackal
#

I was expecting that

#

You need to put your service call in an if-then

- if: "{{ iif(target_data) }}"
  then:
    - your current service call
silent vector
#

And an else for if it's not?

marble jackal
#

or just add it to the condition

#

{{ iif(target_data) and (lights or switch or event_lights or event_switch) }}

#

why did you put the condition in a variable, and not directly in the value template of the conditon?

#

Seems a bit redundant this way

silent vector
#

Just to keep it clean, and not have a ton at the top. How would it work to add that to the condition? I'm trying to understand how it would stop the issue while still allowing the rest of the service calls to work?

marble jackal
#

yes, I was about to mention that

#

the if-then is better then. the else is optional, you can leave it empty

#

btw, you better default target_data to [] instead of {}

#

as entity_id expects a list, not a dict

silent vector
#

The condition works with the exception of the light variable. It keeps failing. Still trying to understand it because the calls are script, switch or boolean. So if I condition the call itself to having target_data then wouldn't it mess it up if it doesn't? Going to try [] now

marble jackal
#

which will be the case if target_data results in {}

silent vector
#
service: script.off_daniels_bathroom_lights
data: {}
target: {}

I was trying to do this which works when calling it from developer tools. I think I need to condition target_condition to not appear and be '' unless it has to appear

marble jackal
#

That also will not work, your service call expects data there

#

you should only perform the service call when all data for the service call is available, hence the if-then I proposed

#

I also don't fully understand the need for target_condition here

#
- if: "{{ iif(target_data) }}"
  then:
    - service: '{{ service }}'
      data: {}
      target:
        entity_id: '{{ target_data }}'
#

or even simpler

- if: "{{ target_entity in ['switch.daniels_bathroom_fan_switch','input_boolean.daniels_bathroom_fan_automation_running'] }}"
  then:
    - service: '{{ service }}'
      data: {}
      target:
        entity_id: '{{ target_entity }}'
#

then you don't need the target_data variable

silent vector
#

I just realized. I am setting {} as default but it will not be read that way because I am using target_condition and in it's current form it won't even read {} properly as it reads entity_id: {} the goal would be for that line to just '' when it's not needed. I am trying to key the entity_id. The purpose of setting {}```` to default was so that it would be `target: {}` when it was not needed. But it's not going to do that the way I have it setup. If I could set that to `target: {}` and then when needed bring in `entity_id: x it would work? I was leveraging an automation Petro helped me with a while back where he variablized the key.

#

https://dpaste.org/w550O
I was trying to do all of this in a single service call. The service_data variable is what he used

#

Making everything a variable

marble jackal
#

this condition will also run in error when the trigger is your event trigger or the home assistant start trigger:

  - condition: template
    value_template: >-
      {{ trigger.entity_id == 'sensor.daniels_bathroom_fan_off' and
      trigger.to_state.state == 'True' }}
silent vector
#

I see it's not possible to do this

{{ {iif(target_data != '','entity_id:',''): target_data  } }}
``` Without a `:`
#

I'll use if-then Any idea why the lights variable in the condition is not working

marble jackal
#

The fact that the GUI completely messed up your templates also doesn't help

silent vector
#

Yes I really hate that with a passion.

marble jackal
#

but I kinda see why you need an empty target: now, you also have a script as service, which is perfectly valid with an empty target

marble jackal
silent vector
#

Yes that's what I was aiming for. Just use an empty target when it's not needed. Then I wouldn't need if-then and just a single service. But it doesn't appear possible to make the key just not be there. As soon as entity_id is there it messes it up.

marble jackal
#

you can replace this:

  target_data: >-
    "{{ iif(target_entity in
    ['switch.daniels_bathroom_fan_switch','input_boolean.daniels_bathroom_fan_automation_running'],target_entity,'{}')
    }}"
  target_condition: |
    {{ {entity_id: target_data  } }}
silent vector
#
service: script.off_daniels_bathroom_lights
data: {}
target: 
  entity_id: []

Worked hm

marble jackal
#

with:

  target_condition: |
    {{ {'entity_id': target_entity } if target_entity in ['switch.daniels_bathroom_fan_switch','input_boolean.daniels_bathroom_fan_automation_running'] else {} }}
#

that also works because an empty list is a valid target

#

an empty dict is not

silent vector
#

It worked!!!!!

#

What you did ^

#

Now the question is why is the light variable broken in the condition or something messed up but isn't because I validated the entire thing in the template editor.

marble jackal
#

This one:?

  lights_script: >-
    {% if (now() >= today_at('05:50') and now() <= today_at('18:30')) %}
    script.morning_daniels_bathroom_lights {% elif (now() >= today_at('18:30')
    or now() <= today_at('05:50')) %} script.night_daniels_bathroom_lights {%
    endif %}
silent vector
#

This

condition: >-
    {% set lights = trigger.entity_id in
    ['binary_sensor.daniels_bathroom_presence_detector','binary_sensor.daniels_bathroom_motion_sensor_1_home_security_motion_detection']
    and lights_status != set_lights %} {% set switch = trigger.platform ==
    'event' and trigger.event.data.command == 'Away' and switch_status !=
    set_switch %} {% set event_lights = trigger.platform == 'event' and
    trigger.event.event_type == 'automation_reloaded' or trigger.event ==
    'start' and states('binary_sensor.daniels_bathroom_presence_detector') ==
    'off' and lights_status == 'on' %} {% set event_switch = trigger.platform ==
    'event' and trigger.event.event_type == 'automation_reloaded' or
    trigger.event == 'start' and states('sensor.daniels_bathroom_fan_off') ==
    'True' %} {{ lights or switch or event_lights or event_switch }}
#

GUI makes this look awful.

marble jackal
#

I already gave you the solution for that ๐Ÿ˜›

#

But define not working

silent vector
#

Not working as In when the trigger is one of those sensors it's not working. It's failing. When the trigger is one of those sensors and I can visually see the variables light_status and set_lights are not equal it should pass. It isn't.
I tested it with this. How do you set a trigger.entity_id or trigger.platform variable in template editor? I remember you showing me once but I didn't take note of it. I have to remove the . or it doesn't work.
https://dpaste.org/brOWq

#

Then I just asked for {{ lights }} and it was true.

marble jackal
#

{% set trigger = { 'entity_id': 'binary_sensor.daniels_bathroom_presence_detector', 'platform': 'state' } %}

silent vector
#

Perfect that will be much easier to test these big templates now

marble jackal
#

you can also just open the trace, and copy the entire trigger json from there

silent vector
#

Bug in the app as I couldn't download trace for some reason. It kept crashing. Had to open a Browser

marble jackal
#

I didn't need the trace, it was just a tip to copy the trigger object from the trace to devtools > template

honest narwhal
#

Hello, I have a weird one. Template sensor is derived from the state of an input number. This sensor has worked for several months. Today it is unavailable despite the input number still being populated. Not sure how to even troubleshoot this one as it should just work. The template sensor is:

template:
  - sensor:
      - name: "Electricity Demand Max"
        unique_id: electricity_demand_max_sensor
        unit_of_measurement: kWh
        state: >
          {{ states('input_number.electricity_demand_max') |float(0) }}

and {{ states('input_number.electricity_demand_max') |float(0) }} in the template editor returns 1.422 as expected where as {{ states('sensor.electricity_demand_max') is unavailable. Is it possible the template sensor has become unavailable because the input number has been static for a couple of weeks?

silent vector
#

Oh I see

marble jackal
#

are you sure it didn't create a 2nd version (sensor.electricity_demand_max_2)

tepid onyx
#

I'm trying to list entities from a group:
this works using jinja filters:
{{ expand(state_attr('group.alllights', 'entity_id')) | rejectattr('entity_id', 'in', ['light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) | map(attribute='entity_id') | list }}
But I can't seem to get a for loop to work:
`{% for x in expand('group.alllights') | rejectattr('entity_id', 'in', ['light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) | map(attribute='entity_id') -%}

  • {{ x }}
    {% endfor %}`

What am I doing wrong

#

The for looop work in the yaml template editor but when trying to use it with e.g. light.turn_on it throws an error in the "Dev Tools | services"

marble jackal
#

@tepid onyx why do you want a loop? The first one creates a perfectly valid list for you to use in your service call

tepid onyx
#

I'm using the first one but I haven't used for loops for ages now I can't get it to work...

#

having a brain fart what am I missing

marble jackal
#

you don't have to use the loop

#

why do you want to use it?

#
- service: light.turn_off
  target:
    entity_id: >
      {{ expand(state_attr('group.alllights', 'entity_id')) | rejectattr('entity_id', 'in', ['light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) | map(attribute='entity_id') | list }}
honest narwhal
tepid onyx
marble jackal
#

because HA will do whitespace control, and put them all in one line:
- light.1 - light.2 - light.3

#

that's not valid

#

you need to provide a list like this if you want to use a template [ 'light.1', 'light.2', 'light.3' ] which is what the first template does

#

I don't understand why you are making it so hard for yourself

#

If you want to use a loop, you need to use a namespace, and add the values to that

#
{% set ns = namespace(lights=[]) %}
{% for x in expand('group.alllights') |  rejectattr('entity_id', 'in', ['light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) |  map(attribute='entity_id') -%}
  {% set ns.lights = ns.lights + [ x ] %} 
{% endfor %}
{{ ns.lights }}

Which will give the exact same result as your first template

edgy umbra
#

Is there a easy way to change the day in dutch? Now it prints Monday 25/07 instead of Maandag 25/07

#

"{{ now().strftime('%A %d/%m') }}"

marble jackal
#

I'm creating a combined weather entity, which combines the forecast of multiple weather entities

mighty ledge
#

lemme take a look

#

so

#

first thing I notice is taht you do this

#
{% set datetimes =  (expand(entities) | map(attribute='attributes.forecast')| list)| sum(start=[]) | map(attribute='datetime') | unique | sort | list %}
#

pretty sure sort is already a list

#

if it's a generator, you'd just want to declare that in the for line

#

otherwise, I think it looks good

marble jackal
#

okay, thanks

mighty ledge
#

well, whats the iif doing for iif(pp)?

#

seems odd to me

#

i don't use iff

#

so, if you're just turning into true/false, you can optimize that by just doing if pp, and emtpy list in an if statement is essentially false.

#

Ah yeah, that's all that's doing. So just remove the iif() around the pp, no point

marble jackal
#

changed the last line in the for loop to {% set ns.forecast = ns.forecast + [ dict(f.items() | list | selectattr('1')) ] %} to remove the none items from the dicts (if there is only one weather entity left which eg doesn't provide wind_speed)

#

and removed the iif()

mighty ledge
#

yeah i usually do that part differently

#

whenever i'm adding dynamic things, I'll use namespace and add items to alist

#

but it ends up being moreif statements

silent vector
#

What would a combined weather entity allow you to do differently? As in what are the use cases, sounds interesting. Also pretty cool to see 2 legends working together!!

mighty ledge
#

I think he just want's to know what each one is saying and get a 'crowd sourced' result using a bunch of weather entitites

marble jackal
#

I especially want to always have a temperature and forecast and such available

silent vector
#

I may have some use for something like this to clean up what I do with pulling in weather data. Definitely interested in seeing the final yaml if possible @marble jackal and the template for the sensor.weather_entities

marble jackal
#

So if I combine 3, I think 1 of them should be available ๐Ÿ™‚

silent vector
#

Yep That's what I'm thinking I end up having to have a bunch of extra code to ensure there's at least something working. By doing a bunch of "or".

marble jackal
#

the template sensor is basically only there to have a list of entities excluding the combined weather entities themselves, so the data of the combined weather entity is not included in itself

silent vector
#

I see. Very interesting. Always something to learn. I always thought about combining weather data but didn't know how or if it was possible. But anything is possible it seems with Jinja.

silent vector
#

Thank you!.. hm invalid response?

marble jackal
#

yeah, I get the same

#

but I copied it directly from my browser screen

#

you can navigate to it from the link in my profile ๐Ÿ™‚

silent vector
#

Yep i found it. Thanks again.

silent barnBOT
winged coral
#

Hi guys I'm having some trouble with a rest sensor and templating the resulting values. Currently I get one sensor Salah times where the value is string with all the timings' json, and Fajr, Dhuhr, Asr, Maghrib and Isha templated entities just show up as unknown. How would I change my config (linked below) so that the individual times are populated and I suppose get rid of the overarching Salah Times catch all entity?

https://www.toptal.com/developers/hastebin/juvecasomu

silent seal
#

Are you sure the Salah times sensor actually has the ID of sensor.json_time? It seems unlikely

mighty ledge
#

so, just add json_attributes_path: $.data.timings

winged coral
#

above line 6?

#

@mighty ledge

mighty ledge
#

doesn't matter, anywhere in the configuration for the rest sensor

#

not the template

paper hazel
#

Why is the first one not working - If I understand the docs correctly, the first syntax is better to use if values are not available during boot etc.```
{{ state_attr('cover.left_garage_door', 'last_updated') }}

{{ states.cover.left_garage_door.last_updated }}

inner mesa
#

it's not an attribute

#

it's a property of the state object

#

there's no alternative to the second one

paper hazel
#

Thank you for explaining - much appreciated! Everyday I learn a little more... ๐Ÿ™

rain grove
#

Hi, I think templates are the right tool for my task but I need some help understanding time-based rules. I have a computed temperature difference between 2 other values already, called deltatemp. I want to cycle a zigbee on or off based upon tolerance of the deltatemp but want to 'dampen' it over time with this logic:

#

deltaT > 1.5 for 120seconds = ON
deltaT < -0.5 for 120seconds = OFF

#

any ideas?

#

I need some sort of rolling time evaluation and I can't quite wrap my head around it (i'm a python guy)

paper hazel
#

Why not two numeric triggers and call the zigbee cycle in the actions?

#

Are alternatively, perhaps two binary template sensors for the below and above values and use that as triggers. state on for x minutes/seconds

winged coral
winged coral
rain grove
#

so how would I use something like

#

{{ states('sensor.deltatemp') > '1.5' }}

inner mesa
#

that's unlikely to work ๐Ÿ™‚

#

since states are strings, and you've made the number 1.5 a string, too

rain grove
#

it returns false

inner mesa
#

no doubt

#

{{ states('sensor.deltatemp')|float > 1.5 }}

rain grove
#

if i change to < it returns true, the single quotes help right the format

#

ok

inner mesa
#

comparing a string with a string when you want a numeric comparison is unlikely to be what you want

rain grove
#

ahh, i see, thanks

#

so how can i use that for a time value calculation?

inner mesa
#

use what?

#

that looks like a temperature differential?

rain grove
#

yes

inner mesa
#

what does it have to do with a "time value calculation"?

rain grove
#

it's a calculation for a custom cooling unit (think refrigerator) and I'd like it to not cycle too frequently, so if it passes that threshold for say 2mintes, then cycles off

inner mesa
rain grove
#

I will look into, thanks much!!!

#

I'm not I understand this portion, "and fires if the value is changing from above to below or from below to above the given threshold" The example uses 17 and 25 as 'above' and 'below' values

inner mesa
#

it triggers when it crosses one of the thresholds that you established

rain grove
#

so 16 to 18 is above

#

but 24 to 26 is not above?

inner mesa
#

yes

rain grove
#

ok

inner mesa
#

it crossed out of the range, so no

#

above 25 isn't below 25

rain grove
#

I see

#

so the logic for this automation example would be turn on switch when above value and turn off switch when below? or is that not stated explicitly in this example?

inner mesa
#

if you want that, you should use two triggers to differentiate the two different events

#

specifying both above and below is providing a range that will cause a trigger when the value transitions into that range

rain grove
#

np, so one to turn on, with only above and another to turn off when below?

inner mesa
#

yes

rain grove
#

awesome, ty

visual matrix
#

I'm trying to use a sensor attribute as a url for an attachment but I can't get the correct format to show the picture in the notification

#

attachment: url: "${states['sensor.overseerr_movie_requests'].attributes.last_request_poster}"

inner mesa
#

that looks like Javascript

visual matrix
#

I tried so many combination

inner mesa
#

this channel is for Jinja templates

visual matrix
#

Is it possible to show the link in jinja to work with the attachment url?

#

something like url: {{ states.sensor.overseerr_movie_requests.attributes.last_request_username }}

inner mesa
#

no idea

#

I don't really know what you're doing

visual matrix
#

The sensor attribute is returning an URL which show an image, I'm using that to be shown in the notification data

#

But i'll keep digging

#

thanks tho

rain grove
#

Hey @inner mesa like this?

silent barnBOT
inner mesa
#

that's not similar to what you had above

#

you want to trigger if the sensor value becomes exactly -1 and stays there?

#

I pointed you to a numeric_state trigger and you've used a state trigger, rarely a good choice for a value crossing a threshold

fiery rock
#
{% set q = expand(p) | selectattr('state', 'eq', 'Open') | map(attribute='entity_id') | list %}
{{ t[0] }}```
Works fine so long as one of my `input_select`'s is displaying `Open` but, obviously, if none of them are then the list is empty which leads to `UndefinedError: list object has no element 0`.
#

What can I do avoid this error? I was thinking of defining the q first with a single entry in the list and then appending the list with the above template thereby ensuring the list always has an element but I realise this wont work as I'll then want to call t[1] which will just give me the same error except for element 1.

#

I think I solved it. I thought I'd try defined() and it works okay.

{% set q = expand(p) | selectattr('state', 'eq', 'Open') | map(attribute='entity_id') | list %}
{% if q[0] is defined %}
      {{ q[0] }}
{% endif %}```
deft timber
#

You could also use {{ q[0] | default() }}

fiery rock
#

That is probably the better option. Thanks.

silent vector
#

Anyone know why on automation reloaded and the presence detector is on which needs to be off to be true in the service variable it keeps evaluating to true.
https://dpaste.org/9AGDh

charred dagger
#

It probably reads if (platform = event AND event = reload) OR (event = start AND presence = off). Add some parentheses where you want them instead.

silent vector
#

I tried. Adding it around the and ( presence = 'off' ) but it didn't work.

#
    {% elif trigger.platform == 'event' and trigger.event.event_type == 'automation_reloaded' or trigger.event ==
    'start' and (states('binary_sensor.daniels_bathroom_presence_detector') == 'off') %} 
charred dagger
#

You'd want if platform = event AND (event = reload OR event = start) AND presence = off, I guess.

silent vector
#

I'll try that.

#

That worked thank you!

charred dagger
#

Do you understand why?

#

The first method would be true if the platform was even and the even was reload. But it would also be true if the event was start (regardless of platform) and presence was off.

charred dagger
silent vector
#

Yes I remember Petro schooling me on pemdas (order of operations). After being schooled a few times lol I usually get it right figuring out where to add parenthesis just not this time.

charred dagger
#

You can replace states('binary_sensor.daniels_bathroom_presence_detector') == 'off' with `is_state('binary_sensor.daniels_bathroom_presence_detector', 'off')' by the way. That adds some protection against errors in some cases.

silent vector
#

Which errors would it cause?

charred dagger
#

The order of boolean operations (and/or) is always weird. And can also vary from language to language. I always put parentheses just to be sure.

#

In your case states( likely won't cause any problems, but in some cases if the entity doesn't exist you'll get weird errors. It's good to just get into the practice of using is_stateIMO.

silent seal
#

I much prefer is_state purely for the graceful fail

silent vector
#

Hm that's interesting. I never saw that but it's good to know. I just thought it was about preference to use either one. Not that one had a graceful fail vs the other not having it.

silent seal
#

The problem with an == check is if the types do not match, then it throws a wobbly. And if your entity is unavailable, then the type is a string regardless of what else it may have been before.

silent vector
#

Interesting thank you for the explanation

silent seal
#

Though usually states are strings, but attributes may not be, hence is_state_attr also being a nice function.

marble jackal
#

all states are strings, attributes can be a native type

paper hazel
#

I was pointed here to request assistance with cleaning up this template trigger. Currently it is working, but I understand this can be done more streamline. I would appreciate assistance on how to do this better that I can apply it in future ideas too.```
trigger:
- platform: template
value_template: >-
{% set t = now() %} # To make it update every minute
{{ (states | selectattr('entity_id','in',
state_attr('light.group_outside_security_lights','entity_id')) |
selectattr('state','eq','off') | list | count) >= 0 }}

silent seal
#

The time pattern should help you automatically update every minute ๐Ÿ˜‰

paper hazel
#

I'm trying to steer clear of adding a "helper" entity and using a template directly in the trigger

marble jackal
#

I read that you added the now() to have it evaluate every minute, but that makes no sense, it will already update on state changes

silent seal
#

Thatโ€™s why I suggested the time pattern trigger to update every minute, if thatโ€™s what you actually need/want

paper hazel
marble jackal
#
  trigger:
    - platform: template
      value_template: >-
        {{ expand('light.group_outside_security_lights') |
        selectattr('state','eq','off') | list | count >= 0 }}
silent seal
#

The template does not do actions

marble jackal
#

And you can simply expand a group

#

No need to iterate over all states

paper hazel
paper hazel
paper hazel
paper hazel
silent seal
#

Groups are what you want. Take a look at how template sensors work and update usually, and then look through the triggers for more info ๐Ÿ™‚

paper hazel
#

Thank you - I think I have an okay understanding of those two. What I'm still getting my head around is the whole iterating through groups etc... I'm forcing myself to familiarise myself with jinja

marble jackal
#

In case you want it to update on state changes of all group members, this will work

  trigger:
    - platform: template
      value_template: >
        {% set entities = state_attr('light.group_outside_security_lights', 'entity_id') %}
        {{ expand(entities) |
        selectattr('state','eq','off') | list | count >= 0 }}
silent seal
#

The good news about Jinja, is itโ€™s very similar to many other templating languagesโ€”Twig, Blade, Liquid, etc.

marble jackal
#

However, it will not trigger again if a second light turns off

paper hazel
#

@marble jackal You are the man! I removed the '=' and the forgotten bracket after count and it is wokring a charm now!```
- platform: template
value_template: >-
{{ expand('light.group_outside_security_lights') |
selectattr('state','eq','off') | list | count > 0 }}

marble jackal
#

The delay in your version was caused because your were irritating over the entire states object, and that is only done once a minute

paper hazel
marble jackal
#

states.domain is limited to once per 10 seconds

#

If I'm correct ๐Ÿ˜…

#

At least both are limited

paper hazel
#

Nevermind - saw you just answered this ๐Ÿ™‚

silent seal
paper hazel
#

I absolutely love the template editor - Spend a lot of time there trying to figure stuff out. And as always the help here has been overwhelming - I dont think it gets said enough, the HA community is brilliant and the help here invaluable. ๐Ÿ™

silent seal
#

Agreed, so many helpful folks, so many ideas to steal, the limit is the time in which to implement the ideas, and the cash to spend on the cool gadgets ๐Ÿ˜„

paper hazel
#

All true, I keep a "to-do" list on Google keep of ideas to implement. Lack of time is traded off against sleep, unfortunately the last one is the biggest hurdle, not to mention the maintenance as these gadgets age/breaks... ๐Ÿ˜‚ That said, I have been building on my instance for a few years building it up, and I'm very very close to having everything I need on HA - Only a few lights & PIRs left HW wise...

#

Fingers crossed - I'm still running on a RPi and it is coping...

silent seal
#

I just hope you have backups off the device, and preferably arenโ€™t running on an SD card. If not, I recommend your next projects are: backups get copied elsewhere ASAP, and then get it booting off an SSD.

paper hazel
paper hazel
thorny snow
#

Hi! I'm trying an automation sending a message if the outside temp is less than 1 degree below inside temp. I am using temp reading from the ventilation unit which is updating values precise and often. I used a binary sensor evaluating temperatures which then triggers the automation which sends notification. It makes me nuts as it is going "the wrong way": If it's hot, it states Off... I just want to understand why

  - platform: template
    sensors:
      outdoor_temp:
        device_class: heat
        friendly_name: AuรŸentemperatur
        value_template: "{{(states.sensor.vallox_outdoor_air.state) | float > (((states.sensor.vallox_extract_air.state) | float )-1 )}}"
silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

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

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

marble jackal
thorny snow
#

Great, thanks, I'll do that. However, I am mainly adding entities with dropdown menu of file editor. Is there a way that this directly adds "correctly" with states()?

silent seal
#

If youโ€™re typing in the template editor (where itโ€™s easy to test your automation), it definitely auto completes

silent barnBOT
#

When working with templates, don't forget:

  • You can test them in Developer tools -> Templates
marble jackal
#

But if it shows on when it should show off and the other way round, I would suggest to change > into < ๐Ÿ˜…

thorny snow
#

Absolutely! However I'm just starting and I like to understand what happens so this is my try. However, I never stepped over the template editor. Can it also be used to save templates or only live testing?

silent seal
#

Itโ€™s only for testing, you save them by putting them in the place you need them (automation/script actions, template sensors, etc.)

#

Itโ€™s also useful for debugging

silent barnBOT
#

Paste the following code into the Template Builder in Developer Tools to list all sensors and their names:

{%- set domains = [states.sensor] %}
{{ \"Entity ID\".ljust(50) }} {{ \"Entity Name\" }}
{%- for domain in domains %}
{% for item in domain %}
{{ item.entity_id.ljust(50) }} {{ item.name }}
{%- endfor %}
{%- endfor %}
silent seal
#

Things like that can be really useful when youโ€™re poking around looking for information.

thorny snow
#

Perfect. Another help-yourself tool. Thanks a lot ๐Ÿ˜† ๐Ÿ™

silent seal
#

HA is a lot of DIY. But if you can show what youโ€™ve tried then it inspires other users, and makes it a lot easier to help you.

thorny snow
#

Don't get me wrong. I really love HA, it's great how easy it to create even complex automations. But when it comes to some lines of code I am just at the beginning of a huge and steep learning curve :-D simple double checking tools are great then.

silent seal
#

Youโ€™ll get there.

#

And if youโ€™re ever worried about something youโ€™re doing, do a backup first, download it to another device, and then just do it anyway

#

Worst thing that can happen is you end up restoring the backup you made just before you changed it all.

#

I have lots of files floating around with bits of old snippets in that I was trying out as a way to help myself in the future. Though, my HA config is in git as well which is the next step up ๐Ÿ™‚

rain grove
inner mesa
#

That's great!

thorny snow
#

Hey all, got sent here from #automations-archived / #general-archived the problem here would be im having a hard time and huge mess creating it all, ang got said that there is way to much stuff involved like to much booleans, so someone here would be able to help -> So, im at work for at least two hours boolean on, i leave work ( zone ) , booolean is on, send notification, boolean is of, second boolean of leaving work is on, i arrive closer to home ( zone ) , second boolean is on, send notification turn secoind boolean off, i arive at home, noone is home, send notification
this and like another 5-7 automations like this

silent seal
#

Trigger-based template sensor for "I was at work for two hours" ๐Ÿ™‚

thorny snow
#

i think im getting alergic to links with docs ๐Ÿ˜„ but ill try to understand this one ๐Ÿ™‚

#

so its a trigger, like in automations the first part in GUI ?

silent seal
#

You should always start by reading the docs and trying things. It's much easier to help someone who says "I am trying to do X, I tried to do this with Y <link to code>, but I'm struggling with Z/it's not working in this particular scenario"

#

That one is indeed a trigger, very similar to the automations in the GUI.

#

But there are also template sensors and template binary sensors.

thorny snow
#

my problem with docs is im understanding like 5% of the stuff there, and thats on a good day, the it's been written, its just unusable for me, i got only that its a trigger, thats all...

silent seal
#

Try reading the whole page, and looking at the examples. You can copy the template parts and put them in the developer tools and see what they output.

thorny snow
#

the simples way here would be wait for trigger, super easy and really doable in GUI only it doesn't work when im working on HA ...

#

This is an advanced feature of Home Assistant. Youโ€™ll need a basic understanding of:

Home Assistant architecture, especially states.
The State object.

silent seal
#

You'll need that for automations in the long run too ๐Ÿ˜‰

thorny snow
#

and thats where it ends, first two sentences

silent seal
#

Easier to get started now, even if all you understand is that a boolean or binary state can be on and off right now.

thorny snow
#

i've wrote it here like dozen times, its like i have to learn everything in HA just to make a automation and it all in the robotic text of docs, impossible in my case...

#

p.s. nothing against people who help here !!!!!! ๐Ÿ™‚ i get it, i have to know each and everything in HA and YAML and so on.

silent seal
#

You definitely need to start reading the documentation and googling the terms you don't understand. The HA docs have a search feature which is very helpful, as are the links in the docs and the sidebar.

#

Both the Home Assistant Architecture and the state object link you to their own pages there to read through.

thorny snow
#

went back to #general-archived im just done here for today, but still thanks for trying

fiery rock
#
{% set q = expand(p) | map(attribute='friendly_name') | list %}
{{ q }}```
returns 
```[Undefined, Undefined, Undefined]```
Is `friendly_name` not considered an attribute?
inner mesa
#

it's an attribute, but not that kind of attribute ๐Ÿ™‚

fiery rock
#

๐Ÿ˜† of course.

inner mesa
#
{% set p = integration_entities('input_select') %} 
{% set q = expand(p) | map(attribute='attributes.friendly_name') | list %}
{{ q }}
#

and that's easier written like this:
{{ states.input_select | map(attribute='attributes.friendly_name') | list }}

#

and even easier:
{{ states.input_select | map(attribute='name') | list }}
which will use "name" if it's defined, and friendly_name if not

#

(I think)

fiery rock
#

Is "name" the full name of the entity, ie input.select.kitchen_shutters? Or would it just return kitchen_shutters?

#

Because it just returns the friendly_name when trying in the Dev Tools.

#

Additionally, what is considered an "attribute" in the first example?

#

@inner mesa Can I buy you a (virtual) coffee or beer or something? You have been very helpful with all my question and I'd like to thank you somehow.

inner mesa
#

no coffee or beer needed, happy to help. Thanks for the offer, thoguh

#

Is "name" the full name of the entity, ie input.select.kitchen_shutters? Or would it just return kitchen_shutters?

#

neither. input_select.kitchen_shutters is an entity_id and kitchen_shutters is the object_id, which is the part of the entity_id after the "."

#

the name and friendly_name are things that you assign

fiery rock
#

Got you.

inner mesa
#

"attribute" in that statement means "property of a state object"

#

<that last part is more complicated that I made it sound>

fiery rock
#

I think I get it though. So by using map(attribute='attributes.friendly_name') I'm passing the dict key of "attributes" of which I want to extract the "friendly_name"

#

The attribute I want to map is "attributes" and from that I want to extract the friendly_name.

#

Am I close to understanding?

inner mesa
#

I think they actually generate the entire set of "attributes.xxx" for each key in the dict and make those available as "attributes" for the purpose of Jinja, rather than it being a general purpose way to index into dicts

#

but I haven't looked into the implementation

#

for instance, I don't know if map(attribute='attributes.foo.bar') is valid

inner mesa
#

I'm now puzzled by how attributes work in Jinja (at least as implemented by HA). Take these statements:

{% set data={'foo':{'bar': 'blah'}} %}
{{ data.foo }}
{{ data['foo'] }}
{{ data|attr('foo') }}

The second and third lines both return what I would expect: {'bar': 'blah'}
The third returns UndefinedError: 'dict object' has no attribute 'foo'

silent seal
#

Huh, that's unexpected for me too

inner mesa
#

jinja-filters.attr(obj: Any, name: str) โ†’ Union[jinja2.runtime.Undefined, Any]
Get an attribute of an object. foo|attr("bar") works like foo.bar just that always an attribute is returned and items are not looked up.

silent seal
#

Yes, that's what I'd expect. I'll grant I'm a PHP dev and especially thanks to MongoDB am very used to "abuse the code, it'll return what I want", but I really would expect the last one to work

inner mesa
#

the terminology in the Jinja docs is pretty loose and doesn't usually make a distinction:

You can use a dot (.) to access attributes of a variable in addition to the standard Python getitem โ€œsubscriptโ€ syntax ([]).

silent seal
#

I think I've run into something like this before with the attr where I was trying to get something and HA wasn't working the way the jinja docs said it should

inner mesa
#

it doesn't look like I can create attributes in my own data structures, just items

#

then they talk about "elements":

#

You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too. What attributes a variable has depends heavily on the application providing that variable.

silent seal
#

How odd. It reminds me of whenever I want to create an array, and I have to wrap it in a dictionary first ๐Ÿคช

inner mesa
#

then there's this:
{{ data.items()|selectattr('0', 'eq', 'foo')|map(attribute='1')|first }}

#

-> {'bar': 'blah'}

silent seal
#

I think it's 1am talking, that seems somewhat nonsensical

inner mesa
#

pretty sure I learned it from petro. It's quite magical

silent seal
#

I mean, I understand how it works

inner mesa
#

but it looks like the only way that I can "create" attributes from my own data structure for use with those functions

silent seal
#

But a good chunk of my brain is saying "that seems wrong"

elder moon
#

is there a template equivalent of "for:" trigger option?

#

basically i want to make a wait_template, where the automation will not only wait for a couple of states to be off, but stay in this state for a longer bit of time

marble jackal
#

Yes, use the last_changed object of the entity

#

But it might be easier to group all the entities, and use the state of the group

#

It will be off when all members are off

#

You can then use a state condition on the group and use for:

#

Oh, wait, not in a wait_template

#

But at least it makes your template easier, as you only have to take one entity into account

elder moon
#

ahhh, ok this is a good idea but not as universal as ive been hoping for - ive got a couple of automations where i would like to add motion sensing and this last_changed should work fine for those, but ive been hoping for a solution which i could also use for numeric states (so wind speed is lower than... for on hour)

marble jackal
#

No, that won't work. You can only get that working using a template binary sensor

#

Which is on when your numeric state is below ...

elder moon
#

hmm not good

#

ok maybe i will try to do the numeric_state thing without the "for:" thing, but instead will do some kind of hysteresis by increasing the number

#

also just for the record i think that "wait for trigger" could work if i would only be waiting for one numeric_state

#

hmmm hold on...

#

recently HA added an option to use a template as a trigger?

marble jackal
#

Not recently, the template trigger had been a thing for as long as I know

elder moon
#

ahh, dont mind me, i doesnt seem to be possible to use "for:" with template triggers either, at least not through UI

marble jackal
#

However, the caveat with it a trigger is that it will only will if it changes from false to true.

#

No, you can't use for: with template triggers, also not in YAML

#

Only with state, and numeric state

#

Oh and device

elder moon
#

the thing is that those weather sensors often give random, odd readings and thats what i want to avoid here

marble jackal
#

This is the first time you mention weather sensors, what are you trying to achieve here

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.

marble jackal
#

Oh wait, wind_speed, missed that

#

Really your only solution here is too create a binary sensor which is on if the wind speed is below your threshold

#

You can then use that both for triggers and conditions

silent seal
#

There is a threshold helper (integration) which can do exactly that. You can set it up in the UI under helpers or in YAML

marble jackal
#

Ah, okay, the template binary sensor is not the only option ๐Ÿ˜…

silent seal
#

It is not, the threshold is just different way to do it ๐Ÿ˜„

#

It's basically a template binary sensor with special fields so you don't have to use Jinja

marble jackal
#

Yeah, wasn't aware it existed (should have known though)

strange geode
#

Hey there, im really trugling with a telegram template.

im trying to include a maps location with cordinates and a message in one.

#

it only send the maps link but dosent attached the message

fossil venture
#

There's nothing wrong with your templates. Perhaps that is how the Telegram send location service works. You could ask in #integrations-archived

strange geode
#

okay strange. because map is sending finde trougt, but no msg ๐Ÿ˜ฆ

mighty ledge
#

why aren't you creating a notifier

#

when notifying someone you should be using the notify service

scarlet berry
#

hi, im not sure if im in the right section but can someone help me with my configuration.yaml

i made a sensor to detect when my phone is connected via bluetooth to a certain mac address.
the sensor works fine everytime, i can see it in my dashboard. the only issue is its getting flagged as an invalid config, And i dont understand why because its working like i said.

this is the error

Configuration invalid!

Integration error: phone_connected_to_PC_Speaker - Integration 'phone_connected_to_PC_Speaker' not found.
Integration error: value_template - Integration 'value_template' not found.
Integration error: friendly_name - Integration 'friendly_name' not found.
Invalid config for [binary_sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 83).

silent barnBOT
mighty ledge
#

compare it to your binary_sensor someone_home

#

does it look remotely similar?

scarlet berry
#

lol no i was just looking at that....i think you can tell i copy and past my code...im just confused as to why it works

mighty ledge
#

because the last 3 lines are correct for the new template style

#

these 4 lines are doing nothing and shouldn't be in your config:

- sensors:
phone_connected_to_PC_Speaker:
friendly_name: "Phone Connected To PC Speaker"
value_template: ### Phone Connected To PC Speaker ###
scarlet berry
#

ok that fixed it....thanks soo much.

shrewd epoch
#

hi guys!

silent barnBOT
mighty ledge
#

looksl ike your entity_id is wrong for sensor.humidifiersb

shrewd epoch
#

hum

mighty ledge
#

you added _json for some reason

#

when the name of your rest sensor is Humidifiersb

shrewd epoch
#

oh

mighty ledge
#

which would make the entity_id sensor.humidifiersb

#

also, you should be using state_attr

shrewd epoch
#

'{{ states.sensor.humidifiersb.attributes["humidity"] }}'and so on then?

mighty ledge
#

instead of states.xxx.yyy.attributes

#

'{{ state_attr("sensor.humidifiersb", "humidity") }}'

shrewd epoch
#

whats the differance?

#

the first one is just if the module got different sensors and not just attributes right?

#

and the last one if the sensors just got attributes and no more sensors

mighty ledge
shrewd epoch
#

oh ok

#

do you know how i can make all these sensors and build a devices of them inside Home assistant, is that even possible?

#

and btw it worked, thanks you sir!

mighty ledge
shrewd epoch
#

Oh, would be a cool feature

mighty ledge
#

I don't think it'll get added. It's been up as a discussion before

shrewd epoch
#

oh ok, just for templates would be helpful to merge some sensors to a device

buoyant sapphire
#

trying to get the delta between a certain input_datetime variable and todays date. not sure what im doing, but maybe someone can help me:

#this one results in "1", while the input is todays date (-> expected would be 0)
{{ (as_timestamp(states("input_datetime.staubilastrunwohnzimmer")) - as_timestamp(now().date()) ) | timestamp_custom("%j")| int }}

#this one results in "364", while the input is yesterday (-> expected would be 1)
{{ (as_timestamp(states("input_datetime.staubilastrunflur")) - as_timestamp(now().date()) ) | timestamp_custom("%j")| int }}

#this one results in "363", while the input is the day before yesterday (-> expected would be 2)
{{ (as_timestamp(states("input_datetime.staubilastruneingang")) - as_timestamp(now().date()) ) | timestamp_custom("%j")| int }}
inner mesa
#

you want the number of days?

buoyant sapphire
#

yes sir

inner mesa
#

that's much easier

#

as TheFes will now demonstrate...

buoyant sapphire
#

๐Ÿ˜„

marble jackal
#

Take the highest value now() and subtract the lower value from it, instead of the other way round

buoyant sapphire
#

tried that and failed. that gave me very funky results. but let me try again.

inner mesa
#

{{ (now() - states('input_datetime.date_test')|as_datetime|as_local).total_seconds()//86400 }}

buoyant sapphire
#

thank you very much

marble jackal
#

This also works for the number of complete days
{{ (now() - states('input_datetime.date_test')|as_datetime|as_local).days }}

inner mesa
#

nice

buoyant sapphire
#

ye even better. tyvm

inner mesa
#

I can never remember what you can easily get from a timedelta, and I'm often disappointed

marble jackal
#

Hehe

inner mesa
#

it apparently supports "days" and "seconds", but not "minutes" or "hours", for instance

daring pecan
#

Hi - I was wondering if anyone here knows how to change the color mode on a light template?

last mesa
#

Hi, is this the right channel to post a question about templated sensors?

inner mesa
#

Sure

last mesa
#

I am trying to get create a binary sensor that changes states depending on time and some input_datetime entities.

So far I managed this:

#
  - trigger:
    - platform: time
      at: input_datetime.aqua_fim_fotoperiodo
      id: 'off'
    - platform: time
      at: input_datetime.aqua_inicio_fotoperiodo
      id: 'on'
    - platform: homeassistant
      event: start
      id: 'off'
    binary_sensor:
      - name: "fotoperiodo_aquario"
        state: "{{ trigger.id }}"```
#

it works for the 2 time events but i want it to be "correct" when homeassistant starts... so I am trying to write a rule that sets the id if the time homeassistant start is after "input_datetime.aqua_inicio_fotoperiodo" and before "input_datetime.aqua_fim_fotoperiodo"

inner mesa
#

Ok

last mesa
#

the logic should be

  id is on if 
   (input_datetime.aqua_fim_fotoperiodo > input_datetime.aqua_inicio_fotoperiodo and now > input_datetime.aqua_inicio_fotoperiodo and now < input_datetime.aqua_fim_fotoperiodo) or 
   (input_datetime.aqua_fim_fotoperiodo < input_datetime.aqua_inicio_fotoperiodo and (now > input_datetime.aqua_inicio_fotoperiodo or now < input_datetime.aqua_fim_fotoperiodo)) 
   else if is off 
#

but I can`t figure out how to compare 'now' to the input_datetime entities

inner mesa
#

So you can write almost exactly that

#

You need to convert the input_datetime state to an actual local datetime with |as_datetime|as_local

#

And compare with now()

last mesa
#

issue is that my input_datetime only has time (no date)...

inner mesa
#

should be okay if you use now().time()

last mesa
#
 iif( input_datetime.aqua_fim_fotoperiodo > input_datetime.aqua_inicio_fotoperiodo and now().time() > input_datetime.aqua_inicio_fotoperiodo | as_datetime | as_local ...
``` ?
inner mesa
#

ok, maybe not

#

this may be helpful:
{{ (today_at(states('input_datetime.date_test'))|as_local).time() > now().time() }}

#

that's an input_datetime with only the time

silent barnBOT
last mesa
#

Thanks RobC! I got it working with the following code:

{% set var_now = now().time() %}
{% set var_finish = (today_at(states('input_datetime.aqua_fim_fotoperiodo'))|as_local).time() %}
{% set var_start = (today_at(states('input_datetime.aqua_inicio_fotoperiodo'))|as_local).time() %}
{% set var_after_start = var_now > var_start %}
{% set var_before_finish = var_now < var_finish %}
{% set var_and = var_after_start and var_before_finish %}
{% set var_or = var_after_start or var_before_finish %}
{% set var_start_before_finish = states('input_datetime.aqua_fim_fotoperiodo') > states('input_datetime.aqua_inicio_fotoperiodo') %}
{{ ((var_start_before_finish and var_and) or ((not var_start_before_finish) and var_or)) | iif('on','off') }}

I will leave it here if someone needs something similar.

inner mesa
#

BTW, this is doing a string comparison, which may not work the way you expect:
{% set var_start_before_finish = states('input_datetime.aqua_fim_fotoperiodo') > states('input_datetime.aqua_inicio_fotoperiodo') %}

#

ideally, you would do something similar to what you did earlier to convert the time string into a real datetime and then do the comparison @last mesa

#

as long as the times are zero-filled and in 24-hour mode, you will probably be okay, though

strange geode
#

betwen firststate, and secondhere it inserts a space betwen.

#

and makes my link invalid.

marble jackal
#

.share the entire template

silent barnBOT
#

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

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

marble jackal
#

Are the spaces included in the state of your entity?

#

You can always use | replace(' ','')

silent vector
#

Is it possible to make a template trigger than will wait for another trigger within 10 seconds or timeout
if another trigger happens turn on.

The purpose is i am using an fp1 and tracking zha events (approach,leave) to turn on/off a light. It works well but sometimes it will fire a leave event just because i moved back a little bit not that i got up and walked away.
It usually retriggers within 10 seconds. the purpose of this would be to turn on if that happens as i would use that as a condition.
i could just use wait for trigger in the automation but i am trying to use a single service call with various capabilities for efficiency.

marble jackal
#

Maybe using trigger ids and last_updated. You can also store the trigger_id and last trigger datetime in attributes, and use that

silent vector
#

How would I do that? Storing the trigger IDs and last trigger datetime

marble jackal
#

Something like:

template:
  - trigger:
      - id: "foo"
      - id: "bar"
    sensor:
      - name: Your sensor
        state: "{{ your template }}"
        attributes:
          trigger_id: "{{ trigger.id }}"
          triggered: "{{ now().isoformat() }}"
silent vector
#

Thank you.

marble jackal
#

You can refer to them using this.attributes.trigger_id which will be at the time of the trigger, so before they are rendered again

#

So it will contain the previous trigger

#

And trigger time

silent vector
marble jackal
#

Something like that yes

silent vector
#

In the state refer to it using this.attributes.trigger_id == 'retrigger' and triggered < 10 seconds? Not sure how to format the time

marble jackal
#

With the code you posted above the trigger_id will either be approach or leave

silent vector
#

I will change that. It will be leave first. Then check if approach is fired in less than 10 seconds. If not turn on.

marble jackal
#

Something like this.atrributes.trigger_id == 'leave' and (now() - as_datetime(this.attributes.triggered)).total_seconds() < 10

silent vector
#

How would that check for if approach is fired then do nothing as in stay (false/off) or if approach is not fired turn on/true

marble jackal
#

You can add trigger.id == 'approach'

silent vector
#

this.atrributes.trigger_id == 'leave' and (now() - as_datetime(this.attributes.triggered)).total_seconds() < 10 and trigger.id == 'approach'?

marble jackal
#

Yes

silent vector
#

Perfect thank you.

thorny snow
#

Hey, working on kinda huge automation here but need some help with templates, the main idea is, if a Light is on for longer than 10min while a window is opened, if itโ€™s 1h before sunset, send a notification about the exact room light is on, that itโ€™s on too long while the window is open. ( The living room light has been on while the living room window is open, donโ€™t be that lazy ) So I kinda need some help on the template part of it.
And I can do it in GUI for each room for each window and each light separately but Iโ€™m sure someone here could help / share if he has something like this already done ๐Ÿ™‚ Iโ€™m pretty basic in YAML ๐Ÿ™‚ Oh and using my names instead of friendly namesโ€ฆ in the link are some light entities and some mappings hopefully that helps here ๐Ÿ™‚
https://dpaste.org/O5GmC

#

https://dpaste.org/fPULD and this is the automation for one window and one light in one room ๐Ÿ™‚ if that helps, as i've said, i can just repeat this like around 20 times with all possible cases but im sure there is a way to do it a bit more organised ๐Ÿ˜„

silent vector
# marble jackal Yes

I'm getting this

Template variable error: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'atrributes' when rendering '{{ this.atrributes.trigger_id == 'leave' and (now() - as_datetime(this.attributes.triggered)).total_seconds() < 10 and trigger.id == 'approach' }}'
#
Error rendering state template for sensor.bedroom_presence_detector_condition: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'atrributes'

Here's the code
https://dpaste.org/x1RkH

marble jackal
#

Ah, right, change it to this.get('attributes', {}).get('trigger_id')

silent vector
#

Which part should be changed?

silent barnBOT
marble jackal
#

this.attributes.trigger_id to what I just posted

#

And the same for the other attribute

#

Please remove that code wall from your post

thorny snow
#

Yeah why itโ€™s not autoremoved ? ;D

silent vector
#

Where is the extra ')' needed?

Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensor'][0]['state']. Got "{{ this.get('attributes', {}).get('trigger_id') == 'leave' and (now() - as_datetime(this.get('attributes', {}).get('triggered')).total_seconds() < 10 and trigger.id == 'approach' }}". 

(now() - as_datetime(this.get('attributes', {}).get('triggered')).total_seconds() < 10

marble jackal
#

After triggered, there should be 3 there

silent vector
#

No more errors but it doesn't appear to be doing what I expected. As in it's not becoming true.
If event leave is fired and within 10 seconds event approach is fired it should become true. It didn't do that. It's staying false.

friendly_name: Bedroom Presence Detector Condition
trigger_id: approach
triggered: '2022-07-28T08:38:24.404193-04:00'
marble jackal
#

.share the entire sensor yaml

silent barnBOT
#

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

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

silent vector
marble jackal
#

You did not replace this part with the new version this.atrributes.trigger_id

silent vector
#

In the Template.yaml I did. I forgot to add that to dpaste.

marble jackal
#

Unfortunately there is no trace here, what you can do is break the template in 3 parts and put that in 3 attributes so you can see on which part it falls

shrewd epoch
#

Anyone know what gives me the error of:

Configuration validation
Validate your configuration if you recently made some changes to it and want to make sure that it is all valid.
Configuration invalid!

Platform error humidifier.template - No module named 'homeassistant.components.template.humidifier'```

https://pastebin.com/81zwAjVa

Thanks guys!
silent vector
#

I had the command for the event messed up.

#

It's meant to be 'Away' not 'Leave'. How do I make this auto turn off? It did go to true.

#

Just add auto turn off and give it a few seconds?

marble jackal
#

Correct

silent vector
#

Perfect thank you.

thorny snow
indigo haven
#

Finished product

binary_sensor:
  - platform: template
    sensors:
      campainha_zigbee:
        friendly_name: "Campainha"
        value_template: "{{ state_attr('sensor.0x00124b002241ad4d_action', 'action') in ['single', 'double', 'long'] }}"
marble jackal
#

If so, I would add them in areas, eg an area named Bedroom

thorny snow
#

Yes the idea is they are in the same room ๐Ÿ™‚

#

so far ive got the automation to work and it worked ๐Ÿ˜„ so the idea works ๐Ÿ™‚

thorny snow
#

like i have rooms and they are in the right room / area ๐Ÿ™‚

marble jackal
#

Then create your variables like this:

variables:
  mapping:
    Bedroom:
      light: light.bedroom
      sensor: binary_sensor.window_bedroom
#

You use areas in HA?

#

You can set them in the GUI

thorny snow
#

Yep i have areas ๐Ÿ™‚ so the right sensor is in the right area already ๐Ÿ™‚

marble jackal
#

And the light as well?

thorny snow
#

yep

marble jackal
#

Okay, I quickly draft something based on my mapping example above

thorny snow
#

didn't understood what You've meant but take You're time ๐Ÿ™‚

#

and why use areas ? is the way i have it in that one automation that bad ? it would be just was easier to correct it later on, when i need it ๐Ÿ™‚

#

just asking ๐Ÿ™‚ i've had something similar where you've helped and it works like a charm !!!! ๐Ÿ™‚

marble jackal
#

Because you already have the areas

thorny snow
#

ill have to test it since im not that good with yaml to get it just from code ๐Ÿ™‚

#

but i will definitely give a feedback here ๐Ÿ™‚

marble jackal
#

It belongs in configuration.yaml

thorny snow
#

sorry for the holdup, You're welcome to check #general-archived my HA was such a buggy mess ๐Ÿ˜„

fiery rock
#

When using map(attribute=*) what do I replace the * with to return the "entity", eg I want the return to be something like input_select.alpha or counter.number?

#

Found the answer whilst looking into some other issue on the forums. Turns out it's map(attribute='entity_id') which I swear I tried already ๐Ÿคทโ€โ™‚๏ธ

inner mesa
fiery rock
#

Thanks, that is the exact information I was looking for earlier (but will be very useful in the future ๐Ÿ‘).

elfin torrent
#

my value is {34AB9527089500000005010100328F}

    value_template: >
            {% if "{{value[2]}}"   == "4"  %}
             1
            {% else %}
             {{value[2]}}
            {% endif %}

it should be 1 right ? but why it show 4
What have I missed ?

loud mountain
#

current: 1972 current_consumption: 414.3 voltage: 208 friendly_name: Smart Plug
hi guys, how do i add this state attributes into sensor entity? from integration local tuya

elfin torrent
#

i'm sorry. i don't understant. i am new user. Can you advise me how I need to fix it?

inner mesa
#

you started a template with {% and then put {{ }} in the middle

#

{{ 1 if value[2] == '4' else value[2] }}

marble jackal
#

And then this should be your template in the if:

      - condition: template
        value_template: >
          {% set sensors = mapping[area] %}
          {{ expand(sensors) | selectattr('state','eq','on') | list | count > 0 }}
#

And you might want to add your sunset condition you had in your own automation

elfin torrent
inner mesa
#

rule #1

#

you need to surround your template in quotes

elfin torrent
analog mulch
#

Is there some way of getting a template sensor to be registered as related to a particular device, so that it appears on the deviceโ€™s UI page? Eg I calculate energy for a device using a template and would like that to appear together with the other entities related to the device

#

Eg you see that HA picks up the automations using the deviceโ€™s entities and puts them on the page

marble jackal
#

Nope

analog mulch
thorny snow
crude tartan
#

I have a templates.yaml file but not matter what I do i cannot move this template from my config to it without breaking something. ```sensor:

  • platform: template
    sensors:
    vapor_deficit:
    friendly_name: 'vpd in kilo pascals'
    value_template: >-
    {% set T = ((states('sensor.greenhousemotion_air_temperature') | float) - 32) * 5/9 %}
    {% set RH = states('sensor.greenhousemotion_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'```
#
  - name: vapor_deficit:
    value_template: >-
      {% set T = ((states('sensor.greenhousemotion_air_temperature') | float) - 32) * 5/9 %}
      {% set RH = states('sensor.greenhousemotion_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'```
mighty ledge
#

first post is correct, second post is not

#

second post is... a mixture of wrong code for both the new and old style

#
- sensor:
  - name: vapor_deficit
    state: >-
      {% set T = ((states('sensor.greenhousemotion_air_temperature') | float) - 32) * 5/9 %}
      {% set RH = states('sensor.greenhousemotion_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'
crude tartan
lethal dawn
#

Is there an easy way to pick the defined value from one of two columns, from a list of entities?

I currently have

{{ expand('binary_sensor.lounge_door_sensor_occupancy', 'binary_sensor.lounge_sofa_sensor_occupancy') | selectattr('attributes.occupancy', 'defined') | map(attribute='attributes.occupancy') | list | max }}

but now need to add attributes.presence as a fallback for any sensors where attributes.occupancy is undefined

inner mesa
#

Not that I'm aware of. You'd need to generate separate lists and combine them

flint wing
#

Ok, I'll explain briefly my goal, maybe someone can point me toward the best solution. I have just installed a flow meter with ESP32 and I am fetching values for instant water flow (in litres). I'm trying to calculate how much water (in litres) has been used last time a water flow has been detected, and keep that value somewhere (in a sensor?) so I can use it in an automation if it reaches more than a certain threshold. Example: water flow for more than 3 minutes, it's probably someone having a shower, I want to use that data to calculate volume (in litres) x cost of electricity to heat 1 litre of water, then call a service and send a message to a Google Home in my bathroom telling how much that shower cost.

mighty ledge
mighty ledge
#

it calculates the area under the curve, which is the value you're looking for.

silent vector
#

Petro, do you know why I'm getting

list index out of range

On the set variables at the first for each and probably I will get the same error on the second for each as it is nearly identical
https://dpaste.org/bRtV8

lethal dawn
#

I now have flawless motion/mmWave combo sensors ๐Ÿ˜ƒ

silent vector
#

I think I just need to change the thermostat variable to

flint wing
mighty ledge
#

Take a look at the integration integration

#

it will calculate x/time stuff for you

flint wing
#

Ok fine! I'll read from there! Thank you Petro

mighty ledge
#

if you're struggling setting that up, just head over to #integrations-archived , also, after you set up the integration integration, you can use the item in utility_meter integration to get stats over different time ranges

#

basically, you don't need a template

flint wing
#

@mighty ledge, about the Integral method to select, I couldn't decide which. In the documentation it mentions that "In case you expect that your source sensor will provide several subsequent values that are equal, you should opt for the left method to get accurate readings.".

In my case, when water starts to flow I want to calculate volume in litres until flow stops. I want to keep track of those different events and especially those when water flow for more than 3 or 4 minutes as this probably mean it's a shower happening.

mighty ledge
flint wing
# mighty ledge what your asking for isn't possible. You have to get creative for a calculation...

Yesss... That's why I'm baffled into overthinking this for the last 24h.... I will have to dig further into this... There must be a way, I just haven't found it yet.... When water flows, I have the debit in L/min. When flow goes from 0 L/min to any value above this, I know it's a starting point to count, but I don't know how to use that as a trigger to count and I don't know where to calculate this... That's my challenge here....

mighty ledge
#

using left will ignore the long pauses where the water isn't flowing.

#

๐Ÿคทโ€โ™‚๏ธ

#

but programmatically turning that calc on or off is not possible. So, maybe you are over thinking it.

#

area under curve = total amount over x time.

flint wing
#

Do you know where I should discuss this challenge as it does not seem to be appropriate in #templates-archived

flint wing
#

Ok, I'll head over there and see if I can get some help thinking about this. Thanks Petro for your help so far. ๐Ÿ™‚

mighty ledge
#

if that's the case, just set up energy meter with your water set as gas

#

as that handles gas and electric, but not liquid, but liquid is basically represented the same way as gas is. Volume/time

flint wing
#

I want total volume of water after flow is detected and then stops.

mighty ledge
#

but why

#

what could you possibly want that for other than just monitoring

flint wing
#

Because I want to use that value when it is above 3-4 minutes, then make a background calculation with a Template so I can call a service to TTS how much that shower cost

#

I know it's crazy, but that's a funny project I'll share in a school webinar and it pushes the limit of what can smart homes can do to help become aware of water consumption

mighty ledge
#

You aren't going to be able to get that without getting the information from the database

#

and it will only work for the last shower.

flint wing
mighty ledge
#

that will require a template, and it will require a properly formatted sql query

flint wing
#

The webinar will be presented to 5000-10000 students this fall 2022 and winter 2023

#

I will present the backstory behind it and mention the struggles to achieve the goal toward it. I hope it will raise interest into smart home and community of builder for the future

mighty ledge
flint wing
mighty ledge
#

because it won't be friendly for non-coders.

flint wing
#

I'm a Ph.D. in education, I'll find a way to make it friendly to show how it has been done

mighty ledge
#

ok, by all means then, it would be an SQL sensor with a query and a value_template that summates the last shower volume. Then you'd make another template that just uses the last total volume multiplied by the $ per liter

flint wing
mighty ledge
#

You might need 2 datetimes

#

or 1

#

basically, you'd have to set the datetime via an automation when the flow starts

#

then use that datetime in the SQL query. Possibly set a datetime when the flow stops as well

#

then grab all the states between the 2 datetimes

#

sum them

flint wing
#

I see the path toward the goal now, but I need to make sure I get the starting point correctly. Now that my flow meter is set, I must work in automation to set a datetime? Is that the next step?

mighty ledge
#

Yea, I'd say so

#

if your flow sensor is literally 0, you could just do an automation that looks at any numerical change going above 0.

#

maybe a template sensor to help with that if you really want

#
template:
- binary_sensor:
  - name: Waterflow on
    state: "{{ states('sensor.xyz') | float(0) > 0 }}"
#

the automation would be...

#
- alias: Set On/Off Datetime
  trigger:
  - id: 'on'
    platform: state
    entity_id: binary_sensor.waterflow_on
    from: 'off'
    to: 'on'
  - id: 'off'
    platform: state
    entity_id: binary_sensor.waterflow_on
    from: 'on'
    to: 'off'
  action:
  - service: input_datetime.set
    target:
      entity_id: input_datetime.{{ 'last_shower_start' if trigger.id == 'on' else 'last_shower_end' }}
#

just make 2 input datetimes: last_shower_start, last_shower_end

#

then you have the SQL query

flint wing
#

You are amazing, I'll try it out right now. I'm so thankful Petro ๐Ÿ˜

mighty ledge
#

or you could do it slightly differently

#

where your sql sensor just summates everything from a starting timestamp

#

and then when the binary_sensor goes off, you send the notification.

#

that might be easier

flint wing
#

template sensor are created in configuration.yaml ? Correct?

mighty ledge
#

yep

#

I'm not sure you can do this with SQL either

#

as the query doesn't allow for variable times

#

So, you might have to attempt to sum itself with another template sensor.

flint wing
#

Should I test the automation you suggested now?

#

@mighty ledge, in the suggested automation, you are pointing to last_shower_start and last_shower_end. Should I create these entities?

mighty ledge
#

try it with this template sensor.

#
- sensor:
  - name: Last Shower Summation
    state: >
      {% if states('binary_sensor.waterflow_on') %}
        {{ this.state | float(0) + states('sensor.xyz') if this.state is defined else 0 }}
      {% else %}
        off
      {% endif %}
flint wing
#

I'll add it in configuration.yaml

mighty ledge
#

sorry wait a sec

flint wing
#

Ok

mighty ledge
#

yeah add that.

#

then add this automation, forget the datetime stuff

flint wing
#

On this line: {{ this.state | float(0) + states('sensor.xyz') }}

the sensor.xyz should be pointing toward which sensor?

mighty ledge
#
- alias:
  - platform: state
    entity_id: sensor.last_shower_summation
    to: 'off'
  condition:
  - condition: template
    value_template: "{{ trigger.from_state is defined and trigger.from_state.state | is_number }}"
  action:
  - event: event_shower_ended
    event_data:
      volume: "{{ trigger.from_state.state | float }}"
#

then, make a template sensor that calculates the cost....

#
- trigger:
  - platform: event
    event_type: event_shower_ended
  sensor:
  - name: Shower Cost
    state: "{{ trigger.event.data.volume * 0.01 }}"
    unit_of_measurement: $
flint wing
#

Cost is 0,01 $ / litre. I double-checked with local Power Facility here in Quebec/Canada

mighty ledge
#

Yeah, so basically how this works is you have a sensor that adds a state to the previous state everytime the shower is on

#

don't restart during this time, as you'll lose the data

#

but you'll have a cost of the last shower

abstract sapphire
#

Don't mean to barge in on this bit but hoping someone can help me understand. I've got a sensor that outputs a value similar to "2022-07-30T07:22:40+10:00". How would I go about removing everything except the time "07:22:40"

mighty ledge
#

make a template sensor

#
template:
- sensor:
  - name: Friendly Time
    state: "{{ (states('sensor.xyz') | as_datetime).strftime('%H:%M:%S') }}"
abstract sapphire
#

Thanks very much.

mighty ledge
#

so to recap @flint wing

#

this should be in configuration.yaml

#
template:

- binary_sensor:
  - name: Waterflow on
    state: "{{ states('sensor.xyz') | float(0) > 0 }}"

- sensor:
  - name: Last Shower Summation
    state: >
      {% if states('binary_sensor.waterflow_on') %}
        {{ this.state | float(0) + states('sensor.xyz') if this.state is defined else 0 }}
      {% else %}
        off
      {% endif %}

- trigger:
  - platform: event
    event_type: event_shower_ended
  sensor:
  - name: Shower Cost
    state: "{{ trigger.event.data.volume * 0.01 }}"
    unit_of_measurement: $
#

with this automation

- alias:
  - platform: state
    entity_id: sensor.last_shower_summation
    to: 'off'
  condition:
  - condition: template
    value_template: "{{ trigger.from_state is defined and trigger.from_state.state | is_number }}"
  action:
  - event: event_shower_ended
    event_data:
      volume: "{{ trigger.from_state.state | float }}"
flint wing
#

@mighty ledge, I just want to make sure I followup since you are a fast template-guru ๐Ÿ˜…

  1. I created the binary_sensor for Waterflow on
  2. I need to create a template sensor for Last Shower Summation
  3. I need to create automation with - alias: - platform: state entity_id: sensor.last_shower_summation
  4. I need to make a template sensor that calculates the cost

Is that the correct order?

marble jackal
#

Guess .time() would also work for @abstract sapphire as the source sensor doesn't output microseconds

flint wing
#

@mighty ledge, that for recap, it answers my last comment

marble jackal
#
template:
- sensor:
  - name: Friendly Time
    state: "{{ (states('sensor.xyz') | as_datetime).time() }}"
mighty ledge
#

I guess you could simplify it down

#

to this

#
template:
- sensor:
  - name: Last Shower Summation
    state: >
      {% set current_liters = states('sensor.xyz') | float(0) %}
      {% if current_liters  > 0 %}
        {{ this.state | float(0) + current_liters  if this.state is defined else 0 }}
      {% else %}
        off
      {% endif %}

- trigger:
  - platform: event
    event_type: event_shower_ended
  sensor:
  - name: Shower Cost
    state: "{{ trigger.event.data.volume * 0.01 }}"
    unit_of_measurement: $
abstract sapphire
flint wing
#

@mighty ledge, and when you write sensor.xyz, I guess you are referring to my sensor that calculate water flow, is that correct?

mighty ledge
#

yep

#

hold up tho, let me rejigger it cause I left out something

flint wing
#

And as a reminder, water flow below 3 minutes have few chance of being a shower.

mighty ledge
#

that requirement will force you to change your template last_shower summation

#

you'd have to set the trigger as a template, but then keep in mind, that you'll loose all data between 0 and 3 minutes

flint wing
mighty ledge
#

right, but those liters wouldn't be in the estimated cost

#

that's what I'm saying

flint wing
#

Then I guess the automation that would be at the end, I mean the call service to shout out the cost of the shower could use the last shower duration? It would not call service TTS to unless above 3 minutes?

mighty ledge
#

you could add an automation that sets the input_datetime for the start of the shower.

flint wing
#

The final automation could use last shower duration and send call service TTS to a GoogleHome in bathroom. TTS would say "Based on your shower duration, this shower cost X dollars".

mighty ledge
#

right, but as it stands you don't have the duration

#

you only have the summation

#

so to get the duration, you'd need to calculate the duration

#

aka, you need the start time

flint wing
#

Then I just need to trigger call service to TTS beyond a certain threshold summation

mighty ledge
#

is the flow rate constant?

flint wing
#

Kind of.... It will vary slightly if other people use water in house

mighty ledge
#

oof, that's not going to be easy to detect

#

so this is on your entire house flow?

flint wing
#

And also depending on time of the day because if many neighbors use water, it ends up affecting flow

#

Yes, my flow meter if for my entire house. But I will install a dedicated flow meter for hot water tank very soon

#

I was starting to get into the programmation and calculation but your help has pushed me weeks ahead because I don't come anywhere near your knowledge of templating and coding. That's why I'm trying to keep up the pace.

mighty ledge
#

well, either way, you can set the start and end time datetimes with that other automation

#

and then you can make a sensor that calculates the difference

#

and when the difference is greater than x, you can send the notification

#

keep in mind that the value might be negative at times because you're in the middle of a shower that hasn't ended. And you might run into issues where you have to wait for the value to be calculated by putting a 20 second wait in your notification automation

flint wing
abstract sapphire
#

Alright I've got the templating I want setup but for some reason it's not adding a space between the two IF statement values. Eg it will show "sun will rise at xx.There is a 0% chance..." without a space between the two statements. If I put any other character there it will show but spaces don't.

{%- if now() < (states('sensor.astronomical_sunrise_time_0') | as_datetime) -%}The sun will rise around {{ (states('sensor.astronomical_sunrise_time_0') | as_datetime).strftime('%H%M') }}.
{%- if now() > today_at("05:00") -%} There is a {{ states('sensor.rain_chance_0') }}% chance of rain today.
{%- endif %}{%- endif %}
#

Oh and please tell me if I can clean that up. Looks messy as all hell in my eyes but don't know.

#

Without creating template sensors.

inner mesa
#

Use quotes?