#templates-archived

1 messages · Page 71 of 1

thin spindle
#

I guess its just too high for me, as HomeAssistant is still new to me.

#

do you mind share your code pieces?

#

what I started was this:

plain magnetBOT
#

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

fickle sand
#

Yep, I will start a thread with the pieces I have

#

Do you have a power sensor for the charger?

thin spindle
thin spindle
fickle sand
#

Calculate individual devices energy costs

dense swan
#

Quick question...

{{ states.sensor.office_sensor_temperature.state | round > 74 }}

Would only be rendered every minute as a Template Trigger according to the docs right?

inner mesa
#

no

#

it would be rendered whenever the state of that entity changes

dense swan
#

Ok, so if the sensor is updating it would then update based on the update time.

mighty ledge
#

it updates live

#

source changes -> template changes

inner mesa
#

and should be written as follows:
{{ states('sensor.office_sensor_temperature')|float(0)|round > 74 }}

mighty ledge
#

you can skip the float if you use round

#

#themoreyouknowrobc

inner mesa
#

you're confusing a template that just starts with states|.... with one that specifically targets an entity

#

yeah, well

#

better safe than sorry

dense swan
#

ahh ok thanks!

mighty ledge
#

round float's the value, taht's why round accepts a default

storm rose
#

Hi folks... I am newbie with HA and I would like to create a sensor from weather.get_forecasts service. When I call following using dev tools, it works:

service: weather.get_forecasts
target:
  entity_id:
    - weather.chambery
data:
  type: hourly

But following template does not set my sensor state:

- trigger:
    - platform: event
      event_type: refresh_1h
  action:
    - service: notify.mobile_app_black
      data:
        message: test
    - service: weather.get_forecasts
      target:
        entity_id:
          - weather.chambery
      data:
        type: hourly
      response_variable: hourly_forecast
  sensor:
    - name: Météo dans 1 heure
      unique_id: h1_outdoor
      state: "{{ hourly_forecast['weather.chambery'].forecast[1].condition }}"
      attributes:
        temperature: "{{ hourly_forecast['weather.chambery'].forecast[1].temperature }}"

Where I am wrong?

mighty ledge
#

the only thing that looks odd is your trigger

#

everything else looks fine

storm rose
storm rose
mighty ledge
urban rune
#

When a state trigger has a for property and an empty to property (i.e. sensor must be at a fixed value for at least 1 minute), what will the trigger.from_state.state value be? Will it be the previous value it was at, or the previous value it was at for 1 minute ?

inner mesa
#

it will be whatever value it was before it changed and stayed the same for 1 minute

#

the for: clause has nothing to do with the previous value

rocky hawk
shadow summit
#

nevermind i figured it out. way easier than i expected

plain magnetBOT
#

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

quasi frost
#

good mrning, i am trying to calculate 2 entys and round the result:
{{ states("sensor.nas1_volume_2_gesamtgrosse") | float - states("sensor.nas1_volume_2_belegter_speicherplatz") | round(2) }}

Bute the result is not roundend:
Result: 3.1200300871680007

#

whats wrong?

marble jackal
#

You're only rounding the last one

#

Convert the last one to float as well, add parenthesis around the calculation and then apply the round filter

#

@tardy saddle that code is for a card on your Dashboard, not for a template sensor. It uses JavaScript, which is only used on the #frontend-archived in specific cards

unkempt oyster
#

Hello, which LLM AI is best for generating home-assistant templates?

mighty ledge
#

They are all pretty bad

#

none of them "get it right"

#

no matter what, it will require knowledge to fix

unkempt oyster
mighty ledge
#

that's not a template

#

that's a light provided by the template integration

#

this channel is specifically about jinja templates

#

which is everything in {{ }} or {% %}

thin spindle
#

I have problems casting the right value to a input number.
Can you tell me how I have to declare it?

metadata: {}
data:
  value: '{{ sensor.auto_ladevorgang_netzstromkosten }}'
target:
  entity_id: input_number.auto_ladevorgang_netzstromkosten_vor_ladebeginn```
mighty ledge
#

That example is a pretty good starting point

thin spindle
#

sensor.auto_ladevorgang_netzstromkosten is a helper of type riemann integrator

mighty ledge
thin spindle
#

normally by states

mighty ledge
#

ok then, so what are you missing from your template

thin spindle
#

🙂

#

so this is good?

#
metadata: {}
data:
  value: states('sensor.auto_ladevorgang_echtstromkosten')|float(0)|round(2)
target:
  entity_id: input_number.auto_ladevorgang_echtstromkosten_vor_ladebeginn```
mighty ledge
#

now what are you missing?

thin spindle
#

or do I have to cast with {{ }}

mighty ledge
#

what is required in pin 2 for all templates?

thin spindle
#

so like this:

metadata: {}
data:
  value: {{ states('sensor.auto_ladevorgang_echtstromkosten')|float(0)|round(2) }}
target:
  entity_id: input_number.auto_ladevorgang_echtstromkosten_vor_ladebeginn```
mighty ledge
#

Now you're missing another requirement for yaml

mighty ledge
#

this link

thin spindle
#

ok so I need to quote for yaml <=> jinja and {{ }} for the inside jinja part

mighty ledge
#

yep

thin spindle
#

so this should be good right?

metadata: {}
data:
  value: "{{ (states('sensor.auto_ladevorgang_echtstromkosten')|float(0))|round(2) }}"
target:
  entity_id: input_number.auto_ladevorgang_echtstromkosten_vor_ladebeginn```
mighty ledge
#

yep

thin spindle
#

thanks for the link also - I didnt saw a explaination like this yet 👍

mighty ledge
#

take a moment to read all the pins, they have good info

thin spindle
#

I will do so! Thanks 🙂

tardy saddle
runic egret
#

Hey, I have some matrix switches with 4 buttons with led behind each. I have a script where I turn off all 4 leds to reset the color. However I want to make it more smarter, since I dont want to add a script for each switch. How can i do that.

The script looks like this now, for one device.

service: light.turn_off
data: {}
target:
  entity_id:
    - light.matrix_kontor
    - light.matrix_kontor_2
    - light.matrix_kontor_3
    - light.matrix_kontor_4
mighty ledge
#

If I understand you correctly, the 4 lights make up a color?

runic egret
#

no, there is 4 buttons, with each an rgb led

#

but I found another solution

runic egret
#

I have to set a zwave parameter on the device instead

#
service: zwave_js.bulk_set_partial_config_parameters
data:
  parameter: "31"
  value:
    "65280": 0
    "16711680": 0
    "4278190080": 0
target:
  device_id: 3db9cf9bd81b65a28baabf976ede9bcd
alias: Button 2 LED indicator OFF
mighty ledge
#

I still don't see what you need multiple scripts for

runic egret
#

I don't anymore 🙂 its was mostly because of a setting, where it didn't turn off the light correctly after indicating a push

tribal cedar
#

Would any templating experts mind helping me on this one. I basically have an input_select which has a list of entity ids for various motion sensors in my house. I then use a template like below on a custom template sensor, per room (eg utility room below) where I check for any motion sensors that have the word 'utility', if any of their states are 'on', then my overarching sensor is also on.

{{ (states.input_select.all_motion_sensors.attributes.options | select('search', 'utility') | map('states') | select('search', 'on') | list | count) > 0 }}

This has been working fine for many months, however I have various cases where my motion sensors messages that motion is no longer detected on a sensor (or if HA reboots) are not reaching HA for various reasons. This causes the motion sensors to get stuck in an 'on' state until someone again walks past them. It has meant some cases where some lights are left on all night, or unexpectedly left on during other period after a HA restarts.

As a workaround I was thinking of updating the template above to also only mark this overarching sensor as 'on' if some of the motion sensors attributes.last_triggered was eg in the last 5 minutes. And to filter out any who are 'stuck' for longer than this. I have been trying to no avail to get the template to filter these out. Any ideas of a way to do it? Hoping to find some way to maybe 'reject' items using something like

((as_timestamp(now()) - as_timestamp(state.attributes.last_triggered)) | int) > 300

But now to get that into my existing template, I'm getting lost.

plain magnetBOT
#

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

ocean bear
lofty mason
marble jackal
#

@tribal cedar
{{ expand(state_attr('input_select.all_motion_sensors', 'options')) | selectattr('entity_id', 'search', 'utility') | selectattr('state', 'eq', 'on') | selectattr('last_changed', '<', now() - timedelta(minutes=5)) | list | count > 0 }}

#

But why use the options for an input select for this? A binary sensor group would make more sense I would say

steel marsh
#

what does everyone think would be the best way to tackle a switch that sometimes goes unavailable. It is Meross plug, which has two switches (one local/lan and the other one cloud based). So say I wanted the switch to primarily use the local option, but if the local one was unavailable, then it uses the cloud one. Would some type of switch template be the best method?

ocean bear
#

oooooh - I got my errror
Option was called 'PV-Überchuss ' with a space at the end......what the hell...
Used this helper for over a year only in an automation - so I just clicked the option, never had the need to rewrite it...

#

thanks for helping

#

maybe something to implement - shouldnt be alowed imho

analog mulch
#

You could drive your desired state with an input_boolean helper. And then have an automation which would flip the local switch if available else switch the cloud and flip the local switch to match the input_boolean whenever it came back alive

#

Or just create a switch entity which basically does the same

runic swan
#

Hi friends, I'm trying to make a template that takes in multiple doors and uses their "open" state as a trigger; that is, trigger an action when any of them transition to open, even if another one was already open (so I can't do "when this group transitions to on..." as a trigger). Is there a good way to do this? I couldn't figure out how to do a multi-select in the automation variables. I was trying to use a fairly complex numeric state template as an alternative (that way I could make a door group outside of the blueprint and expand and check from there), but that doesn't seem to work (even though the template itself works in the template preview in dev tools when I sub in the entity ID for state.entity_id: {{ now() | as_timestamp - states[expand(state.entity_id) | sort(attribute='last_changed', reverse=true) | map(attribute='entity_id') | select('is_state', 'on') | list | first].last_changed | as_local | as_timestamp }} has a result of 0.005... right after I open the door).

Any ideas?

naive swan
runic swan
naive swan
mighty ledge
#
template:
- sensor:
  - name: last open
    unique_id: alsdkfjaoiehavajksdlkj
    device_class: timestamp
    state: >
      {{ expand(... your list of entities to track) | selectattr('state','in', ['on','open']) | map(attribute='last_changed') | sort(reverse=True) | first }}
    availability: >
      {{ expand(... your list of entities to track) | selectattr('state','in', ['on','open']) | map(attribute='last_changed') | sort(reverse=True) | first | default(None) is not none }}  
inner mesa
#

that just points out that template sensors need a variables: section

mighty ledge
#

Keep in mind, if you use states without (), your template will be throttled to at most 1 update per minute.

#

shhh

#

⁽ᵇᵘᵗ ʸᵉˢ⁾

runic swan
mighty ledge
#

using just states

#

I just made a post about this on the forums

#

How frequent will a template update? Click here to see.

marble jackal
inner mesa
#

That's a thought

steel marsh
analog mulch
#

In the turn_on/off keys you can write a short script checking if the local switch is available and flipping one or the other depending

