#templates-archived

1 messages · Page 67 of 1

worn dust
#

oh derp button on the top right, let me check

lethal bison
#

@worn dust under target:, change device_id: to entity_id:. When you erase the hash, and start typing "thermostat", it will autocomplete with the available entities under that heading

worn dust
#

the traces is showing code that I don't have in my template... this is what my automation has:

alias: Thermostat Automation
description: Set thermostat based on outside temperature
trigger: []
action:
  - service: climate.set_temperature
    metadata: {}
    data:
      temperature: |
        {% if 60 < 70 %} 68 {% elif 60 > 70 %} 75 {% endif %}
    target:
      entity_id: climate.thermostat
#

Oh wait I'm guessing traces shows the last run or something?

lethal bison
#

@worn dust Correct, you can walk through the last 5 executions, step by step

worn dust
#

Awesome knowing that will help a lot, I'll look into it and come back if I run into trouble. Thanks much.

wicked smelt
#

Can anyone help me. Trying to use rest but getting a error: Template variable error: 'value_json' is undefined when rendering '{{ value_json.state }}'

A rest sensor is like this:

The json looks like this:

{"state":"clean", "date":"06.02.2024 21:11:05", "line":1, "name":"data", "active_devices":"2", "working_devices":"2", "status_devices":"in_sync
in_sync"}

lethal bison
#

just 2 drives? need to beef up those numbers

wicked smelt
#

hehe, works for me and my home assistant I think 😄

#

But does anyone know i'm getting this error? The json are correct format?

lethal bison
#

I've never touched REST sensors, but it seems like the value templates may not be correct. From the provided JSON, all the elements are root-level elements, you may have to set up individual sensors

#

verify the example json is correct, I don' t think the last in_sync is valid

wicked smelt
#

you are absolutely right. I changed the in_sync line and it worked. Thanks alot!!

slender adder
#

Question is there a way to make it so that when a light in a area is on change icon?

lethal bison
#

that's already built in. "Color Icons Based on State"

#

You can couple that with the Header Toggle, or create your own custom card

undone jungle
#

@marble jackal the sensor of your designed worked just fine for two days, and all of a sudden became unavailable, even though the incurrent information is still incrementing just fine. Would you be willing to assist?

plain magnetBOT
#

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

marble jackal
#

That link doesn't work, but that template shouldn't result in unavailable

#

If it does, there must be an error in your log

undone jungle
#

I'll be looking into the logs now

#

Logger: homeassistant.helpers.sensor
Source: helpers/trigger_template_entity.py:208
First occurred: 17:40:03 (7 occurrences)
Last logged: 17:51:52

Error rendering state template for sensor.water_heating_gas_energy_consumption: ValueError: Template error: round got invalid input 'unknown' when rendering template '{% set to = trigger.to_state.state %} {% set from = trigger.from_state.state %} {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %} {% set previous = this.get('attributes', {}).get('previous', from | float) %} {% set delta = to | float(0) - previous %} {{ (this.state | float + delta * 11.474) | round(3) }} {% else %} {{ this.state | round(3) }} {% endif %}' but no default was specified
Error rendering state template for sensor.water_heating_gas_energy_consumption: ValueError: Template error: round got invalid input 'unavailable' when rendering template '{% set to = trigger.to_state.state %} {% set from = trigger.from_state.state %} {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %} {% set previous = this.get('attributes', {}).get('previous', from | float) %} {% set delta = to | float(0) - previous %} {{ (this.state | float + delta * 11.474) | round(3) }} {% else %} {{ this.state | round(3) }} {% endif %}' but no default was specified

#

It seems it got tripped up receiving an unknown into a number evaluation.

marble jackal
#

It failed on the round filter you added in the else part (which wasn't needed anyway)

undone jungle
#

Right, now I see how it made no sense....

#

It would have been rounded already.

marble jackal
#

And your version is also missing the default for the float filter I added in the last version

undone jungle
#

Is this the latest?

#

I am not sure in which statement.

#

The only float(0) I can see matches with mine, or am I wrong?

#

Should float in this statement also have a 0 default filter? {{ (this.state | float(0) + delta * 11.474) | round(3) }}

#

Or do you refer to the previous, where the float is produced after it being pulled from the attributes

#

This would make more sense to have a default, if the attribute previous would get lost at some point.

marble jackal
#

And because of the current state of the sensor as well

#

The old data wasn't correct BTW

#

It was counting double

dark kindle
#

Trying to template a delay action in a script based on a Duration field but can't find any examples nor getting it anywhere with randomly trying. Is this possible or go back to using a number and template a delay for just "minutes"?

inner mesa
mighty ledge
#
myscript:
  sequence:
  - delay: "{{ delay }}"

...

service: script.myscript
data:
  delay: "10:00:00"
#

most minimum example

#

script and the service call, calling the script

plain magnetBOT
#

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

dark kindle
#

(copied the wrong thing, field is named my_duration)

mighty ledge
#
  - delay: 
      seconds: "{{ timedelta(**my_duration).total_seconds() }}"
#

but then when you call it, you have to use

service: script.myscript
data:
  my_duration:
    minutes: 5
undone jungle
#

Should I thus add the {{ (this.state | float(0) + delta * 11.474) | round(3) }}

mighty ledge
#

you only need defaults if the code tries to convert a string to a number and it fails

#

if you account for that with your if statements, you don't need it

dark kindle
mighty ledge
#

I have no idea what you're asking

#

if you want to use the selector, you must use what a selector provides at all times

#

when you manually use the script

dark kindle
#

but the duration isnt defined if not passed in the data: so i guess not

mighty ledge
#

no, defaults are not passed. Fields and selectors are just for the users sake, they do not actually provide information to the script

#

I mean, if you use the selector it provides the information. But if you don't, nothing is provided.

undone jungle
dark kindle
mighty ledge
undone jungle
#

Exactly! And in Fes' sketche there isn't a default for the 'this.state' float

mighty ledge
#

so add one

undone jungle
#

Which is what I was trying to understand why he said it's needed but later said he updated the sketch without it. I know I can add it but also was trying to understand if my actions make sense.

mighty ledge
#

he probably just made a clerical error, it's easy to do w/ templates

marble jackal
#

Especially the attribute is changed, I used from_state.state there, but it has to be to_state. state

#

That will be from_state.state the next time it triggers

#

I included it to add the right delta if your source sensor has been unavailable

undone jungle
undone jungle
#

And finally, would you recommend using the default filter in the {{ (this.state | float(0) + delta * 11.474) | round(3) }} statement, since you've mentioned it being necessary.

marble jackal
#

It is the previous attribute

#

Yes, It's needed there

undone jungle
#

OK, so finally the filter is not needed in the to loop since it's tested for number in the if already and I'll add the default to the this.state

plain magnetBOT
#

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

stone lintel
#

Hi, I'm trying to create a binary sensor for a button push on my rf doorbell with the following yaml but it doesnt seem to be working, I'm using the UI to set up a helper

  event_type: esphome.rf_code_received
  event_data:
    code: d7aa3
  variables:
  to_state: on```
Is someone able to point me in the right direction please? The sensor just stays as off
marble jackal
#

That's a trigger, the template helper expects Jinja code

#

If you want to create a trigger based template binary sensor, you'll have to do it fully in YAML

stone lintel
#

Thanks, something like this?

  - trigger:
      platform: event
      event_type: esphome.rf_code_received
      event_data:
          code: d7aa3
    binary_sensor:
      - name: Front Door
        auto_off: 5
        state: "true"```
marble jackal
#

Yep

warm steeple
#

Does anyone have pointers at where to read up on how to work with the data in exposed_entities doing Jinja template stuff? Googling doesn't find me any useful dev documentation

marble jackal
#

What would you like to achieve?

plain magnetBOT
#

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

quasi frost
#

when i check the configuration yaml i got this message:
Konfigurationswarnungen
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 86: expected dictionary for dictionary value 'sensors->friendly_name', got 'nicht erfasste Verbraucher'
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 87: expected dictionary for dictionary value 'sensors->unit_of_measurement', got 'W'
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 88: expected dictionary for dictionary value 'sensors->value_template', got "{% if (states('sensor.heizungskeller_gesamtleistung')|float - states('sensor.gesamt_leistung_plugs')|float) > 0 %}\n {{ states('sensor.heizungskeller_gesamtleistung')|float - states('sensor.gesamt_leistung_plugs')|float }}\n{% else %}\n {{ 0 }}\n{% endif %}"
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 94: expected dictionary for dictionary value 'sensors->nicht_erfasste_verbaucher_template', got "{{ [ states('sensor.heizungskeller_gesamtleistung'), states('sensor.gesamt_leistung_plugs') ] | map('is_number') | min }}"

#

What is wrong?

marble jackal
#

you haven't provided the object id for the 2nd sensor

#
# first sensor:
sensors:
  power_import:
    friendly_name: "Power Import"
# 2nd sensor
sensors:
  friendly_name: "nicht erfasste Verbraucher"
#

@quasi frost see the difference?

quasi frost
#

just the postion?

summer arch
#

Is it possible to template the due date Param for a add new Todo service? I want to set a Todo to empty the vacuum so that my google nest setup tells me as a notification.

If you don't add a date then google doesn't put it on the calendar and the nest won't tell me to do it.

I need to use a template to get the current date and use that as the param

#

Is that possible?

quasi frost
#

ah no, the power import

marble jackal
# quasi frost just the postion?

no, the equivalent for power_import: is missing for the 2nd senosr.
BTW, you can put it allunder one platform: template line

- platform: template
  sensors:
    power_import:
      friendly_name: "Power Import"
    something_else:
      friendly_name: "nicht erfasste Verbraucher"
#

and you are using the legacy format, I would suggest to start using the modern template sensor format

quasi frost
#

how does it look like in the modern format?

marble jackal
# quasi frost how does it look like in the modern format?

you now have it under the sensor integration (possibly in a separate yaml). The new format uses the template ingegration
so it would be something like

template:
  - sensor:
      - name: "Power Import"
        state: >
          {{ your template }}
        availability: >
          {{ your availability tempplate }}
summer arch
marble jackal
#

you should be able to jsut use now().date()

summer arch
#

Looks like it worked

floral shuttle
#

just discovered that {{integration_entities('')}} actually has an output

#

[ "media_player.panasonic_viera_tv", "remote.panasonic_viera_tv" ], and I cant understand why that is

#

could it be the only integration that has a non existing id?

#

seems a bug really?

mighty ledge
#

not really

#

that just means an integration didn't register itself properly

#

the function looks at the entity registry

#

or the device registry, can't remember which

#

it looks at the entity registry

marble jackal
#

I also have quite a list there, but for me it's all the HACS update entities

mighty ledge
#

same here

#

but the code has a fallback

#

if it can't find a config_entry it falls back to the fallback

#

it tries to find the entry name from entity_sources which is a function in HA

thorny snow
#

divid Value Imput sensor

floral shuttle
#

or at least a chance for improvement

mighty ledge
#

it depends

#

the function has fallbacks and it outputs the fallbacks

#

so the function is working by design

#

which means it's not a bug with the function

floral shuttle
#

on that fallback: why does it list these 2 entities?

mighty ledge
#

because it outputs what I said above

#

it outputs the fallback of entity_sources

floral shuttle
#

sorry, but I dont understand that.... If you 2 see all HACS update entities there, how come I dont get these? (using HACS...)

sweet oasis
#

Hello, how to create an sensor, which will copy existing sensor, but only when existing will return value, and not copy, when existing is unavailable?

floral shuttle
#

no matter the reason, it seems useless to show these 2 entities, if (and they are) also properly output when using the actual integration name {{integration_entities('panasonic_viera')}} I just dont get why those would be any fallback at all.

floral shuttle
mighty ledge
#

it's literally in the code as "Fallback will grab a domain from entity_sources"

#

as a comment in the code

#

this is 100% by design

#

why are you feeding your template an empty string anyways?

floral shuttle
#

I am not... I always first type the structure and then fill that with relevant data. In dev tools template, not in the UI or so. Doing that, I noticed this unexpected (to me) output.

#

so the 'getting a domain' is just a random domain.. feels a bit arbitrary, or even funky if you ask me, to output some useless output. even if it is by design.

#

imagine any of our other templates do that....

#

seems a default of 'No integration set' would make more sense

mighty ledge
#

would you rather have an error?

#

or supply defaults?

floral shuttle
#

no, I'd rather have a useful default

mighty ledge
#

well, you go down that path and then we have to make breaking changes

#

by all means, make a FR

#

still not a bug though

#

as it's clearly the original design of the function noted by the comments in the function

floral shuttle
#

no, I see its no bug.

#

suppose it would not pass devs checks these days then

floral shuttle
slow vine
#

would this work for and conditions? I know i could do and in the template, I want to know what happens with this:

      - choose:
          - conditions: >
            "{{ condition1 }}"
            "{{ condition2 }}"
            sequence:
marble jackal
mighty ledge
#

so you can read the whole function

floral shuttle
#

yeah, sorry, didnt want to be a smart ass, I just noticed a difference in those sentences, and figured you might have copied something else. Np.

peak vector
mighty ledge
#

I'm not at home w/ my dev box

#

There's 2 calls i'm unfamiliar with, it's the entry grabbing portion and the entity_sources portion.

peak vector
#

I'm almost sure that's it. @tame niche you added the function, maybe it should not allow searching by the empty string?

#

Also, the config entry search is a bit meh because it will in a non-deterministic way (at least from the user's point of view) give you entities from one of many possible config entries with a matching title. I think it should either hand back none or all.

mighty ledge
#

if we really want to add it, couldn't we just add if not entry_name:...

#

Not sure how many people are searching for None though

#

which does return values for integrations I think, but I might be remembering device_id

peak vector
#

hehe

#

the context is that the integration_entities template function searches by config entry title

#

in many cases, integrations set the title to the emtpy string, and frontend just shows the integration name, so from the user's point of view it's not clear the config entry has no title

#

that might actually be the most common case evenprobably not

#

so, if you call integration_entities with the empty string, the result is the entities of the first config entry without a title

barren breach
#

Hi all. Can somebody help me out with this simple template?
`template:

  • sensor:
    • name: "DA_Wärmepumpe_Temp_Abfall"
      unit_of_measurement: "°K"
      device_class: "temperature"
      state_class: "measurement"
      state: "{{ state_attr('climate.luft_wasser_warmepumpe', 'current_temperature') - states('sensor.luft_wasser_warmepumpe_in_water_temperature')}}"`
      I want to substract this state attribute with the state. Each on their own seems to work but as a substraction it won't give back a number.
      Hope you can help. Thanks.
lyric comet
#

All states are strings so you need to convert them to numbers.

barren breach
#

aahhh, thanks a lot, so it needs to be casted

lyric comet
#
{{ (state_attr('climate.luft_wasser_warmepumpe', 'current_temperature') | float(0)) - (states('sensor.luft_wasser_warmepumpe_in_water_temperature') | float(0)) }}

You might not need to do the attr as those can be numbers, but I tend to cast them just in case.

barren breach
#

works! 😄

hard apex
#

Hi, I would like to get current action from entities on my climate group.
This code:

{{ expand('group.group_termostati') |  map(attribute='attributes.hvac_action') | list }}

produces this output:
[<HVACAction.IDLE: 'idle'>, <HVACAction.IDLE: 'idle'>, <HVACAction.IDLE: 'idle'>, <HVACAction.OFF: 'off'>]
while instead I was expecting:
[ 'idle', 'idle', 'idle', 'off]
Any way to convert the results in the needed values ?

#

this works fine for a single entity:

{{ states.climate.termostato_sala.attributes.hvac_action }}
inner mesa
#

I guess that's an artifact of moving to enums?

#

weird

hard apex
#

Probably, but single entity works fine is just map() that doesn't

inner mesa
#

yeah, I can't figure out how to pull out the values

mighty ledge
#

it's an enum, so name gets IDLE and value gets idle from the <HVACAction.IDLE: 'idle'> object

mighty ledge
#

They are weird

#

Basically what we see in the list is the string representation of the object, but when we access the object, it outputs the value

hard apex
#

Thx petro. I would have expected the same result and this took on the wrong road.

{{ expand('group.group_termostati') |  map(attribute='attributes.hvac_action') | map(attribute='value') | list }}

works as suggested

mighty ledge
#

Yeah it's a bit odd

#

but it's the nature of generators

#

they don't access the object they supply unless they don't have to

#

which is why we get the string representation of it

#

definitely an oversite by the dev team, but we can easily work around it

inner mesa
#

looks like map(attribute='value') only works on enums?

#

seems like a magic thing

hard apex
#

Should be documented for all users to find out easily

inner mesa
#

Should just be fixed somehow 🙂 The differing behavior and exposing implementation details is suboptimal

mighty ledge
#

Not sure how it could be fixed without completely breaking generators or changing the attributes from enums

#

and by breaking I mean, making them slower

lunar crater
#

do template sensors support the usage of an object_id ?

#

/ can i migrate them from a unique_id to another

marble jackal
#

What's the relation between object_id and unique_id?

lunar crater
#

i am not sure
for mqtt the unique_id is just whatever with the object_id being what the ui shows as object id

#

ie i have something like this for mqtt sensors

name: Outdoor Temperature
object_id: Temperature-Probe-68f6cee342a8 Celsius
unique_id: db68590e-13bb-404b-9846-b13e2329c7d1
#

but the documentation about template sensors doesnt mention this field

mighty ledge
#

they generate the object_id from the slug in the old template style

#

if the name isn't provided in the new template style, they are generated from the unique_id but slap a template_ before the unique_id

#

TLDR: Template sensors do not have an object_id field like MQTT entities do.

lunar crater
#

i see

#

i suppose its safe to touch the unique id field tho? (after the entity already wrote some statistics id like to keep)

#

i somehow ended up with a stroke writing one of them id like to correct / make into a uuid

name: "shellyem3_485519dc8561_channel_abc_power_consumption"
unique_id: "shellyem3_485519dc8561_channel_abc_powe_consumption"
#

oh no it seems to use the unique_id as statistics one

mighty ledge
#

Once you set a unique id, never change it

#

That’s what identifies it in the system.

lunar crater
#

.-. i suppose this requires careful db modifications

mighty ledge
#

What are you trying to do?

lunar crater
#

i would like to fix my unique_id to have either an r in power or replace it with a uuid if that id isnt visible anywhere on the ui

mighty ledge
#

If you’re trying to replace an entity but use the old db. Delete the entity and make sure the new one on instantiation has the same entity id as the only one

mighty ledge
#

You mean object_id?

lunar crater
#

i set the name and unique_id both for my template sensors as i started with this setup
but i do like the way how i have it for the mqtt one a bit more

#

so i thought i could make adjustments

mighty ledge
#

You have to make adjustments from the UI

#

Or delete the entity and let config_entries recreate it with new info

lunar crater
#

where do i find this config

lunar crater
#

just to make sure, if i am deleting a template entity over the frontend it does not remove the statistic does it

#

yay that seems like it did work

#

this is way too exiting for me ^^, thanks for your help!

mighty ledge
#

Sorry back to help

mighty ledge
#

the big thing is, don't change the unique_id. There's no reason to once you create something with it

#

If you don't like the unique_id, then you might be SOL. I've never had to deal with that level of change so I'm not familiar with the process

#

Although

#

What you could do....

lunar crater
#

i did end up commenting out the template, deleting the entity and recreating it with a new unique one
the statistics carried over which is what i care the most about

mighty ledge
#

ok

#

well then nm

lunar crater
#

not sure if there is something that internally uses the unique_id over the frontend that borks now

mighty ledge
#

well history and statistics should use the enitty_id

lunar crater
#

but so far my dashboards look unsuspicious

mighty ledge
#

so, deleting and recreating should work

#

what you DON'T want to do, is rename the old then craete the new one with the old name

#

because that will just carry the history to the new renamed entity

#

you specifically have to delete the old one

#

so that it doesn't carry to something else

lunar crater
#

i am not sure wether or not i like the helper entities when working with templates

#

it feels like modifying the same stuff in two places, especially if something depends on a riemann sum

#

waait i just saw there are template helper 😮

#

Thats like significantly better ^^

mighty ledge
#

It has drawbacks though

#

limited options, etc

lunar crater
#

ill keep that in mind

#

for now i just need it for splitting grid supply and return from a shelly

floral shuttle
#

ofc you know Erik, just for the others to share, and linked to the discussion here

plain magnetBOT
#

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

spring pollen
#

device_class: power was breaking it. Something changed with that maybe, since it worked before? Either way it works now

mighty ledge
#

You should be using a binary sensor with device class power, outputting a result of on or off

fervent hemlock
#

I do not know where to start looking...
I use a helper to input_number through a slider, that I use to set the time in active directory when my sons computertime should end. The number is the hour in 24 hour format. That works perfekt. The slider is for me and my wife to easy be able to extend for one hour
But now my son would like to get a heads up 10 min before his computer turns of.
So i got the helper input_number.computertime_stop that equals 19. And I need to get a datetime = "18:50:00" to use in a trigger. Any hints on what to search for or ideas for a template?

lyric comet
#

I normally set up a template sensor like:

#
  - name: Timer Offset
    state: "{{as_datetime(state_attr('timer.timer','finishes_at')) - timedelta(minutes=10)}}"
    availability: "{{state_attr('timer.timer','finishes_at') is not none}}"
    device_class: timestamp 
lofty mason
fervent hemlock
warm steeple
#

Anyone had luck creating a dict and referencing it later in the same template?

#

Specifically with the key being a variable, that seems to be the tricky part

inner mesa
#

like this?

{% set foo = "bar" %}
{% set mydict = {foo: "blah"} %}
{{ mydict.bar }}
#

-> blah

warm steeple
#

-> {'bar': 'blah'}

#

So a scoping issue, I'm assuming

inner mesa
#

yes, you need to use a namespace if you want something in a for loop to be available outside it

#

this will probably do what you expected:

{% set ns = namespace(mydict={}) %}
{% set foo = "bar" %}
{% set ns.mydict = {foo: "blah"} %}
{% for name in areas() %}
  {% set ns.mydict = {name: loop.index} %}
{%endfor %}
{{ns.mydict}}
#

it's overwriting the initial assignment

warm steeple
#

Well, that's still farther than I've gotten 🙂

#

Ha, figured it out.

#

{% set ns = namespace(mydict={}) %} {% set foo = "bar" %} {% set ns.mydict = {'None': 0} %} {% for name in areas() %} {% set foo = {name: loop.index} %} {% set ns.mydict= dict(ns.mydict.items(), **foo) %} {%endfor %} {{ns.mydict}}

warm steeple
#

Extra ) at the end

#

)}}

