#templates-archived

1 messages Β· Page 17 of 1

inner mesa
#

I can't really tell what you wanted

sacred sparrow
#

Just if those sensors are "unavailable" or "unknown" that I want the sensor to be off

inner mesa
#

all of them?

#

some of them?

sacred sparrow
#

all of them

#

if any are "unavailable" or "unknown" then the sensor state should be off

inner mesa
#

{{ expand(['sensor.collingwood_short_text_0', 'sensor.outside_home_feels_like_temperature', 'sensor.outside_min_temp', 'sensor.collingwood_temp_max_0', 'sensor.collingwood_rain_chance_0', 'sensor.melbourne_pollen_count', 'sensor.collingwood_uv_category_0'])|selectattr('state', 'in', ['unavailable', 'unknown'])|list|length == 0 }}

sacred sparrow
#

still shows as unavailable

inner mesa
#

put it in devtools -> Templates and debug

sacred sparrow
#

UndefinedError: str object has no element ('unavailable', 'unknown')

inner mesa
#

oh, I missed a comma

sacred sparrow
#

Ah yes! That worked. Thank you πŸ™‚

silent flicker
#

Is there a way to wildcard match these results?

{{ states('sensor.openweathermap_weather') in [ 'scattered clouds' ] }}

there are many weather conditions that involve clouds, so instead of listing them all, is it possible to just wildcard "cloud" ?

inner mesa
#

yes, reverse that

#

{{ 'clouds' in states('sensor.openweathermap_weather') }}

silent flicker
#

will that work the same for multiple conditions? like:

{{ states('sensor.openweathermap_weather') in [ 'cloud', 'snow', 'rain' ] }}
inner mesa
#

you flipped it around again

silent flicker
#

yeah, i know. will it work for all 3 of those if i flip it around?

inner mesa
#

no

#

read it like a sentence

silent flicker
#

so i can only do 1 at a time?

#

was hoping to have a one-liner

#

i want to check for cloud,snow,rain. but wanted them to be more of a wildcard because results could equal: cloudy, snowy, rainy, etc

inner mesa
#

{{ 'blah'|regex_search('foo|bar|blah') }}

silent flicker
#

oh regex. hm

#
{{ states('sensor.openweathermap_weather') | regex_search('cloud|snow|rain') }} 

like that? πŸ˜„

inner mesa
#

try it

silent flicker
#

does regex_search ignore caps? sometimes it might be Snow instead of snow

inner mesa
#

{{ 'Bar'|lower|regex_search('foo|bar|blah') }} -> True

silent flicker
#

oo i like that

#

thanks. ive been trying to get this figured out for a week lol

#

basically when weather condition changes, it will announce it to the house

#
{{ states('sensor.openweathermap_weather') | lower | regex_search('thunderstorm|drizzle|rain|snow|sleet|mist|smoke|haze|sand|dust|fog|ash|squalls|tornado|hurricane') }} 

i think this is it, thanks

sacred sparrow
#

is anyone able to see why this template sensor would be unavailable?:

#
    - platform: time
      at: "05:00:00"
      id: 5am
    - platform: state
      entity_id: sensor.outside_home_temperature
  sensor:
    - name: "Outside Min Temp"
      unique_id: outside_min_temp
      availability: "{{ states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number }}"
      unit_of_measurement: "Β°C"
      device_class: temperature
      state: >
        {{ iif (trigger.id == '5am' or
        states('sensor.outside_home_feels_like_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_feels_like_temperature'), states('sensor.outside_min_temp')) }}"```
#

sensor.outside_home_temperature = 12.9
sensor.outside_home_feels_like_temperature = 7.7

#

at 5am it triggered and the state was 8.1

#

but now its Unavailable

inner mesa
#

put the availability template in devtools -> Templates

sacred sparrow
#

I tried that and it says "True"

#

in logs it says:
Error rendering state template for sensor.outside_min_temp: ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ iif (trigger.id == '5am' or states('sensor.outside_home_feels_like_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_feels_like_temperature'), states('sensor.outside_min_temp')) }}"' but no default was specified

which is normal since the sensor is unavailable but I am just not sure why it would be

inner mesa
#

well, there ya go

#

states('sensor.outside_min_temp') isn't in your availability template

sacred sparrow
#

I changed it: availability: "{{ states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number and states('sensor.outside_min_temp') | is_number }}"

inner mesa
#

it's still going to be "unavailable"

sacred sparrow
#

now the state is "unknown" how can I have that it always shows the last known state

inner mesa
#
    - name: "Outside Min Temp"
      unique_id: outside_min_temp
      unit_of_measurement: "Β°C"
      device_class: temperature
      state: >
        {% set available = states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number and states('sensor.outside_min_temp') | is_number %}
        {{ this.state if not available else iif (trigger.id == '5am' or
        states('sensor.outside_home_feels_like_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_feels_like_temperature'), states('sensor.outside_min_temp')) }}
sacred sparrow
#

I tried that without the extra " on the end - do I have to wait for the trigger again?

inner mesa
#

oops

#

or just change the state

sacred sparrow
#

the state of sensor.outside_home_feels_like_temperature just change and so did sensor.outside_home_temperature but sensor still showing as Unavailable

inner mesa
#

debug it

#

I don't have your system

sacred sparrow
#

should I delete " availability: "{{ states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number and states('sensor.outside_min_temp') | is_number }}""

inner mesa
#

yes, note that I removed it

sacred sparrow
#

ah yes - sorry I just copied the state section

#

I'll give it a few minutes for my states to change πŸ™‚

inner mesa
#

jsut change the state

#

no waiting

sacred sparrow
#

how do I force a state change?

inner mesa
#

devtools -> States

#

find the entity, click on it, change the state, "set state"

sacred sparrow
#

strange - I set it to 20 and then it dropped to "1"

#

let me try again

#

when I reload the template entities it goes to 1

#

I'll put it back to 20 and see what happens when my sensors change with the weather outside - I'll be back in 15 mins

#

seems to be working - unsure why it drops to "1" when I reload

#

thanks for your help!

silent flicker
#

are conditions for equal to "==" or "="

inner mesa
#

tests are always "=="

silent flicker
#

TY

sacred sparrow
#

is there a better way to do:

    - name: "Collingwood Cloudy"
      availability: "{{ not is_state('sensor.collingwood_extended_text_0', 'unavailable') and not is_state('sensor.collingwood_short_text_0', 'unavailable') }}"
      state: >
        {{ 'cloudy' in states('sensor.collingwood_extended_text_0') or
        'Cloudy' in states('sensor.collingwood_extended_text_0') or
        'cloudy' in states('sensor.collingwood_short_text_0') or
        'Cloudy' in states('sensor.collingwood_short_text_0') }}

I've also noticed in the history of the state that even though the binary sensor is "on" it still triggers on - is there a way to stop that so it only triggers if it goes off to on

inner mesa
manic epoch
#

I'm running into a hurdle here. I have this line:

calculated_adjustment: "{{ states(target_temperature) | float - actual_temperature }}"

but I'd like to alter the end of it by adding an arbitrary 2 to it, so whatever numerical answer it comes out with, just simply add 2 to it. I assumed I needed | + 2 after actual_temperature but it doesn't seem to take...?

sacred sparrow
#

how about my issue with it changing to state on even though its already on? just trying to clean up my history

#