#

The multiple command version in the docs is the relevant one

bronze prawn
#

{{expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list |first}}

I hope this is the last time I am asking for help on this. I have this and it works great, but I would now also like to modify this for a different call where it will return the entity from the group that matches sensor.assist_last_called. I think I need to do something with map(attribute='attributes.display_device') to return just the entity name but try as I might I am not able to figure it out.

atomic blade
#

I'm getting this error Template error: as_datetime got invalid input '2024-03-21 04:00:09-06:00', but if I run as_datetime("2024-03-21 04:00:09-06:00") in the template devtools it's fine.
The error does later say no default was specified as well, but I don't get why it's saying that input is bad in the first place...

steel marsh
marble jackal
#

I have a PR open to make that work (it will just not do anything with it, and return the input as output)

atomic blade
marble jackal
atomic blade
#

Yeah probably a good idea to have that overloaded on the backend

#

It's just hard to see in the error message what type it is

marble jackal
#

you could do:

{% set date = now() %}
{{ date if date is datetime else as_datetime(date) }}

or

{% set date = now() %}
{{ as_datetime(date, date) }}
inner mesa
#

Doesn't some version of that give a 'cannot convert to float' error?

#

That's always a weird one

marble jackal
#

the last one will return de input as output in case it can not convert it

mighty ledge
#

Datetime objects are "overloaded" in the backend

#

the normal output for a datetime object is not 2024-03-21 04:00:09-06:00

inner mesa
#

I think it's the same use case

mighty ledge
#

when stringified

#

normal output for a datetimeobject is datetime.datetime(year=..., day=.......) when stringified

#

so it may be missleading, but that's done on purpose specifically for variables in automations and outputs from templates

atomic blade
mighty ledge
#

yes, but you're talking about the error which is

atomic blade
#

But yeah if that's the stringified version then it doesn't seem like it was a date object after all?

mighty ledge
#
Template error: as_datetime got invalid input '2024-03-21 04:00:09-06:00'
marble jackal
mighty ledge
#

I instantly know what the problem is, because I know a stringified datetime in HA will output YY-mm-dd HH:MM:SS-ZZ:ZZ

#

the error should probably not use the HA __str__

atomic blade
#

Ahh ok so it is a datetime

mighty ledge
#

yes

atomic blade
#

Or the error can just be sure to include the type

mighty ledge
#

a string with the format YY-mm-dd HH:MM:SS-ZZ:ZZ will always resolve to a datetime and won't produce the error

#

so this is just a rule you should keep in the back of your mind

marble jackal
#

or as_datetime() could just return the datetime object instead of throwing an error 🙂

mighty ledge
#

That too

#

as does float or all other conversions

atomic blade
#

This whole setup is kinda janky anyways how I'm using imap. I think the imap integration should be fixed to not emit events but make use of the new event entity

marble jackal
atomic blade
#

It also re-emits events when the integration is loaded. So I had to add something to check for the email date. Having it not re-emit would also fix this

marble jackal
#

ah, you were using it for imap events

#

those are indeed datetimes already

#

and I had the same issues

#

with the integration emitting events every time it's reloaded

inner mesa
atomic blade
#

Nice, I've never heard anyone else using it and was surprised

#

Would you agree converting that to use the new event entity would be appropriate?

mighty ledge
#

new event entity?

atomic blade
#

newish. Introduced maybe mid last year?

mighty ledge
#

yeah, if it outputs events, any ingration using old events should change to the event entity

#

but that doesn't always happen

atomic blade
#

I want to say the imap change was made maybe a little before the event entity was introduced?

marble jackal
#

The event has quite some data though

atomic blade
#

true...

#

Well otherwise it should at least be fixed to not re-emit on reload

eager yarrow
#

Q: I made an overview for monthly, bi-monthly, quarterly [...] recurring tasks from a dedicated calendar. Working fine, now in the optimization phase. Is it possible to 'template' the definition of attributes, so I could write something like '[Jan, Feb, Mar ....]' in the definition file and write the code once to shorten it? It's 12 times more or less the same code --> screenshot here | code to optimize here.

plain magnetBOT
#

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

bronze prawn
#

ughh.. that's ugly. Reposting:

Still stuck.

#
{{expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list |first}}

Which returns the entity in the group who's associated mic was last called. This returns the display_device attribute of that entity.

#

I now want the same type of thing but instead I just want the entity member of the group to be provided. I've tried altering this to get rid of the attributes portion but I am getting back a lot of data and I'm not sure how to pull just what I need from it:

{{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | list  }}

It returns this as an example:

#
[<template TemplateState(<state sensor.assistsat_viewlrthinksmart=; title=Wikipedia Search, message=, image=, timer=, alarm=, cycle_view=, mode=normal, mic_device=sensor.thinksmart_lr_stt, mediaplayer_device=media_player.thinksmart_lr, display_device=sensor.thinksmart_lr_browser_path, browser_id=Thinksmart-LR, view_timeout=20, message_font_size=3vw, friendly_name=AssistSat_ViewLRThinksmart @ 2024-03-19T12:34:43.354585-05:00>)>]

I can see the name I'm looking for which is the very first part "state sensor.assistsat_viewlrthinksmart=" and I want the "sensor.assistsat_viewlrthinksmart" returned. I'm sure this is easy but I've been scratching my head on this for a long while now. Can someone show me what I'm doing wrong?

inner mesa
#

you're missing a map() call

#

you need to specify what you want returned out of that object

#

in this case, probably |map(attribute='state')|list|first

bronze prawn
#

Group is defined as:

assist_satellites:
  name: Assist Satellites
  entities:
    - sensor.assistsat_viewlr
    - sensor.assistsat_viewlrthinksmart  
#

To be clear, I'm wanting to check the attributes of each one of the group entities to see if the attribute mic_device matches the 'sensor.assist_last_called' value and then return the name of the group entity member that matches.

#

I'm not sure why it's returning the value it is returning but note that the state is null from the example I show above

inner mesa
#

so you want the entity_id

#

so: {{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) |map(attribute='entity_id')|list|first}}

bronze prawn
#

ohhh.. I didn't realize that was an attribute

inner mesa
#

it's confusing terminology. it's not an attribute of an entity as defined by HA, but it's an attribute of the state object

bronze prawn
#

Right. I see that now. I was thinking that it's not listed as a attribute so that's not the way but I get it. Thanks for clearing this up. NOW I think I have all the pieces to support multiple assist satellite devices with different screens.

mighty ledge
#

it's a property in python, jinja renamed it to attribute

#

🎉

inner mesa
#

yeah, I opted not to introduce yet more confusion 🙂

#

nevermind that map(attribute='attributes.xxx') is a thing

mighty ledge
#

yeah, that's an odd one

#

getattr errywhere

#

even ptyhon isn't consistent

bronze prawn
#

You probably thought I'd stay away longer but here I am again.

variables:
  target_display_device: "{{states('input_text.assist_target_display_device')}}"
  target_satellite_device: "{{states('input_text.assist_target_satellite_device')}}"
  target_mediaplayer_device: "{{states('input_text.assist_target_mediaplayer_device')}}"

So I'm declaring these variables. Works great.

#
service: chime_tts.say
target:
  entity_id: media_player.thinksmart_lr
data:
  chime_path: www/viewassist/broadcast.mp3
  tts_playback_speed: 100
  volume_level: 1
  message: "{{ states.sensor.assistsat_viewlr.attributes.message }}"
  tts_platform: google_translate

I'm wanting to replace the message line to show the state of target_satellite_device variable's .attributes.message. So something like:

message: "{{ states.[target_satellite_device].attributes.message }}"

#

Is it possible for me to replace that portion with the variable I'm declaring in variables block?

#

or even a:

message: "{{ states." + {{ target_satellite_device }} + ".attributes.message }}"

Type thing. Is that even possible? Wow.

inner mesa
#

don't ever nest templates like that

#

it's unnecessary

#

just remove the extra {{ }}

#

and use different quotes inside and out

#

actually, the quotes are kind of mess there

#

message: "{{ state_attr(target_satellite_device, 'message') }}"

mighty ledge
#

fyi that doesn't work with target selectors

#

(talking to dinki)

#

target selectors return a dict

#

if it's an entity selector set to 1 entity, that will work (what rob said)

bronze prawn
#

You guys are great. I've learned a lot in my month or so working on this project. Found out a lot more about CSS, templating, and JS than I ever thought I might know!

inner mesa
#

Pass it on!

bronze prawn
#

Certainly trying. I'm trying to structure things to make it easy for folks to use and also documenting and explaining what I'm doing. Maybe it will make sense to other folks than just me.

bronze prawn
#

another one. How can I get an entity_id if I have the device_id?

marble jackal
#

device_entities(device_id)

#

but that will give all entities of the device

bronze prawn
#

{{ device_entities('43a9ed37b1ef81e194be835371c8292d')|first}}
Got it. This is the one I need. Thanks!

haughty breach
#

You might want to do a more specific selection instead of using first... IIRC, list order isn't guaranteed.

inner mesa
slate fossil
#

message: "{{ state_attr(target_satellite_device, 'message') }}"
Is there any standardization or best practice regarding use of quotation marks? Or is it just a matter of preference? I usually use single-quotes on the outside and double-quotes on the inside.

inner mesa
#

Doesn't matter at all

#

My way is the best way for no reason at all 🙂

bronze prawn
agile patrol
marble jackal
slate fossil
#

I think my practice of single/outside; double/inside quotes comes from the docs of the custom:button-card. It was the first card I used when I started designing my dashboard. value: '[[[ return variables.index + 2; ]]]'. Looking at the doc above, it states this:

Quoting style
Templates are strings, and thus are double-quoted. As a result of that, single quotes should be used inside the template.
Guess I'll have to go through and update... everything...

marble jackal
#

I think Frenck sent me that link once, and I'm following it since

inner mesa
#

I think JSON is the only place where it matters

silent vector
#

Trying to save this

  - if:
      - condition: template
        value_template: "{{ foo != [] }}"
    then:
      - event: Test Event
        event_data: "{{ memory_event_data }}"

Where memory_event_data is a dictionary.

But I keep getting this trying to save
Message malformed: expected dict for dictionary value @ data['action'][0]['then'][0]['event_data']

#

Spacing got messed up when pasting

inner mesa
#

It told you that event_data needs to be a dict

#

Yours is just a key

silent vector
#

But memory_event_data is a dictionary

For example memory_event_data corresponds to
foo: adam
I'm using dict.from_keys in jinja. This has worked for other fields requiring dictionaries

#

For example this works

  - service: light.turn_{{ set_lights }}
    target:
      entity_id: "{{ target_lights }}"
    data: "{{ light_setting }}"
marble jackal
#

What does the service call result look like in the trace?

silent vector
#
params:
  domain: light
  service: turn_off
  service_data:
    transition: 5
    entity_id:
      - light.kitchen_lights
  target:
    entity_id:
      - light.kitchen_lights
running_script: false
inner mesa
#

The one that isn't working...

#

But if it doesn't pass config check

silent vector
#

Yeah I can't even save it

#

I'm thinking it's a bug in the config validation for that action

#

Because it should work

#

As long as the jinja is actually a dictionary