#

Hmm,nvm

warm steeple
#

What error are you getting?

summer arch
#
Executed: February 9, 2024 at 11:18:46 AM
Result:
params:
  domain: todo
  service: add_item
  service_data:
    item: Empty Vacuum
    due_date: '2024-02-09'
    entity_id:
      - todo.home_assistant_notifications
  target:
    entity_id:
      - todo.home_assistant_notifications
running_script: false
#
service: todo.add_item
metadata: {}
data:
  item: Empty Vacuum
  due_date: "{{now().date()}}"
target:
  entity_id: todo.home_assistant_notifications

#

My automation trigger set a Todo task in my google tasks for 8/2/24 instead of 9/2/24

#

Where did I go wrong

summer arch
#

Even hard coding the date is wrong. Looks like bug in google tasks integration?

warm steeple
#

off-by-one maybe?

lethal bison
#

Trying to do math with an input_number. For testing, input_number.disco is set to 130
{{ (60000 / int(states.input_number.disco_bpm.state)|round(0)) }} should return 461, but doesn't round - I get 461.53846153846155

inner mesa
#

You just rounded the state

lethal bison
#

oh, shit I see it now

#

fixed, thanks! {{ (60000 / int(states.input_number.disco_bpm.state))|round(0)}}

summer arch
slow vine
#