is it something like:

        states('sensor.collingwood_extended_text_0')|regex_search('cloudy') or states('sensor.collingwood_short_text_0')|regex_search('cloudy'),
        'off') }}```
inner mesa
#

what you did doesn't solve your problem

#

If it's triggering when the state doesn't change, then an attribute must be changing. There's nothing you can do about that with a template sensor, unfortunately

sacred sparrow
manic epoch
#

are there any unintended consequences I'm not thinking of if I take [snipped]...........float + calculated_adjustment ) * 2 ) | round ) / 2 }}" and instead of / 2 (which is of course a whole number) do something like / 1.9? The end result of this is a setpoint that's fed to my furnace thermostat. In one example, the output was 66.7, but my thermostat display just ends up saying 67 (only displays two digits). Perhaps that's fine?

#

if I divide by 1.9 it gets me more in line with where I want to be as far as the final number/answer, but couldn't help but to feel as though perhaps HA won't like that for some reason

hollow mortar
#

So sensors dont save their state when restarting HA, what would be the best template to put into a template sensor created just for this, to "detect" restarts, iow only restarts trigger it?

inner mesa
#

Add a unique_id

hollow mortar
#

What do you mean by adding a unique_id?

inner mesa
#

To your template sensor

#

It should save/restore the state

hollow mortar
#

Eh?

inner mesa
#

?

hollow mortar
#

So I just searched for these sensors that did not restore like a week, two ago, but couldnt find them just yet (i think they are normal sensors: history-stats) but that doesnt matter because I used this story to more easily explain what I need atm (sorry)

#

What I need atm is a sensor that triggers only on restarts

#

Will try that unique_id later when I find those problematic ones

#

So I think I found them, if I remember correctly its not that they kinda do not restore, the sensor they are counting becomes briefly unavailable and that triggers an On state as another cycle (=doesnt restore or merge it with the previous cycle)

#

Thats by design and I think unresolvable and so its a case closed for me

hollow mortar
marble jackal
lean canyon
#

I need help. I trying to import this https://community.home-assistant.io/t/engine-heater-automation/132528. But this {{ strptime(((as_timestamp('1970-01-01 ' ~ states('sensor.car_heater_departure_time')) - (states('sensor.car_heater_run_time')|float *3600))|timestamp_local), '%Y-%m-%d %H:%M:%S').strftime("%H:%M") }} doesn't work. Tried in jinja and got "ValueError: Template error: strptime got invalid input '1970-01-01T14:23:00+01:00' when rendering template '{## Imitate available variables: ##}" thankful for any help.

mighty ledge
lean canyon
#
input_boolean.car_heater_enable = off
input_boolean.car_heater_weekday = on
input_number.car_heater_3h_before_temp = 12.5
input_number.car_heater_hour = 19.0
input_number.car_heater_minutes = 0.0
sensor.car_heater_3h_before_start_time = unavailable
sensor.car_heater_departure_time = 19:00
sensor.car_heater_run_time = 0
sensor.car_heater_start_time = Never
mighty ledge
#

TBH that whole package is crap

lean canyon
mighty ledge
#

it's deprecated, but you can still use it

#

the guy who wrote that package didn't know templates very well, or automations for that matter. It just happens to work. That's my opinion, take it with a grain of salt.

#

if it works for you, by all means, use it. But it's not optimized at all

#

well, looking at the date, it looks like he didn't have many options

#

so it's just old

lean canyon
#

Ok, thank you @mighty ledge . I will search for a replacement if I don't find anything I try to make this work with your suggestion.

plain magnetBOT
#

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

mighty ledge
#

@fading oriole are you sure you got the clamps going in the correct direction?

#

as for your template, rename the value fields to state and delete the state: {{ value }} line.

fading oriole
mighty ledge
#

well, you shouldn't be getting negative numbers from your values, that typically indicates the clamp is going in the wrong direction

fading oriole
mighty ledge
#

anyways, back to your templates, you need to the beginning from

template:
  sensor:

to

template:
- sensor:
mighty ledge
#

FYI, if they are going the wrong direction, the values aren't going to be correct at all

#

so negating the values won't help

fading oriole
mighty ledge
#

if these are clamps that go on a wire, yes the direction matters

#

it depends on how they were wired

#

if you're trying to just get the return and it's installed correctly, then yes, negate the values

fading oriole
mighty ledge
#

personally, I always thought that the circuit would be set up in away that you wouldn't be measuring the load vs the return on the same clamp.

#

it's possible you have a different setup

lusty pasture
inner mesa
#

ah, the dreaded nested template

lusty pasture
#

yes

inner mesa
#

first, you're not actually assigning a string as I assume you think you are

lusty pasture
#

well, thats just in template debugger

inner mesa
#

looks pretty random

lusty pasture
#

the var is getting set properly and passed to the script but isnt getting resolved in the notify data section

lean canyon
inner mesa
#
{% set camera = 'amcrest2' %}
https://hass.domain.com/local/alerts/%22%7B%7B {{ states('sensor.' ~ camera ~ '_alert_image') }}
#

not sure what you're trying to do, but that's the idea

lusty pasture
inner mesa
#

🀷

#

ok

lusty pasture
#

thanks, i'll try that out

mighty ledge
lean canyon
lusty pasture
#

Thank you, I did have to update to image: from entity_id: but the template changes you suggested worked perfectly

remote cradle
#

Why can I add a template sensor to my energy dashboard? I don't understand, It has the good state_class and a valid unit? It does not show in the energy list for the gas sensor...

#

state_class: total_increasing
unit_of_measurement: kWh
device_class: energy
icon: mdi:fire
friendly_name: sensor.total_gas_energy

mighty ledge
plain magnetBOT
#

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

inner mesa
#

no, you cannot create entities that way

meager sparrow
#

I know repeat (from scripts )isn't the way to do this, but wondered if it was possible any other way

#

Okay, thanks Rob!

#

Writing them all out as in the first example is the cleanest (only) way I can do this then?

#

Ideally wanted them to have a defined-once set of other params i.e. min_temp max_temp etc

#

I could do that with variables I guess

inner mesa
#

You could use YAML anchors to reduce the repetition

meager sparrow
plain magnetBOT
meager sparrow
inner mesa
#

That has some of the right characters in it...

meager sparrow
#

I see a few errors, can't edit post πŸ˜„

#

I'll have a play, but thanks for sharing the concept

still plank
#

The docs say that a for_each loop in a script can iterate over a list returned from a template, but there are@no examples of how to return a list from a template. Any ideas?

marble jackal
#

I can give a lot of examples of a template returning a list

#

But it might be easier if you give some more insight in what you would need

still plank
#

I’ve figured it out now. It seems that a string formatted like a JavaScript list equates to a list.

#

I’m pretty much there with my mission now- I want to set each light that is on in a group to 20% of its current brightness - not 20% overall

mighty ledge
marble jackal
still plank
#

Interesting. Here’s what I came up with:

#

alias: Hall to 20%
sequence:

  • repeat:
    for_each: >-
    [{% for entity_id in states.light.hall.attributes.entity_id -%} '{{
    entity_id }}'{% if not loop.last %}, {% endif %}{%- endfor %}]
    sequence:
    - if:
    - "{{ is_state(repeat.item, 'on') }}"
    then:
    - service: light.turn_on
    data:
    entity_id: "{{ repeat.item }}"
    brightness: "{{ (state_attr(repeat.item,'brightness') * 0.2) | int }}"
    mode: single
#

light.hall is a light group with a few lights in it

marble jackal
#

my version was using all lights, you seem to have a light group you want to apply it to, use this then:

repeat:
  for_each: "{{ expand('light.hall') | selectattr('attributes.brightness', 'defined') | map(attribute='entity_id') | list }}"
#

I selected on all lights which have a brightness attribute, that also means they are on, as otherwise the attribute doesn't exist

still plank
#

I need to read more on the templating stuff. Your version seems neater than mine.

marble jackal
#

It also filters out lights which are unavailable

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

marble jackal
#

Here are some links to start with

still plank
#

Thanks.

#

What does the map part of your expression do?

marble jackal
#

The expand function returns the entire state object, the map filter takes only the entity_id out of that

#

I'm off to bed now, but if you have further questions others can help here

still plank
#

You’ve been very helpful, thank you.

cyan musk
#

Is there a way to have an easy template where if a smart light switch toggles on or off a smart globe will also toggle to the same as the switch?

marble jackal
glossy viper
#

hi. i create(d) sensors for (almost) every national team that takes part in Qatar WC through a custom integration. I have an automation notifying me every time a team scores, but i have to change at every game the name of the sensor. can i make my automation to read every sensor and notify me when an attribute changes and for what team ? http://pastie.org/p/11nfdmSG3yYt0Ww8o3Ry8C

marble jackal
#

you can just add all sensors in the entity_id field

#
entity_id:
  - sensor.mex
  - sensor.qat
  - sensor.ned
  - etc
glossy viper
#

true. but when mex will play ned...basically from sensor.mex i will get 1-0 if mexic scores....and sensor.ned will get...hopefully 0-1

#

sometimes simple things are not obvious for me. thank you πŸ™‚

marble jackal
#

Just use one trigger then

#

not both

#

you do need some adjustments in your template though`

plain magnetBOT
glossy viper
#

thank you

marble jackal
#

the only thing is that you don't know who scored

#

so you also don't know who is winning πŸ˜›

glossy viper
#

:))))

marble jackal
#

what kind of further information is in that sensor?

#

you can probably add some relevant information to that message

glossy viper
#

there is team_abbr

#

also opponent_Abbr

#

i can have... in the match {{ trigger.to_state.attributes.team_abbr }} - {{
trigger.to_state.attributes.opponent_abbr }}
the score is {{ trigger.to_state.attributes.team_score }} - {{
trigger.to_state.attributes.opponent_score }}

#

?

marble jackal
#

yes, that will work

#

the only thing is that you can have ARG - KSA then, when the match is officially KSA - ARG

glossy viper
#

single thing is that the information will be doubled

#

πŸ™‚

marble jackal
#

no

#

it won't be doubled, because you onlyl use the team score as trigger

#

not also the oponent score

glossy viper
#

host and opponent are provided by the integration....hope will be the official ksa-arg

#

thank you for the effort

marble jackal
#

@glossy viper

alias: WC3
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.mex
      - sensor.ned
      - sensor.qat
      - 
    attribute: team_score
action:
  - service: notify.whatsapp
    data:
      title: S-a marcat in meci
      message: >-
        {% set match = trigger.to_state.attributes.event_name | replace('@', '-') %}
        {% set host = match.split(' - ')[0] %}
        {% set team = trigger.to_state.attributes.team_abbr %}
        {% set score = [ trigger.to_state.attributes.team_score, trigger.to_state.attributes.opponent_score ] %}
        In the match {{ match }} the score is {{ score | join(' - ') if team == host else score | reverse | join(' - ') }}
cyan musk
#

Thanks!

woven vine
#

Hey guys, is it possible to get a list of all areas in templates?

mighty ledge
#

yes, but it's not optimal

#

there's no simple way to do it

woven vine
#

it's totally okay

mighty ledge
#
{{ states | map(attribute='entity_id') | map('area_name') | reject('none') | unique | sort }}
woven vine
#

ah okay you get all states and iterate trough them to get the area and unique the list to remove dupes. Thought about this but got afraid about the performance because this seems to be very expensive everytime, right?

mighty ledge
#

yep

woven vine
#

I guess this would be a great addition for HA if this would get a native implementation

marble jackal
#

@woven vine you can put it in the attribute of a trigger based template sensor with the HA start event as the trigger

#

then it's performed once when your system starts, and you can use the attribute in your templates

#

add the template reloaded event as a second trigger so you can easily update the data after you added/changed an area

#

unless there is an area updated event you can use

woeful grove
#

hey ive a basic Question. i want do send me time Difference to my Phone. Currently i send only the time. Is there a Calculation in Notifier Possible
=now-abfahrtszeit

start time attribute is in hh:mm

Part of the Automation
service: notify.mobile_app_iphone_12 data: title: 🚌 You canΒ΄t reach the current Bus. DonΒ΄t worry the next one comes soon! message: "Next start TimeπŸ•’ : {{ state_attr('sensor.oebb_journey_2_2', 'startTime') }}"

Maybe someone can help me how the calculation would work

#

so it will look something like {{ state_attr('sensor.oebb_journey_2_2', 'startTime') }}" - now but i dont know exactly how πŸ™‚ Maybe someone knows

inner mesa
#

It's just math

#

{{ (now() + timedelta(minutes=2)) - now() }}

#

you might need to do this:
{{ today_at(state_attr('sensor.oebb_journey_2_2', 'startTime')) - now() }}

woeful grove
#

yeah i know its very simple but i stuggle πŸ˜‰ with writing im still learning

#

@inner mesa that works in the Template Dev Tools in general but not as Notifier

inner mesa
#

it's no different from what you have above

#

it's just a template

woeful grove
#

so i need a new Template i cant do that directly in the notifier

inner mesa
#

I'm not following

#

you were using this:

#

message: "Next start Time:clock3: : {{ state_attr('sensor.oebb_journey_2_2', 'startTime') }}"

#

so use this:

#

message: "Next start Time:clock3: : {{ today_at(state_attr('sensor.oebb_journey_2_2', 'startTime')) - now() }}"

#

it's just a different template

woeful grove
#

sorry it works like charm @inner mesa is there any possibilitys to get away after mm:ss

woeful grove
#

0:40:03:64868

#

0:40 would be enough

