#templates-archived

1 messages · Page 78 of 1

mighty ledge
#

of course you can ask template questions

dusky drift
#

i have a powerplug that gives out Watts ofc and i want to expose it to Homekit

#

but since HK cant read Powerplugs

#

i tried to fake a sensor giving Lux

#

the Sensor is active but doesnt read out the real sensor

mighty ledge
#

post what you tried

dusky drift
#

  - platform: template
>     sensors:
      homekit_converted_sensor:
        friendly_name: "MPower"
        unit_of_measurement:  "lx"
        device_class: illuminance
        value_template: "{{ state_attr('sensor.smart_switch_2309263180307151081348e1e9dbf36b_power','W') }}"
plain magnetBOT
#

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

mighty ledge
#

can you format it please

dusky drift
#

sure

mighty ledge
#

just edit your previous comment

#

i can already see your template in th etemplate sensor is wrong

#

{{ states('sensor.smart_switch_2309263180307151081348e1e9dbf36b_power') }}

#

assuming your entity_id is actually sensor.smart_switch_2309263180307151081348e1e9dbf36b_power

dusky drift
#

why?

mighty ledge
#

why what?

dusky drift
#

what is wrong about it?

mighty ledge
#

your template? or the entity_id?

#

the template is wrong, just a misunderstanding of templates on your part. The entity_id isn't necessarily wrong, I'm just not sure if you provided the correct one to the template.

#

beginners typically don't know what entity_id's are, I'm not saying you do or don't. But you said you were a beginner.

dusky drift
#

sure iam 🙂

#

so the entity id i gave is the real sensor

#

i thought the template would pick this one to read out

mighty ledge
#

the entity_id is the identifier for the existing information

#

the states function gets the state for the provided entity_id

#

you used the state_attr function, which gets attributes from a state object.

#

the state on an entity is not an attribute, so that's your miss understanding

#

you're assuming that state_attr(entity_id, 'w') will get the watts out

#

but the watts are the main state

#

so you just need the states function, i.e. {{ states('sensor.smart_switch_2309263180307151081348e1e9dbf36b_power') }}

dusky drift
#

ow

#

i understand

mighty ledge
#

so if you use the template I provided, it should work (Assuming that sensor.smart_switch_2309263180307151081348e1e9dbf36b_power is the correct entity_id)

dusky drift
#

omg

mighty ledge
#

you should try the template in the template editor

#

developer tools -> template tab

#

it also has auto-complete for entity_id's

dusky drift
#

ok i will get into that

#

it works

mighty ledge
#

developer tools -> states shows you all entitys (and their states, entity_ids, and attributes)

dusky drift
#

god

#

thank you so much

mighty ledge
#

np

dusky drift
#

ill get to work on that

last basin
#

hi, i'm trying to create a helper which copies the numerical state of a template i created from my climate sensor (because there isnt an entity for the value i need from it) but i'm struggling with what to create the helper template as as it keeps complaining about
Sensor None has device class 'temperature', state class 'measurement' unit '°C' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'value_template: "21.5"' (<class 'str'>)¬
any ideas ?
i'm using
value_template: "{{ states('sensor.mainhousetemp')|float }}"

#

or if i use the device directly even i get the same complaint about non-numeric value
value_template: "{{ state_attr('climate.heating', 'temperature') }}"

#

ok ignore me, figured it out

#

hmm ok so now i have the helper, the blueprint i have only is looking for number helpers, and doesnt see my template one. is there a way i can make a number helper = the other helper? would that need to be an automation in of itself?

lofty mason
#

yeah you need an automation for that

last basin
#

gotcha, i think i've made one and it looks like it is alll working now 🙂

torn meteor
#

does the switch template have any "magic" variables like this.action for the action (on/off) requested?

#

some templates have this kind of thing

thorny snow
#

Hi - anyone got any idea where HA stores the input from the template editor in Developer tools? I've got some bad templates which aren't in my config and I know HA reads the editor on boot and gives errors. I've cleared as many places as i can on my machines but still have some stragglers...it's very frustrating!

lofty mason
#

that question doesn't make sense to me. HA (core?) doesn't "read" anything from the frontend.
If the template in the editor is stored, it's cached locally in the client.

thorny snow
#

It does. Put a bad template in the editor and restart - look in your logs and voila - a startup error.

#

I've cleared all my caches and history on all machines that have ever accessed it.

lofty mason
#

can you show an example of whats your "bad" template, and what log message you get on restart?

thorny snow
#

Here's the log (this code doesn't exist anywhere on my config)

plain magnetBOT
#

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

lucid thicket
torn meteor
#

so this.trigger.event would have the "on" payload if i tapped that template switch on?

lucid thicket
#

this is the state object of the switch. The state object has no property called trigger

#

if you have a trigger-based template entity, it would have a variable called trigger populated with that data. But there is no such thing as a trigger-based template switch

torn meteor
#

so in my template i can say

turn_on:
  service: script.turn_on
  data:
    target_entity: script.my_script
    data:
      intended_action: trigger.event

?

#

oh.

#

so i can't do what i want

#

wait haha i'm a dummy - the fact that i'm INSIDE turn_on is enough to know the intended action

#

nevermind

wooden drift
#

hi all - I'm seeing HA change text on me in the raw editor after I save, exit, and go back into raw editor. For example.

            {{ states(''sensor.day_en'') }}, {{ states(''sensor.date_en'') }}```
is changed to:
``` name: |
            {{ states(''sensor.day_en'') }}, {{ states(''sensor.date_en'') }}```
is this expected behavior?
marble jackal
#

It changed the > to |?

#

Both have the same result in this case, doesn't make a difference

wooden drift
#

interesting, it's strange that the raw editor is making unnecessary changes like that

lofty mason
#

it's part of the yaml -> json -> yaml serialization/deserialization

#

the whitespace character doesn't exist in json, so that info is lost

#

but I think it faithfully creates the correct output

marble jackal
#

It also adds these double single quotes, which are escaped single quotes

wooden drift
#

yeah I noticed that too

#

are the open {{ necessary in that block before "states"? can't it just be states('sensor.day_en....)

#

nvm - answered my own question

marble jackal
#

The {{ and }} are required, they are essential in Jinja templates

indigo pine
#

Hi everyone, I’m new to Home Assistant and I’m trying to learn by watching lots of tutorials but got stuck on a problem, trying to get current temp from any on my sensors with state_attr. I’m getting null or none when using {{ state_attr(‘sensor.aqara_temp_humidity_sensor_temperature’, ‘current_temperature’) }} and I’ve tried lots of things but nothing seems to work 🙁 What am I doing wrong 😑

wooden drift
#

please provide your full yaml in a log

#
        - layout: name_state
          name: |
            ⌂ {{ states('sensor.home_temperature') }}°F

this is mine, works fine

indigo pine
#

Yes using only states works for me too but not when using state_attr

lofty mason
#

your temperature sensor has an attribute of current_temperature? That seems odd. Did you look at what actual attributes exist on that sensor? (check developer-tools -> states)

wooden drift
#

why do you need to call on the attribute if the states works fine?

indigo pine
#

This is what I get

{'state_class': <SensorStateClass.MEASUREMENT: 'measurement'>, 'unit_of_measurement': <UnitOfTemperature.CELSIUS: '°C'>, 'device_class': 'temperature', 'friendly_name': 'Sovrum Temp'}

indigo pine
lofty mason
#

you sound confused about the difference between states and attributes.
The state is the primary piece of information for a sensor. For a temperature entity, the state would be the temperature.
Attributes are like secondary information.

indigo pine
#

Ok. why do we use attributes then?

inner mesa
#

you can see them all in devtools -> States

inner mesa
indigo pine
inner mesa
#

videos are often wrong. avoid whoever posted that one

#

they don't know what they're doing

wooden drift
#

if I want to pull state from weather, what should my code look like?

inner mesa
#

or you missed the .state at the end, but you should use what I pointed to anyway

wooden drift
#

I'm getting my internal temp and weather with this code:

        - layout: icon|name_state
          name: |
            ⌂ {{ states('sensor.home_temperature') }}°F
          state: |
            {{ state_attr('weather.home','temperature') }}°F

but for the life of me I'm struggling to pull state from weather. The docs say I can get it but no idea how

lofty mason
#

state like cloudy ?
That's just states('weather.home')

wooden drift
#

{% set state = states(weather.home) %} ?

#

or do I have to pass the forecast variable too? hourly?

indigo pine
wooden drift
# inner mesa they show an example

the first example doesn't seem to have anything related to state (like cloudy), the second example has forecasting and has state but it's not entirely clear to me to pull just state and pass it onto a variable in yaml what I need to do

inner mesa
#

the state is just the state of the weather.xxx entity

#

you just posted an example of retrieving the state of an entity

#

you posted:
⌂ {{ states('sensor.home_temperature') }}°F

#

then did this:

#

{% set state = states(weather.home) %} ?

#

note the difference

wooden drift
#

I mean there's a couple differences 😉

#

but, you gave me a good place to start, I think I see it....maybe

lucid thicket
wooden drift
#

still not getting it: {% set state = states('weather.home') %}

frail dagger
#

{% set state = states('weather.home') %}

wooden drift
#

yes, sorry I updated to weather.home but still nothing, I thought that returns the state

frail dagger
#

That's what you need.

wooden drift
#

yeah - I'm not sure why weather.home is returning nothing

#
            {{ state_attr('weather.home','temperature') }}°F

returns temperature fine

inner mesa
#

they probably showed {{ states.sensor.xxxx.state }}

#

but again, don't do that

indigo pine
#

no he didn't

frail dagger
inner mesa
#

then ignore their videos as they don't know what they're doing

indigo pine
#

so you are saying that dont look att youtube tutorials

frail dagger
#

Honestly, the forums are usually a better resource than Youtube videos are simply because a lot of videos are old and refer to old versions of HA. Same thing with ChatGPT assistance.

wooden drift
#

@frail dagger now I'm making some progress:

        - layout: icon|name_state
          name: |
            ⌂ {{ states('sensor.home_temperature') }}°F
          state: |
            {{ states('weather.home') }}

returns "sunny"

but:
{% set state = {{states('weather.home) }} %}
returns error:
TemplateSyntaxError: expected token ',', got 'weather'

inner mesa
#

wherever you saw this:

and for this, it looks like you just did something like {{ states.sensor.xxxx }}, which isn't how you get a state

wooden drift
#

sorry it actually returns:
TemplateSyntaxError: expected token ':', got '}'
when I fix that ` error

frail dagger
wooden drift
#

yeah I resolved that, then hit the second error

marble jackal
#

You are nesting templates

indigo pine
frail dagger
#

{% set state = states('weather.home') %}

marble jackal
#