is one of these better than the other?

"{{ is_state('input_select.which_room', 'living_room') }}"
"{{ states('input_select.which_room') in ['living_room'] }}"

I prefer the second way because I am using it in other parts of the script with a real list ['living_room', 'den', 'kitchen'] etc...

inner mesa
#

the equivalent to the second example using is_state is "{{ is_state('input_select.which_room', ['living_room']) }}"

#

in other words, you can provide a list of possible states there, and I think that's the preferred way

summer arch
#

How to add one day to now()?

I want to get tomorrow's date

mighty ledge
#

(today_at() + timedelta(days=1)).date()

#

if you just want the date

summer arch
#

That did the job thank you.

#

Looks like the Google task implementation has a off by one bug. Calling add Todo for today sets a Todo for yesterday

light scroll
#

Can someone please explain why this template is not entirely correct? I don't want it to be reported if it is within a range.

  - sensor:
      - name: "house_energy_consumption"            
        unit_of_measurement: "kWh"
        state_class: total_increasing
        device_class: energy       
       # availability_template: "{{ (states('sensor.energy_consumed_tariff_1') | float(0) | round(2)) + (states('sensor.energy_consumed_tariff_2') | float(0) | round(2)) > 11000 }}"
        availability: "{{ states('sensor.energy_consumed_tariff_1') | float(0) | round(2)  +  states('sensor.energy_consumed_tariff_2') | float(0) | round(2) > 11000  }}"
        state: >
          {% set A = states('sensor.energy_consumed_tariff_1') | float(0) | round(2) %}
          {% set B = states('sensor.energy_consumed_tariff_2') | float(0) | round(2) %}
          {% if (A + B) > 0 -%}
            {{ (A + B) }}
          {% else %}
            unavailable
          {%- endif %}```
#

availability_template doesn't work. so what did I messed up?

mighty ledge
#

availability_template isn't valid for new template styles

#

availability does the same thing, so you're using the correct field

#

why are you rounding the value?

#
template:
  - sensor:
      - name: "house_energy_consumption"            
        unit_of_measurement: "kWh"
        state_class: total_increasing
        device_class: energy       
        availability: >
          {% set a, b = ['sensor.energy_consumed_tariff_1', 'sensor.energy_consumed_tariff_2'] | map('states') | list %}
          {{ a | is_number and b | is_number and a | float + b | float > 11000 }}
        state: >
          {{ ['sensor.energy_consumed_tariff_1', 'sensor.energy_consumed_tariff_2'] | map('states') | map('float') | sum | round(2) }}
#

or you can just use the sensor group helper using the Sum option.

#

without the template

light scroll
#

thanks, will try it, and rounding is not necessary, will remove it.

marble jackal
#

wait, unless one of them is above 11000 of course

#

scrap that 🙂

mighty ledge
#

unless you're syaing to make that the availability

marble jackal
#

yeah, it thought this might be a one step approach for the availability, but if one of the sensors is above 11000 you still get unexptected results

mighty ledge
#

no, because the and doesn't make the rest of it evaluate

marble jackal
#

I meant with only my version

mighty ledge
#

oh ok

#

There's a number of ways to handle the availability, I always go with the most optimized (if I see it)

#

optimized for speed that is

light scroll
#

that is a really nice thing in your code 'is_number' appreciated that!

mighty ledge
#

you can use is_number as a mapped filter too, but it doesn't help in this case

mighty ledge
light scroll
#

i will look into that for my esphome sensors that is feeding this energy sensor.

#

haha!

marble jackal
#

no worries 🙂

mighty ledge
sonic ember
#

I'm having a data type error that I'm not sure how to solve, but I think I have an idea. I have this template:

    - unique_id: solar_forecast_estimate_current_hour
      name: Solar forecast current hour
      state: >
        {% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %}
        {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%}
        {% set data = watts.items() %}
        {{watts[nu] if nu in watts else 'No production estimated'}}
      icon: mdi:sun-clock
      unit_of_measurement: W
#

And this is the error I get:
ValueError: Sensor sensor.solar_forecast_current_hour has device class 'None', state class 'None' unit 'W' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'No production estimated' (<class 'str'>)

marble jackal
#

sensors with a unit_of_meaurement should output a numeric state

#

No production estimated is not a numeric state

sonic ember
#

I guess it makes sense, since that's a string, and I want this sensor to have a float.

#

Exactly. So do I just make it a "0" or just accept an unavailable or?

#

I actually don't even know why I need a fallback

marble jackal
#
    - unique_id: solar_forecast_estimate_current_hour
      name: Solar forecast current hour
      state: >
        {% set nu = today_at().replace(hour=now().hour).isoformat() %}
        {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts') %}
        {{ watts[nu] }}
      icon: mdi:sun-clock
      unit_of_measurement: W
      availability: >
        {% set nu = today_at().replace(hour=now().hour).isoformat() %}
        {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts') %}
        {{ watts is not none and nu in watts }}
sonic ember
#

Ooo thanks!

#

That's more complex than I was thinking, but makes sense

marble jackal
#

don't know why you were defining the data variable

#

you were not using it

sonic ember
#

I forget. I must have taken this from another example and changed it for my own needs, and then not removed that part.

#

It's a while ago

tame axle
#

How can I get the zone of the current user? Something like
{{ zone_id('user') }}

fleet viper
#

Is there a way on a notification to convert a sensor in minutes to a more human friendly text? i.e. sensor = 121 minutes, send 2 hours, 1 minute.

i would liek to avoid creating a helper sensor for this and do it in the notification automation itself

lucid thicket
lofty mason
#

Markdown card does support a {{user}} var of the person viewing it. But otherwise in many places a user is not even a relevant concept for a template, it may be running where there is no user.
Probably want to elaborate on where you have this template, and what is the use case.

lucid thicket
# fleet viper Is there a way on a notification to convert a sensor in minutes to a more human ...

Maybe something like this:

{% set seconds = states('sensor.minutes_until_something') | float * 60 %}
{% set years = seconds // 3153600 %}
{% set days = seconds % 3153600 // 86400 %}
{% set hours = seconds % 86400 // 3600 %}
{% set minutes = seconds % 3600 // 60 %}
{{ '%dy ' % years if years else '' }}{{ '%dd ' % days if days else '' }}{{ '%dh ' % hours if hours else '' }}{{ '%dm' % minutes }}

Modify to your liking

fleet viper
lucid thicket
#

Use the dash at the front of each line. {%-

#

Or maybe at the end. Or both.

fleet viper
#

so replace {% with {%- ?

fleet viper
#

cool, got it ty

#

code is not the prettiest but the notification looks great!

lucid thicket
#

There is a macro by TheFes if you want something much more powerful that’s fairly simple to use

tame axle
#

*sorry for ping i was too sleepy to realize

lyric comet
#

A post on the general forum reminded me I need to strip out all my Weather reporting as for no reason I could understand the Forecast stuff is being removed from the Weather Entity, before I do I just wanted to check there is no way to pull a service response in a Jinja Macro, with out having to change all the automations and scripts which use it. Has anyone got around this at all? My current thought is to use MQTT to get the response and put it in a MQTT sensor every half hour or so.

marble jackal
#

@lyric comet You can put them in a template sensor without the use of MQTT. Trigger based template sensors support an action section, and variables created there are carried over to the sensor section

summer arch
#

Hi, want to check my understanding of self referencing

- unique_id: phone_wifi_status
    state: "{{ is_state('sensor.sensor.phone_wifi_connection', 'TP-Link_5DF8') }}"
    delay_off:
      minutes: 2
    device_class: presence
    icon: |
      {% if is_state('this', 'on')%}
        mdi:wifi-check
      {% else %}
        mdi:wifi-cancel
      {% endif %}
#

The usage of this will just self reference this sensor

lucid thicket
marble jackal
#

Then.. this is the full state object, to use it in that template, you need to use this.entity_id

#

you could also use this.state == 'on'

#
icon: "{{ 'mdi:wifi-check' if this.state == 'on' else 'mdi:wifi-cancel' }}"
summer arch
#

oh wait

#

is that a stray )

summer arch
marble jackal
#

remove the quotes around the template which does the output

summer arch
marsh cairn
#

Multiline templates without quotes, single-line templates with quotes

#
state: "{{ true }}"
state: >
  {{ false }}
north locust
#

anyone know how to turn this into a REST sensor ?

{"message":"ok","data":{"id":716,"ping":6.49,"download":202.3896,"upload":186.52,"server_id":41001,"server_host":"drt-speedtest-b.voiped.eu:8080","server_name":"Voiped Telecom","url":"https:\/\/www.speedtest.net\/result\/c\/ea5c16d5-6633-491a-82da-1b23f2c64ec3","scheduled":false,"failed":false,"created_at":"2024-02-10T14:20:43.000000+01:00","updated_at":"2024-02-10T14:20:43.000000+01:00"}}
#

tried this but no output :

rest:
  - scan_interval: 60
    resource: http://192.168.188.46:8844/api/speedtest/latest
    sensor:
      - name: "Downloadx"
        value_template: "{{ value_json.download }}"
inner mesa
#

Looks like you want {{ value_json.data.download }}

north locust
#

ah ty

#

can i give them an icon as well ? and should i put them in a device_class ?

#
    sensor:
      - name: "DownloadX"
        value_template: "{{ value_json.data.download }}"
      - name: "UploadX"
        value_template: "{{ value_json.data.upload }}"
      - name: "PingX"
        value_template: "{{ value_json.data.ping }}"
lyric comet
#

I am currently writing a script to enqueue an album based on the current track playing extracting the information from the media_content_id. I can use urlencode() to build the new format, but I need to decode the media content id, but urldecode() does not exist when I try to use it. Is there an equivalent or a work around please. I know I could just do spaces but I am bound to come across some ampersands or similar.

hexed galleon
#

Is there any way to use a template as a condition for the conditional card?

inner mesa
summer arch
#

Hi. I am looking to setup a cast notification for when some tasks finish.

I put on the washing machine and vacuum while I am out, I come home and want the cast to tell me "while you were out the washing machine and vacuum finished". What is the easiest way to handle this? What if only one finishes while I am out?

I thought maybe a template sensor with a list of notifications? Which I can then set and get from various automations to result in

"Hi, while you were out [] and [] and... Finished their tasks"

#

Figured templates would be the place to help

#

I imagine I would need to have a trigger sensor and then pull some information from the trigger event (entity name probably) then add that entity name to the list. However when I need print out the string I will need to clear the sensor

#

Also how would I programatically build the string? I know individually how to for loop and set variables but not how to append strings etc

#
set string = "Hi, while you were out list[0]"
for list[1] to list.end
  string += ", and list[i]"
string += " finished"
return string
#

I took a stab but absolutely no clue

plain magnetBOT
#

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

summer arch
#
2024-02-11 15:41:01.555 WARNING (MainThread) [homeassistant.components.sensor.helpers] sensor.completed_tasks rendered invalid timestamp: ['entity_id', 'state', 'attributes', 'last_changed', 'last_updated', 'context', Undefined]
plain magnetBOT
#

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

keen ruin
#

I want to get a list of lights that are on in an area. I get it to work, but one of the light are a helper that combines two lights into one. I can't get it to show up. Why?

This gives me the list i want. But the helper isn't showing:
{{ expand(states.light) | selectattr('entity_id', 'in', area_entities('Vardagsrummet')) | map(attribute='entity_id') |list }}

This gives me a list of all entities in an Area, but the helper is still not showing!
{{ expand(states) | selectattr('entity_id', 'in', area_entities('Vardagsrummet')) | map(attribute='entity_id') |list }}

inner mesa
#

You're trying to use that as the state?

#

States are limited to 255 characters. The logs would show that

keen ruin
inner mesa
#

You said 'the helper isn't showing'

#

Whatever that means

summer arch
keen ruin
# inner mesa Whatever that means

{{ expand(states.light) | selectattr('entity_id', 'in', area_entities('Vardagsrummet')) | map(attribute='entity_id') |list }}

Gives me this list:
['light.vardagsrummet_vitrinskapet', 'light.vardagsrummet_fonstret_2', 'light.vardagsrummet_fonstret_1', 'light.vardagsrummet_taklampan', 'light.vardagsrummet_golvlampan', 'light.vardagsrummet_pa_tv_banken']

I have combined 'light.vardagsrummet_fonstret_2', 'light.vardagsrummet_fonstret_1' to one light with a helper, i think it is called lightgroup. This is named 'light.vardagsrummet_fonstret'

inner mesa
#

You can't use a template just anywhere

keen ruin
inner mesa
#

What is wrong? What did you expect?

keen ruin
#

'light.vardagsrummet_fonstret' should be in the list

inner mesa
#

It's a weird way to do that

#

{{ area_entities('Vardagsrummet')|seiect('is_state', 'on')|list}}

#

But it sounds like the helper simply isn't in the area

#

You could verify that

#

Just lights:
{{ area_entities('Vardagsrummet')|select('match', 'light.')|seiect('is_state', 'on')|list}}

keen ruin
inner mesa
#

I don't know. They should be the same

keen ruin
#

I am not that experienced but this feel like a bug to me

inner mesa
#

Mine is much more efficient

keen ruin
inner mesa
#

BTW, states and states.light are both already collections of state objects, so calling expand() on them doesn't make sense

#

I don't know what that's actually doing for you, but perhaps that's not doing what you expect 🤷

keen ruin
inner mesa
#

Lots of garbage out there

keen ruin
summer arch
#

Hi. I am looking to setup a cast

#

Made a thread so that all my intermediate answers to myself don't get lost while waiting for help

dense breach
#

Hi guys I am having problem with my home assistant I want to use 1 input of impulse sensor for multiple outputs cause I need impulses and water flow L/minute but when I am using -platform: template sensors: I get error message --> [sensors] is an invalid option for [sensor.template]. Please check the indentation. Does anyone know how to solve this ?

marble jackal
#

We might be able to if you would post your YAML

plain magnetBOT
#

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

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

dense breach
#

@marble jackal u mean whole config

summer arch
dense breach
#

ok I ll post it

#

so how do I do it

marble jackal
#

Using one of the links above

dense breach
#

here is link

#

I am finding answer almost for 2 days

#

so you are my last chance

#

@marble jackal thx for help

marble jackal
#

You are placing the sensor config for an Home Assistant template sensor in an ESPHome config

#

That won't work

#

Furthermore, ESPHome doesn't support Jinja

dense breach
#

so is there any way I can use same pin like GPIO13 multiple times

#

I want to get Water flow pulses and second gauge I need for L/minute

#

@marble jackal

#

do you know how to do it

marble jackal
rugged robin
#

Hey,
is there a way to loop through all entities with a certain device_class?
I want to get a list with all humidity sensors with humidity higher than a certain value

lyric comet
#

Something like this?

{% set sensors = states.sensor 
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'humidity') 
| map(attribute='entity_id')
| list
 %}
 {%for sensor in sensors%}
   {{sensor}}
 {% endfor %}
rugged robin
#

wow thats nice, it works 🙂

#

thanks

lyric comet
#

BTW You could also add a select() to filter down to the ones over the value.

marble jackal
lyric comet
#

Thanks TheFes. I thing I normally filter for ON/OFF so not a problem, but you are of course correct as aways, sorry.

coral garden
#

Does anyone here know if it's possible to dynamically change groups using the new group integration? The old integration group.group_of_things had a service call that allowed changing of group members but it seems the new group integration light.group_of_things doesn't seem to have the same functionality

inner mesa
coral garden
#

yes but people here in templates know lots of things I shall ask in integrations

inner mesa
#

It will still be no

coral garden
#

I have been x'd

inner mesa
#

Posting in a random channel because you think there are smart people there is...weird and wrong

coral garden
#

well I'd like to make a template that dynamically selects lights as members of a group depending on device state and time of day and then have an automation that acts on that group

#

since I'm just adjusting light properties, I wonder if I can just dynamically modify an input_text of entity_ids and pass that to the light.turn_on service call

leaden swan
#

So I trying to get my Google home to respond based of a sensor value but I don't understand and have hard time figure it out I have a script that is this ```service: tts.google_en_com
data:
message: blodsockret är {{states('sensor.last_glucose_level_mmol')}}.
cache: false

