#templates-archived

1 messages ยท Page 166 of 1

marble jackal
floral shuttle
#

if your interested in sorted listing those in the frontend, you can also let the frontend do the work for you in an auto-entities filter. filter: template: > {% set threshold = states('input_number.battery_alert_level')|float(0) %} {% for s in expand('group.battery_sensors_auto') if s.state|float(0) < threshold %} {{s.entity_id}} {%- endfor %} sort: method: state numeric: true

#

that auto group is nothing more than an automation creating that at startup: action: service: group.set data: object_id: battery_sensors_auto entities: > {{states.sensor|selectattr('attributes.device_class','eq','battery') |map(attribute='entity_id')|list}} so if you wish, you could also use that in the filter

#

btw, seems that automation does not error without the | selectattr('attributes.device_class', 'defined') though the template editor does

marble jackal
# marble jackal This works (using 2 for loops, first one to create a dict, second one to format ...

Had a 2nd look, now using one for loop

{%- set threshold = 30 -%}
{%- set ns = namespace(states=[], format=[]) -%}
{%- for state in states.sensor
          | selectattr('attributes.device_class', 'defined')
          | selectattr('attributes.device_class', 'eq', 'battery')
          | selectattr('state', 'is_number') -%}
  {%- if state.state | int < threshold -%}
    {% set name = state.name | replace(' battery', '') | replace(' Battery', '') %}
    {% set state = state.state | int %}
    {% set ns.states = ns.states + [dict(name = name, state = state)] %}
    {% set index = (ns.states | sort(attribute='name') | sort(attribute='state') | map(attribute='name') | list).index(name) %}
    {% set ns.format = ns.format[:index] + [name  ~ ': ' ~ state ~'%'] + ns.format[index:] %}
  {%- endif -%}
{%- endfor -%}
{{ ns.format | join(', ') }}
marble jackal
#

The battery entities with the same state are also sorted by name

sacred sparrow
#
- trigger:
    - platform: time
      at: '05:00:00'
    - platform: numeric_state
      entity_id: sensor.outside_home_thermometer_temperature
      below: sensor.outside_min_temp
  sensor:
    - name: "Outside Min Temp"
      unit_of_measurement: "ยฐC"
      device_class: temperature
      availability: "{{ not is_state('sensor.outside_home_thermometer_temperature', 'unavailable') or is_state('sensor.outside_home_thermometer_temperature', 'unknown') }}"
      state: '{{ states(''sensor.outside_home_thermometer_temperature'') }}'
``` at 5am it registered the temp at 13.9 which is fine but then at 6:23am sensor.outside_home_thermometer_temperature went to 11.3 but my sensor did not change the state to 11.3
marble jackal
#

I see no reason why it didn't work. Unfortunately there is no such thing as a trace for the trigger based template sensors, so there is not much I can do further

#

You could replicate it in an automation using an input_number, so at least you can see if it triggers when it should

sacred sparrow
#

okay thanks - I'll give that a go ๐Ÿ™‚

#

would the trigger in the automation be:

platform: numeric_state
entity_id: sensor.outside_home_thermometer_temperature
below: '{{ states('input_number.outside_min_temp') }}'```
marble jackal
#

no just below: input_number.outside_min_temp

marble jackal
#

no error anymore ๐Ÿ˜›

acoustic arch
#

geez... the error was in the action part

marble jackal
#

hehe

floral shuttle
#

is this still the best way to get the number of minutes of uptime? {{((now().timestamp()-as_timestamp(states('sensor.uptime')))/60)|int}}

#

tried the today_as() (which I still have not used...) but didnt see the correct use for it in this case

#

in fact, I only need this to set a condition in certain automations to not fire unless minutes is >1

marble jackal
floral shuttle
#

nice yes. thx!

floral shuttle
#

that would translate to a dedicated uptime minutes sensor like: {{ ((now() - as_datetime(states('sensor.uptime'))).seconds/60)|int }} and then allow me to do: condition: condition: numeric_state entity_id: sensor.ha_uptime_minutes above: 1

marble jackal
#

Yes, that should work

#

although that will only be true after 2 minutes, as 1 is not above: 1

silent seal
#

I stole from here a while ago and have:

{{ ( now() - states('sensor.uptime')|as_datetime ).seconds }}

as a template sensor

#

I believe this also works:

{{ (( now() - states('sensor.uptime')|as_datetime ).seconds / 60) | round }}
#

(at least it does in my template editor)

royal cargo
#

Hey guys, I'm experiencing and odd issue with a bayesian sensor. It seems to turn off for the the tiniest milisecond, when a "state" platform observation turns off, even though the sensor itself is way above the treshold probability:
https://i.imgur.com/jDXfvqj.png
Even though it's only off for an insurmountable short time, it still triggers whatever follows in my automation to turn off accordingly. Any ideas?

#
  • platform: "bayesian"
    name: bathroom_is_occupied
    prior: 0.06
    probability_threshold: 0.35
    observations:
    • platform: "state"
      entity_id: binary_sensor.samjin_motion_b26e1201_ias_zone
      to_state: "on"
      prob_given_true: 0.99
    • platform: "numeric_state"
      entity_id: "sensor.bathroom_movement"
      prob_given_true: 0.92
      above: 0
#

Both the observations above are enough to stay above the probability threshold, and they are active at the same time, but when the "state" observation with the ias_zone turns off, it still triggers the entire sensor to turn off for this infinitesimally short amount of time

mellow perch
#

is there any way to get {{(states('input_text.discord_family_channel')) | string }} to return a string if the text is numerical?

silent seal
#

Well, it already is a string, and you're casting it to a string

mellow perch
#

But in developer tools it's showing giving "result type: number"

#

And the automation doesn't work because it says it wants a string for the target attribute

inner mesa
#

don't worry about the type that the template editor reports

#

~share your automation

silent barnBOT
#

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

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

inner mesa
#

My guess is that you didn't surround the template in quotes

mellow perch
#

