#templates-archived

1 messages Β· Page 29 of 1

mighty ledge
#

Then remove the presets

#

You don't really have any control on what homekit does other than exposing or not exposing entities via HA

latent geyser
#

Ok so I found a workaround. Voice commands were getting confused by the five switches all with the same name. I was able to ungroup the switches in HomeKit, rename the redundant ones (they were Called Off, Medium, Low, High) and rename them all to 'Ignore Me' and remove them from the Home View. That leaves only the fan, which responds as expected, although it seems HomeKit has its own ideas for what low medium and high mean, but I can deal with that.

mighty ledge
marble jackal
#

@mighty ledge what does something like {% else: %} do? So the colon? I saw something in the docs about parsing all as a block, but didn't really understand what that meant

mighty ledge
#

I'm skeptical it exists

#

where did you see that?

mighty ledge
#

but else: isn't something I would expect to see in jinja

#

oh

#

I found a mention of this

#

it does nothing

#

so it's only for readability if you're used to python

#

in python...

for i in range(4):
    i
#

is the equivalent

marble jackal
#

That's in the docs

#

Whoops, you linked to that

#

Ah okay

mighty ledge
#

yeah the word block refers to this {% the code here %}

#

but it's basically saying the normal python rules w/ colons can be used

#

optionally

civic cargo
#

I have an air purifier with 1 preset mode ("sleep"), and 3 speeds (33%, 66%, 100%)
Rather than needing to perform a special action to turn the fan to "sleep", I'd like the fan slider on my dashboard to set to these 4 options as if they were all percentages.

25% on slider = sleep preset 50% on slider = previously 33% 75% on slider = previouslly 66% 100% on slider = previously 100%

I've attempted to use a template fan (https://www.home-assistant.io/integrations/fan.template/), but I'm struggling to find the right combination of letters despite a handful of attempts

I'm hoping for some suggestions on how I could get this done πŸ™‚

Latest template attempt:
http://pastie.org/p/6VK1sgcAbtzSN0xnKGtCKA

hazy charm
#

Hello
I am looking to make a template to set the value in seconds in a timer helper from the value of an entity
Can anyone hint me in the right direction of a solution being it documentation, forum posts or any other form of guidance ?

civic cargo
hazy charm
#

@civic cargo
I was hoping to use
https://github.com/rianadon/timer-bar-card
and i need to set the value of a timer helper to the value of an entity to show a "progress bar" of the started progress which will have a variable time

civic cargo
#

@hazy charm
I see
I think you could use the number box card to set it, and and timer bar card to display it

I could be mistaken though

mighty ledge
hazy charm
#

i will definitively give it a try, did not know cards could be used for that

mighty ledge
#

i.e. if the percentage is 25%, then choose to run an action that sets the sleep preset.

#

if the percentage is 50, set the percentage to 33, if the percentage is 75 set to 66, etc

#

you don't need preset modes at all for the template fan either

#

and your percentage_template needs to return 0, 25, 50, 75 or 100 based on the state of fan.air_purifier

#

i.e. if the preset mode is sleep, return 25, if it's off return 0, if it's on return 50 if it's 33, 75 if it's 66, and 100 if it's 100

civic cargo
#

testing, please hold

civic cargo
#

That is to say, I think I understand the principal of what you're suggesting, but execution is still eluding me

hazy charm
civic cargo
hazy charm
civic cargo
hazy charm
mighty ledge
#

So you can write a script and call it or write the full script in that field

plush pewter
#

how do i get the enitity the name of the highest valued entity ?
{% set mylist = states("counter.csgo_thomas_deagle")|int,
states("counter.csgo_mikkel_deagle")|int,
states("counter.csgo_oliver_deagle")|int,
states("counter.csgo_holst_deagle")|int,
states("counter.csgo_max_deagle")|int %}
{{mylist|max }}

marble jackal
#

Wth a namespace and for loop, as states are strings and you can't properly sort them in a one line template

sonic sand
#

hi TheFes,
The fish tank just fed the fishes but I still got unknown at unknown notification.
https://imgur.com/xM3i5zr
automation template
http://pastie.org/p/6JO0joKVn2Uk0S6ljjoW7O
logs showing an error

Logger: homeassistant.helpers.template_entity
Source: helpers/template_entity.py:329
First occurred: 10:29:57 PM (1 occurrences)
Last logged: 10:29:57 PM