But I don't get it to run
arctic sorrel
#

You need to quote templates

#
service: tts.google_en_com
data:
  message: "blodsockret är {{states('sensor.last_glucose_level_mmol')}}."
  cache: false
inner mesa
#

Not that one

arctic sorrel
#

Also, check your log for errors or warnings

inner mesa
#

You only need to quote it if the {{ is at the beginning to avoid it looking like a dict

arctic sorrel
#

Ah, interesting

#

Still, the log will help here

#

Probably ||the lack of a media player target||

inner mesa
#

And 'don't get it to run' is void of any detail

leaden swan
#

Of course I forgot the media player target

#

Ok got this and the script runs without any error ```service: tts.speak
: {}
entity_id: tts.bs
data:
media_player_entity_id: media_player.kok
cache: true
message: >-
service: tts.google_en_com data: message: blodsockret är
{{states('sensor.last_glucose_level_mmol')}}. cache: false

arctic sorrel
#

that looks badly formatted

leaden swan
#

Well got it working now so I'm happy 🙂 now I'm just wondering if I'm able to take the sensor value and divide it or is it not possible to do math calculations?

inner mesa
#

If you covert the state to a float with |float(0) you can perform math on it

leaden swan
#

So if I want to devide it by 10?

inner mesa
#

Do that

leaden swan
#

I realise I want to make a helper because I need to use it in my dashboard

#

But I can't grab my head around it how to do it

inner mesa
#

math is done the same pretty much everywhere

#

there are also docs in teh topic

#

here

#

{{ states('sensor.last_glucose_level_mmol')|float(0)/10 }}

undone jungle
#

Dear all, how would I go about updating the icon_template variable to the new schema?

    - name: "Charging time remaining"
      unique_id: "x5_xdrive50e_custom_charging_time_remaining_formatted"
      state: >
        {% if is_state('sensor.x5_xdrive50e_charging_end_time', 'Unknown') %}
          {{ '' }}
        {% else %}
          {{ states('sensor.x5_xdrive50e_charging_time_remaining') | int | timestamp_custom('%H:%M', false) }}
        {% endif %}
      icon_template: >-
        {% if is_state('sensor.x5_xdrive50e_charging_end_time', 'Unknown') %}
          mdi:clock-outline
        {% else %}
          mdi:clock-end
        {% endif %}
#

icon_template doesn't seem to be support as it used to, anymore.

inner mesa
undone jungle
#

I've looked through but failed to find it. Now I see there was even an example

#

Thank you and sorry for a simple solution I could have found myself.

#

Didn't use the right keywords...

leaden swan
#

@inner mesa thank you, now I just need to figure out how to take down some decimals

inner mesa
#

|round(2)

leaden swan
#

{{ states('sensor.last_glucose_level_mmol')|float(0)/10|round(2) }} is that correct?

inner mesa
#

You need to add parentheses around what you're rounding

leaden swan
#

Don't get it but maybe will figure it out :p

#

Ah got it 🙂

#

Much thanks!

leaden swan
#

Is there anyway to respond to the Google home you ask or do it need to be a fixed media player

undone jungle
plain magnetBOT
#

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

undone jungle
#

I'd like to expand the first statement to include situations when the variable for charging end has passed, since the integration doesn't nullify the sensor when the charging is done.

#

Technically what is already in the if should suffice, but I am not 100% if there is some delay in the charging status updating, while the time sensor is already changing.

marble jackal
leaden swan
#

But rly cool

fervent hemlock
#

I got some great help the other day, thanks. But now I end up with an other problem.
I have a slider where I set the hour when my sons computer will turn off. At normal schooldays that is 21:00, but friday and saterday it's 23:00:
And my son wants a 5 min heads up from Google Display. And I set up an automation that worked during the week.
The template I use to get the correct time is
{{ today_at(states('input_number.computer_time_stop')|int|string + ":00") - timedelta(minutes=5) }}
But this friday I extended his time to 24:00 and that's the same as 00:00. But computers do not think 24:00 exist.
I thought if I could subtract 1 hour and add 55 minutes and delete the timedelta part. But I can't figure it out...
Anyone has a good idea?

inner mesa
#

23:59?

fervent hemlock
# inner mesa 23:59?

The "problem" is that the slider is from 1 to 24, so that's the value I have to work with

fervent hemlock
lyric comet
#

Why not use a time helper rather than a number helper.

fervent hemlock
slow vine
#

is this the way to use response_variable:

- service: shell_command.my_command
  data:
    response_variable: my_command_response
- service: input_text.set_value
  data:
    entity_id: input_text.response
    value: "my_command_response: {{ my_command_response['stdout'] }}"

I think it should work but the input text is just blank.

lyric comet
#

response_variable is not within data

#
metadata: {}
data:
  folder: "{{folder}}"
response_variable: response
slow vine
#

I see. I fixed it, but still something is wrong. Its not setting. (it works without the template)

marble jackal
plain magnetBOT
#

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

floral shuttle
#

is this new to to logger?:```
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'friename').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'friname').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'frname').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'fname').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'name').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>

