#templates-archived

1 messages ยท Page 165 of 1

plucky heron
#

This is a {%- if 1 == 1 -%} test. {% endif %}

#

how do i insert a space between a and test

#

this is the string that template creates: "This is atest."

mighty ledge
#

{%- means remove whitespace before this {% means don't remove whitespace before this

#

-%} means remove whitespace after this {% means don't remove whitespace after this

#

you're doing both

plucky heron
#

ahh ok

plush willow
#

I have a question about scripts. Is it possible to pass a input number entity state to service call data parameters?

#
  • choose:
    - conditions:
    - condition: state
    entity_id: input_select.cover_master_bedroom_close_mode
    state: Ventilatie
    sequence:
    - service: cover.set_cover_position
    data:
    position:
    states('input_number.master_bedroom_cover_ventilatie_positie')
    target:
    entity_id: cover.master_bedroom
#

So this: states('input_number.master_bedroom_cover_ventilatie_positie') should be used as position value

mighty ledge
silent barnBOT
buoyant sapphire
#
Todays date is {{ now().date() }} 
Last time the vacuum robot ran was {{ states('input_datetime.staubilastruneingang')[0:10] }}

It would be great to get the delta/difference from these two dates. eg: 1, when it was running the last time yesterday.

Any idea how I can compare two dates, or any other template-idea on how to extract the information how many days it has been since a certain script was run?

mighty ledge
buoyant sapphire
mighty ledge
#

you can't, that's just for output

#

if you want to perform logic, you haveto use the datetime

#
{% set time = states('input_datetime.date_time') | as_datetime | as_local %}
{% if (now() - time).days >= 1 %}
  {{ relative_time(time) }}
{% else %}
  ...
{% endif %}
buoyant sapphire
#

thank you very much @mighty ledge

plush willow
full token
#

Hi,
I'm quite new to MQTT and even more to templates...
I'm trying to get lights, but I can't get the states right (command seems to be working)

#

The command I can send :

#

{"type":"Buffer","data":[1]}

#

The status that doesn't seem to be understood by my template

#

"{"value":{"type":"Buffer","data":[1]}}"

#

With this config :

#

light:

  • platform: mqtt
    object_id: "Mur Salon"
    name: "Salon - Applique"
    payload_off: "{"type":"Buffer","data":[0]}"
    payload_on: "{"type":"Buffer","data":[1]}"
    command_topic: "knx/1/0/3/write/dpt1"
    state_topic: "knx/1/3/3/"
    state_value_template: "{{ value_json.data | replace([0], 'off') | replace([1], 'on') }}"
#

( Last one, I tried many others )

#

Could somebody please help me ? ๐Ÿฅบ

inner mesa
#

Yeah, that's not right ๐Ÿ™‚

#

It's giving you a list with an integer in it

#

you would access that item with {{ value_json.value.data[0] }}

#

then, probably use payload_on: 1 and payload_off: 0 or whatever the actual values are

full token
#

Thanks for your help
Let's try that ๐Ÿ˜‰

tepid onyx
#

If I change "{{ ' ' ~ name1 ~ ' ' ..... to
{{ name1 ~ ' '.......
It appears to populate the input_text as expected but following the script in the debugger it does not run

snow laurel
#

What is the correct way to create a template that triggers when there is a sharp drop in a sensor? So if sensor.drive_to_work decreases by 20% for instance.

inner mesa
#

you probably want a trend sensor

snow laurel
#

Can't be done with a use of ".from_state.state"?

inner mesa
#

you could, but that would just register a difference between two readings

#

if that's what you want, it's easy

snow laurel
#

yeah I suppose that is too small a delta.

orchid oxide
#

the following means: dont continue if input_select.mode has not been 'home' for less than 5 seconds.

conditions:
  - condition: state
    entity_id: input_select.mode
    state: Home
    for:
      hours: 0
      minutes: 0
      seconds: 5
``` how can i say: dont continue if input_select has been 'not home' for less than 5 seconds
inner mesa
#

do you really mean the string "not home" or anything other than "Home"?

orchid oxide
#

i mean anything other than home, sorry

inner mesa
#

I would just make a template condition for that

#

The easiest way is to create a template binary_sensor that represents the thing you care about and then base your condition on that

#

{{ is_state('input_select.mode', 'Home') }}

#

then, {{ not is_state('binary_sensor.home', 'on') and states.binary_sensor.home.last_changed < utcnow() - timedelta(seconds=5) }}

orchid oxide
#

thanks. looks like last_changed shows in utc, so I just changed now() to utcnow(), and also, unless im understanding wrong. it'd have to be.{{...< utcnow() - timedelta(seconds=5)}}, that seems to work, vs the other way the last_changed is always gonna be less

inner mesa
#

yeah, that's what I get for multitasking ๐Ÿ™‚

#

luckily, you can hack around in devtools -> Templates to catch stuff like that

latent cypress
#

Is there a way to set a value in a for statement and have the scope live outside the for statement? It doesn't seem to be working with this script:

{% for weatherAlert in weatherAlerts %}
  {% if weatherAlert.event == 'Heat Advisory' %}
    {% set isHeatAdvisory = True %}
  {% endif %}
{% endfor %}
Is heat advisory? {{isHeatAdvisory}}```
inner mesa
#

Yes, with a namespace

latent cypress
#

Great thanks!

marble jackal
#

But this looks like it should be possible without a for

native sparrow
#

{{ now() - states.sensor.dual_dishwasher.last_changed }}gives me a result of 18:45:45.828521 which is H:M:S. How can I get it to just show hours and minutes?

native sparrow
#

OK I'v got this but surely there is a nicer option ```{{ (now() - states.sensor.dual_dishwasher.last_changed)
| string | truncate(5,True,'',0) }}

marble jackal
#

Also a bit of a hacky workaround {{ today_at(now().replace(microsecond=0) - states.sensor.dual_dishwasher.last_changed.replace(microsecond=0)).strftime('%H:%M') }}

native sparrow
#

Not pretty either - but maybe mine would fail when hour is only one digit ?

marble jackal
#

Or this ๐Ÿ™‚ {{ ((now() - states.light.booglamp.last_changed) | string).split(':')[0:2] | join(':') }}

native sparrow
#

If only there was something like unix cut

silent vector
#

Any idea what's wrong here? I'm trying to use a single action to loop through those cameras I put in a variable.
template value should be a string for dictionary value @ data['action'][0]['repeat']['sequence'][0]['data']
https://dpaste.org/suPx6

marble jackal
#

This part is wrong: "{{ if trigger.entity_id == 'sensor.outdoor_light_on' | iif('ON','OFF') }}"

#

2 things:
Remove the first if
Add brackets, because you now only apply the iif filter to sensor.outdoor_light_on

#

The last one is why I rather use the iif function, it's more clear

#

"{{ iif(trigger.entity_id == 'sensor.outdoor_light_on', 'ON','OFF') }}"

silent vector
#

I see, it was my first time using it and it made perfect sense for this scenario, thank you.

#

Still getting the error though.

marble jackal
#

Ah wait, this part is also wrong

#

{{ frigate/{{ camera }}/improve_contrast/set }}

#

use this:

            topic: >-
              {% set camera = cameras[repeat.index] %} 
              frigate/{{ camera }}/improve_contrast/set
#

or

            topic: >-
              {% set camera = cameras[repeat.index] %} 
              {{ 'frigate/' ~ camera ~ '/improve_contrast/set' }}
#

you can not nest templates

silent vector
#

Oops yep can't nest templates. Thank you again.

marble jackal
#

or use a for_each repeat

silent vector
#

How would I use a for each repeat

marble jackal
#
  - repeat:
      for_each: '{{ cameras }}'
      sequence:
        - service: mqtt.publish
          data:
            topic: "frigate{{ repeat.item }}/improve_contrast/set"
            payload:  "{{ iif(trigger.entity_id == 'sensor.outdoor_light_on', 'ON','OFF') }}" 
silent vector
#

Shouldn't it be "{{ iif(trigger.entity_id == 'sensor.outdoor_light_on', 'ON','OFF') }}"

marble jackal
#

sorry, directly copied it from your dpaste

#

forgot to edit that one ๐Ÿ™‚

silent vector
#

I figured, although even with that ^ I'm getting expected a dictionary for dictionary value @ data['action'][0]['repeat']

marble jackal
#

I also did not fix the other issue

silent vector
#

The nested template?

marble jackal
#

how is it like this (see edited post above)

silent vector
#

Is it because I have a list variable and not dictionary?

mighty ledge
#

compare your yaml to the example. What's different

silent vector
#

That was definitely an issue and I think the editor on mobile was being weird. Sometimes it messes up my spacing. It works now. Thank you both.

marble jackal
#

whoops, should have seen that

#

Oh, it was actually correct in my code ๐Ÿ™‚

silent vector
#

Not sure what I did then or if it was the mobile automation editor which is buggy for me some times.

mighty ledge
#

how do I know this? Because it happens all the time

silent barnBOT
dusty thorn
inner mesa
#

sounds like it doesn't have that attribute

dusty thorn
#

But it's defined right there?

inner mesa
#

right where?

dusty thorn
#

In the attributes section of the entity

inner mesa
#

it probably doesn't have it yet

#

this represents the current state, and you're in the process of defining it

dusty thorn
#

Suppose I can stick the entity in the value template, but I was hoping to be able to just have a generic value template I could copy over to other temp/humid sensor pairs if I make any changes etc

inner mesa
#

I don't think that will help

#

you can check if the attribute exists in the state, or use an availability template

#

I guess only the former will work

#

or, as you say, just use the states() value there

dusty thorn
#

The temp&humid entities are ZHA and exist outside of reloading the template entities, so it does work directly grabbing from the value section

#

(I had it working before trying to genericise it)

#

What's the order of the entities being updated?
I'm guessing state then attributes given the issue I just had

#

If that's the case the example in the documentation is a bit misleading

inner mesa
#

the current state is a complete thing, the order in which the new state is calculated isn't relevant here

#

your problem is just a chicken-and-egg problem

dusty thorn
#

It is relevant if it means it's always "one update behind" and you're calculating state off it as the doc example does

inner mesa
#

I'm not following

#

yes, this is always the current state, which you can use when calculating the new state

dusty thorn
#

The doc example uses a templated value in the attributes, and calculates the value with a template referencing that attribute

inner mesa
#

there's nothing in between where some of the current and some of the new state is represented in this

#

it also has a default

#

which you do not

dusty thorn
#

So if I understand correctly, it's always one update behind

inner mesa
#

it's always the "current" state

#

where you are defining the new state

dusty thorn
#

What is "current" here? The state that is currently showing in the UI etc, before it is updated with new values when sensors update?

inner mesa
#

what you see in devtools -> States

#

in the example, the first state will be "Value when missing", and the next update it will be the time of that update

dusty thorn
#

That feels like a bug tbh, as you'd have to some workaround mechanism to trigger a second update if you want your template to actually do anything useful on start (if you do as the docs suggest you do)
Might be an idea to stick a note on that docs example

#

To be clear, not saying it is a bug, it's just unexpected behaviour

inner mesa
#

I suppose you could suggest a note. It's consistent from my viewpoint

#

There are buttons at the bottom of each doc page to suggest an update

mighty ledge
manic tartan
#

Hallo everybody. What is API alternative (if any) for gathering properties for an object? Thanks in advance.

{{ states.light.lvr_cc1 }}
Result type:ย string
<template TemplateState(<state light.lvr_cc1=off; min_mireds=153, max_mireds=500, supported_color_modes=[<ColorMode.COLOR_TEMP: 'color_temp'>, <ColorMode.HS: 'hs'>], off_brightness=None, friendly_name=Kolorowa lampka, supported_features=59 @ 2022-06-14T20:28:56.903707+02:00>)>

patent sparrow
#

I created an (Template?) Input Select (Dropdown?) via the Home Assistant GUI - Helpers. I need to rename some and reorder them. Can I do this without deleting and recreating them?

inner mesa
#

if you created it in the UI, it's unrelated to templates

#

as far as i can tell, you can only delete options and add new ones

patent sparrow
#

fair enough - i thought "Helpers - Input Select" was effectively a front-end gui for "Template - Input Select", hence choosing this channel

#

i guess i'll delete and recreate them, thanks

strange geode
#

Hey Guys

I wanna send a notification witch inclued a sensor state. and a url from local ip with sensors state. like

I want to inclued the states of two sensores in message is this how it should be put or ?
message: '{{ states(''sensor.1'') ( https://www.local.ip/api=1&query={{ states('sensor.1.jpg') }} }}'

This is working: '{{ states(''sensor.1'') }}' when i push a message.

But i want to include this to the message: https://www.mylocalip.com/?api=1&query={{ states('sensor.mysensor2') }}

modest loom
#

I thought this would be easy to find so sorry if it's obvious: can configurations for old-style sensor: templates and ones for new-style template: sensors coexist int he same configuration.yaml?

#

(I'm adding a new one and I'd prefer to do it in the most up-to-date format but I have a bunch of old ones I don't have the time to convert right now.)

#

I tried it and it appears to work (it was easier than I expected to test), so I think I've answered my question, but I'll leave this here in case I've gone down a horribly wrong path. Thanks!

marble jackal
#

Yes, no issues with using new and legacy template sensors together

marble jackal
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.

coral geyser
#

Hi,

#

how add subject in this

fossil venture
#

Subject in what?

coral geyser
#

Mail

#

warn

#

but i found the solution

#

title: message

soft bough
#

my alarmclock automation has stopped working, and it seems to be something with the templates,

{{ (states('sensor.date') + ' ' + states('sensor.time')) == ( states.input_datetime.next_alarm.attributes.timestamp | int - (30*60) ) | timestamp_custom('%Y-%m-%d %H:%M', True) }}

and

{{ states('sensor.time') >= '22:30'|timestamp_custom('%H:%M', True) or states('sensor.time') <= '12:30'|timestamp_custom('%H:%M', True) }}
#

i cant find anything in the releasenotes about change to this, but it stoped working without me changing anything in the automation so i'm guessing its a result from updating home assistant version

#

it should fire 30min before my alarm ( input_datetime.next_alarm )

marble jackal
#

What is the error you are seeing, and how are you using these templates?

soft bough
#

im getting that there is no default for timestamp

marble jackal
#

That answers the first question

#

{{ today_at('12:30') <= now() <= today_at('22:30') }}

This removes the need to use these custom_timestamps at all (and the need for sensor.time and sensor.date)

heavy bough
#

anyone any idea how I can count number of hue lights turned that are connected via a bridge? theres no sensor entity for it?

manic tartan
#

Hi. Is there a simplest way to get input_select index than:
{% set eid = 'input_select.console_audible_information_level' %}
{% for idx in range( 0, state_attr( eid, 'options') | length) %}
{{- loop.index0 if states( eid) == state_attr( eid, 'options')[idx] -}}
{% endfor %}

marble jackal
#

@manic tartan {{ state_attr(eid, 'options').index(states(eid)) }}

manic tartan
#

Thx. I was looking for this in Jinja template manual :-(. To clarify my undestanding - this method is Python list method or part of templates?

#

BTW, I expect the 'calculation cost' is the same (for manual search and index()), it should no be calculated every time I need this value. I have created sensor to have it calculated in advance. Is this best approach for having such a value?

  • sensor:
    • name: console_audible_information_level
      state: >-
      (...)
marble jackal
manic tartan
#

OK :-).

marble jackal
#

Which manual are your referring to here?

marble jackal
manic tartan
#

input_select: console_audible_information_options: name: "Poziom powiadomieล„ gล‚osowych na konsoli (tablet)" options: - "Cisza, brak powiadomieล„ gล‚osowych" - "Tylko alarmy" - "Ostrzeลผenia i alarmy" - "Informacje, ostrzeลผenia i alarmy"

#

An array of options available via GUI. I want to have numeric value based on zero based index of the selected value (states(eid)).

#

To have it calculated on-time (not evaluate every time I need this) I have created a sensor that uses the template to get that index:
- sensor: - name: console_audible_information_level state: >- (...)

#

Not sure if it is the best approach, but anyway it was easy to archive not having to calculate every time I need an index.

#

And works perfectly. But, I'm new to HA so looking for proper way if any :-).

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

manic tartan
#

๐Ÿ™‚

marble jackal
#

I don't think it will make much difference using this simple template to get the index, or get it as the the state of a template sensor

manic tartan
#

Will try to test and compare, but if it is one-lines it looks much better :-).

surreal maple
#

Hi, I am trying to find the position of covers at a numerical value, but the only attribute I can find is a bolean "open" or "closed" value. Thanks for the help in advance ๐Ÿ™‚

inner mesa
#

if you don't see it in the attributes in devtools -> States, it's probably not available. It's also possible that your cover doesn't support it

ornate osprey
#
      dager_til_matavf:
        friendly_name: Matavfall hentes om
        value_template: '{{ (( as_timestamp(strptime(states.sensor.mat_plast_og_rest.state, "%d/%m/%Y")) - as_timestamp(strptime(states.sensor.date.state, "%Y-%m-%d") ))/ (3600*24)) | round() }}'
        unit_of_measurement: dager
#

Can anyone please help me with why this code is not working after the latest update? ๐Ÿ™‚ Thank you in advance

#

the -platform: template is on top. I hve about 10 template sensors ๐Ÿ˜›

inner mesa
#

what is "not working" about it?

ornate osprey
#

It is saying unavailable

#

It is supposed to read date from another sensor, and was working in 2022.4

inner mesa
#

without any more info, I'm going to assume that you have some garbage in your sensor state and you didn't add a default

#

so the template is failing to render. And you would have a log message about that

#

and would have for 6 months or so

ornate osprey
#

I can check the log. ๐Ÿ™‚

#
TemplateError('ValueError: Template error: strptime got invalid input '2022-06-22 00:00:00' when rendering template '{{ (( as_timestamp(strptime(states.sensor.mat_plast_og_rest.state, "%Y/%m/%d")) - as_timestamp(strptime(states.sensor.date.state, "%Y-%m-%d") ))/ (3600*24)) | round() }}' but no default was specified') while processing template 'Template("{{ (( as_timestamp(strptime(states.sensor.mat_plast_og_rest.state, "%Y/%m/%d")) - as_timestamp(strptime(states.sensor.date.state, "%Y-%m-%d") ))/ (3600*24)) | round() }}")' for attribute '_attr_native_value' in entity 'sensor.dager_til_matavf'
#

So I guess my question is. What am I doing wrong? ๐Ÿ˜›

#

Anyone? :/

inner mesa
#

you should debug it in devtools -> Templates

#

you're providing the state of an entity and a format, and the two don't match

ornate osprey
#

I guess coding is not my greatest skill ๐Ÿ™„

#
ValueError: Template error: strptime got invalid input '2022-06-22 00:00:00' when rendering template '{{ (( as_timestamp(strptime(states.sensor.mat_plast_og_rest.state, "%Y/%m/%d")) - as_timestamp(strptime(states.sensor.date.state, "%d-%m-%Y") ))/ (3600*24)) | round() }}' but no default was specified
#

This is the output I got in template

inner mesa
#

guessing you didn't actually write this

#

this is the problem

ornate osprey
#

You could really tell ๐Ÿคฃ In between copy paste is a friend

#

Anyways the sensor it reads from is a custom component which provides a date for emptying of garbage bin, the sensor counts down the days until. Any idea how I can fix this. because it was working before? ๐Ÿ˜›

inner mesa
#

again, you need to debug it in devtools -> Templates. That doesn't just mean "paste it in there"

ornate osprey
#

2022-06-22 00:00:00 This is the output from the custom component

inner mesa
#

and that's clearly not the format you've provided for it

ornate osprey
#

So it is missing the hours? bc the format is correct? ๐Ÿ˜› Y m d ๐Ÿ˜ฅ

#

I could really just as well read chinese right now. Is it an easy fix, or should I just delete the code?

#

Anyways, thanks for that. I should have known I could have used google instead of discord. I guess Ill comment out or delete the code and forget about it. Have a good day ๐Ÿ™

thorny snow
#

Hi, how would I add leading zeros to a number? this is my current template, however it should always have 5 digits: {{ range(0, 99999) | random }}

mighty ledge
thorny snow
#

@mighty ledge mm. Its really just like that: I just want to have a random 5-digit number set as door open key every week.

mighty ledge
#

right, but you have to be using the template somewhere

#

where are you using it

mighty ledge
mighty ledge
ornate osprey
#

Thank you petro ๐Ÿ™‚

thorny snow
#

@mighty ledge this is the automation:

  • id: '1655307170540'
    alias: 'Set new code'
    trigger:
    • platform: time
      at: 01:00:00
      action:
    • service: input_text.set_value
      data:
      value: '{{ range(0, 99999) | random }}'
      target:
      entity_id: input_text.kennwort_haustur
tulip spindle
#
sensor:
  - platform: template
    sensors:
      carro_bluetooth:
        friendly_name: 'Carro Bluetooth'
        value_template: >
          {%- if states.sensor.poco_f2_pro_bluetooth_connection.attributes.connected_paired_devices == "[00:87:61:06:65:32]" %}
            Bruno
          {% else %}
            Desligado
          {%- endif %}
#

Hi guys, I have this template that suddenly stopped working. I don't really know how to solve it. Can anyone help? Thank you very much

dreamy sinew
#

go to the template tester ( devtools > Templates) and check the value of:
{{ state_attr('sensor.poco_f2_pro_bluetooth_connection', 'connected_paired_devices') }}

#

chances are it should be == ["00:87:61:06:65:32"]

tulip spindle
#

@dreamy sinew Thank you very much for your precious help, in the template tester I have true and false depending on whether the device is turned on or not. But I'm not able to create the sensor... I don't know much about this type of code...

marble jackal
#

Did you update the app recently? The connected Bluetooth device list is not actually a list and not a string looking like a list

tulip spindle
#

I updated yes, the problem is that it stopped working a while ago and only now I noticed it. When I test the template I have this. The device is off, but if you turn it on it passes true

marble jackal
#

Well the change is already 2 months old

#
sensor:
  - platform: template
    sensors:
      carro_bluetooth:
        friendly_name: 'Carro Bluetooth'
        value_template: >
          {%- if  "00:87:61:06:65:32" in state_attr('sensor.poco_f2_pro_bluetooth_connection', 'connected_paired_devices') %}
            Bruno
          {% else %}
            Desligado
          {%- endif %}
#

Try that

proper holly
#

Working with a blueprint and trying to use multiple selector for media_player domain entities

#

media_players_str: !input "media_players" media_players: "{{ expand(media_players) | list }}" media_states_str: !input "media_states" media_states: "{{ expand(media_states) | list }}" media_timeout: "{{ states('input_number.media_occupancy_timeout') | int(10) }}" media_is_playing: "{{ expand(media_players) | selectattr('state','in', media_states) | list | count > 0 }}"

#

I think something isn't right with what I am trying to do on expanding.

#

I get a "list" I believe of entity_id's from the selector, and I want to check if ANY of them are playing.

tepid onyx
#

morning,
This works but how do I write this in the newer format:
value_template: "{{ trigger.from_state.attributes.media_content_type == 'movie' }}"
This doesn't work:
value_template: "{{ state_attr(trigger.from_state.entity_id, 'media_content_type') == 'movie' }}"

tulip spindle
#

@marble jackal Thank you very much, it is already working as expected...

#

๐Ÿ™

marble jackal
tepid onyx
#

that would be why, whoops

#

thanks fes

#

Is there any way to test trigger templates in the template editor?

opaque creek
#

Hm. Will the Utility Meter's
"source: sensor.energy"
"cycle:daily"
use the daily-energy use from my energy dashbord? I want my daily energy as a sensor! Is that possible?
So far it just says "unknown" the sensor.daily_energy

manic tartan
#

@marble jackal I can see you have s good day today :-). Do you know how to dump script/automation variables? this.data or this.variables doesn't work. Thx in advance.

exotic jungle
#

hi is it possible to use this piece of code transition: '{{( as_datetime(state_attr(''sun.sun'', ''next_setting'')) - now()).seconds }} into part of a delay call? if so how do i do it.. thanks .. maybe delay: seconds: <<code here>> ?

inner mesa
exotic jungle
#

awesome thanks.. will give it a go

#

does that mean I need to convert it to minutes then?

#

oh sorry looking at the code again.. looks like the final output is in seconds?

silent vector
#

Is there a way to select light groups that are on? Not individual lights but light groups. Specifically zigbee groups not ha groups if that makes a difference. I know you can check a specific area but can you select light groups whether that's a specific area or globally?

mighty ledge
inner mesa
#

how do you differentiate a zigbee light group from any other light in HA?

marble jackal
#

I know Deconz and Hue both have an attribute for that on the entity. is_hue_group for example

#

Which can be true or false

#

I don't know how that is for ZHA and Z2MQTT

marble jackal
silent vector
marble jackal
#

but you might also want to check if they have an attribute you can use, so you are more free in the naming

silent vector
#

No special attributes other than the fact I gave all light groups icon: mdi:lightbulb-group

marble jackal
#

Which Zigbee integration do you use?

silent vector
#

ZHA

#

On temperature change the state result is 2 temperatures. I assume it's because I'm going to the minute on both the end of a time block and the start of a new one. Is there a template to only allow 2 digits (68)? Rather than 68 69 for example. Or is it as simple as a < 100 template. Or I can just stop going to the minute too lol.
https://dpaste.org/zVpmF

marble jackal
#

You could change {% for h in hours if h[0] <= t <= h[1] %} to {% for h in hours if today_at(h[0]) <= now() <= today_at(h[1]) %}

#

you can remove {% set t = now().strftime('%H:%M') %} then

silent vector
#

Perfect. Yeah as of now I don't think there's anything special for zha groups. Could that template be modified to check an area too?

marble jackal
#

yes

#

Did you remove the different settings for the days of the week btw?

silent vector
marble jackal
#

BTW, at eg 5:30, which state do you want to have then?

silent vector
#

{{ states.light | selectattr('entity_id', 'in', area_entities('Living Room')) | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }} this is used for regular lights. If i wanted to check an area for light groups with your template how would I add in the area?

#

Summer Daniels Thermostat Schedule changed to 63 65 per logbook. That's what was happening.

marble jackal
#

Yes okay, but at that time, would you want it to show 63 (so using the end time 5:30) or 65 (using the start time 5:30)

silent vector
#

At that time it should show 65

marble jackal
marble jackal
silent vector
#

I also have the individual lights in the areas though. I would want to use the same lights filter you used to select the light group.

marble jackal
#

yes, just combine it

#

{{ states.light | selectattr('entity_id', 'in', area_entities('Living Room')) | selectattr('entity_id', 'match', '.+_lights$') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}

silent vector
#

Perfect. Would the thermostat schedule you just sent also work for multiple day settings? All I would do is use the conditional state on which attribute to use as I did here right?
https://dpaste.org/X6uTw

marble jackal
#

Yes, as soon as you define hours the rest is the same, so it will also work there

silent vector
#

Perfect. Thank you.

silent vector
#

Could this work? The repeat.item isn't working. https://dpaste.org/O19Jr
From step details

service_data:
    topic: frigate//improve_contrast/set
    payload: 'OFF'
marble jackal
#

trigger.item only exists in a for_each repeat

#

you are now using a count repeat

#
  - repeat:
      for_each: "{{ outdoor_cameras if trigger.id == 'outdoor' else indoor_cameras }}"
      sequence:
        - service: mqtt.publish
          data:
            topic: frigate/{{ repeat.item }}/improve_contrast/set
            payload: >-
              {{ 'ON' if trigger.entity_id in ['sensor.outdoor_light_on', 'input_boolean.downstairs_shades_status' ] 
                and is_state('input_boolean.downstairs_shades_status', 'on') else 'OFF' }}
vast iris
#

Hi I need some help:

total_energy_consumption_from_grid: friendly_name: "Stromverbrauch" unit_of_measurement: "kWh" device_class: energy value_template: > {% if states('sensor.total_energy_text') == 'unavailable' %} {{ states('sensor.total_energy_consumption') }} {% else %} {{ ((states('sensor.total_energy_text') | float) * 0.0001) | round(2) }} {% endif %}

The sensor is not available to energy dashboard, how can I fix that?

marble jackal
#

it needs state_class: total_increasing

#

But you can't add that using the legacy format, so either convert it to the new format, or add that using customize.yaml

#

as you are using two different sensors here, be careful you don't get value decreases, that will mess up your energy dashboard

silent vector
vast iris
#

Oh I didn't knew there is a new format. I have to check that. The second should only show the current value in case my sensor is down. I also could remove it. I thought I would avoid problems with that.

#

@marble jackal Awesome it worked - but I just used the customize entry. I have to convert the sensors later on. Thank you for your help.

slow vine
#

Is there a way to use a template to add parameters to a shell_command from the service call itself? I searched and saw that I can use a template to get data from a different sensor but I couldnt find how to send data via service_call. Example:

shell_command:
  echo_test: echo {{ my_name }}

automation:
...
    action:
      service: shell_command.echo_test
      data: "Russell Joseph"
wild anchor
#

How can i parse this number 1655326503002 (Javascript timestamp) to a relative time.
This one is working, and show me the correct time
{{ (1655326503002 / 1000 ) | timestamp_custom("%Y-%m.%d %H:%M:%S.611725-03:00") }}
But i cant parse to get it as relative time

floral shuttle
#

having this template works fine: {% set presence = states('zone.home')|int(0) %} {% set icon = {0:'mdi:account-off', 1:'mdi:account', 2:'mdi:account-multiple', 3:'mdi:account-multiple-check'} %} {{icon.get(presence,'mdi:account-group')}}

#

however, template for the colors goes awol: {% set presence = states('zone.home')|int(0) %} {% set colors = ['grey','steelblue','saddlebrown', 'gold','darkorange','maroon'] %} {{colors.get(presence,'green')}} with UndefinedError: 'list object' has no attribute 'get'

#

this works, but hasn't got the guard {% set presence = states('zone.home')|int(0) %} {% set color = ['grey','steelblue','saddlebrown', 'gold','darkorange','maroon','green'] %} {{color[presence]}} so I would need to go back if /else, while i like the getter.. what am I missing?

mighty ledge
mighty ledge
#

icon is a dict btw

#

in your first template

wild anchor
#

I love you petro, i have 10 days trying differents approachs!

floral shuttle
#

Nothing wrong with a good old fashioned if / else ;/)

mighty ledge
#

or just change your last line to
{{ colors[presence] if presence < colors | length else 'green' }}

#

@floral shuttle

floral shuttle
#

Ok let me think that through ..thx!

hearty prairie
#

I have a list with long/lat and see that HA has a distance/closest function allowing me to calculate the distance from home to that point... any idea on how I may reorder that list by running that function for every item? I mean.. is there anything similar to a sort lambda kind of function in jinja? The only thing I can find is sort(attribute=foo)

dreamy sinew
#

looks like distance isn't set up as a filter, only as a function

#

@hearty prairie try something like this:

{% set ns = namespace(distances=[]) %}
{% for location in locations %}
{% set ns.distances = ns.distances + [{'name': 'loc{}'.format(loop.index), 'distance': distance(location[0], location[1])}] %}
{% endfor %}
{{ ns.distances|sort(attribute="distance") }}```
hearty prairie
#

was just hoping I could do this as a oneliner/simpler :p

dreamy sinew
#

that was working in the template tester so could definitely mess with it

#

yeah, without distance as a filter you have to use a loop

hearty prairie
#

ok, but then I'm on the right track, awesome ๐Ÿ™‚

full token
#

Hi
I already talked about my issue a few days ago, but I still can't figure out how to make HA "understand" the status of my light ๐Ÿ˜ฆ

#

( Using last version, I changed since last time )

inner mesa
#

I thought we went through this already

#

What you have there won't work

full token
#

I tried using payload_on=1 and payload_off=0, but I couldn't make it work either

inner mesa
#

Well, start there

#

Don't stick templates in the payload keys

full token
#

Since my last try, I enabled logs, and it doesn't complain with that config, so I thought I was on the right way ๐Ÿ˜ฆ

#

Is there a way to give a command template using those payload ? So that it receives a json message ?

inner mesa
#

There's no point to that, you just need to parse it in the state_value_template so you end up with a string

#

You're trying to move the wording around, which isn't allowed, and just makes it more complicated

#

You can go to configuration -> Integrations -> MQTT -> Devices, find your device, click MQTT Info to see what's it's getting and how the payload is being parsed

full token
#

"This entity ('light.salon_plafonnier') does not have a unique ID, therefore its settings cannot be managed from the UI. See the documentation for more detail."

#

To avoid that, I tried to use object_id but it doesn't seem to change much

#

Now the status is ok, if I switch the light on/off without using HA, but trying to do it with HA doesn't work as following the logs, HA send "1", while "{"type":"Buffer","data":[1]}" is expected

full token
#

Ok, it's unique_id that I must use, not object_id ๐Ÿ™‚

full token
#

Thanks for your help @inner mesa ๐Ÿ™‚

silent vector
#

This isn't triggering off the time pattern and I assume it's because the condition is messing it up. How would I keep the condition efficient while accounting for the fact one of the triggers is a time pattern?
https://dpaste.org/EpG4u

frank gale
#

I have a known entity_id light.wled from a device WLED Livingroom. I want to get the entity that contains the string _intensity and has numberas device_id.
How could I do that?
I got the device_id from this:

{% set con = states
              | selectattr('entity_id','eq', 'light.wled')
              | map(attribute='entity_id')
              | map('device_id')
              | first %}

Now I'm missing the part to track down the number with _intensity in entity_id which is child from this device_id

marble jackal
#

{{ device_entities(con) | expand | selectattr('domain', 'eq', 'nubmer') | selectattr('entity_id', 'search', '_intensity') | list }}

frank gale
#

Thanks!!!

vagrant monolith
#

Hey!

silent barnBOT
vagrant monolith
mighty ledge
#

reject the ones that are none if they are actually none. if they aren't defined, only select the ones that are defined

vagrant monolith
#

How?

mighty ledge
#

how did you select the ones with the datetime?

#

did you copy/past that template or make it yourself? I guess that's what I should ask you.

vagrant monolith
#

I made it myself with some help of template guys

#

I mean, some of the sensors only works on some days, because other days the values can be none

mighty ledge
#

do you understand selectattr?

vagrant monolith
#

Not exactly

mighty ledge
#

ok

#

then just add | selectattr('attributes.today', 'defined') | selectattr('attributes.today', 'ne', none) before your other selectattr

vagrant monolith
#

defined?

mighty ledge
#

yes defined

vagrant monolith
#

So this?

mighty ledge
#

yep

vagrant monolith
#

Lets see if it works, and is it possible to check so its a date instead?

mighty ledge
#

nope

vagrant monolith
#

Okay

mighty ledge
#

you have to check to see if it exists

vagrant monolith
#

But lets see if they got a value yet

mighty ledge
#

try it in the template tester

#

no point in restarting if it doesn't work there.

#

templating 101

vagrant monolith
mighty ledge
#

template editor -> then deploy

#

what's the format of today?

vagrant monolith
mighty ledge
#

where does that come from

vagrant monolith
#

What do you mean?

#

It's a custom component

mighty ledge
#

yeah, so is it always strings or is it always datetimes? right now they look like strings, not datetimes

#

I have no idea how that template ever worked before.

vagrant monolith
#

One second

#

They are strings indeed

#

And idk

mighty ledge
#

Well, what custom integration

vagrant monolith
#

sun2

#

I think this is solving string to date

#

device_class: timestamp

mighty ledge
#

that's for the main state

vagrant monolith
#

Okay

#

Looks like i solved it chaning none to "none"

#

{{(sensorData|selectattr('attributes.today', 'defined')|selectattr('attributes.today', 'ne', "none")|selectattr('attributes.today', '<', now())|

mighty ledge
#

ok, it's always a string, just looked at code

vagrant monolith
#

Do you have any recommendation for making the template better?

#

Still doesnt work tho

mighty ledge
#

becuase they aren't datetimes

vagrant monolith
#

But its not the template

#

Its something in my spaces

mighty ledge
#

they are strings

vagrant monolith
mighty ledge
#

you don't have enough indents

vagrant monolith
#

First line right?

#

The one that has least spaces

mighty ledge
#

yes

vagrant monolith
#

Okay, thanksรค

#

Now it works, thanks ๐Ÿ˜„

#

I have one more problem

#

My SMHI sensor returns unavailable

#

Until I reload the sensor after each restart

barren jungle
#

script.toggle service is such a weird concept.
I wonder in what scenario folks use this?

mighty ledge
#

when you have a delay, turning off a script stops the script in the delay

silent vector
#

This isn't triggering off the time pattern and I assume it's because the condition is messing it up. How would I keep the condition efficient while accounting for the fact one of the triggers is a time pattern?
https://dpaste.org/EpG4u

barren jungle
#

(this isn't really serious problem i'm just bored)

#

But then why doesn't camera and climate have a .toggle?
if they have .turn_on and .turn_off defined

mighty ledge
#

because they don't have on/off states?

#

toggle only works on something that has an on, off state and the on off state needs to be known to HomeAsisstant

#

cameras and climate have other states aside from on, off

#

so toggle doesn't make sense

#

where a script can be 'on' when running, so you can toggle it off

#

it's not something that's purposely given to that domain, it's inherited by the fact that it has an on/off state.

barren jungle
#

but media_player has multiple states (like paused, idle, buffering) and supports toggle. And so does vacuum.

marble jackal
inner mesa
silent vector
#

Add and trigger.platform != "time_pattern"?

inner mesa
#

I'm not entirely sure what you're doing there because you're not actually using the values from the state change

silent vector
#

I'm trying to stop it from doing anything if the to state is null or unavailable

inner mesa
#

That's one way to limit it

silent vector
#

The to state will be a number

inner mesa
#

But you're just unconditionally proceeding at 5 after the hour anyway

silent vector
#

Well actually I want it to pass if it's a time pattern I just want it to not pass if it's the sensors and their value is null or unavailable. The way the sensor is setup both will occur.

inner mesa
#

But, again, you're going to proceed once an hour no matter what

silent vector
#

I'm not sure I'm following. How would that occur? It's ok if it's the time pattern that's the trigger. It's not ok if the trigger is the sensors and their to state value at the time of the trigger is null or unavailable. That's idea of what I'm trying to prevent.

inner mesa
#

Ok, it does that

#

My point is that regardless of whether those sensors are valid, it's going to proceed to the action once an hour

silent vector
#

But how lol that's why I'm confused

inner mesa
#

Because you're explicitly restricting the condition to the state trigger

#

If you want it to apply all the time, put both sensors in the condition explicitly

silent vector
#

Yeah I realized that wouldn't make sense. can I do a conditional statement if elif in a condition?

inner mesa
#

You don't need that

silent vector
#

Yeah it would make sense to be if the trigger is either of the sensor their values can not be equal to null or unavailable. If it's a time pattern it's fine to pass and then I should probably check the state of the sensors though to make sure they aren't equal to null or unavailable

inner mesa
#

You really don't care what the trigger is

silent vector
#

It only happens for a minute. So it will be corrected next time around.

#

Yeah I guess that's correct. I really care about the state value.

#

I should just say both have to be not equal to unavailable and null

inner mesa
#

So just check that with a template

silent vector
#

It happens on template reload the way the template is setup it will result in null for 1 minute. Yeah that makes more sense.

lethal bison
#

Apologies in advance - I still don't quite get the layout and structure of the yaml files in HA. Trying to implement a 'presence detection timer' sensor - to report how long it's been since a user has been 'home' - using this as a guide (https://community.home-assistant.io/t/presence-detection-calculate-time-away-and-set-as-variable/92453/3). Is there a way to add a variable or three in the yaml so a sensor is kept for each of my configured users, without having to manually add/copy/paste the entire codeblock for each user?

vagrant monolith
#

Hey

#

How do I convert attributes.today to a Datetime?

      {{(sensorData|selectattr('attributes.today', 'defined')|selectattr('attributes.today', 'ne', "none")|selectattr('attributes.today', 'ne', "")|**selectattr('attributes.today', '<', now())**|
rose scroll
warm heron
#

hey I need a little help:

#

My I have no idea how to extract the hours in format HH:MM out of this template.
{{ (as_timestamp(fcast.datetime) | timestamp_local) }}
I wanted to use .strftime() but the object type that I get from these are either float or string.

#

of course I want the local hours and minutes.

warm heron
warm heron
marble jackal
marble jackal
silent vector
#

Can a math expression be a variable? I'm trying to do this in the template editor and it's not working.

{% set input_number = 50 %}
{% set mode = '+' %}
{{ input_number mode 2 }}

Ideally the answer would be 52.

marble jackal
#

Then I guess the answer is no ๐Ÿ˜…
{{ input_number + 2 if mode == '+' else input_number - 2 }} maybe?

silent vector
#

Yeah that's perfect. Good to know that it can't be done the way I tried.

marble jackal
#

Or this

{% set input_number = 50 %}
{% set mode = '-' %}
{{ input_number + int(mode ~ 2) }}
#

Only works for + and - though

silent vector
#

Yeah that's all I needed + and -. What is ~ called?

marble jackal
#

Both sides of it will be combined together as a string

#

So in the example above it will be "-2"

silent vector
#

I see, is there a name for the specific ~ though? Is it concatenate?

marble jackal
#

Well that is what is does ๐Ÿ‘๐Ÿผ

silent vector
#

How would I get this to evaluate to true? Based on current conditions it should be evaluating to true. temperature is 70 and the input number is 70

{% set input_number = 'input_number.daniels_scheduled_temperature' %}
{% set mode = '-' %}
{% set entity = 'climate.daniel_s' %}
{% if states(entity) == 'cool' and state_attr(entity,'hvac_action') == 'idle' and state_attr(entity,'temperature') | int(mode ~ 2) < states(input_number)| int %}
true
{% endif %}
#

This worked

{% set temperature = state_attr('climate.daniel_s','temperature') %}
{% set input_number = states('input_number.daniels_scheduled_temperature') | int %}
{% if temperature + 2 > input_number %}
e
{% endif %}
warm heron
#

thanks for the help earlier! I have another question tho:

What am I doing wrong here? I want to store the values of my for loop calculation in this list to use it later in the template.

{% set offsetList = [] %}
{% for i in range(columns) %}
{% if columns % 2 == 1 %}{% set columns = columns - 1 %}{% endif %}
{% set offsetList = offsetList.append((i - (columns / 2) - crossShift)) %}
{% endfor %}

however I get SecurityError: access to attribute 'append' of 'list' object is unsafe..

#

I could just use the values straight away but It makes the code messy and very long lines in this case

marble jackal
silent vector
#

That worked thank you as always!

marble jackal
#

I used int as a function, and you used that part as the filter to convert the state to an integer

astral pebble
#

how would i turn the [132.0, 136.5, 140.5] the statistics sensor gives out into a list?

#

would i just have to do string parsing or is there a better way?

inner mesa
#

It's not a list?

astral pebble
#

{{ states("sensor.co2_history")[0] }} gives me just a [

#

so does {{ states.sensor.co2_history.state[0] }}

inner mesa
#

there's probably a better way, but:
{{ "[1, 2, 3]"[1:-1].split(', ')|map('float')|list }}

astral pebble
#

that does indeed work

#

now time to see if i can actually get the automation to work

#

so {{ states("sensor.us_nw_psei_co2_intensity") | float <= (states("sensor.co2_history")[1:-1].split(', ') | map('float') | list)[0] }} should get if the co2 intensity is relatively low

marble jackal
inner mesa
#

see, I knew there was a better way ๐Ÿ™‚

astral pebble
#

works ๐Ÿ‘

fierce hornet
#

I'm creating a template cover so the cover shows closed when the position is 8 or lower. and otherwise uses the state of the actual cover.

  closed
{% else %}
  {{ states('cover.screen_kamer1_source') }}
{% endif %}```
The problem is. When closing the cover a little bit, the cover assumes it's open and so doesn't display the up arrow on the frontend. Is there a way to fix this?
#

Found the answer myself, by just adding the position template ofcourse. Problem solved.

paper hazel
#

Hi, I'm struggling to get my mind around how I could get this to work. Any suggestions will be much appreciated```
- condition: time
after: "{{ states('input_datetime.reminder_start_time') }}"
before: "{{ states('input_datetime.reminder_end_time') }}"

#

Nevermind - Found it. Read over it probably 20 times ๐Ÿคฆโ€โ™‚๏ธ --> condition:```

  • alias: "Example referencing a time helper"
    condition: time
    after: input_datetime.house_silent_hours_start
    before: input_datetime.house_silent_hours_end
warm heron
inner mesa
#

You need to use a namespace

#

Random example:

#

@warm heron

thorny snow
#

Hey everyone, can anyone help me with this value template. Trying to get 3 values from a sensor. But itโ€™s failing for some reason and Iโ€™m having a total brain freeze. {{ state_attr('sensor.my_gmail_com','body')
|regex_findall_index("(?:^|(?<= ))(light|off|bedroom)(?:(?= )|$)")

tepid onyx
#

If I use {{ trigger.now }} it displays as a full timestamp e.g.: 2022-06-19 19:36:00.000589+10:00'
What filter can I use to just display %H:%M
I've tried:
{% set test = { "ts":"2022-06-19 19:36:00.000589+10:00" }%} "{{ as_timestamp(test.ts) | int(0) | timestamp_custom('%H:%M', False) }}"

#

but it displays 09:36 instead of 19:36 for some reason

#

in the automation i would use: "{{ as_timestamp(trigger.now) | int(0) | timestamp_custom('%H:%M', False) }}"
but it converts it to the wrong time

tepid onyx
#

had to remove "false", solution is:
"{{ as_timestamp(trigger.now) | int(0) | timestamp_custom('%H:%M') }}"

#

Does that mean it's using utc time. My HA instance has the correct time from my ntp servers. addiing "False" to "timestamp_custom()" makes it localtime right?

marble jackal
#

@tepid onyx you can try trigger.now.strftime('%H:%M') if it is a datetime object. Otherwise as_datetime(trigger.now).strftime('%H:%M')

warm heron
#

maybe something like a not-random example ^^'

inner mesa
#

Did you read it and see the namespace reference?

#

It's not that complicated

warm heron
#

yes I read it - with namespace reference do you mean the method in the example?

#

because I do not understand the use of namespace()

inner mesa
#

Ok

marble jackal
#

Without the namespace you can not define a variable in a for loop and use it outside the loop

warm heron
#

got so far

tepid onyx
marble jackal
warm heron
# marble jackal And how far did you get in applying it to your code?

I got this from an xda devs pretty much as a skeleton but I do not understand it:

{% set crossedAt = namespace(value=0) %}
{% for entry in state_attr("weather.home_hourly", "forecast") | reverse() -%}
  {% if entry.temperature|float > 22 %}
    {% set crossedAt.value = loop.revindex %}
  {% endif %}
{%- endfor %}
{% set crossedAt = crossedAt.value %}
#

it works

marble jackal
#

Okay, and which part do you not understand?

warm heron
#

what I need to put into namespace and what it does to the variable I'm setting it to

marble jackal
#

In your case you need to create a namespace for your offsetList

#

something like:

{% set ns = namespace(offsetList = [] %}

And then use ns.offsetList instead of offsetList

sturdy bay
#

Embarassing question: I see a lot of mention of sensors like sensor.count_sensors and sensor.count_binary_sensors but I don't see any reference of how those are created. Could someone point me to the idiot's guide on how to create these sensors?

inner mesa
#

they're template sensors

#

the channel topic has links to the docs for templating

sturdy bay
#

Thanks, found what I was looking for!

primal zealot
#

Hey.... i was wondering if anyone knows why is this wrong:

  - platform: mqtt
    state_topic: "nudge/ou_04"
    name: "esp_nudge_04"
    value_template: {{value_json.state}}```

This is what i get when i check the configuration:

Error loading /config/configuration.yaml: invalid key: "OrderedDict([('value_json.state', None)])"
in "/config/configuration.yaml", line 78, column 0```

inner mesa
#

Yes, surround the template in quotes

warm heron
#

It works!

marble jackal
#

Didn't expect otherwise ๐Ÿ˜‰

fallen topaz
#

Hi folks! Apologies if this isn't the right place to ask. I am tinkering with getting Home Assist to talk to a homemade MQTT light I rigged up years ago that has a VERY non-standard control format as a result. I'm comfortable creating the logic to control it, the only question is, how do I determine what is present in the command payload when I control it with the dashboard. For instance, if I slide the brightness slider, how do I know if the information passed to the MQTT Light template has things like colors or effects defined. Is there a way to interrogate exactly what's being sent by Home assistant when I adjust a light with the GUI?

stuck remnant
marble jackal
#

Replace the triple single quotes

#

You probably used the GUI to add it, and added quotes around the template there, the GUI added more quotes

stuck remnant
#

yeah haha

marble jackal
fallen topaz
marble jackal
fallen topaz
sturdy juniper
#

Can I directly use a device_trackers's attribute inside a templae sensor where I want to count how many device_trackers are in a certain state or do I first need to create seperate template sensors for each attributes themselves ?

inner mesa
#

What attribute?

sturdy juniper
#

ap_mac

inner mesa
#

You just want to know how many have a certain value?

sturdy juniper
#

want to count the amount of devices connected to a certain AP

#

yes

inner mesa
#

{{ states.device_tracker|selectattr('attributes.ap_mac', 'defined')|selectattr('attributes.ap_mac', 'eq', 'whatever')|list|count }}

sturdy juniper
#
{{ [
          is_state('state_attr(device_tracker.xxx', 'ap_mac)', 'xx:xx:xx:xx'), 
          is_state('state_attr(device_tracker.xxx', 'ap_mac)', 'xx:xx:xx:xx'), 
          is_state('state_attr(device_tracker.xxx', 'ap_mac)', 'xx:xx:xx:xx'), 
          is_state('state_attr(device_tracker.xxx', 'ap_mac)', 'xx:xx:xx:xx'), 
          ] | select('true') | list | count }}
#

was hoping to use it like that since I'm only interrested in 4 devices

#

but that's not working :p

inner mesa
#

that could be simpler...

#

right, it's also broken

#

see mine

sturdy juniper
#

TIL, thanks !!!

inner mesa
#

if you just want some device_trackers:

#
{% set devices = ['device_tracker.xxx', 'device_tracker.yyy', 'device_tracker.zzz'] %}
{{ devices|expand|selectattr('attributes.ap_mac', 'defined')|selectattr('attributes.ap_mac', 'eq', 'whatever')|list|count }}
marble jackal
#

Use what Rob provided indeed, if you want to limit it to this 4, you can put them in a group

#

Or do that :)

sturdy juniper
#

wow, I wish I had 10% of your skills ๐Ÿคฃ

marble jackal
#

Nice thing about a group is that you can do that in the GUI, so it's easy to add or remove trackers

#

@sturdy juniper What you had didn't work because you were checking for the string 'true'. It would have worked if you used select()
{{ [ true, true, false ] | select() | list | count }} results in 2

#

Oh, and instead of state_attr(x, y) == z you can also use is_state_attr(x, y, z)

#

Just for future templates ๐Ÿ‘๐Ÿผ

sturdy juniper
#

thanks alot ! I'll have to schedule some tutoring lessons with you sometime ๐Ÿ˜„

kind silo
#

What is the proper way to write
- platform: template sensors: door_garage_single_door: value_template: >- {% if ((float(states.sensor.xiaomi_vibration_garage_single_door_angle_y.state) > 60)) and ((float(states.sensor.xiaomi_vibration_garage_single_door_angle_z.state) > 0)) %} Closed {% else %} Open {% endif %}

marble jackal
marble jackal
# kind silo What is the proper way to write `- platform: template sensors: door_garag...

The proper way is not to use state.some.entity_id.state, but use states('some.entity_id').
You are also using the legacy template, which is not an issue right now, but it could be that it will be depreciated in the future.
And you are not providing defaults for your float functions, or providing an availablity template, which will cause issues when the sensors are not available (eg just after restart)

thorny snow
# marble jackal Regex is not my strongest suit, what are you trying to achieve here?

Iโ€™m trying to have a trigger or a condition in automation using value template, so when I receive an email with certain words in it through imap integration, the automation that contains the template runs. The order of words can be in any order and letter case can be either upper or lower case. Thatโ€™s why Iโ€™ve tried regex way as I was trying to simplify the search/match of the key words

#

The whole idea is to have an automation that runs and executes on keywords that appear in an email no matter in which order they show up nor what letter case they are in. Using Siri, i tell her โ€œNote Turn off the lights in the living roomโ€ , Gmail gets an email in folder/label Notes with subject/body โ€œTurn off the lights in the living roomโ€. HA automation gets key words โ€œoff light living roomโ€ and kills the light in living room. Thatโ€™s why I need help with the template, canโ€™t figure out how to have it search for words in non particular order and not depending on letter case

marble jackal
#

Uhm, I might be mistaken, as I don't use Apple, but I believe there is an integration to link HA with Siri (HomeKit)

thorny snow
#

That part Iโ€™ve already figured out, the only reason Iโ€™m using Siri here is to have it put a note in google notes aka make a new email that syncs instantly with the gmail folder/label notes. Subject ends up being the note Iโ€™ve told Siri to make

#

Then having imap integration check for that folder and get the note aka email as state, in my case subject/state ends up being โ€œset living room light offโ€

#

That part is done

#

Now Iโ€™m trying trigger an automation using a template that searches/matches keywords from the state/subject of the email imap integration received

#

And thereโ€™s where Iโ€™m stuck, canโ€™t figure out how to make a template that searches/matches keywords in no particular order and no matter what lettercase keywords are

silent vector
#

For some reason I can't paste these variables into an automation editor without an error. I tested the logic and it works. Not sure why I'm getting an error.
https://dpaste.org/K5TTm

odd condor
#

Hi guys! Possibly a stupid question, but... How do I extract 'last_changed' value of an entity so I can use it in templates? If I'm not mistaken it used to be under attributes, but I don't see it there any more? Thanks!

odd condor
silent vector
#

The red line, if you go back to ui editor and come back it's gone because It thinks something is wrong with it. It won't save with it either. Never had this happen so I assume there may be an issue with the code? I tried saving and it saved but removed it.

marble jackal
#

The dpaste shows some strange syntax highlighting, did you use tab instead of spaces maybe?

#

and you intend it a bit much

silent vector
#

I do about 99% of my editing on Mobile on an app called "quick edit" and I think it tends to jack up spacing. I did some changes in the automation editor and it took it. One more question.

#

how would i format this
{{ now().strftime('%H:%M') >= '20:00' and now().strftime('%H:%M') <= '06:00' }}
As that doesn't seem to work

#

then how would i add a Not (both not between the time frame and cooling) meaning if it's between the timeframe it can't be cooling then.

{{ states(condition) != '' and states(condition) != 'unavailable' and states('input_boolean.3_zone_script_running_status') == 'off' and not now().strftime('%H:%M') >= '20:00' and now().strftime('%H:%M') <= '06:00' and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' }}```
marble jackal
#

{{ now() >= today_at('20:00') or now() <= today_at('06:00') }}

#

You need to use or here, not and

#

states(condition) != '' this will probably never be the case, states() always returns the state, or unknown, or unavailable.

silent vector
#

Yeah I remembered the time from the schedule we worked on together but I couldn't figure out how to put that in a condition. When it's null it will be unknown or unavailable?

marble jackal
#

states.some.entity_id.state can return null, but states() will never do that

#

and x == '' will not check for null, you need to use x is null then

#

{{ states(condition) not in ['unavailable', 'unknown'] and states('input_boolean.3_zone_script_running_status') == 'off' and (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' }}

silent vector
#

Does the not in make the rest of the statement not? As in it would be true as long as all of those are not what is specified.

marble jackal
#

no, not all of those, only the states(condition) in [ 'unavailable', 'unknown' ] part

silent vector
#

I would want to have the time and cooling be tied together. If it's during that time and cooling it's false if it's not during that time and it's cooling it doesn't matter.

marble jackal
#

Maybe it's easier if you split it into different parts

{% set condition_state = states(condition) not in ['unavailable', 'unknown'] %}
{% set boolean_state = is_state('input_boolean.3_zone_script_running_status', 'off') %}
{% set time_cooling = (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' %}
{{ condition_state and boolean_state and time_cooling }}
silent vector
#

I was thinking that.

#

And to use in a condition just make it a variable

#

That can be used that way in a condition?

marble jackal
#

Yes, it will return true or false

silent vector
#

Because it will be either true true true = true or false true true = false?

marble jackal
#

Yes

silent vector
#

Wow I didn't know that was possible. Thank you.

marble jackal
#

It's not different in what you were already doing, it's just cut into chunks

thorny snow
#

Hi, I am having issues with getting a garage door cover setup using a single relay (zooz zen17) and single door sensor (SM-4201-LQ) mounted to the bottom of the door on one side. The overall function is working fine aside from the change of state reported by the sensor. What happens is when the sensor changes state it will quickly 'bounce' and go from 'open > closed > open' or 'closed > open > closed'

I am looking for some advice on how to go about debouncing that state change so it only goes from open > closed or closed > open.

silent vector
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.

valid hatch
#

So template switches, locks, covers, etc still use the "legacy" style?

marble jackal
#

Correct

cobalt otter
#

Where can I find more documentation on the various functions available to me in templates? E.g., the {{ states('climate.garageac1') }} states() function. My google-fu is failing me.

inner mesa
#

in the links from the channel topic

silent barnBOT
cobalt otter
#

Thanks!

#

(should have been obvious, but I guess I'm blind these days!)

silent vector
# marble jackal Maybe it's easier if you split it into different parts ```jinja {% set condition...

This isn't evaluating to true. The first 2 are. The time isn't. The goal would be for this to be true outside of the hours between 20:00 and 06:00 if the thermostat is also cooling. Meaning if during 20:00 and 06:00 the thermostat is cooling this would be false. in addition to the first 2 conditions being true of course. Would I do this {{ not (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' }}

silent seal
#

this translates to:
Not after 8pm
Not before 6am
hvac action is cooling.

So it would only be true after 6am, and before 8pm, when the HVAC is cooling

silent vector
#

Original post from thefes

{% set condition_state = states(condition) not in ['unavailable', 'unknown'] %}
{% set boolean_state = is_state('input_boolean.3_zone_script_running_status', 'off') %}
{% set time_cooling = (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' %}
{{ condition_state and boolean_state and time_cooling }}
inner mesa
#

Most of this is just writing down what you want to do and adding English words like and and or

#

There's little magic involved

silent vector
#

Yeah I know. The problem I'm having is the time.

#

Getting the time frame correct.

#

It's easy to say and and or not. I'm struggling with saying and and not between the time frame and cooling during that time frame

silent seal
#

Start by writing something that evaluates to true for the time.
Then write something that returns true for the HVAC
Now take both statements and write
(statement 1) and (statement 2)
You only need to wrap them in brackets if they contain and or or, but adding extras, as long as they line up, doesn't hurt.

marble jackal
#

so if it has to be true in that timeslot, and when the state is cooling, it would be:
{{ today_at('06:00') <= now() <= today_at('20:00') and is_state_attr('climate.daniel_s', 'hvac_action', 'cooling') }}

silent vector
marble jackal
#

okay, so it needs to be false when this is true {% set time_cooling = (now() >= today_at('20:00') or now() <= today_at('06:00')) and state_attr('climate.daniel_s', 'hvac_action') == 'cooling' %}

#
{% set condition_state = states(condition) not in ['unavailable', 'unknown'] %}
{% set boolean_state = is_state('input_boolean.3_zone_script_running_status', 'off') %}
{% set time_cooling = (now() >= today_at('20:00') or now() <= today_at('06:00')) and is_state_attr('climate.daniel_s', 'hvac_action', 'cooling') %}
{{ condition_state and boolean_state and not time_cooling }}
silent vector
#

Yes. I also have a weird automation issue. This works sometimes and others it doesn't. It's weird because in the template editor it works everytime but in the automation it is null or only one of 2 variables needed actually does anything. I'm not sure if it's because I'm using 'true' and it's messing with stuff but the other one should be a number. I also don't think I did the value on the for each properly.

Here's when it worked but only for being 'true' and null for the number below it.
https://dpaste.org/5q3YF

When it didn't work.
https://dpaste.org/1FZwB

What the automation yaml was when it did and didn't work.
https://dpaste.org/naKAK

Full Yaml
https://dpaste.org/UJdEK

marble jackal
silent vector
#

Going to check now thank you.

marble jackal
#

Some advice on your variable

silent vector
#

That worked (time condition). And would that fix the null temperature deviation too (the changes you said to make)

marble jackal
#

maybe

#

๐Ÿ™‚

silent vector
#

Is that true supposed to be there with the elif on line 29?

marble jackal
#

whoops, I missed that one, it was not indented like the rest

silent vector
#

Oh ok. Is what I'm doing with the for each value going to work? Using repeat.item to evaluate the state

marble jackal
#

Looks okay, but it is a bit hard to read because the GUI probably messed it up

#

but states(repeat.item) should work

silent vector
#

Yeah the gui does mess it up I wish it didn't. I just tested the changes. The deviation was true. Perfect. But the temperature keeps nulling out.

#

Which Is so weird because as I said it works in the template editor.

#

Error rendering variables: UndefinedError: 'repeat' is undefined Error rendering variables: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

marble jackal
silent vector
#

Nope that's an automation error

#

homeassistant.components.automation.new_automation77 Source: components/automation/__init__

marble jackal
#

If you put something like this at the the top of the template editor, the template seems to work without errors:

{% set repeat = { 'item': 'input_number.left_dockpro_temperature' } %}
{% set dockpro_condition = 4 %}
#

But I don't have these entities, so it doesn't render anything for me. But you can probably use it to debug your template

#

however, the variable repeat should be available in your repeat action

silent vector
#

I will try.

#

And for the temperature deviation temperature? Any idea why it's null, it's a really simple template.

#

It does work in the template editor so weird.

#
{% set repeat = { 'item': 'input_number.left_dockpro_temperature' } %}
{% set dockpro_condition = '+' %}
{{ states(repeat.item) | int + int(dockpro_condition ~ 4) }}

Evaluates to 78

marble jackal
#

It will fail on this trigger:

  - platform: state
    entity_id:
      - sensor.daniels_summer_temperature_overshoot
      - sensor.master_bedroom_summer_temperature_overshoot
    id: Overshoot Fallback
    from: 'False'
    to: 'True'
#

The trigger.entity_id won't have an attribute temperature then because it is not a climate entity

silent vector
#

That's why I have the fall back thermostat variable. It works. It takes the object Id and changes it to the climate entity id

marble jackal
#

but not in the temperature deviation temperature variable

silent vector
#

It's not meant for that action. It's meant to track the the attribute temperature changes from the trigger.id 'Temperature' only the overshoot uses the fallback thermostat variable to determine the correct thermostat

marble jackal
#
  temperature_deviation_temperature: >-
    {% if trigger.to_state.attributes.hvac_action == 'cooling' %} 
      {{ state_attr(trigger.entity_id, 'temperature') + 2 }} 
    {% elif states(trigger.entity_id) == 'cool' and states(trigger.entity_id) == 'idle' %} 
      {{ state_attr(trigger.entity_id, 'temperature') }} 
    {% elif trigger.to_state.attributes.hvac_action == 'heating' %} 
      {{ state_attr(trigger.entity_id, 'temperature') - 2 }} 
    {% elif states(trigger.entity_id) == 'heat' and states(trigger.entity_id) == 'idle' %} 
      {{ state_attr(trigger.entity_id, 'temperature') }}
    {% endif %}
#

The 2nd and 4th statement can never be true, the entity has to have 2 different states at the same time

#

both (cool or heat) and idle

#

This template will also fail to render on the trigger Overshoot Fallback so you might want to make sure it only renders on the right triggers

#

looks like you want to check if trigger.to_state.attributes.hvac_action is idle instead of states(trigger.entity_id)

silent vector
#

I didn't even notice that. It really should be HVAC action.

#

'idle' is an HVAC action

marble jackal
#

so that's probably why it didn't return a value, as you don't provide an else

#
  temperature_deviation_temperature: >-
    {% if trigger.to_state.attributes.hvac_action == 'cooling' %} 
      {{ state_attr(trigger.entity_id, 'temperature') + 2 }} 
    {% elif trigger.to_state.attributes.hvac_action == 'heating' %} 
      {{ state_attr(trigger.entity_id, 'temperature') - 2 }} 
    {% else %} 
      {{ state_attr(trigger.entity_id, 'temperature') }}
    {% endif %}
#

why not use this?

silent vector
#

Because it's a +2 when it turns on -2 when it turns off threshold in the winter and -2 +2 in the summer.

#

So idle and heat is different from idle and cool if that makes sense. The thermostat triggers above x in the summer and below x in the winter.

marble jackal
#

Yes, the +2 and -2 are still in

#

But all the other statements returned just the temperature

silent vector
#

What you did makes sense actually whoops

#

It does the same thing but cleaner

marble jackal
#

yes, and it always returns something

#

which was not the case in your template

silent vector
#

It should have always returned something if I was tracking the HVAC action correctly as an attribute.

marble jackal
#

That's fair

silent vector
#

Then it would have had a temperature as one of them would have always been true unless it was off. But I think your way is cleaner.

#

And that's the goal

marble jackal
#

It also doesn't refer to a non-existing trigger attribute in case the trigger is Overshoot Fallback anymore, avoiding template errors.

silent vector
dark rock
#

hi guys, I'm trying to create an automation based on a template condition as explained to me before by TheFes on the linked message, but I'm not sure what I'm doing wrong.

As far as I can see, value_template is correct, but obviously is not because the automation goes to the default action everytime it's runned.

pastebin with automation code is here: https://pastebin.com/JYKxqpS0

thanks again for your help ๐Ÿ™‚

marble jackal
#

You need to put quotes around your entity_ids

#

states('sensor.whale')

#

Not: states(sensor.whale)

dark rock
#

thanks. back in your message from the other day there was no quoutes around the entity_ids, why is that? is a diferent scenario or they are just missing? (asking in order to know more about this)

marble jackal
#

There are no entity_ids in that template

#

Only references to the this variable and now()

#

Without quotes you are referring to a variable

silent vector
#

Temperature deviation worked, I used the cleaner template you sent. Now I'm just trying to figure out why the repeat is acting weird. Working 1 time and not the other times.

marble jackal
silent vector
#

Something was blocking the automaton from triggering properly. It was greyed out but I could see the time.

#

It attempted to trigger.

#

It said nothing was executed essentially

dark rock
silent vector
#

I tried to change the template it's reading for repeat and I'm getting this error. The spacing is fine. It got messed up pasting it from the editor to dpaste.
https://dpaste.org/3P1ov

marble jackal
#

You are missing a + in your last statement

#
                      dockpro_condition == '-' and states(repeat.item) | int >= 89 %} {{ states(repeat.item) | int +
                      int(dockpro_condition ~ 4) }} {% endif %}                                                    ^ THERE
silent vector
#

That's supposed to be concatenated? From the DockPro condition

marble jackal
#

No

#

You have the + in the statement above that

#

int(dockpro_condition ~ 4) creates an integer, which is either 4 or -4. You still need to add that integer to the current state

silent vector
#

That's how you told me to do it I thought over the weekend. To concatenate.
I'm confused because this works
{{ states(input_number) | int + int(mode ~ 2) }}' it will +/- if the mode is + or if it's -

marble jackal
#

Yes, and you have the + there

{{ states(input_number) | int + int(mode ~ 2) }}
                              ^ THERE
silent vector
#

That's also what I have above no?

marble jackal
#
                      dockpro_condition == '-' and states(repeat.item) | int >= 89 %} {{ states(repeat.item) | int 
                      int(dockpro_condition ~ 4) }} {% endif %}
#

This is what you have

mighty ledge
#

why are you doing the +/- with a string?

#

that' requires a bunch of casts

silent vector
#

Ohhh now I see I thought I had it already.

mighty ledge
#

{% set sign = -1 if x == '-' else +1 %}, then multiply everywhere. 100x more efficient

#

or something to that effect.

silent vector
#

That would be dockpro_condition sign 4? For example?

mighty ledge
#

how do you multiply?

#

on a calculator

silent vector
#

Well I'm not trying to multiply *

#

Oh wait is it Dockpro_condition sign ?

mighty ledge
#

{% set sign = -1 if dockpro_condition == '-' else +1 %}

#

then check for sign being > or < 0

#

then use sign in the calc

#

+ sign * 4

silent vector
#

I see. +1x4 or -1x4

mighty ledge
#

no, the sign does that

silent vector
#

No I'm saying that's what it does lol.

#

Sign is - or +

mighty ledge
#

well, you had the sign wrong as the eq would be + -1 * 4 and + +1 * 4

#

pedmas

silent vector
#

Yeah I don't use it anymore lol. So I would have never thought of this process.

mighty ledge
#

parenthesis, exponent, division, multiplication, addition, subtraction

silent vector
#

Yeah we had a McDonald's song and a dear aunt Sally to go with it in school. It just never comes to mind that pemdas can be used for this

#

I'm learning a lot from you 2. I went from using 0 variables in automations/scripts to changing everything from massive choose automations/scripts to variables everywhere.

marble jackal
#

So you could do this:

  dockpro_condition: "{{ iif(trigger.to_state.attributes.hvac_action == 'cooling', 1, -1) }}"
{{ states(repeat.item) | int + dockpro_condition * 4 }}
#

same with mode

#

and instead of dockpro_condition == '-' you can use dockpro_condition < 0

silent vector
#

With mode it would need to be different because of cooling -2 idle +2 and heating +2 idle -2

#

But it will work for the DockPro.

marble jackal
#

I meant that mode now also results in "-" or "+" which you can change to -1 or 1

#

and for temperature_deviation_mode you can then use mode * -1

#

I can see so much I would do different, and I know for sure you will see so much you will do different if you look at it again in a couple of months ๐Ÿ™‚

silent vector
#

I see. this change may fix whatever was stopping the DockPro option from working reliably. Yes for sure even just a few weeks even I am thinking of how something could become more efficient. I never used an iif until a week ago and now I'm using it in 10 places probably.

sonic nimbus
#

Hi guys.
How to put in the template a condition if my humidity sensor is above some percentage?
Im getting the correct value when I type this {{states('sensor.bathroom_thp_humidity')}}

But I want something like

action:
- if: "{{states('sensor.bathroom_thp_humidity') > 53}}"
  then: #do something
marble jackal
#

states are always strings, so you need to convert it to a number

#

"{{ states('sensor.bathroom_thp_humidity') | float(0) > 53 }}"

sonic nimbus
#

thanks @marble jackal I got it ๐Ÿ™‚

silent vector
#

Hey TheFes I had to change the temperature service call to keep the state of the input number if idle else do +/-2 but I think I messed up something with the iif

- service: climate.set_temperature
            data:
              temperature: >-
                {{ iif (trigger.to_state.attributes.hvac_action == 'idle', 'states(input_number) | int', 'states(input_number) | int +
                int(mode ~ 2)') }}
#
Result:
params:
  domain: climate
  service: set_temperature
  service_data:
    temperature: states(input_number) | int + int(mode ~ 2)
tidal heart
#

I have a template sensor producing a url. Don't seem to be able to get a tap_action to open it though. Is that not possible?

#
  tap_action:
    action: url
    url_path: >
      https://uk.flightaware.com/live/{{ states('sensor.opensky_tracked_plane')
      }}
marble jackal
#

depends on the card, most cards don't support jinja

tidal heart
#

custom:mushroom-template-card Not sure what it's based on

silent vector
#

Nevermind I need to remove the '' around the input number and else statement

#

There are some mushroom card wizards on the mushroom post.

shrewd igloo
#

Is it possible to break down (split) a value of a helper, containing a long number (or text of numbers)?

#

like using first 5 digits, then using next 5 digits...

#

something like [:5] in python

inner mesa
#

it's the same thing

#

play with it in devtools -> Templates

shrewd igloo
#

like that?
"{{ states('input_text.kitchen_zone')[:5] | int }}"

inner mesa
#

try it

#

copy and paste exactly that in devtools -> Templates

shrewd igloo
#

working, thanks

obsidian lintel
#

Trying to make a binary sensor that display off when my lux is lower than 120

```ceiling_light_state:
  friendly_name: "Ceiling Light State"
  value_template: >-
    {%- if states('sensor.0x00158d000704f8e4_illuminance_lux')|float < 120 -%}
      Off
      {%- else -%}
      On
    {%- endif -%}```

However I get an unknown

#

nvm the hyphens

#

got it

marble jackal
#

Just use

    ceiling_light_state:
      friendly_name: "Ceiling Light State"
      value_template: >-
        {{ states('sensor.0x00158d000704f8e4_illuminance_lux')|float < 120 }}
obsidian lintel
#

sick

#

way better

languid mural
#

Hello, I have a few ceiling fans that I'm trying to control with Broadlink RM pro via RF. I have learned the codes.
Can't figure out how to work with the new speed templates for the fans, I had fans more than a year ago and it worked with speeds without templates. Now it seems to have changed and a lot of outdate and confusing information.

Anyone has such config working perhaps?

gloomy notch
#

Was told to post this in here

Im trying to do very basic maths in an integration, haven't had to use YAML before, so not sure how I'm meant to do it, trying to set a helper value to calculate excess solar, since I know total usage and solar, but just not excess solar, got the automation running every 5 mins, and trying to get it to set correctly, below is the setting, its not working, but not sure what to change to make it work, I know the 2 entities are correct, its just the syntax im not sure about

data:
  value: {{ {{ sensor.inverter_zina_goodwe }} - {{ sensor.goodwe_monitoring_91000hku21b01692 }} }}
target:
  entity_id: input_number.excess_solar```
marble jackal
#

There is a lot wrong here

gloomy notch
#

I figured there would be, this is my first attempt at trying to do yaml, done everything else in the GUI so far, just saw on the input_number examples they used the {{ }} to wrap values

gloomy notch
#

Got it working with a template sensor instead, much better solution than what I was trying to do, and the docs for it showed the proper syntax as well

  - sensor:
      - name: "Solar Excess"
        unique_id: solar.excess
        unit_of_measurement: "kw"
        state: >
          {% set generation = states('sensor.inverter_zina_goodwe') | int %}
          {% set consumption = states('sensor.goodwe_monitoring_91000hku21b01692') | int %}

          {{ generation - consumption }}```
marble jackal
#

You are nesting templates, you are not using quotes inside and outside your template
You you are not getting the state of your friends entities
You are not casting the strings (which states are) to a number so you can use them in a calculation

#

You are doing that all now (took me some time to type this)

#

Well no quotes outside your template, but you are now using the multi line notation

marble jackal
gloomy notch
# marble jackal I also saw the post on Facebook, you can do it in a one liner

I'd prefer the multi-line, more explicid, but someone on facebook said it eneds up needing to use python because of the sets or something, need to look up any performance implications etc, would rather figure it out now, im sure I'll end up using many more template sensors etc over time, only going to add more and more automations and calculations, I'm about to add 30+ devices in the next couple months

marble jackal
#
template:
  - sensor:
      - name: "Solar Excess"
        unique_id: solar.excess
        unit_of_measurement: "kw"
        state: >
          {{ states('sensor.inverter_zina_goodwe') | int - states('sensor.goodwe_monitoring_91000hku21b01692') | int }}
#

That's not true, it's all Jinja

#

I don't think it has any effect on performance, and it increases readability

gloomy notch
#

I think the multi-line is more readable, the extra-long line redability changes to much with line length

marble jackal
#

๐Ÿ‘

silent vector
#

Any idea why this isn't continuing past the input number set value when it is null? I added continue on error for this reason but the script is stopping.
https://dpaste.org/pVY4h

silent vector
#

Stopped because an error was encountered at June 22, 2022, 5:53:11 AM (runtime: 0.09 seconds) It stops on the climate service call. Because the input number failed because it was ''

marble jackal
#

Put the whole service call in an if-then so it only runs with a valid value

silent vector
#

Didn't think of that, that's a good idea thank you.

acoustic swift
#

Hi, I'm trying to bold text in notification template that's part of my automation. Tried using single asterisk () and triple (**) but with no success. Is there some way other way to do it?

mighty ledge
#

depends on whatever you're sending the notification to and whatever langauge it accepts for formatting

acoustic swift
#

Using Gmail

#

I've tried it in the development tab but it doesn't format their either

mighty ledge
#

right, but the development tab doesn't do formatting

#

Gmail excepts HTML, so that's how you'll have to make things bold.

acoustic swift
#

All right, I'll give that a try

mighty ledge
acoustic swift
#

Is it possible to bold text in push notifications from HA?

mighty ledge
#

pretty sure that also accepts html

acoustic swift
#

Doesn't seem to work

#

Tried both <strong> and <b>, but no luck

mighty ledge
#

did you include the ending characters?

acoustic swift
#

Yup. Also tried including <hmtl></html> and <body></body>

mighty ledge
#

Then it may not be possible

acoustic swift
#

All right, thanks anyway

rose scroll
#

Since the template fans now return the fan speeds as a percentage in range [0,100], you may need to convert from the percentage to your numerical fan speeds

buoyant sapphire
#

i got a helper and i am trying to check if the date in my helper is todays date.

can someone help me get this here right, so that is returns true/false:

{{ {{ states("input_datetime.staubilastrunburo")[:10] }} == 
{{ now() }} }}
inner mesa
#

You have way too many {{ }}

#

Depends on how exact you want to be (include seconds? no?)

{{ (states('input_datetime.date_test')|as_datetime).replace(second=0) }}
{{ now().replace(microsecond=0).replace(second=0).replace(tzinfo=none) }}
{{ (states('input_datetime.date_test')|as_datetime).replace(second=0) == now().replace(microsecond=0).replace(second=0).replace(tzinfo=none) }}
marble jackal
#

In his post he mentions date:

{{ as_local(as_datetime(states('input_datetime.test'))).date() == now().date() }}
inner mesa
#

oh, nevermind :). Much easier

plucky heron
#

{% if trigger.idx == 1 or trigger.idx == 2%} camera.doorbell_main {% elif trigger.idx == 3%} camera.garage_camera {% endif %}

#

is there anything wrong with that code?

#

i keep getting an invalid entity id error

inner mesa
#

You have no 'else' case, so it could be blank

#

Otherwise, need to see the rest

plucky heron
#

it's the first action calling camera snapshot

#

if i remove the trigger idx stuff the entities work

#

seems like the if statement is causing the problem

#

i replaced all the references to trigger.idx with numbers and the code works.

languid mural
inner mesa
#

Was just going to ask that ๐Ÿ™‚

marble jackal
#

Just checked in a trace of my own

plucky heron
#

was wondering about that, but the code still doesn't work

marble jackal
#

Was not sure myself

inner mesa
#

somebody should update the docs

marble jackal
#

If you give the triggers the entity_id as trigger id, you can just use:

target:
  entity_id: "{{ trigger.id }}"
#

Or a trigger variable (as they already have a trigger id)

#
trigger:
  - platform: something
    variables:
      snapshot_target: camera.doorbell_main
plucky heron
#

I will try your suggestions, but that simple if statement should work right?

marble jackal
#

Yes, with trigger.idx 0 to 2

inner mesa
#

And maybe use an 'else' as the last bit

marble jackal
#

And a space between 1 and %} I guess ( where you had 2%}

#

And also in the other statement

#

Where you had 3%}

plucky heron
#

lol... yeah it was the spaces

#

thanks!

marble jackal
#
{% if trigger.idx <= 1 %}
     camera.doorbell_main
    {% else %}
     camera.garage_camera
    {% endif %}
plucky heron
#

is there an editor or something to catch syntax errors like that?

marble jackal
#

devtools > templates

#

But that is tricky with trigger variables. But if will error on syntax errors before it will error on the missing variable

#

You can always define it for testing purposes:
{% set trigger = { 'idx': 1 } %}

plucky heron
#

ahh nice. will definately use that

inner mesa
#

kinda dumb that the parser trips on that, considering that %} should be readily identifiable

#

I wonder if you can use that in a string ๐Ÿ™‚

paper hazel
#

I'm trying to get my head around this and why this is not working```
{% if is_state('input_select.speaker', 'Kitchen') %}
{% set active_speaker = 'media_player.kitchen_speaker_cast' %}
{% elif is_state('input_select.speaker', 'Living Room') %}
{% set active_speaker = 'media_player.living_room_speaker_cast' %}
{% endif %}

Test: {{ is_state('{{active_speaker}}', 'idle') }}

#

I have been testing this on the GUI under templates

inner mesa
#

you're using quotes around the variable

#

which makes it a string

#

and you're also using is_state() incorrectly at the end

#

look at the others...

paper hazel
#

That was an accident - Fixing it quickly.

paper hazel
#

Or am I looking at the wrong quotes?

#
{{ is_state({{active_speaker}}, 'idle') }}

Error to: TemplateSyntaxError: expected token ':', got '}'
#

Doh! Seems I was trying to over complicate it - Thank you for pointing me in the right direction.```
{{ is_state(active_speaker, 'off') }}

inner mesa
#

now you're nesting templates

#

yes

paper hazel
#

Just want to thank everyone that has assisted me on here - Without the help I received here, my HA instance will not be half as awesome as it it. Much appreciated!

hollow tide
#

Is there any way I can easily make my items in the sidebar permanently ordered a certain way without having to manually do it for every device?

#

I was reading so far the only thing I saw was making a custom sidebar but that seems kind of excessive for just wanting to make sure the side bar items stay in a certain order

rose scroll
rose scroll
# languid mural Low, Med, High.

Then something like this may work:

{% if target_fan_power == false %}
  Off
{% elif target_fan_speed | int(0) == 0 %}
  Off
{% elif target_fan_speed | int(0) <= 33 %}
  Low
{% elif target_fan_speed | int(0) <= 66 %}
  Med
{% else %}
  High
{% endif %}
#

Idea is to map the percentages coming out of the fan speed to your commands saved in Broadlink.

nimble copper
#

Does anyone have an elegant / oneline way of comapring if a datetime is today. i.e. 2022-06-23 00:00:00 is today?

#

This is what I have. Happy for improvements to be suggested:
{{ now().date() | string == strptime(states('sensor.next_dry_laundry_day'), '%A %d %B %Y')|as_timestamp|timestamp_custom('%Y-%m-%d') }}

The original sensory state example is Thursday 23 June 2022 It's a string rather than a datetime object or UNIX timestamp.

marble jackal
#

changed it (jinja edit ๐Ÿ˜‰)

nimble copper
#

That, works now.

sacred sparrow
#

what would be the best way to turn this into a template:

trigger:
  - platform: time
    at: '05:00:00'
condition: []
action:
  - service: input_number.set_value
    data:
      value: '{{ states(''sensor.outside_home_thermometer_temperature'') }}'
    entity_id: input_number.outside_min_temp

I want it to display the temp at of that sensor at 5am.

#

then I only want it to change if temp drops below that 5am that day

marble jackal
sacred sparrow
#

well if at 5am the temperature is 8 and then sometime that day it goes to 7 I want it to change the template state to 7 as its lower than the temp at 5am

nimble copper
#

Is there a way to get strptime to work using map on a list?

I.e.

{{ state_attr('sensor.next_dry_laundry_day', 'forecast')[1:]
| map('strptime', '%A %d %B %Y')
| list }}
#

Jinja throws an error TemplateRuntimeError: No filter named 'strptime'.

marble jackal
#
trigger:
  - platform: time
    at: '05:00:00'
  - platform: numeric_state
    entity_id: sensor.outside_home_thermometer_temperature
    below: input_number.outside_min_temp
marble jackal
nimble copper
#

Or is there a way to use map to remove the last 5 characters of every item in the list?

marble jackal
#

Same way I guess ๐Ÿ™‚

sacred sparrow
#

is there a way to make it into a template instead of a automation?

marble jackal
#

Create a trigger based template sensor using the same triggers?

buoyant sapphire
#

i guess there is a datatype problem, but why is this returning false, even thou both is 2022-06-23

{{ states("input_datetime.staubilastruneingang")[:10] ==  now().date() }}
marble jackal
#

I already answered that yesterday

buoyant sapphire
#

ah. didnt see. let me check. sry

marble jackal
buoyant sapphire
#

how can i combine two statements, each of them returning true/false on their own into one statement, so that if at least one returns true, the entire statement returns true?

example:
statement1: is it raining? (yes)
statement2: is today sunday? (no)

what i am looking for statement: is today sunday, or is it raining (yes)

marble jackal
#

That's very ugly indeed

sacred sparrow
#
    - platform: time
      at: '05:00:00'
    - platform: numeric_state
      entity_id: sensor.outside_home_thermometer_temperature
  sensor:
    - name: "Outside Min Temp"
      availability: "{{ not is_state('sensor.outside_home_feels_like_temperature', 'unavailable') or is_state('sensor.outside_home_feels_like_temperature', 'unknown') }}"
      state: ???

what would I make the state of my sensor to show the min temp of my sensor? I want to remove the need of 'input_number.outside_min_temp' entirely

#

I can't find many template examples to figure this out

#
- 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"
      availability: "{{ not is_state('sensor.outside_home_feels_like_temperature', 'unavailable') or is_state('sensor.outside_home_feels_like_temperature', 'unknown') }}"
      state: '{{ states(''sensor.outside_home_thermometer_temperature'') }}'
marble jackal
sacred sparrow
#

can I use the templates entity inside the template?

#

below: sensor.outside_min_temp

marble jackal
#

yes, for the trigger that doesn't matter

marble jackal
#

assuming you have no other input_datetimes with that naming convention

silent vector
#

Is there a trigger or a template that detects when the automations are reloaded?

silent vector
#

Perfect.

thorny snow
#

how do you do an or opeartor in a template (i.e. or, ||, etc?

#

nvm i assume its just the word or since i can use the word and

marble jackal
#

Correct

thorny snow
#

trying to fix this janky count of lights on :/ its showing 3 extra entities which means 0 lights off echoes -3 etc

wanton jasper
#

Hello all, I am trying to set the new badges on my mushroom cards but I cant seem to get the template to work for a reading of a sensor. I built a fart sensor for the bathroom and I want to set a badge if there is a high TVOC levels. This is what I have but its not setting the badge and the sensor is over 1. Will adjust after its working.
{% if is_state('binary_sensor.basement_bath_pir_sensor', 'on') %} mdi:paper-roll {% elif is_state('binary_sensor.basement_bath_pir_sensor', 'off') %} mdi:cancel {% elif is_state('sensor.basement_bath_tvoc', | float > '1.0' ) %} mdi:scent {% else %} {% endif %}

marble jackal
#

{% elif is_state('sensor.basement_bath_tvoc', | float > '1.0' ) %}
That part is not correct, use:
{% elif states('sensor.basement_bath_tvoc') | float > 1 %}

marble jackal
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.

thorny snow
#

ok i have been banging on this for a while i need some tips... I want to count how many lights are on but i do not want to count the lightswitches - I only want bulbs (Hue)

I have tried this:
{{ states.light | selectattr('state', 'equalto', 'on') | list | count }}
but that counts the switches too and anything in the light domain.

#

since each light has a unique name i thought maybe i could check each one and increment a count but that is dumb and messy

#

nvm got it working.... never fails you spend hours then after you ask you figure it out

winter pilot
#

I'm trying to create a variable so I can add it and get the result but it's not working. Where did I go wrong?
{% if loop.last %}
{% set bca = (loop.index|int) %}{% endif %}
{% endfor %}
{{bca + bcb}}

#

i'm testing in dev tools in order to get it working before putting it into action.

silent seal
#

You're missing at least the start of the for loop...

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.

winter pilot
silent seal
#

Uhhh, that's interesting

#

Why are you combining the for loop and the if?

winter pilot
#

I only want to get the count if all criteria is met. I was building as I went so it could also be two ideas merging into one.

#

This will be used for a "status report" that gets fed to Alexa for devices that have low battery conditions

silent seal
#

Well, tip 1: break things down into smaller chunks. You're repeating yourself with item.name | lower, and a good rule for programming is DRY (don't repeat yourself)

#

Did you look at using something like this?
states.sensor | selectattr('attributes.device_class', 'eq', 'battery') | selectattr('state', '>=', '90')
That's just a snippet, but it'll grab all the batteries for you pretty neatly

winter pilot
#

you'll have to excuse me, the HA platform is new to me so I am learning (and googling) as I go... I'm used to other languages. if I remove that, the code fails (item.name....) so not sure what I would put in place of or the best optimization for the code.

silent seal
#

Well, set a variable ๐Ÿ™‚

winter pilot
#

well, honestly, the code I am using I found and it worked so I stopped googling lol.

silent barnBOT
silent seal
#

Here's a small template which might get you off to a better start:

silent barnBOT
#

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

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

so, that errored out when I pasted it hah.

#

TemplateSyntaxError: unexpected char '\' at 40

silent seal
#

Well, this is a quick attempt at simplifying what you currently have:

{% for item in states.binary_sensor %}
  {% set item_name = item.name | lower %}
  {% if (
    "battery" in item_name
    and not "voltage" in item_name
...
    and not "pixel" in item_name
    and "off" in item.state | lower )%}
    {{ (item.name+' '+item.state) |regex_replace(find=': Low Battery Level', replace='', ignorecase=true) |regex_replace(find="'", replace='', ignorecase=true) |regex_replace(find=",", replace='', ignorecase=true)}}
    {% if loop.last %}
      {% set bca = (loop.index|int) %}
    {% endif %}
  {% endif %}
{% endfor %}
#

But you still have a lot of repetition in there, what are you trying to achieve?

winter pilot
#

I get what you did. For some reason it added massive space between the items. I am essentially trying to list all sensors and binary sensors that indicate a low battery condition. I want to count each of them, (IE: 3 sensors and 2 binary sensors) and then add the two values together to get, in that case, 5 devices. Then i'll pass that to the Alexa notify service to tell me about it once a condition I set is met.

silent seal
#
{% set battery_sensors = states.sensor | selectattr('attributes.device_class', 'defined')  | selectattr('attributes.device_class', 'eq', 'battery') | map(attribute='entity_id') | list %}
{{ battery_sensors }}

That's a list of the entity IDs of battery sensors.
You could add in rejectattr('state', 'in', ['unavailable', 'unknown', 'discharging', '100']) | after selecting the battery, and a further filter for battery < your_threshold_here

#

Then after all that you could instead have {{ battery_sensors | join(', ') }} which will do a nice comma separated list.

winter pilot
#

Well, that is definitely cleaner code haha. I'm looking at it trying to get that filter in place.

silent seal
#

Do it before the map, the map takes your objects and changes them into strings of entity_ids (have a play to see what else you can return there too)

winter pilot
#

For the numerical filter < 25, is it as simple as '<25' because that feels wrong on all levels to me hah

silent seal
#

It's a bit tricky to do in a one liner, because the state is actually a string

#
{% set battery_sensors = states.sensor | selectattr('attributes.device_class', 'defined')  | selectattr('attributes.device_class', 'eq', 'battery') | rejectattr('state', 'in', ['unavailable', 'unknown', 'discharging', '100']) | sort(attribute='state') | map(attribute='entity_id') | list %}
{% set low_battery = namespace(sensors=[]) %}
{% for battery in  battery_sensors %}
  {% if (states(battery) | int) < 30 %}
    {% set low_battery.sensors = low_battery.sensors + [state_attr(battery, 'friendly_name') ~': '~states(battery)~'%'] %}
  {% endif %}
{% endfor %}
{{ low_battery.sensors | join(', ') }}
#

That's probably what I'd do. The array creation is a bit of a hack, but it works

#

Updated to include the battery %, and sort them lowest to highest (most urgent first)

winter pilot
#

oh nice. thanks for the help so far, btw. I think I almost have it.. I just have to get the counting in place but I have an idea on that already.

silent seal
#

You have an array, use the | length filter on it ๐Ÿ˜‰

#

{{ low_battery.sensors | length }} will tell you how many items

winter pilot
#

I was count to "|count" it lol

#

*was going to

#

my brain and fingers are beginning to disconnect already

silent seal
#

I'm not sure why the sort isn't quite working for me, everything is great, 1% up to 27%, and then an 8% ๐Ÿค”

winter pilot
#

haha. story of my life sometimes.

silent seal
#

But as I have 6 in order, I'll blame the IKEA integration that I've almost done away with for now ๐Ÿ˜‚

winter pilot
#

so I added:
{% set bsa = low_battery.sensors | count %}

then duplicated what you did for binary sensors (adjusted accordingly)
then added
{{ low_bbattery.sensors | count }}
{% set bsb = low_bbattery.sensors | count %}
{{ bsa+bsb }}

#

haha. You had to compile the IKEA integration yourself, right?

#

๐Ÿ˜›

silent seal
#

Nope. I'm replacing it with Zigbee2MQTT. Much more stable

winter pilot
#

'twas an Ikea joke.

silent seal
#

Though another programming trick: variable names are free, and descriptive ones help avoid headaches and confusion ๐Ÿ˜‰

winter pilot
#

oh I know.. I am also lazy too so there is that. lol

#

find and replace is a great friend of mine.

#

if it's something I can do, how can I comment out code lines in templates.

silent seal
#

In the YAML file you can use # at the beginning of the line

winter pilot
#

what about the actual template, like in the dev tools template editor.

silent seal
#

In dev tools/jinja wrap your line with {# #}

winter pilot
#

of course. I tried everything BUT that...

stuck kelp
#

I swear this used to work but it doesn't any more:

{{ states.person | select('eq','home') | list | count }}

It returns and empty list though someone is home

#

I searched this channel and this similar one does work:

{{ states.person | 
  selectattr('state', 'eq', 'home') | 
  map(attribute='name') | 
  list | count
}}

Just finding it odd :/

inner mesa
#

I don't see how the first one would have ever worked

stuck kelp
#

Looking in the doco I can't even see a function called select()

inner mesa
#

You don't need the map() call at all

#

select() is a filter

stuck kelp
#

Ah yeah, I see why the map() isn't needed . List size is the same regardless

marble jackal
hexed wing
#

(as it becomes: "8" > "2" == True)

#

a great gotcha in programming; everyone will hit that one once ๐Ÿ˜„

marble jackal
#

would have worked with leading zeroes, or if there was a way to cast values to another type while using filters. I know petro was working on that for select and select_attr