Probably he want just
{{ states('weather.home) }}

frail dagger
#

I think he wants to use the state variable though? I'm not sure 🤔

wooden drift
#

yeah I want to use variable to pass to an icon mapping

wooden drift
#

I think it's working but my mapping isn't working now. But, no errors which is promising

wooden drift
#

probably best to just share the entire yaml at this point, I forget what this channel prefers for posting longer 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.

wooden drift
#

https://dpaste.org/Dne0e, I believe state is being passed on based on no errors and no default weather icon that used to come up, so I think I'm down to my path to my icons being wrong

frail dagger
#

Line 71 is wrong: {% set state = {% set state = states('weather.home') %} should be {% set state = states('weather.home') %}

#

I can't really validate the rest of it as I don't do frontend stuff.

#

But it looks good?

wooden drift
#

for my path, if I'm using a docker, the "./" is equivalent of location of my docker configuration folder right?

frail dagger
#

Yup. It translates to /config

wooden drift
#

super weird result - where my icon should be, it just reads "icon" in super small font

frail dagger
#

I'm not good with frontend at all. lol

wooden drift
#

@frail dagger huge help. Beer on me 😉

frail dagger
sonic nimbus
#

How is this possible

{{states('device_tracker.520d_xdrive')}} #Garage
{{is_state('device_tracker.520d_xdrive', 'zone.garage') }} #False
#

so the first line clearly says that car is parked in zone called 'Garage'

#

what is better approach for this

inner mesa
#

seems clear

#

"Garage" isn't "zone.garage"

sonic nimbus
#

yeah, but Im confused? do I need some binary_sensor which will calculate is the car are in the zone or not?

#

and then just to observe that binary_sensor?

inner mesa
#

I'm not following you at all

#

you wrote a test to check if it was "zone.garage" when you already know that it's "Garage"

sonic nimbus
#

so here what I want, very simple.
Each night at 00.00 I want to check if my car is int he garage or not.

I created zone: zone.garage
Now I want to put condition template to check if the car (device_tracker.520d_xdrive) is in the garage or not. If not, notify me.

#

So my question is presumably that when device_tracker is in the some zone, in this example 'Garage' zone, its state will be 'Garage', the name of that zone right?

#

I dont need to check and compare if that device_tracker are really in the zone, just by string 'Garage'?

#

What if I want to rename zone in couple of weeks into 'New Garage'?

#

is that will break my automation?

marsh cairn
#

You could just call the old one "Old Garage" Kappa

sonic nimbus
#

Yes, but from perspective of maintanance I will need to edit my automation right?

#

I would like to use zone.garage if the device tracker is in or out that zone

frail dagger
#

Why not just put an entity state condition in your automation on zone.garage = 1?

#

Feels like you're over-complicating it.

sonic nimbus
#

{{states('zone.garage')}} returns zero, and
{{states('device_tracker.520d_xdrive')}} returns 'Garage'

#

how that is possible?

#

if device tracker returns 'Garage' that means that at elast 1 entity is in the zone?

lucid thicket
#

state of the zone is the number of people

#

not device trackers

marble jackal
#

The state of a zone only counts person entities

#

🐌

frail dagger
#

Ahhhhh, gotcha. My bad.

#

lmao 🐌 today.

inner mesa
#

what if the cars are people?

sonic nimbus
#

ok, so I cant use it because this device_tracker is basically BMW integration not human 🙂

frail dagger
#

I mean, I named my car... so, it's people to me.

#

Yup, I was wrong (I said it twice 🙂 )

sonic nimbus
#

I have attributes for location (longitude and latitude) position of the car, and based on that I created zone with radios of 10 meters

#

but apparently my automation is bad, because it's not matching want I want to be matched

#

maybe I can use zone trigger and some helper boolean to keep track if the car is in the zone

frail dagger
#

Post the automation.

lucid thicket
#

how about something complicated like this:

{{is_state('device_tracker.520d_xdrive', slugify(state_attr('zone.garage','friendly_name')) ) }}
sonic nimbus
frail dagger
#

Try that again, the paste is returning a 500 error for some reason.

sonic nimbus
#

slugify(state_attr('zone.garage','friendly_name')) = > garage needs to be Garage 🙂

frail dagger
#

So, you're already using the value template, just use Garage instead of zone.garage.

frail dagger
sonic nimbus
#

Then how it is possible to be false this statement?

lucid thicket
#

What is setting the state of the device tracker? Is that the BMW integration doing that?

frail dagger
#

Yeah, probably because of slugify.

sonic nimbus
lucid thicket
#

Slugify does make it lower case, but that was intentional, because that is what the state of a device tracker should be when it is in a zone

sonic nimbus
#

When it is in a zone the first letter is a capital one.

lucid thicket
#

In the front end, yes. Not in the back end

sonic nimbus
#

also in the backend

#

please see the screenshot

lucid thicket
#

At least normally. In your case, it also has a capital in the back end

sonic nimbus
#

nevermind, I think we fixed it now 🙂

lucid thicket
#

Did you overwrite the state of the device tracker in dev tools and use a capital letter?

inner mesa
#

you can name zones whatever. you want

lucid thicket
#

Is it just Home and Away that will cause device trackers to use a state that doesn’t match the frontend? (home and not_home)

inner mesa
#

coudl be

green summit
#

Hey guys, I have a question. I have open weather in ha and I noticed something weird with forecasts. It seems to be pulling the Forcast data for like 4 hours ahead. Now I know the 3 hours of data is there when Iook at the sensor. But the weather.get_forcasts starts 4 hours ahead.

lucid thicket
# sonic nimbus I didnt

Yeah, looks like I was wrong. For user-created zones, the device tracker will use the zone’s friendly name as the state

marble jackal
green summit
#

That's my thinking as well. But can it be fixed lol

#

Now I need to check something

marble jackal
#

What needs to be fixed?

#

You can compare timezone aware datetimes with each other if they are in a different timezone

sonic nimbus
#

How can I create template trigegr for my vacation mode automation, to triggers in to cases:

  1. When Im not in city zone anymore for 4 hours or more
  2. When Im on airport (witihin city zone) waiting for 2 and a hlaf hours to be boarded into a plane, then I suppose will have for my iphone device_tracker status 'unavailable'
dusty chasm
#

woo this worked! I was printing states['sesnor.foo'] for debugging and it was showing just the sesnor attributes instead of the whole state object, so I thought I couldnt access last_changed from that

green summit
empty bone
#

I think I just posted my message in the wrong group "integrations". So just to cover my bases I will try the templates group. I suck at yaml, it takes me months to figure this kind of stuff out. Mainly cause I get distracted and don't want to sit in front of the computer. I am or have been trying to figure out how to get a weather intigration working. To populate a cool weather card I found on HACS. I understand I am supposed to write a weather template where I as the user create the entities that pull in the data. What I am hoping is someone is willing to share a weather template that they are using so A. I can look at it and try to understand it. And B, I could possibly modify if I need to for my own use. I would really appreciate it if anyone is avalible to assist.

green summit
#

Alright, I have a sensor thats pulling from openweather. hour0_date: "{{ hourly['weather.openweathermap'].forecast[0].datetime }}" The openweathermap is sending me the time in UTC which is fine but I need to bring it back to my timezone. How can I accomplish this?

marble jackal
green summit
#

Yea, end goal is to have that time in my timezone.

marble jackal
#

To do what with it?

green summit
#

I found a kodi plugin that pulls weather sensor data via the API from HA. So when its being read into Kodi its reading that time, which again is incorrect.

#

Now, granted within the Kodi plugin I can make it update based on the local time as well. However I thought it'd be a quick update to just do it within HA but its eluding me.

marble jackal
#

How does the plugin get the data? Do you only send the first list item or the entire forecast for the next days?

sonic nimbus
#

Why Im having an error: {{ (as_timestamp(states.binary_sensor.frontdoor_motion.last_changed | default(0)) - as_timestamp(states.binary_sensor.front_door.last_changed | default(0))) < 30 }}

ValueError: Template error: as_timestamp got invalid input '0' when rendering template '{{ (as_timestamp(states.binary_sensor.frontdoor_motion.last_changed | default(0)) - as_timestamp(states.binary_sensor.front_door.last_changed | default(0))) < 30 }}' but no default was specified
sonic nimbus
#

is this correct logic:

{% set current_time = now().time() %}
{% set start_time = strptime("09:00", "%H:%M").time() %}
{% set end_time = strptime("10:30", "%H:%M").time() %}

{{is_state('media_player.bedroom_tv','on') and (start_time <= current_time <= end_time)}}
#

is there any better approach?

mighty ledge
mighty ledge
stuck remnant
#

hey guys, I need to send a payload template of a clipboard (sensor.asclepius_activelink)

service: mqtt.publish
data:
  qos: 0
  retain: false
  topic: homeassistant/button/TheGoat/launchurl/action
  payload_template: 
#

anyone know the template to grab the text value of said sensor?

frail dagger
stuck remnant
#

gee thanks!

coral marsh
#

What's the variable to capitalise all ?
{{'user' | capitalize }}

inner mesa
#

it's called a "filter"

#

{{ 'foo'|upper }}

#

see the Jinja docs in the topic for more

marble jackal
#

You probably want upper

#

Oh, Discord cache strikes again

coral marsh
#

Ah thanks, I tried uppercase instead lol

chilly hemlock
#

Hey all, I'm trying to put together a template for sorting all my lights by floor and then area (with custom sorting) for use in auto-entities. Just checking in, in the off chance someone has already done something similar before

#

If not I may just hold off until auto-entities hopefully gets support for sorting by floor and secondary sort

plain magnetBOT
#

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

haughty breach
chilly hemlock
#

Thanks. It doesn't seem to recognise flatten, however.

marble jackal
#

Use | sum(start=[]) instead of flatten

#

@haughty breach probably installed Spook 👻

chilly hemlock
#

Thanks 🙂

haughty breach
#

Sorry, forgot that was custom...

chilly hemlock
#

Would it be possible to include multiple floors

inner mesa
#

I would have expected that you could start with a list, but no. You need to use a loop

marble jackal
#

{{ floors() | map('floor_areas') | sum(start=[]) | map('area_entities') | sum(start=[]) | select('match', 'light') | list }}

inner mesa
#

or...that

violet geyser
#

How can I use templates in the google assistant config for including entities that I labelled? Config should look like this:

google_assistant:
  entity_config: 
    light.entitiy1:
      expose: true
    light.entitiy2: ...
marble jackal
#

You can't

#

You can't use templates in the Google Assistant YAML config

#

I don't think it's possible with Nabu Casa as well, there is no service call to expose entities

violet geyser
#

fair, albeit unfortunate. I'll just put it manually, will use the template dev tools to generate the list from a template that I can copy paste

lyric jungle
#

hey, whats wrong with my syntex ?

service: input_number.set_value target: entity_id: input_number.screentime_hours_bank data: value: "{{ ((states("input_number.screentime_hours_bank") | float)*3600 - (state_attr("input_datetime.eithan_screentime_add" , "timestamp") | float))/3600 }}"

marble jackal
#

You're using the same quotes inside and outside your template

#

Use single quotes outside and double quotes inside, or the other way around

#

Or use the multi line notation to avoid quotes outside the template

lyric jungle
#

thanks

plain magnetBOT
#

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

green summit
#

@marble jackal I originally tagged you in this but didn't realize it was going to do that. But thats the way it returns. I just need 20 to be 16 lol

smoky tinsel
#

So, im trying to setup a dashboard and the addon im using isn't very mature yet but i do like some of the features. Is it possible to add An Icon, Sensor Name and Value, similar to how the standard dashboards show them, using a template.

As an example, I have some light sensors, and on the standard dashboard they show a sun icon, followed by the text "Light Sensor Light level", followed by the value "20 lx".

Is there a way for me to achive that exact same thing using templates?

inner mesa
#

seems like what you're calling "addons" are "cards"

smoky tinsel
#

No, I have a whole dashboard addon (HA Fusion) I am using, so doesnt have standard cards. It has some stuff but for the standard card style icon - text - value it doesnt seem to have anything. So was wondering if i could recreate that with template syntax

inner mesa
#

you can easily create a string with "Light Sensor Light level" followed by the value "20 lx" with the value being the state or attribute of an entity

smoky tinsel
#

It is possible to get the icon too or is that too far for templates?

inner mesa
#

if you find a unicode icon that you like, you can include that

#

you can't specify an mdi:xxx icon there and have it render

smoky tinsel
#

Ok cool, thanks

dusty chasm
#

Hi, im trying to do the basic hourly forecast template sensor thing, but keep getting an error that my response_variable is undefined (UndefinedError: 'hourly' is undefined)

#
  - trigger:
      - platform: time_pattern
        minutes: /15
    action:
      - service: weather.get_forecasts
        data:
          type: hourly
        target:
          entity_id: weather.forecast_home
        response_variable: hourly
    sensor:
      - name: "Forecast Home Hourly"
        unique_id: hourly_weather
        state: "{{ now() }}"
        attributes:
          forecast: "{{ hourly['weather.forecast_home'] }}"```
green summit
#

Where do you get that error? In developer tools?

green summit
#

I noticed in developer tools I can't test either and it was bugging me lol

dusty chasm
#

developer tools and actual error log for my sensor
2024-06-15 18:24:09.623 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('UndefinedError: 'hourly' is undefined') while processing template 'Template<template=(template:

green summit
#

SO I dont think it works in dev but I have something similar let me compare

#

you have this in a template yaml?

dusty chasm
#

uhh i could be putting in the wrong place since im not used to this

#

but I went Settings -> Devices & services > Helpers > Create Helper > Template > Template a sensor > paste in the state template box

green summit
#

Is it in your config file? For me I placed template: !include template.yaml in my config file and then in my template.yaml file I have exactly what you have but remove template:

dusty chasm
#

If it only works in actual yaml i can try that

green summit
#

Yea I dont know about creating the helper template but I did it that way and it works. Only thing I'm trynna do is change the time lol

dusty chasm
#

That seems to work, thanks! not sure what the difference is but ill take it

green summit
#

same, I wish I knew

#

I'm literally going through it now with that same template. Just can't seem to figure out how when I'm setting the attribute to subtract time from it.

dusty chasm
#

Hmm, it seems to be in my local timezone already for me

#

oh wait you mean the attribute itself, yeah im not sure, im just passing the sensor to a dashboard card

green summit
#

yea I'm messing around with pulling this data via the API into a Kodi plugin.

#

Openweather sends it in UTC

lucid thicket
green summit
#

you happen to know if I can do what I'm trying to do or is that another nope

lucid thicket
#

you are trying to convert all the UTC datetimes in the response to local datetimes?

marble jackal
# green summit <@723160143314812971> I originally tagged you in this but didn't realize it was ...

I think I understand that you are trying to achieve but:

  • I haven't used Kodi for maybe 10 years, but at that time you could simply point to online sources for the weather, no need to use Home Assistant for that
  • In case you really want to use that plugin, that plugin should handle conversion from UTC to local time. Write up an issue for the author of the plugin
  • In case you really want to use the plugin, you can maybe use another weather integration which might have local datetimes instead of UTC datetimes
  • In case you really want to use the plugin and your current weather provider, I think you need to create a trigger based template weather which iterates over every item in the forecast and replaces the datetime string in each item with a local one. Seems like a lot of work for something which could be done a lot easier
green summit
#

Yes, I can update the plugin. I stated that previously. Sure, you can say use a plugin thats going to pull my local and not UTC time. All well and dandy. I'm simply asking for the Home Assistant way. I see plenty of people converting times and all that when looking around. None have seemed to work for me so far. If its simply Home Assistant can't do it because x y or z then fine. It just seems to me that if Home Assistant has all these abilities to modify time and format display that this shouldn't be such an issue that it seems to be.

lucid thicket
#

you can do anything you want in a template. It's not an issue for home assistant.

#

I agree with TheFes, there are better ways to go about this. And I'm not great with namespaces, so there's probably some simplification that can be done. I've also been contemplating whether to post this or to teach you to fish, but here is something that works because I'm hanging up for the night: https://dpaste.org/6KUxh

marble jackal
limber haven
#

Hm Having a bit of trouble with some templating, I'm trying to reduce the number of seperate automations I have for handling 'Door opens, turn on light in the room' so want to compact it all into 1 if possible. I've setup the sensors and lights so the follow the same scheme (binary_sensor.ROOM_door_contact & light.ROOM_lights) and wrote teh following automation to trigger but it keeps failing https://dpaste.org/ic9B0 with Error: In 'template' condition: ValueError: Template error: as_timestamp got invalid input '' when rendering template '{{ as_timestamp(now()) | round - as_timestamp(['light.' + trigger.entity_id.split('_')[0]].last_changed) | round > 10}}' but no default was specified

#

(it's supposed to check if the lights in that room have been off for 10 seconds, sort of as a debounce)

marble jackal
#

as_timestamp(states['light.' + trigger.entity_id.split('_')[0].split('.')[1]].last_changed)

#

You forgot states. and you forgot to remove binary_sensor.

limber haven
#

Hmm..

plain magnetBOT
#

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

limber haven
#

That doesnt seem to work either, get 'list object has no element 1' but I've been screwing around with it in templating and this ```{% set door = 'binary_sensor.kitchen_door_contact' %}

{{ door.split('.')[1].split('')[0] }} So I tried to convert that in the condition to be{{ as_timestamp(states['light.' + trigger.entity_id.split('.')[1].split('')[0]].last_changed) | round > 10}}returns the value of 'Kitchen' which.. is the correct word Im looking for to get added to the template but that produces the same error as before? Error: In 'template' condition: ValueError: Template error: as_timestamp got invalid input '' when rendering template '{{ as_timestamp(states['light.' + trigger.entity_id.split('.')[1].split('_')[0]].last_changed) | round > 10}}' but no default was specified ```

plain magnetBOT
#

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

marble jackal
#

You can't use templates in a tap action

#

Call a script and use the templates in the script

limber haven
#

I think I got it 🙂 ```{{ as_timestamp(states['light.' + trigger.entity_id.split('.')[1].split('_')[0] + '_lights'].last_changed) > (as_timestamp(now()) < 10) }}

marble jackal
#

Ah right, I missed that _lights part before

limber haven
#

(It should read the state of the lights, then turn them on if its been off for ten seconds, which.. should be good enough to stop debouncing)

marble jackal
#

Maybe an easier solution it to use a combination of areas and labels. Give each light which should be triggered by a motion sensor a specific label and make sure they are in the same area as the motion sensor

#

Then you don't need all this entity id matching

#

So for example a motion_triggered label

limber haven
#

JHmm, I'll read up on that 🙂

marble jackal
# limber haven JHmm, I'll read up on that 🙂

Then you get something like this:

{% set area = area_id(trigger.entiy_id) %}
{% set light = area_entities(area) | select('in', label_entities('motion_triggered') | list | first %}
{{ now() - states[light].last_changed  < timedelta(seconds=10) }}
#

This only works if there is only one light with that label in each area (like you have now with the entity_id matching)

#

It could be adjusted to work with more lights

limber haven
#

Huh, I see! that does seem much simpler

half fable
#

Hello, I don't understand well template, I m tying to add a Open/Close helper when my car flap is 1/0 (close or open)
Is this correct ?

Template binary sensor
State template*

  Close
{% elif states('sensor.dt5930_charge_flap_dc_status') == '0' %}
  Open
{% else %}
  Unknown
{% endif %}```
inner mesa
#

Does it work?

topaz marsh
#

hi, I wonder how I can create my own demo for home assistant, without having connected hardware components to it?

haughty breach
#

A binary sensor will only ever be on or off, if you want it to show Open/Closed in the frontend you need to specify a device class of door, window, or cover. If you want the actual state to be Open/Close/Unknown you need to set it up as a sensor, not a binary sensor.

half fable
half fable
#

It should always be On or Off (at least based on the history)

#

So if I want on or off what should I write ?

haughty breach
#

{{ is_state('sensor.dt5930_charge_flap_dc_status', '0') }}

#

That's all you need for the State template of a binary sensor helper to be 'on' when the flap status is '0'.

half fable
#

{{ is_state('sensor.dt5930_charge_flap_dc_status', '0') }} => it will set Open if 0 right ?

haughty breach
#

Yes

plain magnetBOT
heavy verge
#

I am trying to convert a sensor that reports strings "Off" and "1" to "100" to an int
I tried the template
{{ states(''sensor.second_floor_odu_status'') | replace("Off", "0") | int }}

#

but the UI refused to accept the double braces, so I get this

#

Oh I can't post a screenshot here

#

Sensor None has device class 'power_factor', state class 'measurement' unit '%' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: '{ states(''sensor.second_floor_odu_status'') | replace("Off", "0") | int }' (<class 'str'>)

lofty mason
#

you need double braces, not single braces

plain magnetBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

heavy verge
#

It errors out in the UI if you use double braces.

#

I just used "combine the state of several sensors", and just used the one, and it seems to be working

mighty ledge
#

it won't error if you're using double bracers, you're doing something wrong

#

double bracers are required for templates

#

If you're using hte UI to create a template sensor, this is all you should paste in the template box

{{ states('sensor.second_floor_odu_status') | replace('Off', '0') | int }}
#

and you can simplifiy it to

heavy verge
#

I did, and it is erroring and not allowing me to proceed. I cannot post the screenshot of it due to this channel not allowing me to.

mighty ledge
#
{{ states('sensor.second_floor_odu_status') | int(0) }}
heavy verge
#

int(0) fixed it

#

Without that it was refusing to proceed, thanks

#

Now it's multiplying it by 100, probably because I set the measurement as a percent

mighty ledge
#

That would do it

heavy verge
#

I added /100, will see if that fixes it

mighty ledge
#

If you just want a value, fill out the UOM only.

heavy verge
#

Yeah I will if that doesn't work

#

Is there an easy way to get rid of the mean/average line on sensors?

mighty ledge
#

elaborate

#

with pictures

heavy verge
#

I don't want the averaging or mean

#

I just want the actual reading

mighty ledge
heavy verge
#

How do I change the graph type for when I click on a measurement on the overview?

mighty ledge
#

The measurement overview is always the statistics graph and you can't change that

heavy verge
#

super

ivory harbor
#

whats the best way to compare a current state to a change? do I have to use a helper to store the previous state? That feels inelegant? This doesnt work {{ (states.sensor.couch_person_count.state | int) == (states.sensor.couch_person_count.attributes.previous_value | int - 1) }}

inner mesa
#

there's no such attribute as previous_value

#

you can see all attributes in devtools -> States

ivory harbor
#

i know... was trying to be illustrattive of the goal

#

I thought this would work: '{{ (trigger.from_state.state | int - trigger.to_state.state | int) == 1 }}'

inner mesa
#

the way to do it is to write an automation or a trigger-based template sensor and do that

ivory harbor
#

ah

brazen gyro
#

Hi, I hope this is the right place to ask a questions regarding template sensor:
I have a sensor, which shows the water-usage of my softner. At the moment it shows 500000 liter (several years, so the value is correct).
As I might want to change the system in the future and don't want to loose historical data I created a simple template-sensor, which just gets the value of my real sensor and integrated it in the energy-dashboard with the following code:
https://dpaste.org/m7x3b
It all works well, but as soon as I restart HA the STATISTICS of the template sensor gets as a one-time value the complete value (500000 liter) of the real sensor and not the 5 minute consumption. So I need to go to the statistics-dev-tool and modify the value.
What am I doing wrong?

marble jackal
#

Your if statement doesn't make sense. As you provided the default 0 for your float filter, it will always be a number

brazen gyro
marble jackal
#

Your problem is the default for the float filter

#

You should use an availability template instead, but you can only do that in YAML, not when you create it in the GUI as a helper

brazen gyro
marble jackal
#

The available template will make your template sensor unavailable, while your default for the float filter made it 0
0 is treated as a reset, which was causing the spikes

brazen gyro
heady sonnet
#

i have a template for checking the forcast that is no longer working
%if state_attr('weather.pirateweather','forecast')[0].precipitation_probability < 51 %}

i can do a call service to get teh infromation but i need to pull out today which shoudl be [0] Can someone help me fix my template?

service: weather.get_forecast
data:
  type: daily
target:
  entity_id:
    - weather.pirateweather
fickle sand
heady sonnet
#

i want to have my automoation check to see if it is going to rain

#

that is the goal, how i get tehre i don't partically care the template above is what worked last year and dosn't seem to work now

fickle sand
#

Okay do you check the template in the conditions part of the automation or in as condition in the actions part?

heady sonnet
#

figure sharing it is easier than trying to explain

fickle sand
#

If the latter you can do it all within the same automation, else if the automation is complex you best bet is to create a template sensor

#

It's a simple automation so we can rewrite it to handle everything within the automation. If you have a minute I can write something that should work

mighty ledge
#

put the condition in t he action section

#

after you get the forecast

heady sonnet
#

i like simpler

fickle sand
#

That is what i am planning to do

mighty ledge
#

kinda redundant to do it like that though

#

with your and condition in there

fickle sand
#

Oh I didn't mind to delete that from the copied over automation. But yeah that can be leaved out

heady sonnet
#

wait which part is redant?

mighty ledge
#

the and condition

#

conditions naturally are and

fickle sand
#
  - condition: and
    conditions:
heady sonnet
#

and so i can learn and hopefully not bother with you in teh future, you are calling the service but how does the templeate get fille dout?

#

and ahh

#

for the redunant part

fickle sand
#

you set the response variable forecastwhere it stores the data from the service call, that variable is available in the actions part for all templates after the service call

heady sonnet
#

can i paste that into the template editor to see what it spits out

fickle sand
#

Nope, it's not available in the template editor, but you can see the response data in the service part of the devtools

heady sonnet
#

yea i got that far

#

it looks like it works, now i just need it to rain so teh automation will fail. unfortuanlly raid isn't looking good these days

#

thank you for the help

analog kayak
#

Scenario: Have a template entity in a trigger like this:
- platform: state not_to: entity_id: '{{ inputs[0].trigger_entity }}' id: 'StateTrigger' alias: '0'
That doesn't work, but this does:

  • platform: event
    event_type: state_changed
    event_data:
    entity_id: '{{ inputs[0].trigger_entity }}'
    id: 'StateTrigger'
    alias: '0'
mighty ledge
#

entity_id does not support limited templates

#

99% sure I already mentioned this to you

analog kayak
#

You did

#

Is there another way to accomplish this with platform state so I don't get triggers on atribute changes?

#

Right now I'm using a condition in the action block to ignore them, but there still a lot of triggers when you open a cover.

mighty ledge
#

Nope

analog kayak
#

Is there a way to conditionally disable triggers?

mighty ledge
#

yep, using limited_templates you can disable/enable triggers

#

but, it's not live

#

limited templates are only resolved on automation load

#

which is why they are limited

analog kayak
#

That would work.

#

Any example of that?

mighty ledge
#

enabled: "{{ whatever variable you want that resolves true/false }}"

analog kayak
#

Ok, that's straightforward

stark apex
#

Hi Team, I need a little nudge (or maybe a big nudge) in the right direction here. I feel like I'm super close to figuring this out but just missing something simple.. I am trying to create an automation that will use the 'get_forecasts' service call so that I can get just the conditions for the upcoming days and turn those conditions into sensors. I'm including where I'm currently at (and stuck). https://pastebin.com/a1ARm7mb. Please guide me down the right path 🙂

marsh cairn
#

At least your response variable is called daily and you are using the variable forecast later

#

Not sure what the condition in the actions is intended to do

stark apex
#

I’m just trying to return the conditions, and nothing else

frail dagger
marsh cairn
#

And I guess the sensor states need an overhaul

frail dagger
#

Well, that's not really an automation. It looks like a template sensor to me. AFAIK, automations can't create sensors.

marsh cairn
#

I missed "automation"

frail dagger
#

Probably just mixing up terms.

stark apex
#

The thought behind the automation was bundling it all in due to the service 'get_forecasts' having to be called on a scheduled basis to continually update. Should those be broken up to where I am calling the 'get_forecasts' at a schedule time with an automation and then using a helper template to create the daily condition sensors?

marsh cairn
#

Template sensors can have a service call action to retreive the data

frail dagger
stark apex
mighty ledge
#

I'm not understanding your question

#

your yaml only needs like 2 changes to make it into template sensors

#

your automation yaml

fickle sand
#

You can use a time trigger in a trigger template sensor that updates once a day

mighty ledge
#
template:
- trigger:
  - platform: time
    at: "00:01:00"
  action:
  - service: weather.get_forecasts
    data:
      type: daily
    target:
      entity_id: weather.tomorrow_io_home_daily
    response_variable: response
  sensor:
  - name: Day 1 Condition
    unique_id: tomorrow_io_d1_condition
    state: "{{ response['weather.tomorrow_io_home_daily'].forecast[1].condition }}"
  - name: Day 2 Condition
    unique_id: tomorrow_io_d2_condition
    state: "{{ response['weather.tomorrow_io_home_daily'].forecast[2].condition }}"
analog kayak
#

Can you make event trigger do 'and' instead of 'or' for event_data?
`trigger:

  • platform: event
    event_type: zwave_js_value_notification
    event_data:
    device_id: !input 'switch'
    command_class_name: 'Central Scene'`
mighty ledge
#

triggers can't be 'and'

analog kayak
#

ok

#

Can I reference an input like this for a trigger entity_id: '!input input1[0].target.entity_id' Where the input name is input1?

stark apex
west loom
#

Hello. I'm trying to get the device name in a numeric_state trigger, e.g. {{ trigger.to_state.name }} too high for {{ trigger.for }}. However, this results in a error: "Error: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'"

mighty ledge
haughty breach
#

You can use the States tool to temporarily set the state above or below your threshold for testing.

west loom
tacit sun
charred dagger
#

For context. This ☝️ is from a discussion in #automations-archived. The intention is that is should show if a sprinkler has been turned on today.
I don't think it will because of the and states.switch.sprinkler1.state == 'on' part.

tacit sun
#

yeah... I removed that.

ivory harbor
#

i have a white space issue. This works, but it gives me a blank line for every entitiy it skips:

             | selectattr('attributes.device_class', 'eq', 'battery')
             | rejectattr('state', 'equalto', 'unavailable')
             | rejectattr('state', 'equalto', 'unknown')
             | map(attribute='entity_id')
             | list %}
          {% for entity in battery_entities %}
            {% set battery_level = states(entity) | int(default=100) %}
            {% if battery_level < 25 %}
              true
            {% endif %}
          {% endfor %}
          false```
#

ugh, indent is right on my end

silent seal
#

Try using {%- endif -%} as that will remove the spaces around that.

ivory harbor
#

drat... didn't change it

#

ill read up some more

#

got it! thanks @silent seal great tip

mighty ledge
#

there are other ways to optimize it

ivory harbor
#

that sets the scale?

mighty ledge
#

I don't know what you mean "sets the scale"

#

anyways, more optimization (but not much)

#
{{ states.sensor 
     | map(attribute='entity_id')
     | select('has_value')
     | select('is_state_attr', 'device_class', 'battery')
     | map('states')
     | map('int', 100)
     | select('<', 100)
     | list | length > 0 }}
#

it would be better if you started without using states.sensor

split spire
#

I want to add a human readable uptime to my esphome devices, I already have an uptime sensor for raw seconds, and it's in the Diagnostic section, however no matter what I do, I cannot get a template sensor to show up there, it always shows up under "Sensors", even when entity_category is set to diagnostic

  - platform: template
    name: Human Uptime
    icon: mdi:timer-outline
    accuracy_decimals: 0
    entity_category: diagnostic
    lambda: |-
      return id(uptime_raw).state;
marble jackal
#

It's best to ask on the ESPHome discord. But I would advise to use the start time of the device as uptime sensor, as it is static and won't have to write a new state to the database every second

ebon copper
#

New to templates, have a bit of a confusion. I'm trying to set up a VPD calculator using the template here https://community.home-assistant.io/t/calculating-vapor-pressure-deficit-or-vpd-in-kpa/162582, put in my sensor info and told it it was an atmospheric measurement sensor. But I'm getting an error I don't understand how to parse:
Sensor None has device class 'atmospheric_pressure', state class 'measurement' unit 'kPa' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'sensor: - platform: template sensors: vapor_deficit: friendly_name: 'vpd in kilo pascals' value_template: >- 1.77unit_of_measurement: 'kPa'' (<class 'str'>)

marble jackal
#

Looks like you pasted an entire YAML configuration in a GUI based template helper

ebon copper
#

uhhhh ... I don't have an option to open a yaml configuration in the UI here

marble jackal
#

only put this part in

          {% set T = ((states('sensor.th16_si7021_temperature') | float) - 32) * 5/9 %}
          {% set RH = states('sensor.th16_si7021_humidity')|float %}
          {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %}
          {% set VPD = ((100-RH) / 100) * SVP %}
          {{-VPD | round(2) -}}
ebon copper
#

oooooooh

#

okay, I get it. Thank you!

#

Added the sensor to my dashboard and it defaulted to mHg for unit of measurement. Curiosity is there any way that I can force it to default to mPa even though it's not an imperial measurement?

#

(working on plant stuff, and it'll be going into some docs to help other plant people who may want to do grow tent automation)

marble jackal
#

you can edit the enitity and choose a different unit of measurement

ebon copper
#

right, that's what I've been doing. I was just wondering if there was a way to pre-empt that for when it comes time for me to write up a guide

willow wing
#

Hey Guys, i have a little error Invalid config for 'template' at templates/Team Tracker/1. Bundesliga.yaml, line 1: 'rest' is an invalid option for 'template' someone can assist me to fix this? here the code

  resource: https://site.web.api.espn.com/apis/v2/sports/soccer/wc/standings
sensor:
  - name: "World Cup"
    unique_id: "World Cup"
    value_template: "{{ now() }}"
    json_attributes_path: "$['children'][0]['standings']"
    json_attributes:
      - entries
marsh cairn
#

You placed a REST integration into the template integration. It is it's own thing.

willow wing
#

yaml is not my world ^^

marsh cairn
#

Your code has to go into the configuration.yaml directly and not into a template include. I guess that's what you are doing.

willow wing
#

oh okay, i was trieing to move it in templates because i head its better

marsh cairn
#

And then you likely have to check your indentation. But that might be me watching that on phone.

marsh cairn
willow wing
#

okay, thank you 👍🏻

west loom
rich moss
#

Hello. Does anybody know how to deal with entities not being ready while starting up? Right now i have a sensor that throws up errros during startup since the entity referenced in its template is not ready for a while during startup.

#

i just tried this but no good:

  - binary_sensor:
      - name: Max Gusts Today Exceeded 30
        device_class: problem
        state: >
          {{ states('sensor.weather_station_max_daily_gust') | float > 29.99 }}
          availability: "{{ is_number(states('sensor.weather_station_max_daily_gust')) }}"```
#

I tried that based on an example in the docs

#

I used quotes like they did but not sure if thats right?

mighty ledge
#

indentation is wrong

rich moss
#

oh crap

#

I am testing it. Just ran into another problem during startup an integration is taking too long to start for some reason but will check back

#

Waiting on integrations to complete setup: {('alexa_media',

#

never had that happen before. its taking way too long

#

but it must be unrelated

#

Will HA eventually give up and move on to the next part of starting?

#

It just finally finished. And I got no value error so i thinks its working now I fixed the indentation! Thanks again Petro!

green yacht
#

(Moved from automations at Tinkerer's request): Still having a bit of trouble with my sprinkler automation. Options 2-5 of my choose action work fine (I just added 5 this morning as a catch all because my yard isn't getting watered with choice 1 and it's been in the mid 90*s F for the last 1.5 weeks), however Option 1 isn't working at all. I got help with the template condition here, but I'm wondering if someone can take a look at the "final" YAML https://dpaste.org/XOhuz I built the automation on June 17th ahead of the time trigger.

The goal was to have a condition that made the 1st choose run every other day

When I test the template in Dev tools I get a string result of ' 0.0 '

mighty ledge
#

your value_template is wrong

#

you have backticks in it

green yacht
#

at the start and end of the template you mean (I've never worked with templates before this)

#

?

mighty ledge
#

you have "`{{...}}`"

#

it should just be

green yacht
#

OH I see that now.

mighty ledge
#

"{{ .... }}"

green yacht
#

so keep the double quotes and drop the single quote

mighty ledge
#

outside that, it seems you're checking for every 1.5 days?

#

which doesn't really make sense

#

those aren't single quotes, those are backticks

green yacht
#

it was to account for daylight savings

mighty ledge
#

backtick `

#

single quote '

#

double quote "

green yacht
#

blind <--

mighty ledge
#

account for daylight savings?? what for

#

what is the goal of that template

green yacht
#

it's meant to be a condition to have the automation choice 1 fire every other day when the time trigger is met

#

there was talk about how using "2" for the days would result in failure a small percentage of the year (daylight savings)

#

🫨

mighty ledge
#

just change your time to be 3am

#

which only happens once a day every day

#

2am falls on DST which means it will be checked twice those days

#

or go 4am

#

to be safe

#

I run mine at 4:45am

green yacht
#

ok. So the to do is: change the trigger to 3 or 4am (or just be fine with it not firing 2x/year) and remove the back ticks from the template?

mighty ledge
#

that's what I'd do

green yacht
#

cool, thank you petro, I'll give that a go!

mighty ledge
#
            value_template: "{{ (today_at().timestamp() // (60*60*24)) % 2 }}"
green yacht
#

appreciate the help/patience

#

Just to be clear, the template should tick over to "2" at midnight correct?

#

it's showing 1 right now

mighty ledge
#

that template will never show 2

#

it will show 1 or 0

green yacht
#

oh as in on or off

mighty ledge
#

it will change to 0 around midnight UTC

green yacht
#

got it! Thank you.

mighty ledge
#

are you GMT?

green yacht
#

gmt -7

#

(truthfully I don't care what days this runs as long as it skips a day between runs)

mighty ledge
#

sorry back

#
{% set offset = (now().utcoffset() - now().dst()).total_seconds() %}
{{ (now().timestamp() + offset) // (60*60*24)) % 2 }}
#
            value_template: >
              {% set offset = (now().utcoffset() - now().dst()).total_seconds() %}
              {{ (now().timestamp() + offset) // (60*60*24)) % 2 }}
#

Your other option is to go with just the day of the year number

#
            value_template: "{{ now().timetuple().tm_yday % 2 }}"
#

but you might get 2 sprinkler days in a row

#

between dec 31st and jan st

#

100% depends on leapyear or not

green yacht
#

OK I'll give this a shot in a bit-- ironically I just had the pipe feeding my sprinklers break. I looked out back and water was shooting 10 ft in the air.

frail dagger
green yacht
#

oh there's still time haha

green yacht
inner mesa
#

add a paren at the beginning

green yacht
#

thank you

ebon copper
#

I have a 2fer issue here. big one is I'm trying to add two integer numeric temps (a nominal temp + an offset) to get a max temp that I can pass to an automation to evaluate if the sensor temp is above the max temp. Images of my sensor configs are here https://imgur.com/a/AYmYrc4 and the state template for the max temp is {{ (states('input_number.day_temperature') + states('input_number.ac_offset')) | float(0) }}

#

The other issue is anyone know why I can't directly edit YAML on HA Container version for helpers?

#

it -looks- to my untrained eye like it's querying the sensors right, but pulling zero for both values (when it should be 73 and 3)

marsh cairn
#

You need to convert the states to a float to add them. Now it tries to add two strings, fails and uses the default value of 0

ebon copper
#

ahhh. I saw somewhere how to do that ... give me a minute

marsh cairn
#

You already did it. Just at the wrong place

#

{{ states('input_number.day_temperature')|float(0) + states('input_number.ac_offset')|float(0) }}

ebon copper
#

ooooh

#

ding! Perfect!

#

and in reality I wanted int, but that's already fixed

marsh cairn
#

States are strings. Attributes can be floats or integers

#

If in doubt - convert them

ebon copper
#

yeah, i'm just still learning HA's logic and syntax. It's a bit backwards from what I'm used to, like doing int(float)

marsh cairn
#

Now we need to convert you to metric units and °C dr_evil

ebon copper
#

-I- can, it's just easier when talking to others local to me. Kind of like how I made a VPD sensor and even though I coded it in mPa, it keeps adding to the cards as inHg

mystic mortar
#
      unique_id: "gas_in_kwh"
      device_class: energy
      unit_of_measurement: kWh
      state: >
        {{states('sensor.gas_usage') | float(0) * 10.26 | float(0) | round(1)}}```

The state above gives data in the template editor, but the custom sensor outputs 'unknown'
inner mesa
#

To start, you're converting 10.26 to a float and then rounding it before using it in the calculation. You need to add parentheses

#

Second, every line after the first needs to be aligned with name:

#

Third, need to see the rest of the template sensor definition .

mystic mortar
#

@inner mesa there all linedup in the code, just not on discord.
As for the other code, there is really nothing that is relevant to this part. There is sensor.gas_usage, which is a util meter in the UI that provides the data .

marble jackal
#

If you create a template helper, only put in the actual template, not the full YAML

#

the YAML is used when you create it in a yaml file

#

But if you want to use this on the energy dashboard, you should create it in YAML and add an availability template. Otherwise you will get spikes in the statistics on every restart of HA

distant plover
#

I have this template sensor where state is time left when washing machine is running, 'Wash done' when it's done and blank state when door is open. Suggestions on how to prevent it showing "Wash done" if the door has been opened but then closed again? {% if is_state("sensor.vaskemaskin_washer_machine_state", "run") -%} 🌀 {{ time_until(states('sensor.vaskemaskin_washer_completion_time')| as_datetime) | replace('hours', 'timer') | replace('hour', 'time') | replace ('minutes', 'm') | replace ('minute', 'm') }} 🌀 {% elif is_state("binary_sensor.bad_vaskemaskin_dorsensor", "off") -%} 💦 Wash done 💦 {%- else -%} {%- endif %}

lucid thicket
plain magnetBOT
#

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

marble jackal
#

You are not outputting anything here, only declaring a variable

#

Still not outputting anything

#

But I'm also not sure what you are trying to achieve

#

You already have a working sensor, you are just creating a new sensor with the same data

#

Okay, just do what they do then, you are declaring a variable hour but not outputting it

#
state: "{{ states('sensor.openweathermap_rain') }}"

Vs

value_template: >
           {% set hour = states('sensor.openweathermap_rain')|float %}
#

Where are you placing this config?

#

I guess you are placing it in sensor.yaml but it doesn't belong there

#

You should place it directly in your configuration.yaml

#

Or create a separate template.yaml

#

This configuration is under the template integration

marsh cairn
#

Which is still the wrong integration

#

That yaml belongs to the template integration, not the sensor one.

#

configuration.yaml

#

As TheFes said

marble jackal
#

sensor rain: !include rainmeter.yaml means you ar including a file under the sensor integration

#

the configuration for this trigger based template sensor is not working under the sensor integration

#

it's belonging to the template integration

#

so you can't put it in this rainmeter.yaml file

#

the only way to include mutliple integrations (sensor and template in this case) in one file is by using packages

plain magnetBOT
#

To enable packages, add packages: !include_dir_named packages to your configuration.yaml so that it looks similar to this:

homeassistant:
  ...
  packages: !include_dir_named packages

Important: The packages: line must be nested under homeassistant:!

For more information on packages, please refer to the packages docs: https://home-assistant.io/docs/configuration/packages/

marble jackal
#

no

marsh cairn
#

That is a sensor, not a template

marble jackal
#

the statistics sensor does belong under the sensor: key as it is belonging to the sensor integration

#

All the HA documentation is written under the assumption that the YAML is placed directly in configuration.yaml. This means that the first line always contains the intengration. In this case sensor:

#

(you added template: yourself here)

marsh cairn
#

Good thing: dog is already fed

#

Hopefully before someone feels insulted by that statement.

#

To make it more clear:
Your swearing and insulting is not appreciated.
It isn't even about anything HA related.

winter belfry
#

I think the main offense is the generalization. Be frustrated with the recall training of the dog instead (I have the same challenge)

bronze prawn
#
unchecked_items: Ezekiel Bread, Salt, Eggs, Bread, Shredded Cheese, Chicken Wings

I have this shopping list. I am using Assist to remove items. I can do stuff like:

 {{ trigger.slots.item | lower in             state_attr(list_entity,'unchecked_items')|map('lower')|list}}

To check if the item is in the list. I want to remove the item if it is in the list, but I am not sure how to grab the value with the proper case. Removing from the list is case sensitive.

#
              - service: todo.remove_item
                data:
                  item: "{{ trigger.slots.item|title }}"

I can use this as I am adding with voice and using title case BUT if the user adds it manually there is no guarantee that the case will match

bronze prawn
#

It's something like this:

{% if "eggs"|lower in (state_attr('todo.anylist_alexa_shopping_list','unchecked_items')|map('lower')|list) %}
true
{%- endif %}

But I don't know how to get the true value "Eggs" as the response.

#

Hope you guys don't mind me talking to myself 🙂

{%- for item in state_attr('todo.anylist_alexa_shopping_list','unchecked_items')|list -%}
{% if ("chicken wings"|lower) == (item|lower) %}
  {{item}}
{%- endif -%}
{%- endfor -%}

So this works. Is this the best way though?

inner mesa
#

I feel like I provided a solution to this a while ago

#

I didn't look too closely at what you're doing there, but isn't that the same thing?

empty bone
#

Hello, I am trying to figure out how to create a weather template that will give me entities and data to put in a weather card I found in HACS. Too say I'm not good with yaml is putting it mildly. I have installed the weather integration "tommorrow.io" and I had a person provide me with an initial template. I tried to compare it with a weather template I found in the HA community files. Honestly I'm not sure I understand if the template I have or the one I found works and what and if I am missing anything. Is there anyone that would be wiling to help me. I need a weather template that works with tommorrow.io integration. Any assistance or guidence would be appreciated.

marble jackal
glacial relic
#

Hi everyone, I’m having trouble accessing tomorrow’s weather forecast in Home Assistant. I’m using the weather.home entity with the met.no integration. The current weather data works fine, but I can’t seem to retrieve the forecast for tomorrow. Here’s what I’ve tried:

Current Weather (works fine):
{% set weather_condition = states('weather.home') %} {% set temperature = state_attr('weather.home', 'temperature') %}

Attempt to Fetch Tomorrow's Forecast (not working):
{% set forecasts = state_attr('weather.home', 'forecast') %} {% set tomorrow_forecast = forecasts[1] if forecasts and forecasts | length > 1 else None %} {% set tomorrow_temp = (tomorrow_forecast.temperature | int) if tomorrow_forecast and tomorrow_forecast.temperature else 'N/A' %}

This results in N/A for tomorrow's temperature. Any ideas on how to correctly fetch tomorrow’s weather data? Thanks!

wanton sapphire
#

you have to use the service weather.get_forecasts to retrieve forecast data

glacial relic
#

Thanks! can you show me an example maybe?

wanton sapphire
#
target:
  entity_id:
    - weather.home
data:
  type: hourly
response_variable: response```
#

after that your forecast will be available in {{ response['weather.home'].forecast }}

glacial relic
#

is there a way to do it in a template?

marsh cairn
glacial relic
#

i tried.. if i copy and paste i get this: "UndefinedError: 'hourly' is undefined"

marsh cairn
#

You likely cannot just copy and paste it, but have to adjust it to your needs

wanton sapphire
marble jackal
inner mesa
#

We really need a more elegant, combined solution for that

lucid thicket
#

I’d love to see something Jupyter-notebook style, and we could choose each cell to be a template renderer, a device call, an event creation, or an event listener. And variables and template output would show below each cell

bronze prawn
bronze prawn
#

I have this:

{{ state_attr('sensor.viewassist_masterbedroom',"data") }}

which returns this:

{'list': 'todo.anylist_alexa_shopping_list'}

I want the value defined by list. How do I do that? I am planning to use this attribute to store a few different items. I thought this may be a handy way to temporarily pass data to the views.

lucid thicket
#

You can use this to get the value of list

{{ state_attr('sensor.viewassist_masterbedroom',"data")['list'] }}
bronze prawn
#

Is there a way to return the type? I think this is being set as just a string

inner mesa
#

then something that you've said doesn't add up

#

you can test this yourself:

{% set test = {'list': 'todo.anylist_alexa_shopping_list'} %}
{{ test['list'] }}
bronze prawn
#

I just tried without putting it in quotes and still does not provide a response. I have used this successfully to post a list but never a dictionary like this

inner mesa
#

using a python script to set a state in the state machine is just a bad idea

#

anyway, you know that you can confirm what attributes the entity has in devtools -> States

#

BTW, JSON requires double quotes for strings, so perhaps that's the issue

#

flip your quotes around

bronze prawn
# inner mesa using a python script to set a state in the state machine is just a bad idea

Yep. I know it's not a good solution. The problem is I have very little time to get up to speed to be able to write an integration. The goal for the project is to get something usable out there and people smarter than me might come in and do some clean up. I'm already seeing a bunch of folks helping with things so it's encouraging to think I might get some help with this. I think it's better to come out with a hacky solution that works rather than focus on finding a perfect one.

bronze prawn
inner mesa
#

again, you can check what attributes the entity has

#

does it have what you expect?

#

my guess is that it just has a string that looks like a dict, but isn't a dict

#

you need to actually provide a dict in the attributes dict that you're providing in your python script

bronze prawn
# inner mesa does it have what you expect?
data: "{\"list\": \"todo.anylist_alexa_shopping_list\"}"

I think this is what you're telling me to check. I clicked on the entity name in dev states and it shows up at the top with all attributes. I had been looking in the column to the right with the attributes and it did not display those espace characters.

inner mesa
#

that's just a string

bronze prawn
#

so it is a string and not an actual dictionary.

#

weird I am able to make a list without problem using the same script but not a dictionary. I guess it doesn't like the double quotes as the list is using single

bronze prawn
inner mesa
#

I don't entirely know what you're doing, but I just threw this together and it works fine:

entities = data.get('entity_id')
if not entities:
    logger.error('No entity_id provided')

state = data.get('state')
if not state:
    logger.error('No state provided')

foo_value = data.get('foo_value')
if not foo_value:
    logger.error('No foo_value provided')

if isinstance(entities, str):
    entities = [entities]

for entity in entities:
    logger.info('entity_id: {} to: {}'.format(entity, state))
    old_state = hass.states.get(entity)
    new_value = {"foo": foo_value}
    new_attributes={**old_state.attributes, **new_value}
    hass.states.set(entity, state, attributes=new_attributes)
#
service: python_script.change_state
data:
  entity_id: input_boolean.test1
  state: "off"
  foo_value:
    foo: bar
    blah: floop
#
{% set value = state_attr('input_boolean.test1', 'foo') %}
{{ value['foo']}}

-> bar

#

it creates or reassigns an existing key in the attributes of an entity to anything you pass in, including a dict

bronze prawn
#

Thanks for the encouragement. I managed to do this:

service: python_script.set_state
data:
  entity_id: "sensor.viewassist_masterbedroom"
  data: "{% set data = {'allow_create': 'yes', 'entity_id': 'no', 'state': 'off'} %} {{ dict(data) }}"

and then:

state_attr('sensor.viewassist_masterbedroom',"data")['state'] }}
off
inner mesa
#

that's a far more complicated way of doing what I did in my service call above

bronze prawn
#

I am already using a script. I tried using your service call example above but it did not work so I modified.

inner mesa
#

it's equivalent to:

service: python_script.set_state
data:
  entity_id: "sensor.viewassist_masterbedroom"
  data:
    allow_create: yes
    entity_id: no
    state: 'off'
bronze prawn
#

Let me double check. Maybe I did something odd

inner mesa
#

you're creating a dict, and then turning that dict into a dict 🙂

bronze prawn
#

haha.. You know this is how I learn right? 🙂

service: python_script.set_state
data:
  entity_id: sensor.viewassist_masterbedroom
  data:
      mystate: off
      entity: todo.anylist_alexa_shopping_list

This works fine. I just am unfamiliar with syntax. I just don't know what I don't know. Again, thanks for your patience.

inner mesa
#

there are only two kinds of data structures in YAML

#

[1, 2, 3] is a list

foo:
  foo: bar
``` is a dict
bronze prawn
#

Well that makes it easy then. I'm glad I won't have the chance to mess this up any more than twice! haha

#

Soooo.. This gets me really close but not all the way. I need to convert:

{{ state_attr('sensor.viewassist_masterbedroom',"data")['entity'] }}

to javascript to use with button card. I can get this far:

list:   '[[[ return hass.states[variables.var_assistsat_entity].attributes.data ]]]'

but not sure how to grab the value for entity. This returns [object Object] . I've tried adding ['entity'] after the attributes.data a few different ways but just get nondescript errors.

slate fossil
#

@bronze prawn The first entity that I found that has a nested attributes list is image_processing.demo_face. Right now, it has a state of Hans. These are the attributes: ```
faces:

  • confidence: 98.34
    name: Hans
    age: 16
    gender: male
    entity_id: image_processing.demo_face
    [...two more face examples but shortened here...]
    total_faces: 4
    device_class: face
    friendly_name: Demo Face```
#

Using "[[[ return states['image_processing.demo_face'].attributes.faces[1].name ]]]" I was able to return Helena who is the second face (not shown in the code above.) Using 0 returns Hans.

plain magnetBOT
#

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

empty bone
#

Oh, I didn't ask my question before hitting enter. My question was where do I place this yaml code for this view?

bronze prawn
#

but it's not working. Am I misunderstanding?

inner mesa
#

data is not a list

#

It is a dict

#

Remove [0]

slate fossil
#

@bronze prawn That may go back to what RobC mentioned about the difference between a dict and a list. (I still don't completely understand the difference myself.) Notice the difference between your attributes and mine: https://i.imgur.com/f5zZpmP.png

bronze prawn
# inner mesa Remove [0]

ButtonCardJSTemplateError: TypeError: Cannot read properties of undefined (reading 'list') in 'return hass.states[variables.var_assistsat_entity].attributes.data.list'

slate fossil
#

I found another entity that might have a similar set-up as yours. "[[[ return states['sensor.persistence_tracker'].attributes.changes['light.all_lights']. This is a persistence tracker that I set-up in configuration.yaml. changes: light.all_lights: '2024-06-22T20:32:44.606108+00:00' light.office_lights: '2024-06-22T18:54:20.159015+00:00' [...shortened...]

bronze prawn
#
[[[ return hass.states[variables.var_assistsat_entity].attributes.data['list'] ]]]

Is not allowed so I'm guessing also invalid

slate fossil
#

Are you trying to "load" the entire object or just a single value? You might need something like list[]: "[[[ return hass.states[variables.var_assistsat_entity].attributes.data['list'] ]]]" if you're trying to get everything into the list variable. Using list by itself (without the []) I think is the difference between defining a simple variable and a dict or list (again I don't know the difference.)

slate fossil
bronze prawn
# slate fossil Are you trying to "load" the entire object or just a single value? You might nee...

I was hoping to pull just the value stored in list. By the way, it's not a list perse. It's a todo list entity just in case there was confusion. todo.alexa_shopping_list is the value that list holds that I'm trying to get.

Long story short, I'm trying to pull that value so that I can use it as the to do list entity for the todo list card so I don't have to build a view for every todo list a user might have.

empty bone
pulsar tapir
#

Hi i was wondering if anyone could help me with this automation? I want to save the current state of input_select.acmode to current_state. Then perform an comparison of current_state and input_select.acmode. I am struggling to set current_state. Any pointers? Sorry if this is the wrong channel. Just redirect me thanks!

variables:
  current_state: "{{states('input_select.acmode')}}"
  value: "states('input_select.acmode')"
condition: template
value_template: "\"{{states('current_state') ==  states('input_select.acmode')}}\""
scenic verge
#

Is there a way to make a history stats based on the average of a entity's number of the last 2 hours? Or if not, simppy record what it was an hour ago, and what it was 2h ago?

#

Its not a linear graph i want to track though. Its a pirate weather entity of rain chance

scenic verge
#

In all the examples in there you have to set a hour of the day. I want to track the last 2h.

marble jackal
#

Set start on start: "{{ now() - timedelta(hours - 2) }}"

wanton sapphire
#

yes, that, or ```
end: "{{ now() }}"
duration:
hours: 2

scenic verge
#

thanks i got it. but how do i now make it track a numeric value and give me the average of the last 2h? what "state" (i suppose) should i put in there?

wanton sapphire
scenic verge
#

thanks, thats looking great for my use case.

#

what happens if the entity behind a history stats or statistics becomes unavailable?

#

the statisticd or history stats also becomes unavailable? or shows 0?

scenic verge
#

anyone know why this sensor i made in configuration.yaml isnt working?

  name: "Last 2 hours of rain"
  entity_id: sensor.pirateweather_precip_probability_0h
  state_characteristic: average_linear
  max_age:
    hours: 2``
#

the entity itself where it gets data from, is showing a percentage. now its 0%

#

the sensor i made shows "not available"

scenic verge
#

it started working when i added the percentile line to the template....but i can only fill in a number of 99? 100 is not allowed. what if the sensor reports 100 as percentage for 2 hours....?

marsh cairn
#

Put on a swimming vest? shksShrug

scenic verge
sonic nimbus
#

{{ (state_attr('media_player.living_room_speaker', 'source_list') | select('not in', ['Bluetooth', 'Line-in']) | list | random) }} it returns me an error

#

IndexError: Cannot choose from an empty sequence

#

TemplateRuntimeError: No test named 'not in'.

#

I got this using chatgpt: {% set sources = state_attr('media_player.system_speaker', 'source_list') | reject('eq', 'Bluetooth') | reject('eq', 'Line-in') | list %} {{ sources | random }}

unique turret
#

How do I go abouts 'grouping` multiple lights to show as 1 using templates? For example: I have 4 lights in a group, and templates should report it is as 1 light

frail dagger
unique turret
#

I get that, I'm not trying to create a group, just wanting to print number of lights on

frail dagger
unique turret
#

so it will show, "1 light is on" instead of "4 lights are on". If I use groups it will always report as 4 lights on

#

At the moment I have this that shows amount of lights in a group:
{% set state= expand(states.light.living_room) | selectattr( 'state', 'eq', 'on') | list | count %} {% if state > 0 %} {{ state }} light on {% else %}Off {% endif %}

frail dagger
#

Yup. That works.

inner mesa
#

could be even simpler

unique turret
#

Yeh, but I don't think you got my initial post. The 4 light bulbs are part of same product, and each bulb is inside the living room group. This shows as 4 lights, I want it to show as 1 light on

inner mesa
#

{{ state_attr('light.xx', 'entity_id')|select('is_state', 'on')|list|count }}

frail dagger
unique turret
#

so 4 ceiling lights, should show as 1 light on

inner mesa
#

the entity_id attribute contains all the group members

frail dagger
#

Ahhhhh... gotcha... gonna steal that 🙂

inner mesa
#

might be a little less computationally expensive, but probably doesn't matter

frail dagger
unique turret
#

Wouldn't you have to create a group within a group to do that? Example:
Hallway light group: 4 Ceiling lights, 1 Lamp

It will show as 2 lights on, not 5?

frail dagger
#

Nope. Just create 2 groups and if you have to, use All entities.

#

I do that in my office. I have the Office Lights group (with 12 lights) and a smaller Office Desk Lights that uses All entities set to true.

unique turret
#

Ah, wasn't aware of All entities option, thanks! 🙂

frail dagger
#

No problem ablobbouncefast

calm dawn
#

Hey folks - Was wondering if you could give me some quick help. I've been racking my brain trying to google for the right answer. I'm using the custom Hass-room-card and creating a template for the secondary property. The secondary property allows for templating.

I want to display the humidity with an icon. My yaml looks like this:

type: custom:room-card
name: Living Room
icon: mdi:sofa-outline
show_icon: true
show_name: true
secondary: |
  {{states("sensor.first_floor_humidity")}} <ha-icon icon="mdi:water"></ha-icon>```

When the card renders the HTML is displayed and not rendered.  

I'm missing something obvious. I was wondering if you could point me in the right direction.
random basin
#

Can someone please tell me how to get templated entity state/attribute value in scripts please. Tried different combination but nothing worked until now.

light_toggle:
  fields:
    entity_light:
      selector:
        entity:
          domain: light
#
  sequence:
    - service: light.toggle
      target:
        entity_id: '{{ entity_light }}'
    - service: tts.google_say
      data:
        entity_id: media_player.bedroom
        message: "'{{ states['entity_light'].attributes.friendly_name }}' turned '{{ states['entity_light'].state }}'"
haughty breach
#
  sequence:
    - service: light.toggle
      target:
        entity_id: '{{ entity_light }}'
    - service: tts.google_say
      data:
        entity_id: media_player.bedroom
        message: |
          {{state_attr(entity_light, 'friendly_name')}} turned {{states(entity_light)}}
random basin
#

Thats awesome @haughty breach You saved me. I never thought it would work without any quote. Even was searching internet until now. Have not got similar posts anywhere yet.

This resolved my issue. Thanks a lot

haughty breach
#

It's important to only use quotes where and when they are needed. Extraneous quotes can be just as bad as missing ones.

thin pivot
#

Help templating results from web service call

rapid horizon
#

@haughty breach I respectfully disagree on avoiding quotes (in general). YAML will typecast some string values if they're not wrapped in quotes, which can lead to unexpected behavior

#

Though yes, if mixing single/double quotes, multi-line strings are a great alternative

mighty ledge
#

it will not miss type cast

rapid horizon
#

@random basin you might find this tool helpful: https://yaml-multiline.info/ There are multiple formats of multi-line strings for YAML. Yamlint can also be helpful, though I doubt there's a convenient way to integrate it with the home assistant UI.

mighty ledge
#

unless it's a specific type, anytime there is a word, it will be a string

rapid horizon
#

@mighty ledge there's a well-known example of this being an issue in the ansible world: file permissions. Specifying an octal number without wrapping it in quotes can sometimes convert it to base 10

mighty ledge
#

but that has nothing to do with what we were even talking about...

#

nevermind the fact that there's a resolver after the fact for templates in home assistant

#

so the output result from your yaml may not match the result being found for the template resolver

#

this is why we have these rules pinned in this channel

rapid horizon
#

I'm talking about general issues with unquoted inline YAML values. I acknowledge your point on Home Assistant -specific YAML though

mighty ledge
#

well there's no reason to confuse the shit of people who don't know yaml

rapid horizon
#

I wouldn't phrase it that way, but yeah, you have a point there as well.

empty bone
#

I need some clarification, I'm trying to understand "templating" in HA. Is a template an automation? Or is an automation considered a template? Would a script be considered a template? And where do the templates reside in HA? or once created where would a user put them within HA?

mighty ledge
#

A template is a template

#

it's all the information between template indicators

#

e.g. {{ ..... contents of your template .... }}

#

see the pins in this channel. One of the pins describes the difference between YAML and templates

empty bone
#

Ok, so I saw the pin on how differentiate yaml from jinjia. So a person who creates an automation and then wants to "add a template" would go into the yaml code of the automation and add in the {{ ...template...}} portion to make it function? Is this correct? And it would get saved right back into the automations folder? The same goes for scripts?

mighty ledge
#

Templates are only allowed in specific places

#

they can be used in specific areas of yaml

#

so your question doesn't make sense as they don't replace an automation or script

#

they suppliment automations and scripts

#

like a tattoo. You can't have a tattoo without skin to put the tattoo on. Well you can't have a template without the yaml to put it in.

inner mesa
#

You'd have to be pretty hardcore to get a tattoo of a template

marsh cairn
#

And it should be correct. After rolling it out, it is read-only

mighty ledge
green yacht
#

can someone show me an example of how a template condition appears in the UI of an automation (not YAML)? I've tried to get a template condition set 3 different ways with the help of people here (different templates), all of them test correctly in the development tools, but none of them actually work in the automation.

frail dagger
green yacht
#

Before anyone says anything, I know the automation is "extensive." Issue is still with choice 1 (always skips). Always defaults to choice 5.

"{{ (today_at().timestamp() // (60 * 60 * 24)) % 2 }}" << no spaces around the *'s

https://dpaste.org/BrpZk YAML

lofty mason
#

get rid of the quotes in the UI I think

frail dagger
#

Same. You don't need the quotes on line 31.

lofty mason
#

Well I think you want one pair of quotes when looking at it in YAML

frail dagger
#

It's weird, it's like it's doing some weird escaping thing.

#

Yeah, just before and after the braces, but I'm also looking at the // and scratching my head on that one.

lofty mason
#

// is floor division

#

divide and round

green yacht
#

I'll give this a test and if it at least fires this time that will be an improvement

#

Thanks guys

lofty mason
#

I'm not sure if returning 1 is sufficiently truthy or not

#

it says it wants a boolean true to pass

green yacht
#

I'll try both and report back

#

thank you!

marble jackal
waxen rune
#

I enter a description on my automations sometimes. Is it possible to fetch that data in a template?
I cant' find out if the description is an attribute (doesn't seem like it) or if there's some other way to use that data.

distant plover
#

I'm trying to create a template sensor with triggers to show 3 states: Time left of washer, Wash done, Idle. If door has been opened after a wash and then closed, the state should be Idle. But ideally I want it to work even if HA restarts. Worst case it must show Idle after a restart and the door is closed, not Wash done. I can't get it to work properly. Help? 🙂 https://pastebin.com/QP32L0GA

weary canyon
#

Hi, I would like to create a template sensor for sensor.sun_next_dusk - 10mins. I am currently struggling to build the template - can anyone help please. Sorry new to all this!

marble jackal
#

the template will be:

#

{{ states('sensor.sun_next_dusk ') | as_datetime - timedelta(minutes=10) }}

weary canyon
#

wow, that was so quick, thanks! missed the timedeleta part

marble jackal
#

you can create a helper in the GUI and apply the state class timestamp

#

then you can use it for time triggers

weary canyon
#

do I need a unit of measurement

marble jackal
#

no

weary canyon
#

works, thansk so much Fes

distant plover
#

I can't get my head around this. Can I change it to only show Wash done when sensor.vaskemaskin_washer_machine_state goes from run to stop and else show Idle?

marble jackal
#

you can make it a lot easier if you just add more triggers

marble jackal
#

and what does it show when it is active

distant plover
#

When wash is done it's set to 3 hours later. I had a wash done 18:32 and it was then set to 21:15. Today at 08:43 it was set to 11:26 even though I haven't put on any wash.

#

When active it shows the time when wash is done

marble jackal
#

okay

#

but it's a datetime string including the date right?

distant plover
#

Don't understand why it suddenly set that at 08:43 today. I did nothing. Perhaps an update to Samsung servers.

#

Current state is 2024-06-25T09:26:14+00:00

#

So yes 🙂

marble jackal
#

that's in the past

#

it's currently 10:53 UTC

distant plover
#

Yes. I think it's mostly idle unless a new wash is put on. When that happens it would say something like 2024-06-25T12:26:14+00:00

marble jackal
#

okay, you just said it was 3 hours in the future when there is no wash active

#

or that only happens at the moment the wash finishes, and then it remains the same until a new wash is turned on

distant plover
#

Yeah, that seems correct (except for that fluke this morning at 08:43 where it set the time to 11:26)

marble jackal
#

did you restart HA at 8:43?

distant plover
#

My sensor.vaskemaskin_washer_machine_state has been 'stop' since 18:32 yesterday

marble jackal
#

so you want it to be idle after the washer is done, until the door is opened

distant plover
#

No restart.

marble jackal
#

after the door is opened, you want it to be wash done

distant plover
#

No. Wash done when washer is done until door is opened. Then Idle.

marble jackal
#

okay

distant plover
#

The problem I've had is if the door is then closed again. Then it would show Wash done. I don't want that.

marble jackal
distant plover
#

Will do. Thanks!

#

Maybe the wife can put on a wash 😆

#

Hm. I put it in and restarted and got Invalid config for 'template': expected str for dictionary value 'to', got None. The template sensor itself is unavailable.

#

sensor.vaskemaskin_washer_machine_state is stop, binary_sensor.bad_vaskemaskin_dorsensor is on, sensor.vaskemaskin_washer_completion_time is 2024-06-25T09:26:14+00:00

marble jackal
#

@distant plover no need to restart, just reload template entities

#

to: on on line 13 should have been to: "on"

distant plover
#

Good tip on the reload template. I'll remember that. And "on" made it work. Thanks. 🙂 Will do some testing.

waxen rune
#

I'd like to do a clean up in my system and find any references to entities that doesn't exist any more in automations and scripts. I know how to write a template for listing all entities that do exist.
Can I somehow do it the other way around, like searching automations.yaml and scripts.yaml for non-existing entities (with a template)?

frail dagger
waxen rune
#

Thanks, I'll have a look there!

waxen rune
frail dagger
dark epoch
#

I'm working on a template that looks at Calendar entries to check for label entries. The idea is that if a calendar entry has a location label assigned, and that location contrains the word "Office" the code should return a 1, otherwise it should return a zero. I'm looping through all calendar entries and labels to do this. I've been using AI, but it cannot figure out how to make it work. Perhaps I can get better luck with actual people? - Here is the code I have that does not work properly. My best guess is that Jinja2 sees 'result' as a global variable outside the loop and as a local variable inside the loop, but that's a guess.

plain magnetBOT
#

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

mighty ledge
#

that code just looks at a curated list of things. It doesn't look at any entities.

#

as for why that code is failing, you need to use namespace to store values that update within loops

#

e.g.

{% set ns = namespace(result=0) %}
...
{% set ns.result = 1 %}
...
The result is: {{ ns.result }}
dark epoch
#

Sorry, I copied the AI code example trying to fix it, this is the code looking at HASS:

#

{% set result = 0 %}
{% for entry in states.calendar %}
{% for label in entry.attributes.labels %}
{% if "Office" in label %}
{% if entry.attributes.due_today == true %}
{% set result = 1 %}
{% break %}
{% endif %}
{% endif %}
{% endfor %}
{% endfor %}

#

But I will try the namespace fix now

marble jackal
#

same issue regarding the namespaces

mighty ledge
#

entities do not store labels in attributes

marble jackal
#

and labels is no attribut... 🐌

dark epoch
#

If I put {{ label }} inside the second loop, it does return the correct label value

#

Is this an unstable way to access that label?

mighty ledge
#

that's just not a way to access labels

#

no idea how that is working for you.

#

as it's not a thing that works.

dark epoch
#

The namespace fix actually got it to work, but I do want to fix the label access so it doesn't break with the next codefix

frail dagger
#

You're not accessing any lables though. Nor any entities. How are you planning on building your calendar entries?

mighty ledge
#

he's accessing calendars in his second post

#

but he's also accessing a made up attribute

dark epoch
#

Here are the attributes I see in the States viewer for the calendar entry:

#

friendly_name: Scott to Work
message: Scott to work
all_day: false
start_time: 2024-06-25 06:09:21
end_time: 2024-06-25 07:09:21
location:
description:
due_today: true
overdue: true
all_tasks: Scott to work
priority: 1
labels: Andon Office Blue

mighty ledge
#

what integration?

dark epoch
#

Todoist - the tasks automatically show up as calendar entries

#

since the tasks have far fewer details

mighty ledge
#

is that custom?

#

are those labels, labels set in todoist or labels set in HA?

dark epoch
#

It's a HA integration and not HACS if that is what you mean?

#

labels are set in Todoist

mighty ledge
#

ah ok, so they are not HA labels, that's the confusion here

dark epoch
#

Oh! - yeah, I forgot HA created their own labels

mighty ledge
#

that attribute is not normal, and don't associate that attribute with HA labels

#

if you add other calendars, that template will fail because that attribute doesn't exist

dark epoch
#

It doesn't seem to, here is the calendar entry right below that from the Holiday Integration:

#

message: Independence Day
all_day: true
start_time: 2024-07-04 00:00:00
end_time: 2024-07-05 00:00:00
location: United States, NV
description:
friendly_name: United States, NV

marble jackal
#

for labels in entry.attributes.labels seems wrong here, at least with that example you gave

mighty ledge
#
{% set ns = namespace(result=false) %}
{% for entry in states.calendar if entry.attributes.labels is defined %}
    {% for label in entry.attributes.labels %}
        {% if "Office" in label %}
          {% if entry.attributes.due_today == true %}
            {% set ns.result = true %}
            {% break %}
          {% endif %}
        {% endif %}
    {% endfor %}
{% endfor %}
#

that will work for only todoist calendars

marble jackal
#

there is only one string in that labels attribute, so for label in entry.attributes.labels will split that up in the individual characters

mighty ledge
#

that's not necessarily true

#

the states table doesn't make lists of strings look nice

#

it's most likely a list at all times but the states table "pretties it"

marble jackal
#

could be

mighty ledge
#

I really hate the states table's attributes parser

marble jackal
#

unless they copied it from the overview after clicking the entity_id. That will show it as a list

dark epoch
#

Yes, Todoist Labels come over as a list

#

friendly_name: Scott to Work
message: Scott to work
all_day: false
start_time: 2024-06-25 06:19:21
end_time: 2024-06-25 07:19:21
location:
description:
due_today: true
overdue: true
all_tasks: Scott to work
priority: 1
labels: Andon Office Blue, Andon Bar Blue

#

Here it is with two labels - This should return 1 if the code looks for "Office" and 1 if the code looks for "Bar"

mighty ledge
#

FYI @marble jackal here's a screencap of a list with 1 item from a select entity

#

and here's one with multiple options

#

aka, hides the list with 1 option

dark epoch
#

So do I need to change this line: "for label in entry.attributes.labels"

marble jackal
#

yeah, I kinda assumed he copied from this:

mighty ledge
#

I already fixed it for you

dark epoch
#

I don't understand. I thought accessing entry.attributes.labels was the issue but it also shows in your code

#

Is it ok to use as long as I am filtering out undefined entries?

mighty ledge
#

right, but look at the added if statement 😉

dark epoch
#

Ok, but I thought the whole issue was that this is a non-standard way to access that data. Did I misunderstand, or was that the confusion about Todoist Labels and HA Labels?

mighty ledge
#

the confusion was about todoist labels and ha labels

dark epoch
#

Got it - Ok, thanks for the help!

green yacht
slender adder
#

message: The forecast is {{ states('weather.forecast_thuis') }}
{{ attributes('weather.') }}

Can i get attributes from a entity this way?

#

i dont know anything from templates XD

#

Attributes
temperature: 23.1
dew_point: 18.4
temperature_unit: °C
humidity: 74
cloud_coverage: 0.8
pressure: 1012.4
pressure_unit: mbar
wind_bearing: 81.8
wind_speed: 8.6
wind_speed_unit: km/h
visibility_unit: km
precipitation_unit: mm
attribution: Weather forecast from met.no, delivered by the Norwegian Meteorological Institute.
friendly_name: Forecast Thuis
supported_features: 3

#

ah works like this
"{{ state_attr('weather.forecast_thuis','temperature') }}"

slender adder
#

Another question did some1 get it to work to send a todo-list as a notification?
I wanna use it as a grocery list, and when some1 enters the zone of the supermarket it needs to send that notification to the device of the user who entered

distant plover
# marble jackal `to: on` on line 13 should have been `to: "on"`

I've tested it a bit now and understand more of the template and I realize that the trigger to update time left only triggers when the state of sensor.vaskemaskin_washer_completion_time changes. How can I change it so it's updated every minute basically (since I want to see time_until and not what time it's done)? I don't want the state of the template sensor saying it's 59 minutes left and the next minute it's 'Wash done'. 🙂 https://dpaste.org/Rx37c

#

Don't need one minute interval but I want it to be updated according to time_until. {{time_until(states('sensor.vaskemaskin_washer_completion_time')| as_datetime)}} is now 30 minutes but {{states('sensor.vaskemaskin_complication')}} is 🌀 1 time 🌀.

mighty ledge
distant plover
#

Ok. But do I understand this correctly, if I don't have any triggers the state of a template sensor is 'live'? If you understand what I mean, hehe

mighty ledge
#

sorry, i don't understand what you mean

#

typically, it's not a good idea to have a state constantly update based on time

distant plover
#

If I have just this it will update constantly, wouldn't it? sensor: - name: Vaskemaskin complication unique_id: vaskemaskin_complication state: > 🌀 {{ time_until(states('sensor.vaskemaskin_washer_completion_time')| as_datetime) | replace('hours', 'timer') | replace('hour', 'time') | replace ('minutes', 'm') | replace ('minute', 'm') }} 🌀

mighty ledge
#

it would update once a minute

#

again, you typically don't want that to happen

#

it will just flood your database with useless data

#

that's why things are left as a timestamp

#

and if you want a notification, then you perform the math in your notification

#

if you want the time displayed on the frontend, you keep it a timestamp sensor and display that in the frontend. It will countdown without state updates.

distant plover
#

I see. All that makes sense. My issue is that I want to display it as a complication on my WearOS watch. And there I can only show the state of a sensor.

mighty ledge
#

and you haven't put the completion_time on that?

#

I'd try that first instead of what you're doing.

distant plover
#

The idea was to avoid having to calculate myself how much time is left by looking at two timestamps 😛

mighty ledge
#

right, but there's no reason for that because the UI typically does that for you with timestamp sensors.

#

the whole point of timestamp sensors is to show a relative time that counts down or up in the UI without having state changes

distant plover
mighty ledge
#

I really don't think you're understanding what I'm saying.

#

if you put the timestamp sensor there, it will show up as a relative time

distant plover
#

Hold your horses. Must try! 😄

distant plover
#

Well, it works like you said. But I can't tweak it to my exact preference. Like surrounding emoticons. And '40 m' instead of 'om 40 minutter'.

coral marsh
#

How do I hide | separator, to only show when the second line of code is present (light count)?

  expand(states.light.kitchen) | selectattr( 'state', 'eq', 'on') | list | count
  %} {% if state > 0 %} {{ state }} light  {% else %} {% endif %}```
mighty ledge
#

move it inside your if statement

coral marsh
#

Ah lovely, thanks

plain magnetBOT
#

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

tawny coral
#

I've tried executing it normally but it still doesn't run "option 2" which is to turn on 1 ac and set the FTX to high

#

when i check the timeline it says "Choose: no action executed"

#

So the question then is, is this an incorrect template?

action:
  - choose:
      - conditions:
          - condition: template
            value_template: "{{ trigger.to_state.state | float > 23 }}"
        sequence:
          - type: turn_on
            device_id: 71335c8dc91194f73296da6293294841
            entity_id: 983f94b37c36bb0df51bfcf66a13c096
            domain: switch
          - service: switch.turn_on
            data:
              entity_id: switch.vsr300_man_high_mode
marble jackal
#

why not use trigger id's?

#

template should work though, I would advice to use numeric state triggers instead of device triggers

hallow plover
#

Is there a less-kludgey way to say:

(175 < state_attr('light.night_lights', 'rgb_color')[0] < 185) and 
(5 < state_attr('light.night_lights', 'rgb_color')[1] < 15) and 
(245 < state_attr('light.night_lights', 'rgb_color')[2]) 
}}```
#

A way to see if an RGB value is 'around' a certain set of values? Better yet, 'around' a certain color name?

plain magnetBOT
#

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

mighty ledge
#

@unborn acorn assuming you mean you want to use target? value_template: "{{ target == 'Option 1' }}"

unborn acorn
#

yes. thx that worked!

plain magnetBOT
#

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

unborn acorn
#

trial and error {{ target_position }}

mighty ledge
unborn acorn
#

Another question, is it possible to change color on an icon based on a helper variable or a sensors data?

mighty ledge
unborn acorn
#

thx

lucid thicket
#

Any way to do element-wise addition of lists or tuples without looping? i.e.
(1,2) + (3,4) = (4,6)

mighty ledge
#

nope

#

that would require numpy

lucid thicket
#

Or maybe zip that i still haven’t gotten to making a pr for. Maybe in a few months…

mighty ledge
#

You can still do a half-ass zip

#

for x in y:
set a, b = x

#

or for a, b in y

#

sorry, brain fart on that last response

#

yes zip

#

implementation is quick, testing would be a PITA

haughty breach
#

You can abuse dict():

{% set x = [(1,2),(3,4),(5,6)] %}
{% set d_x = dict(x) %}
{{ (d_x.keys()|sum, d_x.values()|sum) }}

Edit: Fixed making the dict twice