#

check the friendly_name it is parsing, character by character

marble jackal
#
      state: >
        {% set charging_start_time = states.binary_sensor.x5_xdrive50e_charging_status.last_changed %}
        {% if is_state('binary_sensor.x5_xdrive50e_charging_status', 'on') and now() > charging_start_time %}
            {{ (now() - charging_start_time).total_seconds() | int  }}
        {% else %}
          0
        {% endif %}
undone jungle
#

The problem I am trying to resolve is to determine the start time, while the BMW integration is terrible at timely updates.

#

Some entities pop in to the next state immediately, some even spam the same information, but others update way way to long to be useful.

undone jungle
#
    - name: "Charging time remaining X5 50e formatted"
      unique_id: "x5_xdrive50e_custom_charging_time_remaining_formatted"
      state: >
        {% if is_state('binary_sensor.x5_xdrive50e_charging_status', 'off') or states('sensor.x5_xdrive50e_charging_end_time') in ("unavailable", "unknown") %}
          {{ '' }}
        {% else %}
          {{ states('sensor.x5_xdrive50e_charging_time_remaining') | int | timestamp_custom('%H:%M', false) }}
        {% endif %}
      icon: >-
        {% if is_state('binary_sensor.x5_xdrive50e_charging_status', 'off') or states('sensor.x5_xdrive50e_charging_end_time') in ("unavailable", "unknown") %}
          mdi:clock-outline
        {% else %}
          mdi:clock-end
        {% endif %}
#

Would it then make sense to use this sensor for formatting the time stamps ?

plain magnetBOT
#

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

olive meteor
#

How can I add a default to the following template (to account for initial errors when last_triggered is none)? I've tried a number of things I've found in the forum, but none have worked. Thanks! {{ now() - state_attr(this.entity_id, 'last_triggered') > timedelta(hours=3) }}

marble jackal
#

you can use this.attributes.last_triggered instead of using state_attr(). That attribute will always exist.

marble jackal
shadow summit
#

Hi all. Trying to create my first custom sensor but doesn't seem to be saving? I've verified that the code works in the template area but when I add the code to configuration.yaml and restart, the new sensor isn't showing in entities. Do I need to do any additional steps? From what I've looked at, I was assuming I wouldn't need to do anything more.

inner mesa
#

Share the code

plain magnetBOT
#

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

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

shadow summit
marsh cairn
#

The sensor's state is definately unknown when away and numerical if present?

inner mesa
#

I just put exactly that in my config and it works fine:

inner mesa
#

I don't have those entities, of course

marsh cairn
#

However, I would go with a binary sensor

#

for presence

shadow summit
#

What were the exact steps you took after altering config.yaml?

inner mesa
#

I already have template entities, so I pasted it in my templates.yaml and reloaded template entities

#

I suggest looking at the HA logs

shadow summit
#

should I have a templates.yaml? Because I don't.

inner mesa
#

you don't need it

shadow summit
#

ok and probably one more noob question, sorry. where do i find the logs? 'Logbook' doesn't seem to be the right place to look

marsh cairn
#

This would create a binary sensor for presence. Does that work for you?

template:
  - binary_sensor:
      - name: "Adam Car Presence"
        unique_id: 51639777-f8dc-4252-8c8f-b0a255fa220e
        device_class: presence
        state: "{{ states('sensor.esphome_web_f0c630_ultrasonic_sensor')|is_number }}"
#

Yeah. just realized that when pasting 🤣

inner mesa
#

I can't point out what's wrong if you keep fixing it 🙂

shadow summit
#

I got it working. I needed a full restart rather than just the light yaml restart.

#

Thanks for your input!

inner mesa
#

okay, you said you restarted

#

reloading YAML entities isn't a restart

shadow summit
inner mesa
#

I sure wish that logs like this told you what entity it's rendering when it encountered the error:
2024-02-12 16:14:37.419 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'presence' when rendering '{{ value_json.presence }}'

#

I know that it's an MQTT discovered entity because I've seen them before, and I know that it's from ESPresence because I just do, and I was able to able to search in MQTT Explorer to find the entity that it's referencing and fix it, but man, it's way too hard

sick ice
#
  - condition: template
    value_template: >-
      {{ (now() -
      states.device_tracker.dave_location_tracker.last_changed).total_seconds()
      > 60 }}
    alias: Prevent rapid home/away state changes from causing nuisance door openings

Can someone help me sort this template, it was my attempt to prevent my garage door from opening when we're leaving due to a new quirk where the state changes fromnot_home to home momentarily when we're leaving.
Unfortunately, the above template also prevents the automation from running when it is triggered bydevice_tracker.dave_location_tracker changing from not_home to home.

Is there a way I can get it to return false if there has been a previous state change from home to not_home within the past 60 seconds?

inner mesa
sick ice
#

that was my first thought too but adding delay to the garage door opening would be annoying. I haven't yet figured out if the 'bounce' is always immediate or not, hence using atime as high as 60 seconds

#

from today's logs, the location changed back to home 6 seconds after going to away. even having a 10second hold on the attribute would mean waiting in front of the garage for it to work

#

oh wait... I see there's more reading to be had. "You can also fire the trigger when the state value changed from a specific state, but hasn’t returned to that state value for the specified time."

#
trigger:
  - platform: state
    entity_id:
      - device_tracker.dave_location_tracker
    from: not_home
    to: home

"Please note, that when using from, to and for, only the value of the to option is considered for the time specified."

I'm still not seeing how I can do that from the trigger witout introducing a delay.

#

maybe this?
{{ trigger.from_state.last_changed > utcnow() - timedelta(seconds=60) }}

sick ice
#

did some testing, this seems to work:
{{ trigger.from_state.last_changed < now() - timedelta(seconds=60) }}
Had my sign backwards and not sure that utc is needed.

marsh cairn
#

@terse nymph Do you need the tilted status or would it be sufficient to be an icon? This would be my suggestion with a tilted icon and the status as attribute (just in case)
https://dpaste.org/VF4wM

#

You can change the window icons, if you prefer the US style windows

#

Hope I understood it correct 😆 - This one can be grouped with any other door/window sensor and considers the window open, as long as it doesn't have the state closed

terse nymph
# marsh cairn Hope I understood it correct 😆 - This one can be grouped with any other door/wi...

I have a binary sensor group with all window sensors. I get a notfication after a specific time on my mobile showing all open windows. The solution behind is template which expands the binary sensor helper group as a list. Problem was that i have also window sensors which are "normal" sensors and not a binary sensor. It was not possible to add them to the binary sensor group, means i was not able to show them in my notification.

#

In the meantime i was able to solve it. I have created a binary sensor template helper for those window sensors. (open = on / tilted and closed = off) https://dpaste.org/hUWxF

marsh cairn
#

Yeah. Mine does basically the same, just with additional icons and the state as attribute

#

(and considering tilted as open)

terse nymph
#

Sorry, i consider tilted also as open like you. I have corrected my previous post.

marsh cairn
spring hornet
#

I've seen someone have an entity where it has the count of all lights on in the house. Where do I go to make such entity? I'm new to HA and don't see where to make it at, thank you!

lucid thicket
livid summit
#

Hello everyone,

This is my first template after some searching.
My main objective is to set some valves on or off depending on the temperature (for now).

So i've created a script and I'll create an automation for every room and I'll set the state of that valve equal to the output of this script

My first doubt if I have to cast this variables to be float or is it done automatically.
The second, do you guys know if { value = true } turns a switch on? I can only send off on the developer tool

Template:

alias: "HVAC: Valve control"
variables:
  valve_condition: |
    {% if set_temperature < real_temperature %}
      {% set valve = true %}
    {% else %}
      {% set valve = false %}
    {% endif %}
    {{ {'value': valve} }}
    
sequence:
  - stop: End
    response_variable: valve_condition
mode: single
icon: mdi:hvac
fields:
  set_temperature:
    selector:
      text: null
    name: Set temperature
    description: Temperature set on thermostat
  real_temperature:
    selector:
      text: null
    name: Real temperature
    description: Real room temperature
livid summit
#

Sorry guys, any help? I'm really stuck on this

inner mesa
#

Stuck how?

#

Templates don't do anything, so they won't turn on a switch

leaden swan
#

i have an entity that showing how much electricy is drawn and a graph below it. im trying so move the sensor value to the center using card_mod but i can't freaking do it. any ideas?

inner mesa
#

Seems like you're just asking questions without testing it?

leaden swan
floral steeple
#

hi, so does restful sensor allow for templating in the payload like:

payload: > 
    {
    "prompt": "magnificent scenery, wide landscape, sharp and crisp background, very beautiful landscape, fantasy, birdview, best quality, masterpiece, ultra high res, dark blue light, photo, photorealistic, wide view, kkw-ph1, professional shot of house, {{ state_attr('weather.forecast_home', 'forecast')[0].condition }} day",
    "size": "512x512",
    "model": "landscape-photoreal"
    }
tacit sun
#

hey... I am trying to create a template condition for an automation. Currently, I'm able to check if a single condition is true, but how would I change it to: If <sensor> is any of (numbers in a list) then true

Currently have :

{{ states('sensor.openweathermap_weather_code') == '200' }}
#

This?

{{ states('sensor.openweathermap_weather_code') | int in (200,201,202,210,211,212,221,230,231,232) }}
marble jackal
#

That would work

lucid thicket
#

@frank geyser here is some template code you can put into the template editor in developer tools. This could be simplified but I tried to keep each step with named variables so it would be a bit more clear what it was doing. You can modify this to fit your needs.

#

{% set feed_times = ['04:00', '10:00', '14:00', '23:00'] %}
{% set last_triggered = today_at('11:25') - timedelta(days=2) %}
{% set missed_feeds = 0 %}
{% set missed_days = (now().date() - last_triggered.date()).days %}
{% if missed_days %}
  {% set missed_feeds_trigger_day = feed_times | map('today_at') | select('gt', today_at(last_triggered.time())) | list | count %}
  {% set missed_feeds_whole_days = (missed_days - 1) * feed_times | count %}
  {% set missed_feeds = missed_feeds + missed_feeds_trigger_day + missed_feeds_whole_days %}
{% endif %}
{% set missed_feeds_today = feed_times | map('today_at') | reject('gt', now()) | select('gt', last_triggered) | list | count %}
{% set missed_feeds = missed_feeds + missed_feeds_today %}
{{ missed_feeds }}
frank geyser
#