TemplateError('ValueError: Template error: timestamp_local got invalid input '2023-02-13 20:29:57+00:00' when rendering template '{%- if state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1') -%} {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %} {{ as_datetime(feed_record.timestamp)|timestamp_local }} {%- endif -%}' but no default was specified') while processing template 'Template("{%- if state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1') -%} {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %} {{ as_datetime(feed_record.timestamp)|timestamp_local }} {%- endif -%}")' for attribute 'timestamp' in entity 'binary_sensor.feed_record_result'
sacred sparrow
#

{% if trigger.platform == 'state' or states('device_tracker.delonghi_primadonna') == 'not_home' %} how would I make this to only trigger if not_home is for 5 minutes or greater?

inner mesa
#

Your coffee machine gets around

#

Why not just make that the trigger?

marble jackal
#

@sonic sand that error is not related to the automation

#

It looks like the old code for the template sensor

#

for the unknown thing a trace (you can download the json) will help

sonic sand
marble jackal
#

in settings > automations > select your automation > traces (top right)

#

then make sure to select a trace which has the wrong message

#

and then you can download the json file with the button in the top right

sonic sand
marble jackal
#

okay, it triggers quite often..

sonic sand
#

Is there a way to get the 6th trace?

marble jackal
#

nope

sonic sand
#

yeah.. my internet is bad here

sacred sparrow
sonic sand
sonic sand
marble jackal
#

yes, but you were still receiving notifications with unkown. This should solve that

#

but the error you posted was not related to you receiving messages with unknown

#

I don't understand the use of that template sensor with the group, it will always show you X/X

sonic sand
#

perfect

#

well I wanted to show the total amount of tempature sensors and how many of them are showing something and not on OFF state or Unknown.

marble jackal
#

but that is not what that template does

sonic sand
#

I know, I couldn't find a way to do it so I used that...

marble jackal
#

the parts before the / and after will always be the same number

sonic sand
#

yeah

marble jackal
#

not sure why Watchman complains about it though

sonic sand
#

very annoying to see that

marble jackal
#

but that is not related to templates

#

log an issue in the Watchman Github maybe

sonic sand
#

Okay, thanks dude

#

my fishes are loving you πŸ˜‚

marble jackal
#

If you start using more complicating templates using partial matches of entities, you will get more Watchman logs

sonic sand
#

As an expert does your System -> Logs are empty all the time? or it pops sometimes an error or two

ruby vault
#

so, I am trying to make a template binary sensor with attributes of the time we left and entered a zone.

  • trigger:
    • platform: state
      entity_id: person.jurgen
      binary_sensor:
    • name: "Jurgen at School"
      state: "{{ is_state('person.jurgen', 'School') }}"
      attributes:
      arrived: >-
      {% if (trigger.to_state.state == "School") or (trigger.to_state.state == "school") %}
      {{ now() }}
      {% endif %}
      left: >-
      {% if (trigger.from_state.state == "School") or (trigger.from_state.state == "school") %}
      {{ now() }}
      {% endif %}

Now, the attributes do not work. They are empty, do the trigger states like in an automation work like this? https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-numbers-selects-and-sensors This doco implied to me that it would, but why do I get empty attributes? The binary_sensor state works.

ruby vault
#

right. Interesting

#

Thanks

mighty ledge
#

keep in mind that if you use an ifstament like that, when the statement fails, it will be empty

#

so you need to fall back on the previous timestamp

#

using this.attributes.arrived when that happens

#

but you also need to make sure that all of that exists

#

becuase it won't at start up

#

basically, what you're trying to do isn't going to be simple if you aren't a templater

ruby vault
#

yeah, I hear you. Thanks

sonic sand
stuck remnant
#

can this be written to turn on if the state of the sound sensor has been above 150db for more than 30secs instead of the way it is currently?

      - platform: state
        entity_id: sensor.samsung_j3_ipcam_sound
    binary_sensor:
      - name: "Bathroom sound"
        state: >
          {{ (now() - states.sensor.samsung_j3_ipcam_sound.last_changed).seconds < 5 }}```
inner mesa
#

Assuming that it started below that, just use a numeric_state trigger

stuck remnant
#
  - trigger:
      - platform: numeric_state
        entity_id: sensor.samsung_j3_ipcam_sound
        above: 150
    binary_sensor:
      - name: "Bathroom sound"
        state: >
          {{ (now() - states.sensor.samsung_j3_ipcam_sound.last_changed).seconds < 30 }}```
#

is this it?

inner mesa
#

Just use for:

stuck remnant
#
      - platform: numeric_state
        entity_id: sensor.samsung_j3_ipcam_sound
        above: 150
        for: "00:00:30"
    binary_sensor:
      - name: "Bathroom sound"
        state: >
          {{ (now() - states.sensor.samsung_j3_ipcam_sound.last_changed).seconds < 30 }}```
#

like this?

inner mesa
#

state template REQUIRED

stuck remnant
#

is good now?

inner mesa
#

No

stuck remnant
#

😦

inner mesa
#

What does that template evaluate to?

stuck remnant
#

turns the sensor on if the sound sensor changed states in the last 30s

inner mesa
#

You already did that with the for:

stuck remnant
#

that's why I said to take out the template

inner mesa
#

Which is not allowed

stuck remnant
#

yeah

#

so I don't know how to type it

inner mesa
#

Add a trigger for below 150 and use {{ trigger.to_state.state|float > 150 }} as the state

stuck remnant
#

but wouldn't that trigger it when it goes below that threshold?

inner mesa
#

Or use this:

delay_on time (optional)

#

Do you ever want it to turn off?

stuck remnant
#

yeah

inner mesa
#

Then

#

Don't use a trigger at all, use a state template of {{ states('sensor.whatever')|float > 150 }}, and use delay_on: '00:00:30'

stuck remnant
#

oh okay

#

thanks!

inner mesa
#

There are many ways to do it, but I think that's the easiest

marble jackal
sonic sand
acoustic arch
#

{{ now() >= alarm - timedelta(minutes=1) if alarm else false }}
This is the shorthand of what?
What does if alarm mean?

#

if exists? if true?

marble jackal
#

if is is anything besides falsely

#

So not none, false, "", 0, [], {} and others I missed

floral shuttle
#

using a template like value_template: > {{'Groen' in value_json.rss.channel.item[12].description}} returns True, when used in a regular rest sensor, but 'off' in a binary rest sensor...

#

template is True, so should be 'on' for the binary rest ....?

#
  - platform: rest
    unique_id: platform_rest_knmi_waarschuwingen_binary
    resource: https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml
    name: Platform rest knmi waarschuwingen
    value_template: >
      {{'Groen' in value_json.rss.channel.item[12].description}}
sensor:
  - platform: rest
    unique_id: platform_rest_knmi_waarschuwingen
    resource: https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml
    name: Platform rest knmi waarschuwingen
    value_template: >
      {{'Groen' in value_json.rss.channel.item[12].description}}
marble jackal
#

You are not creating a binary_sensor wiht the bottom one, you are creating a sensor

#

and a sensor will not convert true to on

marble jackal
#

oh wait

#

now I see it

floral shuttle
#

the binary sensor should have converted the True of the template to 'on'

marble jackal
#

True vs off

#

yes, that πŸ™‚

#

That is indeed very strange

#

BTW I would turn it around, make the sensor on when Groen is not in de description, but that's not the question here

floral shuttle
#

using a regular binary:```

  • binary_sensor:

    • name: KNMI waarschuwing Noord-Brabant
      unique_id: knmi_waarschuwing_nb_binary
      state: >
      {{'Code Groen' in state_attr('sensor.knmi_waarschuwingen_nb','description')}}
#

correctly

floral shuttle
marble jackal
#

What if you do something like this?
{{ 1 if 'Groen' in value_json.rss.channel.item[12].description else 0 }}

#

just to test if that works

#

if it does, it looks like a bug in the restful binary sensor to me

floral shuttle
#

will file an issue

torpid hare
#

I have a simple dht22 sensor, that I'm trying to get into HA, but I'm overseeing something...

{"humidity":26.4,"temperature":21.3}```

and:
```mqtt:
  sensor:
    - name: "DHT22 Temperature"
      state_topic: "neo2/dht22"
      unit_of_measurement: "Β°C"
      value_template: "{{ value_json.temperature }}"```

and yet still: 
`ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'value_json' is undefined when rendering '{{ value_json.temperature }}'`

What am I missing??
mighty ledge
#

I think you screwed something up with your unique_id

#

and you're looking at the wrong entity

#

your unique_id is platform_rest_knmi_waarschuwingen_binary yet the entity you're creating is binary_sensor.platform_rest_knmi_waarschuwingen and that does not jive with the autogenerated entity_id's

#

Although I do see the name there

floral shuttle
#

yeah, I did edit those manually, because there are a few related restful sensors around. to be sure, I deleted those, restarted and recreated them

mighty ledge
#

well, I don't see how this can be a bug

#

because the test cases test this situation

#

and the code checks for 'true', 'on', 'open', and 'yes'

#

but it first attempts to assign it as a bool

floral shuttle
#

yes, that is what was confusing me. given the fact my unique_id is in fact unique, there cant be any system confusion cant there?

mighty ledge
#

so the rest data you're using is XML, are you sure you aren't running into using an incorrect key issue?

marble jackal
#

If the result of the sensor with the same template is True, the binary sensor should be on and not off
That's why I thought it might be a bug somewhere

mighty ledge
#

Looking at the code, I don't see how it can be

#

The only possibility that I see for an error is if the rest backend does not have data

#
    def _update_from_rest_data(self) -> None:
        """Update state from the rest data."""
        if self.rest.data is None:
            self._attr_is_on = False
            return

        response = self.rest.data

        if self._value_template is not None:
            response = self._value_template.async_render_with_possible_json_value(
                self.rest.data, False
            )

        try:
            self._attr_is_on = bool(int(response))
        except ValueError:
            self._attr_is_on = {
                "true": True,
                "on": True,
                "open": True,
                "yes": True,
            }.get(response.lower(), False)
#

if there's no rest data, it will return false always

#

otherwise if there is rest data, it attempts to make the response a boolean. If that fails, it takes the lowered string result and see's if it's `true', 'on', 'open', 'yes'.

#

if it is, it returns true, else false

#

pretty simple logic

#

so the only screwup that can happen is self.rest.data not being populated.

marble jackal
#

ah yes, it uses lower

#

I thought it might be that the result was "True" like in the (non binary) sensor, but that is coverted to lowercase

#

so that also can't be the issue

#

I kinda understand this code πŸ™‚

#

It converts things like true, false, "1" to an integer, and then to a boolean value, if that results in true it turns the binary_sensor on, if it results in an error, it checks for the strings in the dict if it can match one of those (in lowercase) and otherwise returns false

mighty ledge
#

I'm 90% sure you could contribute to core

#

there are some principles you'd need to learn but it wouldn't be too hard

marble jackal
#

still looking where to start to learn those principles, but currently I'm already contributing to the intents repo πŸ™‚

mighty ledge
#

you already understand object orientation, the next thing you'd need to learn is object scope when coding

#

are you using alexa for intents?

marble jackal
#

no, for the new Assist integration

#

well, the rebranded conversation integration πŸ˜‰

mighty ledge
#

ah

marble jackal
#

But I will find some time to learn python (at least for HA) somewhere in the future

obtuse zephyr
mighty ledge
#

Also, there are no test cases that verify XML works

#

Then again, the binary sensor makes no mentions that it will work with XML where the rest sensor does

marble jackal
#

Okay, so not a bug, but a missing feature compared to the rest sensor πŸ™‚

mighty ledge
#

That it appears to be

#

However that would be a bug for the rest integration

#

however that doesn't mention XML either

#

well, actually, the rest integration handles that

#

and it does work with xml

#

nope, I'm wrong, that should also fail

#

Seems like the rest update coordinator should handle the xml to json instead of it being handled in the sensor

#

then it would fix binary sensors

#

without making changes to binary sensors]

floral shuttle
#

in any case.... we have an issue πŸ˜‰ btw, commenting the complete platform: rest sensor does Not take out the entity...

mighty ledge
#

that doesn't mean it will be fixed if xml wasn't intended to be used w/ xml

#

just keep that in mind

#

taht falls in line w/ feature requests

floral shuttle
#

its remains in the states overview, until I restart

mighty ledge
#

not sure what you mean by that

floral shuttle
#
sensor:
#   - platform: rest
#     unique_id: platform_rest_knmi_waarschuwingen
#     resource: https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml
#     name: Platform rest knmi waarschuwingen
#     value_template: >
#       {{value_json.rss.channel.item[12].description}}
#

still shows:

mighty ledge
#

becauyse you have a unique_id

#

and it's restoring the state

floral shuttle
#

but I can not delete it

mighty ledge
#

restart

floral shuttle
#

thats what I said.... only on restart

mighty ledge
#

yes, when you reload, HA doesn't know that the entity no longer exists

floral shuttle
#

also without unique_id. If one does not use unique_id, it constantly adds new entities..... _2, _3, _4 etc

mighty ledge
#

that's a caveat of using YAML reloads & unique_id

#

it's like this for all YAML reloading & the use of unique_id

#

unique_id registers the entity in the entity registry, so now the system see's it. The system does not know it comes from yaml

floral shuttle
#

on template: we can simply delete the entity

mighty ledge
#

so when you reload, the system is happy

#

but it doesn't k now that the yaml has been removed

#

until you restart

#

template is the same way when you use unique_id

floral shuttle
#

now that I have your eyes: we can use value_template: > {{value_json.rss.channel.item[12].description}} in the value_template on the platform: rest, but we can Not do that using the rest: config

#

what could be the reason for that?

mighty ledge
#

not sure what you mean

#

is this for binary sensor again?

floral shuttle
#

no, for regular. see eg:```

  • resource: https://cdn.knmi.nl/knmi/xml/rss/rss_KNMIwaarschuwingen.xml
    scan_interval: 900

    sensor:

    • unique_id: knmi_waarschuwingen_basis
      name: KNMI waarschuwingen basis
      value_template: >
      {{now()}}
      json_attributes_path: "$.rss.channel.item[0]"
      json_attributes:
      • title
      • category
      • description
      • enclosure
      • link
      • guid
      • pubDate
      • author```
#

if I replace the value_template with eg value_json.rss.channel.item[0].description it returns unknown

mighty ledge
#

So you're putting that in the sensor: field for the rest integration?

#

thanks

#

you can turn on debugging for the rest integration to see where it's going wrong

#

the sensor platform has a ton of debugging

#

lines

floral shuttle
#

there simply is no syntax for that template I can find to give something useful...

mighty ledge
#

are you following the rules for XML when getting information out?

floral shuttle
#

uhm..... dont know...

mighty ledge
#

IIRC (I don't have them memorized) You need to selectively use $ with attributes

#

xml is dumb

#

so it forces us to do different things to convert the values to json

floral shuttle
#

given the fct the platform: rest can do so without anything further, I was perplexed by the output in the rest: config

mighty ledge
#

because you can have an XML attribute and an XML name at the same level with the same name, but you need to distinguish between them

strong pier
#

Hello, I hope I am right in this Channel :). Currently I am controlling my remote control of my my shutters with a servo and the EspHome integration so ItΒ΄s possible to set the Servo to a specific level so that It press a button on my remote control. Now my question is how can I create a cover template in HomeAssistant to get a better control over the ui.

floral shuttle
#

so, currently, on binary sensors in the Rest integrations, I am stuck with a platform: rest binary config that can not evaluate the value_template correctly, and a rest: binary config that wont allow the same path to the item in the attribute.... for now, a template: binary_sensor to the rescue. Whether or not these issues would qualify as feature request should not be returned to the user. The inconsistency in behavior is remarkable. And that is always bad.

#

btw, value_template: > {{True}} or {true}} do make the binary state to 'on' πŸ˜‰

#

there simply seems to be no correct connection between the resource and the referencing value_template: value_template: > {% set code = value_json.rss.channel.item[12].description %} {{'Groen' in code}}

#

as is logged:```
Logger: homeassistant.helpers.template
Source: helpers/template.py:624
First occurred: 14:34:14 (14 occurrences)
Last logged: 14:42:29

Template variable error: 'value_json' is undefined when rendering '{{'Groen' not in value_json.rss.channel.item[12].description}}'
Template variable error: 'value_json' is undefined when rendering '{{'Groen' in value_json.rss.channel.item[12].description}}'
Template variable error: 'value_json' is undefined when rendering '{% set code = value_json.rss.channel.item[12].description %} {{'Groen' in code}}'

plain magnetBOT
mighty ledge
#

You cannot use XML w/ binary_sensor rest

#

It simply does not work and it will not populate json, so value_json will be undefined

#

You keep focusing on the template, the template is fine

#

it's your resource

#

your resource outputs xml

#

rest sensors can read from XML, rest binary_sensors cannot read from XML

mighty ledge
#

@terse pike you can't put switches in the template integration. Switch is only available using the legacy template integration. Also, they key for sensor: is not sensors:. Notice the lack of the letter s.

terse pike
mighty ledge
#

you can create a template switch, you just have to use the correct placement in your configuration.yaml

#

it needs to go in the switches section and the documentation covers the yaml format.

mighty ledge
#

those directions seem straight forward

floral shuttle
mighty ledge
terse pike
mighty ledge
#

Do you undertand what you did wrong

#

you put

#
template:
... stuff
#

and that's not correct

#

you need to put the switch in the switch section.

#
switch:
... stuff for switch
sensor:
... stuff for sensor
#

and make sure your code matches the code in the post. You changed things and removed the -platform: template line for both of your entities

#

you also have a . in the name of your switch and sensor

#

please follow the examples in that post and the examples in the documentation

#

yaml is very sensitive to spaces, and naming, and punctuation

#

all have to match

plain magnetBOT
mighty ledge
#

@terse pike

#

also, your code has an errro for the sensor template

terse pike
mighty ledge
#

ok? yaml does not allow the period in the name

acoustic arch
#

if i define a variable to pass into a script, do i have to redefine the same variable again inside that script to get it to pass on to another script inside the script?

mighty ledge
#

if you have a script that passes X, then any service that's called where you want to pass X, you have to declare X in that service call data

full nacelle
#

(https://ibb.co/syqWYb8) Here is an action that has to be performed. This action contains (https://ibb.co/ZgyxdL3) Where time is triggered, action is performed. The action send the data to a script connected to a skill and sends it to echo device. Then you can say yes or no(https://ibb.co/Lh7Z1wD) to the action (ex. if tv is idle for more than 5 mins, switch off. If said yes ). This will send data to yes automation(https://ibb.co/ZL44FbY). Now what I want is the yes enitity to be automatically updated to the action playing so I dont have to create multiple Yes for every action I input. The code can be found here (http://pastie.org/p/2PuGtMTCPor9O3z5EwKCWv) for all this.

acoustic arch
#

any docs for that? πŸ˜…

mighty ledge
#

how are you passing the variable to your current script...

acoustic arch
#

can it be a 'simple' if variable X = A, then set variable Y = A?

#

im not at home with this stuff yet

#

lemme check

mighty ledge
#

if you pass

service: script.something
data:
  a: 1
#

then anything inside that where you want a to continue...

service: script.somethingelse
data:
  a: "{{ a }}"
acoustic arch
#
    data:
      override: 1```