hmm. That seems to have solved it. I'd tried with and without quotes, so I'm not sure what else I had wrong in previous testing. It works now. (without the | string as well.

sacred sparrow
steady kestrel
#

hello!

{{ state_attr('light.kantoor', 'brightness' ) / 2.55 if is_state('light.kantoor', 'on') else 'Off' }}%
{{ states("sensor.temperatuur_kantoor_temperature") }} ยฐC

Output:

Result type: string
100.0%
26.57 ยฐC

how do i trim the string of the 100.0%

#

And the% stays there if its off -.-

marble jackal
steady kestrel
#

thanks! Gonna try to understand this!

marble jackal
#

Might be better to change | int to | round(0)

#

~ concatenates the parts on both sides as strings

steady kestrel
#

done ๐Ÿ™‚

shell leaf
#

anyone can link me to a good guide about templating, specifically i have like 7 rooms requiring motion detection (conditions and triggers). I would rather not write up / gui input all the same conditions and triggers (other than the sensor entity obviously)

#

referring to automations

languid mural
#

Thanks! I'll take a look at this

plucky heron
#

{{ now() > (states.binary_sensor.garage_motion_sensor.last_changed + timedelta(minutes=3)) }}
why does that throw an error in the condition tester? It says "template value should be a string ... got None"

inner mesa
#

see first pinned message

thorny snow
#

Looking for a simple option to show lights on at the moment, p.s im totaly new so im using only ui and no yaml at the moment

inner mesa
#

it's a simple template

#

{{ states.light|selectattr('state', 'eq', 'on')|map(attribute='name')|list }}

thorny snow
#

ok how where to enter it and how to use it ? like i understand that i have to replace the entity_id with my entity id but thats all ๐Ÿ˜„

inner mesa
#

what are you trying to do with it?

thorny snow
#

im trying to make a dashboard and on top of it i will have a chip who shows couple things that are open

inner mesa
#

it sounds like you're using the mushroom card or something similar

#

I have no "chips"

thorny snow
#

yep its the mushroom thing

inner mesa
#

and I have no experience with the mushroom card suite

thorny snow
#

oh ok, ill just try my luck there then ๐Ÿ™‚

inner mesa
#

a variant of the template I provided above is the starting point

sacred sparrow
#
    - platform: time
      at: "05:00:00"
    - platform: state
      entity_id: sensor.outside_home_thermometer_temperature
    - condition: numeric_state
      entity_id: sensor.outside_home_thermometer_temperature
      below: sensor.outside_min_temp
  sensor:
    - name: "Outside Min Temp"
      unit_of_measurement: "ยฐC"
      device_class: temperature
      availability: "{{ not is_state('sensor.outside_home_thermometer_temperature', 'unavailable') or not is_state('sensor.outside_home_thermometer_temperature', 'unknown') }}"
      state: "{{ states('sensor.outside_home_thermometer_temperature') }}"
#

is it possible to have conditions? like above

inner mesa
#

no

#

first, conditions don't belong in the trigger, and second, you cannot use conditions in template sensors

sacred sparrow
#

is there another way?

thorny snow
sacred sparrow
#

haha I like your request better

#
- trigger:
    - platform: time
      at: "05:00:00"
    - platform: state
      entity_id: sensor.outside_home_thermometer_temperature
  sensor:
    - name: "Outside Min Temp"
      unit_of_measurement: "ยฐC"
      device_class: temperature
      availability: "{{ not is_state('sensor.outside_home_thermometer_temperature', 'unavailable') or not is_state('sensor.outside_home_thermometer_temperature', 'unknown') }}"
      state: "{{ iif (states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"
stiff sluice
#

I'm having problems with my value template when a key contains a - character. What should my value template look like? https://pastebin.com/HDAH8MuZ

marble jackal
sacred sparrow
#

I just want it to do
state: "{{ states('sensor.outside_home_thermometer_temperature') }} "
at 05:00:00 but every other time

state: "{{ iif (states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"

marble jackal
#

Add trigger ids and use those in yourstate template

sacred sparrow
#

I've never used trigger ID's before - where should I start?

#

I'd love to see some examples ๐Ÿ™‚

#

well I have in automations with CHOOSE but not for template sensors

marble jackal
#

The idea is the same, but now you use them in your if statement

#
state: "{{ iif (trigger.id == 'whale' or states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"
#
- trigger:
    - platform: time
      at: "05:00:00"
      id: whale
sacred sparrow
#

ahh so I only need a trigger id on one of them

marble jackal
#

Change whale in both places to something to like

#

You only need to identify that one

sacred sparrow
#
- trigger:
    - platform: time
      at: "05:00:00"
      id: 5am
    - platform: state
      entity_id: sensor.outside_home_thermometer_temperature
  sensor:
    - name: "Outside Min Temp"
      unit_of_measurement: "ยฐC"
      device_class: temperature
      availability: "{{ not is_state('sensor.outside_home_thermometer_temperature', 'unavailable') or not is_state('sensor.outside_home_thermometer_temperature', 'unknown') }}"
      state: "{{ iif (trigger.id == '5am' or states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"```
#

where in that does it tell it to do "states('sensor.outside_home_thermometer_temperature')" when its 5am?

marble jackal
#

Yes, but you can simplify your availability template to "{{ states('your.sensor') | is_number }}"

#

At 5:00 that trigger will be the one triggering, so trigger.id == '5am' will be true

#

So it will pick that option of the iif

sacred sparrow
#

ahh I see

#

great tip on the availability sensor ๐Ÿ™‚

floral shuttle
hexed wing
#

(now() - states.person.xxx.last_changed) = already a timedelta

#

(now() - states.person.xxx.last_changed).strftime('%X')

#

no need to juggle with things

#

oh wait

#

that doesn't work with timedelta's ๐Ÿ˜ฆ

#

good morning Frenck

floral shuttle
#

hehe

#

tbh, I did try that first too...

hexed wing
#

that might be it actually, not sure if it can be made simpler

marble jackal
#

You can use seconds instead of total_seconds()

hexed wing
#

No?

#

seconds is limited to max a day

#

while total_seconds() is the whole timedelta represented as seconds

#

when doing conversions like these, I would say one should use total_seconds()

marble jackal
#

Oh, in that case not

#

Good to know!

floral shuttle
#

thx for confirming.

#

1 more detail please. I expanded it with a test to do: {% set zones = states.zone|map(attribute='name')|list %} {% set id = 'marijn' %} {% if states('person.'~id) in zones or is_state('person.' ~id,'home') %} to check if person is in a zone. In my config, 'home' is not the name of my zone home so I added that extra line. would have hoped something like states('person.'~id) in [zones,'home'] would be possible, but that doesnt work. Can that be done differently?

#

so, either be in the list zones or in 'home'

proper ore
#

hi all. im trying to create an input boolean for summer or winter. i want to use it for a conditional card in lovelace. whats the best approach to define a period based on month of year?

#

maybe i should use something else and not a boolean for this?

floral shuttle
#

create a template binary

proper ore
#

ahh i see this is new to me (im a neewb :))

#

googling ๐Ÿ˜„

floral shuttle
#

yes, define any relevant period for you in the template, check if it is now, on, true, and use that in the conditional card as entity

proper ore
#

thx so much ! @floral shuttle , do you perhaps have an example yaml you can share to get me started?

floral shuttle
#
      - unique_id: wintertijd_binary
        name: Wintertijd
        picture: /local/season/winter.png
        state: >
          {{now().timetuple().tm_isdst == 0}}

      - unique_id: christmas_time
        name: Christmas time
        state: >
          {% set today = now().day %} {% set month = now().month %}
          {{month == 12 and today >= 24 or month == 1 and today <= 2}}
#

I have these even as trigger based templates, because with that their updating it limited to the trigger you define (and not per each minute). As such they go under:```
template:

  • trigger:

    • platform: time_pattern
      hours: 0
      minutes: 0
    • platform: homeassistant
      event: start
    • platform: event
      event_type: event_template_reloaded

    binary_sensor:

proper ore
#

cool thats very helpful! thx @floral shuttle !

short wren
#

Is it possible to crate a sensor that automatically includes all sensors of a specific type? I want a simple sensor that tells me if any of my Twitch channels goes live, and don't want to add them manually to a list (because I will forget to add them to both places).

floral shuttle
#

that would probably be possible yes. What did you try and didnt work out?

floral shuttle
#

sweet! thank you very much!

#

can rewrite: {{trigger.to_state.state in ['home','not_home'] or trigger.from_state.state in ['home','not_home'] or trigger.to_state.state in zones or trigger.from_state.state in zones}} at least to {{trigger.to_state.state in (zones,['home','not_home']) or trigger.from_state.state in (zones,['home','not_home'])}}

#

maybe even:{% set location = (zones,['home','not_home']) %} {{trigger.to_state.state in location or {{trigger.from_state.state in location }} ?

#

need to test if I need to quote the (zones,['home','not_home']) in the set location line.

#

or, maybe this would even be easier: {% set location = states.zone|map(attribute='name')|list + ['home','not_home'] %} {{trigger.to_state.state in location or trigger.from_state.state in location}}

marble jackal
warm isle
#

I could use a hand

template:
  - sensor:
      - name: combined_power_usage_kwh
        unit_of_measurement: kWh  
        device_class: energy
        state_class: total_increasing
        attributes: 
          reject_this_sensor: >-
              {{ 'true' }}
        state: >-
          {% set pwr = states.sensor
            | rejectattr('state','in',['unknown','unavailable'])
            | selectattr('attributes.unit_of_measurement', 'defined')
            | selectattr('attributes.unit_of_measurement', 'eq', 'kWh')
            | map(attribute='state') | map('float') | list %}
          {{ pwr | sum }}

I try to put every energy sensor I have and will have in a template.
Current implementation has just one downside, it includes itself
An idea how I can get around it? Tried rejectattr('attributes.reject_this_sensor', 'eq', 'true') but that will let the template fail

silent seal
#

Why not rejectattr('name', 'eq', 'combined_power_usage_kwh') ?

warm isle
#

because I did'nt crossed my mind ๐Ÿ˜„

silent seal
#

Start simple ๐Ÿ˜‰

warm isle
#

tryed to, but used entety_id instead of name or | rejectattr('friendly_name','eq','combined_power_usage_kwh') ๐Ÿคฆโ€โ™‚๏ธ Noice that it can be so easy

#

yaaay Works! thanks โค๏ธ

marble jackal
#

As friendly_name is an attribute, you need to use atrributes.friendly_name

marble jackal
warm isle
#

Great!, very much appreciated!
does anyone happen to have a template to filter all the attributes of a particular entity? I had something like that around but it got lost over time

marble jackal
#

What do you exactly mean here? Filter all the attributes?

warm isle
#

well, more like list all, to have a reference for jinja

marble jackal
#

states.your.entity.attributes.items()

warm isle
#

Got a pointer for me where you found this.name, I guess there is a hell lot more

warm isle
#

ouch.. they gotten a whole lot longer since I checked them the last time ๐Ÿ˜„ Thanks a ton, this should give me good options to brake stuff

#

uh, so new! ahead of times

deft sail
#

Hello all, I am FAR from a programmer so be gentle with me, having an issue or potential issue with some 433mhz door switches, most on doors, one on a cover(garage door). When i edit my configuration.yaml file in Studio Code Server, I see errors. As of now, they still work but I'm assuming it's part of a planned breaking change so I'm trying to get a jump on it. The error says, String does not match the pattern of "DEPRECIATED" I've tried everything I can think of and can see on the templating help areas, MQTT binary sensors etc. Will try to screen shot or paste some code

silent barnBOT
sacred sparrow
#
- trigger:
    - platform: time
      at: "05:00:00"
      id: 5am
    - platform: state
      entity_id: sensor.outside_home_thermometer_temperature
  sensor:
    - name: "Outside Min Temp"
      unit_of_measurement: "ยฐC"
      device_class: temperature
      availability: "{{ states('sensor.outside_home_thermometer_temperature') | is_number }}"
      state: "{{ iif (trigger.id == '5am' or states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"

My lowest temp today was 8.2 but this template now shows 10 which was the temp a few minutes ago - I am not sure how that happened as 8.2 < 10.

#

it triggered at 5am perfectly and was 9.6 - then at 6:58 the temp dropped to 8.2 and the template above set the sensor to 8.2 but then at 10:04am the temp went to 10am and the template sensor changed it state to 10 even though it should have just stayed 8.2?

marble jackal
#

You are doing a string comparison, and "10" < "8.2" is true, because 1 is lower as 8

#

Convert the values to floats in your comparison

#
      state: "{{ iif (trigger.id == '5am' or states('sensor.outside_home_thermometer_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"
#

@sacred sparrow

sacred sparrow
#

ah that makes sense - thank you ๐Ÿ™‚

#

I think I've bothered you with this template sensor for 3-4 days now - I really appreciate it

marble jackal
#

No problem

mighty ledge
floral shuttle
#

selecting all domain group entities works with {{states.group|map(attribute ='entity_id')|list}} Trying to do that with the integration_entities like {{expand(integration_entities('group'))|selectattr('domain','eq','group')|list}} doesnt..

#

I need to select the domain because otherwise it adds all other domains obviously

#

{{integration_entities('group')|select('search','group')|list}} feels like a hack..and it doesnt result in a correct list of groups, if the string is in the object_id.

#

how should I adapt the integration_entities template to only show domain group entities?

mighty ledge
#

The group integration covers all domains

#

Thatโ€™s why you have to filter the domain after

floral shuttle
#

sure, I understand that, it just doesnt work.. the result is []

mighty ledge
#

yes, because the group integration doesn't supply group entities

#

the integration entities only work with new integrations. The old group entities fall under 'not showing up' under integration entities as they aren't set up using config flow.

floral shuttle
#

hmm, if I do plain {{integration_entities('group')}} I get my group entities of domain group, with all other domains

#

yes they are yaml groups, but still show in the integration_entities. My hope was to only show those. My believe was they need a unique_id (which they all have) to show

#

and heck, I tried it with domain light {{expand(integration_entities('group'))|selectattr('domain','eq','light') |map(attribute='entity_id')|list}} and this results in a list of all light entities. So, not integration_entities('group') at all ..

#

whats even more remarkable: there's not a single grouped light in that listing!

#

so it does find the grouped light groups created via the UI, and effectively expands those to a list of single lights. It cant however return all grouped light groups?

mighty ledge
mighty ledge
#

I wrongly assumed that was the issue

floral shuttle
mighty ledge
#

there's nothing to fix though

#

expand always recurses into groups and expands them

#

just do expand on a single group entity

#

you'll see the ending result does not contain the group

#

@floral shuttle

#

by design

floral shuttle
#

Yes thatโ€™s what this boils down to: if you want a list of domain group entities, you need to use the states.group format

mighty ledge
#

right

#

so, it's not a bug

#

the original intent of expand was to expand groups

floral shuttle
#

I still would love to understand why the integration_entities() on its own does show the yaml groups but we can not not filter those

mighty ledge
#

because it's a list of entity_id's

#

and when you expand a group, the group entities are expanded....

#

it's not 'integration_state_objects', it's 'integration_entities'

floral shuttle
#

Hehe that would be nice though

mighty ledge
#

i.e. you get a list of strings, that are the entity_id's

trail estuary
#

I have this template:

    {% set new_level = trigger.to_state.attributes.brightness|int %} 
    {% if 0 < new_level < 10 %}
      10
    {% elif 80 < new_level < 100 %}
      150
    {% else %}
      {{ new_level }}
    {% endif %}

The first part (between 0 and 10) works, but the high end does not. The target entity is set to levels higher than 150...

#

What am I doing wrong?

marble jackal
#

@thorny snow Not sure what the trigger is and what the target is. Are they the same light?

#

But if you set the trigger entity to any brightness other then 1 - 9 or 81 - 99 , it will just use the brightness of the trigger entity, so this can go up to 255

inland peak
#

Hello everyone, I need some help with parsing an MQTT string from a motion sensor. Basically, I have a PIR sensor that replies in MQTT.

#

I want to set it up as a binary sensor so I added the following

    name: Wemos passive infrared motion sensor
    state_topic: "tele/Wemos_D1_V3.0_Test_bench/SENSOR"
    value_template: '{{ value_json.Switch7 }}' ```
to my binary_sensor.yaml
trail estuary
inland peak
#

Problem is, the reply I get is ACTION:ON or ACTION:OFF, which can't work as a binary sensor

#

how can I get it to only reply with switch7 and on or off, so the binary will work?

#

the full MQTT string from tasmota is "stat/Wemos_D1_V3.0_Test_bench/RESULT = {"Switch7":{"Action":"OFF"}}"

inner mesa
#

value_json.Switch7.Action

inland peak
#

ok, thank you

#

I think I tried that, but got an error. Maybe I did something else wrong then

#

Than worked, thank you.

#

Can I just keep piling on the variables after the dot, if I have even longer strings?

#

Will something like "value_json.Switch7.Action.Result.Data.Whatever" work if the string is this long?

inner mesa
#

You're indexing into a dict

#

If that's the data structure, yes.

#

It's important to understand what that's doing

inland peak
#

Yeah, I'm trying to understand the documentation, I just though it only accepted one variable after the dot, for some reason.

#

Thank you for the explanation

inner mesa
#
{% set value_json = {"Switch7":{"Action":{"Result":{"Data":{"Whatever":7}}}}} %}
{{ value_json.Switch7.Action.Result.Data.Whatever }}

-> 7

#

you can test this in devtools -> Templates

stuck kelp
#

Is there a means of getting last_value from an entity in templating?

#

Faking a cover and only have contact sensor on the top and bottom.
My idea is to do something like (in psuedocode):

{% if last_state was open %}
opening
{% elseif last_state was closed %}
closing
{% endif %}
inner mesa
#

Not like that, but you can with a trigger in an automation or template sensor

#

trigger.from_state.state

stuck kelp
#

I'll go that route, cheers mate!

deft sail
# mighty ledge Check out the breaking changes for MQTT this month.

Thanks, and I did, and for a minute I thought I had something but no such luck. I guess I can't find any examples close enough to anything I have to get things working. I listen to the top tele/Tasmota_RF2/# and when I open my door switch, I see the message {
"Time": "2022-06-27T21:49:52",
"RfReceived": {
"Sync": 14070,
"Low": 470,
"High": 1400,
"Data": "6E3E0A",
"RfKey": "None"
}
}, but U'm lost on how to get the rest working. I guess if all else fails I can wimp out and order a bunch of zigbee door swiches, but I liked the $3 mqtt switches and up till now they worked fine. Actually they still do but not for long I guess

torn gorge
#

Hello! I get an error and I would like which integrations is from. I don't have a template with this value query.

2022-06-28 10:12:56 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'float object' has no attribute 'temp' when rendering '{{value_json["temp"].value}}'

Any tipps how to debug this?

supple shadow
#

Going a little crazy trying to configure something that should be simple. I have a button and clicking on it is calling a script, I want to include some arguments when I call the script to be used as variables inside the script.

  action: call-service
  service: script.start_music
  data:
    myMessage: The light is on!

Script

service: system_log.write
data:
  message: '{{ myMessage }}'
#

But myMessage always evaluates to empty, I've tried sending the data via the variables format as well as the format posted above, which appears to be correct according to the documentation

mighty ledge
#
  action: call-service
  service: script.start_music
  service_data:
    myMessage: The light is on!
#

data isn't valid for tap_action, service_data is.

#

Hold the phone on that

#

data might be valid now

#

depends on the version you are running

supple shadow
#

What assumption sorry?

#

Ah, I'm on 2022.6.6 I believe. I didn't see anything specific to tap_action, perhaps that is the problem

mighty ledge
#

the assumption of data being a valid key

#

doesn't matter, looks like it's now valid

#

that must have changed in one of the last 2 versions

#

it's always been service_data and it always bites everyone in the ass

#

anyways, if that's not your problem, it's the capital M in myMessage

#

also, it could be your script because your script isn't a valid script, but it is a valid service call. Is that your entire script?

supple shadow
#

No just a snippet of the script - the script does run fine until the point that myMessage is required.
Are these keys case insensitive? re: your comment on the capital M

mighty ledge
#

yes

#

they are, but typically HA does not like any capitals

#

in the keys

supple shadow
#

That's odd, though I'm not a python developer so not too sure.

I can confirm that service_data does work, with the key myMessage

mighty ledge
#

so you'd have to change both your tap action and your script to have mymessage

mighty ledge
#

you're on 2022.6.6 for sure?

supple shadow
mighty ledge
#

for the UI

supple shadow
mighty ledge
#

tap-action is not the same as a script action

supple shadow
#

Ah I didn't know that - perhaps we can add a note in the script documentation to mention the difference when calling from the UI and link to that perhaps

#

Got it

mighty ledge
#

You're welcome to suggest an edit

supple shadow
#

Done, thanks for the help

mighty ledge
#

np

mighty ledge
supple shadow
#

the version I copied above I took directly from my settings page, I just updated from 2022.4.x about a week ago. And yes as soon as I tweaked it to use service_data then I saw that the message showed in the logs. I cleared the log and ran a second test to be sure and then changed back to data and another test showed it stopped working then

#

๐Ÿคท

mighty ledge
#

are you willing to write up an issue on the frontend for this?

supple shadow
#

Hmmm, that would be odd. I can look into it further in the morning

mighty ledge
#

I think you have enough info

supple shadow
#

Yeah, first I will do some looking around - I may step through the frontend code.

mighty ledge
supple shadow
#

I'm not particularly familiar with the code base but here's an opportunity to get to know the frontend

mighty ledge
#

FYI, service_data was changed to data in 2022.6.x

supple shadow
#

Interesting - do you know where the change was centrered? Was this a change in the backend as well, or just how the frontend works with it

mighty ledge
#

Just keep in mind scripts are wierd in the backend

#

if you call a script with variables using the script.turn_on service call, you need to provide the data like this:

#
service: script.turn_on
target:
  entity_id: script.xyz
data:
  variables:
    myvariable: xxx
#

where as, if you call it via the script itself, you do not

service: script.xyz
data:
  myvariable: xxx
supple shadow
#

Yes I gave that a good go while I was debugging earlier trying to find the right format

mighty ledge
#

so, if you want to, you can add the following tap actions to your testing

#
action: call-service
service: script.xyz
data:
  variables:
    myvariable: xxx
action: call-service
service: script.turn_on
data:
  entity_id: script.xyz
  variables:
    myvariable: xxx
supple shadow
#

OK - got it. It was me being new to custom components. I had written this in YAML and not considered how this may get configured via the YAML. I was using a custom component that I did not update, so it must have been expecting service_data before the update. I hadn't thought to look at what I was actually configuring in the end

mighty ledge
#

Ah

#

ok

#

that makes sense

supple shadow
#

I'd naively looked at the data payload as just a dynamic object but I guess it was validating or parsing it and obviously not happy with data

#

I have learned my lesson there I suppose

mighty ledge
#

well custom stuff is the wild wild west and they typically don't use the built-ins from HA

#

which means they need to keep it up with HA instead of utilizing HA updates

#

what's the custom element?

supple shadow
#

mushroom-entity card

mighty ledge
#

ah, i'd just write up an issue with that

#

they probably don't know about it

#

it's been service_data for 5 years at this point

supple shadow
#

Actually it looks like I just need to update it which I will do

silent vector
#

Hey Petro, I know thefes helped me with this but not sure if you could help explain why after 20:00 next start is 05:30 when it should be 00:00. I assume it's something to do with 00:00. Next start works correctlt for all other times. Right now it's 08:11 and next start is 15:00
https://dpaste.org/zCF4W

marble jackal
#

It's because of the default I used

silent vector
#

Oh you are here lol.

marble jackal
#

Your data didn't have a start at midnight, that was only added because the day starts then

#

So I made the default pick the 2nd item in the list instead of the 1st

#

{{ (hours[index + 1] | default(hours[1]))[0] }}

#

There

silent vector
#

Oh ok now that I have a 12am it can be removed?

#

The default*

marble jackal
#

If you change hours[1] to hours[0] it will start at midnight

silent vector
#

{{ (hours[index + 1] | default(hours[0]))[1] }}?

marble jackal
#

The default itself is still needed, because [index + 1] will fall if the current time is the in the last time block

silent vector
#

Makes sense. So a having a 12am is a must if I am to change this {{ (hours[index + 1] | default(hours[1]))[0] }} to selecting the first number?

#

{{ (hours[index + 1] | default(hours[0]))[1] }} is that correct?

marble jackal
#

Yes, correct

silent vector
#

Sounds good thank you as always. I'll note that and use that.

marble jackal
#

๐Ÿ‘

inner mesa
mighty ledge
#

I had no clue it was changed until I went and looked at the docs

#

It wasn't covered in the RN

inner mesa
#

It was annoying, so I'm all for the change

mighty ledge
#

yep

floral shuttle
#

trying to smarten up some templates I was wondering if we have the means to make this shorter:```
{% set x = ['unavailable','unknown'] %}
{{trigger.to_state.state not in x and trigger.from_state.state not in x

floral shuttle
mighty ledge
floral shuttle
#

i mean: trigger: platform: event event_type: call_service event_data: domain: persistent_notification service: create action: service: notify.system data: message: > {% set message = trigger.event.data.service_data.message %} etcetc

mighty ledge
#

Yes, but that's the call_service event

floral shuttle
#

sure. I just did a service_data full config search and this came up ๐Ÿ˜‰

mighty ledge
#

right but that's not changing

floral shuttle
#

so its a 'replace here, but not there' thingy

mighty ledge
#

and has nothing to do with the frontends tap action

#

you think it would be more readable if it was replaced?

floral shuttle
#

no!

mighty ledge
#

so it would be trigger.event.data.data.message?

floral shuttle
#

tbh, I didnt mind the service_data at all, as it was very clear what it stands for.

mighty ledge
#

it does, in the context of the event

#

it doesn't in the context of tap-action

floral shuttle
#

still, getting back to frontend services on buttons: it would be good if custom cards would adopt the same

sturdy juniper
#

Hey peoples..
I have 5 entities that have an attribute (MAC adress)
I'd like to create a template sensor for each that changes value depending what the attribute's state is.
I know how to do this with a large if-elseif structure, but I was wondering if any of you wizards knew a cleaner way to achieve this ?

floral shuttle
# mighty ledge it doesn't in the context of tap-action

it would be even easier if instead of: tap_action: action: call-service service: input_boolean.toggle service_data: entity_id: input_boolean.dst or now: tap_action: action: call-service service: input_boolean.toggle data: entity_id: input_boolean.dst we could do: tap_action: action: call-service service: input_boolean.toggle entity_id: input_boolean.dst but I believe we even need a target: there now. Or is that only backend. yes. o well

rose scroll
#

Fill in the blanks appropriately.

sturdy juniper
#

thanks !!! ๐Ÿ‘

mighty ledge
#

try it, you'll see it produces an UndefinedError: 'attribute_state1' is undefined

sturdy juniper
#

Ah.. ๐Ÿ™†โ€โ™‚๏ธ

mighty ledge
#

just put single quotes around attribute_state1, like this 'attribute_state1'

rose scroll
#

Yup that's what I meant. Petro's right!

sturdy juniper
#

perfect ๐Ÿ‘Œ

sacred sparrow
#

My weather sensor shows 3 states (Min, max and current temp) in the UI on dashboard. is there a way to make a template sensor that does the same?

karmic lotus
#
{% set lights = expand(area_entities('my_area')) %}
{{ lights | selectattr('state', 'eq', 'on') | list | count > 0 }}

How can I filter out any entities that aren't lights in this expression?

#

Nevermind got it ๐Ÿ˜„

#

selectattr("domain", "eq", "light") did the job

buoyant sapphire
#

if i have a sensor which result type is "number", how can i compare that?

my sensor has the value "136".

this here (correctly) returns "true"

{{ states("sensor.lumi_lumi_sensor_motion_aq2_d0a28e07_illuminance") < "150"}}```

however this here also (and its false) returns "true"

{{ states("sensor.lumi_lumi_sensor_motion_aq2_d0a28e07_illuminance") < '50'}}

floral shuttle
#

you need to make a 'number' of that illuminance state, because currently it is a 'string' and you can not compare a string to a number. Right now you make a string out of the number and you're comparing 2 strings ๐Ÿ˜‰

#
  state: >
          {{states('sensor.mean_outdoor_lux')|float(0) <
            states('input_number.outdoor_low_lux')|float(0)}}```
#

so in you're case: {{states("sensor.lumi_lumi_sensor_motion_aq2_d0a28e07_illuminance")|float(0) < 50}}

buoyant sapphire
#

thank you @floral shuttle . i tried with | float as well as | int, but somehow didnt use it correctly. - thanks for clarifying and your time ๐Ÿ™‚

thorny snow
#

trying to make humidity/temperature sensor to work on homekit

#

how? ๐Ÿ˜„

#

thank in advance

floral shuttle
#

you really should check the section on how to ask a question in #rules

silent vector
# marble jackal Yes, correct

It's selecting the second time now for all times lol. Not sure why. I'm using
{{ (hours[index + 1] | default(hours[0]))[1] }} just as you said.

silent barnBOT
lyric gazelle
#

Hello,
I have never got around to learning to do my own templates, i have always reversed other peoples work, but not i am a bit stuck and wondering if anyone would have any tips for me.
I have setup a scraping to pull the current price from my profile at my energy company.
And i get the value back (but also contaning the price/kWh)
This is what i am getting though the API of the scraping tool and what i am "trying" to do with HA.
https://www.toptal.com/developers/hastebin/toviqatuze.less
Anyone got any suggestions, it would be greatly appriciated!
Cheers

floral shuttle
#

so you're asking how to split that value and take out the kr/kWh bit?

lyric gazelle
#

@floral shuttle Yes, just getting the numbers out ๐Ÿ™‚

floral shuttle
#

you do that with the split function, find it in the template docs and see if you can make it

#

use {{value_json[0].selection5.split(' kr/kWh ')[0]}} and see what happens

lyric gazelle
#

Thanks @floral shuttle , just to make sure ( you are refering to the Jinja docs right? )

floral shuttle
#

what that does, it splits the value at the string between quotation marks, and next selects the first ([0]) item

lyric gazelle
#

Cool, thanks, rebooting HA now

floral shuttle
#

why?

lyric gazelle
#

Loading the changes to the rest sensor?
Or did i miss something?

floral shuttle
#

you can reload rest sensors in the Yaml dev tools, or by hitting 'c' (for the quickbar)and select rest

lyric gazelle
#

LOL! Cheers, missed that aswell ๐Ÿคฆโ€โ™‚๏ธ

rain crescent
#

i feel this is probably pretty simple, but i'm trying to build a template filter that includes both a device state and a device class (All open doors / windows). Can anyone help? This obviously doesn't work as thing.* is from the state class

{% for thing in states %}
{% if thing.state == "on" and thing.device_class == "door" %}
{{ thing.entity_id}}
{% endif %}
{% endfor %}
#

I've seen examples where folks manage a group of devices so they only have to expand the group and filter on the attribute. Was hoping to keep this dynamic.

#

IE "{{ expand('group.doors_windows')|selectattr('state','eq','on')|list|count }}"

lyric gazelle
#

Thanks @floral shuttle it comes back with "unknown" unfortenetly, but i can try and read a bit of the docs also

floral shuttle
#

add |selectattr('attributes.device_class','defined') |selectattr('attributes.device_class','eq','door')

rain crescent
floral shuttle
#

did you test it?

rain crescent
#

yeah, nothing atm. validating my zigbee sensor is open

floral shuttle
#

but why not use the {{ expand('group.doors_windows')|selectattr('state','eq','on')|list|count }} you posted ?

rain crescent
#

group.doors_windows isn't built in is it?

floral shuttle
#

I thought you had that..

rain crescent
#

ah, nope, sorry, that was the example I found online

floral shuttle
#

the use states

rain crescent
#

actually I wonder if i could build a dynamic object of entity IDs that are in state open and then filter on device_class attribute

floral shuttle
#
   {{states
            |selectattr('attributes.device_class','defined')
            |selectattr('attributes.device_class','eq','door')
            |selectattr('state','eq','off')
            |map(attribute='entity_id')|list}}```
#

needed off, because all of my doors are closed ๐Ÿ˜‰

rain crescent
#

awesome. thank you!! ๐Ÿ™‚

floral shuttle
#

you know you can have auto-entities do this for you, if you only need it in the frontend?

silent barnBOT
rain crescent
#

huh, cool bot.

#

ah, guessing you mean I could use the include: filed with auto-entities instead of the template: one?

floral shuttle
#

no, but seeing what you have in the auto-entities is my exact suggestion, I wonder why you asked in the first place ?

rain crescent
#

just put your suggestion into it. the template that I had in before was the one I pasted to start.

#

It works as expected. Thank you!

mighty ledge
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.

floral shuttle
#

a ok,. And I meant if you dont need it in the backend, you can do it all in the frontend

#

saves you another template sensor

rain crescent
#

ahh, so no need to create a template group, just have the auto-entities filter it directly.

#

yup, got it. Thank you again!

marble jackal
silent vector
#

It returned 06:30 when it should have been 05:30 and right now 19:00 when it should be 15:00

marble jackal
#

Ah, that's because the last part should be [0]

#

You are now taking out the end time of the next block

#

You should use {{ (hours[index + 1] | default(hours[0]))[0] }} if 00:00 is valid as next_start, otherwise {{ (hours[index + 1] | default(hours[1]))[0] }}

silent vector
#

I see. I'm trying to add this condition to the schedule we worked on and I can't seem to get it right. https://dpaste.org/YMphg
In the last elif statement I'm trying to say, if the thermostat is equal to 'climate.daniel_s' and the time is after 20:00 or before 06:00 and one of 2 things is occuring. Either the temperature before next start is above 65 or the current temperature of master bedroom is less than or equal to 62 then +3. It worked before I added the above 65 part. It didn't isolate the thermostat and increased another thermostats temperature lol. I also tried using a set Boolean and that didn't work either oddly.

marble jackal
#

Well, you use a variable next_start in that template, but you do not define it anywhere

silent vector
#

It's defined. I'm updating the dpaste

#

Couldn't update heres the entire script, all variables 'not defined' are passed from the automation. Something is up with my elif that's all. https://dpaste.org/0XrOz

floral shuttle
marble jackal
#

Maybe add some brackets {% elif thermostat == 'climate.daniel_s' and (state_attr('climate.master_bedroom', 'current_temperature') <= 62 or (thermostat == 'climate.daniel_s' and temp | select('>', 65) | list | count > 0)) and (now() >= today_at('20:00') or now() <= today_at('06:00')) %}

#

Don't know if I put them in the right place now, but this seemed logical to me

silent vector
#

It worked. I tested changing the time to make it true right now and a different thermostat. I was wondering what the (now() was for instead of now() what does that do? These brackets break it up and make it do?

mighty ledge
#

or my dear aunt sally blah blah blah

silent vector
#

Oh my lol the pemdas again. To control how home assistant reads it even without doing math use that?

mighty ledge
#

parenthesis, exponents, division, multiplication, addition, subtraction

silent vector
#

Although I guess the now() is math

#

<=

mighty ledge
#

that's a method/function

silent vector
#

I see. Didn't realize that pemdas applied to that as well.

mighty ledge
#

for jinja, it's more like

#

fpedmase

silent vector
#

Going to take note of that.

mighty ledge
#

filters/functions, parenthesis, exponents, division, multiplaction, addition, subtraction, equal signs

silent vector
#

Makes sense.

mighty ledge
#

coding is math btw

#

so, always applies

silent vector
#

Good to know.

mighty ledge
#

I might have that order wrong

#

either way

#

just remember the math pedmas

silent vector
#

I will lol before I come back here with another issue only to have you popup again and say pemdas for probably the 3rd time now or peppridge farm remembers pemdas

paper hazel
#

Is there a way to create a group dynamically using a wildcard in the entity_id name. For example, on startup create a group called securitylights, and add all entities with the name starting light.security* to it? I received a recommendation to ask here to assist with how such a template will look, to use with group.set.

marble jackal
#

Yes, sure

#

Using the group.set service call, and a template

#

{{ states.light | selectattr('entity_id', 'match', '^light.security') | map(attribute='entity_id') | list }}

paper hazel
#

Thank you!

silent seal
#

I'm sure I'm missing something obvious, but I get these errors pop up in the logs from time to time:

Template error: float got invalid input 'unknown' when rendering template {{ float(states('sensor.switchbot_lounge_curtain') | default(0)) }}'but no default was specified
The thing is, I do have a default specified?

inner mesa
#

I suspect that 'default' just checks for None or similar.

#

The better way to do it is with states()|float(0)

silent seal
#

Cool, I'll give that a shot, thanks ๐Ÿ˜„

inner mesa
#

Point is that 'unknown' is a perfectly good value for default()

silent seal
#

Yes, which is annoying but understandable.

tepid onyx
#

I've always wondered whats the difference between:
"{{ states('remote.hu01_lounge') == 'off' }}"
and
"{{ is_state_attr('remote.hu01_lounge', 'off' }}"
or is it just another way to write it? is there some point to having an is_state ?

inner mesa
#

they're quite different ๐Ÿ™‚

#

perhaps you meant:
"{{ is_state('remote.hu01_lounge', 'off' }}", in which case they're nearly or completely the same

tepid onyx
#

oops yes, not is_state_attr I mean't is_state

inner mesa
#

from the docs:

It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isnโ€™t ready yet (e.g., during Home Assistant startup).

tepid onyx
#

yah I saw that but is there any other differences I wonder. It's just OCD and coding semantics for me but I am curious. I use both interchangeably but it's always been a question for later

#

Just to keep twisting the knife, the docs say: "It is strongly advised to use the states(), is_state()," which is both. I think that refers to the old format like states.something.attributes.someattr for e.g.

silent seal
#

Well, is_state won't throw an error when it's not available yet, which is pretty nice

tepid onyx
#

neither will states() ?

silent seal
#

True. I was thinking of states.blabla.thingy.whatsit which of course will

mighty ledge
# tepid onyx neither will states() ?

is_state has a subtle difference where none is explicitly built into the check. Meaning, it will always be false if the entity doesnโ€™t exist. Where as states() will return none of it doesnโ€™t exist. If youโ€™re checking for a valid state, it doesnโ€™t matter what youโ€™re using. If youโ€™re checking for none, do not use is_state

#

is_state(โ€ฆ, none) will be false where states(โ€ฆ) == none will be true.

#

Technically you shouldnโ€™t use == none anyways

#

Anyways, super subtle differences

lean jay
#

Hey can someone help? I@ trying to change this input select of my air purifier into a light switch so I can control itโ€™s with a slider:

#
trigger:
    - platform: state
entity_id: select.kids_sensible_pure_light
action:
    - service: switch.turn_on
data_template:
               entity_id: >
                {% if   is_state('select.kids_sensible_pure_light', 'on') %}
                  switch.on
                {% elif is_state('select.kids_sensible_pure_light', 'dim') %}
                  switch.dim
                {% elif is_state('select.kids_sensible_pure_light', 'off') %}
                  switch.off
                {% endif %}```
silent seal
#

Your spacing is horribly off for yaml

silent barnBOT
#

YAML is the mark up language used by Home Assistant, consistent indenting (two spaces per level) is key. Here is a primer, and this explains multi-line templates. For validating YAML see YAML Lint.

#

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.

lean jay
#

I ran it through the YAML editor then reposted into configuration.yaml file but still got these errors:

#

Integration error: action - Integration 'action' not found. Integration error: entity_id - Integration 'entity_id' not found. Integration error: data_template - Integration 'data_template' not found. Integration error: alias - Integration 'alias' not found. Integration error: trigger - Integration 'trigger' not found.

inner mesa
#

that just indicates that your indentation is still "horribly off"

tulip ridge
#

Hey, does anybody know how I can template a electricity meter sensor? I have the current usage of my home: 130 W and I want ja meter that shows 1 kWh after aprox. 8 hours. The "utility meter" shows 2 kW after 30 minutes. Don't know what that means ๐Ÿ˜„

marble jackal
tulip ridge
#

@marble jackal thank you that is looking promising. now how can i get this sensor into the energy dashboard?

#

as "Grid Consumption"

marble jackal
tepid onyx
floral shuttle
#

so i was confused about the new bool() function. believed it to be a boolean tester. But it seems to be more of a translator really

#

I now wonder where we can use that optimally. just tried to use is as 'availability template' replacement in my mqtt sensors on a value. (replacing value_template: > {{value if value in ['on','off'] else none}}but there it re-states the on/off to true/false rendering all of my sensors unknown...```
- unique_id: amp_left_auditorium_state_binary
state_topic: '70:B3:D5:6F:31:F2/powerswitch-zwave/c5745b57/state'
name: Amp left Auditorium state
<<: &binary
payload_on: 'on'
payload_off: 'off'
device_class: power
value_template: >
{{value|bool(none)}}

#

and it that sense it is truly different from eg the is_number() ```
value_template: >
{% set maximum = 2400 %}
{{ [ value | round(2), maximum] | min if value | is_number and value | float >= 0 else none }}

mighty ledge
#

it's like float or int

floral shuttle
#

yes, I guess that was my misunderstanding. probably because I had been looking for such a test and wish was father of the thought (Dutch saying...) Still. it's not completely like float and int either, because bool changes/translates the outputs state and not type? (unless they're true/false already)

mighty ledge
#

no, its exactly like float or int

#

it changes a string to a boolean

#

boolean is always true/false, nothing else

#

it translates on, off, true, false strings to True or False

hexed wing
#

probably because I had been looking for such a tes

mighty ledge
#

I've thought about adding a is_boolean filter/function for templates

floral shuttle
#

right! so I should be doing: {{value if value is boolean else none}}

mighty ledge
#

yep, but you can't use that as a filter

floral shuttle
mighty ledge
#

is for some reason is not a valid test for selectattr, select, etc

floral shuttle
#

well, in that case the is_boolean() would be most welcome still

#

cant post in an image but the value is boolean doesnt work as expected, returning null, both in the mqtt config, and in template editor (Result type: dict) using: {% set value = 'off' %} {{value if value is boolean else none}}

languid moat
#

I have a Zigbee light strip for which I have created 4 scenes. I also have a Zigbee button (Sonoff SNZB-01) that I was to configure to cycle through those 4 scenes. The state of these scenes gets updated with a date/time string, instead of on/off. I haven't been able to fingure out how to create this list of scenes and have each button click active the next scene in the list. I was thinking a template could do this, but I'm not having much luck. Might anyone have an idea how to do this?

marble jackal
floral shuttle
#

yes, but it should have returned True...

marble jackal
#

Ah, right

floral shuttle
#

or 'off', in this case, sorry

#

heck what role do we need for an image.....

marble jackal
#
{% set value = "off" %}
{{ value if value | bool('no boolean') is boolean else none }}
#

You actually need the new filter here

floral shuttle
#

yep that works!

#

however, it is a bit unexpected we need that to be able to test the is boolean...

#

replacing {{value if value in ['on','off'] else none}}

inner mesa
#

That's the test you were doing

marble jackal
#

Well the string "off" is not a boolean

floral shuttle
#

but off is and {{off is boolean}} still returns False

#

btw, have changed all of my binary_sensors to you suggestion and confirm that is working as it should

inner mesa
#

It is not a boolean

#

That is a variable

floral shuttle
#

hmm. so, cut it short, first I need to 'translate' it to a boolean with |bool, and than test if that is boolean, else it renders null

inner mesa
#

UndefinedError: 'off' is undefined

#

{{ off }}

floral shuttle
#

yep see that now. interesting

inner mesa
#

There aren't many reserved words

floral shuttle
#

guess in ['on','off'] already proved that, being a string in a list, and not a boolean perse/at all

#

thx, til

mighty ledge
#

is boolean literally checks to see if a value is a boolean object

#

'off' or 'on' are strings, so is boolean will return false

manic tartan
#

Hi. Is there a way to create a data dict in template ("missing" append() method for dict)? The below doesn't work, tried to write it down as python-like syntax ๐Ÿ™‚ -> TemplateSyntaxError: expected token 'end of statement block', got '['
(the goal is to use that data dict in next service call)
{% set nm = namespace() %} {% set nm.data = {} %} {%- for key in [ key1, key2, key3] %} {%- set nm.data[ key] = 'value' %} {%- endif %} {% endfor %} {{nm.data}}'

inner mesa
#
{% set nm = namespace(data={}) %}
{% for key in ['key1', 'key2', 'key3'] %}
  {% set nm.data = dict(nm.data, **{key: "value"}) %}
{% endfor %}
{{ nm.data }}

->

{
  "key1": "value",
  "key2": "value",
  "key3": "value"
}
#

aside from the namespace syntax, this is the magic:
{% set nm.data = dict(nm.data, **{key: "value"}) %}

manic tartan
#

Thanks.

#

It seems this 'unpack' operator do the trick. I have to check how and why. Never seen/used this in Python.

inner mesa
#

the most common usage in Python is with an argument list including **kwargs (keyword arguments)

manic tartan
#

Example 3: Creating dictionary using iterables
The keys and values can be passed to dict() in form of iterables like lists or tuples to form a dictionary and keyword arguments can also be passed to dict().

Syntax:

class dict(iterable, **kwarg)

inner mesa
#

I confess that I have that bit of code in a note that I can refer back to

manic tartan
#

So this is why it has added new key/value, not replacing.

inner mesa
#

I understand it, but would have trouble coming up with it from scratch

manic tartan
marble jackal
#

You can also use it to change a value in a dict:

{% set test = {
  "key1": "value",
  "key2": "value",
  "key3": "value"
} %}
{% set test = dict(test, **{"key2": "new value"}) %}
{{ test }}
manic tartan
#

This 'magic' will be very, very useful to prepare data dict in one template pass. .

marble jackal
#
{
  "key1": "value",
  "key2": "new value",
  "key3": "value"
}
manic tartan
#

This 'update' scenario is also very usable. Thanks for recalling this.

manic tartan
#

It looks it works like a charm ...
sequence: - variables: loggers: >- {% set nm = namespace(data={}) %} {%- for object in states.input_select %} {%- if object.entity_id | regex_search('^input_select.logger_.+') %} {%- set logger = object.entity_id.split('_')[2].upper() %} {%- set level = states( object.entity_id) %} {%- set nm.data = dict( nm.data, **{logger: level}) %} {%- endif %} {% endfor %} {{nm.data}} - service: logger.set_level data: "{{loggers}}"

#

I have a set of helpers to set log_levels on-the-fly and needed script to restore logger levels after restart.
{ "LIGHTS": "info", "MANUAL": "debug", "MOTION": "info", "OTHERS": "debug", "STATUS": "debug" }

#

BTW, have you 'kind of' reusable library methods for common sensor parsing/listing/selection or using specific, dedicated templates in scripts/automations? Just wondering if is good practice to have a common, reusable script (or templates macro) for 'selection sensors by regex match' in this case or leave it as is as template evaluated variable.

marble jackal
#

Please don't share images of text, if someone wants to suggest a correction, they will have to type it all over

#

.share the code using a code sharing website

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.

mighty ledge
#

if you want to use spaces...

#
{%- set nm.data = dict.from_keys(nm.data.items() | list + [(logger, level)]) %}
civic cargo
#

I'm trying to use a template to trigger an automation an hour before high noon.
It works as intended when testing using the Template editor, but does not trigger when in an automation.
Creating just a single line without the constants also works as intended.

Are setting values the way I am not supported for Automation triggers, or could there be something else wrong?
(I'm aware of the strategy of creating a helper to use as a constant, but I prefer the idea of everything being together -hence my current attempts)

{% set hours_to_offset = -1 %}

{% set hour_in_sec = 3600 %}
{% set time_offset = hour_in_sec * hours_to_offset %}

{{ (as_timestamp(state_attr('sun.sun','next_noon')) + time_offset) | timestamp_custom('%R',true) == states('sensor.time') }}

mighty ledge
unique gyro
#

Hello! ๐Ÿ™‚ Iโ€™m having a hard time setting up a binary sensor around a zha_event. According to this topic, it should now be possible : https://community.home-assistant.io/t/wth-dont-we-have-event-binary-sensors/219658/21 but when trying it, it only displays unavailable. I verified the template documentation but I should be fine according to it. Is my template wrongly formulated according to the event? Hereโ€™s the configuration : https://dpaste.org/vozGE and an image for reference : https://i.ibb.co/FVSR8Q5/Binary-sensor.png

civic cargo
mighty ledge
marble jackal
#

Doesn't something like this need an auto_off? How will it ever turn off after it has been turned on otherwise?

acoustic arch
#

how can i join variables as string into a new variable?

{% set jaar = (now().year)  %}
{% set maand = (now().month)  %}
{% set gecorrigeerde_tijd = dag-maand-jaar %}```
That last one does a match calc instead of making it a string. but donno the syntax...
#

quoting doesnt work... forum searched but not found

unique gyro
mighty ledge
#

th'eres a bajillion forum examples of that and what you're asking fuzzy

#

if you justr want to join the ints and get a string back instead, just use ~ instead of -

acoustic arch
mighty ledge
marble jackal
#

{{ now().strftime('%D-%M-%Y') }}

unique gyro
marble jackal
#

If you don't want the leading zeros, check the link petro sent

acoustic arch
#

ill have a tinker with that!

mighty ledge
#

aslo, add a - before trigger:

#

- trigger:

#

keep trigger in with binary_sensor though

#
template:
- trigger:
    - platform: event
      event_type: zha_event
      event_data:
        device_ieee: 00:08:89:00:01:d9:df:f2
        unique_id: 00:08:89:00:01:d9:df:f2:18:0x0006
        device_id: 7d98ffa3028511eb9091ab77437cf133
        endpoint_id: 18
        cluster_id: 6
        command: on
  binary_sensor:
    - name: Sonnette
      state: "true"
      device_class: sound
      auto_off: 4
#

oh

#

I see another

#

wrap on in quotes 'on'

#
template:
- trigger:
    - platform: event
      event_type: zha_event
      event_data:
        device_ieee: 00:08:89:00:01:d9:df:f2
        unique_id: 00:08:89:00:01:d9:df:f2:18:0x0006
        device_id: 7d98ffa3028511eb9091ab77437cf133
        endpoint_id: 18
        cluster_id: 6
        command: 'on'
  binary_sensor:
    - name: Sonnette
      state: "true"
      device_class: sound
      auto_off: 4
unique gyro
acoustic arch
# marble jackal `{{ now().strftime('%D-%M-%Y') }}`

still confusing. I have a time string which i have parsed to a time with {{ strptime(starttijd_regen, "%H:%M")}}

Now i need to ADD current date only, since i have the time already. This to get rid of 1900-01-01

{{ now().strftime('%d-%m-%Y') }} gives me a date but how to add both to a timeobject..

#

going to as_timestamp and add both?

unique gyro
#

Yay it works! ๐Ÿ˜„ Strange that it shows unavailable at first. Once it sees the event, the binary sensor show available.

civic cargo
# mighty ledge ``` {{ state_attr('sun.sun','next_noon') | as_datetime | as_local - timedelta(ho...

@mighty ledge I'm impressed with what you shared earlier and have tweaked some other projects using what I've learned.
I'm curious if there's a sexier way to do either of these:

This checks my google calendar to see if I have a work event today
{{ as_timestamp(state_attr('calendar.work_calendar','start_time')) | timestamp_custom('%F', true) == states('sensor.date')

This checks my google calendar to see if I have a work event on the day that is in 9 hours (This runs when I go to bed, and so effectively checks if I will be working when I wake up, even if it's checking after midnight)
{{ as_timestamp(state_attr('calendar.work_calendar', 'start_time')) | timestamp_custom('%F', true) == (as_timestamp(now()) + (9 * 3600)) | timestamp_custom('%F', true) }}

PS: I hope I don't sound like I'm asking you to do my work for me, and I'm sorry if it does. I really want to learn. You don't owe me anything โค๏ธ

silent seal
#

You can use a timedelta to explicitly add 9 hours by the way instead of multiplying by 3600 ๐Ÿ˜‰

#

But, you should probably look at the today_at('9am') filter, that might be a lot easier to work with ๐Ÿ˜‰

#

E.g.

{% set start_time = state_attr('calendar.france', 'start_time') | as_timestamp  %}
{{ start_time == today_at(start_time| timestamp_custom('%X', true)) }}
civic cargo
#

I appreciate the example.
Syntax is often a struggle for me.

silent seal
#

I had to switch out your calendar to one that I have, but I think it's easy enough to swap it back

civic cargo
#

For sure.
I'm excited to tinker with this more soon

silent seal
#

Also, if you're sharing a short template like that, you can put three ` on a line with py after them, your example, and then another line with three more backticks for better formatting. (py being python, yaml being yaml, etc.)

#

Though in general, it's best to use a code sharing site ๐Ÿ™‚

civic cargo
#

#Learning
Good to know.
Thank you ๐Ÿ™‚

silent seal
#

No problem. I've stolen plenty from Petro myself ๐Ÿ˜‰

#

After all, automation is all about not having to do the thing yourself ๐Ÿ˜›

orchid oxide
#

How do I check to see if an entity exists

#

States.domain.object_id returns a dict null but how can I check for that

inner mesa
orchid oxide
#

ahh, none without quotes, gotcha. tried null and 'none'

inner mesa
#

Anything with quotes is a string

manic tartan
mighty ledge
silent vector
#

Can you do an include in a templates file? To modularize the file by breaking out groups of related templates? Would that still work using reload templates and how would that be done?

marble jackal
#

I don't think you can do that. There is an include function in jinja, but I could not get it working in devtools

silent vector
#

I meant in the file itself. I should have said in the template sensors file my mistake. I'm referring to inside of a templates.yaml

marble jackal
#

You can use YAML anchors

silent vector
#

Also I created a start time on the schedule we worked on the start is a string. How would I make a template that checks If the time now is 5 minutes or greater than start. For example the output of start may be start: '05:00'. What's the format for using a yaml anchor?

marble jackal
#

You can use today_at(start)

#

now() - timedelta(minutes = 5) > today_at(start)

silent vector
#

Perfect, that worked. That would allow me to say in English (include this file 'schedules.yaml' of templates)?

marble jackal
#

You can only use anchors in the same yaml file

silent vector
#

I remember a video on Dr zzz channel with Frenck where he said he broke out his automations file into various sub files but I wasn't sure if that could be done with templates and still be reloadable.

marble jackal
#

I use one file per automation myself

silent vector
#

That same thing can't be done in templates? Put 5 template sensors into a file? Then include that file in the templates file so that it's read as 1 file?

marble jackal
#

I also have (mostly) all my template sensors in separate files

#

But 5 in one file would also work

silent vector
#

Yes that's exactly what I'm looking for. How would I do that? My file is getting full of related templates that could easily be separated for sanity.

marble jackal
#
template:ย !include_dir_listย /config/include/template/
#

That is the line used to include the folder

silent vector
#

You put that line in the main templates.yaml?

marble jackal
#

No, you could place it in configuration.yaml. I don't have a templates.yaml

#

But I've gone quite far in splitting the configuration,

silent vector
#

I understand now. That points to a directory that includes all files within that directory and this can be reloaded from UI still?

marble jackal
#

Yes

silent vector
#

Awesome thank you.

civic cargo
#

{{ (state_attr('calendar.work_calendar','start_time') | as_datetime | as_local).date() == (now() + timedelta(hours=9)).date() }}

silent seal
#

So it picks "today" or "tomorrow" automatically? unless I've massively misunderstood and forgotten all my dutch ๐Ÿ˜‚

civic cargo
#

I'm tinkering with now() in an attempt to use it as an automation trigger.
{{ now() }} reports back with a 6 digit decimal, which isn't suitable for a trigger.

Is there a way to remove those decimals?

I'm aware of sensor.time, which may very well be the best solution (and so my question may be silly), but I'm more asking to improve my understanding of these systems.

inner mesa
#

{{ now().replace(microsecond=0) }}

#

you can change the other components, too: hour, minute, second

silent seal
#

I can't believe I didn't think of doing that. You're a genius

civic cargo
inner mesa
#

yes, Jinja uses Python data types and you can use Python methods on them

civic cargo
#

Can Jinga use Python data types in the same way Arduino can use C++ functionality?

#

Not identical, but built off the other and some added tools

inner mesa
#

I have no idea how Arduino uses C++ functionality. The reality is that Jinja uses Python data types

cobalt otter
#

What's wrong with this snippet as a Template Sensor? - sensor: - name: "Freezer1 Temp" unique_id: "freezer1_temp_id" state: {{ states(sensor.freezer_temp_1) | float * 2.0 }}

#

Gives me an error: Error loading /config/configuration.yaml: invalid key: "OrderedDict([('states(sensor.freezer_temp_1) | float * 2.0', None)])" in "/config/configuration.yaml", line 70, column 0

inner mesa
#

the indentation is pretty hard to make out ๐Ÿ™‚

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).

cobalt otter
#

I'll put it in a pastebin.

inner mesa
#

but the main issue is that you need to surround your template in quotes

#

rule #1 of templates

cobalt otter
#

Hmmm... I'll try quotes.

inner mesa
#

you also need to surround the entity_id in quotes

#

state: "{{ states('sensor.freezer_temp_1') | float * 2.0 }}"

cobalt otter
#

Thanks! That was the problem. The quotes on both the state and the entity_id.

acoustic arch
#

i think i need a template trigger... "when all lights downstairs in zone A and B are off"

inner mesa
#

Zones don't typically have lights

acoustic arch
#

ok so i make a group of lights in helpers then?

#

then use that?

inner mesa
#

Did you mean 'area'?

acoustic arch
#

sorry yes!

#

its late ๐Ÿ™‚

#

a group wont help. thats a toggle ofcouse... i need a sensor maybe then

inner mesa
#

There's a template function to return the entities in an area

#

You don't need any of those things

acoustic arch
#

ok. thx. ill go look for it then

inner mesa
#
{% set entities = area_entities('Family Room') + area_entities('Kitchen') %}
{{ entities|select('match', 'light.')|expand|selectattr('state', 'eq', 'on')|list|length == 0 }}
acoustic arch
#

ooof nice!

#

i was searching the forum, but im not sure what i was looking for hehe

#

i understand whats written but i still cant make up the syntax

#

its like understanding german but not able to speak it(im dutch)

#

so in my case is going to be list|length = 0

inner mesa
#

sorry, yeah. But you need == 0

acoustic arch
#

np. thx for the help!

#

exactly what i need ๐Ÿ™‚

#

gonna be a reminder which doors/windows are open at bedtime

#

one more question... can i set a variable in a trigger template?

inner mesa
#

that's an ambiguous question

#

what are you trying to do?

acoustic arch
#

trigger: all lights in living and kitchen are off
condition: after 10pm
action: notify mobile

#

i copy paste a lot of stuff around between automations. but this kind of trigger is new to me

inner mesa
#

that doesn't require you to set a variable

acoustic arch
#

well it does add both areas together

inner mesa
#

you can use that template anywhere, so if that's your question, then yes, you can set a variable like that in any template anywhere

acoustic arch
#
{{ (area_entities('woonkamer') + area_entities('keuken'))|select('match', 'light.')|expand|selectattr('state', 'eq', 'on')|list|length == 0 }}```
inner mesa
#

you can make it harder to read, yes

acoustic arch
#

i put that variable between brackets and it worked...

inner mesa
#

you didn't need to do that

acoustic arch
#

well im a novice pushing code around as a hobby

inner mesa
#

then I think it's all the more important that the things you write are easy to read and understand

acoustic arch
#

true that

#

split stuff for ez reading

#

ill try to paste your solution into the trigger template and test it out

#

it works in develop tools. but it throws an error as automation trigger

inner mesa
#

you did something wrong

acoustic arch
#

im sure i did

#
platform: template
value_template: >-
  {% set entities = area_entities('woonkamer') + area_entities('keuken') %}
  {{ entities|select('match', 'light.')|expand|selectattr('state', 'eq', 'on')|list|length == 0 }}
inner mesa
#

what is the error?

acoustic arch
#

i only changer the trigger so it must be there. lemme see

#

Message malformed: invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['value_template']

inner mesa
#

that's weird

#

you can try this:

#
platform: template
value_template: >-
  {% set entities = area_entities('woonkamer') + area_entities('keuken') %}
  {{ expand(entities|select('match', 'light.'))|selectattr('state', 'eq', 'on')|list|length == 0 }}
#

or, just create a template binary_sensor with that and use it in a state trigger

acoustic arch
#

well it saved the automation

#

lemme check!

#

bingo!

#

i turned off all lights and got the notify

#

just need to add the condition now

#

great thank you!

inner mesa
#

interesting:

            hass_globals = [
                "closest",
                "distance",
                "expand",
                "is_state",
                "is_state_attr",
                "state_attr",
                "states",
                "utcnow",
                "now",
                "device_attr",
                "is_device_attr",
                "device_id",
            ]
            hass_filters = ["closest", "expand", "device_id"]
            for glob in hass_globals:
                self.globals[glob] = unsupported(glob)
            for filt in hass_filters:
                self.filters[filt] = unsupported(filt)

#

looks like it should have disallowed the function, too

slow ice
#

hey, a noob question, how do i find out, what capabilities a devices has, and what kind of stuff i can expose as sensors

#

for example i currently have a tecking SP22 smart plug, and it's been added on localTuya, and i would like to expose it's sensor, power consumption, voltage

#

i found this random sample tuya_g4_current_consumption: friendly_name: "balcony consumption" unit_of_measurement: 'W' value_template: "{{ states.switch.balcony_socket.attributes.current_consumption }}"
is there a way to get the entire list of attributes listed that this device has?

inner mesa
#

are you asking about how to access things that are already exposed via attributes?

#

that's not what it sounded like from your first statement

slow ice
#

well because i do not know how to phrase it

inner mesa
#
  1. Look in devtools -> States and see if it already exposes what you want. If not, 2) go to configuration -> Devices, find your device, and see if there are entities that aren't enabled and do have what you want
#

templates only allow you to access things that already exist

slow ice
#

yes yes, this is what i was looking for, states

#

and if lets say an attribute does not show up, and i need to get back to integrations to expose it, where should i look to see what entities are possible to expose?

inner mesa
#
  1. go to configuration -> Devices, find your device, and see if there are entities that aren't enabled and do have what you want
#
  1. If neither is what you want, ask in integrations
slow ice
#

alright, probably it gets boring after a while having the same old questions asked

#

thanks for your time

inner mesa
#

after they've been answered, yes ๐Ÿ™‚

fossil venture
#

Why does this binary sensor template always become true exactly one minute **after **the on time, instead of at the on time? ```
state: >
{% set t_now = now().strftime("%H:%M") %}
{% set t_on = states('input_datetime.upstairs_ac_am_on_time') %}
{% set t_off = states('input_datetime.upstairs_ac_am_off_time') %}
{{ t_on <= t_now <= t_off }}

marble jackal
fossil venture
#

That does seem to have made a difference. I wonder why?

marble jackal
#

I guess it has probably something to do with now() being rendered once per minute, and that it doesn't rely on whole minutes now, but I also can't really put a finger on it

silent vector
#

I am trying to track the last changed of the HVAC action attribute. I assume this would be the way to go about it because I don't think it would work doing this {{ state_attr(thermostat, 'hvac_action').last_updated }}
https://dpaste.org/1wtzU
However I can't get the attribute in the template sensor to work.

marble jackal
#

last_changed is not an attribute

#

Attributes don't have a last_changed object, only the entity itself

#

If you want to track that of a specific attribute, you need to create a template sensor out of that attribute

silent vector
#

Yes so I made a template sensor out of the attribute to track that to obtain that but I don't think I'm doing it right.

#

It's in the dpaste

#

This works {{ states.sensor.daniels_hvac_action_last_changed.last_changed }} but it would more efficient for this to be achieved within the template sensor itself so it can be true/false. I wasn't sure if you can do this.state in the manner I'm doing it

marble jackal
#

What does the attribute return now?

silent vector
#

Null

#
TemplateError('UndefinedError: 'str object' has no attribute 'last_changed'') while processing template 'Template("{{ now() - timedelta(minutes = 5) > this.state.last_changed }}")' for attribute 'last_changed' in entity 'sensor.daniels_hvac_action_last_changed'
thorny snow
#

Hey, all, hopefull everyone is doing well so far today ๐Ÿ™‚ so im back with new problems and questions ๐Ÿ˜„ Today im trying to optimize and simplify some of my basic GUI automations, is there a way to simplify these two automations and to create one out of them ?
https://dpaste.org/enZFP

marble jackal
#

You need this.last_changed

silent vector
#

It worked. Thank you.

thorny snow
#

from a quick look seems to be ok, im like realy new, and it super hard here so huge thanks for Youre time !

#

id is like the state of the service in that case ? like Id on, that means the service ( smart plug ) gets triggered, right ?

marble jackal
#

I added ids to the trigger, and I use those in the service call

#

You can use anything for the trigger id, but in this way you can use them directly

#

Do note the automation only works if it is triggered by the state of the sensor now, you can not run actions manually as there is no trigger id then

thorny snow
#

ok, the last sentence i understood ๐Ÿ˜„ from the first one i took screenshot ๐Ÿ™‚

#

I have another one ( Of course.. ), this one is about light in storage room, i would like to merge both of them and add the lux thing, so that if its light enough, the light wouldn't turn on at all, im not just jet sure whats the lux number i have to use since i haven't found a way to measure it for now so lets say 50 lux ๐Ÿ™‚

#

and what im doing for now, if i get the idea, im just copy pasting, and editing the automations i get here, like i got the dehumidifier automation, i managed to get another one for other room out of it, simple, but still progress ๐Ÿ™‚

silent vector
#

This is odd, if I run this in template editor it's True {{ hvac_action_last_changed }} and if I do {{ hvac_action_last_changed == 'True' }} it's false and if I do {{ hvac_action_last_changed == 'true' }} it's also false. This is a variable I set what it's equal to in the template editor which is a sensor for context. That's how I just used {{ hvac_action_last_changed }} to get the output.

marble jackal
#

That's because 'True' is a string, not a boolean

#

'True' != True

silent vector
#

Oh my lol. No quotes

#

Fixed

marble jackal
#

Not sure why you want to do this though

silent vector
#

I'm using it as part of the schedule script to modify the temperature under certain conditions so knowing the thermostat is idle or cooling for example and it has been for x minutes is the goal.

marble jackal
#

Okay, but why use variable == true when you can simply use variable

silent vector
#

Because the variable can be false and I want it to be true in this statement. oh I get it now the result will be true in itself. Otherwise false and that's the same thing as variable == false if it's false and same as variable == true if it's true because it's a boolean

marble jackal
#

Yes, variable == false is the same as not variable

#

When variable is a boolean

silent vector
#

Yes makes sense now. I didn't think of that.

woven zenith
#

hello guys & gals!
I'm trying to refresh my dashboards and use Minimalist UI, but i'm stuck trying to use an if/else statement for a card title. Anyone got any insights on how i could accomplish this:
ulm_card_script_title: > {% if is_state('input_number.lr_fan_state', 0) | int %} Fan Off {% elif is_state('input_number.lr_fan_state', 1) | int %} Fan Low {% elif is_state('input_number.lr_fan_state', 2) | int %} Fan Medium {% else %} Fan High {% endif %}

#

as is, it prints the everything as a string and doesn't parse it

inner mesa
#

the | int that you've added to each condition doesn't do anything

#

In any case, it seems like this is more of a #frontend-archived question. Most cards don't support templates at all

frigid marsh
#

Trying to create a script to increase the a/c unit's target temperature by 1, but I get a "malformed" error. I followed a solution that's about 3 yrs old - doesn't appear to work, but I'm pretty sure I've messed this up somehow. Can someone help?

https://dpaste.org/4CX6o

inner mesa
#

data_template: became data: years ago

#

what is the actual error that you're getting?

frigid marsh
civic cargo
#

I have a template sensor which returns True or False if the calendar event exists today or not.

Currently, there are no calendar events in the future (a fairly common occurrence), and returns a null value of dict type
From the Template editor:
{{ state_attr('calendar.my_calendar','start_time') }}

null```

(I think) I'd like my code to either validate if the value of the calendar is a datetime object and proceed in determining the result, or conversely return false if the calendar is in a null state.
#

I think I got it
The line I was looking for was
{% if state_attr('calendar.work','start_time') == None %}

None -captital N, no quotes

obsidian lintel
#

I need some help with Regex,

How would I get the first 6 digits of the number from this whole string

Phone Number: 87654321

inner mesa
#

I would just do this:
{{ "Phone Number: 87654321".split(': ')[1][:6] }}

obsidian lintel
#

I cant use split here because there is also

#

Name: Astogems

#

Phone Number:
Address:

#

and 87654321 can be any value

#

.Phone Number: (.)\n

#

.*Phone Number: (.*)\n

#

I managed to think of this but I cannot get the first 6 digit

inner mesa
#

I was expecting this to work, but I can't get capture to work:
{{ "Phone Number: 87654321"|regex_replace('.*: (\d{6}).*', '$1') }}

obsidian lintel
#

Tricky one eh

inner mesa
#

you can still use split():

{{ "Name: Astogems
Phone Number: 12345678
Address: 123456789".split("Number: ")[1][:6] }}
#

-> 123456

obsidian lintel
#

Yeah but the Name could also be RobC

#

Its err

#

Generated from Google Calendar

#

.*Phone Number: ([0-9]{6})

inner mesa
#

it doesn't matter what the name is. You mean "Phone Number: " isn't constant?

obsidian lintel
#

The value of Phone Number isnt constant

inner mesa
#

I'm not relying on that

obsidian lintel
#

The value of everything isnt constant

inner mesa
#

are you still saying that what I have above won't work?

obsidian lintel
#

It would work is my friends name is Astogems but his name could be RobC or maybe John

inner mesa
#

it doesn't matter. you're looking for the phone number, right?

#

nothing in that search string has anything about the name

obsidian lintel
#

Oh my god hahaha I didnt notice, I apologise

#

Yup, exactly im only looking at the values after Number:

#

However would this work with a context such as

Full Name: John
Last Name: Smith
Phone Number: 87654321
Address: 123 Apple Street
Postal Code: 123456

inner mesa
#

it doesn't matter

#

try it

obsidian lintel
#

Got it Thanks a lot

bleak cipher
#

Hello
I can not for the life of me figure out why this template is not working

      - name: Pegasus Array Available
        where: '"path" =~ /.*user0/ AND "host" =~ /^Pegasus$/'
        measurement: '"disk"'
        unit_of_measurement: bytes
        field: '"free"'
        database: telegraf
        group_function: last
        value_template: '{{ states.sensor.pegasus_array_available | multiply(0.0000000000001) }}'
``` Any suggestions?
inner mesa
# obsidian lintel Got it Thanks a lot

this does it as well with a regex:

{{ "Name: Astogems
Phone Number: 12345678
Address: 123456789"|regex_findall_index('.*: (\d{6}).*')}}

as does this (apparently \1 references a capture group):

{{ "Phone Number: 87654321"|regex_replace('.*: (\d{6}).*', '\\1') }}
inner mesa
#

value_template: "{{ states('sensor.pegasus_array_available')|float | multiply(0.0000000000001) }}"

inner mesa
#

please no pictures of text

#

if you have text, show the text

bleak cipher
#

ok

inner mesa
#

the problem is that the quotes are the same inside and out

#

fixed

bleak cipher
#

ohh. so can single quotations just not be used for this?

inner mesa
#

it just has to be parseable, and using the same type of quotes makes it impossible to parse

bleak cipher
#

that makes sense. thanks!

obsidian lintel
#

Where should I go to ask questions about Restful Commands

inner mesa
obsidian lintel
#

Thanks!

paper hazel
#

Is there a method with template to differentiate between a normal light, and a light group?

inner mesa
#

A light group will have an entity_id attribute

paper hazel
#

Will something like this work? I'm still very green with jinja, but trying to learn```
{{ states.light | rejectattr('entity_id') | map(attribute='entity_id') | list }}

inner mesa
#

No

#

You can test these things in devtools -> Templates

paper hazel
#

Thx - I spend a lot of time there. The above seem to filter all the entities. What I have so far is```
{{ states.light | rejectattr('entity_id', 'match', '^light.browser*') | rejectattr('entity_id', 'match', '^light.*doorbell_flash') | rejectattr('entity_id', 'match', '^light.*control_screen') | map(attribute='entity_id') | list }}

#

The above filters out unwanted lights - This template is used with group.set to create a group dynamically.

inner mesa
#

{{ states.light|selectattr('attributes.entity_id', 'defined')|map(attribute='entity_id')|list }}

paper hazel
#

Thank you - I really appreciate the help. This community is awesome!

magic mulch
#

Is it possible to stick a template sensor to a area? I

inner mesa
#

As long as you give it a unique_id

ivory harbor
#

I've got another head scratcher... with this template, when I try and adjust the position of my blinds, I get an error that "position is undefined" https://dpaste.org/XN80B

inner mesa
#

It doesn't have a position_template

magic mulch
ivory harbor
#

I also get the same error if I use optimistic: true

ocean forge
#

Can someone point me in the right direction here?

Trying to set a helper value == my fan's current speed

service: input_number.set_value
target:
  entity_id: input_number.dallasfanspeed
data:
  value: '{{states(''fan.dallas_bedroom_ceiling_fan'', ''percentage'')}}'
inner mesa
#

you're using the wrong function, assuming that "percentage" is an attribute

#

value: "{{ state_attr('fan.dallas_bedroom_ceiling_fan', 'percentage') }}"

ocean forge
#

Cool, that action seems to work
But apparently my overall automation is broke

#

Thanks much

ivory harbor
slim elk
ivory harbor
#

even if I remove the math, it is still undefined

slim elk
#

what does the call to the script look like?

ivory harbor
#

cover.bedroom_large_right: Set position to 62

slim elk
#

can you share?

ivory harbor
#

not sure how... the template is exposed as a device via homekit and I'm dragging a slider in home kit which I think is calling the set position

slim elk
#

sounds like maybe HomeKit isn't passing the position value to the script when triggered that way. Maybe an input_number in HA exposed to HomeKit that would trigger the automation in HA using the value from the input number to set the position

proud flint
#

Hey jinja ninjas, is there a simpler way of achieving what I'm doing here? Taking timestamp for now and timestamp for last changed of a sensor to get how many hours since last update as a value_template:
{{ ((as_timestamp(now()) - as_timestamp(states.binary_sensor.front_door_contact.last_changed))/3600) | float | round(0)}}

silent vector
#

Any idea why this is resulting in

Message malformed: template value should be a string for dictionary value @ data['action'][1]['data']

https://dpaste.org/tkCpU

inner mesa
#

Yes, you're not using iif() properly. It's a function

acoustic arch
#

can i set an attribute of an entity for development purposes? im testing a rain sensor but its not gonna rain soon lol

#

or should i overwrite the value manually

inner mesa
#

Yes, in devtools -> States

acoustic arch
#

with {% set ..... % }

silent barnBOT
#

To test an automation there's three stages you can follow. Testing the action, the condition and action, and the whole automation:

  1. Use Configuration -> Automations to find the automation and then push Run Actions. If this fails your problem is in the action: section, and details should be found in your log file
  2. Use Developer tools -> Services and call automation.trigger on the automation with skip_condition: false. If the first passes but this fails then the problem is in your condition: block
  3. Use Developer tools -> States to find the trigger entity, click the name, then change the state (at the top) to something that'll trigger the automation before pushing Set State. If this fails then the problem is with your trigger: section, or the automation is turned off (you can check that in Developer tools -> States).

You can also see this section in the docs and with HA 2021.4 onwards debug automations.

inner mesa
#

Not with that. That just sets a variable

#

See #3

acoustic arch
#

OOOOh i can type in that section!

#

kewl

#

thx

silent vector
marble jackal
trail estuary
#

Hey! I want to check if the state of a sensor is above a certain value at a given time every hour. Is that possible?

#

For example a binary sensor that is true if the state of the sensor is above 3.5 and the minutes of the current hour is more than 40.

marble jackal
trail estuary
#

That should do it!

#

I get this: TypeError: '>' not supported between instances of 'str' and 'float'

inner mesa
#

all states are strings

#

so it's correct

#

{{ now().minute > 40 and states('sensor.whale')|float > 3.5 }}

trail estuary
#

Not sure why, but I had to modify it to make it render properly....
{{ (now().minute | float >= 40) and (states('sensor.hourly_consumption_meter')|float > 3.5) }}

inner mesa
#

the parens may have been required, but now().minute should already be a float or int

trail estuary
#

Let me try that... Just for fun! ๐Ÿ™‚

inner mesa
#

{{ now().minute is integer }} -> True

trail estuary
#

{{ (now().minute >= 40) and (states('sensor.hourly_consumption_meter')|float > 3.2) }} also works great! ๐Ÿ™‚

silent vector
#

Any idea how I can have a variable result, pull a corresponding list? For example away_selector output could be one of 3 lists for example if it's daniel_away then the goal is to simultaneously pull that list daniel_away to use on line 28. Initially I had away_selector above the lists so I thought I needed to move it below them but that didn't work. I was trying to avoid more logic and something efficient. I'm assuming I'll have to use a different strategy for this and not use the same list names as the output for away_selector but I figured it was worth trying.
https://dpaste.org/Q354x

inner mesa
#

but the object_ids are already the names of the lists? It seems like that's how you tie those two things together

silent vector
#

I just realized that yes, the only difference is adding _away to the zone object IDs and doing a single replace

marble jackal
silent vector
karmic lotus
#

I have this group entity and I want to dynamically add all entities that come from a specific integration. How can I do that?

group:
  ignored_unavailable_entities:
    entities:
      - light.some_light
      - ...
      - <all entities from specific integration>
inner mesa
inner mesa
#

I don't know if this is helpful, but it works:

- id: test
  alias: test
  variables:
    lists:
      mylist_1:
        - "foo"
        - "bar"
      mylist_2:
        - "blah"
        - "floop"
  trigger:
    - platform: state
      entity_id:
        - input_boolean.test1
        - input_boolean.test2
  action:
    service: persistent_notification.create
    data:
      message: "{{ lists['mylist_' ~ trigger.to_state.object_id.replace('test', '')] }}"

@silent vector

karmic lotus
#

Could you by any chance give a minimal YAML example?

#

On how to combine manual addition of entities to the group with the templated ones?

inner mesa
#
    - service: group.set
      data:
        object_id: zwave_js_group
        entities: "{{ integration_entities('zwave_js') }}"
#

If you want to add more entities to an existing group, you should create a new group instead based on the original group and the new entities

karmic lotus
#

So if I add a group to a group, does the nested group automatically expand?

inner mesa
#

I don't know

#

I suspect no, since you can have groups of groups

#

a group is just an entity, after all

karmic lotus
#

So maybe I should just use a template group that gets the integration's entities to which I add the "manual" entities within the template, if that is possible

inner mesa
#

the only way to create such a group is what I showed above

#

and you can add whatever you want

karmic lotus
#

Oh, but I don't understand how I can practically do this with using the service :/

inner mesa
#

just like I showed you

karmic lotus
#

I mean I could create an automation that just invokes this service constantly

inner mesa
#

that's working code

#

yes, you would need to run that either at startup, or periodically

karmic lotus
#

Alright. Thank you.

#

There's probably a good reason for this, but it seems a little weird there are no template groups, like what you can do with e.g. sensors.

inner mesa
#

the devs have moved away from group.* groups and encourage domain-specific groups now. I don't know if there's a good technical reason that they couldn't support template definitions, but maybe it's just a feature request

karmic lotus
#

One last question, is the parameter of integration_entities() the name of the integration as seen in the integration column of the entities table?

inner mesa
silent vector
inner mesa
#

did you review my proposal?

#

it chooses a list from the set of variables based on the object_id of the triggering entity, modified to remove a part of the name

silent vector
#

I saw it, I was answering the first post, I'm just confused how I would implement in this in my use case.

inner mesa
#

ok

#

it seems like it solves it

silent vector
#

I think I understand it now. Thank you

silent vector
inner mesa
#

Yeah, that doesn't look like what I gave you

#

You need an index and you're providing a comma-separated list and you're not stripping the part of the string as we discussed

silent vector
#

I'm a little stuck on how to make what you sent work. Can you show how I would do that with my lists?

inner mesa
#

You have this:

#

entity_id: '{{ lists[away_selector | list | join('','')] }}'

#

I gave you this:

#

message: "{{ lists['mylist_' ~ trigger.to_state.object_id.replace('test', '')] }}"

#

note how I assemble the name of the list and use it as an index to choose the right list

#

you're creating a comma-separated list and not doing any string manipulation

silent vector
#

So swap mylist_ with away_selector? I know but that's what I'm stuck on because I'm trying to align it with the Entity IDs.

inner mesa
#

that's what my example does

#

it takes the entity_id that triggers, such as input_boolean.test2, and uses a part of it to build the name of the list to use

#

you're already doing some of it in your away_selector variable

silent vector
#

Every entity id has a different name before _ though. daniel_away , all_away. That's the part I'm stuck on. Your example was test2 strip test and select mylist_2 essentially.

inner mesa
#

doesn't away_selector already have the name of the list you want?

silent vector
#

It does

inner mesa
#

then just use it

#

entity_id: '{{ lists[away_selector] | join('','') }}'

silent vector
#

That's what I was stuck on

inner mesa
#

it's just that

silent vector
#

Perfect thank you.

thorny snow
#

So im trying my luck out here, I get the idea, I know what I need, but I just can do such an automation in my day 3/4 on YAML and doing it in the UI with like 5 automations isnโ€™t the best way, so im trying my luck here ๐Ÿ™‚ looking for a template to do the following, if the iRobot Script isnโ€™t working, when a movement is detected and the Brightness is below 50 lux turn on the light, if there has been no movement for 20 sec, and the robot script isnโ€™t running, turn off the light

iRobot script: irobot_with_automatic_lights
Light entity: switch.0x54ef4410003b3633
Movement detection entity: binary_sensor.motion_sensor_storage_room_occupancy
Brightness Entity: sensor.motion_sensor_storage_room_illuminance_lux

haughty raft
#

thats pretty simple really, don't see a need for templates

#

movement = trigger, brightness value = condition, script = condition

thorny snow
#

i get the idea, my problem is code writing, thats why im asking for the template...

fleet pivot
#

Hello, I looking for a long time and cant find solution. I trying new template system because, old templates doesn't support "state_class: measurent".

template:      #Missing property "platform"   
  - sensor:
    - name: "switches_power_consumption"
      unit_of_measurement: "kWh"
      device_class: energy
      .
      .
      .

and getting error:
Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 13).
I will be very happy for any kind of help or information
thanks ๐Ÿ™‚

inner mesa
#

What version of HA are you using?

fleet pivot
#

8.2

inner mesa
#

That's not a version

fleet pivot
#

Home Assistant Core 2022.6.7
Home Assistant Supervisor 2022.05.3
Home Assistant OS 8.2

inner mesa
#

Where did you put that? Seems like you put it in sensors.yaml or similar, when it belongs in configuration.yaml

fleet pivot
#

I ussed include in configuration,yaml
sensor: !include sensors.yaml

inner mesa
#

Right, it doesn't go in there

fleet pivot
#

okey, thank you very much I didnt expect include doesnt work for this

inner mesa
#

It's not that. It's that it sounds like you put the code above into sensors.yaml, where it doesn't belong

#

It's not the include that's the problem, but that you put it in the sensor: section

fleet pivot
#

okey, witch section is right for this code, I feel bad, because it's work but its in configuration.yaml and thats doesnt feel right

silent barnBOT
inner mesa
silent barnBOT
quaint crystal
#

struggling to understand how this error is occurring:

a template reads "undefined when rendering" in the logs, but it works fine in the developer tool window

#

a basic {{ state_attr('weather.home_hourly','temperature') }}

#

sensor shows as "Unknown" in the Ui, and logs show Template variable error: 'weather' is undefined, but it does template correctly in the developer tools section. Matches state I see as well for my weather entity

inner mesa
#

That error indicates that you're using the wrong quotes

#

It's interpreting 'weather' as a variable, as well as temperature

quaint crystal
#

ahhh whey copying my yaml over onto the server the single quote were removed. doh! thanks a ton

formal fern
#

Can I ask for a second set of eyes on this... I'm sure I'm missing something and/or doing something stupid, or both?

  - platform: template
    switches:
      heat_required:
        value_template: {{ is_state_attr('climate.bedroom_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.ensuite_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.ruby_bedroom_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.guest_room_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.living_room_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.sitting_room_thermostat', 'hvac_action', 'heating' ) }}
#

Error: The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while parsing a flow mapping in "/config/configuration.yaml", line 177, column 26 expected ',' or '}', but got '<scalar>' in "/config/configuration.yaml", line 177, column 97

#

Works successfully in the developer tools

#

Thank-you all... I was missing the quotes at the start of the value_templates ๐Ÿ˜„

#

And then of course I want this as a sensor not a switch ๐Ÿ˜„

deft timber
#

You have to quote your template

#

or:

switch:
  - platform: template
    switches:
      heat_required:
        value_template: >-
           {{ is_state_attr('climate.bedroom_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.ensuite_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.ruby_bedroom_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.guest_room_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.living_room_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.sitting_room_thermostat', 'hvac_action', 'heating' ) }}
marble jackal
#

Based on the posts he added, he already found out ๐Ÿ™‚

deft timber
#

๐Ÿ˜‚ I answered too fast :-p

buoyant sapphire
#
  - wait_template: '{{ states("vacuum.staubi") == "docked" }}'
    continue_on_timeout: true
    timeout: '12000'

i was hoping this is two hours, looks like its not. does someone know what the value/metrix here is exactly? 120 did also not work for me before.

marble jackal
#

@buoyant sapphire This is 200 minutes. The timeout is in seconds, so 2 hours is 7200 (there are 60 seconds in a minute, not 100)
But such a long timeout will be risky, as it will be cancelled by an automation reload (also when you edit another automation in the GUI, and save it) or a reboot of HA
And you can rewrite your template to: '{{ is_state("vacuum.staubi", "docked") }}'

marble jackal
#

@bronze tide

condition: template
value_template: "{{ is_state('binary_sensor.whale', 'on') or (is_state('binary_sensor.whale', 'off') and (now() - states.binary_sensor.whale.last_changed).seconds < 60) }}"
bronze tide
shell leaf
#

hey, is anyone able to explain how i get my successfully created template sensor to be added to my recorder so it records the data and shows up in my statistics page?

marble jackal
#

Did you set a specific configuration for recorder?

#

And did you set a state class for you sensor?

trail estuary
#

Is it possible to limit a template from rendering? I have this template that takes the current electric consumption, divides it by now().minute and multiplies it with 60. For the first 10 minutes or so, the estimations this calculation does have huge errors. Can I have the template render only after 10 minutes into the hour? Other ways to filter the huge errors/variations?

dense tinsel
#

Hi Everyone, I am hoping I can get an idea on how to approach what I assume has been done, but I cannot find anything so far, likely wording. I have a energy monitoring smart outlet running Tasmota on a dumb โ˜• coffee maker. I am hoping to have a badge on my main page showing if the Coffee is brewing or heating. Brewing is easy, as power is over 700W. The challenge is with the warming state as the heating element only comes on every minute or so, so power drops to 1W like the phantom draw.
What I am trying to use is something like condition in rules "for 5 min", so I can say if power is below 2W for 5 min then it's "Off". I will happily share the results if nobody has posted this.
Thanks in advance!! For context I am running Core 2022.6.7.

obsidian lintel
#
    url: "https://api.ttlock.com/v3/keyboardPwd/add"
    method: POST
    content_type: "application/x-www-form-urlencoded"
    payload: "clientId=971e80f12xxx3b914fc6b0551b4&accessToken=c014bb77xxxxxx1287c478b&lockId=48xx23&keyboardPwd=456123&keyboardPwdName=Test2&startDate=1656979200000&endDate=1656997200000&addType=2&date={{as_timestamp(now())}}"```
#

I created a Rest Command, it work if I just input the date= parameter with the Epoch current time

#

But when I use a template, it does not work

#

Is there a problem with my code formatting?