marble jackal
#

The send custom event action probably doesn't accept templates for that field. Only for the value fields of the respective keys

inner mesa
#

yeah, probably true

#

so just give it a key:

#
test_event:
  sequence:
    - variables:
        eventdata:
          foo: bar
          blah: foo
    - event: foo
      event_data:
        data: "{{ eventdata }}"
silent vector
#

Yeah that can work. Would be nice to not need to do that though

inner mesa
#
- id: event_test
  alias: Event Test
  trigger:
    - platform: event
      event_type: foo
  action:
    - service: persistent_notification.create
      data:
        message: "{{ trigger.event.data.data.foo }}, {{ trigger.event.data.data.blah }}"
#

works fine with that

tacit sun
#

When I put this in a condition statement, it doesn't pass... however, when I put the exact same template in dev tools, it shows true...

{{ state_attr('light.mudroom', 'xy_color') == (0.701, 0.299) }}
#

any ideas?

inner mesa
#

share the actual condition

#

and what does that attribute look like in dev states?

tacit sun
#

I saved the automation, and it now works. That template is the actual condition

inner mesa
#

I meant the actual YAML, but if it works...

tacit sun
#

seems like, value template condition won't work unless first saved?

#
condition: template
value_template: "{{ state_attr('light.mudroom', 'xy_color') == (0.701, 0.299) }}"
inner mesa
#

I don't know what you mean by this:

seems like, value template condition won't work unless first saved?

#

you mean the preview that shows up in the visual editor?

tacit sun
#

meaning, I added it as a new condition in an automation, and when testing it from the visual editor... the condition doesn't pass even though it should

inner mesa
#

as in:

you mean the preview that shows up in the visual editor?

tacit sun
#

then, I saved the automation with the new condition and ran the test again, and now it passed

inner mesa
#

alright, so you're good now

tacit sun
#

yes... just pointing out potential bug in the visual editor condition testing function for the value template conditions.

inner mesa
#

Feel free to report that

plain magnetBOT
#

Want to see what issues are open (or were open and are now closed)?

Don't forget to check for any alerts

If you think an upgrade broke something then:

  1. Downgrade to the previous version to check if it works correctly there
  2. If it does then change the logger settings for that integration to debug
  3. Upgrade to the new version again
  4. Look in the logs for errors
  5. Open an issue, following the template provided and including the log information
open vapor
#

The system has 6 media players named media_player.soundxxxxxx.
Is there an elegant way to write a template to check that the volume on them does not exceed the specified value?

wide monolith
#

I have been trying to create "dummy" templates so that I can use the values in other areas but plain templates dont seem to work... I must be missing something...

template:
  sensor:
    - unique_id: my_var
      state: somevalueid

sensor.my_var or sensor.template_my_var does not exist, and sometimes it does but its unavailable instead of "somevalueid"

inner mesa
#

That's a weird use of template sensors

#

You're not following the proper syntax

#

Consider any of the input_xxx helpers instead

silent vector
#

In jinja you can variabalize + - but can >= <= be variabalized so you can do

(x - y) ~ (v ~ 2)?
Where v is >=

Essentially variabalize a comparison operator

marble jackal
#

You can do something like this

{% set a = 5 %}
{% set b = 3 %}
{% set test = '>=' %}
{{ [a] | select(test, b) | list | count > 0 }}
#

So, with your input

{{ [x-y] | select(v, 2) | list | count > 0 }}
silent vector
#

Interesting very nice.

sonic sand
#
TemplateError('ValueError: Template error: int got invalid input 'unavailable' when rendering template '{{ (states('sensor.qbittorrent_down_speed') | int / 1000) | round(1) }}' but no default was specified') while processing template 'Template<template=({{ (states('sensor.qbittorrent_down_speed') | int / 1000) | round(1) }}) renders=6>' for attribute '_attr_native_value' in entity 'sensor.bytes_sent'
TemplateError('ValueError: Template error: int got invalid input 'unavailable' when rendering template '{{ (states('sensor.qbittorrent_up_speed') | int / 1000) | round(1) }}' but no default was specified') while processing template 'Template<template=({{ (states('sensor.qbittorrent_up_speed') | int / 1000) | round(1) }}) renders=6>' for attribute '_attr_native_value' in entity 'sensor.bytes_upload'

Hi, how can I ignore OR show 0 when state equals to unavailable also to prevent this error from showing up in my logs?
Sensor: http://pastie.org/p/62BiaFfoLfieAa7qkSCTVo

fickle sand
#

| int(0) after each states function

sonic sand
inner mesa
#

because unavailable is a string that cannot be converted to an integer, so the default of 0 will be returned

sonic sand
#
value_template: "{{ (states('sensor.qbittorrent_down_speed') |int(0) | int / 1000) | round(1) }}"
#

like that?

inner mesa
#

ideally you would add an availability test to your sensors

#

well, now you're using the int filter twice...

sonic sand
#

yeah because if i'll not do /1000 it will show it in kbps

inner mesa
#

remove the second one

#

|int(0) | int

#

that's unnecessary

#

|int(0)

sonic sand
#

but i still need the /1000 one

inner mesa
#

fine, but that wasn't the problem

sonic sand
#

i will ask it differently, is there a way to keep it /1000 but ignore if state equals to unavailable?

inner mesa
#

in any case, you can add an availability_template to prevent the value_template from being evaluated if the states are unavailable

#

yes, with an availability_template

sonic sand
#
availability_template: "{{ state_attr('sensor.qbittorrent_down_speed') is not unavailable}}"

is that ok?

inner mesa
#

first, unavailable is a string and needs to be quoted

#

second, use != instead of is not

marsh cairn
#

!=

inner mesa
#

third, you're using state_attr without specifying an attribute

sonic sand
#
unit_of_measurement: KiB/s
device_class: data_rate
icon: mdi:cloud-download
friendly_name: qBittorrent Download speed

those my attributes, so it should be state not att

inner mesa
#

I suspect you wanted availability_template: "{{ states('sensor.qbittorrent_down_speed') != 'unavailable'}}"

#

or availability_template: "{{ states('sensor.qbittorrent_down_speed')|is_number }}"

sonic sand
#

Thanks!

unique herald
#

I have a input_number with a time in minutes, I'm trying to start a time with the service timer.start but the duration needs it in HH:MM
I've tried something like this and it just isn't doing what I am expecting:

{{ states('input_number.mag_counter') | int*60 | timestamp_custom('%H:%M', False) }}
#

Discord formatting

#

The resultant is 00:0000:0000:0000:0000:00...........

inner mesa
#

timestamp_custom is expecting a timestamp, and you just gave it a number of minutes

unique herald
#

What would I use instead?

inner mesa
#

just use seconds:

Duration in seconds

#

in other words, just get rid of the whole timestamp_custom() part

unique herald
#

The error says that it should be in the format HH:MM for dictionary value ['duration']

#

Ugh

#

Figured it out

#

So I tried this but it still doesn't work

tap_action:
  action: call-service
  service: timer.start
  target:
    entity_id: timer.mag_timer
  data:
    duration: '{{ states("input_number.mag_counter") | int*60 }}'
#

Says it has to be in the format HH:MM

marble jackal
#

You can't use templates in a tap action

unique herald
#

🤦‍♂️

marble jackal
#

So the service call gets the full template text, which isn't what it expects

#

Call a script

unique herald
#

Thank you

simple tulip
#

Hi, I'm new to this topic and I don't understand why my automation isn't working. Could someone possibly help me find the error?
I think I might have done something wrong with the sensor.

https://dpaste.org/QwHk9

#

The sensor is displaying the correct value. The automation just isn't being triggered.

inner mesa
#

Remove the quotes around 50

simple tulip
#

I had tried that already. Then the 50 turns red, but it still doesn't work.

inner mesa
#

What value does the sensor have now?

simple tulip
#

100%

simple tulip
#

Understood. I also have the automation set for "off". If I now set the value to "below 100", it should work, right?

inner mesa
#

I'm not following

simple tulip
inner mesa
#

You have 1 trigger. The sensor needs to transition from below 50 to above 50

#

Does it transition from above 100 to below 100?

#

Maybe read that whole section again

simple tulip
#

It works. Thanks for the help.

safe meadow
#