terse pike
acoustic arch
#

i have some light scripts inside a wrapper script. But sometimes i want a certain light to do something else then default

#

then in the script of the light itself i make a choose, with the variable as condition

#

ill go and toy with this info. thx

marble jackal
# mighty ledge

@terse pike indentation is also off, there is only 1 space before media_player.avidad_echo_dot_motion:

mighty ledge
#

as long as everything else is indented at that level too

#

e.g.

this:
 is:
             valid:
 yaml:
   foo:
marble jackal
#

oh okay, I thought it always had to be in pairs of two spaces πŸ™‚

mighty ledge
#

nope

#

yaml crazy

#

dictionary keys and listed items need to be the same level

#

that's pretty much the only spacing restrictions

#

so it's impossible to single space a listed item too btw

#

cause -foo: is not valid

lone bobcat
#

looking for some assistance. I'm trying to write an automation that gets triggered by a state change of all lights in an area. As I understand it, templating can help me here but I'm having trouble finding a yaml example of this use case.

full nacelle
#

you can create an entity to specify it a an area

#

and add that in entity_id

lone bobcat
#

Sorry, I'm not making the connection. I have an Area defined (lets call it "Outdoors"). In it, I have several entities. I want to trigger when any on of those entities "Outside" have a state change. I know I can list all the entities in the entity_id section of the state trigger, but what I'm looking to do is have the entities dynamic and populated by the area so any new entity added the "Outside" area get captured by the automation

lofty mason
lone bobcat
#

Thanks TimO. I actually found that resource but I'm having trouble understanding it in the context of the overall automation yaml.

lofty mason
#

You have template trigger which fires when a template becomes true, and you have a template example that can tell you if lights in an area are on or off. I think you should be able to put it together from those two things (or ask more questions if still confused on a point).

lone bobcat
#

I think so, but I don't care if the lights are on or off so much as if the state of one of the entities change. I'll see if I can piece it together from the links

mighty ledge
#

if you are trying to trigger off a single entitys state change inside a group or area, you're going to have to jump through hoops or declare all the entities out in the automation.

lone bobcat
#

Really? That seems like such a simple concept.

full nacelle
#

Hi, i was setting up actionable notification for my echo device, did everything now want to create this:

(https://ibb.co/syqWYb8) Here is an action that has to be performed.
This action contains (https://ibb.co/ZgyxdL3) where time is triggered, action is performed.
The action send the data to a script connected to a skill and sends it to echo device.
Then you can say yes or no(https://ibb.co/Lh7Z1wD) to the action (ex. if tv is idle for more than 5 mins, switch off. If said yes ).
This will send data to yes automation(https://ibb.co/ZL44FbY).

Now what I want is the yes enitity to be automatically updated to the action playing so I dont have to create multiple Yes for every action I input. The code can be found here (http://pastie.org/p/2PuGtMTCPor9O3z5EwKCWv) for all this.

magic cargo
#

noob question: any reason why a template would return true in the dev tools but false in the automation condition? πŸ˜‰

{{as_datetime(states('sensor.levisamsung_next_alarm')).astimezone()}}
{{(as_datetime(states('sensor.levisamsung_next_alarm')).astimezone() < now() or as_datetime(states('sensor.levisamsung_next_alarm')).date() > now().date())}}

returns

2023-02-15 08:00:00+01:00
True

in the dev console, but in the automation i get false in the trace

#

the template:

  - if:
      - condition: template
        value_template: >-
          (as_datetime(states('sensor.levisamsung_next_alarm')).astimezone() <
          now() or as_datetime(states('sensor.levisamsung_next_alarm')).date() >
          now().date())
    then:
(...)
#

(so just a copy pasta)

#

trace:

Executed: 14 February 2023 at 18:34:14
if
Executed: 14 February 2023 at 18:34:14
Result:
result: false
if/condition/0
Executed: 14 February 2023 at 18:34:14
Result:
result: false
entities: []
#

this is probs something stupid as its my first template, but i can't find it

floral shuttle
#

now this seems out of the ordinary... a direct template on a rest resource:{{ states('sensor.platform_rest_knmi_waarschuwingen_pubdate')}} returns Tue, 14 Feb 2023 19:58:00 +0100 . trying to get that into a device_class: timestamp . Any guidance how I should proceed here please?

#

is the only way to build a strptime? like {{ strptime(states('sensor.platform_rest_knmi_waarschuwingen_pubdate'), '%a, %d %b %Y %X %z ')}}

mighty ledge
#

seems odd hat you have a space at the end of your format though

floral shuttle
#

Yes, I’ll fix that . And a default ..

floral shuttle
#

this seems to be ok already:{{as_timestamp(strptime(states('sensor.platform_rest_knmi_waarschuwingen_pubdate'),'%a, %d %b %Y %X %z'))}}

#

or, directly in the rest sensor value_template πŸ˜‰ ```
- name: Platform rest knmi waarschuwingen pubDate
value_template: >-
{{as_timestamp(strptime( (value_json.rss.channel.item
| selectattr('title', 'eq', 'Waarschuwingen Noord-Brabant')
| first)['pubDate'],'%a, %d %b %Y %X %z')) }}

#

setting device_class: timestamp to that breaks the sensor though and makes it return unknown

marble jackal
#

device_class: timestamp expects a datetime, or a isoformat datetime string

#

not a timestamp

#

which is somewhat confusing, but if you remove the as_timestamp it should work

floral shuttle
#

right, so I should set the class to the strptime template directly?

mighty ledge
#

just omit the as_timestamp

#

you can just outright delete just that word

floral shuttle
#

thx

#

on a default value there, most templates I found simply use ,0 which seems an odd default really . wouldnt something like now() be more useful?

#
      - name: Platform rest knmi waarschuwingen pubDate
        value_template: >-
          {{strptime( (value_json.rss.channel.item
            | selectattr('title', 'eq', 'Waarschuwingen Noord-Brabant')
            | first)['pubDate'],'%a, %d %b %Y %X %z', now() ) }}``` ?
mighty ledge
#

I use whatever default I want to use that makes sense for the context of the sensor

blazing burrow
#

is it possible to read a json file and render it with a template?

#

i guess i should ask what i'm after... i am using custom:auto-entities to "pre-populate" cards based on json in a template sensor attribute, and this works, but is rather cumbersome.

i'm wondering about defining these in separate json files just to clean things up some πŸ€”

grim flicker
#

I have a template trigger that should check if a esp sensor is in fact updating every 30 seconds (for testing purposes at the moment) but for some reason my trigger isnt fired when the 30 seconds mark has passed. instead it fires when the state changes. could someone tell me what im doing wrong?

  - platform: template
    value_template: >
        {% if as_timestamp(now())|int - as_timestamp(states.sensor.zolder_temp_sensor_bmp280.last_changed)|int > 30 %}
          true
        {% else %}
          false
        {% endif %}
#

when testing the template in the dev tools it does work but i have to manually refresh it to update the outcome or wait until a state change happens for it to change from false to true. is there something wrong with the refresh rate of these template triggers?

#

its almost like these template triggers are only evaluated after an amount of time or on a state change. not actually calculating the timestamp in realtime. At the moment im using a seperate sensor with this template and the sensor turns on and off. and this seems to work fine. but with over 4000 entities i would like to reduce the amount of sensors as much as possible and was looking for a way to directly do this in an automation without a seperate sensor. Now i wonder if its even possible to do it the way i want right now

plain magnetBOT
#

@full nacelle I converted your message into a file since it's above 15 lines :+1:

full nacelle
#

and it converts my msg into code. wow

#

I was trying to use chatgpt to answer my question but It seems I have exceeded the number of tries in an hour

The code he has made is this http://pastie.org/p/5hNqTWNdRIjYkCY2eMgVM3

What I want is to get a sensor which update my https://ibb.co/QKC8f8j entity_id in the arrow. I have multiple automation like these so they contain a common name action in them. Can anyone tell what's wrong in the code. THIS CODE WAS FOR THE TEMPELATE IN DEVELOPER TOOLS.

marble jackal
# grim flicker I have a template trigger that should check if a esp sensor is in fact updating ...

Some remarks

  1. you don't need this if else construction, as the part you are testing will return true or false itself
  2. you don't need to convert to timestamps, you can use the datetimes directly
  3. now() will only be evaluated once per minute, so this will evaluate to true anywhere between 30 and 90 seconds after the state change
  - platform: template
    value_template: >
        {{ now() - states.sensor.zolder_temp_sensor_bmp280.last_changed > timedelta(seconds=30) }}
grim flicker
#

Ok thanks so eventually it will work when I set it to 10 minutes for example. The only thing is that it won't be as precise right?

#

That explains allot about the random changing from true to false. It's not random but once per minute

marble jackal
#

Yep, now() is updated on the minute change

humble mortar
#

Any ideas on this?

#

Do you do something like value.value.value

#
  <tr align="left"><th>Item</th><th>Stat</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
{%- if value is defined %}
  <tr><td>{{ name }}</td><td>{{ value }}</td></tr>
{%- endif %}
{%- endfor %}
</table>```
marble jackal
#

Apply a second for loop on the value

#

And please don't tag me

humble mortar
marble jackal
#

I would use different variable names, to avoid confusion

humble mortar
marble jackal
#

You probably don't really understand what you are doing πŸ˜…
Assume you have a directory like this

example:
  key1: 
    subkey1: value1
  key2
    subkey2: value2

with example.items() you turn this into a list of tuples [( "key1", { "subkey1": "value1" }), ( "key2", { "subkey2": "value2" })]

With {% for name, value in example.items() %} you assign name to the first item of each tuple, and value to the 2nd item.
But you could also do {% for banana, apple in example.items() %}. It doesn't matter how you call these variables.

sonic sand
# marble jackal Forgot to change the message template ```yaml - service: notify.home_assistant...

hi again
well the portions does show up (values.value) but there is a problem with the timestamp it showing unknown in the notification still.
https://imgur.com/10Lom9M

automation:
http://pastie.org/p/6iTChEY8DXolq0APPrGZbo

also someone at #automations-archived told me to create an automation for notification if the fishes have not been fed for more than 2 days and 6 hours I will have to create a template automation and I should consult in #templates-archived how to do it correctly.
Thanks man

marble jackal
#

I don't have time to look into the automation now

sonic sand
#

Sweet, thanks dude

humble mortar
marble jackal
#

Yes, there are only two

marble jackal
full nacelle
#

Can someone help me with my temp too?

marble jackal
full nacelle
#

There was no one to help so I choose the way

humble mortar
marble jackal
#

No, no, no... I was giving an example there, not a solution

#

But I don't have any more time now

full nacelle
#

(http://pastie.org/p/0NR6UVF0dDxpDV3rdFIAlD) Here is a script that I am using to call multiple automations. One of my automations are something like this. (http://pastie.org/p/76nQeMq0TGgDzDElqHrvXs). These automations have 1 word in common which is 'action'. What it does is it sends the data to alexa skill and then it receives it through this automation(http://pastie.org/p/24unVsQi8JuZtXFFvpxZLk) if said yes and (http://pastie.org/p/4NdEk4izPlKc5m9ZFhGQ5D) if received no from echo device. I dont want to create multiple yes received for every action automation.

#

not from ChatGpt

#

that this is a real waste

marble jackal
#

Your automations don't have a trigger, that makes no sense

full nacelle
#

doesn't work

marble jackal
#

Look at the trace of the automation, does it actually trigger? Are you triggering it manually by using Run actions?
doesn't work doesn't help in resolving the issue

humble mortar
full nacelle
#

Now I have multiple action automation and want the yes automation to only be one.

marble jackal
# humble mortar How do I format your example properly into the template?

Something like this. I'm in mobile, so no guarantees

  <tr align="left"><th>Item</th><th>Stat</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
{%- if value is defined %}
  <tr><td>{{ name }}</td><td>
  {% for k, v in value.items %}
    {{ k }}: {{v }}</ br>
  {% endfor %}
  </td></tr>
{%- endif %}
{%- endfor %}
</table>
marble jackal
full nacelle
#

I will use it in alexa app routine

#

And this one id just a demo

#

For the test i am triggering it manually

#

I will be using this to confirm my things for exam if I turn off a computer and my files are not saved it will ask me if I am sure that I want to turn off my computer if I say yes it will turn off if I say no it will not I have such automattions all over my home so it is useful the sentences also can be changed but the response yes and no matters

marble jackal
#

If not, answer I need to know if it does trigger, and if so, what the trigger variable looks like in the automation trace

grand osprey
#

Hi there, I'm having some trouble with a sensor template that grabs the second element value from a timer list that doesn't always exist. My original code is http://pastie.org/p/4BIQERkBelJzahahd6G8oa

Which produces errors in the log like:
Template variable error: list object has no element 1 when rendering '{{ states.sensor.living_room_display_timers.attributes.timers[1].local_time_iso }}'
Template variable error: list object has no element 1 when rendering '{{ states.sensor.living_room_display_timers.attributes.timers[1].label }}'
Template variable error: list object has no element 1 when rendering '{{ states.sensor.living_room_display_timers.attributes.timers[1].duration }}'

I've attempted a few different if statements to check if the element exists, but so far the error keeps popping up in the log. My last attempt was: http://pastie.org/p/7KRyeasznAaf9XDiBnysAa

tidal heart
#

I have some template sensors that can get really long states and want to cut them of a max chars and I've tried truncate but it does not seem to take spaces in to account. Is there anyway around that?

I've done this in the past but can't remember how it's done

humble mortar
magic cargo
#

can someone help plz πŸ₯Ί

humble mortar
marble jackal
mighty ledge
#

Should check that attr for mapping before iterating

#

Dictionary items() always returns a list of tuples that has a key and value. It’s impossible for it to be missing key or value. At worse it returns an empty list, which the for loop will skip

#

Both of those pastes don't exist anymore

marble jackal
mighty ledge
#

Last I remember, some of the main dictionary items had different values

marble jackal
#

yes, I think there was a system thing which was different

mighty ledge
#

long story short, he may need to check to see if the attribute is mapping before trying to iterate instead of forcing a from_json because it should already be json

marble jackal
#

ah okay

mighty ledge
#

yeah, but he needs to post the data again for confirmation

#

his data structure is definitely built for someone to create objects. It's not nice for jinja itering

humble mortar
mighty ledge
mighty ledge
#
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
  <tr><td>{{ name }}</td><td>
  {% if value is mapping %}
  {% for k, v in value.items() %}
    {{ k }}: {{v }}</ br>
  {% endfor %}
  </td></tr>
  {% endif %}
{%- endfor %}
#

@humble mortar ^

#

that's going to look shitty tho as a table

marble jackal
#

Maybe return the string in an else?

mighty ledge
#

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

#

no clue what he wants

#

if he wants separate tables, he'll have to rework all the HTML

humble mortar
mighty ledge
#

Yep

#

Are you sure you even want this data?

humble mortar
#

What does is mapping mean and how did that fix it?

humble mortar
#

Just with a bit more data πŸ˜„

analog mulch
#

Hi. I have a trigger-based sensor. I would like write to its attributes a value with the key equal to the object_id of the trigger, Something like

trigger:
- platform: state
  entity_id: 
   - sensor.bla1
   - sensor.bla2
  variables:
    trigent: "{{trigger.to_state.object_id}}"
...
sensor:
  attributes:
    {{trigent}}_last_state: "{{trigger.to_state.state}}"

Is something like this allowed? If not, how can I work around it -- I would like to have a general template for an arbitrary number of monitored entities, which would save their individual state in the attributes with the attribute name generated by the template somehow. Or at least so that I could retrieve in the templeate for the state

#

Or maybe one could have just one attribute name fixed, with a dictionary as the attribute state?

mighty ledge
fickle sand
#

Hi, why does this template not output a string into my local language (Dutch)

{{as_timestamp(now()) | timestamp_custom('%A %d %B')}}

output: "Wednesday 15 February"

grizzled grove
#

Any idea if it's possible to get the "attribute" elevation, we have set for our Home?

analog mulch
#

Or maybe another way of asking: is it possile in a template to create a variable name based on a string stored in another variable -- sort of equivalent of python's exec

mighty ledge
# humble mortar I was going for something like this https://imgur.com/a/W7kzfHU
{%- macro writeline(key, input, indent='') %}
{%- if input is mapping %}
{%- if key %}
{{ indent }}{{ key }}:
{%- endif %}
  {%- for k, v in input.items() %}
{{ indent + '  '}}{{ writeline(k, v, indent + '  ') }}
  {%- endfor %}
{%- elif input is iterable and input is not string %}
{%- if key %}
{{ indent }}{{ key }}:
{%- endif %}
  {%- for v in input %}
    {{ indent }}{{ writeline('', v, indent + '  ') }}
  {%- endfor %}
{%- else %}
{{ indent }}{{ key }}: {{ input }}</ br>
{%- endif %}
{%- endmacro %}

<table>
  <tr align="left"><th>Item</th><th>Stat</th></tr>
{%- for name, value in state_attr('sensor.printer_3d_system_info','system_info').items() %}
  <tr><td>{{ name }}</td><td>
  {{ writeline('', value, '') }}
  </td></tr>
{%- endfor %}
</table>
#

that uses a recursive macro with no safety built in, it shouldn't iterate forever but it can if this go wrong

#

anyways, it will traverse whatever shape you throw at it

humble mortar
#

Fancy! I'm not sure why but it puts a large gap at the start of the markdown

mighty ledge
#

looks like there's issues with the func, I'll have to look at it in a bit

marble jackal
#

I guess it's because the python version is provided as a list
"version": [3, 7, 3, "final", 0]

humble mortar
#

The ui editor also mangled the code word wrapped some of it.

#

Seems to mangle it every time you save and then click code editor again 😦

#

There was also a bunch of carriage returns throughout the macro stuff removed it then it closed up the gap a bit I think the rest is table padding removed the table

analog mulch
#

Another idea: if I set a variable to be a dictionary within a template, can I update its values somehow. Whatever I try fails.

blazing burrow
#

how can I make a template sensor that updates every day?

analog mulch
inner mesa
analog mulch
inner mesa
#

something like:

{% set orig_dict = {"foo": "bar", "floop": "blah"} %}
{{ dict(orig_dict.items(), **{"foo": "new"}) }}
#
{
  "foo": "new",
  "floop": "blah"
}
analog mulch
#

A brilliant. Thanks0.!

inner mesa
#

I confess that I keep an example in a note because I can never come up with it when I need it

spark flame
#

Is there a way to use value_json without referencing the name of the key, as in which element number?

#
{'Cords, Chargers, and Printer Cartridges': {'category': 'rotating', 'quantity': 1}, 'Batteries': {'category': 'standard', 'quantity': 1}, 'Plastic Film': {'category': 'standard', 'quantity': 1}, 'Light Bulbs': {'category': 'standard', 'quantity': 1}, 'Threads': {'category': 'standard', 'quantity': 1}}
#

I've got this attribute where the first element will change every 2 weeks to a new named category

#

This Ridwell integration has some of the worst sensor attribute formatting I've seen

#

I suppose I could just regex it out

twin igloo
#

Hi All,
I have maybe a stupid question.
I want to integrate some of Matthias dashboards ideas in my dashboard.
I have a lovelace UI dashboard.*
I have copied the button_cards_templates dir + content in the config dir of my HAS.
There is a light.yaml template in there...

But i still get the button-card template light not found...
I looked but i have no ui-lovelace.yaml to put the include in it..and it seems correct as i use UI mode

So i found on internet that you need to add it into the dashboard itself by going into edit and raw configuration editor...
But whatever i put into there, i or gives me an invalid syntax error or it does not work either...

Do i need to put it into that raw configuration error or somewhere else?
What is the correct syntax to put it into there?

Any help would be much appreciated...already strugeling for days with this...

spark flame
twin igloo
spark flame
#

Is it some kind of template light? I'm not even sure what you're attempting to run exactly

marble jackal
inner mesa
#

hey, check that out

#

less magic

twin igloo
# spark flame Is it some kind of template light? I'm not even sure what you're attempting to ...

Sorry if i was not clear...
In a dashboard i have this custom_button_card

  • type: custom:button-card
    entity: light.bureau
    name: Bureau
    template:
    • light
    • icon_hue

Light and icon_hie are button_card_templates....
I have all those in a seperate dir with a lot of yaml files...
Instead of putting the code via the raw configuration editor like this in the dashboard itself...
..
button_card_templates:
light:
double_tap_action:
action: fire-dom-event
browser_mod:
service: browser_mod.popup
data:
title: |
[[[
return !entity || entity.attributes.friendly_name;
]]]
card_mod:
etc....

because it's a lot of code i want to reuse in different dashboards., I am looking in how to put !include-dir all those files that i also have as seperate yaml files.....
The only way i got it working is to put everything into the raw configuration editor....But it's so messy....

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

spark flame
#

If you want ui-lovelace.yaml you'll have to make it manually and configure HA to use it

#

That was the old way to do custom dashboards before they had UI management

haughty pond
#

Hey, any good idea for the following. I have a button, that when pressed should grab a datetime of a sensor, and use that for triggering an automation when that time occurs?

lofty mason
haughty pond
#

So easy, will give it a shot. Thx

lofty mason
#

I guess it doesn't even need to be a script, even just a call service could probably do it.

haughty pond
#

Results in error

#

Failed to call service input_datetime/set_datetime. expected float for dictionary value @ data['timestamp']

#

The output of that state_attr is "2023-02-16 02:00"

mighty ledge
#

button card doesn't accept templates

#

gotta make a script

haughty pond
#

Gotcha

mighty ledge
#

but timestamp usually wants a float

#

so...

#

as_timestamp(state_attr('binary_sensor.nordpool_planner_activate_dishwasher', 'starts_at'))

#

but I do have to ask, is that timestamp local time or UTC?

haughty pond
#

Localtime

mighty ledge
#

because it will be off by your timezone if it's local

haughty pond
#

Based on my geographic area

mighty ledge
#

ok

#
state_attr('binary_sensor.nordpool_planner_activate_dishwasher', 'starts_at') | as_datetime | as_local | as_timestamp
haughty pond
#

service: input_datetime.set_datetime
data:
timestamp: >-
state_attr('binary_sensor.nordpool_planner_activate_dishwasher',
'starts_at') | as_datetime | as_local | as_timestamp

mighty ledge
#

if you set the datetime field instead of the timestamp field, you can omit the as_timestamp

haughty pond
#

Gets me an error still, now trying with a script

mighty ledge
#

you're missing the {{ }}

#

see the first pin for templates

haughty pond
#

Yeah, missed the {{ but still getting an error with about float

mighty ledge
#

are you trying to test this in the service caller?

#

or just by running the script

haughty pond
#

Just running a script now

mighty ledge
#

then there should be an error in your logs related to the template

haughty pond
#

Would be good to set a target to begin with ^^

mighty ledge
#

ah yes πŸ˜‰

haughty pond
#

But still getting error 😦

#

DISKMASKIN - Set start: Error executing script. Invalid data for call_service at pos 1: expected float for dictionary value @ data['timestamp']

mighty ledge
#

is that the most recent error or an old one?

#

because that will return a float

haughty pond
#

Most recent

mighty ledge
#

test it in the template editor to see for yourself

haughty pond
#

Oh, just did it

#

Misslyckades med att anropa tjΓ€nsten input_datetime.set_datetime. expected float for dictionary value @ data['timestamp']. Got None

mighty ledge
#

that can't be the result of the template editor as it doesn't validate yaml

haughty pond
#

Sure is

mighty ledge
#

developer tools -> template?

haughty pond
#

Yup!

#

OH!

#

Sorry

mighty ledge
#

.. yeah

haughty pond
#

Was using the service tab

#

service: input_datetime.set_datetime
target:
entity_id: input_datetime.diskmaskin_starttid
data:
timestamp: >-
2023-02-16 02:00:00+01:00

#

Why the +01:00? Because looking at Dev tools - states it doesn't show that

mighty ledge
#

that's a datetime object

#

with your local timezone applied

#

and you put this template in the editor?

{{ state_attr('binary_sensor.nordpool_planner_activate_dishwasher', 'starts_at') | as_datetime | as_local | as_timestamp }}
haughty pond
#

Didn't have "as_timestamp"

#

Now it outputs:

#

service: input_datetime.set_datetime
target:
entity_id: input_datetime.diskmaskin_starttid
data:
timestamp: >-
1676509200.0

mighty ledge
#

alright, that's a float

haughty pond
#

Yeah

mighty ledge
#

so then your script should work

#

with that template

haughty pond
#

YAY!

#

Sucess

#

Thanks, @mighty ledge

mighty ledge
#

np

regal seal
#

hi! Can someone be a second pair of eyes for me? estimated_island_battery_total_energy is calculating properly but estimated_battery_total_energy is showing unavailable. http://pastie.org/p/3TDaQhCwiw29LosX6nFh3e

mighty ledge
#

also keep in mind that you may have issues at startup if your sensors are not numbers

#

your source sensors, i.e. bank1,2 and3

queen cairn
#

How to return integer in template?

regal seal
mighty ledge
#

change float to float(0) to supply 0 as a default

regal seal
#

sweet! Thank you. One final question -- I'm trying to specify state_class on these items but I'm getting an error of Invalid config for [sensor.template]: [state_class] is an invalid option for [sensor.template]. Check: sensor.template->sensors->estimated_battery_energy_bank_1->state_class. however, the docs show that state_class is valid in the template integration.

mighty ledge
#

You have to use the new style template sensors to use state_class

#

you're using the legacy style

regal seal
#

oh, ok, I'll look up how to migrate over. Thank you.

plain magnetBOT
regal seal
#

With the new format, I see that the root of the yaml is template -- I use !include_... macros in configuration.yaml. Any pointers on how to maintain that pattern in the new format? I was thinking template: !include_dir_list templates/ and then having a path of ./templates/sensors/xyz.yaml -- is that accurate?

mighty ledge
#

You can do that by using

template: !include_dir_merge_list template
#

keep in mind this is a list, and not a named

#

you can't use named because of the nature of the template: yaml

#

then in that folder (config\template), make sure you list out your entities inside your files, here's an example of one of mine:

- binary_sensor:
  - unique_id: washer_status
    name: Washer Status
    device_class: power
    state: >
      {{ is_state('input_boolean.washer', 'on') }}
    attributes:
      template: energy

  - unique_id: announce_washer
    name: Announce Washer
    device_class: door
    state: >
      {{ is_state('switch.announce_washer', 'on') }}
    attributes:
      template: energy

  - unique_id: dryer_status
    name: Dryer Status
    device_class: door
    state: >
      {{ is_state('input_boolean.dryer', 'on') }}
    attributes:
      template: energy

  - unique_id: announce_dryer
    name: Announce Dryer
    device_class: door
    state: >
      {{ is_state('switch.announce_dryer', 'on') }}
    attributes:
      template: energy

- sensor:

  - unique_id: energy_terrif
    name: Energy Terrif
    state: "0.053080"
    unit_of_measurement: $/kWh
queen cairn
#

I have created the following template to create a sensor that changes the temperature sensor being targeted by a thermostat depending on the time of the day, then have the generic_thermostat set it as the targeted sensor. The developer tools template is returning the named sensor, and I believe it should return a temperature of that sensor instead (integer). Any ideas on how to fix this?

{% if ((states.sensor.time.state > '19:30') and (states.sensor.time.state < '00:00')) or ((states.sensor.time.state > '00:00') and (states.sensor.time.state < '06:30')) %}
sensor.master_air_temperature
{% else %}
sensor.kitchen_air_temperature
{% endif %}
rose scroll
#

And to simplify the template even more:

{% if now() > today_at('06:30') and now() < today_at('19:30') %}
  {{ states('sensor.kitchen...') }}
{% else %}
  {{ states('sensor.master...') }}
{% endif %}
queen cairn
rose scroll
#

What do you mean? Entities only report when they change state.

queen cairn
#

I think i figured it out. My sensors were losing battery quite quickly but I just went in and saw that they were reporting every minute with the reporting threshold set to 10 degrees. I set the reporting interval to 0 and the threshold to 10 (1 deg) and it seems to work now.

#

Thanks for the help though.

rose scroll
#

πŸ‘Œ

next pier
#

first time making / dealing with a template. I've used a drop down menu, and that may be suitable, but I'd like a template sensor that can tell if me or my wife's phone are in an MQTT room. Is there a guide or something I could copy to get my feet wet?

full nacelle
marble jackal
#

That's strange, because the trigger is now even more generic

#

so if it triggered before, it should also now

analog mulch
#

How can I protect myself from a possibly missing attribute in a template? I am intending to write a sensor which will eventually populate the attribute, but in the initial state it has not done so. The state then depends on the value of this attribute. So I want something like set attr = this.attributes.attr when in the initial state attr is not there (it's not None, the key is not there yet), which results in UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'attr'.

analog mulch
floral shuttle
#

trying to replicate the logic Bram uses in his weather card, I have this now, which, besides some defaults to be added, works ok with a big caveat: it has not yet implemented the ..weatherIconsDay https://github.com/bramkragten/weather-card/blob/8773e031775f58ebfabdfbbfb56907db4a7aed0e/dist/weather-card.js#L25 yet. Ofc, this is required to map the states, but so far I have not encountered a jinja way to do so. I think... can we? Or do I have to copy the entire map verbosely, and only change the night icons.?

grave solstice
#

Hi, i got a value_template from MQTT is there a way to get all subtopics in a list?

floral shuttle
#

I could probably catch it with a condition: {% set condition = states('weather.buienradar') %} {% if states('sun.sun') == "below_horizon" and condition in weatherIconsNight %} {{weatherIconsNight[condition]}}.svg {% else %} {{weatherIconsDay[condition]}}.svg {% endif %} .... but still would like to know if we can call the mapper inside the second, and override it on certain states

ruby vault
#

Any thoughts on what I am doing wrong here?

{{ strptime('2023-02-16 17:15:57.390622+11:00', '%Y-%m-%d %H:%M:%S.%f+%z') }}

ValueError: Template error: strptime got invalid input '2023-02-16 17:15:57.390622+11:00' when rendering template

floral shuttle
#

you left out the important part: but no default was specified πŸ˜‰

ruby vault
#

sure, you can specify one and it just returns the default.. If the strptime works, I don't need a default.

#

This works, so it just does not like the timezone offset at the end for some reason.

{{ strptime('2023-02-16 17:15:57.390622', '%Y-%m-%d %H:%M:%S.%f') }}

#

oohhh

#

got it

{{ strptime('2023-02-16 17:15:57.390622+1100', '%Y-%m-%d %H:%M:%S.%f%z') }}

I was adding in the + when it was not needed. πŸ™‚

floral shuttle
#

was just typing that.... sorry for being slower than you..

#

btw, if you past code here, use the <> button after selecting the text, or backticks before and after the text like {{ strptime('2023-02-16 17:15:57.390622+1100', '%Y-%m-%d %H:%M:%S.%f%z') }}

ruby vault
#

yeah, cool. Can do.

plush wolf
#

I am once again looking for a pointer towards the right guide / post: I have a drop down list on the interface to select and what time of day exterior lights should turn on. This varies frequently and I am not making friends with the state of the sun approach I had so-far. So I want to be able to select the trigger time in the UI via drop-down. I have found how I can make a drop down list item a condition for an automation, I have not seen it to make it a trigger? Simple example would be I select 4PM on the drop down and from there on out the automation triggers as of 4. If I select 5PM the day thereafter the automation triggers at 5 there on out

mighty ledge
plush wolf
#

But then how do I link the drop-down to the automation?

mighty ledge
#

just use the datetime as the at option

#
trigger:
- platform: time
  at: input_datetime.whatever_you_name_it
#

all covered in the trigger docs

plush wolf
#

Okay perfect, will test. Thanks a lot

vernal pulsar
#

I'm trying to pass the entity_id of a media player into a script and get the volume level but I can't get it to work. Is this possible?

variables:
  mediaplayer_state: '{{ states("{{ media_player_target}}") }}'
marble jackal
#

you are nesting templates

vernal pulsar
#

Yes, is that not allowed?

marble jackal
#

if media_player_target is a variable you defined somewhere, you can just refer to it in another template:

variables:
  mediaplayer_state: '{{ states(media_player_target) }}'
#

And no, that is not the way it works πŸ™‚

vernal pulsar
#

Thank you @marble jackal !

floral steeple
#

good day! I have a google mini in my shed, buts its not always on (runs off solar power), how can I put an availability condition so that I don't always get an error thrown in my logs. Something like this?

    data:
      availability: >
        {{ state('media_player.shed_speaker') not in [None, 'unknown', 'unavailable'] }}
      entity_id:
        - media_player.shed_speaker
      message: "{{ message }}"
ruby vault
#

ah, do a condition in the previous step

#
  - "{{ state('media_player.shed_speaker') not in [None, 'unknown', 'unavailable'] }}"
  - service: tts.cloud_say
    data:
      entity_id:
        - media_player.shed_speaker
      message: "{{ message }}"
#

just be aware, if that condition is false it'll stop the whole automation action sequence and nothing executes after it

#

so you can use an if, if you have more stuff after it.. or change the order as necessary

#

also, that condition is condition short hand, you can use the more readable and verbose:

  - condition: not
    conditions:
      - condition: state
        entity_id: media_player.shed_speaker
        state:
          - None
          - "unknown"
          - "unavailable"
  - service: tts.cloud_say
    data:
      entity_id:
        - media_player.shed_speaker
      message: "{{ message }}"
#

@floral steeple ^^

floral steeple
#

@ruby vault hey thanks, that would work...I'll have to reorder it so its the last excecution...or maybe a if-then-else as you suggested, but could make it overly complicated

#

i used if then

ruby vault
#

yeah, well the else is optional, so just an

 - if:
     - "{{ state('media_player.shed_speaker') not in [None, 'unknown', 'unavailable'] }}"
   then:
     - service: tts.cloud_say
         data:
           entity_id: 
             - media_player.shed_speaker
           message: "{{ message }}"

will do

floral steeple
#

so that way that way the automation stops gracefully

#

perfect! I did it exactly like you

ruby vault
#

yeah, ezpz

floral steeple
#

actually, the GUI added some extra fluff

#
  • condition: template
    value_template:
#

I guess I could keep it

ruby vault
#

yeah, tis fine. It just another way

floral steeple
#

awesome, thanks for your help!

ruby vault
#

no problems

#

rare to get someone talking in AU and friends tz. πŸ™‚

floral steeple
#

I'm in MST...is everyone else sleeping lol

ruby vault
#

oh, wow.. Ok, that works. How is yesterday afternoon? πŸ™‚

floral steeple
#

lol going well

#

how is tomorrow afternnon?

ruby vault
#

well, only 0910 but yeah, looking to be a fantastic day

floral steeple
#

🀣

dark rock
#

Hi! I need to send a json message to mqtt using a template. The idea is to obtain a message like this:

{"value":2590629792,"protocol":32,"length":32,"delay":423}

but using a value that is stored in a helper. I have tried this:

{{{"value":int(states('input_number.mqttto433code')),"protocol":32,"length":32,"delay":423}}}

and the templeate editor converts it properly, but when trying to send it, it raises the error: "failed to call service script/velocidad_ventilador. Value should be a string for dictionary value @ data['payload_template'].

How can I fix it?

marble jackal
#

No way to know for sure when you don't share the complete service call, but my first guess would be that you didn't wrap your template in quotes

dark rock
mighty ledge
dark rock
#

like this:

payload_template: >
  {{{"value":int(states('input_number.mqttto433code')),"protocol":32,"length":32,"delay":423}}}
#

dont know why the spaces in the second line are not showing up

mighty ledge
#

You have to format it using 3 backticks before and after

grand quarry
#

Does jinja have 3 braces?

mighty ledge
#

No, he’s outputting a dictionary

#

2 braces for the template, 1 brace for the dictionary

mighty ledge
dark rock
#

yeah, it does not fail

mighty ledge
#

πŸ‘

dark rock
#

thanks @mighty ledge

mighty ledge
#

Np

#

FYI that’s called multiline indicator

#

When you do single line templates you need to wrap the single line in quotes. But then you run into quoting issues

#

So you can skirt around those issues by making it a multiline template

marble jackal
#

well, in this case you could've also used double quotes for "input_nuberm.mqtto433code" and then wrap the template in single quotes

#

that's why it is important to be consistent with the quotes inside the template πŸ™‚

mighty ledge
#

Ya, but that’s too much to explain when you’re on mobile 🀣

#

I took the lazy way out

dark rock
#

this is the other option then? payload_template: '{{{"value":int(states("input_number.mqttto433code")),"protocol":32,"length":32,"delay":423}}}'

marble jackal
#

yes

#

I would also suggest to add some spaces to increase readability

#

and another option is:
payload_template: '{{ dict(value = states("input_number.mqttto433code") | int, protocol = 32, length = 32, delay = 423) }}'

dark rock
#

don't know why, but it's converting the double qoutes to single quotes and the message does not work

#

if i send the message ussing mqtt explorer this is it:
{
"value": 2774917024,
"protocol": 32,
"length": 32,
"delay": 423
}

if i send it with the template is like this:
{'value': 2778324896, 'protocol': 32, 'length': 32, 'delay': 423}

#

If i send the message using mqtt explorer, the program works (this is for open mqtt gateway)

marble jackal
#

I don't use mqtt myself, I expect it expects a dict, and not a json string. Do you know that @mighty ledge

wraith basalt
#

Hello, i currently have a problem with the last_updated state.

Why do those two not give the same value:

{{ states.sensor.smart_socket_16a_5_power.last_updated }}

{{ state_attr('sensor.smart_socket_16a_5_power', 'last_updated') }}

The first one gives the wanted value, but the second one returns None.
And states('sensor.smart_socket_16a_5_power').last_updated throws an error.

marble jackal
#

it's not an attribute of the entity

wraith basalt
#

Oh okay, thank you.

craggy sparrow
#

Hey guys, I am having a little trouble with mqtt hvac, I have set it up in my configuration.yaml, but I get this error when I update the temperature using the thermostat card:

Failed to call service climate/set_temperature. UndefinedError: 'dict object' has no attribute 'unknown'.

the relevent part of my configuration.yaml is here: https://pastebin.com/ipjZFkAm

and I think the problem lies in my templates :S

{% set modes = { 'off': '02', 'heat': '01' } %}
{% set fan_modes = { 'off': '01', 'low': '02', 'high': '03', 'anti-frost': '04'} %}
{{ ["F1F1", "0210", modes[states('climate.panel_heater_office')], "00", "02001900", fan_modes[state_attr('climate.panel_heater_office', 'fan_mode')], ('%#x' % (value | int))[2:], "0100", "00", "01000001", (('%#x' % ( 48 + (modes[states('climate.panel_heater_office')] | int) + (fan_modes[state_attr('climate.panel_heater_office', 'fan_mode')] | int) + (value | int)))[2:] | upper), "7E"] | join }}

marble jackal
#

My guess would be that states('climate.panel_heater_office') results in unknown and so you are now trying to find modes.unknown which is not a valid attribute

craggy sparrow
#

haha

#

I think you are 100% right

#

@marble jackal Thanks πŸ™‚

craggy sparrow
#

@marble jackal it works! thanks a bunch. not sure how i missed that in my copy/paste frenzy

dark rock
#

@marble jackal @mighty ledge I'm an idiot. I was sending the data to the incorrect topic mindblown

marble jackal
#

That would also help

dark rock
#

🀣 sometimes I would love to be able to read and comprehend the text at the same time

magic cargo
#

I think i finally found my issue, i think im not using operators right? if i put (1 > 0) in a template it says condition did not pass?

#

how do i compare things?

marble jackal
#

Which issue are you referring to here?

magic cargo
#

uhm, some long time ago i had an issue with the dev tools not giving same result as template condition

marble jackal
#

Okay

marble jackal
magic cargo
#

oh, is it broken? πŸ€”

#

i mean

#

trace shows same result

#
Executed: 17 February 2023 at 14:07:06
Result:
result: false
#
if:
  - condition: template
    value_template: (1 > 0)
#

dev tools does show True

#

whats going on? πŸ˜…

analog mulch
#

I am trying for the first time to use YAML anchors for some template sensors. For example (I'm cutting the complicated parts of these):

- sensor:
    - &cumulator_sensor
      name: Electricity total Energy cumulative
      state_class: total_increasing
      unique_id: "roigjoreofffifnofnvo"
      state: >- ....

and then I create a second sensor in the same file which is being included into config.yaml through !include_dir_merge_list templates/

- sensor:
    - <<: *cumulator_sensor
      name: Electricity total Energy
      unique_id: "roigjoreoifnofnvo"

I get an error that my name and unique_id are duplicated. The second sensor works fine seemingly, but am I doing something non-legit?

versed shoal
#

Hey folks, kindly redirect me if this isn't the right place to ask, but I'm wondering if it's possible to use a template to redefine how a service works.

For instance: I have five IKEA Frytur blinds that I am adding to a picture-elements dashboard, so if I want to just tap on the icon to call-service cover.toggle that would be fine except that I want the open behaviour of cover.toggle to cover.set_cover_position with a value of 95% since the blinds don't like being pulled up into the body of the roller. I had been using 3D printed standoffs to hack this, but then I set all my other automations to only open to 95% and have removed the standoffs.

versed shoal
marble jackal
#

a jinja templates needs to be wrapped {{ and }}

#
if:
  - condition: template
    value_template: "{{ 1 > 0 }}"

It also needs quotes if you use the single line notation

fossil hearth
#

how to access/ get value of the previous valid state of an entity?

#

so that my automation can have a condition to not trigger if previous value is the same ..

#

without the need of a helper

analog mulch
#

I store it in an attribute

fossil hearth
#

i mean i thuaght of this, but i remember there was a way to get the previous valid value as it will be very crucial to most of the automations.

marble jackal
#

You can just compare trigger.from_state.state with trigger.to_state.state

#

but... If you set up a state trigger with a blank to: or from: it will only trigger if the state changed, so not if only attributes changed

analog mulch
magic cargo
fossil hearth
#

i have a sensor that comes in as a number, this is the condition to resolve this matter. what do you guys think
{{ (states.sensor.numeric1.state| int is number) and (trigger.from_state.state| int is number) }}

marble jackal
fossil hearth
#

yes agreed πŸ˜„

marble jackal
#

whoops, replied to the wrong post πŸ™‚

magic cargo
#

{{states('input_number.targettempbedroom')|float+0.3}} this should work for incrementing a number on the fly right?

#
service: climate.set_temperature
data:
  target_temp_high: {{states('input_number.targettempbedroom')|float+0.3}}
  target_temp_low: {{states('input_number.targettempbedroom')|float-0.3}}
target:
  entity_id: climate.bang_bang_climate_controller
#

like that?

#

cause it gives me Error running action expected float for dictionary value @ data['target_temp_high']. Got None expected float for dictionary value @ data['target_temp_low']. Got None

inner mesa
#

You need to surround your template in quotes

magic cargo
#

oh i see

#

not used to editing in yaml xD

brittle jacinth
#

I need to define a sensor that is a division of 2 other sensors. Is it not possible to define this via the home assistant "Helper" UI? Or do I have to define it via yaml?

#

I assumed it was going to be either "Combine the state of several sensors" or "Derivative sensor" but neither has division operators or is limited to 1 input sensor.

marble jackal
#

No, divison is not an option in those, you need to define a template sensor in yaml for that

analog mulch
#

Am I allows to use soemthign like states(this) to protect mysellf from unavailable or just this.state inside a template sensor state.

marble jackal
#

states(this.entity_id) works

#

but not states(this)

#

or this.get('state', 'unknown')

#

or this.state | default('unknown')

analog mulch
#

I have a problem with a template, which goes to unavailable every time I reload the templates. I think I've boiled it down to this:

- sensor:
    - name: Electricity total Energy Tester
      unique_id: "erigmehpoigem"
      state: >-
        {% set current = states(this.entity_id)%}
        {{current}}
#

Is there some way of protecting myself here?

brittle jacinth
#

I just learned that there is a legacy definition for sensor template that I've been using an HA docs recommends the modern format. However, I'm getting tripped up on identation. In my sensors.yaml file, I have this currently and exact identation. What is the "modern" format version of this?

- platform: template
  sensors:
    attic_humidity:
      unique_id: sensor.attic_humidity
      value_template: "{{ state_attr('climate.attic', 'current_humidity') }}"
      unit_of_measurement: "%"
      friendly_name: "Attic Humidity"
      device_class: humidity
analog mulch
#

the new is:

template:
 - sensor:
    name: Attic humidity
    state: "{{state_attr('climate.attic', 'current_humidity') }}"

where the template key is in configuration.yaml -- so it dosn't go into the sensors key

floral steeple
#

hey all, this little if-then part leads to an error: Error: In 'template' condition: UndefinedError: 'state' is undefined

  - condition: template
    value_template: >-
      "{{ state('media_player.shed_speaker') not in [None, 'unknown',
      'unavailable'] }}"
then:
  - service: tts.cloud_say
    data:
      entity_id:
        - media_player.shed_speaker
      message: '{{ message }}'

Not sure why, basically, I don't want it to send TTS to that speaker is if not avaiable.

#

ok...its supposed to be states mindblown

brittle jacinth
# analog mulch the new is: ``` template: - sensor: name: Attic humidity state: "{{stat...

what am I doing wrong in this yaml file?

template:
  sensor:
    unique_id: tower_array_used_percentage:
    name: Tower Array Used Percentage
    state: >-
      {{ ((states('sensor.tower_array_used') | float / states('sensor.tower_array_total') | float) *100) | round(2) }}
    unit_of_measurement: '%'

~~vs code validation errors galore: https://i.imgur.com/LQ8lwMj.jpg~~
(Just learned the vs code validation errors are annoyingly likely false positives.. so ignore this last part. Yaml still fails to load with errors in my logs like this:

while scanning for the next token found character '%' that cannot start any token in "/config/sensors.yaml", line 14, column 28
mapping values are not allowed here in "/config/sensors.yaml", line 9, column 12
obtuse zephyr
#

Why would you say VS Code errors are false positives

#

How are you including that file

obtuse zephyr
#

That issue is closed as fixed

brittle jacinth
obtuse zephyr
#

But the file you linked is concerned w/ template:

brittle jacinth
obtuse zephyr
#

If you want to split it like you did sensor:

template: !include template.yaml could go in your config

#

and then you pick up from line 2

brittle jacinth
#

Oh i see.. i need to include with template: !include template.yaml in order to have it evaluate template sensors.

I've historically done my inclusion in my config yaml like this:

automation: !include automations.yaml
binary_sensor: !include sensors_binary.yaml
climate: !include climate.yaml
group: !include groups.yaml
light: !include lights.yaml
media_player: !include media_players.yaml
notify: !include notify.yaml
sensor: !include sensors.yaml
script: !include scripts.yaml
switch: !include switches.yaml
zone: !include zones.yaml
obtuse zephyr
#

Gotcha, that's fine, you'll just need to add template to your list there w/ a new file

ruby vault
#
    - data:
        message: >-
          Outside Laundry Door is open
        title: Laundry
      service: notify.jurgen,notify.megan```

is this valid?
#

and double service line

#

Oh i see i need to include with

#
2023-02-18 11:24:59.318 ERROR (MainThread) [homeassistant.components.automation] Automation with alias 'Laundry Outside Door left open and nobody home' could not be validated and has been disabled: Service notify.jurgen,notify.megan does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']. Got 'notify.jurgen,notify.megan'

well, that answers that. πŸ™‚

inner mesa
#

no, it is not. you can create a notify group, though

ruby vault
#

I am trying to do this with an automation

    - service: notify.all
      data:
        title: person detected
        message: no one at home
        data:
          image: |-
            {% if trigger.entity_id == "binary_sensor.back_person_occupancy" %}
              /api/camera_proxy/camera.back_person
            {% elif trigger.entity_id == "binary_sensor.front_person_occupancy") %}
              /api/camera_proxy/camera.front_person
            {% else %}
              /api/camera_proxy/camera.webcam_person
            {% endif %}
#

but I keep getting the following error:

2023-02-18 16:42:43.412 ERROR (MainThread) [homeassistant.components.automation] Automation with alias 'someone appraoch the house and no one is home' could not be validated and has been disabled: template value should be a string for dictionary value @ data['action'][0]['data']. Got OrderedDict([('title', 'person detected'), ('message', 'no one at home'), ('data', OrderedDict([('image', '{% if trigger.entity_id == "binary_sensor.back_person_occupancy" %}\n  /api/camera_proxy/camera.back_person\n{% elif trigger.entity_id == "binary_sensor.front_person_occupancy") %}\n  /api/camera_proxy/camera.front_person\n{% else %}\n  /api/camera_proxy/camera.webcam_person\n{% endif %}')]))])
2023-02-18 16:42:44.733 ERROR (MainThread) [homeassistant.components.automation] Automation with alias 'someone appraoch the house and no one is home' could not be validated and has been disabled: template value should be a string for dictionary value @ data['action'][0]['data']. Got OrderedDict([('title', 'person detected'), ('message', 'no one at home'), ('data', OrderedDict([('image', '{% if trigger.entity_id == "binary_sensor.back_person_occupancy" %}\n  /api/camera_proxy/camera.back_person\n{% elif trigger.entity_id == "binary_sensor.front_person_occupancy") %}\n  /api/camera_proxy/camera.front_person\n{% else %}\n  /api/camera_proxy/camera.webcam_person\n{% endif %}')]))])

I am not following its problem. :\

#

ah, there is a rogue ) in tehre

#

argh, 30mins on a rogue ), the error was totally throwing me

tribal cedar
#

Hi guys, I have a motion sensor which goes to 'on' state when motion is detected. It stays in that state for a minimum of 10 seconds. I however have a use case where I'm working a 'light follow' mode where I want to know if motion was very recently triggered (recent as in the last 2 seconds, in order for the follow mode to work correctly). Because of the minimum 10 seconds state on my motion sensor, the best resolution I can get is 10 seconds which is too high, all I can know is that the sensor was triggered sometime in the last 10 seconds but no lower.

I set up a template sensor in my configuration.yaml that aims to give me what I want by looking at the last_updated key on the sensor, however it seems that the template sensors don't update frequently enough either and don't work as expected. Is there some docs on how often templated sensors update. Basically this block of template works in my developer tools section if i manually ensure the template is retriggered (by typing any characters in the dev template window), but it won't automatically update fast enough when in the configuration.yaml or when in the dev tools window (and when not helped along by typing characters to get it to refresh).

https://pastebin.com/XwxZmEf4

The dev tools say the following, but I assume keys like last_updated are not part of that listening?

This template listens for the following state changed events:
Entity: binary_sensor.motion_now_in_living_room

marble jackal
#

@tribal cedar The problem with your template is that now() or utcnow() are only evaluated on every whole minute, so your binary sensor will turn off somewhere between 2 second and 1:02 minuten after being turned on

#

A better solution will be to create a trigger based sensor which turns on when your motion sensor does, and has an auto turn_off after 2 seconds

#

In any case your template is overly complicated

#

This would do the exact same (inaccurate) thing as your current sensor

{%- set sensor = 'binary_sensor.motion_now_in_living_room' -%}
{{ is_state(sensor, 'on') and now() - states[sensor].last_changed < timedelta(seconds=2) }}
#

But what will work

template:
  - trigger:
      - platform: state
        entity_id: binary_sensor.motion_now_in_living_room
        to:  "on"
    binary_sensor:
      - unique_id: motion_sensor_turned_on_last_2_seconds
        name: Motion sensor turned on in last 2 seconds
        state: "{{ True }}"
        auto_off: "00:00:02"
cosmic hamlet
#

I got a text parsed template with lots of else if.

#

How can I make the script output one line

plain magnetBOT
#

@cosmic hamlet I converted your message into a file since it's above 15 lines :+1:

cosmic hamlet
#

oh when i get it in a template the \n are removed

barren jungle
#

Hi
Is it possible to get secret value inside template (template entities)?
Like equivalent of !secrets from yaml?

analog mulch
inner mesa
#

That's the only way I can think of. The short answer is no, you can't access secrets directly from a template

barren jungle
#

@analog mulch @inner mesa ok, thanks for the reply

neon bolt
#

Hello there, I have an issue with one of my scripts that launched that action at 1AM this morning

#
service: climate.set_temperature
data:
  target_temp_low: "{{ states('input_number.temperature_confort')| float(0) +1 }}"
  target_temp_high: "{{ states('input_number.temperature_max_mode_nuit')| float(0) }}"
  hvac_mode: heat_cool
target:
  entity_id: climate.nest
#

the trace tells that it was done, but the Nest value did not change

#

is there any way to check and retry after the first attempt ?

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

marble jackal
#

Please edit your message and format it as code

neon bolt
#

GRRR canadian Keyboard πŸ˜‰

marble jackal
#

You can copy them from the bot message if you can't find the right character on your keyboard

neon bolt
#

that's what I did, thanks for your help

marble jackal
#

You can use a repeat with a delay in it which performs it every x seconds until the data reported by the entity matches your requested data

neon bolt
#

how can I check that "the entity matches your requested data" part ?

#

is it normal that there is no check ? it's just a fire and forget ?

marble jackal
#

Yep, that's what it does

neon bolt
#

ho ...

marble jackal
#

Well, if the integration reports an error or warning, it will log it

neon bolt
#

I learned something

#

I don't have any trace at all, except the command was sent

#

but in log, no change was done to Nest

#

I did exactly the same commanda 2h later that worked

#

I really think I would need to achieve what you proposed

marble jackal
neon bolt
#

thanks, I will check that

sonic sand
loud mesa
#

Hey all, I'm getting an error in my logs about a template. Not sure where to even start to track this one down. Here's the log entry:

Logger: homeassistant.helpers.template
Source: helpers/template.py:575
First occurred: February 14, 2023 at 9:50:46 PM (5232 occurrences)
Last logged: 11:58:50 AM

Template variable warning: 'user' is undefined when rendering '{{user}}'

inner mesa
#

Seems clear enough

loud mesa
#

I don't recall setting any type of a templte up for use with a user...

rose scroll
sonic sand
acoustic arch
#

im trying to get mute and unmute working in a mushroom template chip
https://hastebin.com/share/yoqejeloho.yaml
I need `` is_volume_muted: true ` templated like i did with the iconcolor above, but somehow i cannot get it to work?

#

tap_action should do both

#

is the servicecall inside a frontend item templatable?

marble jackal
#

You can't use templates in a tap action

#

You can call a script and do the logic in there

marble jackal
acoustic arch
#

thank you.

#

ill call a script then. πŸ™‚

marble jackal
#

First, you don't need to do == true as it will already return true or false itself

#
  data:
    is_volume_muted: >
      {% if state_attr('media_player.receiver_huiskamer', 'is_volume_muted') %}
        false
      {%else%}
        true
      {%endif%}
acoustic arch
#

that looks better then my hacked together version πŸ™‚

marble jackal
#

You can't template a whole key: value pair like you were doing

#

You need to return a dict then, but it's easier to just template the value

acoustic arch
#

i thought it was going to write the whole string

#

you are sooo correct... yet again πŸ™‚

marble jackal
#

Yes, but that's the issue, it expects a dict, not a string

acoustic arch
#

ill pass this in a script and go from there

marble jackal
#

And you need to reverse the logic of the boolean value to unmute when it's muted

acoustic arch
#

i was thinking a IF THEN in the script

#

IF muted A. Else B

#

or a choose. both should work

marble jackal
#

And you can simplify it to:

  data:
    is_volume_muted: >
      {{ iif(state_attr('media_player.receiver_huiskamer', 'is_volume_muted'), false, true }}
acoustic arch
#

thats just shorthand right?

marble jackal
#

That's using the iif function

acoustic arch
#

ill have a read about that. thx!

acoustic arch
#

i think i can manage from ehre

#

have a great sunday

viral sierra
#

hello everyone,
I have an infrared transmitter that sends a temperature command to the air conditioning. for example I send 19 or 21 or I increase the FAN. I would like to know if there is a thermostat integration that allows you to bind this command to a thermostat. I'm not talking about PID type integrations. THANKS !

plain magnetBOT
tribal cedar
#

Is there a way I can create templated sensors, but in a loop. For each area I have I'm finding myself having copy/pasted a lot of templated sensors, with very little differences between them, usually an area name and an entity name differing only.

heavy crown
#

Hi, I am trying to help someone on the HA forum but what he is showing is beyond me.... an attribute is converted in python

#
from: '2023-02-19T00:00:00+00:00'
#

becomes

#
'from': datetime.datetime(2023, 2, 19, 0, 0, tzinfo=datetime.timezone.utc)
#

in his devtools > template .... any ideas from the specialists here?

dense swan
#

Anyone know where I am going wrong? I have a group of lights I ALWAYS want to keep on but at night when we trigger the "good night" automation I have an action to call lights.off and entity is set to all. I want to turn off all "on" lights EXCEPT those in the helper group. This isn't working and shows one of the devices I don't want to come back.

#
  | selectattr('state', 'eq', 'on')
  | rejectattr('entity_id', 'in', expand('light.group_keep_on_lights'))
  | rejectattr('attributes.entity_id', 'defined')
  | map(attribute='entity_id')
  | list  
}}```
#

I am getting back ['light.dimmer_dry_contact_relay', 'light.great_room_fan_light'] but expect just ['light.great_room_fan_light']

#

I can use this:

#
  | selectattr('state', 'eq', 'on')
  | rejectattr('entity_id', 'in', expand('light.group_keep_on_lights'))
  | rejectattr('entity_id', 'search', 'light.dimmer_dry_contact_relay')
  | rejectattr('attributes.entity_id', 'defined')
  | map(attribute='entity_id')
  | list  
}}```
#

But was hoping to use a group helper for wife factor.

limpid swallow
obtuse zephyr
#

state_attr('light.group_keep_on_lights', 'entity_id') will get you your entity_id list

dense swan
#

@obtuse zephyr how do I filter those out of the final returned list?

obtuse zephyr
#
{{ states.light 
  | selectattr('state', 'eq', 'on')
  | rejectattr('entity_id', 'in', state_attr('light.group_keep_on_lights', 'entity_id'))
  | rejectattr('attributes.entity_id', 'defined')
  | map(attribute='entity_id')
  | list  
}}
dense swan
#

Thanks!

obtuse zephyr
#

you bet

dense swan
#

@obtuse zephyr that is throwing TypeError: argument of type 'NoneType' is not iterable in the dev tools

obtuse zephyr
#

What does {{ state_attr('light.group_keep_on_lights', 'entity_id') }} return

dense swan
#

Null, that explains it

obtuse zephyr
#

πŸ™‚

dense swan
#

I mean there is an object in there.

#

That group has one device at the moment

#

I'd expect it to return the one device right?

#

Or do I need more than one to make the list work?

obtuse zephyr
#

{{ states.light.group_keep_on_lights }}

#

What's that show

dense swan
#

<template TemplateState(<state light.group_keep_on_lights=unavailable; supported_color_modes=[<ColorMode.ONOFF: 'onoff'>], icon=mdi:lightbulb-group, friendly_name=Group: Keep on lights, supported_features=LightEntityFeature.0 @ 2023-02-18T21:02:03.978964-05:00>)>

obtuse zephyr
#

Are all the lights in the group off?

#

err

dense swan
#

Yes, they are.

obtuse zephyr
#

like... disconnected/unavailable?

dense swan
#

Oh

#

Let me check

obtuse zephyr
#

If every device in a group is unavailable, that'll break like that

dense swan
#

<template TemplateState(<state light.dimmer_dry_contact_relay=on; supported_color_modes=[<ColorMode.BRIGHTNESS: 'brightness'>], color_mode=brightness, brightness=255, friendly_name=Richie Fan Light, supported_features=LightEntityFeature.TRANSITION @ 2023-02-18T21:51:40.548133-05:00>)>

#

The one device in that group is on

#

that light.dimmer_dry_contact_relay is the one device in that list atm

obtuse zephyr
#

Well, you can see it's reporting unavailable for that group state though... which is odd

dense swan
#

Yea, do I need to toggle the all entities in the group?

#

Or is HA returning a string when the template is expecting an array?

obtuse zephyr
#

The problem isn't w/ the template currently... it's why the group is returning unavailable, when you say there's only 1 member of the group and that member is on

dense swan
#

Is that a bug? πŸ™‚

obtuse zephyr
#

Doubtful.... can you check your group options for that light group

#

Also, check your home-assistant.log

dense swan
#

I have one member and hide members and all entities is off

#

Checking logs

#

Logs don't show anything but I don't have debug turned on.

obtuse zephyr
#

Could you try creating another light group, same member just to see

plain magnetBOT
dense swan
#

@obtuse zephyr trying now

#

That works...

#

Do I have a bad group or name in the old group?

obtuse zephyr
#

I don't see anything wrong with it

dense swan
#

Let me re-create it...

#

That worked...

#

So weird.

obtuse zephyr
#

Hmm, try restarting HA once, just to see if everything comes up ok

dense swan
#

Ok.

thorny snow
#

Howdy, is it possible to use templates to create a group by defining a entitiy.id suffix, so all sensor.XXXX_foo (suffix foo) will be added automatically?

dense swan
#

came up ok after restart

obtuse zephyr
#

Good, odd though

obtuse zephyr
thorny snow
#

i'd like tu sum all power-sensors.

thorny snow
obtuse zephyr
#

You can come up w/ a template to grab all sensor entities that match a pattern and sum them, again, its not actually a group though

dense swan
#

thanks for the help @obtuse zephyr!

obtuse zephyr
#

You're welcome

halcyon mountain
#

I have a Helper entity that receives the number of steps I take from a Shortcut on iOS based on the steps my Apple Watch records. I don't take walks with my phone as it is my unwind time. This works and my entity shows as input_number.steps and a State of current steps. I thought I could create a value_template to hold these steps for historical purposes. I tried this -

http://pastie.org/p/0i3SOcP3rmNhWMDpWZEcBC

but upon adding to sensors.yaml the configuration check just spins and I see an error in the log. So looking for ideas on how to do this.

inner mesa
#

I'm not clear on what 'hold these steps for historical purposes' means. The HA database already does that for the original helper entity.

halcyon mountain
#

Then maybe I'm looking at it wrong. I see the history in the entity but when I try and use a history graph card the help entity is not listed. The steps in the helper entity are a state rather than attribute. I think that is why.

inner mesa
#

Doubtful

halcyon mountain
#

I'm more like confused than sceptical.

inner mesa
#

I suppose it's possible that the UI entity picker for that card doesn't let you choose an input_number entity, but I don't know why that would be the case

arctic sorrel
#

I'd ensure you set a unit_of_measurement

#

That seems to be missing one, and that tends to result in them not being graphable

halcyon mountain
#

Hi Tinkerer, fan of your work, you mean in the Helper?

inner mesa
#

There are other issues with your sensor.

#

entity_id was deprecated long ago, and your indentation is off

#

And it's the legacy format

#

Looks like it was copied from somewhere

halcyon mountain
#

Yeh, I was copying what I found on an old forum post.

halcyon mountain
#

Looks like the History Graph Card doesn't support attributes as I suspected. My idea to create the template sensor is still where I'm headed. Thanks.

marble jackal
inner mesa
halcyon mountain
#

My Helper is the entity that I write the data from iOS into. It is stored in that entity as an attribute. It's just a place I use to dump the Number.

inner mesa
#

It's an input_number, right?

#

Those don't have attributes that you set

#

Anyway, if you have a solution...

halcyon mountain
#

It's a Number helper.

inner mesa
#

It only has a state

halcyon mountain
#

Sorry I said attribute above, you are right, it is state.

inner mesa
#

Right, you're off in the weeds with the whole attribute thing

halcyon mountain
#

Nothing new for me. I chase rabbits down holes all day.

#

It's learning I tell myself.

inner mesa
#

Like I said, maybe the card doesn't let you pick an input_number for some reason. Or maybe you need a unit_of_measurement. The link to the docs I listed above show how to create a sensor with a unit

halcyon mountain
#

Thanks @inner mesa . I'll keep moving along.

heavy crown
marble jackal
heavy crown
#

OK...thanks at least for the help!

mighty ledge
#

All python objects behave this way

#

So just use the str filter or isoformat

heavy crown
#

fixed now

mighty ledge
heavy crown
#

aha, top!

mighty ledge
#

When you have objects inside lists or dictionaries, it doesn’t try to type the listed objects, only the main list

#

So you get it’s string converted values, which are the repr

#

Which is usually meaningless in HA templates, but helpful when debugging in python

heavy crown
#

appreciating the explanation and already made a few comments in my 'notes' on templates πŸ™‚

plain magnetBOT
#

@brittle jacinth I converted your message into a file since it's above 15 lines :+1:

brittle jacinth
inner mesa
#

You didn't make a list

brittle jacinth
#

@inner mesa when you say "make a list" you mean with the hyphens?

inner mesa
#

Yes, as in the examples

brittle jacinth
#

PHEW. got it to work finally! thank you

plain magnetBOT
#

@stable wagon I converted your message into a file since it's above 15 lines :+1:

thorny snow
#

Hello there! I am having a problem with a sensor in the energy dashboard, the sensor or the battery is not showing, I am using a Lynx battery from GoodWe, and an ES Inverter; in the hass website already say that could have problems with it, and that I must use a template for getting the values, but, I am really new in this, and I can't make it show, here is the template I created, but, first, it do not show the values, and 2nd, it don't show on the energy dashboard as an option.

  - sensor:
      - name: "Entrada Salida Bateria"
        unit_of_measurement: "W"
        device_class: "power"
        unique_id: "sensor.battery_power_w"
        state_class: "measurement"
        state: >
          {% set e_s_battery = states(sensor.battery_power) | float %}

Any idea of what can I do?

marble jackal
#

You are not outputting anything, the only thing you are doing now is defining a variable

#

And please format your code as code

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

thorny snow
#

Done, do I make the outputting?

thorny snow
#

Oh! I see, sorry, I am really new, and learning while doing things... now i've don this :

  - sensor:
      - name: "Entrada Salida Bateria"
        unit_of_measurement: "W"
        device_class: "power"
        unique_id: "sensor.battery_power_w"
        state_class: "measurement"
        state: >
          {% set battery_w = states(sensor.battery_power) | float %}
          {{ battery_w }}

But I suppose something is wrong with it, as the template data say, Unknown. Any help?

analog mulch
#

Hi. Is it possible to set an atrribute value for a trigger template sensor manually (or through some service) like I can with the state using developer tools? I only need it to survive until the next trigger so that the new attribute value gets picked up by the template.

marble jackal
thorny snow
#

Thank you!

#

it actually works! it's showing the information, anyway, is not showing on the energy dashboard, on the Battery section....

plain magnetBOT
#

@thorny snow I converted your message into a file since it's above 15 lines :+1:

thorny snow
#

Sensor still not appear on battery in energy dashboard

hard venture
#

Alright... I figured out how to use a service call to increment/decrement a counter, but how do I actually reference the counter itself to use it? I want to brighten lights very slowly by dividing by counter, so I tried:
{{ (state_attr('switch.adaptive_lighting_living_room','brightness_pct') | int) / counter.morninglightdivisor }}
Which, I'm sure everyone here is screaming the same thing as the templates tool is: 'counter' is undefined.

marble jackal
#

states('counter.whatever') | int

hard venture
#

Ah. thank you.
Seems odd that everything is kept as a string and has to be converted to int, especially a "counter" that would be, by default, an integer, but, what do I know.

stable wagon
#

Okay trying to make it shorter. Why does my gauge card doesn't show the value from the template:

  - type: gauge
    entity: sensor.waschmaschine_program_progress
    title: Waschmaschine
    state_color: true
    value_template: >-
      {% set fortschritt = states('sensor.waschmaschine_program_progress') | float %}
        {% if fortschritt <98 %} {{ states('sensor.waschmaschine_program_progress') }}
        {% elif fortschritt >= 98 %} 100
        {% else %} Maschine aus
        {% endif %}
floral shuttle
marble jackal
#

You can't just put a value_template somewhere and expect it to work

stable wagon
#

I think I can πŸ™‚ maybe i'll be disappointed then ;-). Okay so I have to establish a Template Sensor to make it work...

heavy crown
#

example using a helper

#
type: custom:card-templater
card:
  type: gauge
  entity: input_number.sunsetmin
entities:
  - entity: input_number.sunsetmin
    state_template: '{{ states("input_number.sunsetmin") | int(0) }}'
chilly locust
#

Trying to add the word "ago" to the end of this, but the way I have it, it only works when both hours an minutes are present. If it's under 1 hour, it doesn't include it. Where should I put the text so that it always shows up?

{% set text = [phrase(days,'day'),phrase(hours,'hour'),
              phrase(minutes,'min')]
              |select('!=','')|list|join(', ') %}
{% set last_comma = text.rfind(',') %}
{% if last_comma != -1 %}
{% set text = text[:last_comma] + ' and' + text[last_comma + 1:] + ' ago' %}
{% endif %}
{{text}}
inner mesa
#

add it to the text variable outside the if

#

or just make the last line {{ text ~ ' ago' }}

ruby bolt
#

Is there a way to list all the entities that belong to a given zwave device using a template?
I have this trigger data in an automation and I'm trying to get the entities in that device so I can add/remove them from a light group. I have the node_id and device_id. I just can't figure out how to get the light in that device.

inner mesa
#

this works fine for me:

{% set id = device_id('lock.dr_door_lock') %}
{{ device_entities(id) }}
tepid onyx
inner mesa
#

You need to turn the new item into a one item list by surrounding it with []

#

{% set ns.items = ns.items + ['new_thing'] %}

tepid onyx
#

Yah I just figured that from searching from one of your examples in the past....Bit rusty. thanks though, thanks twice!