I will have a proper dig into this on the weekend - for now I just added a http call out to some healthcheck service that will light my phone up like a christmas tree should the cat not get his biscuits 😛

lucid thicket
#

Sounds good!

final trellis
#

would you please tell me why this sensor returnr error ?

#
  - name: "frontdoor Gesture"
    unique_id: frontdoor_gestures
    state_topic: "gestures/frontdoor_camera2"
    value_template: "{{ value_json.gesture }}"
    availability:
      - topic: "gestures/availability"
    json_attributes_topic: "gestures/frontdoor_camera2"
    json_attributes_template: "{{ value }}" tojson }}"
#
Logger: homeassistant.util.yaml.loader
Source: util/yaml/loader.py:270
First occurred: 11:07:06 (5 occurrences)
Last logged: 11:14:08

while parsing a block mapping in "/config/mqtt.yaml", line 195, column 5 expected <block end>, but found '<scalar>' in "/config/mqtt.yaml", line 202, column 45
while parsing a block mapping in "/config/mqtt.yaml", line 195, column 5 expected <block end>, but found '<scalar>' in "/config/mqtt.yaml", line 201, column 45
while parsing a block mapping in "/config/mqtt.yaml", line 193, column 5 expected <block end>, but found '<scalar>' in "/config/mqtt.yaml", line 199, column 45
while parsing a block mapping in "/config/mqtt.yaml", line 193, column 5 expected <block end>, but found '<scalar>' in "/config/mqtt.yaml", line 200, column 45
#

i found it
json_attributes_template: "{{ value }}" tojson }}"

#

but what is the correct?

#

json_attributes_template: "{{ value_json | tojson }}"
????

marble jackal
#

The last one would at least be a valid Jinja template

#

But that will turn it into a string

tropic breach
#

Hi! Can someone help me with this config? Somehow the last_reset doesnt get set in my mqtt sensor entity:
- name: "Zelle 1" state_topic: "venus-home/N/xxx/battery/2/Voltages/Cell1" unique_id: zelle_1 value_template: "{{ value_json.value }}" icon: "mdi:battery" unit_of_measurement: "V" state_class: measurement last_reset_value_template: "1970-01-01T00:00:00+00:00"

marble jackal
#

Why would you need last_reset ?

lyric comet
#

It is clever enough to only put the state value in the state.

tropic breach
#

Thank you guys! Deleted some if the config items and now it works!

plain magnetBOT
#

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

undone jungle
#

This sensor returns TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime' and I can't seem to locate the issue

#

@marble jackal assisted in putting it together a few days back, but I am not sure if he's around today.

#

Ow Hi 😉

#

The issue is definitely focused around the subtraction of date from date, but not sure what I am doing wrong.

marble jackal
#

You changed the reference to last_changed to a sensor state

#

Which is a string instead of a datetime object

#

What is the state of that sensor?

undone jungle
#

sensor.x5_xdrive50e_charging_end_time

#

I believe it is a date.time object

marble jackal
#

Use as_datetime on it to convert to a datetime object

#

It's a string, all entity states are strings

undone jungle
#

{% set charging_end_time = states('sensor.x5_xdrive50e_charging_end_time') | as_datetime %}
as_datetime as an output filter, correct?

marble jackal
#

Yes

undone jungle
#

One down, and last to go, since the output format still doesn't want to agree here:
EDIT: Sensor name changed and was giving issues - NEVERMIND!!

marble jackal
#

You could use | as_datetime(now()) to prevent errors when the entity is not giving a valid state

#

Oh wait, you already test on that

#

You could remove the whole if statement if you do that

#

Do note you have to be in 2024.2 for that

marble jackal
#

@undone jungle what is the state of that sensor when that binary sensor is off?

wary yew
#

Can someone explain to me why the first one (which is the recommended approach in the docs) returns None, and the second one returns the right value?

{{ state_attr('binary_sensor.kitchen_presence_sensor_presence', 'last_changed') }}
{{ states.binary_sensor.kitchen_presence_sensor_presence.last_changed }}
fickle sand
#

last_changed isn't an attribute but part of the entity object. The first is a python function to access the attributes, the second accesses the objects directly

wary yew
#

got it, thanks. Is there an alternative way then to avoid using the states.binary... since the docs recommend to avoid it?

fickle sand
#

I think the warning is directed to accessing states and attributes from the entity object not to other parts. But I could be wrong there

marble jackal
#

You're correct Bas

#

state_attr() is recommended because it avoids errors when you try to access an attribute which doesn't exist, eg during startup or when an integration fails

#

But as last_changed is not an attribute, there is no other way to access it

thin linden
#

guys, I don't understand :

template:
  - sensor:
      - name: "HD462 Status"
      unique_id: hd462_status
      icon: >- # always shows mdi:printer-3d-off
        {% if is_state_attr('sensor.hd462', 'print_stats.state', 'printing') %}
        mdi:printer-3d
        {% else %}
        mdi:printer-3d-off
        {% endif %}
      state: "{{ state_attr('sensor.hd462','print_stats.state') }}" # does not work
      # state: "{{ states.sensor.hd462.attributes.print_stats.state }}" # works, but deprecated

NB: hd462 is a rest entity from a klipper 3d printer api json, no issues there, but all values in attributes

fickle sand
#

Does this work?

state: "{{ state_attr('sensor.hd462','print_stats').state }}"
marble jackal
#

You can't combine a fixed value of the icon with a template

#

That will output 2 icons

#

And your indentation looks off

thin linden
#

so, I can't change the icon from the attibute value ?

inner mesa
#

Sorry, the comment overflowed to the second line and confused me

#

You need to fix the state_attr() call as you did above

thin linden
#

I see

inner mesa
#

state_attr('xxx', 'yyy').state == 'printing'

thin linden
#
template:
  - sensor:
    - name: "HD462 Status"
    unique_id: hd462_status
    icon: >-
      {% if state_attr('sensor.hd462','print_stats').state == 'printing' %}
      mdi:printer-3d
      {% else %}
      mdi:printer-3d-off
      {% endif %}
    state: "{{ state_attr('sensor.hd462','print_stats').state | default('unavailable') }}"

this seems to work as I want
thanks everyone

marble jackal
final trellis
undone jungle
#

When charging state is not charging i.e. OFF the times become unknown

#

May I ask why you ask?

final trellis
marble jackal
#

to_json is used to create a json string

#

It will not be a dictionary or list or whatever anymore, just a string. So you can't take objects out if it anymore

marble jackal
undone jungle
#

Do tell 🙂

marble jackal
#
{% set n = now() %}
{% set charging_end = states('sensor.x5_xdrive50e_charging_end_time') | as_datetime(default=n) %}
{{ (charging_end - n).total_seconds() | int }}
inner mesa
#

Probably need as_local in there?

undone jungle
#

I'll think about it, though since it works now and is a bit more robust (if the sensor become strange in their outputs), I may leave it be...

#

Thank you for another valuable templating lesson though (I'll store it for later) as I have created several other sensors from 'rejected' ideas you've shown me.

#

I am actually seriously considering adding 2 staggered trigger to this sensor, since I have had an issue today when the chanring_end_time didn't trigger from unknown to date while the state of charging become ON so it was still showing a 0 for both end and elapsed sensors.

#

#1 trigger would be to check the change of charging sensor state from off to on and then every 5 min for 3 hours as timed trigger, to make sure the end time is updated.

#

The sensor will not update if just the charging state is the trigger, so it also needs to rely on the end time

marble jackal
inner mesa
#

Ah, I usually ignore those 🙂

final trellis
#

he is saying to integrate the app with home assistant use a mqtt sensor.

mqtt:
  sensor:
    - name: "Garage Gesture"
      unique_id: garage_gestures
      state_topic: "gestures/garage"
      availability:
        - topic: "gestures/availability"
      value_template: "{{ value_json.gesture }}"
      json_attributes_topic: "gestures/garage"
      json_attributes_template: "{{ value }}" tojson }}"
#

when I test configuration it gives me the following error
So I guess the project is abandoned and the code has changed ....

#

would you please help me adjust it ?

inner mesa
#

That last line doesn't make any sense. It has an unmatched quote in the middle, and an unmatched }}. It's broken syntax

final trellis
#

οκ. pls see image from mqtt explorer

#

how can I grab gesture value???

#

like this?

json_attributes_template: "{{ value_json | tojson }}"
#

noone?

inner mesa
#

No

final trellis
#

🙂

inner mesa
#

That's taking json and turning it into a string

#

There is documentation for this...

final trellis
#

it seems everybody is busy tonight 🙂

inner mesa
#

No, just hoping you'd figure it out

final trellis
#

@inner mesa please don't hurt me

inner mesa
#

{{ value_json.gesture }}

final trellis
#

I have figure out many more difficult things

#

am just confused because the programm owner is what it says

final trellis
#

great!!! Most of the times, the problem is that we are reading wrong documentation.
if we are lucky and we find the right one, then things are easier

#

so i have two incoming values coming

#

can i insert them as attributes to a sensor ??

#

they are not nested

inner mesa
#

Clicking the 'Template' link here would have brought you there:

#

Actually, I see that you already had that in value_template

final trellis
#

is this on the link above ?

inner mesa
#

Why are you trying to put it in an attribute too?

#

It's the documentation for an MQTT sensor

final trellis
#

because it will trigger for all the family

#

i want to filter it only for me

inner mesa
#

It's the same value in two places

final trellis
#

e.g. if person = makis and gesture = stop then

#

do i have to create two sensors ? this is what am asking

#

or can i import as attributes in one sensor ?

floral shuttle
#