my fan lights do a nice fade in/out when going between brightness percentages, but on light_on/off it is a harsh direct to off or direct to whatever the previous % brightness was. I was thinking about a template so that if it is going on to change brightness to 1% and then to whatever it should go to and when going off, set to 1%, then to off. problem is tracking what the original brightness was (so turning it on doesn't go to 100% when it previously was on at 50%) and also do I need to make the on/off a script and call the script in the template or can I do that directly inside the template definition?

atomic kite
#

I want to use the EnergyZero integration to get a nice graph of all energy tariffs for today and tomorrow, similar to how my energy provider does it. Does anyone know how I could make a graph like that?
https://tibber.com/nl/energieprijzen For reference.

marble jackal
analog mulch
#

Hi. What's the efficient method of doing the following:

I would like get a list of my climate entities which do not have their temperature attribute set to the value that I have stored in a dictionary. I get the list of the entities via:
{{states.climate|selectattr('entity_id','search','trv')|selectattr('state','eq','heat')|expand}}
which gives a list of entities with ids of the form climate.trv_<area>
and then I have a dictionary which looks like:
{% set eco_temps = {'gabinet':20, 'kids': 20, 'salon':20, 'bedroom':20.5, 'bath':21,'shower':21}%}
where the keys in the dictionaries map onto the <area> substring in the entity_id

mighty ledge
#

what

#

you want to take the temperature and map it to the area?

#
{% set ns = namespace(items=[]) %}
{% for climate in states.climate|selectattr('entity_id','search','trv')|selectattr('state','eq','heat') %}
  {% set ns.items = ns.items + [ (area_name(climate.entity_id), climate.attributes.temperature) ] %}
{% endfor %}
{{ dict.from_keys(ns.items) }}
#

but I have no clue what you're actually asking

marble jackal
#

he wants to know which climate entities are not on the temp from the eco_temps dict

mighty ledge
#

I somehow missed that line

analog mulch
#

OK, so something this?

{% set eco_temps = {'gabinet':20, 'kids': 20, 'salon':20, 'bedroom':20.5, 'bath':21,'shower':21}%}
{% set ns=namespace(count=0)%}
{% set trv_list = states.climate|selectattr('entity_id','search','trv')|selectattr('state','eq','heat')%} 
{%for trv in trv_list%}
  {% if trv.attributes.temperature == eco_temps.get(area_id(trv.entity_id),20) %}
  {% set ns.count = ns.count + 1 %}
  {% endif %}
{%endfor%}
{{ns.count}}
mighty ledge
#

no

#

it can be done in 1 line

marble jackal
#

oh, how many

mighty ledge
#

Hmm, maybe not 1 line

marble jackal
#

are the climate entities also assigned to an area?

analog mulch
#

yeah I forgot to tell you that - the area_id's are the keys of the dict

#

I half came up with the above, but I don't know if that's the effiient thing to do

mighty ledge
#
{% set ns = namespace(items=[]) %}
{% set eco_temps = {'gabinet':20, 'kids': 20, 'salon':20, 'bedroom':20.5, 'bath':21,'shower':21}%}
{% for climate in states.climate|selectattr('entity_id','search','trv')|selectattr('state','eq','heat') %}
  {% set target = area_id(climate.entity_id) %}
  {% set temp = eco_temps.items() | selectattr('0', 'eq', target) | map(attribute='1') | first | default(None) %}
  {% if temp is not none %}
    {% set ns.items = ns.items + [ climate.entity_id ] %}
  {% endif %}
{% endfor %}
{{ ns.items }}
#

that'll just give you a list of entity_id's that aren't matching their area, if it has a matching area

#

now you may need to change {% set target = area_name(climate.entity_id) | slugify %} instead of what's there

#

it depends on when/how you created the area.

#

if you want a list of area names, it'll be different

analog mulch
#

Ok I think I can manage from here -- I was wondering if there is some map-filter magic one can do but iterating through the list is the simple thing. Thanks a lot!

mighty ledge
#

no, that doesn't exist

#

would be nice tho

next remnant
#

i have 2 identical template sensors. ever since upgrading from 2024.2.5 to 2024.3.3, they do not seem to update after the initial update they get from the raw sensors. in addition, 1 of the template sensors does not save its state, so on reboot it reverts back to unavailable instead of the last value, whereas the 2nd template sensor does save its state.

here is my configuration: https://dpaste.org/53dBz

im wondering why this worked before, and now doesnt work on 2024.3.3, and what i have to do to fix it

#

also i noticed in states that the last updated and last changed of the "stable" is not changing every minute as configured in the template. i cant recall if it was like this before, but it seems like the time pattern of every minute "/1" is not being followed

mighty ledge
#

if they don't look in your logs for errors

next remnant
#

the rest sensors work, they just take a few minutes to start working (and are api throttled). so on restart, they are set to unknown for up to 10 minutes

#

the template sensors are the ones that are the problem

mighty ledge
#

so what's the problem with that? You're pulling the states every 1 minute, so I'd wager that those will be unknown too

#

until the source gets values

next remnant
#

i was under the understanding that template sensors persist on reboot, and only update if the source was a valid value (not unknown or unavailable)?

analog mulch
#

Is there some way of getting a list of entity_id's from a list state objects which are generated by selectattr without iterating in a for loop?

next remnant
#

i guess the 2nd part of that is solved by calling "states()" but thats part of my template sensor

#

the goal of stable sensor was to eliminate the noise i get from the raw with random api failures, gaps because of restarts, etc.

#

but again, this worked in 2024.2.5, but now is not working in 2024.3.3, so i feel something changed that either broke something, or changed how these work but i cant find the change in any docs so im not entirely sure

mighty ledge
#

that's how you have it set

#

if it takes 10 minutes to get a state, but you ask for a state during those 10 minutes, you're going to get whatever is in the rest sensor

next remnant
#

but using "states(sensor)" prevents that if the sensor is unknown or unavailable, yes?

mighty ledge
#

no

#

that will get you unkonwn or unavailable

next remnant
#

oh, thats not how it worked before (because these have worked flawlessly for the last month). i can try the template sensor to check "is_state" first, but im curious. why does 1 template sensor still have the last value, but the other template sensor doesnt?
this is right after a restart

#

hmm, i cant seem to add an image to the chat like you did

mighty ledge
#

use imgur

#

it will restore a state if it can

next remnant
mighty ledge
#

are you in between a poll period?

#

it checks every minute on the minute IIRC with that trigger

next remnant
#

that was right after i restart HA

#

in fact, the basement stable doesnt update to a value until the raw updates, and then it wont update if the raw gets changed.

#

so there are 2 issues as i originally mentioned, but im not sure if they are related

mighty ledge
#

are there errors in your logs?

next remnant
#

yes i see

Error doing job: Exception in callback _TrackPointUTCTime._run_action()
<additonal error messages>
ValueError: could not convert string to float: 'unknown'
<stack trace>
ValueError: Sensor sensor.basement_remote_sensor_stable has device class 'temperature', state class 'measurement' unit '°F' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'unknown' (<class 'str'>)

so i see it as a byproduct of the sensor not pulilng the right value, because i think it is trying to convert the "unknown" to int

#

my rest sensor also has an error, but thats expected because it requires some rotating tokens and is rate throttled, so that is why it is a bit intermitent (and why i wanted a stable sensor) as i get errors daily

inner mesa
#

So you should either provide a default for your int conversion with int(0) (or whatever you want) or use the availability field to prevent rendering if the source value isn't a number

next remnant
#

i can add "is_state" to check first, but im still confused why the 2 sensors act differently. why would 1 need it, but not the other?

inner mesa
#

The source sensor is different

next remnant
#

they both from source from an identically designed sensor. their name is different, but they act the same

inner mesa
#

Apparently not. This one reports unknown

#

Does the other one?

next remnant
#

no. theres a difference in the value, but i dont understand why

mighty ledge
#

most likely the onboarding process for the 1 that has 65 is failing at the one with unkonwn meaning it never loads the 65 one

#

which is why your 65 one isn't updating

#

so your yaml is this:

#

which makes sense

#

that's the issue with yaml

next remnant
#

if i set the state through dev tools, shouldnt it store the state for the next reboot?

mighty ledge
#

no

#

set_state does not do what you think it does

#

this is why we always tell people to never set state

inner mesa
#

Just set availability for each

mighty ledge
#

it won't give what he want's then

#

needs to use this.state

#

and always return a value

#

that's numerical

#

for it to not error in the beginning

next remnant
#

i thought this.state was not supposed to be used anymore?

mighty ledge
#

??

#

where'd you get that idea?

next remnant
#

IIRC thats what i saw, and saw instead to use "states()". but this was from a month ago so maybe i am remembering wrong

mighty ledge
#

I think you are

#

this.state has caveats, but you can still use it for whatever

next remnant
#

sorry im very confused. i looked up is_state and saw there is no way to set is_not_state, so i just used a | and i am getting different results. and then i also noticed it is listening for entity unknown (is this correct?).
https://imgur.com/a/PXJm9Lp

mighty ledge
#

not is_state(...)

#

not is a keyword in jinja

next remnant
#

for some reason line 9 evaluates to unknown but should be an int, or line 10 should not evaluate to 4. this combination should not work

mighty ledge
#
{% set raw = 'sensor.basement_remote_sensor_raw' %}
{% if raw | has_value %}
  {{ states(raw) }}
{% elif this.state is defined and this.state | is_number %}
  {{ this.state }}
{% else %}
  0
{% endif %}
next remnant
#

if sensor.basement_remote_sensor_raw is unknown then this is undefined

mighty ledge
#

this.state is looking at itself, not the raw

next remnant
#

let me try this in the template, because the dev tool is throwing an error

mighty ledge
#

because this.state doesn't exist in the template editor

#

you can test there by adding

{% set this = {'state': 40} %}
#

before that whole thing above

olive sparrow
#

good afternoon - is it possible to do a count of objects in a response? For example, if an API returns an array (say of devices connected to wifi) is there a way to count the number of objects, instead of listing each one?

inner mesa
#

|length

olive sparrow
#

the specific use case is a RESTful connection to a wifi router that sends back a list of all devices connected, I would just like to know how many

inner mesa
#

|count

olive sparrow
#

cool - thanks! I dont mess with templates much, I do most in NR and MQTT but I am trying to make a package I can share with other router owners for their use as well

olive sparrow
#

the next question is - without MQTT discovery, is there a way to create a device and then the entited off of that?

inner mesa
#

probably through websockets 🤷

olive sparrow
#

Sorry I am trying to dive you a screenshot

#

i use MQTT discovery currently to create the device, and then sensors off of that device

#

I am hoping there is away to do that without MQTT discovery (i am trying to convert from the dark side (Node Red) )

inner mesa
#

I'll again suggest maybe websockets

#

or write a companion integration

olive sparrow
inner mesa
#

generally, you'd create a companion integration that communicates with external software or a device and creates devices & entities for HA

#

there's already one for NR, but I have no idea what it does

olive sparrow
#

not sure I am up to making an integration, but above my pay grade!

#

but might be worth the attempt - juyst what I needed another project 🙂

next remnant
# mighty ledge ``` {% set raw = 'sensor.basement_remote_sensor_raw' %} {% if raw | has_value %}...

this appears to be working, but i have been trying to add and test while on a call for work. so i will continue testing but i think this fixed it, thanks.
i didnt realize this defaulted to 0 though as the last exception, so now i have to figure out how to remove this value from history because it makes my graphs look wonky. if you happen to know how id appreciate it, but otherwise i realize its my mistake and a different topic all together

polar venture
#

how can I set the value of a jinja2 variable to be unknown?

vital crown
#

Is possible to access the last_changed of an attribute?

#

Like this:
{entity.attribute}.last_changed

lofty mason
#

no, that's not recorded

vital crown
#

Ok

lofty mason
#

you'd need to make it a proper sensor first

mighty ledge
marble jackal
#

@mighty ledge: question.. In my relative_time_plus macro I forgot to use quotes in one place. I should have used 'error' instead of error (see this simplified version)

vital crown
#

What should enter as time condtion to make a template trigger at the start of every week?

#

template:

  • trigger:
    • platform: time
      at: "00:00:00"
#

Thats for every day, but what do I enter for every week?

mighty ledge
mighty ledge
vital crown
#

monday 00:00

marble jackal
mighty ledge
#

typically, you do that trigger with a condition pointing out monday then

mighty ledge
#

the devs be like

marble jackal
#

There it issues a warning, wonder why it doesn't do that with the template above then 🙂

#

no warning

#

I thought it might have to do with it being used in tests

#

but then:

#

funny that it retruns true

devout dragon
#

how can i get the index of a timestamp in an array? i want to start from that index and to the end in a calculation ...

#

like array | indexof(timestamp)

#

or whatever 🙂

marble jackal
#
{% set list = ['a', 'b', 'c'] %}
{{ list.index('b') }}

This wil return 1

devout dragon
#

ah so it was that easy 🙂

mighty ledge
#

that's some Jinja magic

floral steeple
#

hey, why can't I use a template in the beginging of the message sentence, like this:

  - service: tts.speak
    data:
      cache: true
      media_player_entity_id: media_player.basement_family_room
      message: {{trigger.id}}, your phone is now ringing.
    target:
      entity_id: tts.piper
mighty ledge
#

you can, what's the number 1 rule of in-line templates?

floral steeple
#

🙂 ' or '' ?

mighty ledge
#

🎉

floral steeple
#

lol

#

now, the quesiton is, single or double?

mighty ledge
#

whatever floats your boat

floral steeple
#

thank you

olive sparrow
#

good morning - this is likely something simple, but I am running into an issue when there is a number in the path for value_templates:

  "value_template": "{{ value_json.cellular.sim.1.simCardDetected}}",
#

if I change the '`1' to 'one' in the corresponding MQTT data, it works, but the data coming back from the API call I am making has the numeric 2

#

the source data is:

"cellular": {
    "network": "LTE-A",
    "mobileType": "LTE-A",
    "modulePowerOn": true,
    "sim": {
      "1": {
        "active": true,
olive sparrow
#

@mighty ledge Thank you!

olive sparrow
#

I have another template question, if anyone is around.

#

I am trying to create a MQTT binary_sensor.

#

Here is the definition:

unique_id: Pepwave Router 111Cell SIM 1 Active
state_topic: integration/pepwave/status/wan/cellular
value_template: '{{ value_json.cellular.sim['1'].active}}'
payload_on: 'True'
payload_off: 'False'
device:
  manufacturer: Pepwave
  identifiers: 293B-1637-2F63
  sw_version: 1711471720472
  name: Pepwave Router
  model: Pepwave MAX BR1 Pro 5G
platform: mqtt```
#

the value of sim['1'].active is "true", but regardless of whether I set payload_on: True or payload_on: true it still shows unknown

#

i have that value already in a sensor, so I can confirm it is reading the right values

marble jackal
#

Did you also try without quotes?

olive sparrow
#

when I open up the entity in the displaty, it says "Unknown" but there is a log entry that it turns on \

#

let me try a few things - maybe the API pull is coming down with a different format

mighty ledge
#

you have '{{ ' ' }}', it needs to be "{{ ' ' }}" or opposite '{{ " " }}'

knotty idol
#

question? I have my template set like this:
{% set next_event=as_timestamp(state_attr('calendar.school_days','start_time')) | timestamp_custom("%Y-%m-%d",true) %}
{% set tomorrow=(now().date() + timedelta(days=1)) | string %}
{{ next_event == tomorrow }}
I get the state as off when my calendar clearly shows school for tomorrow (The state should show 'on'). i cant figure out what is wrong on my template.

lucid thicket
knotty idol
lucid thicket
#

Put it all in the template editor in developer tools, and add the lines

{{ next_event }}
{{ tomorrow }}
#

Then paste the result of the template here. Format it with backticks ```

knotty idol
#

I pasted and got false for result

{% set tomorrow = (as_timestamp(now()) + 86400) | timestamp_custom('%Y-%m-%d', True) %}
{{ next_school_day[:10] == tomorrow }}```
marble jackal
#

What is the result of this:

{% set next_event=as_datetime(state_attr('calendar.school_days','start_time'))%}
{{ next_event }}
{{ now() }}

knotty idol
#
2024-03-26 16:08:00.519287-05:00```
marble jackal
#

Okay, so your next event has the same date as today

#

It's probably the current event though

lucid thicket
#

And then tomorrow would be 2024-03-27 so your comparison will be false

knotty idol
#

Oh i want it for the next day so i can set automations for the next day

marble jackal
#

If you have an all day event today, it will show that event the whole day today

knotty idol
#

oh ok i set school day as a all day on my calendar

marble jackal
#

If you want to check if there is an event tomorrow, you need to to create a trigger based binary sensor and use the service call in the action part

knotty idol
marble jackal
#

No, you were using the actual state of the entity, which will show the all day event of today.
You need to use the service call to be sure you check for tomorrow

#

Are the only events on that calendar the all day school days?

marble jackal
#
template: 
  - trigger: 
      - platform: time_pattern
        hours: "/1"
    action: 
      - service: calendar.get_events
        target:
          entity_id: calendar.school_days
        data: 
          start_date_time: "{{ today_at() + timedelta(days=1) }}"
          duration: 
            hours: 24
        response_variable: result
    binary_sensor: 
      - unique_id: 827a6f7d-b3fa-4eb4-92cf-c1542fac4d97
        name: School tomorrow
        state: "{{ result['calendar.school_days'].events | count > 0 }}"
#

Something like this, note that it will be unknown until it triggers

lethal bison
#

By all accounts, this automation should work:

  - service: script.single_press_{{ (trigger.event.data.devicename|slugify) }}

however it results in a calls an unknown service: script.single_press_thomas.
The called script exists and has the correct name, what gives?

inner mesa
#

you don't need the parentheses, but it should be fine

neat mortar
#

Hi, it's possible to expose script to HomeKit ? or to start script when i stop roomba by using siri ?

neat mortar
vital crown
#

Im trying to make a sensor that stores the minimum temperature of the week, using a template trigger. But it never seenm to trigger, why?

#

`
template:

  • trigger:
    • platform: template
      value_template: "{{ states('sensor.temp') < states('sensor.temp_min_week') }}"
    • platform: template
      value_template: "{{ now().weekday() == 0 and now().hour == 0 and now().minute == 0 }}"
      sensor:
    • name: Temp Min Week
      unique_id: emp_min_w
      unit_of_measurement: "°C"
      device_class: temperature
      icon: mdi:thermometer-chevron-down
      state: "{{ states('sensor.temp')}}"
      attributes:
      datetime: "{{ now() }}"
      `
marble jackal
#

You are doing a string comparison. And you should account for the initial state of your template sensor being unknown

vital crown
#

Yes, I have set an intial value form template sensor so its not unknown

#

Both templates renders correctly in templates developer tools

#

If change the date template to the current time it render true , so it should be correct
{{ now().weekday() == 2 and now().hour == 9 and now().minute == 18 }}

marble jackal
#

Yes, but it will only trigger if it changes from false to true

#

The problem is in your other template

#
template:
  - trigger:
      - platform: template
        value_template: "{{ states('sensor.temp') | is_number and this.state | is_number and  states('sensor.temp') | float < this.state | float }}"
vital crown
#

Ok, thanks I gonna try that

marble jackal
#

Oh wait, that won't start at Monday

vital crown
#

Hmm, I gonna look into that

vital crown
vital crown
# marble jackal ``` template: - trigger: - platform: template value_template: "{...

Nope, it does still not trigger.
I removed the weekday trigger, for testing. And sensor.temp has a initial state set.
Here is the full code, that I tested

template: 
 - trigger:
      - platform: template
        value_template: >-
          {{ states('sensor.temp') | is_number and this.state | is_number and states('sensor.temp') | float < this.state | float }}
    sensor:
      - name: Temp Min
        unique_id: ute_temp_min_v
        unit_of_measurement: "°C"
        device_class: temperature
        icon: mdi:thermometer-chevron-down
        state: "{{ states('sensor.temp')}}"
        attributes:
          datetime: "{{ now() }}"```
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.

marble jackal
#

Please properly format your YAML

#

It still won't trigger until it changes from false to true

vital crown
#

So how can I do that?

#

apologies for my lack of knowledge btw

marble jackal
#

Change your temp sensor value in devtools > states to something above the current value of your template sensor, and then change it back to the current value

#

And you shouldn't have removed the 2nd trigger, now it won't reset on Monday anymore

vital crown
#

I removed it just for testing

marble jackal
#

No, change the state of sensor.temp to something above the current state of sensor.temp_min and then change it back to what sensor.temp was before

vital crown
#

Ok I will test that. It is set to 100 now and I will set it 101

#

Nope, it it still won't trigger 😦

#

Doesn't seem to update no matter how I change the states

haughty breach
lucid thicket
#

this object can’t be used in the trigger definition

lucid thicket
haughty breach
#

It definitely is

lucid thicket
#

What does it populate with when multiple sensors are defined under a single trigger?

mighty ledge
#

it doesn't this can't be used outside the sensor itself, mekaneck is correct

#

in drews case, your or is always defaulting to the second case on the or statement

lucid thicket
#

Thanks. Really second guessing myself after looking at the docs and those are wrong too

mighty ledge
#

well, it needs to be verified then

#

I could see how it might exist, if each sensor has it's own this associated with it

#

I haven't dove into the code, but it's possible each sensor is loaded separately but all have the same listener, so each have their own this

#

which means the actions are parallel

#

and this would make sense, but I could see that not being the case

haughty breach
#

@lucid thicket Sorry for the insistence... apparently I completely misremembered how I set my original sensor up. I do indeed have this in the state template, not the action block.

mighty ledge
#

Happens to the best of us

#

I do this pretty much every week

#

Just ask Tim

lucid thicket
thorny snow
#

Hi, I'm just beginning trying to understand templates, so this is probably a very basic question. I have
{% for state in states.sensor | selectattr('attributes.device_class','==','temperature') %}
which works fine, but I have sensors that don't have a device class, can I still use this method for making a list?

inner mesa
#

If you add |selectattr('attributes.device_class', 'defined') before the existing selectattr()

thorny snow
#

that includes devices that don't have a class?

inner mesa
#

The opposite, as your existing template will cause an error

#

What is your goal?

thorny snow
#

I'm looking at a tutorial that uses this as an example:

`{% set output = namespace(sensors=[]) %}
{% for state in states.sensor | selectattr('attributes.device_class','==','temperature') %}

{% if 0 <= state.state | int(-1) %}
{% set output.sensors = output.sensors + [state.name ~ ',' ~ state.state ] %}

{% endif %}
{% endfor %}
{{ output.sensors | join ('\n') }}`

This outputs every device with an attribute of temperature. I have multiple devices with a camera attribute and want to output that list. If I change 'temperature' to 'camera' nothing shows.

haughty breach
#

I think you're confusing devices and entities... the template returns sensor entities who's device class is temperature.
Camera isn't an allowed device class for sensors (the terminology is a bit confusing).

thorny snow
#

okay, I get it, I think. I have sensor.double_take_bob, which has an attribute for camera. But in order for this to work, this entity would need a device class of camera, which does not exit, correct?

#

This template is only looking for things that have a device_class of temperature, duh. So then, how would I look for all entities that have an attribute of camera? If that makes sense.

haughty breach
#

What do you mean "which has an attribute for camera"? Is it like camera: true?

thorny snow
#

it's camera: officetable1

haughty breach
#

Ok, then you can just check for that attribute being defined similar to Rob's answer above
{% for state in states.sensor | selectattr('attributes.camera','defined') %}

thorny snow
#

okay, that works, thank you! One step closer.

#

By chance do you have any recommendations where one could start learning about templating in HA? I feel like these are basic concepts that I'm missing.

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

inner mesa
#

start with the second link

thorny snow
#

I've been using the second as a reference, if I had read through it all instead, would I have understood the answer to my own question?

inner mesa
#

maybe?

thorny snow
#

lol, fair point, silly/difficult question

inner mesa
#

search here and the forums

#

you are never the first or even the 1000th person to ask any question, really

#

home assistant how do I do something is an excellent Google search

thorny snow
#

I've been using that a lot, and chatgpt which is sometimes helpful in understanding when it's right. I just feel like I"m jumping around and not necessarily in order.

haughty breach
#

When I started out skalavala's Jinja helpers was helpful, just be aware that it hasn't been updated in a while so there are now better ways to do some things in his examples.

thorny snow
#

thanks, I'll check that out. Without an actual templating for ha class to take, various tutorials, explanations and trying things out will have to do

inner mesa
#

And as I mentioned, search the forums and discord

#

but playing in devtools -> Templates gives you realtime feedback and is a great place to try things and learn

thorny snow
#

yeah, it's a god send. I wish I could make it much larger to see more at once. I've spent hours each day trying almost random things to see what works

inner mesa
#

it would be nice if were reformatted into a vertical layout

thorny snow
#

or some bars to change the size, I have a 49" ultrawide that could use that realestate better imo

inner mesa
#

all the dev tools really need to be rethought, as there's often value in using results from each tab in other tabs, especially now that service calls can return results in a variable, but you can't then easily use that in the template dev tool

plain magnetBOT
#

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

inner mesa
#

you're not following the format from the docs

#

you at least need to add a - before sensor:

bright lark
#

Yep, that was it @inner mesa
Thanks
I think I'd been looking at it so much, I couldn't see the wood for the trees 🤦🏻‍♂️

urban rune
#

I want to create a template sensor that self-references (because it accumulates). So in the template code I need to obtain the state of the sensor I am writing the code for. How can I know with 100% certainty what the entity_id will be for this sensor, so that I can correctly self-reference it in its own code?

scenic verge
#

How can i set a numeric value to the current numeric value minus 30, so to say.

#
metadata: {}
data:
  value: 20
target:
  entity_id: input_number.living_room_virtual_brightness```
#

i basically want the value to go higher or lower. not set to 20.

haughty kiln
#

evening! trying to get a "Home for x hours" sensor going on my person card and I'm pretty close, but this only returns home and not_home. how can I get the sensor value based on my zone, e.g. Home, Work, Store, Town, etc.? {{ ( states.person.myuser.state )|capitalize }} for {{ relative_time( states.myuser.jason.last_changed ) }}

lethal bison
haughty kiln
marble jackal
lethal bison
#

@haughty kiln I use a template sensor that resets each day. This won't give you exactly what you're looking for, but it gives an aggregate of hours home per day

scenic verge
lethal bison
#

cunningham's law

scenic verge
lethal bison
#

it works more often than you'd think

scenic verge
#

a wrong answer because code isnt working, still i copied that from the haos forum.

#

ah, had to include a entity in that above yaml. now works 🙂

lethal bison
#

yeah, I forgot the quotes in the initial reply as well

lethal bison
#

for the life of me, I can't get this script to call another script with a templated name

#

it even passes the value_template: '{{ states(entity) != ''unknown'' }}' conditional

#
Result:
result: true
entities:
  - script.single_press_officeceiling```
`Error executing script. Service not found for call_service at pos 4: Service script.single_press_officeceiling not found.`
plain magnetBOT
#

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

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

marble jackal
#

Share your entire script

halcyon ridge
#

Hello, I can't extract parameter from json. what is correct syntax ?
{{ states.sensor.sms_network.state}} show me {"NetworkName": "Unknown", "State": "NetworkStatusUnknown", "PacketState": "NetworkStatusUnknown", "NetworkCode": "", "CID": "", "PacketCID": "", "GPRS": "Detached", "PacketLAC": "", "LAC": "18337908"}

I want to extract network name, but I'm unable to, {{ states.sensor.sms_network["NetworkName"] }}

marble jackal
#

{{ (states('sensor.sms_network') | from_json)["NetworkName"] }}

#

all states are strings, so you need to convert the json string to a dictionary first

#

might be better to put it in an attribute if you created the sensor yourself

#

I also expect the 255 character limit for states to become an issue here

halcyon ridge
#

thank you

#

and how to display this value on fronted in entity card ?

marble jackal
#

use a card which support templates, like a Markdown card, or create a template sensor using that template and use that

lost locust
#

how do I check an array length? is this right?

{{ trigger.payload_json.after.entered_zones | length > 0 }}
#

also, is there a best practice for that dot-walking method vs using

trigger.payload_json['after']['entered_zones']
inner mesa
#

Dots are a shortcut that you can use if the field doesn't start with a number, isn't a variable, and doesn't have spaces in it

#

Doesn't have 'special' characters

lost locust
#

is that the right way for checking that an array isn't empty?

#

piping to length and then > 0?

inner mesa
#

It's fine

somber bone
#

Hii, I have a newbie question, can any one explain and help me solve this - why do I get [object object]

  - type: custom:more-info-card
    entity: climate.aciravoda_4
    title: {{ states("binary_sensor.salon_sensor") }}
inner mesa
#

You need to quote your template

somber bone
#

like this?
title: "{{ states('binary_sensor.salon_sensor') }}"

inner mesa
#

Yes. Does it work?

#

Easy to check

#

I'm assuming that you've already established that that card even supports templates there

somber bone
#

nope and nope

inner mesa
#

Then do that first

#

Most cards do not support templates

somber bone
#

what can I do if it doesn't?

inner mesa
#

Find one that does

lethal bison
marble jackal
analog mulch
#

Is it correct that when I do this:

          mid: "{{as_local(state_attr('sensor.wu_other_sun_solar_midnight','today'))}}"
          h7: "{{mid+timedelta(hours=7)}}" # 7 h after last solar midnight

where the sensor in mid is a datetime, defining h7 complains that I am concatenating a str and a datetime? Are all variables defined through variables always strings?

#

the sensor.wu_other_sun_solar_midnight is 2024-03-27T22:48:48+00:00

lethal bison
#

@marble jackal I've been playing around with whether it needs to be slugified, I must have left it. Let me make them uniform and give it a go

marble jackal
#

What does that event send

#

Which you use for the trigger

#

Anyway, it will be something for tomorrow for me

lethal bison
#

the event looks like

event_type: esphome.single
data:
  device_id: 90f442478b2298e0c654d9c313bfc52f
  devicename: officeceiling
  name_friendly: Office Ceiling
  action: single_press
  mode: Always On
  brightness: "off"
#

Mode can be ["Always On", "Switched", "Always Off"]
brightness can be ["off", "bright", "medium", "low", "night"]

inner mesa
#

perhaps that will help

analog mulch
#

this particular 'today' attribute is just a datetime string

inner mesa
#

if it treats it as a string, just convert it (again?)

analog mulch
#

yeah, i've ended up droing this:

        h7: "{{as_timestamp(as_datetime(mid)+timedelta(hours=7))}}" # 7 h after last solar midnight

but is that the expected behaviour or a bug

inner mesa
#

datetime objects are weird in that they're not serializable, and that restricts where they can be used

analog mulch
#

yet again timestamp wins. 😉

lethal bison
#

@inner mesa Automation works correctly now. I had to delete script.single_press_officeceiling and recreate. Originally I made the generic script without specifying an entity_id, then I edited the script in the UI and added the entity_id.
This time I specified the entity_id when creating the script, and it loads properly

lucid thicket
#

I have a template as a string inside of a variable. I simply want to print the contents of that variable, but it seems to get evaluated first instead of just printing it. Here is a simplified example:

#
script:
  test_script:
    alias: 'Test script'
    sequence:
      - variables:
          my_var: "{% raw %} {{ (value | float(0) * 14.503773) | round(1) }} {% endraw %}"
      - service: notify.test_log
        data:
          message: >-
            {{ my_var }}
#

When the script is executed, I get the error that 'value' is undefined

#

How can I get the contents of the variable without evaluating it as a template?

viscid timber
#

Hi there,I'm a NEWBEE in HA and Templates at all. I'm looking for a simple Template to invert a binary_sensor output. I need help. Thanks.

marble jackal
sonic sand
#

hey there!
was wondering if I can use notify.phone to be able to send a photo that located in /config/www/tmp/snapshot_vacuum.jpg in addition to the template below.

service: notify.home_assistant_group
data:
  title: :broom: Vacuum Robot has finished and returned to base!
  message: >-
    It took {{ ( states('sensor.roborock_s8_pro_ultra_last_clean_duration') |
    int / 60 ) | round(1) }} minutes and covered {{
    states('sensor.roborock_s8_pro_ultra_current_clean_area') }} m².
lucid thicket
marble jackal
#

What is your goal here, why do you want to send a template?

sonic sand
lucid thicket
#

I’m doing the same thing as the post (writing a script that uses mqtt.publish to create a bunch of mqtt sensors via autodiscovery). Using notify was just easier to make a simple example.

Some of those sensors utilize a value_template or a json_attributes_template

lucid thicket
lucid thicket
fickle sand
#

And as easy to implement by the example from mekaneck

silver pewter
#

Anyone much smarter than me that know this simple, i guess template? i want to test two states, one attribute and one state of same entity. this is only attribute and works:

{% if 'tv.emby.embyatv' in state_attr('media_player.shield_tv_adb', 'app_id') %}
  on
{% else %}
  off
{% endif %}

But i want it like this, but this is not working ofc just added " & " :

{% if 'tv.emby.embyatv' in state_attr('media_player.shield_tv_adb', 'app_id') & if 'playing' in state('media_player.shield_tv_adb') %}
  on
{% else %}
  off
{% endif %}

Thanks! 🙂

inner mesa
#

replace & if with and

mighty ledge
#

all you need is

{{ 'tv.emby.embyatv' in state_attr('media_player.shield_tv_adb', 'app_id') and is_state('media_player.shield_tv_adb', 'playing') }}
#

you don't need the if statement saying explicit on/off

inner mesa
#

depends on what they're doing with the result, but generally yes

mighty ledge
#

if they are outputting on/off then something else isn't configured correctly

#

i.e. they are amking a sensor when it should be binary, or payloads aren't set to True/False, etc

silver pewter
#

Thank you both so much!!! 🙂 I want a input_boolean to auto turn on/off by that state 🙂 to block oone automation. but maybe Binary sensor is the correct way then? i have to try!

inner mesa
#

I return on and off sometimes when using a template to construct a service name, but that's probably a more advanced use case 🙂

bronze prawn
#

Trying to write an automation that will rotate through a list of views. The list looks like this:

cycle_view: "clock,weather,traffic"

Can I use a template with an automation like:

repeat:
  for_each:
    {{ my template }}
  sequence:
inner mesa
#

maybe, if you format them properly

#

definitely, if you do this:

cycle_view:
  - clock
  - weather
  - traffic

and

repeat:
  for_each: "{{ cycle_view }}"
  sequence:
bronze prawn
#

The cycle_view is part of a custom device template that I have. I am open to ideas on how to store those values but it is stored as a single line of text as of now

#

Is there a way to store a list as a line of text?

inner mesa
#

why does it need to be a line of text?

#

I don't know what your first sentence means

#

do you mean that it's a custom template that you've imported?

bronze prawn
#

Probably easier to show you ^^^

marble jackal
#

Click on the entity id, it will show you the structure with proper YAML

#

Copy, and paste that

bronze prawn
#

Is that for me? Not sure I'm understanding what you are telling

marble jackal
#

Preferably when the attribute has a value

marble jackal
bronze prawn
#

Oh, I got you. I can set the state fine, I'm just not sure I'm going about it properly for how I pull that data back out to go into a for_each

#

I'll give it a try and see what happens 🙂

marble jackal
#

Yes, and having it properly formatted will help getting the data out in the right way

#

It is possibly a list already, but that attribute column won't show it like that

bronze prawn
#

I created the template sensor myself. I did not set any specifics on data type for any of the attributes if that is even a thing

inner mesa
#

attributes can have native Python types, including lists

#

so if you created the sensor yourself, make the attribute a list

plain magnetBOT
#

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

bronze prawn
#

So:
{{ state_attr ('sensor.assistsat_viewlrthinksmart', 'cycle_view').split(',')}}
gives me:

['clock', 'weather', 'info']
#

So that should be usable with the for_each right?

inner mesa
#

you declare a type simply by making the value of the attribute conform to the syntax of that type

#

I gave you an example above

bronze prawn
#

I'm coming at this from a novice level so please excuse my ignorance.

inner mesa
bronze prawn
#

Yep. I did see that, but I am unsure how I would format it that way. Am I just setting those values like shown? Add a hypen space viewname carriage return then repeat for each?

inner mesa
#

hmm, I guess it doesn't like that for some reason

#

yes, that's how lists are denoted in YAML

bronze prawn
#

Yeah, I just tried and it doesn't retain the carriage returns. I end up with something that looks like this:
cycle_view: "- clock - weather - info"

Do I need to use the \n \r instead?

inner mesa
#

this works fine

#
- sensor:
  - name: test_list
    state: something
    attributes:
      cycle_view: "{{ [ 'foo', 'bar', 'blah' ] }}"
bronze prawn
#

Thanks. Will give that a try.

#

Okay, defintely able to replicate this now. Thanks for showing me this. Further, if I want to create a dictionary, I can use the same type of thing just so long as I format it correctly? I may want to do something like [ 'clock' : '25', 'weather' : '30', 'front' : '25' ]

#

this would allow me to set the amount of time to show the view before cycling to the next view

inner mesa
#

yes, but you would do this:

#

{ 'clock' : '25', 'weather' : '30', 'front' : '25' }

bronze prawn
#

oops. yeah, wrong bracket type. This is awesome

sonic nimbus
#

hello, how to say for my input variable for my script for if-then condition if that variable is not null?
{{!my_variable1}} ?

marble jackal
#

{{ my_variable is not none }}

lost juniper
#

Hi again, still working on my car sensors and I'm stuck. Is this proper format for json_attributes_template? It looks good in template editor but even if I hardcode the values I do not get any attributes.

      json_attributes_template: >-        
        { {% for i in states('sensor.car1_pids_supported_1_32') -%}
        {% if i == '1' and loop.index | string in states.sensor.pids.attributes -%}
        "{{ loop.index }}": "{{ state_attr('sensor.pids', loop.index | string) }}"{% if not loop.last %}, {% endif %} 
        {% endif %}
        {% endfor %} }

wispy finch
#

Can somebody please help me create a condition? I want to check if the value from an entity is above the value from a specific helper (type: number).
The value from the entity looks like this: 281h 14m 49s
It's sufficient when the first number (281) is checked against the helper value

inner mesa
#

I'm happy to point you in teh right direction, but you will need to fill in the details yourself

worldly rampart
#

Is there any way to md5 hash a value in templating?

...I have a rest API login that needs the user/pass hashing along with a session key that's returned by an initial request before the login one.

inner mesa
# wispy finch ?

{{ states('sensor.someentity')|regex_replace('([0-9]+).*', '\\1')|float > states('number.someentity')|float }}

wispy finch
#

Sorry, I'm not sure were I have to fill in this code. I have insert a "numerical state" in the condition area and filled in this code in the YAML editor

```{{ states('sensor.v2_5162_totals_print_time')|regex_replace('([0-9]+).*', '\1')|float > states('input_number.nevermorewechsel')|float }}````

But I get a error:

Message malformed: Entity is neither a valid entity ID nor a valid UUID for dictionary value @ data['condition'][0]['entity_id']

worldly rampart
#

Perfect thanks

haughty breach
lost juniper
#

I can't get it I have tried every which way and been struggling all day. Do attributes update even if the state value doesn't change?

inner mesa
#

they can

#

I don't know what you've been struggling with, but this simple template sensor demonstrates it. I just watched the attribute update:

- sensor:
  - name: time_test
    state: foo
    attributes:
      current_time: "{{ now() }}"
lost juniper
#

Trying to do mqtt sensor with json_attributes_template.

      json_attributes_template: >-
        { {%- for i in states('sensor.car1_pids_supported_1_32') -%}
        {% if i == '1' and loop.index | string in states.sensor.pids.attributes -%}
        "{{ loop.index }}":"{{ state_attr('sensor.pids', loop.index | string) }}"
        {%- if not loop.last %},{% endif -%} 
        {% endif -%}
        {% endfor %}}

Even if I hardcode some values I don't get any attributes. Do you know if I have to specify json_attributes_topic? I haven't tried that.

#

I think I just answered my own problem. Must specify mqtt topic. Wow the whole day I spent on this stupid thing lol

fossil venture
#

Is there a way to check when the mqtt integration was last reloaded? I have an automation that triggers when some important (to me) entities go offline. So I'm triggering on the unavailable / unknown states. Reloading the mqtt integration (e.g. enabling an mqtt entity like lqi, which is disabled by default, causes a reload) triggers a lot of false alerts. If I could add a template condition to check the mqtt integration was not just reloaded this should fix it.

fossil venture
#

Perfect. Thanks.

fossil venture
#

Hmm. Actually using that event to create a triggered template sensor (to store the last reload time) would create a race condition with the automation state trigger.

haughty breach
#

@waxen junco

{% set events = states.calendar.bay_1.attributes %}
{% set next_event_time = events['start_time']|as_datetime %}
{% set current_time = now() %}

{% if next_event_time - current_time <= timedelta(seconds=300) %}
  turn on the plugs
{% endif %}
lucid thicket
#

Is there a way to create a dictionary from two lists (one list with keys, the other list with values) without looping?

#

Like the Python zip() function

inner mesa
#

No, there's no zip

marble jackal
#

Result

{
  "a": 1,
  "b": 2,
  "c": 3,
  "d": 4
}
#

Keys must be strings

lucid thicket
#

Was hoping there was some clever use of jinja’s batch() or something else that I missed

marble jackal
#

Shouldn't be too hard to add a zip function/filter though

mighty ledge
#

I have a PR in the works for about 4 years now for zip

#

it would be an easy add.

#

jinja really just needs single line loops in cases

#

a 1 liner w/ zip would be {{ dict.from_keys(*zip(keys, values)) }}

lucid thicket
#

That would be nice. What’s the protocol with stale PR’s, what does it take to get someone to either merge or reject it?

mighty ledge
#

I did the work and let it sit 🤣

#

it can be less than 100 lines of code, mostly a test case

vital crown
floral steeple
#

have a template sensor to convert to datetime

    - name: food_waste_cart
      unique_id: redacted
      state: >-
        {{ min(((state_attr('calendar.food_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
      attributes:
        days: >- 
          {{ ((state_attr('calendar.food_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
        friendly_name: "Food Waste Cart"
#

as its giving some startup errors with the calendar not being available

marble jackal
#

Add an availability template to check on the attribute

floral steeple
#
    - name: food_waste_cart
      unique_id: redacted
      state: >-
        {{ min(((state_attr('calendar.food_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
      attributes:
        days: >- 
          {{ ((state_attr('calendar.food_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
        friendly_name: "Food Waste Cart"
      availability: >
        {{ state_attr('calendar.food_refuse', 'start_time') not in [None, 'unknown', 'unavailable'] }}
#

like the above

marble jackal
#
    - name: Food Waste Cart
      unique_id: redacted
      state: >-
        {{ min((state_attr('calendar.food_refuse','start_time') | as_datetime | as_local - today_at('00:00')).days | int,2) }}
      attributes:
        days: >- 
          {{ (state_attr('calendar.food_refuse','start_time') | as_datetime | as_local - today_at('00:00')).days }}
      availability: "{{ state_attr('calendar.food_refuse','start_time') is not none }}"
#

This is what I would do

#

You could even refer to the attribute in the state

#
    - name: Food Waste Cart
      unique_id: redacted
      state: >-
        {{ [ this.attributes.days | default(2), 2] | min }}
      attributes:
        days: >- 
          {{ (state_attr('calendar.food_refuse','start_time') | as_datetime | as_local - today_at('00:00')).days }}
      availability: "{{ state_attr('calendar.food_refuse','start_time') is not none }}"
mighty ledge
#

missing bracket

#

aaaaaad it

#

there ya go

marble jackal
#

Done

mighty ledge
#

fyi, you can skip default by using get

#

this.attribute.get('days', 2)

#

#less typing

marble jackal
#

I also removed the friendly name attribute and put it in the name field

#

Yeah, I had that first

#

Thought this might be easier to understand

floral steeple
#

thanks! Jusg wonderig, there are a couple of options you presented, it looks like the the second the one if a but more concise for this case, which is preferred

marble jackal
#

I think I have template entities which use this.get('attributes', {}).get('some_attribute') for extra failsafe

mighty ledge
#

they really should populate this with an empty state object instead of nothing

#

that would be an easy PR

#

all this safety that needs to be done is normal coding. Should be easier for the layman

#

coud probably make something for this

floral steeple
#

thanks again for explaining that and providing the code 🙂

haughty breach
lucid thicket
#

So uh, what’s the protocol for getting someone to finish a PR that hasn’t been touched for 4 years

mighty ledge
#

well, I looked through my branches and apparently never put it anywhere

#

I think it would be 3 lines of code to add it. And 97 lines to test it.

#

literally 3 lines, you should try to add it

lucid thicket
#

This would be a good one for me to try out editing the code. I might be able to figure out the 3 lines. Creating the tests probably not so much.

mighty ledge
#

well, the test could be short

#

but it also could be long

mighty ledge
#

zip already exists in python, so it seems like it would just be a 1 line change to implment it

#

then for testing, I would test zipping and unzipping a dataset

#

probably nothing else. Then see if the PR makes it through

#

probably won't get added til august, but it would be a good first PR

marble jackal
#

Unless you want to add a default parameter I guess, then it'll be some extra lines and extra tests

mighty ledge
#

default for what?

#

it should error out if you don't give it an iterable

#

if you feed it a state (string), with another state (string), it will use the characters

#

I'd expect zip to only be used to zip 2 iterables together, and unzip into 2 lists

marble jackal
#

Yeah, makes sense

mighty ledge
#

zip(*collection) for unzipping

#

zip(a, b) for zipping

#

collection needs to be [('a','b'),('c','d')]

#

and a, b need to be lists

#

of single items

floral steeple
#

have another issue with this. I modified Allan Porter's conversation blueprint here to do TTS on motion.
https://gist.github.com/Anto79-ops/d926fa8655da7cad0a383e1fa35c40de
But when I try to run it, i get an some errors:
Conversation agent Agenda Notification with tts on motion: Error executing script. Error for call_service at pos 3: Error rendering data template: UndefinedError: None has no element 0

#

Im not sure where pos 3 is?

inner mesa
floral steeple
#

ahh, I shared the edit link..updated the link now

floral steeple
#

im starting to think its this line,
{%- set forecast = state_attr(weather_entity, 'forecast')[0] %}
there is no (more) forcast attribute?

inner mesa
#

Correct

floral steeple
#

😬

#

so, what is the workaround for forecast now? perhaps a beta question

inner mesa
#

A forum question

#

It's been 6 months

floral steeple
#

oh wow, what a process to simply get a forecast, creating a new sensor, etc

lucid thicket
#

Ok so I figured out a hacky way to zip two lists into a dict without looping. Just because I couldn’t accept that it couldn’t be done

#

{% set keys = ['a','b','c','d'] %}
{% set values = [1,2,3,4] %}
{% set my_dict = ('{"' ~ (keys | join('\":%s,\"') ~ '\":%s') | format(*values) ~'}' ) | from_json %}
{{ my_dict }}
marble jackal
#

hehe

#

you could have spent that time in writing a PR to add a zip function/filter 😛

lucid thicket
#

Haha. That will probably take me weeks. Manipulating jinja to do my bidding is easier. But I’m still going to take a crack at the pr.

floral steeple
inner mesa
#

Pretty sure there's an example on that big page

#

It's a list

floral steeple
#

oh nevermind, there was an extra space somewhere 🙂

#

thanks @inner mesa

floral steeple
#

sensor seems to stay unknown. Perhaps I set it up wrong.

#
- trigger:
    - platform: time_pattern
      hours: "12"
  action:
    - service: weather.get_forecasts
      data:
        type: daily
      target:
        entity_id: weather.home
      response_variable: daily
  sensor:
    - name: Daily Temperature Forecast
      unique_id: ba182774-d2f2-4ef3-a6ba-ffb22b8e8fc1
      state: "{{ daily['weather.forecast_home'].forecast[0].temperature }}"
      unit_of_measurement: °C
#

example output from the sevice call is:

#
weather.forecast_home:
  forecast:
    - condition: partlycloudy
      datetime: "2024-03-30T18:00:00+00:00"
      wind_bearing: 175.8
      temperature: 6.3
      templow: -1.2
      wind_speed: 15.5
      precipitation: 0
      humidity: 19
inner mesa
#

Probably hasn't triggered

marble jackal
#

It triggers at 12:00

floral steeple
#

ok that makes. I used the update entity feature but I guess that runs everything starting from the trigger

marble jackal
#

Trigger based template sensors only update on the trigger

floral steeple
#

ok, I changed the trigger to this:

- trigger:
    - platform: time_pattern
      minutes: "1"
#

still unknown

#

after 6 minutes

inner mesa
#

It will fire once an hour

#

Perhaps revisit the time_pattern docs

vital crown
marble jackal
#

It triggers when it becomes true, which is at midnight

floral steeple
floral steeple
#

ok, I've made 3 entities now:
sensor.weather_conditions
sensor.probability_of_precipitation
sensor.daily_temperature_forecast

#

the old way would simply use the attribute of the same entity, with this:

        {%- if weather_entity is defined %}
        {%- set forecast = state_attr(weather_entity, 'forecast')[0] %}
        {%- set temperature_unit = state_attr(weather_entity, 'temperature_unit') -%}
        Weather: {{ forecast.condition }} ({{ forecast.temperature }}{{ temperature_unit }}, {{ forecast.precipitation }}% precipitation)
        {%- endif %}
inner mesa
#

you could just recreate the forecast entity, like the docs show

#

or...make the calls inline and don't create new entities

floral steeple
#

you mean like this:

     {%- if weather_entity is defined %}
     {%- set temperature_unit = degree Celsius%}
     Weather: {{ sensor.weather_conditions }} ({{ sensor.daily_temperature_forecast }}{{ temperature_unit }}, {{ sensor.probability_of_precipitation }}% precipitation)
     {%- endif %}
inner mesa
#

I'm not sure what you're solving with that

floral steeple
#

lol

#

me too

inner mesa
#

I'm just saying that you seem to be complaining that you had to create a bunch of entities

floral steeple
#

i created them

#

it was only 3

inner mesa
#

and I'm saying that if you just followed the example in the docs to create a forecast template sensor, then you could just use that exactly as you did before

#

instead, you chose to separate out individual parts of it

#

the old way would simply use the attribute of the same entity, with this:

floral steeple
inner mesa
#

I mean that you could just do what the docs said

floral steeple
#

but, that uses attributes, I thought attributes are on their way out...which is what caused the problem in the first place

inner mesa
#

no

#

attributes aren't going anywhere

#

unconditionally dumping lots of data into attributes without it being explictly requested is what went away

#

so, like I said, you could also just do it inline and not create any additional entities

#

or...you can just recreate the entity

floral steeple
#

ok, then I did all that for no reason lol

#

ok

inner mesa
#

that's why I pointed you to the docs

floral steeple
#

I know you did

inner mesa
#

because it shows you exactly how to do it

floral steeple
#

and I thought I understood you, but I didn't

#

ok

#

my bad

#

thanks again @inner mesa this really worked

distant abyss
floral steeple
#

Buts it's this exactly, except i changed it to daily and used the proper weather entity_id

#

Oh and I changed the time pattern to 12 hrs

plain magnetBOT
#

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

marble jackal
#

@floral steeple I don't really understand why you update this only at noon, that means you have yesterday's forecast in that attribute for half of the new day

floral steeple
#

Lol you're right. I should change it to midnight...should it be 0:00

oak kiln
#

I think I remember there being a helper to get the "translated" variant of a binary_sensor state in jinja templates (e.g. "open" instead of "on" for a door sensor). Unfortunately though, I can't seem to find it via google.

Does it really exist or am I just hallucinating things into existence?

marble jackal
#

Unless you mean the template (binary) sensor helper, I don't think there is something like that

haughty breach
inner mesa
#

@oak kiln that?

oak kiln
#

Yes! Thanks 🙂

floral steeple
#

how do I put an actual fixed value for temperature_unit in this code:

        {%- if weather_entity is defined %}
        {%- set forecast = state_attr(weather_entity, 'forecast')[0] %}
        {%- set temperature_unit = state_attr(weather_entity, 'temperature_unit') -%}
        Weather: {{ forecast.condition }} ({{ forecast.temperature }}{{ temperature_unit }}, {{ forecast.precipitation }}% precipitation)
        {%- endif %}

like this?
{%- set temperature_unit = degrees Celsius -%}

inner mesa
#

You just want a string?

floral steeple
#

yes, just a string

inner mesa
#

Then quote it, like all the strings you already have there

#

Otherwise, yes

floral steeple
#

awesome, thanks!

lament dust
#

Does anyone know if these is a way to simulate a workday sensor with an offset of 1 without actually creating it? It seems like you can do so with a service call, but I cant figure out if there is a way to do it in a template. I basically just want a way to indicate if it thinks tommorrow is a workday or not as I am testing some automation/sensors

inner mesa
#

Just change the state in devtools -> States

lament dust
inner mesa
#

If you want an entity to have a different state temporarily, change it there

lament dust
inner mesa
#

There no way to get a workday sensor to pretend that it's tomorrow

lament dust
wanton sapphire
#

hi all, is there a way to go from ["a:b","c:d"] to {"a":"b","c":"d"} ?

jolly parrot
#

Assembled in the GUI editor

mighty ledge
#

use multiline notation or quotes, not both.

#

if you're using the UI, just omit the quotes.

jolly parrot
#

Grand! collects up "'s

lucid thicket
# wanton sapphire hi all, is there a way to go from `["a:b","c:d"]` to `{"a":"b","c":"d"}` ?

you could do it all with replace functions, assuming none of the keys or values contain special characters that are being replaced:

{% set input = ["a:b","c:d"] %}
{{ input | string | replace('[','{') | replace(']','}') | replace(':','\':\'') | replace('\'','"') }}

or you could do it by looping. in this case you just have to ensure no colons are in the keys or values:

{% set input = ["a:b","c:d"] %}
{% set ns = namespace(pairs={}) %}
{% for pair in input | reverse %}
  {% set ns.pairs = dict([(pair.split(':'))], **ns.pairs) %}
{% endfor %}
{{ ns.pairs | to_json }}
silver pewter
#

Hi all 🙂 Anyone knows how to do this easy? i want a automation that notifies me when only one or both binary sensors state is above 35 or above.
i dont know how to template it 😛 i tried google 😦

I want a message like this:
"sensor1 AND sensor2 needs to be cleaned"
or
sensor2 needs to be cleaned"

but i dont know how to template that in the message. must be a simple trick someone knows :D.

Notify message would be like:

mighty ledge
#

You don't need templates for this

#

just make an automation with 2 triggers, one for each sensor. Then make a condition that checks both sensors. Then your notification will tell you to clean both sensors.

#

oops, missed one or both

silver pewter
#

So u dont know with one or both? 😛

#

maybe some kind of list template?

mighty ledge
#

I do jnow, I just don't have the time to make an example

#

someone else will help

silver pewter
#

Oh i see, thanks anyway 🙂

plain magnetBOT
#

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

fickle sand
silver pewter
#
{% if states.binary_sensor.sensor1.state == '35' and states.binary_sensor.sensor2.state =='35' %}
  green
{% elif states.binary_sensor.sensor1.state == '35' and states.binary_sensor.sensor2.state =='35'
deepskyblue

How do i change == into above > & below < correctly ? like:

{% elif states.binary_sensor.sensor1.state < '35'
fickle sand
marble jackal
#

Don't do a string comparison with numeric states

fickle sand
#

But for templates it is first best practice to use the states() function, convert that to a float or int, than you can compare with >= or <=; < or > depending if the value itself should also be accounted for.

#
{% if states('sensor.sensor1') | float > 35 and states('sensor.sensor2') | float > 35 %}
#

Although the value of a binary_sensor can only be on, off, unavailable or unknown

silver pewter
#

oh it is a sensor, not binary, sry my bad 😛

plain magnetBOT
#

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

heavy minnow
#

the switch.turn_off works fine, and turns off the AC, but the switch.turn_on shows the above error

inner mesa
#

Share the script that actually has the error

lethal locust
#

hi, i want to set speed by number at the nspanel. i think the whole syntax is wrong. maybe someone can help:

            speed: >-
              {{if states('sensor.wechselrichter_battery_power')|float(0) < 0}}
              20
              {{if states('sensor.wechselrichter_battery_power')|float(0) > 0}}
              -20
              {{if states('sensor.wechselrichter_battery_power')|float(0) = 0}}
              0```
what i am missing here?
stark vale
#

I have the total energy my household needed and the energy I am currently getting/sending to the grid
sadly, the energy usage graph doesn't understand that if total energy needed is decreasing it means that I am returning it to the grid

how can i calculate the energy I return to the grid? is there some sort of variable system I can use to save the last total energy and subtract that to from current total energy?

fickle sand
#

So the if statements should be between {%%}

marble jackal
#

And you need and endif

#

And each statement after the first could be an elif

#

Otherwise you need 3 endifs

lethal locust
#
              {%if states('sensor.wechselrichter_battery_power')|float(0) < 0%}
              20
              {%elif states('sensor.wechselrichter_battery_power')|float(0) > 0%}
              -20
              {%elif states('sensor.wechselrichter_battery_power')|float(0) = 0%}
              0
              {%endif%}```?
fickle sand
#

The last statement could also be simplified to only {% else %}

lethal locust
#
speed: >-
  {% if states('sensor.wechselrichter_battery_power')|float(0) < 0%}
  20
  {% elif states('sensor.wechselrichter_battery_power')|float(0) > 0%}
  -20
  {% else %}
  0
  {% endif %}``` 
if it works i will see tomorrow  if the state changes to positive:) thanks a lot.
fickle sand
#

You can always change manually the value of the sensor until the next update in dev-tools > states to test the template

lethal locust
#

yes 🙂 but i am to slow cause it will update every 5 seconds.^^

#

< lazy

fickle sand
#

Hhaha split-screen with the both tabs open 😉