inner mesa
#
{% set upcoming = "11:00" %}
{% set diff2 = today_at(upcoming) - now() %}
{{ "%s:%s"|format(diff2.seconds//3600, diff2.seconds%60) }}
#

-> 0:38

silent flicker
#

Im pulling a date out of an IMAP integration and it shows up as

{{ (state_attr('sensor.aaronautomation_mail','date')) }}

with the result being "Tue, 22 Nov 2022 10:58:18 -0800 (PST)" . is there a way to convert this to local? im in EST and its in PST for some reason

inner mesa
#
{% set date = "Tue, 22 Nov 2022 10:58:18 -0800 (PST)" %}
{% set dt = strptime(date[:date.rindex(' ')], "%a, %d %b %Y %H:%M:%S %z")|as_local %}
{{ dt }}
silent flicker
#

ohhh, like that huh

#

thanks

silent flicker
#
{{ states('sensor.openweathermap_wind_speed') | float * (2.23694) }}

output = 5.010745600000001

is there a way to round this number to say...1 decimal place?

inner mesa
#

surprisingly, round(1)

silent flicker
#

wth, hang on lol

inner mesa
#

There are great docs in the channel topic

silent flicker
#
{{ states('sensor.openweathermap_wind_speed') | float * (2.23694) | round(2) }}
#

like this?

inner mesa
#

No, that's rounding 2.34694

silent flicker
#

oh. poo

#

i see

mighty ledge
#

move the ( in front of the 2, 54 characters to the left

silent flicker
#

ah i got it, thx

#

the sensor is in meters / second. im converting it to MPH

inner mesa
#

You had both too many parens and also not enough πŸ™‚

silent flicker
#

a lot of this is learning the formatting of how to write it, not so much what needs to be done. i can figure out most things, but not sure how to format it in the yaml way

marble jackal
#

It's not yaml, it's jinja

tawdry pond
#

How can I use the light.turn_on service to set the HS color to it's current color +30 %360? (plus thirty, modulo 360 since HS color can be 0-360)

marble jackal
#

With saturation remaining as is?

tawdry pond
#

Yeah, or just 100.

#

I'll probably hardcode it to 100

mighty ledge
#

isn't that just rgbiv

#

but now you have red twice

marble jackal
#
service: light.turn_on
target:
  entity_id: light.your_light
data:
  hs_color:
    - "{{ [ 360, state_attr('light.your_light', 'hs_color')[0] + 30] | min }}"
    - "{{ state_attr('light.your_light', 'hs_color')[1] }}"
#

This will only work when the light is on though , otherwise the attribute is not available

tawdry pond
#

That's the plan. Thanks!

glossy viper
#

hi. i try to simplify the way i store air conditioner active time. is there a simplier way to store the hours that it was on ? i did this http://pastie.org/p/5QtflbCKFPyV87HkGeDwns but sometimes the value is stored as 0 although my air run 😦

hollow mortar
#

Im adding _(component.sensor.state.duration.{{states(config.entity)}}) to state: into a custom lovelace card and it aint changing 9.31 to "duration"

#

Its just _(component.sensor.state.duration.9.31) in entitys state

#

What am I missing?

inner mesa
#

I can't figure out what you're taking about

hollow mortar
#

custom:template-entity-row can make custom secondary-info and also state

#

But state is kinda decoupled from "gui translation of values"

#

While I added to some _(component.sensor.state.battery.{{states(config.entity)}}) and other _(component.sensor.state.window.{{states(config.entity)}}) they both work

#

Only duration does not atm :/

#

_(component.sensor.state.duration.{{states(config.entity)}})

#

I tried doing _(component.sensor.state.duration.['{{states(config.entity)}}']) because digit is first but it just outputs _(component.sensor.state.duration.['9.31'])

merry delta
#

Should I ask template questions related to mushrom template card here or front-end?

inner mesa
#

Mushroom uses jinja, right?

merry delta
#

Nm, it's definitely a card specific question

plain zinc
#

I'm feeling a bit ridiculous not finding a filter.

Want to find a minimum value of a list of objects.

{{ state_attr('weather.tomorrow_io_home_nowcast', 'forecast') Is a big old list of objects ```{'datetime': '2022-11-23T02:06:00+00:00', 'condition': 'cloudy', 'precipitation_probability': 0, 'wind_bearing': 289.13, 'temperature': 0.4, 'wind_speed': 8.32, 'precipitation': 0.0}


I just want to filter on `temperature`
#

selectattr will match all with temperature in it but I really just want to make it a list of temperature and | min to get the minimum

inner mesa
#

You seem to be missing map(attribute='temperature')

plain zinc
#

ah I was trying map('temperature') at one piont

#

just not attribute='temperature'

#

{{ state_attr('weather.tomorrow_io_home_nowcast', 'forecast') | map(attribute='temperature')|list|min}}

Beautiful thanks

#

Spent way to long on that...

merry delta
#

A template that will show the content playing on a media_player?

merry delta
#

Or extrapolate the source?

prime kindle
#

Inside the conditions of an automation, I want to use the following template which is checking whether the 'UNKNOWN' keyword is present in the state of sensor or not.
If yes then I have to trigger an action, but this condition is not working

condition: state
entity_id: sensor.main_door_lock
state: >-
Β  Β  Β  Β {{'UNKNOWN' in states('sensor.main_door_lock')}}

#

Am I doing anything wrong here

prime kindle
#

service: mqtt.publish
data:
Β  topic: alerts
Β  payload_template: >- Β  Β 
Β  Β  Β  {% if "UNKNOWN" in states("sensor.main_door_lock") %}
Β  Β  Β  Β  Β  Β  Β  {{ "Unknown user is trying to open the door" }}

#

This is also not working

#

It is producing error that template value should be a string

mighty ledge
mighty ledge
deep marsh
#

Hi all,
Is it possible to directly use an OR statement if you loop through a domain?
For instance, I want to loop through all my lights with a linkquality defined or a raw_state defined.

Like this:

{{ states.light 
  | selectattr('attributes.linkquality', 'defined') OR selectattr('attributes.raw_state', 'defined')
  | selectattr('state', 'eq', 'on')
  | map(attribute='name') | join('\n') 
  }}

This is not working (of course), but I'd like to do something like this instead of adding a for loop after I filled a namespace with values. I hope you get what I mean.

deep marsh
mighty ledge
#

gotta make 2 collections and add them

deep marsh
#

I should go the for loop route then I guess

mighty ledge
#

no need

deep marsh
#

Oh, that's also an option indeed

#

Didn't think about it

mighty ledge
#

just make them both lists then add them with a +

#

then apply the | jion

deep marsh
#

Thank you!

mighty ledge
#

np

#

is that for a message? Why just a \n?

deep marsh
#

It's indeed for a message πŸ™‚

mighty ledge
#

πŸ‘

marble jackal
floral shuttle
#

this might be automation, though I am fighting to find the easiest template .... given https://pastebin.com/PXd7EQks what would be the most effective template to calculate the time between switch.turn_on and switch.turn_off in the action? So I can notify: "switch has been on for xx::xx min:sec"

#

ofc I also want to notify the kWh it used during that time, but that is phase 2b... πŸ˜‰

#

trying to use the last_triggered (set when the condition block passes) and the last_changed of the switch seems to be my choice now..though that wont survive a restart I am afraid

#

still, this is what I ws looking at:```
{{(states.switch.opentherm_dhw_comfort_mode.last_changed|as_timestamp -
state_attr('automation.zonneboiler_schakelen','last_triggered')|as_timestamp)|timestamp_custom("%H:%M:%S")}}

#

or, using the this variable: {{(states.switch.opentherm_dhw_comfort_mode.last_changed|as_timestamp - this.attributes.last_triggered|as_timestamp |timestamp_custom("%H:%M:%S")}}

floral shuttle
#

but its completely wrong...

#

since I manually triggered it the notification was not correct, but look at this template that is closer: it adds 1 hour

#

heck, I forgot ,False. sorry

mighty ledge
#

that's why I avoid as_timestamp πŸ˜‰

#

as_datetime, all day

#

no need for as_timestamp... at all

#

{{ states.switch.opentherm_dhw_comfort_mode.last_changed - this.attributes.last_triggered | as_datetime }}

floral shuttle
#

that gives me the TypeError: float() argument must be a string or a real number, not 'datetime.timedelta' when I use the verbose automation entity

#
{{(states.switch.opentherm_dhw_comfort_mode.last_changed -
  state_attr('automation.zonneboiler_schakelen','last_triggered'))
 |as_datetime}}```
mighty ledge
#

you added a parenthesis which changed the meaning

#

use what I wrote πŸ˜‰

floral shuttle
#
  state_attr('automation.zonneboiler_schakelen','last_triggered')
 |as_datetime}}```
inner mesa
#

that is a pretty confusing error message, though πŸ™‚

floral shuttle
#

still throws the same error

mighty ledge
#

not sure how that's possible becaues that's returning a timedelta

#

the error must be coming from something else

floral shuttle
#

this is what I had

mighty ledge
#

odd, just remove the as_datetime, apparently it's already a datetime

inner mesa
#

I wonder what the heck the code is doing there

floral shuttle
#

right! that returns 0:13:03.495317

mighty ledge
floral shuttle
mighty ledge
#

the as_stimestamp one won't be correct past 24 hours btw

floral shuttle
#

well, I hope it will never get to that ...;-)

#

it should only max to 30 min or so

#

but to get it to be correct, what do I need? I cant leave it like this anyways, because of all the micro seconds

mighty ledge
#

why not?

#

make it a duration sensor, set the units to seconds

#

how it will have hh:mm:ss in the UI

floral shuttle
#

this is for my notification.... it should report in HH:MM:SS max

#

will only ever be MM:SS though

mighty ledge
#

(...).seconds | timestamp_custom("%M:%S")

floral shuttle
#

thx! yes thats very nice. btw, why is that first subtraction returning 1970... does it calculate all the way back to the beginning +13 min and 3 secs ..

mighty ledge
#

because you're using as_timestamp

#

0 in seconds is 1970

#

when you subtract 2 times, you get close to zero

inner mesa
#

In the beginning...

floral shuttle
#

yes, thats was what I tried to say.. in the beginning

#

hehe

#

cool. I wont do that again. this is much better

#

thanks!

remote cradle
# mighty ledge you're doing something wrong, based on what you have there, you're confusing the...

Sorry, I needed to be on my computer to reply. Here is my templates.yaml, included in my configuration file : - sensor: - name: gas_volume unit_of_measurement: "mΒ³" state: > {{ state_attr('sensor.gazpar', 'daily')[0]['end_index_m3'] | float(0) }} icon: mdi:fire device_class: gas state_class: total_increasing - name: gas_energy unit_of_measurement: "kWh" state: > {{ states('sensor.gazpar') | float(0) }} icon: mdi:fire device_class: energy state_class: total_increasing

mighty ledge
#

backticks

#

`

mighty ledge
#

as long as you put that in teh template section

remote cradle
# mighty ledge as long as you put that in teh template section

Both sensors are in the state tab of the dev tools. And are working. But I can't add them in the energy dashboard. The gas_volume is in the list of the available sensor for the energy panel but I can't save it when selected, the save button is gray. The gas_energy is not in the list...

marble jackal
atomic blade
#

Is there a way to get an entity's icon via template if it isn't an attribute? Or alternatively, perhaps there's a way I can have the default icon show up as an attribute? It only seems to show up if you set it manually which I don't want to

atomic blade
#

Bummer

floral shuttle
#

thx Martijn, will do. Still, seems to me we should be able to measure the time spent on the action (endtime-begintime) of an automation in a more default way, than spelling out some actual entities and calculating their last_changed/triggered

plain magnetBOT
#

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

stuck remnant
#

This is for a history_stats sensor. I need the start time to always be 24 hours before now, ending with now. how would I write it?
start: "{{ now() - 24 }}"
end: "{{ now() }}"

inner mesa
#

{{ now() - timedelta(hours=24) }}

stuck remnant
#

thats great, cheers

marble jackal
#

or timedelta(days=1)

still plank
stuck remnant
#

what if I need a percentage? I see a type: ratio there but it kind of confused me cos in the example, the time from the start time is said to be divided by the period length but in my case it would be shifting constantly

#

basically what percentage of the last 24 hours has the switch been on

still plank
#

oh, sorry, you want the history_stats sensor in percentage.

stuck remnant
#

That's just it though, the duration won't be til 2am , the start and the endpoint will always be shifting

still plank
#

your period is always 24h though isnt it?

stuck remnant
#

Start will be now minus 24h, and end will be now. And yes, a percentage is what I'm going for

still plank
#

for a history_stats sensor you provide two of start, end and duration. Home assistant works out the one you didn't provide. So even if you provide start and end, and even if those expressions vary, it still works. However, you use is simple. You want a rolling 24h up to now. so you specify the duration and the end, liek this:

- platform: history_stats name: example sensor entity_id: <your entity> state: "on" type: ratio duration: "24:00:00" end: "{{ now() }}"

#

here, end is now() and duration is 24h, so HA works out the start time, and since type is ratio, the output is a percentage.

stuck remnant
#

Oh that makes sense

#

You said it before but it's just now that it clicked for me. Thanks for taking the time

still plank
#

no worries

stuck remnant
#

So it will divide the 24 by 24?

still plank
#

yes. internally, it's doing [entity on time] * 100 / [sensor duration]

stuck remnant
#

But won't that yield 1?

still plank
#

no

#

just try it, it works nicely. history states is really useful

stuck remnant
#

Sure I'll just pop it in see how it goes thanks a lot. Otherwise I can just do with the hours, as is

still plank
#

you can add lots of these sensors all targetting the same entity. so, to experiement and prove it to yourself, add one in hours, one ratio, oen with 24h duration, one with an hour duration etc. look at the state values in developer tools. you'll seen see how it works.

stuck remnant
#

Yeah that sounds like a good perspective

#

Cheers

thorny snow
#

Is there any way to iterate through a bunch of entity_ids based on some criteria, other than forming a group? My entities are dates, thus I cannot put them into a group.

still plank
thorny snow
#

I'd like to switch on heating in several rooms, based on an occupancy table. This table contains date:time information that I converted to date sensors. I'd like to regularly iterate through the sensors to see when to switch on heating.

marble jackal
thorny snow
marble jackal
#

Just scroll to the bottom of that page, there is a section on old school style groups

thorny snow
marble jackal
#

Yep

thorny snow
#

Hi, I want to create a template that subtracts the time from the alarm time. I've found the following script, but that sets the time to one hour before at today. As my alarms are mostly set at night, I want the script to run the following day 1 hour before the alarm. I've already tried tomorrow_at but that doesn't seem to exist. How can I do that?

  - name: "1uurvoorwekker"
    state: "{{ today_at(states('input_datetime.smartsleep')) - timedelta(minutes=60)  }}```
thorny snow
# marble jackal Yep

Do you have any info on whether it stays that way or will eventually be deprecated?

#

The documentation is quite fuzzy wrt its future.

marble jackal
#

it will stay

marble jackal
thorny snow
#

Great, thanks a lot!

still plank
# thorny snow Hi, I want to create a template that subtracts the time from the alarm time. I'v...

i think what you say you want isn't quite right. you're trying to find the next occurence of a particular time of day, which might be later on today (hence today_at would work) or it might be tomorrow, if today's alarm has already passed. You therefore need an if block to see if today's alarm is in the past, or not. It can be done with IIF:

{{ today_at("10:15") if now() < today_at("10:15") else today_at("10:15") + timedelta(hours=24) }}

substitute the string time for the state of your input.

marble jackal
#

At that moment the sensor will indeed show 7:00 today, which is one day early. However, after midnight, the sensor state will change to 7:00 on that new day, and it will be correct

#

If you use it in a time trigger, the trigger will only look at the time part anyway

analog mulch
#

hi I would like to trigger on an event related to some entity_id, when the parent_id in the context is not null. I understand this parameter takes limited templates. How would I do this? I guess the below won't work

    - platform: event
      event_type: "state_changed"
      event_data:
        entity_id: cover.blind_gabinet
      context:
        parent_id: "{{ not null}}"
silent seal
#

What on earth is a parent id?

analog mulch
#

when states are changed by automations they have a parent_id, when they are changed by users/external they are null. I would like to trigger when another automation triggered the change

mighty ledge
#

You have to make that a condition, context isn’t valid in the trigger

analog mulch
mighty ledge
#

Must be new

#

Either way, doesn’t accept templates

analog mulch
#

this works perfectly:

 trigger:
    - platform: event
      event_type: "state_changed"
      event_data:
        entity_id: cover.blind_gabinet
      context:
        parent_id: null
      variables:
        act: "off"
        switch: input_boolean.blind_sunscreener_gabinet_auto
mighty ledge
#

So, it needs to be a condition

analog mulch
# mighty ledge Must be new

The docs say "It’s also possible to use limited templates in the event_type, event_data and context options."

mighty ledge
#

Check the note πŸ˜‰

analog mulch
#

now I understand what that means. ok πŸ™‚

still plank
#

that is interesting. i've wondered before how if you have an automation that will turn off the lights in 10 minutes etc, if someone manually controls a light (via app, switch, anything), you'd want to cancel that delayed action; this could be a way of doing it? i.e. any state change without a parent_id cancels the running automtaion

analog mulch
#

I'm exactly trying to do that -- swtich off automatic tiling on blinds when someone's touched the physical buttons

mighty ledge
#

It’s been on my list of things I want to add to all triggers, but not use the ids and use the actual entities

#

I have time at Christmas break to look at it

silent seal
#

I've been reworking a number of my automations recently to use explicit states (or combinations) instead of trigger IDs and it's been a nice improvement

still plank
#

well i've just tried the above and it works perfectly

silent seal
still plank
#

So how is that an improvement? You end up repeating a load of the trigger logic in conditions in actions? (Genuine question, I’m learning here)

silent seal
#

Instead of saying "if trigger id "temperature went above 5Β°C" and the tank is not full, , then do X, I just check the logic for any trigger

#

I could have #templates-archived triggers that only turn to on when the temperature is above 5, and when the tank is not full, but this keeps it simple.

analog mulch
#

I have to say, most of my automations have started looking like this, and if you add an extra entity to the trigger, the conditions need to be rewritten. so I suggested a condition trigger, which would trigger when a bunch of conditions become true. A kind of newbie template trigger.

mossy osprey
#

I am trying to create a sensor to QC if all my lights in a group are in 'sync' for use in node red after automations. I currently have this in my sensors.yaml: http://pastie.org/p/37Ny0NMbIanBKbpaVdNlNW

This basically filters to group and in TWO templates counts unique brightness and RGB values, hopefully each yielding '1'. The third function AGAIN checks if both are congruent, also hopefully ending in '1'. If 'aggregate' = '1', then no prob, if >1 then there is more than one unique value for something, re-run automation etc.

This is clunky and not the most efficient way to gather this info I feel, plus it clutters up my sensors.yaml. Is there a more accurate way to combine these all into one, or better yet report back the specific problem light in a given group for a more direct error correction post storing the result?

sharp folio
#

successfully set my car up to schedule preconditioning for 30 minutes before work IF I have it the next day, it runs at 10pm via an automation, let me know your thoughts!
https://paste.helpch.at/ovunayexej.yaml

#

I could've done the enabled bit with a condition that lead to hard-coded false and departure time 0, but wanted to see what I can do with templates and kind of use them a bit

#

and I already had the work done for the departure, so πŸ€·β€β™‚οΈ

lethal bison
#

okay so that just creates a sensor that's populated with the triggering entity at the time

sharp maple
#

Hi all - quick question:
Have a template sensor with state: {{state_attr('sensor.bin_days', 'nextbindate') }} which gives a value of 2022-11-26T07:00:00, but when I set device_class: timestamp (after all, this is an ISO8601 format date string), the state becomes "unknown. Am I being particularly stupid here?

#

Ah, solved it myself - a timestamp needs an explicit timezone (even if +00:00) on the end. Sorted.

scarlet sapphire
#

Hello, how can I filter the on/off from binary_sensor.phone1_bluetooth_state=on; icon=mdi:bluetooth ? When I try state.sensor it says undefined

inner mesa
#

what, exactly, did you try?

#

there's not enough there to help

scarlet sapphire
#

{{state.binary_sensor.phone1_bluetooth_state}} is my understanding of how this works since it's not an attribute

#

so this is where I am

inner mesa
#

no, that's not right

scarlet sapphire
#

that I am sure about. can you give me a pointer how to make this work please?

inner mesa
#

that's just retrieving the state of an entity, though. it's not what you originally asked

scarlet sapphire
#

I want to determine if bluetooth is on or off basically

inner mesa
#

alright, then see that link

scarlet sapphire
#

and build an automation to listen for a change

inner mesa
#

then you don't need a template at all

scarlet sapphire
#

sorry for being unclear

inner mesa
#

that's just a state trigger

scarlet sapphire
#

well I want a notification to say the state as well, sorry for beeing incomplete as well

inner mesa
#

that still doesn't mean you need a template

scarlet sapphire
#

ok, what would be the best way todo it then?

inner mesa
#

perhaps just start over

scarlet sapphire
#

done

inner mesa
#

what exactly are you trying to do?

scarlet sapphire
#

I press an aqara button to say "Papa still asleep" if bluetooth is off

#

the aqara buttin triggering an echo notification

inner mesa
#

wow, that's quite far afield from the original question πŸ™‚

scarlet sapphire
#

I got the aqara button to work

#

I got the echo part to work

#

just need to figure out the bluetooth on/off part

inner mesa
#

that part is easy. use a state condition with that entity

scarlet sapphire
#

well I want todo part of the work as well πŸ˜‰

#

hah, that is indeed much easier i GUESS

#

thank you sir

leaden perch
#
  sensor:
    - name:         'Marantz Kamer Volume'
      state_topic:  "marantz/state/0/volume"
      value_template: "{{ float(state) / 0.6 }}"```
I'm trying to divide a value coming from an MQTT sensor by 0.6, but I cannot figure out what the correct term to use for `state` is. I also tried `value`, but that doesn't work either. I've looked at https://www.home-assistant.io/integrations/sensor.mqtt/#examples but that  mentions JSON attributes, which I believe is not what I want
inner mesa
#

What are you getting from that topic?

mossy osprey
leaden perch
#

If I get 0.60 I want to turn it into 1.00

inner mesa
#

Then just 'value'

leaden perch
#

and is the float() neccesary?

inner mesa
#

Maybe, maybe not. Won't hurt

leaden perch
#

huh that works, thanks! no idea why it didnt work before πŸ˜›

ember saffron
#

is this the new syntax? - platform: template sensors:

silent seal
#

No, that's the legacy syntax

vast juniper
#

Can someone correct my syntax here, I want a printout to be true when none of this is met

#
{{ state_attr('calendar.shift_pattern', 'message') != "First Day" or "Second Day"}}
inner mesa
#

{{ state_attr('calendar.shift_pattern', 'message') not in ['First Day', 'Second Day'] }}

ember saffron
inner mesa
#

It understands both

thorny snow
#

I created an old-style group via yaml containing entities with timestamps and try to expand it in a template, but it gives me back an empty list. Could you give me a hint why it does not work?

silent seal
#

The group is empty would be my guess

thorny snow
#

No, I checked it in the developer tools.

#

{{ expand('group.next_arrivals')}} is empty all the time.

#

States in Developer Tools shows the group nicely, with all its members.

marble jackal
#

What does {{ state_attr('group.next_arrivals', 'entity_id') }} show in devtools

thorny snow
#

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'temperature'

#

It looks it is messed up somehow, I need to see where temperature comes from.

#

The members of the group all have device_class: timestamp

#

Do I need to specify device class for the group as well?

marble jackal
thorny snow
#

Sorry, my mistake, I had too many templates in Developer Tools. After cleaning up it nicely shows all member entity_ids, separated by commas.

thorny snow
#

How shall I proceed from here?

marble jackal
#

If that works, expand should work as well

thorny snow
#

I might do something silly but it just does not expand. Can you recommend something else to check on?

marble jackal
#

Did you try with only {{ expand('group.next_arrivals') }} in the template editor?

#

Just to avoid confusion

#

You can try this as well {{ expand(state_attr('group.next_arrivals', 'entity_id')) }}

thorny snow
#

Yes, I've been trying all these in the template editor. I just tried both versions to no avail. Could I have bumped into a bug perhaps?

#

I have another group containing binary sensors (mqtt generated), and the expand works there just fine. The problematic group contains date sensors also created by mqtt.

sharp maple
#

Hi all - quick question for your thoughts. I have an on/off "switch" that is operated by two buttons (let's say "start" and "stop"), which I've configured up on a template switch. The thing is that it can take a long time (up to 5 minutes) from switching it "on" before the device confirms back its status as "on". Unfortunately, the template switch appears to time out and return to the "off" position after 10s or so, which leaves a somewhat ambiguous state until the device reports back, and the switch moves correctly to "on" some period later. Any thoughts on a better way to do this?

proud cradle
#

I'm updating a template I've been using for a while now but ran into an issue. The new datetime format contains microtime (.000) which seams to throw my rejectattr('startsAt', 'lt', now()) off for some reason. I get this error now:
TypeError: '<' not supported between instances of 'str' and 'datetime.datetime'

I've verified that the datetime string can be parsed by Date('2022-11-26T00:00:00.000+01:00')
What is wrong and any idea how to resolve it?

#

New data:

today: 
- total: 2.9208
  startsAt: '2022-11-26T00:00:00.000+01:00'

Old data:

- start: '2022-11-26T00:00:00+01:00'
  end: '2022-11-26T01:00:00+01:00'
  value: 2.81
grim flicker
#

i have a mqtt sensor that needs to report the battery percentage out of this message:

{
  "id": 0,
  "battery": {
    "V": 6.23,
    "percent": 100
  },
  "external": {
    "present": false
  }
}

normally i would use something like:
value_template: "{{ value_json.battery }}"
how do i get info from one layer deeper in the json? so i can use percent as the value for my mqtt sensor

marble jackal
#

try rejectattr('startsAt', 'lt', now(). isoformat())

proud cradle
#

Maybe also know how I could re-write this | map(attribute='total') to return:

[
  [
    startsAt: '2022-11-26T01:00:00+01:00'
    value: 2.81
  ]
]
silent seal
#

Well map will select a value to return. So, you'll have to skip the map

#

Without seeing the whole template and some data it's hard to say what you could do instead

proud cradle
#

I'm thinking if I've overcomplicated this for no reason. I have an ApexCharts chart with the electricity price and now I want to add an boolean line indicating if I've had the heater on or off (which I control from a binary sensor)

silent seal
#

But at least it would have to be:

[
  {
    startsAt: '2022-11-26T01:00:00+01:00',
    value: 2.81
  }
]

Or similar.

proud cradle
#

And now I want another data series in there which should only be 0 or 1 showing if my heater will be triggered or not

#

Could that be achieved in any easier way than creating a new time series with date and value (0/1)?

silent seal
#

So you want dots on the graph where the heater is on?

proud cradle
#

Yeah

silent seal
#

And the heater data?

plain magnetBOT
#

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

proud cradle
#

The heater is controlled from the binary template_sensor I posted in the previous message.

marble jackal
#

expand() works just fine on this group

grim flicker
#

@marble jackal thanks for the help!

thorny snow
proud cradle
#

Can someone explain how I write this if else clause in Jinja/template?
https://pastebin.com/3b7WA4zE

I want to generate a new array (time series) but I don't know how I can do that.

marble jackal
#

I'm not sure what kind of values you expect in this array. But you need to use a namespace

{% set ns = namespace(vars = []) %}
{% for item in heater %}
  {% if item.value < threshold %}
    {% set ns.vars = ns.vars + [ 'whale'] %}
  {% else %}
    {% set ns.vars = ns.vars + [ 'petunis'] %}
  {% endif %}
{% endfor %}
{{ ns.vars }}
proud cradle
marble jackal
#

Don't share images of code

plain magnetBOT
#

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

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

solar hemlock
#

how could I make a template to detect when a timestamp is older / not updated within the last 5 hours? This is what the time stamp format looks like; 2022-11-26T18:05:58+00:00

inner mesa
#

{{ "2022-11-26T18:05:58+00:00"|as_datetime|as_local < now() - timedelta(hours=5) }}

solar hemlock
#

How could I incorporate the time stamp from the sensor named sensor.litterbotz_last_seen?

inner mesa
#

Are you asking how to get the state?

#

That's just basic templating

odd maple
#

is there a simple way in jinja to convert seconds to a HH:MM:SS timestamp?

solar hemlock
#

{{states.('sensor.litterbotz_last_seen')|as_datetime|as_local < now() - timedelta(hours=5) }}

#

Is that the correct syntax for pulling the sensor state?

odd maple
#

no

#

states('sensor.whatever')

sharp folio
#

{{ states('sensor.litterbotz_last_seen')|as_local < now() - timedelta(hours=5) }} I think

#

my lord that was all over the place

#

not sure if you still need as_datetime if it's a timestamp already

solar hemlock
#

Returns with error; AttributeError: 'str' object has no attribute 'tzinfo'

sharp folio
#

try adding as_datetime back

#

still learning myself

sharp folio
solar hemlock
#

Thank you for helping. I'll give it a shot, I feel like I'm working on half my brain lol new born at home and loosing sleep.

sharp folio
#

oh boy definitely a lot to handle πŸ˜‚

solar hemlock
#

That does indeed seem to work. Thank you so much!

sharp folio
#

πŸ‘ no problem!

marble jackal
odd maple
#

looks like timestamp_custom('%X', false) does it too, guess my missing piece was the false bool thanks again

marble jackal
#

Without it the time is converted to local time

#

So eg 3600 as a timestamp will be 1:00 on 1st of January 1970

#

Without the false that will be converted to your local time, and the that time will be used

proud cradle
#

What do I need to change to make this template sensor to work as a list of values?
When I run it I get an error that the state length is too long.

Sensor
https://pastebin.com/SKzH3TVp

Template output (values - this is what I want in the sensor (to use in ApexCharts))
https://pastebin.com/uBa9xfvP

marble jackal
#

Put it in an attribute, states are limited to 255 characters and are always strings, so it won't be a list

proud cradle
#

I google that but didn't see how?

marble jackal
#

btw you are sometimes using state_attr() which is good, but also sometimes states.sensor.whatever.attributes.attribute which should be avoided

proud cradle
#

Got it, thanks.

lethal harbor
#

Hello

#

After 18pm, stock max value. After midnight go to zero and start pushing value sensor after 6am

#

This is the right approach?

keen abyss
#

Hey, I'm trying to configure a total_increasing template sensor that shows the time my cats slept, e.g 05h 24min

This is an increasing value which resets every night at 00:00

I was wondering how should I configure it so that it can show properly in the history stats as well as in grafana, and I wanted to know if there's a way to make this sensor only update its existing value in the database for that day instead of adding a new one(not sure if that's what total_increasing already does)

I.e should I make it hh:mm, <hours>h <minutes>m? Or is there no way for me to display both hours and minutes and I'd have to e.g have it just in minutes?

Thanks for your time!

#

On a second look total_increasing might not be the right type

green scaffold
#

how do i set the temperature of the climate.huiskamer entity to the input temperature from the climate.master_therm_keuken entity. the value_template attribute for temperature is wrong but how do i make it so it uses the an input value rather than a constant float number?

plain magnetBOT
#

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

green scaffold
#

someone mentioned that a value_template only accepts floats, how can i use the input temperature from the master_therm_keuken to change the temp attribute of another thermostat not in config, i am desperate for a solution

silent vector
#

Anyone know how I would make this a conditional boolean true/false?

{{ states.light | selectattr('entity_id', 'in', area_entities(area)) |        selectattr('attributes.color_temp_kelvin', 'defined')  }}

That's not going to work how it's currently structured but the goal is to check if the attribute colo_temp_kelvin is defined

green scaffold
marble jackal
silent flicker
#

(I want to check if the last time the value changed was X seconds ago, so i need to be able to check the timestamp of when it last changed to be able to compare it against now())

white totem
#

For a heat pump that has four states (heat, cool, hot water and off), I have connected an energy meter (kWh, increasing).
How would you split the energy count over those four states? So, I want to know how much energy is used for hot water, and for heating etc.

thorny snow
# marble jackal Just to avoid confusion

I found the problem, the sensors in the group had one character different than the name of the sensors themselves. The state_attr listed them correctly according to the group definition but the entities it referenced were mistyped by one char. Thanks a lot and sorry for being dumb.

proud cradle
#

I have a simple template sensor called electricity_price and every time I restart HA I get an error saying "Entity id already exists - ignoring: sensor.electricity_price"

What is causing this?

    electricity_price:
      friendly_name: 'Electricity price incl. grid fee and tax'
      unit_of_measurement: 'SEK/kWh'
      device_class: energy
      availability_template: >
        {{ states('sensor.electricity_price_osthammar') }}
      value_template: >
        {{ (states('sensor.electricity_price_osthammar') | float + 0.755) }}
marble jackal
#

You seem to have two of these legacy template sensor formats, both starting with electricity_price
So besides this one above, you seem to have another one

sonic nimbus
#

How to check if all lights are turned off with map function but to exclude some lights? I need in combination fo the same thing for media_players entity

scarlet sapphire
#

Hello, when working with now() in a template, is there a value for both hour and time combined or do I need to create this on my own? I basically want to check if it's before or after 7:30

inner mesa
#

Compare against today_at('07:30')

scarlet sapphire
#

thank you sir

visual dawn
#

hi help me with binary sensor please

#

{{ state_attr ('switch.kitchen_button_left','state_left')
or state_attr ('switch.kitchen_button_left','state_right') = ON
}}

#

how write this ?

inner mesa
#

{{ 'ON' in [state_attr ('switch.kitchen_button_left','state_left'), state_attr ('switch.kitchen_button_left','state_right')] }}

marble jackal
#

{{ is_state_attr ('switch.kitchen_button_left','state_left', 'ON') or is_state_attr ('switch.kitchen_button_left','state_right', 'ON') }}

#

Or that

visual dawn
#

oh ) thanks

silent flicker
#

is there a way to get the timestamp of when a value changed? as in, i updated

input_number.servicenow_aaron_s_active_timeout

manually, and i want to check the last time it changed. the logbook has the time, but is there a way to retrieve that info?

Changed to 0.0 triggered by service input_number.set_value
7:29:45 AM - 5 minutes ago - Aaron
inner mesa
#

yes, with the last_changed property

#

so, states.input_number.servicenow_aaron_s_active_timeout.last_changed

obsidian lintel
#

{{ expand(states.sensor) | selectattr('device_class', 'eq', 'power' ) | list | count }}

#

I am trying get a value of all my energy sensors

#

How should I do it right?

marble jackal
#

First of all, you don't need expand here

#

And you as it is an attribute you are checking for, you need to use attributes.device_class

#

And you first need to check if it exists on each sensor, because there are probably sensors without a device_class

#
{{ states.sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'power') | list | count }}
obsidian lintel
#

Thanks!

ember saffron
#

Hi, Is it possible to round a value from a template sensor?

inner mesa
#

there are some good docs on templating in the channel topic

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

cedar bane
#

is it possible to access templates from inside Webpage Cards?

paper hazel
#

When used as a template trigger - Will this work as expected? {{ now() == today_at(states('input_datetime.birthday_message_time')) }}

inner mesa
paper hazel
#

Hmmm... Not sure if it will work in this partiular use case. I'm using the trigger.entity_id in the automation. I think I got a work around using this:```
{{ is_state('sensor.birthday_test_person', '0') and now().strftime("%H:%M:%S") == states('input_datetime.birthday_message_time') }}

paper hazel
#

Not sure if this is the correct forum, but I believe this will be done using templates, hence starting here. I want to add a condition to an automation which tests the state(contents) of a sensor, before proceeding. The sensor gets updated, by an automation when a fault is reported by the automation and harvests the reference number to update the sensor. The sensor have four possible states: unavailable/unknown, None, "Your reference for the incident at <<address>> is XX of XX/XX/20XX" OR "Your call Ref XXX of XX/XX/20XX for an incident at <<address>> has been allocated". I would like to not proceed with the automation is the sensor does not have the value of one of the last two possible states. Any pointers/suggestions would be much appreciated. Thank you!

#

I thought of using a template sensor, with this template. And if the value is > 0 the automation may continue. But sure there might be a prettier more elegant solution.```
{% set x = states('sensor.faultreport') %}
{{ x | regex_findall(find='<<address>>', ignorecase=True) |list |count}}

inner mesa
paper hazel
#

I have a singular input_datetime, to dermine when the message will be sent - e.g 09:00. This particular application uses the trigger ID to derive the name and contact details af the person in question, to the them a message for their birthday. I can probably change the naming conventions on the input_datetime to match the mappings in the automation and still work.

Will it be possible to trigger on a wildcard? E.g’’’
Trigger:
Platform: time
Entity_id: input_datetime.birthday_person_1
…
β€˜β€™β€™

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.

inner mesa
#

you don't have a wildcard there, but you can just add multiple triggers

regal temple
#

I would like to select all my Shelly devices of a specific type (like the following example: all Shelly 1PM units) This info is available as additional info of the Device, but not as an attribute. Is it nevertheless possible to use this to filter out all the Shellies of this type?

inner mesa
#

Look into device_attr

slow vine
#

I am trying to get a list of all media_player entities. I tried this but I'm not sure how to get the var device into a list not str

{% set device_list = states.media_player|selectattr('domain','eq','media_player')|map(attribute='entity_id')|list %}
{% set data = namespace(entities=[]) %}
  {% for device in device_list %}
  {%- set data.entities = data.entities + (device) -%}
  {% endfor %}
{{ data.entities | list }}

This is my error: TypeError: can only concatenate list (not "str") to list

slow vine
#

Now I need to filter out the "unavailable" devices.
{% set device_list = states.media_player|rejectattr('state','eq','unavailable')|map(attribute='entity_id')|list %}

paper hazel
marble jackal
formal ember
#

hey Fes and @mighty ledge - I am revisiting this one. I have this sensor set up, however it does not change. it only ever triggers the automation it relates to at 10pm, but of course then never changes the input_select to change the actual tariff, no idea where it is going wrong in the template though....

#

replied to the old one so you had a point of reference in time πŸ™‚

mighty ledge
#

it wont change the terrif

formal ember
#

why not?

mighty ledge
#

because templates only update themselves?

formal ember
formal ember
#

when its state changes to anything other than unavailable or unknown

marble jackal
#

does the template sensor change?

formal ember
mighty ledge
#

it'll update once per minute

#

on the minute

marble jackal
#

and is the entity_id sensor.tariff_price, because based on the conig it would be sensor.electricity_tariff

formal ember
marble jackal
#

that's not the right sensor

mighty ledge
#

and based on the name of your sensor, your entity_id in the automation should be sensor.electricity_tariff not sensor.tariff_price

#

oh i'm slow this morning

#

🀣

marble jackal
formal ember
#

this does not change either

marble jackal
#

that link doesn't work

formal ember
#

sorry

marble jackal
#

seems to be the same sensor, if there is a graph it has a numeric state

formal ember
#

omg

marble jackal
#

you can't plot peak, off-peak and shoulder in a graph

formal ember
#

ah

marble jackal
#

well, not in a line graph

formal ember
#

better

#

the only spike there is because i manually changed it in dev tools

mighty ledge
#

can you please use the states page instead

marble jackal
#

BTW your config of the template sensor is not the correct one, the one you linked to to start this conversation is the right one

formal ember
#

so, if I were to just change the entity in the automation trigger, it should work?

mighty ledge
#

developer tools -> states. Type tariff in the entity_id field

formal ember
marble jackal
#

you need sensor.tariff_price

#

that one actually returns offpeak

formal ember
#

in the automation?

formal ember
#

rest looked the same to me

mighty ledge
#

I don't see anything wrong after confirming that your entity_id was correct

#

the template sensor should update once per minute on the minute, and you should see it changing states

formal ember
#

any way to test it here and now, rather than waiting until 7am?

mighty ledge
#

remove the unit_of_measurement to see the text states not the graph

marble jackal
#

the offpeak was actually correct

formal ember
#

ahhh yep

marble jackal
#

this is the correct config, I also removed the unit_of_measurement as it makes no sense on this sensor

formal ember
#

the spacing of the template is to the left a bit, that ok?

marble jackal
#

it's indented 2 spaces compared to state: which is correct, yours was indented a bit too far to the right

formal ember
#

ahhh right

#

also, i gave it the name Electricity Tariff, why would it not appear as sensor.electricity_tariff ? Instead it is sensor.tariff_price

marble jackal
#

because it already had that name before you renamed it in the config, and as it has a unique_id the enity_id was already stored in the storage

formal ember
#

its messy... sigh

#

renamed it in the UI, the entity ID

#

so now its just sensor.electricity_tariff

#

now, how can I test this?

mighty ledge
#

you have to wait

formal ember
mighty ledge
#

if you got rid of the unit_of_measurement, you can now see the state changes in history

formal ember
#

yep, did that. thanks a lot

#

i don't know why i had it in there tbh

#

thanks legends, you guys are a wealth of knowledge

mighty ledge
#

I'm a bit hungover, so i'm a weth of knowledge

#

probably missing more than a couple of letters 🀣

marble jackal
# formal ember thanks legends, you guys are a wealth of knowledge

You might want to change the template to this though:

      {% set n = now() %}
      {% set summer = [ 11, 12, 1, 2, 3] %}
      {% set winter = [ 6, 7, 8 ] %}
      {% if today_at('07:00') < n < today_at('22:00') %}
        {% if (now().month in summer and today_at('14:00') < n < today_at('20:00'))
            or (now().month in winter and today_at('17:00') < n < today_at('22:00'))
        %}
          peak
        {% else %}
          shoulder
        {% endif %}
      {% else %}
        offpeak
      {% endif %}
#

It was complaining that I can't define a variable called now (well it didn't say that, took me some time to figure out why it errored)

mighty ledge
#

i always use t to avoid that

#

t

#

or time when i'm not pressed for time

marble jackal
#

Wonder if he will see this before going to bed, otherwise he will have to wait longer to see if it works

formal ember
#

i did

marble jackal
#

πŸ™‚

formal ember
#

i just changed it, now sensor.tariff_price is back. should I use a new UID?

marble jackal
#

if you change the unique_id it will use the name as entity_id

paper hazel
#

Not sure if this is the correct forum, but I believe this will be done using templates, hence starting here. I want to add a condition to an automation which tests the state(contents) of a sensor, before proceeding. The sensor gets updated, by an automation when a fault is reported by the automation and harvests the reference number to update the sensor. The sensor have four possible states: unavailable/unknown, None, "Your reference for the incident at <<address>> is XX of XX/XX/20XX" OR "Your call Ref XXX of XX/XX/20XX for an incident at <<address>> has been allocated". I would like to not proceed with the automation is the sensor does not have the value of one of the last two possible states. Any pointers/suggestions would be much appreciated. Thank you!

formal ember
#

nice

paper hazel
#

I thought of using a template sensor, with this template. And if the value is > 0 the automation may continue. But sure there might be a prettier more elegant solution.```
{% set x = states('sensor.faultreport') %}
{{ x | regex_findall(find='<<address>>', ignorecase=True) |list |count}}

formal ember
mighty ledge
#

football

#

american football

formal ember
#

ah. who won?

#

always thought you were a euro

mighty ledge
#

πŸ€·β€β™‚οΈ my team didn't play, was just there for the good times

formal ember
#

thats the spirit. is it playoffs yet?

mighty ledge
#

no they don't start til jan

jagged obsidian
#

far from it

formal ember
#

i thought the superbowl was in jan

mighty ledge
#

bills played on thursday

formal ember
#

or is that valentines day?

mighty ledge
#

superbowl is always the first sunday in feb IIRC

#

or maybe it's second

formal ember
#

ah right

#

mondays here

#

like, monday morning

#

ok, now i must go to bed πŸ˜„

slow vine
plain magnetBOT
#

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

marble jackal
#

@little forge yep, and I think the only thing you need to do is add .state in your template

little forge
#

ah thanks Fes, misread the docs. scene selector βœ…

hardy swallow
plain magnetBOT
#

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

marble jackal
mighty ledge
#

@hardy swallow is_state_attr will always return false when none, making that always pass

#

use what fes said

thorny snow
#

Just a quick one: rejectattr('state', 'gt', switchontime) . Switchontime is datetime format, and state is string, thus I cannot compare them. How to convert the string into datetime inline?

marble jackal
#

Otherwise use .strftime() to match it

thorny snow
#

Sure, thanks! Will that work inline?

hardy swallow
# mighty ledge use what fes said

A, maybe stupid, question: If i change the template inside configuration.yaml am i forced to restart HA to have the changes effect?

thorny snow
mighty ledge
hardy swallow
mighty ledge
#

same way it's always been

#

developer tools -> yaml page

hardy swallow
#

ah, ok, already did it, but it seems have no effect

marble jackal
mighty ledge
marble jackal
#

Did you save the file? I sometimes make that mistake

hardy swallow
thorny snow
# marble jackal Yes,

Sorry, I'm lost a bit, could you please help me with a oneliner on how to convert the state string into dateformat inline?

marble jackal
#

No, you need to convert the datetime to a string

marble jackal
thorny snow
marble jackal
#

.isoformat() converts a datetime object to a string in the ISO datetime format

thorny snow
#

All right, so I cannot compare objects, but strings in the same format?

hardy swallow
marble jackal
thorny snow
marble jackal
thorny snow
#

I got it, thanks a lot!!!!

hardy swallow
#
                    {% set recordings = state_attr('sensor.sky_q_schedule', 'skyq_recordings') %}
                    {% if recordings is sequence and recordings|length > 0 and recordings[0].skyq_recording_title is defined %}
                    **Recording Now:** {{ recordings[0].skyq_recording_title }}              
                    {{as_timestamp (recordings[0].skyq_recording_start) | timestamp_custom('**Started:** %H:%M') }}
                    {{as_timestamp (recordings[0].skyq_recording_end) | timestamp_custom('**Ends:** %H:%M') }}
                    {% else %}

                    **Actually Not Recording**
                    {% endif %}

                    **Next Recording:** {{state_attr ('sensor.sky_q_schedule', 'skyq_scheduled_title')}}
                    {{ as_timestamp(state_attr('sensor.sky_q_schedule', 'skyq_scheduled_start')) | timestamp_custom('Starts: %A %dth %H:%M') }}
                    {{ as_timestamp(state_attr('sensor.sky_q_schedule', 'skyq_scheduled_end')) | timestamp_custom('Ends: %A %dth %H:%M') }}
                    **Disk Capacity Remaining:** {{states ('sensor.sky_q_used_storage')}}Gb ( {{state_attr ('sensor.sky_q_used_storage', 'skyq_storage_percent')}}% )
```
#

and i get the following error:

ValueError: Template error: as_timestamp got invalid input 'None' when rendering template 
                    '{% set recordings = state_attr('sensor.sky_q_schedule', 'skyq_recordings') %}
                     {% if recordings is sequence and recordings|length > 0 and recordings[0].skyq_recording_title is defined %}
                    **Recording Now:** {{ recordings[0].skyq_recording_title }}              
                      {{as_timestamp (recordings[0].skyq_recording_start) | timestamp_custom('**Started:** %H:%M') }}
                      {{as_timestamp (recordings[0].skyq_recording_end) | timestamp_custom('**Ends:** %H:%M') }}
                    {% else %}

                    **Actually Not Recording**
                    {% endif %}

                    **Next Recording:** {{state_attr ('sensor.sky_q_schedule', 'skyq_scheduled_title')}}
                      {{ as_timestamp(state_attr('sensor.sky_q_schedule', 'skyq_scheduled_start')) | timestamp_custom('Starts: %A %dth %H:%M') }}
                      {{ as_timestamp(state_attr('sensor.sky_q_schedule', 'skyq_scheduled_end')) | timestamp_custom('Ends: %A %dth %H:%M') }}
                    **Disk Capacity Remaining:** {{states ('sensor.sky_q_used_storage')}}Gb ( {{state_attr ('sensor.sky_q_used_storage', 'skyq_storage_percent')}}% )'
but no default was specified
```
mighty ledge
hardy swallow
mighty ledge
hardy swallow
#

ok i must put the if statement in every state_attr?

mighty ledge
#

yep

hardy swallow
#

hmmm...... i'll try also if i am not so able with templates... 😦

mighty ledge
#

I have no idea what you're saying

#

did you copy those templates or did you create them?

#

if you created them, you should have no problem with this.

hardy swallow
#

Oh, i copied....

mighty ledge
#

well, just put an if statement around each one

#

{% if... %}
{% endif %}

hardy swallow
#

ok, thanks

buoyant pine
#

{{ 'happy' if petro == 'moved to HA Container' else 'sad' }}

mighty ledge
#

sad

buoyant pine
formal ember
#

Thanks a lot guys for persevering with me

paper hazel
#

Trying to wrap my head around it, if I would like to update an input_datetime.XXX, which has a date and time value, using input_datetime.set_datetime, but would like to increment the year with one. E.g should it run now, the result would be 2023-11-28 09:00:00. The example below would set todays date if I'm correct. Any help will be appreciated... ```

  • service: input_datetime.set_datetime
    target:
    entity_id: input_datetime.XXX
    data:
    date: "{{ now().strftime('%Y-%m-%d') }}"
inner mesa
#

Unfortunately, timedelta only takes days and weeks

#

better: {{ now().replace(year=now().year+1) }}

paper hazel
#

Hmmm... do I understand correctly, that I will then pass the year, month, and day individually to the data of the service call?

inner mesa
#

No

paper hazel
#

from my understanding:```

  • service: input_datetime.set_datetime
    target:
    entity_id: input_datetime.XXX
    data:
    date: "{{ now().year + 1 }} {{ now().month }} {{ now().day }}"
inner mesa
#

Set datetime

#

See my last post

paper hazel
#

Rendered it in the Dev Tools - For the date it works like a charm, but how do I prevent it from changing the time part of it or do I just have to specify it again?

#

ha - wait... date will only alter the date if I understand the docs correctly

#

Thank you! Much appreciated.... πŸ™

inner mesa
#

this keeps the time if just setting the date doesn't work:

{% set datetime = states('input_datetime.date_test')|as_datetime %}
{{ datetime.replace(year=datetime.year + 1) }}

->
2023-08-22 09:00:00

paper hazel
#

Thank you! Really appreciate your assistance...

paper hazel
#

I'm looking for a shortcut vs hours of typing. I have a bunch of sensors, which I can pull a list with a template. The naming convention is similiar to the new datetime objects. e.g Current: sensor.birthday_person_one and New: input_datetime.birthday_person_one. The current sensors have an attribute "date" of which the value I would like to set to the new input_datetime object. Now I'm sure a for loop should be able to do it, but its a bit beyond my reach... Can someone perhaps assist or point me towards an example I can learn/derive from?

#

I got the list of entities using:```
{{ states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list }}

inner mesa
#

how were you planning to set the attribute of a sensor?

#

where do the sensors come from?

paper hazel
#

The sensors were manually captured by me originally using the custom anniversary component. They have the correct dates. I thought if I could loop through them, extract the date attribute, and use the service call set_datetime to set the date to the the date time entity using replace (sensor --> input_datetime).

inner mesa
#

it's still not clear to me how you will be able to set an attribute of the sensors provided by that integration

#

sensors are read-only

paper hazel
#

I would like to read the attribute from the sensors, then use set_datetime to set the date on the datetime objects

#

The datetime objects are newly created, all with todays date

inner mesa
#

ok

paper hazel
#

The logic in my head runs something like this:```
For each sensor in birthday_Sensors
get date attribute from sensor
mangle entity_id from sensor.birthday_person_one to input_datetime.birthday_person_one
service call - set input_datetime using extracted date attribute.
end of loop

#

I hope it makes sense 😟

inner mesa
#

you can't do all that within a template

#

you can with a foreach construct in a script

paper hazel
#

I was thinking of doing it in a script, because the service dev tools doent support teplates.

#

Where I'm currently stuck, is how do I get form the list to an array I can loop through?

inner mesa
#

standard Jinja syntax: ['person_1', 'person_2']

paper hazel
#

Let me start fiddling there... thx!

paper hazel
#

Sorry for all the questions - Major learning curve here... This seems to create strings, so I'm unsure how to get the date attribute from there. {{ states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list }}

mighty ledge
#

you're mapping the entity_id at the end, map the state instead

paper hazel
#

Thx! Let me try that... Appreciate the pointer! πŸ™

inner mesa
#

or..the date attribute

#

But I think you're going about this the wrong way

paper hazel
#

I probably am - but I'm learning a lot 🀣

mighty ledge
#

I just read everything, what's the actual endgoal here

#

why you trying to increment the year on a datetime

inner mesa
#
  1. Make a list of substrings like person_1, person_2
  2. Build a for_each loop that iterates through that list
  3. One input_datetime.set_datetime service call in the loop with the entity constructed from 'input_datetime.' ~ repeat.item and the datetime: "{{ state_attr('sensor.' ~ repeat.item, 'date') }}"
mighty ledge
#

Yeah, that's what I would do, but why even have these input_datetimes... what's the point

#

you have the sensor already

paper hazel
#

the current sensors only have a date value, which means at midnight it becomes "active" for the day. Now not everyone will appreciate a happy birthday message at midnight, so I would like to fire it later in the day. I orignally foudna way of doing it with a template sensor, but that generated a lot of duplicate work. Rob then suggested date_time which makes a lot of sense as it has a date and time, and I can adjust it for different time zones which is awesome. So without manually recreating everything, I would like to transplant the data.

paper hazel
mighty ledge
#

just make an automation that fires at a specific time in the day that checks the current date and notifies whoever's day is up

#

no reason for datetimes

paper hazel
#

Petro - The end use case is to fire happy birthday messages on a predetermined time using a single automation using mappings with the number/email based ont he trigger.id

mighty ledge
#

what's the format of today?

#

er, the sensor

#

and what's the format of the sensor's name

paper hazel
#

the sensor does a count down - so it goes to '0' on the day

#

sensor name = sensor.birthday_name_surname

mighty ledge
#

right, but the actual name of the sensor

#

well, ok, i'll just work with that

#

so the sensors count down to zero?

#

and how are you notifying people?

paper hazel
#

yip - they count down

#

whatsapp custom integration

mighty ledge
#

right, but how do you know what notify to call?

#

@paper hazel basically, can you post an example notification that you're using to send the happy birthday message

#

I'm almost done with the automation

#

I just need that piece

paper hazel
mighty ledge
#

so you got the example notification?

paper hazel
#

Thank you!

#

Ignore the trigger - It was based on the template trigger I created

mighty ledge
#

@paper hazel

- alias: Notify Birthday
  trigger:
  - platform: time
    at: "10:00"
  variables:
    config:
      test_person: 2712345678@s.whatsapp.net
    people: >
      {{ states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'birthday_', '') | list }}
    items: >
      {% set ns = namespace(ret = []) %}
      {% for sensor in sensors if config.get(sensor, False) %}
        {% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %}
      {% endfor %}
      {{ ns.ret }}
  condition:
  - platform: template
    value_template: "{{ items | length > 0 }}"
  action:
  - repeat:
      for_each: "{{ items }}"
      sequence:
      - service: whatsapp.send_message
        data:
          clientId: default
          to: "{{ repeat.item.whatsapp }}"
          body:
            text: "Happy birthday {{ repeat.item.name }}"
#

add your people to config

#

and you're done

#

change the time you want to notify at too

paper hazel
#

Wow!!!! mindblown

#

I'm trying to learn and wrap my head around this - Could you perhaps explain the voodoo under items?

mighty ledge
#

states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') -> filters all states down to entities starting with birthday with a zero state

#

| map(attribute='object_id') | map('replace', 'birthday_', '') | list -> maps the filtered list to just object_id's and replaces birthday_ with nothing

#

{% set ns = namespace(ret = []) %} -> creates an empty list

paper hazel
mighty ledge
#

{% for sensor in sensors if config.get(sensor, False) %} -> iterates sensors and tries to get the whatsapp id out of the configuration. If that fails, it doesn't use that iteration

mighty ledge
#

{% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %} adds 1 dictionary to the list with 2 attributes, name and whatsapp (the id).

#
      {% endfor %}
      {{ ns.ret }}
``` Ends the foor loop and outputs the resulting list
paper hazel
#

Is this just years of experience or pure genius - absolutely mind blown...

#

I have been butchering at this for about two evenings flopping around between various methods

mighty ledge
#

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

paper hazel
#

Thank you so much for this, and for the time to explain it to me. It is really really appreciated and valued. Both you and Rob's asssitance have helped me tremendously with this and previous endeavours.

mighty ledge
#

I just think β€œwhen I add a person in the future, how much work will I want to put into it”

#

then I design around that

#

That being β€œfuture petro doesn’t want to do shit”

paper hazel
#

Same here - but the lack of design skill sometimes makes designing the task longer than doing it manually 🀣

#

Anything that need to happen more than once, must be automated...

#

@inner mesa & @mighty ledge Just want to thank you again for everything! This forum and the people here are just awesome! πŸ™

paper hazel
#

I added the automation, but gets an error on this condition:```

  • platform: template
    value_template: "{{ items | length > 0 }}"
inner mesa
#

an error

#

too many whales?

#

not enough?

paper hazel
#
Invalid config for [automation]: Unexpected value for condition: 'None'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['condition'][2]. Got None. (See ?, line ?).
#

Had to re-enable the condition to lure out the correct whale... πŸ™‚

inner mesa
#

I can't see how that error is related to that condition

paper hazel
#

I was thinking of trying ```
{{ items | length | int > 0 }}

inner mesa
#

no

paper hazel
#

If I comment out the condition, it passes the check and on automation reload no errors and shows up

inner mesa
#

I guess "items" could be "None", rather than a list

paper hazel
#

Perhaps then ```
{{ items | count > 0 }}

inner mesa
#

no, you're just hacking around

#

I don't see where "items" is being set

paper hazel
#
items: >
      {% set ns = namespace(ret = []) %}
      {% for sensor in sensors if config.get(sensor, False) %}
        {% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %}
      {% endfor %}
      {{ ns.ret }}
inner mesa
#

ok, I see

paper hazel
#

added till first line after endfor

inner mesa
#

so somehow that's "None"

paper hazel
#

Hmmm... In Dev Tools I get UndefinedError: 'sensors' is undefined

inner mesa
#

right, where is "sensors" defined?

paper hazel
#

I looked for it, but could not find it, and not sure how or where to plug it in...

#

going to try this 🀞 ```
{% set ns = namespace(ret = []) %}
{% set sensors = states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list %}
{% for sensor in sensors if config.get(sensor, False) %}
{% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %}
{% endfor %}
{{ ns.ret }}

inner mesa
#

he probably meant "people"

paper hazel
#

Hm... Think so, so then that will read for person in people?

#

My workaround did not work....

#

Will ask him tomorrow...

#

Its now 3:00am and I have to be up by 06:30am... time for some sleep...

#

Thx again! Have a good one!

inner mesa
#

just replace "sensors" with "people" in the for loop. nothing else needs to change

paper hazel
#

let me quickly try...

inner mesa
#

the variable "sensor" doesn't matter

paper hazel
#

It now reads like this, but the error still shows up {% for people in sensors if config.get(sensor, False) %}

inner mesa
#

you didn't do what i said

#

just replace "sensors" with "people" in the for loop. nothing else needs to change

#

you replaced "sensor" with "people", when I said that didn't matter

paper hazel
#

πŸ€¦β€β™‚οΈ Let me go again... Sorry

inner mesa
#

consider what you're doing

#

you couldn't find a definition for "sensors", so that's what you're fixing

paper hazel
#

Error is still popping up```
{% for sensor in people if config.get(sensor, False) %}

inner mesa
#

in my completely fabricated example that works in my setup, it works fine

#
{% set config = {"captured_today_family_room": "2712345678@s.whatsapp.net", "captured_today_living_room":"foo"} %}
{% set people = states.sensor | selectattr('object_id', 'search', '^aarlo_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'aarlo_', '') | list %}
{% set ns = namespace(ret = []) %}
      {% for sensor in people if config.get(sensor, False) %}
        {% set ns.ret = ns.ret + [ {'name': sensor | replace('_', ' ') | title, 'whatsapp': config[sensor] } ] %}
      {% endfor %}
      {{ ns.ret }}
#

->

[
  {
    "name": "Captured Today Family Room",
    "whatsapp": "2712345678@s.whatsapp.net"
  },
  {
    "name": "Captured Today Living Room",
    "whatsapp": "foo"
  }
]
#

so I conclude that there's something about your entities that isn't right

paper hazel
#

In this part - should the number be in brackets? variables: config: test_person: 2712345678@s.whatsapp.net

inner mesa
#

no, but it needs to be real

#

if you just have that, then you didn't follow petro's instructions

paper hazel
#

They are, and correspond with the sensors names

inner mesa
#

all I did was change the strings to search for to correspond to entities that I have that have a state of "0" and changes "sensors" to "people"

#

and changed the config to match those entities

#

boom

#

so you'll need to debug

#

start by printing the value of each variable

paper hazel
#

I will make them less, and see what it does then tomorrow. testting each variable

#

going to be something stupid on my side - pretty sure of it...

#

Thx!

#

BEfore I crawl off - When I change the array to same format as your for config, it works. so it must be something in there. Will scratch tomorrow and try and figure it out

#

Thx!

inner mesa
#

np. I provided the set of changes that I made above

icy marsh
#

Is there any way to combine multiple SNMP sensors into one?

jade kite
#

the state is updated realtime,but the attr is not

#

is there somewrong?

jade kite
icy marsh
#

Yes but for my use it will require creating multiple sensors, and then referencing it by another sensor. I want to avoid that and only define one sensor that pulls in from multiple SNMP data sources

thorny snow
#

I'd like to create an automation where in the action part I call a service and specify a set of entity_ids generated by a template. I could get so far that I have the list of entity_ids generated by a loop, but it does not seem to work. Do I need to pass on the set of entity_ids as a list?

#

{% for i in switchonentities %} input_number.setpoint_room_{{i.entity_id.split('_')[-4] }} {% endfor %}

#

target: entity_id: > {% set switchontime = now() + timedelta(minutes=(states.input_number.homerseklet_beallitas_kezdete.state | int + 4200)) %} {% set switchonentities = expand('group.kovetkezo_erkezesek') | rejectattr('state', 'eq', 'unknown') | rejectattr('state', 'gt', switchontime.isoformat()) %} {% for i in switchonentities %} input_number.setpoint_room_{{i.entity_id.split('_')[-4]}} {% endfor %}

#

This is how the whole target specification looks like.

inner mesa
#

Either a list or a comma separated string

#

List is usually easier

thorny snow
#

Is the comma missing from the end of the entity_ids? How do I delete the comma from the end of the llist?

inner mesa
#

That's...a lot of code to read through

thorny snow
#

This is the line to generate the list of entity_ids: input_number.setpoint_room_{{i.entity_id.split('_')[-4]}}

inner mesa
#

No comma there

thorny snow
#

If I put a comma to the end in the loop, there will be one at the end:

#

{% for i in switchonentities %} input_number.setpoint_room_{{i.entity_id.split('_')[-4] }}, {% endfor %}

inner mesa
#

Then don't add one for loop.last

thorny snow
#

Ok, I'm gonna try it!

inner mesa
#

I'm pretty sure it could be done by constructing a list, but I can't do it on my phone

thorny snow
#

πŸ˜€

inner mesa
#

Foo{{',' if not loop.last}}

#

Or whatever it is

thorny snow
#

Thanks a million, let me try it...

#

It works, you saved my day, thanks again!

final ibex
#

Good morning. I've a simple question, I've my climate valve that have only climate.room entity but don't a sensor entity. is it possible to create a sensor using entity history data?