just realized that this {{states.light |map(attribute='entity_id') |select('in',integration_entities('homekit_controller')) |select('has_value')|list}} is more restrictive than ``` {{expand(integration_entities('homekit_controller'))
|selectattr('domain','eq','light')
|map(attribute='entity_id')
|select('has_value')|list}}

#

ever since the expand on the integration entities were possible, I use those in many auto entities cards... thinking those states.xxx templates were costly.

#

checking the mentioned states these templates 'watches' the version shows all domain entities in the list, even though the output of the template is correct, and identical to the states.light version, but that only lists light entities.

lethal bison
#

I'm activating a script from the frontend with a tap_action, and also using service_data to specify variables to pass to the script. The script activates but does nothing, the variables still look unset?

#

Call script with variables from frontend

distant plover
#

How do I add spaces in front of the first dash? It's getting stripped {{" - " + ( state_attr('sensor.utilgjengelige_entiteter','entity_id')|join('\n - ')) }}

marble jackal
#

what are you trying to do?

distant plover
#

Create a list of unavailable entities I can copy paste directly into yaml 🙂 So every entity needs about 5 spaces, then a dash and then two spaces in front.

#

It works for every entity except the first one

marble jackal
#

why 2 spaces after the dash? and an odd number of spaces before it?

distant plover
#

I'm gonna copy it directly into a package.yaml. For it to be indented correctly it needs 2 spaces after dash and 6 before it.

#

I'm listing ignored unavailable entities

marble jackal
#

there is no yaml syntax which requires 2 spaces after the dash

distant plover
#

Hehe, you're right. I meant 1. 🙂

#

I was thinking of the usual amount of spaces when indenting

marble jackal
#

but anyway, the template editor trims strings before it outputs them, if you just add any other text on the first line, and your template on the second line, you will be able to copy it

#

you could also not include the spaces before it, and copy it in VSCode or File Editor. Select the text block and press tab
That will indent all selected lines

#

or CTRL+]

#

that's actually better, it will indent with 2 spaces

distant plover
#

The template editor fooled me. Thanks 🙂

marble jackal
#

the template editor is not fooling you, it is giving you the output as it would if you'd use it in an automation or script or whatever

distant plover
#

Ok. I intend to use it as a notification in HA but it looks like - is interpreted as a dot

#

Since it supports markdown... hmm

#

I escaped it with \ before the dash. Unfortunately it doesn't include all the spaces it seems. But it's ok, I'll do the tab method in File editor. 🙂

karmic sapphire
#

Is there a way to make a template that gets a count of a specific device family for example TP-Link

marble jackal
#

Do you mean a specific integration?

acoustic arch
#

So without proper knowlegde im building from scratch a gasprice sensor, since DutchGasPrices addon is broken for the time being. Their source is blocking too many api calls.

each sensor outputs like this so far:
{'organization': 'Tango', 'gps': [52.160441, 5.398098], 'address': 'v Randwijcklaan 8', 'town': 'Amersfoort', 'price': 1.919}
Which is well. Not really what i want. I would like the Price as sensor value and the remaining data as attributes...
Any way to rewrite this?
https://dpaste.org/AUkWc

#

my knowlegde kinda ends here lol

haughty breach
floral shuttle
#

for my mockupancy scripts I use{{state_attr('light.home_mode_locked_lights_2','entity_id')|random}} but I just noticed this can return a light that is unavailable. Can we reject those unavailables and still use |random?

summer arch
#

Hello. I want to get unique items in my list. I saw the filter for unique but just want to check what it does?

[ Washing Machine, Vacuum, Vacuum]

Would this be a list of 2 if list | unique

inner mesa
#

assuming you quote the items properly, yes

#

you can test it in devtools -> Templates

fickle sand
haughty breach
#

You could also just select by has_value:
{{state_attr('light.home_mode_locked_lights_2','entity_id')|select('has_value')|list|random}}

floral shuttle
#

right! that is what I was trying to do, but didnt get the syntax right.. works! thx (both of you 😉 )

floral shuttle
#

found a template/automation that seems to sometimes fluke and go crazy:```
Logger: homeassistant.helpers.event
Source: helpers/event.py:296
First occurred: 14:07:35 (20467 occurrences)
Last logged: 14:10:10

Error while dispatching event for automation.count_errors to <Job track state_changed event {'automation.count_errors'} HassJobType.Callback <bound method TrackTemplateResultInfo._refresh of <TrackTemplateResultInfo {Template<template=(:host { color: {% set state = states(config.entity) %} {{'pink' if state == 'on' else 'brown'}}; }) renders=22753>: <RenderInfo Template<template=(:host { color: {% set state = states(config.entity) %} {{'pink' if state == 'on' else 'brown'}}; }) renders=22753> all_states=False all_states_lifecycle=False domains=frozenset() domains_lifecycle=frozenset() entities=frozenset({'automation.count_errors'}) rate_limit=None has_time=False exception=None is_static=False>}>>>```

#

not sure if this is a template issue or automation...but starting with template. What could be done here?

#

happening on ```
filter:
include:
- domain: automation
options: {card_mod: !include /config/dashboard/card_mods/binary_state_color.yaml}

#

maybe try an even simpler template: style: | :host { color: {{'pink' if is_state(config.entity,'on') else 'brown'}}; } and use the is_state() syntax

floral steeple
#

hi all, so got an automation that has a couple of choose options based on trigger IDs. For one of the trigger IDs, how can I put a condition that it only runs at most once per 30 mins. I know how do this for the entrie automation, but not sure how to do it for a specific trigger in the automation.

#
  - condition: template
    value_template: >-
      {{(as_timestamp(now()) -
      as_timestamp(state_attr("automation.turn_on_lights_open_shades_tts_broadcast",
      "last_triggered") | default(0)) | int > 21600 )}}
inner mesa
#

if don't want to affect other triggers, I would just create a separate automation for it

#

it's the simplest way to do it

floral steeple
#

that is true

inner mesa
#

then just put a delay at the end of that other automation

#

based on your example, and assuming that's in the action section somewhere, I would expect that template to never be true because it always just triggered

floral steeple
#

oh good to know, that example is for another automation that I have. Its in the global condition of the automatoin not in the action

#

global meaning the main condition(s)

#

if that is right word for it

edgy umbra
#

Got this error sometimes wen sensor climate is unavailable at startup "ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template<template=({{ state_attr('climate.vicare_heating', 'room_temperature')|float/ 25}}) renders=2>".

#

Why do's it say it don't have a default, i think it's available from the template?

#
    sensors:
      temp_woonkamer:
        unique_id: bf356442-4d88-4f05-8078-3d1e0ed5538d
        friendly_name: "Woonkamer temperatuur"
        value_template: "{{ state_attr('climate.vicare_heating', 'room_temperature') | float(default=0) }}"
        unit_of_measurement: "°C"```
marble jackal
#

It clearly states which template it uses, and it's not that template

#

This is the template which is causing the issue, and this template doesn't have a default
{{ state_attr('climate.vicare_heating', 'room_temperature')|float/ 25}}

edgy umbra
marble jackal
edgy umbra
edgy umbra
#

I have a sensor.woonkamer_temperature and trying to make a min and max template sensor. Any one can share and example how to achieve this.

lyric comet
marble jackal
#

For example

edgy umbra
#

Thanks allot TheFes!

#

Btw, i thought that this format is still working but not longer recommended?

#
This format still works but is no longer recommended. Use modern configuration.

This format is configured as a platform for the binary_sensor integration and not directly under the template integration.```
lyric comet
#

They are not template sensors, they are Statistics sensors.

inner mesa
#

That's unrelated to statistics

#

I wouldn't be surprised if all integrations move away from the platform: syntax eventually, but they're all independent

edgy umbra
#

Oh sorry true, stupid to doubt TheFes 🙂

frail hawk
#

{{ states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', 'eq', 'power') | rejectattr('attributes.unit_of_measurement', 'undefined') | rejectattr('state','in', ['undefined','unavailable']) | selectattr('attributes.unit_of_measurement', 'in', ['W', 'kW']) | rejectattr('entity_id', 'search', 'shellyem3') | rejectattr('entity_id', 'search', 'total_power') | rejectattr('entity_id', 'search', 'power_production') | sort(attribute='state', reverse=false) | map(attribute='entity_id') | list() }}
the sort isn't working, any idea what i have done wrong 🙂

#

trying to sort after which one uses the most power

lyric comet
#

states are strings, so I suspect it is sorting 1,100,1000,2, etc.

frail hawk
#

well if it just was that, but i se no sort at all...

inner mesa
#

Start by removing () after list

frail hawk
#

no difference for me

plain magnetBOT
#

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

marble jackal
#

Working fine here (besides that sorting strings doesn't make sense)
Replaced map(attribute='entity_id') with map(attribute='state')

frail hawk
#

i can se that, but that i can't feed into a card, then there is no names... but trying 🙂

inner mesa
#

What purpose does sorting serve there?

frail hawk
#

to get the entity that uses most power on top of the list

inner mesa
#

It's just a filter

#

I doubt it impacts the order in which they're displayed

frail hawk
#

but don't think i'm able todo the two items together the way i wanted to 🙂

lyric comet
#

Try this to check your values

plain magnetBOT
#

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

frail hawk
#

think i need the bar-card modifies to support the template for the entities input to get it to work 🙂

#

hmm.... actualy its the config-template-card that does the sorting... ok, need to look more into that then... hmmm... well thanx for the help anyway 🙂

lyric comet
#

If you just want to view and sort, you could just look at the flex-table-card from hacs if might well give the sorted list.

frail hawk
#

i'm trying to make a list of automatic genrated entities with power, sorted by what they use... the url i posted higher does it, but i have to add all the enties manual... i wanted not todo that 🙂

#

but will take a look on that one

marble jackal
#

auto-entities actually has a sort option

#

You can sort by state and indicate the state is numeric, so it won't sort them wrong

frail hawk
#

hmmm need to look into that 🙂 thanx

marble jackal
#

You actually already have that in your config, you're sorting by name

#
sort:
  method: name
frail hawk
#

sort: method: state numeric: true reverse: true
that worked 🙂

#

to bad, that max: ${ Math.max(...vars.map(v => states[v.entity].state))} only works on the config-template-card and not on this way todo it 🙂

zealous ibex
#

In a yaml of a service, how can I include if then of jinja2?

#

I implement it it works but I can't save the file. After refreshing it;s gone

#

I'm talking about things like this:
{% if state_attr('light.floor_lamp_left','min_color_temp_kelvin') >= state_attr('light.floor_lamp_left','color_temp_kelvin') -%} Yes {%- else -%} No {%- endif %}

#

And replace yes and no with some command to set the color temperature

lyric comet
#

You can not put service calls in a template. You can set a variable at the start of an automation and condition your automation on the value. Services do not have Yaml.

zealous ibex
#

I see, is there a reason behind it?

lyric comet
#

Yes, that is how Home Assistant works.

zealous ibex
#

Of course as a workaround I can separate the steps and use the if then else outside calling a service. but then I have some duplicate parts

lyric comet
#

No. You can set the variable then use if with a script or automation variable. Templates are used as the inner level within automations, sensors or scripts.

{{state_attr('light.floor_lamp_left','min_color_temp_kelvin') >= state_attr('light.floor_lamp_left','color_temp_kelvin') }}

#

I think you need to spend sometime reading up on the concepts of the different building blocks rather than trying to fight against it.

zealous ibex
#

So I should look up automation variable?

lyric comet
#

Yes, and watch some of the 101 type videos to learn to write automations and scripts. They should always be your starting point.

zealous ibex
#

Thanks I will read on that

#

Hopefully I can create variable in the automation on the fly and it only persisits while the automation is triggered and running

#

Otherwise it can be a pain to manually create these and also see them in the entities

lyric comet
#

variables are local to the automation or script.

zealous ibex
#

that's great 😁

#

I had this concern since home assistant is definitely not always very intuitive to me

lyric comet
marble jackal
#

You can template most of the service call, but not the entire YAML

service: "{{ template}}"
target:  "{{ template2 }}"
data: "{{ template3 }}"
#

Where template2 and template3 should return a dict

zealous ibex
#

I can run it on the go. But if I save it and refresh then it's gone

#

No error messages

marble jackal
#

Not sure what you mean here,

plain magnetBOT
#

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

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

marble jackal
#

Can you share your automation/script

lyric comet
#

I suspect there was an error in the automation somewhere so it did not save.

edgy umbra
#

TheFes, any idea why the max template sensor works but the min still shows 0,0.

marble jackal
zealous ibex
#

This is what I meant:
service: light.turn_on target: entity_id: light.floor_lamp_left data: transition: 1 if cond1 color_temp_kelvin: val1 elif cond2 color_temp_kelvin: val2 else color_temp_kelvin: val3 endif

#

So it's a if else inside the data. And I can run this part with no error, but once it's refreshed it's gone

inner mesa
#

So what you really mean is a single key with a template as its value

marble jackal
#

That is not valid YAML

inner mesa
#

Which is supported and easy

zealous ibex
edgy umbra
marble jackal
marble jackal
#

If it shows 0.0 I would say your temp sensor has had 0.0 as its state in the last 24h

zealous ibex
inner mesa
#

It is a key and you are tempting the value

zealous ibex
#

I see, makes sense. though I still don't get why the way I wrote it doesn't work

edgy umbra
inner mesa
#

You cannot template individual keys like that. You would have to template the entire data section

#

Just the way it is

zealous ibex
#

All right, thanks

#

For the template, is there a way to write it in a different grammar/language? I have little jinja2 experience. And for now I find the way to formulate things are quite let's say detailed

inner mesa
#

No

zealous ibex
#

all right thanks

ruby pollen
#

Been told this is the correct place to ask this ... #general-archived message

I have an issue where my mqtt sensors are not providing the value. They worked fine forever, and the breaking changes didn't seem to point to why mine would break.

Appreciate any help.

fossil venture
#

You should also remove this for all as it is not needed for power sensors last_reset_value_template:

ruby pollen
plain magnetBOT
#

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

#

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

shrewd moat
#

Hey, is it possible to use Template language in yaml config from mushroom chip cards? I put this in but the color doesn't change

    icon_color: |
      {% if states('sensor.total_lights_count_template')|int > 0 %}
        yellow
      {% else %}
        pink
      {% endif %}
leaden drift
#

how can i convert string to list
eg. "string1,string2,string3"
tried "{{ expand("string1,string2,string3") | list }}"

fickle sand
mighty ledge
leaden drift
narrow surge
#

Is e template function available that checks if it starts with a string (MyWiFi), instead of repeating it 3 times like this:

      ...
        {% if (states('sensor.samsung_s24_ultra_wifi_connection') == "MyWiFi") or ((states('sensor.samsung_s24_ultra_wifi_connection') == "MyWiFi - IoT")) or ((states('sensor.samsung_s24_ultra_wifi_connection') == "MyWiFi - Public")) and ((states('sensor.samsung_s24_ultra_public_ip_address') == "123.123.123.123")) %}
          ...
mighty ledge
#

{% if "MyWiFi" in states('sensor.samsung_s24_ultra_wifi_connection') %}

leaden drift
lyric comet
#

That is just a representation of a list, it might be worth explaining how you are trying to use the list.

leaden drift
lucid thicket
lyric comet
#

I think

data:
  target: "{{'string1,string2,string3'.split(',') | list}}"

should work.

narrow surge
marble jackal
mighty ledge
#

That must be a jinja only thing, split returns a tuple in python

#

it is, it returns a list in jinja

#

hmmm, nope python returns a list

#

when tf did they change that

#

sometime between python 2.5 and python 3.9

#

or maybe it's always been a list and I'm miss-remembering?

light scroll
plain magnetBOT
#

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

unborn bridge
#

I am trying to do some WaterLeak senson automation; this is all done; however, I want to expose the Valve to HomeKit. In another case, I did this by creating a virtual switch and using a bridge. In those i was setting a default state of the switch to On using the code below. How can set the state of this switch to whatever the state of the valve is.

my_virtual_waterleak_switch:
        value_template: "{{ is_state('input_boolean.my_virtual_waterleak_switch', 'on') }}"
        turn_on:
          service: input_boolean.turn_on
          target:
            entity_id: input_boolean.my_virtual_waterleak_switch
        turn_off:
          service: input_boolean.turn_off
          target:
            entity_id: input_boolean.my_virtual_waterleak_switch
#

The entiry id is

 - platform: device
    device_id: 50b3f5370d7547de60161bd7eb3a3759
    domain: zwave_js
    type: zwave_js.value_updated.value
tired sable
#

I'm trying to set up a template to run the weather.get_forecasts service and extract data for use on an ESPHome project. I am having some issues, as I can't get the demo template sensor to show any values. It just says 'unkown'. I can call the service manually and see all the forecast data there. But it doesn't seem to pull into the tempate sensor. I can't test the template (I don't think you can test a template that calls a service?). The template always tells me that the response variable is undefined when I try to use it to set the sensor state when I use the template dev tool. I'm not sure how to figure out what is breaking.

acoustic arch
#

goodevening! i got a question regarding rest json sensors:
Its a giant list of gasstations. Each entry has town/price/address/gps_location.

im only interested in my own town Amersfoort. I made it this far: https://dpaste.org/5dSBW

This works. But it only shows the price of the cheapest. I dont fancy making loads of sensors this way, for addresses, gps_locs and prices.
I would like 1 sensor for one gasstation, with town/address/gps as attributes...
im stuck..

wanton sapphire
acoustic arch
#

Correct.

#

But json_atteibutes don't seem to work because I make a namespace first to sort them(I think)

wanton sapphire
#

can't you avoid using the namespace? that way you can indeed use the json_attributes

#

altough it should work even with namespace. That is used only in the template, right?

acoustic arch
#

This is a little piece of a massive json

#

Let's just say the town Sneek has 5 gas stations. I want to know the top 3

#

Price as value, the rest in atteibutes

wanton sapphire
#

if you don't mind sharing the resource I can try to help

#

or is it an api paid service?

acoustic arch
#

no but before its gonna get hammered and start blocking ips i rather keep it to my self for a bit

wanton sapphire
#

sure!

acoustic arch
#

i pinged you

#

as you can see it has loaaads of gas stations

#

i would like a top3 of the town Amersfoort. Price as value, the rest as attributes.

#

json_attributes doesnt seem to work with attributes in them

#

else i could reuse the namespace thingy in there

marble jackal
#

Based on the information above, you can't really do anything with it in a rest sensor, attributes in a rest sensor need a key

acoustic arch
#

At the moment in trying to dump the json to a file and go from there. A 'regular' sensor can do templated attributes right?

#

I'm hoping to just repeat my namespace thingy in each attribute and swap .price to .town etc

marble jackal
#

Yes, but you really don't need a namespace there

terse nymph
#

I have this template sensor:

{{ expand('binary_sensor.fenster_state') | selectattr('state', eq', 'on')
| map(attribute='name') | list | join (', ') }}

In case there is more than one window open i like to add a and between the list of sensors in my TTS
like window1 is open and window2 is open.

Can somebody help me how to adjust the template?

marble jackal
#

{{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}
That will give you the lowest price without the need for a for loop and namespace @acoustic arch

marble jackal
acoustic arch
terse nymph
marble jackal
acoustic arch
#

but rest sensor doesnt allow for template attributes... right?

marble jackal
marble jackal
terse nymph
marble jackal
#
- name: cheapest gas
  state: "{{ template from my previous post }}"
  attributes:
    station: "{{ other template }}"
    address: "{{ and another template }}"
#

@acoustic arch each attribute has its own template

#

In a template sensor

acoustic arch
#

ok sorry for this novice question. But where to i fetch the json from then...

#

for the rest i understand what you are saying. I made similar sensors like this

mighty ledge
#

thats in your rest

acoustic arch
#

ok ill try in 5min

#

and paste what i did in dpaste

#

i pasted attributes for testing only. But they dont show up

#

(after reloading rest-enitities in dev-tools)

mighty ledge
#

check your log for errors

acoustic arch
#

as far as i know, templating in rest sensor attributes is not implemented..... (?)

mighty ledge
#

it's not, you have to use json attributes path to point to the object you want to display then use json attributes to output which ones you want

#

or put the contents of the value_json into an attribute and extract it using template entities

acoustic arch
#

ok but thats something else than the Fes said... i dont think he knew i was fetching with rest i suppose

#

but can i get a path from the extracted item from the json? or only from the original source

#

i need the path from:
{{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}

mighty ledge
#

json attributes path is a json path, it's designed to do whatever you tell it to do, it's just like the templates

#

just different syntax

acoustic arch
#

ok so i need to template the path then

mighty ledge
#

no, you use a json path

#

use that to help you find the path

acoustic arch
#

ok one step back. My rest source is a giant list. I need just ONE item, which is the lowest price. So Fes gave me {{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}

Works. i get the lowest price.

Now i need the Adress and Town of that item.

mighty ledge
#

ok then just make 3 separate entities, one for each using that template

#

but change the mapped attribute

acoustic arch
#

there you go.... 3 sensors.

#

so i cannot use attributes

mighty ledge
#

you can

#

but you have to use json attributes path

#

going in circles here

acoustic arch
#

ow yea.. lol

#

ill paste in 3 gasstations here for markup:

mighty ledge
#

you either need to learn how to use json attributes path, or you need to go via separate sensors, or a single senosr that feeds a template entity

acoustic arch
#

[{"organization":"TinQ","gps":[52.278169,4.513391],"address":"Provincialeweg N206 - 29","town":"Noordwijkerhout","price":1.979},{"organization":"Shell","gps":[51.33081,3.853431],"address":"Serlippensstraat 45","town":"Terneuzen","price":1.939},{"organization":"AVIA","gps":[52.43073,6.54053],"address":"Wierdenseweg 11 (N751)","town":"Daarle","price":1.929}]

#

lets say they are all in my town Amersfoort. My feeling is that json_path only looks at this original data, not the fetched data from the Fes

mighty ledge
#

that's the whole point of json attribuets path

#

to filter down to what you want

#

so, instead of arguing, why not just try the json tester I posted above, take 10 minutes to learn how to use json path

#

once you filter it down to your town, you can then use json_attributes to get them as attributes

acoustic arch
#

but i need all the data from the cheapest. Not just A gasstation

#

i can drill down to one no probs.

mighty ledge
#

ok, then look up how to do that with a json path

#

my man

#

it can do it

acoustic arch
#

ah! ok

#

well there is some new info i didnt know

#

so i need to lean to write a path expression to first find the item with the lowest value inside town Amersfoort, then list the rest

#

thats gonna be a fun new hobby🫣

mighty ledge
#

it's not too bad

#

I have to google it every time, don't have it memorized

acoustic arch
#

i thought json_path was not dynamic

#

just a quick drill down...

mighty ledge
#

well, the basic is a drill down

acoustic arch
#

thanks for the time so far! much appreciated

mighty ledge
#

but you can also have it do fancy things like sorting and selecting based on names/types

#

that's about the extent of it's capabilities though

acoustic arch
mighty ledge
#

yes

acoustic arch
#

got it!

mighty ledge
#

it's dumb, but that's how it was originally designed

acoustic arch
#

and then fetching the rest is easy