#templates-archived

1 messages Β· Page 59 of 1

dense swan
#

@mighty ledge does that look good for automation defined variables section?

mighty ledge
#

no

#

only because you'd run itno an unforseen issue

dense swan
#

Oh.

mighty ledge
#
variables:
  user: >
    {{ trigger.payload_json['action_user']}}
  used_pin: >
    {{ trigger.payload_json[user | string].pin_code }}
  pin_codes_to_name:
  - name: A
    code: '1234'
  - name: B
    code: '5678'
#

that would

#

basically the variable resolver would turn your user into an integer

dense swan
#

ahh

mighty ledge
#

so you must force it as a string

#

where you use it

#

you might want to build in some safety as well

#
    {{ trigger.payload_json.get(user | string, {}).get('pin_code', 'No Code') }}
#

makes it so an invalid code won't error

dense swan
#

Yup, I was going to code that in since pin_code also has status in the field.

median citrus
#

Hi all, I'm having some issues adapting a template sensor that was using the forecast attribute of a weather integration to create a string which I was visualizing on a epaper display.

Somehow with 2023.8 this got broken presumably due to the move to the forecast service.

How can i put the output of a service call into a template?

#

I was using ```
{%- for i in [ 1, 2, 3, 4, 5, 6] -%}
{{ dow[(now().weekday() + i) % 7] }};
{{- weather[state_attr('weather.dwd_weather_city', 'forecast')[i]['temperature']] -}};-}}%
{%- if not loop.last %};{% endif %}
{%- endfor %}

to create a string that was holing the temperature seperated by a ;
mighty ledge
#

then use taht in your template sensor, or go straight to the data you care about in a template sensor.

median citrus
#

thanks for the tip, will check it out!

plain magnetBOT
#

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

opaque sentinel
#

Maybe I need to increment another sensor with the value at the end of every hour?

mighty ledge
#

without the trends of the other sensors over that period, i"m not sure how anyone can help

opaque sentinel
quaint grotto
#

i want to keep track of the energy that goes to hot water vs heating, using the amount of time the boiler fires for

so if the boiler fires whilst the heating is on - then thats easy, it's all heating
and similarly if it fires for hot water, then thats easy too - all hot water

but if the system is calling for hot water and both, then i want to count half of the energy used (ie: firing time) to hot water and half to heating.

does that make sense?

(i know the boiler is currently set to 17kw, so i can convert the firing time to kwh using that)

mighty ledge
#

so it looks like you found the source

mighty ledge
#

if you have 2 separate binary sensors, what else do you need?

opaque sentinel
mighty ledge
#

just think about subtraction

#

you have a and b.

#

if a is static (but above )

#

as B increases, it'll be less negative

#

exactly what's happening

#

your multiplier is doing nothing other than changing the scale

#

so you can remove it in your thought process

#

your current math is (a * x - b * x) which is the same as (a - b) * x

#

your trend is coming from the a-b, not the x

opaque sentinel
#

Yes this makes sense. But where I'm not following is:

At hour 1, (a - b) * x = -2
At hour 2, (a-b) * x = -1

Then I would expect the downwards curve to decrease less, but still decrease.

But the more I think about this, I think that what I have created is a "trend per hour" over a week sensor, not a summary of the week, if that makes sense.

Would the solution to this be to add each hours trend to another sensor?

mighty ledge
#

you want the weekly value?

opaque sentinel
#

Yes

mighty ledge
#

just use utility meter

opaque sentinel
#

With my template as the source?

mighty ledge
#

no, with your sources as the source

plain magnetBOT
#

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

opaque sentinel
#

But it's the difference between source a and b * my usage that I'm after. Sorry if I'm being stupid but I'm still not there

mighty ledge
#

then just subtract a from b in a template sensor and then use that in utility meter

#

@quaint grotto make a template sensor that represents both being on at the same time. THen use history stats on that.

#

then make another template sensor for each value, taking 50% of the last template sensor on each

quaint grotto
opaque sentinel
mighty ledge
#

use utility meter in yaml if you want a variable tarrif

#

IIRC it supports a sensor for the tarrif value

opaque sentinel
#

I'll give it a go. Much appreciate your time and patience πŸ™‚

raven garden
#

Hi everyone. I'm trying to create a template for something specific. My problem is that when I enter the template in the "Templates" section of the yaml I'm getting a "False" value (which I expect), but when I add it to my configuration.yaml as a binary_sensor, I'm getting "on" instead of "off", and I don't understand why.

inner mesa
#

what...template?

#

easier to talk in specifics, rather than vague generalites

raven garden
#

it's based on values in the Pronote HACS plugin, so you can't really copy it, but I can show you no problem πŸ™‚

#
          {% set items = state_attr('sensor.pronote_perrin_antoine_timetable_next_day','lessons') %}
          {% set next_date = as_timestamp(items[0].start_at) | int | timestamp_custom('%Y-%m-%d', true) %}
          {% set devoirs = state_attr('sensor.pronote_perrin_antoine_homework','homework') %}
          {% set devoirs_faits=namespace(value='on') %}
          {% for devoir in devoirs %}
              {% if (devoir.date|string == next_date|string) and (not devoir.done) %}
                 {% set devoirs_faits.value='off' %}
                 {% break %}
              {% endif %}
          {% endfor %}
          {{ devoirs_faits.value | bool}}
mighty ledge
#

just show us the template

raven garden
#

this gives me "false" in the developer tools

inner mesa
#

yep

raven garden
#

and this is how I tried to implement it

plain magnetBOT
raven garden
#

I tried using true/false, | bool or straight value, either way when I go in States and search of that sensor, I get "on" as a status

#

when I should be getting off

#

and I restarted homeassistant to be sure (and the last update shows me it actually updates)

#

I understand I'm probably doint it wrong

#

but I can't figure out what πŸ™‚

mighty ledge
#

and you aren't getting errors in y our logs?

raven garden
#

not that I can see no

#

I don't get it it is now off. I spent my whole evening troubleshooting this yesterday

#

and it now seems to be working

#

I'm wondering if I was hitting a bug maybe because I was looking at the value at homeassistant restart

#

and maybe the recalculated value after the first time pattern hits actually gets the value right

#

because some other sensor might not be up when HA starts

#

and that leads to a "on" state

#

well... I guess my request is now to be discarded, apologies πŸ˜„

dense swan
#

@mighty ledge any reason why this isn't working:

plain magnetBOT
dense swan
#

Seeing the following errors in logs:

#
2023-11-14 18:07:23.847 ERROR (MainThread) [homeassistant.components.automation.lock_bbq_backdoor_notifications] Lock: BBQ Backdoor Notifications: Choose at step 1: choice 3: Error executing script. Error rendering template for variables at pos 1: UndefinedError: dict object has no element 3
2023-11-14 18:07:23.849 ERROR (MainThread) [homeassistant.components.automation.lock_bbq_backdoor_notifications] Lock: BBQ Backdoor Notifications: Error executing script. Error rendering template for choose at pos 1: UndefinedError: dict object has no element 3
2023-11-14 18:07:23.849 ERROR (MainThread) [homeassistant.components.automation.lock_bbq_backdoor_notifications] Error while executing automation automation.lock_bbq_backdoor_notifications: UndefinedError: dict object has no element 3
#

I had user | string there before.

lucid thicket
rocky crypt
#

Hello. Is there a way in template to see if a notify service exists?
I tried:
{% if notify.myevent %}
true
{% endif %}
But this isn't working. I get an error saying 'notify' is undefined

mighty ledge
#

no

rocky crypt
#

Ugh. So do I have another option?
My Problem: I have notify for email to send out. It's a local mail server. But if I am working on my mail server and/or another issue happens where the mail server is down. then the notify.smpt fails completely disabling all my notifications...

#

A simple smtp.reload fixes the problem.. But I don't know when to run it unless the notify.myevent is missing...

opaque sentinel
#

Sounds like you could just ping the smtp server?

#

And use that as a condition

rocky crypt
#

Ok. That may work. I'm shocked this isn't more of a common issue. If internet goes down or anything, this would cause this issue for others as well...

dense swan
plucky depot
#

I am using this template sensor and it works as I want, but I noticed that somtimes I get a 0 value that messes up the sensor uuntil I get a new value. Can anyone tell me how to filter 0 values ?

- trigger:
      - platform: state
        entity_id: sensor.import_power
        not_to:
          - unknown
          - unavailable
    sensor:
      - name: Import Power filtered
        state: '{{ trigger.to_state.state }}'
        device_class: power
        unit_of_measurement: 'W'
#

Can I use somethin like : state: '{{ trigger.to_state.state if trigger.to_state.state > 0}}' ?

inner mesa
#

Then it will have no state if it's zero or less than zero. That's not good.

#

You can use this.state for that to simply repeat the last state, if that's what you want

plain magnetBOT
mighty ledge
#

@dense swan what issues are you having? that script looks wrong

dense swan
#

I fixed it, was easy to setup a spare MQTT topic and do that so I don't have to keep playing with the lock πŸ™‚

mighty ledge
#

well, your conditions aren't correct

#
  - condition: template
    value_template: "{{ trigger.payload_json.action is defined and trigger.payload_json.action }}"
dense swan
#

It was a nested issue in the payload. I fixed it.

mighty ledge
#

not only that, you can manage your variables without doing a choose

#

well, your condition is still wrong

#

null will never be a string

#

to check for null in jinja it's is none

#

but you don't necessarily need that

#

you just need to make sure action is defined (i.e. it exists in the dictionary) and that it has a value

#

which is what that condition does above

dense swan
#

Yea, it is working now with some minor tweaks.

mighty ledge
#

Ok, just keep in mind what I just said, if you keep those conditions, you aren't actuallly checking for null/none properly

#

so that case will error

#

personally, I'd do it like this

alias: Z2M Lock Notifications
description: ""
trigger:
  - platform: mqtt
    topic: richie/BBQ Backdoor
variables:
  config:
  - name: A
    code: '4755'
  - name: B
    code: '5678'
  action: >
    {{ trigger.payload_json.get('action') }}
  user: >
    {% if action and trigger.payload_json.action_source_name == 'keypad' %}
      {{ trigger.payload_json.action_user }}
    {% endif %}
  pin: >
    {% if user %}
      {{ trigger.payload_json.users.get(user | string, {}).get('pin_code') }}
    {% endif %}
  found_user: >
    {{ config | selectattr('code', 'eq', pin) | map(attribute='name') | first | default }}
condition:
- condition: template
  value_template: "{{ found_user is not none }}"
action:
- service: notify.mobile_app_portalgun
  data:
    title: BBQ Backdoor
    message: >-
      Door unlocked by {{ found_user }} via keypad
#

That will be error safe and you can debug it when it triggers and doesn't fire because of the condition.

#

just go to the changed variables tab with the trigger selected to see all the variables on the root automation level.

dense swan
#

Nice, I see the logic there.

mighty ledge
#

fixed a few typos FYI

dense swan
#

@mighty ledge I think there is an issue with pin, the pin is nested under the users{} section so like { users: { 0: { "pin_code": "code" }, 1: { "pin_code": "code" }, } }

mighty ledge
#

yep, fixed

dense swan
#

Interesting if I do if user for pin it won't trigger. I had to remove the if line. But user is set...

spice raptor
#

I want to reduce the volume of my speaker if it is set to to loud once it finished playing. Im having trouble with my template to set the volume. Does anybody have an idea how to check if the volume of the trigger is above 50.

data: >
  {% set volume = state_attr(trigger.entity_id, "volume") | float * 100%} {% if
  volume > 50 %}
    0.1
  {% else %}
    {{volume}}
  {% endif %}
target:
  entity_id: |
    {{ trigger.entity_id }}
dense swan
#

I bet I have to do if user isn't blank since 0 = being considered false?

mighty ledge
dense swan
#

That was it...

#
  pin: |
    {% if user != '' %}
      {{ trigger.payload_json.users.get(user | string, {}).get('pin_code') }}
    {% endif %}
#

If i use "if user" alone the first pin slot, being 0, is considered false so it doesn't populate it.

#

when I tried with any other pin code slot than 0 it worked.

#

so another "gotcha"

mighty ledge
#

i'm not sure it's a gotcha, I'm trying to see if what you're saying the data is, is actually what the data is

#

what's odd to me abotu your data is that you have key's that are string integers

#

I based my code off the assumption that that is true

#

so if you post the traces variables I can confirm that

dense swan
#

Key slots are string integers or the way z2m reports it.

mighty ledge
#

or rework it

dense swan
#

I got it working with all your logic and checks, just that one if statement had to be adjusted.

#

I am trying to break it down with various scenarios via mqtt pubs

mighty ledge
#

πŸ‘

plain magnetBOT
#

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

opaque sentinel
#

I've also noticed that I havent added device_class: monetary, should this be needed?

sturdy fossil
cerulean karma
#

Is there a way to not update a template sensor after it was triggered by time_pattern?

#

without getting a unavailable error

marble jackal
#

refer to this.state on that trigger

cerulean karma
#

yes, but this updates the last_updated doen't it?

marble jackal
#

only if attributes change

cerulean karma
#

ok great

#

thanks

marble jackal
#

but why would you want this?

acoustic arch
#

i have this template from somewhere but it shows the wrong time. I need as_local which in my case is +1hour

Its the pickup_start and pickup_end which needs that. tried but failed...

'secondary_info': state.attributes.pickup_start[8:10] + "-" + state.attributes.pickup_start[5:7] + ' tussen '+ state.attributes.pickup_start[11:16] + ' en ' + state.attributes.pickup_end[11:16] + ' € '+ state.attributes.item_price[:-3],

cerulean karma
#

TheFes: I am unable to explain this and it may be nonsense again...but I am still trying to create my Gas kWh to kW Sensor πŸ™‚

#

I will come back with further questions...sure.

marble jackal
acoustic arch
#

I'll respond in an hour or so

acoustic arch
#

so i need UTC --> as_local (CET)

marble jackal
#

I also use TGTG

#

well, I have the integration, last time I picked up a box was ages ago

#

@acoustic arch I'm not sure if that value is a datetime, or a datetime string.
can you try this in devtools > templates {{ state_attr('sensor.your_box', 'pickup_start') }} | as_datetime

acoustic arch
#

returns
2023-11-16 16:00:00+00:00

#

without as_datetime
2023-11-16T16:00:00Z

#

{{ state_attr('sensor.tgtg_backwerk_amersfoort_verrassingspakket', 'pickup_start') | as_datetime | as_local}} this works as well and it translates it to local which is +1
But dont know the syntax for my original problem.

#

state.attributes.pickup_start[11:16] does not do local at the moment

mighty ledge
#

or convert it back into an iso timestamp

#
{{ (state_attr('sensor.tgtg_backwerk_amersfoort_verrassingspakket', 'pickup_start')  | as_datetime | as_local).isoformat()[11:16] }}
#

or

#
{{ (state_attr('sensor.tgtg_backwerk_amersfoort_verrassingspakket', 'pickup_start')  | as_datetime | as_local).strfttime("%H:%M") }}
forest ferry
#

trying to add the state of a counter (number/integer) to a template.
tried these 2 options unsuccessfully; can you help pinpoint the issue(s) or suggest a better approach? Thank you πŸ™

- image:
    url: >-
       {% set N = states('counter.news_rss_counter') %}
       {{ state_attr('sensor.radio_canada_rss', 'entries')[N].image }}
    name: "test"
- image:
    url: "{{ state_attr('sensor.radio_canada_rss', 'entries')[{{ states('counter.news_rss_counter') }}].image }}"
    name: "test2"    
mighty ledge
#

the first one is the correct one

#

w/o seeing what data is in entries we can't help any further.

obtuse zephyr
#

Presumably you want to throw a | int filter on your N assignment if you're attempting to index it as an array. If it's a key, then more information is needed

forest ferry
#

more info :
in templates, I can extract the url value with

"{{ state_attr('sensor.radio_canada_rss', 'entries')[0].image }}"
#

which returns:

"https://images.radio-canada.ca/q_auto,w_635,h_357/v1/ici-regions/videojournal/16x9/vjcb-inflation-canada-ralentissement.JPG"
obtuse zephyr
#

Yeah, |int filter then

marble jackal
forest ferry
#

incrementing [0] will provide other urls from "entries":

forest ferry
#

can now finish building a better RSS newsfeed custom card with images

marble jackal
#

@mighty ledge just a quick check, if I use an entity_id in a macro, will it render on changes of the entity?
example

{%- from 'cheapest_energy_hours.jinja' import cheapest_energy_hours -%}
{{ cheapest_energy_hours('sensor.nordpool_kwh_nl_eur_3_10_021') }}
#

devtools > templates states it does

mighty ledge
#

Yes, I would assume it does

#

based on how things are registered for templates

#

as long as you use a function/filter/test in your macro that registers the entity_id, then it'll update w/ that.

inner mesa
#

That's not a jinja template

forest ferry
#

I believe my previous question above is somehow template related or where would you suggest I post it? thx!

inner mesa
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

forest ferry
#

Done. Thanks!

neat crown
#

My googlefu is failing me and this is probably stupid simple but how is a template written to grab this data in the forecast. (what is predicted to be not what the current is). So the condition for example.```supported_features: 3
temperature: 13
temperature_unit: Β°C
humidity: 43
pressure: 1019
pressure_unit: hPa
wind_bearing: 158
wind_speed: 12
wind_speed_unit: km/h
visibility_unit: km
precipitation_unit: mm
forecast:

  • datetime: '2023-11-16T14:19:27.096906-05:00'
    condition: sunny
    precipitation_probability: 0
    temperature: 11
    templow: 9```
mighty ledge
#

it's a bit complicated

neat crown
#

Was hoping to gather what the forecast will be for the day. Odd that its not just a regular attribute

maiden raven
#

Hi
i am not sure how to tackle this problem:
i have an automation that makes a service call with a large payload.
I would like this service call to target different entities based on a condition. is it possible to do this without duplicating the service call?
can i build somehow a list of entities in the 'variables' section of the automation and pass the list to the service call?

inner mesa
#

You can use a template right in the target: section

maiden raven
#

can I put ifs in the target somehow?

#

if am thinking about something like this:
action:

  • service: some.service
    payload: <long payload here>
    target:
    entity_id: >
    {% if variable = 3 %} light.somelight {% endif %}
    {% if variable = 4 %} light.otherlight {% endif %}
#

(sorry i don't know how to post code snippets)

inner mesa
#

you can use a properly formed template, yes

#

and

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
#

that's not proper Jinja, though

maiden raven
#

what i want to achieve is: dependent on some variable (or some entity state) i want to include or exclude entities in the target section

inner mesa
#
service: some.service
data:
  payload: <long payload here>
target:
  entity_id: >-
    {% if variable == 3 %}light.somelight
    {% elif variable == 4 %}light.otherlight
    {% endif %}
#

or if it's just two:

  entity_id: "{{ 'light.somelight' if variable == 3 else 'light.otherlight' }}"
maiden raven
#

yeah, but sometimes i want somelight, sometimes otherlight, sometimes both πŸ™‚
i mean sure i can write down all permutations but is there another way of doing it? i was thinking about building a list of entities but i could not figure out the syntax for it

inner mesa
#

how is that list going to help you?

#

you can build that list right there, if you want

maiden raven
#

if i could do something like this:

{% set entites = [] %}
{% if variable = 3 %} {% set entities = entities + ['light.somelight'] %} {% endif %} 
{% if othervariable = 3 %} {% set entities = entities + ['light.otherlight'] %} {% endif %}

then i could dynamically build up the list of entities based on various conditions

inner mesa
#

I was just writing that πŸ™‚

#

so, yes

#

you keep using = when you want ==, though

maiden raven
#

yeah, you are right. i guess it's late πŸ™‚

neat crown
mighty ledge
#

@neat crown ^

rare sage
#

Hi All, I am trying figure out how to have a conditional card that uses the this template to view the card when true "{{ as_timestamp(now())-as_timestamp(states.binary_sensor.zone_slidingdoor_open.last_updated)|int <=60 }}"

floral shuttle
#

does a custom_template resource already exist for the translation of templates like this: {%- macro datum(datetime) -%} {%- set nu = as_timestamp(datetime) %} {%- set months = ['Januari','Februari','Maart','April','Mei','Juni','Juli', 'Augustus','September','Oktober','November','December'] -%} {%- set wdays = ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag', 'Vrijdag','Zaterdag'] -%} {%- set wday = nu|timestamp_custom('%w',default=none)|int(default=0) -%} {%- set month = nu|timestamp_custom('%m',default=none)|int(default=0) -%} {%- set datum = nu|timestamp_custom(wdays[wday] ~ ' %-d ' ~ months[month-1]) -%} {{- datum -}} {%- endmacro -%} ? I checked easy_time and relative_time_plus

#

used in my DST template like {% from 'tijd.jinja' import datum %} {{datum([ns.spring,ns.fall]|min)}} it blurts the date in Dutch Zondag 31 Maart

marble jackal
#

relative time plus doesn't do date translations, also don't think easy time does it.

#

BTW, weekdays and months are not capitalized in Dutch

floral shuttle
#

thx, corrected...

#

how could I add a flag to add the year optionally, and maybe even an hour? I have use cases to add '%Y at %-H am' and hoping to reuse that macro for those too

marble jackal
#
{%- macro datum(datetime, add_year=false) -%}
  {%- set nu = as_timestamp(datetime) %}
  {%- set months = ['Januari','Februari','Maart','April','Mei','Juni','Juli',
                    'Augustus','September','Oktober','November','December'] -%}
  {%- set wdays = ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag',
                  'Vrijdag','Zaterdag'] -%}
  {%- set wday = nu|timestamp_custom('%w',default=none)|int(default=0) -%}
  {%- set month = nu|timestamp_custom('%m',default=none)|int(default=0) -%}
  {%- set datum = nu|timestamp_custom(wdays[wday]  ~ ' %-d ' ~ months[month-1]) -%}
  {%- set datum = datum ~ ' ' ~ datetime.year if add_year else datum -%}
  {{- datum -}}
{%- endmacro -%}
#
{% from 'tijd.jinja' import datum %}
{{datum([ns.spring,ns.fall]|min, add_year=true)}}
floral shuttle
#

nice! dank je wel. I added a simple hour phrase for now too: {%- macro datum(datetime, add_year=false, add_hour = false) -%} {%- set nu = as_timestamp(datetime) %} {%- set months = ['januari','februari','maart','april','mei','juni','juli', 'augustus','september','oktober','november','december'] -%} {%- set wdays = ['zondag','maandag','dinsdag','woensdag','donderdag', 'vrijdag','zaterdag'] -%} {%- set wday = nu|timestamp_custom('%w',default=none)|int(default=0) -%} {%- set month = nu|timestamp_custom('%m',default=none)|int(default=0) -%} {%- set datum = nu|timestamp_custom(wdays[wday] ~ ' %-d ' ~ months[month-1]) -%} {%- set datum = datum ~ ' ' ~ datetime.year if add_year else datum -%} {%- set datum = datum ~ ', om ' ~ datetime.hour ~ ' uur' if add_hour else datum -%} {{- datum -}} {%- endmacro -%} so ```{% from 'tijd.jinja' import datum %}
{{datum([ns.spring,ns.fall]|min,add_year=true, add_hour=true)}}

#

might be a bit compicated to start translating this like you all did in your custom repo's but at least there's a beginning

#

addd to the dst template```
{% from 'tijd.jinja' import datum %}
{"spring": "{{ns.spring.isoformat()}}",
"fall": "{{ns.fall.isoformat()}}",
"event": "{{next.isoformat()}}",
"dag": "{{datum([ns.spring,ns.fall]|min,add_year=true, add_hour=true)}}",
"days_to_event":{{(next-today).days}},
"result": "{{result}}",
"motion":"{{motion}}"}

mighty ledge
#

easy time has translations for month day year

#

unless I'm missing something

#
{% from 'easy_time.jinja' import month %}
{{ month(now()) }}
#
{% from 'easy_time.jinja' import month, weekday %}
{{ month(now()), weekday(now()) }}
#
{% from 'easy_time.jinja' import month, weekday, count_the_days %}
{{ month(now()), weekday(now()), count_the_days(now() + timedelta(seconds=60**4)).strip() }}
#

@floral shuttle ^

#

it also gives you next daylight savings time

#

putting it all together...

{% from 'easy_time.jinja' import month, weekday, count_the_days, next_dst %}
{% set dst = next_dst() | as_datetime %}
{{ weekday(dst) }} {{ dst.day }} {{ month(dst) }} {{ dst.year }}, om {{ dst.hour }} uur.
#

i gotta fix count_the_days, it has a stupid \n in it

#

that's why the strip() is needed for now

#

er, sorry gotta remove count the days, im an idiot

marble jackal
#

Ah, I should have actually checked the repo, didn't remember providing translations for the months, but apparently I did

mighty ledge
#

Lol you did πŸ™‚

#

if you didn't someone else did

#

anyways, easy_time does everything you want except get the DST that is beyond the next. Which, no matter what will never be accurate which is why it's omitted.

floral shuttle
#

I see that now (not sure it has the motion and result , but will check) . However, my example was also about my trash collections πŸ˜‰ so I was looking for a date translator for the whole string in 1 go

mighty ledge
#

what's motion or result

floral shuttle
#

yes thats is

#

motion (should be direction) is obvious... required for several binaries and alerts

mighty ledge
#

direction as in + or -?

floral shuttle
#

yes that would be fine too I guess

#

although, I use that string too... hmm must have another look

mighty ledge
#

I still don't know what you mean by direction

#

I'm guessing

#

what's the translated words you expect in english?

floral shuttle
#

using this {% set today = state_attr('sensor.daylight_savings_times','dst_changed_today') %} {% set motion = 'vooruit' if now().timetuple().tm_isdst else 'terug' %} {% set result = state_attr('sensor.daylight_savings_times','next').result %} {% set ww = 'begint' if today == false else 'begon' %} Daylight savings {{ww}} {{'vandaag, zet de klok handmatig 1 uur ' + motion + ' waarnodig.' if today == true else 'morgen, we ' + result + ' slaap!'}} it indicates the direction we need to adjust the clock dial

mighty ledge
#

That'll have to be a feature request, it does not do that currently.

#

you can however do that quite easily using next_dst_phrase

#
{% set motion = 'vooruit' if 'lose' in next_dst_phrase() else 'terug' %}
#

but you'll have to adjust the if statement to your language

floral shuttle
#

it might be superflous no? because it is a direct translation of the now().timetuple().tm_isdst . No need to create an extra custom template for that.

#

but, getting back to a non dst timestamp like the trashcollector, what would you believe to be the best way forward

#

considering an entity sensor.afvalwijzer_next_date has a state formated like 22-11-2023 ( I did FR the integrtion to return a true datetime, but until then use {{strptime(states('sensor.afvalwijzer_next_date'),'%d-%m-%Y')}}

#
{% set date = strptime(states('sensor.afvalwijzer_next_date'),'%d-%m-%Y') %}
{{ weekday(date) }} {{ date.day }} {{ month(date) }} {{ date.year }}```
#

wait, there is an issue with the weekday using your template:

cyan stirrup
#

Can someone please take a look at my template.yaml I include the file in a configuration.yaml.
The problem is that I am not getting a value out of it states('sensor.degree_day_today') | float yields to 11.
if I directly do "state: '0' " it shows zero. Is my format correct?
https://codeshare.io/bvAQmv

marble jackal
#

can't you just make a utility meter out of your day sensor?

cyan stirrup
#

is it possible to only count a value if it is higher then a certain value with a utility meter? See updated code, on codeshare. It eventually has to work like that. I want to calculate multiple sensor values on the same trigger. maybe I eventually will put those values into the utility meter to keep track for longer time

mighty ledge
#

so it's being considered as UTC

#

use | as_local

floral shuttle
#

Ya I did try that but it doesn’t change the day and it remains friday in all cases…

cyan stirrup
mighty ledge
#
{% set date = strptime('22-11-2023', '%d-%m-%Y') | as_local %}
{{ weekday(date.isoweekday()) }}
#

it expects an integer, not a datetime

#

I can probably add that functionality, but we should read the documentation I wrote 🀣

#

FYI that also means month probably expects the month number too and defaults to the current

#

i.e. month(date.month)

marble jackal
#

the datetime test will be helpful if you want to add it

mighty ledge
#

Oh for sure

#

I'll add it this weekend

#

That macro set needs some love atm

marble jackal
#

that test will be helpful for a lot of marco's in that set

mighty ledge
#

Yes it will

floral shuttle
floral shuttle
mighty ledge
#

I think it's just dumb luck

#

date.month should be the only thing that works

#

I gotta update both of those macros to support datetimes

mighty ledge
floral shuttle
mighty ledge
#

thanks!

floral shuttle
#

btw why is this 1 hour of, {% from 'easy_time.jinja' import next_dst %} {{next_dst() | as_datetime}} ?

#

it should be +1:00 but shows +2:00.. or that calculaing the relative offset

mighty ledge
#

it's not off by an hour, that's the actual time it changes

#

it should not be +1, it should be +2. It's in respect to the current TZ but it occurs in the other TZ, that's why getting the 2nd DST out is not possible

#

I'm not sure how else to explain it to you. But we are looking at the next dst and it's time but we aren't in that dst. Which makes it look wrong but it's correct if you use it mathematically.

floral shuttle
#

no I get it

mighty ledge
#

i.e. as a datetime or using durations

floral shuttle
#

It's in respect to the current TZ but it occurs in the other TZ

mighty ledge
#

yeah, it'll trip ya up for sure but it's the correct time

floral shuttle
#

haha no, I was just wondering why the difference between the 2

mighty ledge
#

ah ok

floral shuttle
#

so I can safely change all of that repetetive yaml of the original sensor to these nice and short imports

neat crown
floral shuttle
#

uhm.... something must be off (my config, your macro) here too since I copied the exact code there...

marble jackal
#

that's quite a DST change

floral shuttle
#

hahah I wish

mighty ledge
#

53 hours isn't normal?

#

i'll have to look at it

marble jackal
ebon yoke
#

i want to create a template sensor that updates an energy measurement only if a different energy measurement increases while the location of a different sensor is at home

#

(this is basically to track the energy added to my ev car when it's charging at home)

mighty ledge
#

or maybe not???

#

hmm

mighty ledge
#

huh, apparently it's an issue w/ easy_time

#

{{ easy_time(3600) }}

#

returns 53 years

plain magnetBOT
#

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

main peak
#

I'm having a problem using a template in a script. Where is the best place to go for help?

inner mesa
#

Here

main peak
#

Ok, I am trying to expand a list in the entity_id: field of a script. I use -- entity_id: [ {{ light_list }} ] -- and get an error:

#

Error executing script. Error for call_service at pos 3: Template rendered invalid entity IDs: [{'[object Object]': None}]

inner mesa
#

Surround the template in quotes

main peak
#

I have reduced this down to a list that contains only one entry. If I put the entry directly in the brackets of entity_id it work.

inner mesa
#

The [ ] is unnecessary

#

The lack of quotes is the issue, though

main peak
#

The quotes did help, but I could have sworn I tried that.

inner mesa
#

It's rule #1 of templates

#

Otherwise it's interpreted as a malformed dict

main peak
#

Ok, so I did try it before with more than one thing in the list and I get a different error. (I will go dig it out of the log).

#

2023-11-17 14:14:19.298 ERROR (MainThread) [homeassistant.components.script.light_test1] New Script21: Error executing script. Error for call_service at pos 3: Template rendered invalid entity IDs: ['light.signify_netherlands_b_v_lwa025_light,light.signify_netherlands_b_v_lwa025_light_2']

inner mesa
#

Remove them

#

If you need a list, make a real list in the template

main peak
#

I think the brackets are needed. entity_id expects a list of items. Normally you pass them by starting each one with a dash. But that won't work because of spaceing.

#

Ok that is good. I thinght I had.

#

{% set members = [ "light.signify_netherlands_b_v_lwa025_light", "light.signify_netherlands_b_v_lwa025_light_2"]%}

#

If that is the correct form for a list, how do I pass it to entiry_id?

#

I'm sorry, I am really just learning this product

marble jackal
#

Where are you defining this variable light_list

main peak
#

Its in a yaml variable: the above line with: {{ members | join(",") }}

#

It's all just test code at this point

#

The whole test script is 16 lines, should I post it?

#

There is the distinct possibility that I am being wrong headed about how I am trying to accomplish.

#

I want to make a list of all of the lights in a group that are turned on and increase their brightness.

#

Here is the error without the square brackets: 2023-11-17 14:18:39.528 ERROR (MainThread) [homeassistant.components.script.light_test1] New Script21: Error executing script. Error for call_service at pos 3: Template rendered invalid entity IDs: ['light.signify_netherlands_b_v_lwa025_light,light.signify_netherlands_b_v_lwa025_light_2']

inner mesa
#

Simply do this:
entity_id: "{{ members }}"

main peak
#

I think you are right. I may not have saved after I changed it to that.

#

It does appear to work now.

#

Thanks for the help

#

BTW is there a good write up somewhere on using Jinja with yaml? I have used Jinja in web pages just a little bit. I find it obscure.

inner mesa
#

The second link in the channel topic

main peak
#

Thanks, I read this yesterday. But maybe I will learn more the second time around.

#

I'm gonna run off and do that. Thanks again for you help and patients with a newbie.

quiet creek
#

I am trying to make a template switch to call a ir remote for on an doff, it was working fine until I added the icon_template and now it won't update the on/off state when I toggle it.

plain magnetBOT
#

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

crisp hound
#

Hi guys! I need to select all entities of a specific integration and with specific domain. So far I can only count all entities {{ integration_entities('myintegration') | list | count }} . How do I filter domain? {{ states.sensor | integration_entities('myintegration') | list }} returns empty list..

inner mesa
#

{{ integration_entities('myintegration')|select('match', 'switch.')|list }}

#

there are many ways to do it

crisp hound
#

@inner mesa Thanks! works fine!

#

and how do I filter or group per device within one integration?

unborn ivy
inner mesa
#

You're nesting your templates

#

Remove {{ }}

#

It's not really doing anything useful, though

unborn ivy
#

{% set batt = ['sensor.frontdoor_battery', 'sensor.slidingdoorbackyard_battery'] %}
{% for b in batt %}
{% if (( states(b) | float ) > 0.8) %}
true
{% else %}
false
{% endif %}
{% endfor %}

#

My bad, I changed the format to "int" and increased the threshold to "80" and it is showing correct results. Thanks!!

inner mesa
#

Ok

inner mesa
#

I don't know how much I care about this, but I feel like the ability to have a 'test' filter that takes a test might be useful. Mainly to be used like map('test', 'gt', 80) to return a list of booleans for each item in an incoming iterator

#

We can select or reject to filter items, but not (that I'm aware of) create a list indicating which items pass a test and which don't

#

I was thinking about how to replicate the solution above (roughly) and couldn't figure out how to get both pieces of information at once in a single line

#

If I can think of a good use case and I'm not just missing something I'll write up an FR

#

I think it would be straightforward to implement

marble jackal
#

What I think would be a great addition is a test like num_gt which would test the input as a numeric value, so you can do things like | selectattr('state', 'is_number') | selectattr('state', 'num_gt', 80)

#

So in total 4 new tests, num_gt, num_ge, num_lt, num_le

#

Don't know if you can provide defaults to tests, but otherwise you can first check on numeric values with is_number like I did above

mighty ledge
#

@floral shuttle easy_time was updated to include all the crap we talked about yesterday plus some other crap

floral shuttle
#

Thanks for the new crap !

young laurel
#

Can I set climate current_temperature attribute to a specific value?

heavy crown
fossil venture
#

Unless you are digging out a septic tank.

mighty ledge
young laurel
mighty ledge
#

It’s an attribute, what I provided you was the service

pliant egret
#

Have what I think is an easy syntax problem. How do I filter by only entities in a specific area?

pliant egret
inner mesa
#

{{ area_entities('Family Room')|select('match', 'light.')|select('is_state', 'on')|list }}

pliant egret
#

ohhh, clever. Thanks πŸ™‚

unborn ivy
#

I've this template that is able to scan a group of battery sensors and compare the state of each battery to a helper and produce counts of batteries that are below the threshold:

{{ expand('group.monitored_batteries') | map(attribute='state') | reject('in', ['unavailable', 'unknown']) | map('int') | select('lt', (states('input_number.battery_levels') | int(0))) | list | count }}

Is there a way to tweak the above template to produce the names of entities as a list?

inner mesa
sonic ember
#

Can I have text values that correspond to a numerical one, for automation purposes? So somewhere I say that high=80% and then in my automation I can say "set speed to high", and in a helper or something I can set what high should be.

#

Does that make sense?

inner mesa
#

yes, that's a straightforward mapping

#
{% set map = {'high': 80, 'medium': 50, 'low': 20} %}
{{ map['high'] }}
sonic ember
#

So how would I go about that? Using a number entity as the "target value" in my automation, and then changing that number when I need?

#

is "map" an entity I'd create in yaml then? I'm confused where to use this?

inner mesa
#

it's a variable that I just created

#

that's a template

#

you can turn that into a macro if you want to use it in other places

sonic ember
#

Yeah I wasn't sure if it'd be a template I should make or another solution. I don't think I've made a variable before with a template, always a sensor or such

inner mesa
#
{% macro speed(level) %}
{% set map = {'high': 80, 'medium': 50, 'low': 20} %}
{{ map[level] }}
{% endmacro %}
{{ speed('high') }}
#

-> 80

#

it's all just Jinja

sonic ember
#

Ah ok. Let me see how I want to go about this, haven't fully decided how to build my automation either. Thanks for the tip

rare linden
rare linden
#

for some reason it's not working, shows as off in my dashboard and doesnt trigger anythign when i try and switch it on

#

the entity id is correct i'm using to get the device_id

mighty ledge
#

the state_attr line looks odd. I doubt it has attributes.device_id, i'ts probably just device_id, but you should be trying your templates in the template editor

rare linden
#

forgot about the template editor, i bet that's it, thanks

analog mulch
#

I am settign up a sensor which will contain a text weather forecast. Is there some character I can put in the template which will then result in a carriage return in the markdown card?

lofty mason
#

"\r", "\n", and "<br>" all generate a newline

rare linden
#

found the issue for some reason the device id is not on the entity so i'll have have to manually list the entity

rare linden
#

annoyingly had to end up hard coding the entities

rare linden
#

eventually found i could do device_entities(device_id('switch.pc_speakers')) as a starting point

radiant spindle
#

hey, using JS templating, how can I get the state of an entity ?

#

(something like that but it doesn't work) label: "[[[ return entity.input_datetime.myclock ]]]"

marble jackal
radiant spindle
#

sorry

marble jackal
#

No worries, just pointing you in the right direction

ebon yoke
#

i have an energy sensor that's throwing invalid values now and then (for instance suddenly 0 or some value that way higher than the rest) and i want to get rid of these (basically just discard them). how can i do that? i tried with the filter sensor, but that seems to average it, and that's not what i want, i want to discard them

lofty topaz
#

I would like to create a new sensor (I think) - I want to keep a monetary total in my HA instance that will be updated daily via an API call.
I don't really know where to start, have looked at online docs, done google searches, asked CHATGPT but none the wiser, is there anyone that can talk me through it?

ebon yoke
lofty topaz
#

hey πŸ™‚
I did try making a helper, but I didn't know the correct data, and then I didn't know how to update over API, I have a GPT that can read and set states already, I just wanted to add a sensor that stores some data, money in this example.

#

I am looking at a way to store some daily info, as chatGPT is statelesss, I already have an accessible HA instance, so though that would be ideal.

#

Whilst I do have a HA running, it was a few years ago that I set it up, and it is all a bit hazy now

#

I used to have some custom sensors that I updated in the front end using number helpers, but I don't know how I did it xd

lucid thicket
lofty topaz
# lucid thicket How about trigger-based template sensor that is triggered on a webhook? I assume...

Thanks for the idea; I already have a custom GPT that I trained to get and set states on entities, I would like to make some custom entities, or at least things that can be updated via the API. I have trained it to use the /api/services/switch/turn_on, and would like to keep it as close to this system as possible.
I may be asking for something that isn't possible or practical, I am not so knowledgeable with HA.

lucid thicket
#

You can just create a helper via the UI that is an input number. Then GPT can set it via /api/services/input_number/set_value

dry narwhal
#

Does anybody know why

    - service: notify.mobile_app_sm_g975f
      data:
        message: "Sensor {{ trigger.entity_id }} changed state from {{ trigger.from_state }} to {{ trigger.to_state }}."

leads to

#
Sensor sensor.eq3_battery_kitchen changed state from <state sensor.eq3_battery_kitchen=GOOD; icon=mdi:battery-bluetooth, friendly_name=eQ-3 Kitchen eQ-3 Battery Kitchen @ 2023-11-18T04:00:34.083536+01:00> to <state sensor.eq3_battery_kitchen=unavailable; icon=mdi:battery-bluetooth, friendly_name=eQ-3 Kitchen eQ-3 Battery Kitchen @ 2023-11-18T04:07:03.425634+01:00>.
inner mesa
#

You missed the .state

#

You're printing state objects

dry narwhal
#

Ah, so from_state.state?

dry narwhal
#

I read that, but maybe I missed the detail because I thought that "from_state" would already be specific to the state. I would not have thought that e.g. from_state.icon would make sense (rather it would then be e.g. from_icon).

grizzled grove
#

I'm using a template, with various variants, in a automation;
ex:

{{(as_timestamp(now()))-(as_timestamp(states.binary_sensor.car_status.last_changed)) < 900}}

But I would like to try them, to see where was the false, at a precise time; for instance using something like:

{{ today_at("18:59:41") ..... }}
#

Could someone give me some idea, how?

haughty breach
#

Can you clarify your question...? Do you want to return the time when your first template changes from rendering true to rendering false?

marble jackal
#

But I also don't understand the question

grizzled grove
mighty ledge
#

if you want a specific time, to the second, you have to make a template sensor w/ device_class timestamp and use that as the trigger

#

otherwise, you can get things to the minute w/ templates

ebon yoke
#

i have a total_increasing energy sensor that sometimes get a bad value, usually it's set to some value that's lower than the previous one. but there could also be a sudden spike. what is the best way to filter those away?

dry narwhal
marble jackal
#

No need to convert to timestamps here as well πŸ™‚ and why put it in an if statement, if will return true or false on its own.

{{ now() - states.sensor.home_assistant_v2_db_size.last_changed > timedelta(hours=12) }}
marble jackal
grizzled grove
#

Hmmm, let me put it like this: at 18:59:41 (according with the trace of the automation) there was a false, in a template with various devices - last_changed). I'm trying to pinpoint which of the devices was the false result.
I could substract the time now() for the moment that there was the trigger, but I was hopping I could simply use a more direct approach in Developer Tools.

#

Kind of simulate what happened at a specific time, during the day.

marble jackal
#

Can't you see in the automation trace which entity triggered it

#

Also note that a HA restart will rest last_changed for all entities

grizzled grove
#

If the template was for one specifically device, yeah.

#

True.

#

Hmmm, maybe something like:
{{ states.binary_sensor.car_status.last_changed < today_at("18:59:41") }}

#

But could I add the 900sec as a mark for the last_change, from that specific time?

#

{{ states.binary_sensor.car_status.last_changed < today_at("18:59:41") - timedelta(minutes=15) }} seems to work.

marble jackal
#

That's the same as

dry narwhal
marble jackal
lofty topaz
stuck remnant
#

hello wizards, I have this template and I want it to be fed to a light {{ payload | split(',') | map('int') }}
how do I do that?
I have this app that averages out my screen and sends this message so the template splits it
R27G26B26

stuck remnant
#

hmm, apparently the template is wrong too

marble jackal
#

there is no comma in there, so it won't actually split anything

stuck remnant
#

so how do I go about it then

#

I dont have access to the payload format

marble jackal
#

{{ ('R27G26B26' | regex_replace('R|G|B', ',')).split(',') | select('is_number') | map('int') | list }}

stuck remnant
#

great! and where do I put it within an automation? I know actions don't take templates

marble jackal
#

alternative

#
{% set payload = 'R27G26B26' %}
{{ (payload[1:] | regex_replace('G|B', ',')).split(',') | map('int') | list }}
stuck remnant
#

wait, the payload is going to differ each 16th of a second (60fps)

marble jackal
#

and service calls accept templates

stuck remnant
#

there;s gonna be a different payload value for each r g b

marble jackal
#

yeah, you should replace the string with your example with the payload variable

stuck remnant
#

but I can;t know that value, it changes too fast

#

oh I get it, so then just use this second line?
{{ (payload[1:] | regex_replace('G|B', ',')).split(',') | map('int') | list }}

marble jackal
#

yes

stuck remnant
#

this is what I got.

  - service: light.turn_on
    data:
      rgb_color: "{{ (payload[1:] | regex_replace('G|B', ',')).split(',') | map('int') }}"
    target:
      entity_id: light.main
    ```

how wrong is it ^^?
stuck remnant
#

hey

mighty ledge
#

you can also use this, it might be slightly faster

#
{{ payload | regex_findall('[RGB]([\d]{1,3})') | map('int') | list }}
#

hmm, probably this would be fastest...

[{{ payload | regex_findall('[RGB]([\d]{1,3})') | join(',') }}]
stuck remnant
mighty ledge
#

yes

stuck remnant
#

I don't know if I'm putting it where it's supposed to be

stuck remnant
#

hmm this is weird

#

it won't let me save

#

like the template was off

#

when I replace the template the save button pops up

#

tried both. This was the last one that worked
{{ (payload[1:] | regex_replace('G|B', ',')).split(',') | map('int') }}

mighty ledge
#

are you viewing this in yaml?

#

or using the UI?

stuck remnant
#

yaml

mighty ledge
#

then what are you talkinga bout "wouldn't let me save it"

stuck remnant
#

the bar at the left becomes red

#

and the save button disappears when I paste the template instead of the old one

mighty ledge
#

whatever you're using to view it doesn't understand that it's valid

#

use a normal text editor

stuck remnant
#

and we have the culprit

#

bad indentation of a mapping entry (2804:48)

2801 | ...
2802 | ... .turn_on
2803 | ...
2804 | ... [{{ payload | regex_findall('RGB') | join(',') ...
------------------------------------------^
2805 | ...

#

except I don't rly know which bit that's pointing to

mighty ledge
#

Are you not copying and using exactly what you wrote above?

stuck remnant
#

yes, i was copying from your message

mighty ledge
stuck remnant
#

yes

#

now says something else lol

#

end of the stream or a document separator is expected (2795:1)

2792 | enabled: false
2793 | mode: single
2794 | - id: '1700466984822'
2795 | alias: hals
--------^
2796 | description: ""

#

even though what I pasted anew was identical

mighty ledge
#

you have to make sure your indentation is correct in relation to all the other crap in your file

#

You can just make this in the UI if you're struggling with yaml.

stuck remnant
mighty ledge
#

can you just post your full file?

stuck remnant
#

2804:48 does this mean the 48th character in the line?

mighty ledge
#

it does

stuck remnant
#

regex_findall it's the underscore from here

#

the 48th

mighty ledge
#

that means you didn't copy it correctly

#

can you just paste your entire file

stuck remnant
#

sure

mighty ledge
stuck remnant
#

is it ok if I just paste the end of it?

#

like 3-4 automations or so

mighty ledge
#

you can just do the last 2

stuck remnant
#

it's a rly big file like 2500 lines long

#

kk

mighty ledge
#

Yeah, you for some reason changed the outside quotes to single quotes

#
      rgb_color: "[{{ payload | regex_findall('[RGB]([\d]{1,3})') | join(',') }}]"
stuck remnant
#

I was literally just thinking that

#

heheh

mighty ledge
#

well, not for nothing, if someone says "copy/paste", you kinda expect them to copy/paste, not rewrite πŸ˜‰

stuck remnant
#

I promise I did no such thing

#

I rly did copy paste as is

#

dunno where that came from

#

and just for the record, I wouldn't believe me either

#

unknown escape sequence (2804:56)

2801 | ...
2802 | ...
2803 | ...
2804 | ... oad | regex_findall('RGB') | join(',') }}]"
------------------------------------------^
2805 | ...

#

after correcting the quotes

mighty ledge
#

that makes no sense

#

did you change all the quotes or just the outside?

#

it needs to be ", not 2 '

#

"

#

when you put it into dpaste, it will even look like a full string

stuck remnant
#

yes thats what I used " and not 2 '

mighty ledge
#

and if your text editor is doing this to you, stop using whatever it is

stuck remnant
#

file editor addon

mighty ledge
#

use VSCode addon

#

if that thing is changing your values, stop using it.

stuck remnant
#

okay.jpg

#

switched to notepad. /based

mighty ledge
#

make sure replace tab w/ spaces is turned on

#

if you use notepad++

#

the vscode addon is much better for editing your config if you're used to file editor

stuck remnant
#

ok, giving it a go

#

Error loading /config/configuration.yaml: while scanning a double-quoted scalar
in "/config/automations.yaml", line 2804, column 20
found unknown escape character 'd'
in "/config/automations.yaml", line 2804, column 58

#

it likes the D

mighty ledge
#

ok, do this instead

#
rgb_color: >
  [{{ payload | regex_findall('[RGB]([\d]{1,3})') | join(',') }}]
#

and if that doesn't work

#
rgb_color: >
  [{{ payload | regex_findall('[RGB]([\\d]{1,3})') | join(',') }}]
stuck remnant
#

computer says no

#

I give up, tell me where I put it in the ui

#

like a noob

mighty ledge
#

what's the error now?

stuck remnant
#

Error loading /config/configuration.yaml: while scanning a quoted scalar
in "/config/automations.yaml", line 2805, column 61
found unexpected end of stream
in "/config/automations.yaml", line 2809, column 1

mighty ledge
#

can you post it in dpaste again?

stuck remnant
#

missed comma between flow collection entries (2805:32)

2802 | - service: light.turn_on
2803 | data:
2804 | rgb_color: >
2805 | [{{ payload | regex_findall('RGB') | join(',' ...
---------------------------------------^
2806 | target:
2807 | entity_id: light.main

#

sure

mighty ledge
#

I'm guessing rgb_color is at the same indentation level as the template

stuck remnant
mighty ledge
#

I highly suggest you pay attention to your yaml and possibly take some time to learn what the indentations mean.

#

you have

#
  
       rgb_color: >
  [{{ payload | regex_findall('[RGB]([\\d]{1,3})') | join(',') }}]
#

now does that look like?

rgb_color: >
  [{{ payload | regex_findall('[RGB]([\\d]{1,3})') | join(',') }}]
#

where do you think the [ should start under rgb_color?

stuck remnant
#

I understand what the indentation means, but I tried to just copy and paste without editing so that I don't fudge it up

#

the next line usually starts 2 characters in, from what I've noticed

mighty ledge
#

if you have a field, and you use the mutli-line identifier (>), then the lines below it need to be indended to let the yaml know it's part of that field

stuck remnant
#

okay that makes sense

#

yeah so.. it went through

#

saved, all good

#

but it doesn't actually do the thing

#

to the lights

#

doublechecked the mqtt client that sends the data too

#

it is on, and triggering the automation

#

trigger flashes

mighty ledge
#

check the automation trace

stuck remnant
#

Error rendering data template: UndefinedError: 'payload' is undefined

mighty ledge
#

change it to trigger.payload

stuck remnant
#

works! cheers

#

but it's slow for some reason. It may be the client, I can't really tell

#

yeah

void flax
#

any ideas on how to trim last 10 char from trigger data

marble jackal
#

from a string?

#

{{ 'your long string9876543210'[:-10] }}

marble jackal
void flax
# marble jackal result: `your long string`

i have this at the moment {{ trigger.data | replace(")>", "") | replace("<MultiDict(", "") |
replace("Motion detected on", "") | regex_replace('[^a-zA-Z0-9 ]', '') }} i put that on the end of the closing bracket and wont let me save

mighty ledge
#

post an example here, and the value you want

void flax
#

Test Location at 0155 PM

#

i want to get rid of last 10 of that

mighty ledge
#

that's the full output of data?

#

i'm referring to the full field, there's likely a much better way to get the information you're after

void flax
#

MultiDict('Test - Location at 01:55 PM': '') is how the webhook trigger data looks

#

is that what you need?

mighty ledge
#

yeah that's what I'm talking about

#

and you just want what? Test - location?

void flax
#

yes

mighty ledge
#

give me a moment

void flax
#

thank you

mighty ledge
#
{{ trigger.data | regex_findall("MultiDict\(\'(.+) at") | first | default }}
#

@void flax ^

void flax
#

i also get Person and Vehicle instead of Motion

mighty ledge
#

ok, give me a moment

#
{{ trigger.data | regex_findall("MultiDict\(\'(?:Motion|Person|Vehicle) detected on (.+) at") | first | default }}
void flax
#

Amazing thank you sooo much

barren jungle
#

IS there a method returning entity attribute from entity_registry?
Similar to device_attr(...) ?

inner mesa
#

what specifically are you looking for?

mighty ledge
#

there is no function but we need one

barren jungle
#

for a few macros I put on todo list
currently I want to check unique_id (or to be precise it's suffix)

#

I want to programmatically find certain type of entities by integration and device_class is not good here

mighty ledge
#

what type of entities?

#

e.g. what does the unique_id offer that device class does not?

barren jungle
#

Depends on integration, is a good example:

        "device_class": "battery",
        "unique_id": "8783189714750ef4ef1a7eaeef5924b77df423f0b5808b807faf3267cbf7e6f7_battery_level",
}       
{        
        "device_class": "battery",
        "unique_id": "8783189714750ef4ef1a7eaeef5924b77df423f0b5808b807faf3267cbf7e6f7_car_battery",
}```
#

many integrations don't even provide device_class for many entities, but reading unique_id suffix or translation_key might be helpful to pick exact entity types

inner mesa
#

making assumptions about how the unique_id is generated seems prone to failure

#

it's just intended to be unique, not parsed

barren jungle
#

or when I have 3 sensors for daily/monthly/yearly consumption that looks almost indentical in state attributes

#

Hmmm it's better then nothing.. and ik it will work only in some cases

#

it's ok for me... unless there is a better alternative?

inner mesa
#

differentiate based on entity_id and use that

#

or add attributes via customization

barren jungle
#

It doesn't feel like a very universal macro if I have to depend on entity naming convention
or presence of manually added attributes
This is probably what I'll do until there will be a better way

mighty ledge
#

it won't be universal either if you have to depend on unique_id

#

unique_id's can be entered by users, or completely generated based on the integration. And each integration is different.

#

there won't be a one size fits all template for that either

barren jungle
#

true as well. However for many of my cases examining the suffix would just work.

mighty ledge
#

well it doesn't exist

#

so it's a moot point

ivory harbor
#

I'm trying to get a template to return true based on the presence of a future goolge calendar event. Is that possible? Or does the calendar state only hold the current event?

mighty ledge
#

it only holds the current event but you can use the calendar.list_events service call to get the future events in a script. Then process your stuff there.

#

it can also be used in a template entity

ivory harbor
#

thats helpful, thanks!

#

I didn't find calendar.list_events in docs

ivory harbor
mighty ledge
#

you can use it in an automations action section, which is a script

ivory harbor
#

copy that, thanks

plain magnetBOT
teal umbra
#

What whould be my best option? And i hope its understandable

mighty ledge
#

Use @marble jackal's macro that does this for you

teal umbra
#

Thx @mighty ledge this is exactly what i need

thorny snow
#

Wow... that's an actual thing. I scrolled back looking for 'Fes's macro'.

crisp hound
#

I want to template a sensor attribute where I need to check a state of the sensor being temlated.. how do I reference this entity in the attribure template? this code does not work: {% if is_state(entity, 'on') %}Check add-on, integration state{%endif%}

crisp hound
#

Thanks @inner mesa !

atomic blade
#

You could use a custom template macro

sharp frigate
copper cliff
#

Hey folks, I'm trying to get HA to create a new sensor using a CSV file that's on an External FTP server.

copper cliff
ebon yoke
#

when first creating a new template sensor, it will be set to unavailable, is there a way to set this to some other value initially?

#

the template sensor will be updated based on a different sensor, but until that other sensor triggers, then it will be "unavailable"

marble jackal
#

if you create a new template sensor, it will be immediately rendered, unless it's a trigger based template sensor (which yours is not)

#

your template can be made a bit shorter though

#
template:
  - sensor:
    - unique_id: energi_varmeovn_office
      device_class: energy
      state_class: total_increasing
      state: >
        {% set source = states('sensor.0x3fff00080000039a_energy') | float(0) %}
        {% set last_val = states('sensor.energi_varmeovn_office') | float(0) %}
        {{ [source, last_val] | max }}
        {% endif %}
ebon yoke
#

how can i create a trigger-based template sensor? i guess that's what i want. everytime the source sensor is updated, i basically just want to filter those values to make sure that no bad values get through

ebon yoke
#

how often are my sensors updated, then?

marble jackal
#

every time your trigger triggers

ebon yoke
#

i thought you said that i'm not using a trigger-based template sensor?

marble jackal
#

oh you meant your current sensor, it is updated every time one of the sensors you mention in it change state

ebon yoke
#

yeah, but that is what i want

#

isn't that kind of a trigger in itself?

marble jackal
#

I guess you want this

template:
  - trigger:
      - platform: state
        entity_id: sensor.0x3fff00080000039a_energy
        not_to: [ 'unavailable', 'unknown' ]
    sensor:
      - unique_id: energi_varmeovn_office
        device_class: energy
        state_class: total_increasing
        state: "{{ trigger.to_state.state }}"
ebon yoke
#

but isn't that kind of redundant?

marble jackal
#

no, because now it will only update on numeric states

ebon yoke
#

to use a template trigger when this just updated whenever the source entity updates (which is exactly what my sensor already does?)

marble jackal
#

you exclude the unwanted states unavailable and unknown now

#

and a trigger based template sensor will restore it's state, so this sensor will always have the last numeric state of your source sensor

ebon yoke
#

well, the problem isn't that the source entity/sensor has something besides numeric state. my problem was that the initial state of the new template sensor was unavailable upon init and then comparing the new value to that value made no sense

#

ah, ok, yeah, that makes more sense

#

is it correct that the new template sensor is named "sensor.template_<unique_id>"?

#

but also in your example. the whole reason why i'm using a template sensor to begin with is because the source sensor is throwing bad values now and then (suddenly 0 and also sudden peaks that's way above the previous measurement). so i need to discard them

marble jackal
#

normally the entity id is the slugified version of the name

#

otherwise it's sensor.templat_[unique_id]

#

and if you provide neither, it's sensor.template_[follow up number]

marble jackal
ebon yoke
#

can you also expand on that to remove the sudden "peaks"? it should be a gradual increase, not a jump. so i guess it needs to be some kind of percentage calculation

marble jackal
ebon yoke
#

well, it's in the source energy sensor as well

marble jackal
#

yes, but on the energy dashboard?

#

that's because the drops to 0, that's seen as a reset

silent vector
#

Does anyone have an idea how to use a variable in this context?

states.myvariable.last_updated
I'm trying to create a test for checking last updated is greater than x but with a variable and all I get is None type

ebon yoke
#

as it will only use the biggest values of the two

marble jackal
#

correct

#

there is probably no sudden spike, the energy dashboards shows a spike because of the wrong interpretation of the change to 0

silent vector
ebon yoke
marble jackal
#

ah, yo should remove those then

marble jackal
silent vector
#

Ah yes I think I have seen that before but forgot.

ebon yoke
fickle sand
ebon yoke
#

that kind of beats the point πŸ™‚

marble jackal
#

Then you should look at the source and why you get these spikes

ebon yoke
#

it's a wall heater that's integrated over mqtt

mighty ledge
#

is the configuration set properly on it?

#

i.e. how is it being added into HA? auto-discovered or manual (via yaml)?

ebon yoke
#

auto-discovered

#

for the most part it gives correct values, but not and then, i see a sudden spike

mighty ledge
#

well if it was correctly setup in HA you shouldn't get any spikes

#

I'd wager the discovery info isn't correct

#

can you post the contents of the discovery topic?

#

should be homeassistant\sensor\<unique_id>\config

ebon yoke
#

what do i need to use to get that?

mighty ledge
#

You can use MQTT explorer or something similar

ebon yoke
#

hm. i have the mosquitto_sub command

#

there's no config under <unique_id>

#

i only have power, current, voltage, energy, hysteresis, display_brightness, display_auto_off, power_up_status, window_open_check and linkquality

#

ah, yes, i have config under for instance energy

#

@mighty ledge any idea?

mighty ledge
#

actually the discovery info is good

#

that means your device is outputting 0

ebon yoke
#

yeah, but it's not only outputting 0, it's also peaking

#

check the image i posted

mighty ledge
#

well, no, it is outputting zero, then when it goes back to it's normal value, you get the huge spike

ebon yoke
#

it should not output zero. this should be a total increasing

mighty ledge
#

correct

#

based on the discovery info you linked, the source of the 0 is the sensor itself

#

or zigbee2mqtt

ebon yoke
#

so with the help of @marble jackal i have the trigger template that will make sure that only greater values are accepted

#

so that's one down, but i still have to account for that sudden spike as well

#

which also should be removed

spark flame
#

Is there a way to evaluate if a device has changed state within a certain time period in a template without a helper or any last_changed attribute?

mighty ledge
#

every entity has a last_changed property

#

its not an attribute

spark flame
#

Ahh

mighty ledge
#

you can interate a devices entities and get the most recent entity that changed and look at it's last_changed

spark flame
#

Basically I have a lux sensor under a light, but it gives delayed readings. I want to have a template sensor with a trigger on sensor value change that checks if the light has changed recently and apply/remove a modifier

mighty ledge
#
- platform: state
  entity_id: light.abc
  to: ~
  for: "00:15:00"
spark flame
#

I have to trigger off the lux sensor state because it might be 30-90s after the light state changes

mighty ledge
#

ya, same principl

#

e

#

the to: ~ looks at any state change

#

remove that and it'll be any state object change

spark flame
#

I need to check if the light has changed tho recently in my template code after the lux sensor updates

mighty ledge
#

right, then that would be the original trigger πŸ˜‰

#

just change your for duration to less than 15 minutes

spark flame
#

I was thinking more in the state value putting an {%if state_attr( light.patio, 'last_changed') type thing

#

But you said it's not an attribute?

mighty ledge
#

why, if you have a trigger that can do it for you

spark flame
#

Yeah but when the light turns on the lux sensor hasn't updated yet so that trigger doesn't help

#

Unless I flip a helper

#

I don't wanna adjust my lux before it's updated it's value and only when the light has changed in the last minute or so

#

Hmm

#

Maybe I can just settle for current state on lux sensor updates

#

The random delay just sent me down a rabbit hole maybe I didn't need to go down lol, thanks for the help πŸ˜„

inner mesa
fossil venture
mighty ledge
#

sorry if I wasn't clear

spark flame
fossil venture
frank gale
#

I have a list with dictionairies. Can I reject the items that a certain attribute didn't change?
Example:

{% set from_state = [{'client': 'Wohnzimmer', 'volume': 0.2, 'playlist': 'house'}] %}
{% set to_state = [{'client': 'Wohnzimmer', 'volume': 0.3, 'playlist': 'house'}] %}

this should return [] since the playlist didn't change, as only the volume changed

#

*without a for

marble jackal
#

I don't get it, why should it return []? Shouldn't it return [{'volume': 0.3}] then?

frank gale
#

The list contains multiple dicts, I need to retain only the dicts that the playlist changed

#
{% set from_state = [{'client': 'Wohnzimmer', 'volume': 0.2, 'playlist': 'house'}, {'client': 'Schlafzimmer', 'volume': 0.2, 'playlist': 'house'}] %}
{% set to_state = [{'client': 'Wohnzimmer', 'volume': 0.3, 'playlist': 'house'},{'client': 'Schlafzimmer', 'volume': 0.2, 'playlist': 'alarm'}] %}

This should return:

[{'client': 'Schlafzimmer', 'volume': 0.2, 'playlist': 'alarm'}]
#

I know how to do it with for and namespace variable, but I like to work with filters πŸ˜‰

light scroll
#

I'm sorry for posting this question again, I can see that it's asked a lot both here and on google. I have the count lights code in my sensor.yaml, but as many others I'm trying to exclude the helper group from the count. Can anyone point me in the right direction?
The code i'm using:

  • platform: template
    sensors:
    count_lights_on:
    friendly_name: "LightOn"
    unit_of_measurement: ''
    value_template: "{{ states.light | selectattr('state', 'eq', 'on') | list | count }}"
marsh cairn
#

You can add rejectattr
rejectattr('entity_id', 'eq', 'light.specific_light')
to exclude a specific light
or
rejectattr('entity_id', 'search', 'string')
to exclude every entity ID containing "string"

inner mesa
#

The light group has an entity_id attribute, so you can just filter on that

#

{{ states.light|selectattr('state', 'eq', 'on')|rejectattr('attributes.entity_id', 'defined')|map(attribute='entity_id')|list|count }}

light scroll
#

Thank you both so much.

pearl grail
#

Hello. I'm trying to write a template that would substract outside temperature sensor from inside temp sensor and then plot them on the same graph with the cubic meter of gas used for that day. Anyone have something similar? Thanks!

marsh cairn
#

The template is quite simple. But it will not plot anything on its own

pearl grail
#

I found some templates over internet, but i got some errors. I need to mention that I'm pretty noob :\

marsh cairn
#

What have you tried and what error do you get?

pearl grail
#

template:

  • sensor:
    • name: Temp Dif
      unit_of_measurement: "%"
      state: >-
      {% set TARGET = states('sensor.temperature_lumi_158d000201c587')|float %}
      {% set SOURCE = states('sensor.temperature_lumi_158d00014a1e10')|float %}
      {{ (TARGET - SOURCE) | round(2) }}
      attributes:
      target: "{{ states('sensor.temperature_lumi_158d000201c587') }}"
      source: "{{ states('sensor.temperature_lumi_158d00014a1e10') }}"
#

Sensor None has device class 'temperature', state class 'measurement' unit 'Β°C' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'template: - sensor: - name: Temp Dif unit_of_measurement: "%" state: >- 14.16 attributes: target: "23.34" source: "9.18"' (<class 'str'>)

mighty ledge
#

seems like you're not sharing the full configuration

plain magnetBOT
#

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

mighty ledge
#

that's complaining about device_class, which is not set according to your unformatted snippit

pearl grail
#
template:
 - sensor:
    - name: Temp Dif
      unit_of_measurement: "%"
      state: >-
        {% set TARGET = states('sensor.temperature_lumi_158d000201c587')|float %}
        {% set SOURCE = states('sensor.temperature_lumi_158d00014a1e10')|float %}
        {{ (TARGET - SOURCE) | round(2) }}
      attributes:
        target: "{{ states('sensor.temperature_lumi_158d000201c587') }}"
        source: "{{ states('sensor.temperature_lumi_158d00014a1e10') }}"
mighty ledge
#

are you overriding the unit of measurement in customize.yaml?

#

if no, did you copy/paste this sensor originally with the unit_of_measurement set to ΒΊC?

marsh cairn
#

Also the unit of measurement looks wrong. Β°C - Β°C doesn't result in %

mighty ledge
#

which cares about device_class and state class

#

for long term stats

#

so if he changed a bunch of things and it made it's way into LTS, then it could cause issues.

#

namely, not having a device_class but using a unit_of_measurement

pearl grail
#

I've modified % with Β°C in the code
In the other boxes from the template window I have:
Unit of measurement : Β°C
Device Class : Temperature
State class : Measurement
I get the same error

mighty ledge
#

if you want to set it to temperature, then device_class: temperature

#

exactly like that

#

and state_class: measurement

#

no capitals, no spaces

marsh cairn
#

Are you using the stuff inside of a template helper in the UI?

pearl grail
#

yes

marsh cairn
#

You are using the YAML configuration. The UI helper just accepts the template itself

pearl grail
marsh cairn
#

The UI helper does not contain the full code of a template sensor from the configuration.yaml.
It just uses the template part itself and some additional UI settings.

mighty ledge
#

just paste this into the user interface:

        {% set TARGET = states('sensor.temperature_lumi_158d000201c587')|float %}
        {% set SOURCE = states('sensor.temperature_lumi_158d00014a1e10')|float %}
        {{ (TARGET - SOURCE) | round(2) }}
pearl grail
#

great, it worked!

#

so this gives me instant value, how about an average for each day so I can also check 1-2 weeks ago?

#

i somehow feel that it should be an easier way to do this 😦

#

or it will record the temperature difference starting today, acting like a new sensor?

marsh cairn
#

The values are stored from now on - for 10 days by default.

pearl grail
#

I've found out that my daily gas sensor resets at 1AM, so I need to write a complex average function that will average that delta T above from 1AM to 1AM

#

but I guess i'll need more experience for that to happen πŸ™‚

#

thanks a lot for the delta T code!

crisp hound
#

Iam playing these days with the templating and now noticed two weird things a) if I setup sensor under platform: template the HA may creates binary_sensor instead; b) some times HA creates sensor with the same name but is suffix 2,3,4, these sensors have attribute restored: true What do I do wrong and how do I clean up the system from resotored sensors now??

marble jackal
plain magnetBOT
crisp hound
ebon yoke
#

@marble jackal i have the zero problem sorted out, but i still have those peak values i need to deal with. Do you have a suggestion on how to address that?

inner mesa
marble jackal
marble jackal
crisp hound
marble jackal
#

Because your unique_id line is commented out

crisp hound
#

I am in template.yaml . If the sensor comfigured like this ```
sensor:

  • name: "siren"

friendly_name: "Sirena status"

state: "1"   ```

HA creates it. But if I uncomment friendly_name -- HA does not create the sensor... same happens with many other sensor tags.. Uuuuuuuuuuuuuuuff

atomic blade
#

I think there's your answer. friendly_name is only for the legacy sensor configuration. Is there a reason you're trying to specifiy name and friendly name? name should work just fine

cursive crest
#

Could someone perhaps help me out with this? I used a cover template to make a garage door in HA with a simple relay and wired contact sensor. It's the cover template example to the dot: https://www.home-assistant.io/integrations/cover.template/#garage-door

In HomeKit, though, this setup goes to shit. The door shows as always "open" when closed, and to press the garage door button at all, I have to set the garage switch to "close" and then "open" again. Mind you, all my switch does is press the garage button, it doesn't send different signals for open and close. Is there any way I can smart this template up to fool HomeKit properly?

(My one major difference, and maybe this is what breaks it, is that I'm using a binary sensor instead of a position sensor)

marble jackal
#

Oh Scott already mentioned that πŸ™‚

mental violet
#

Hi, does somebody has an idea how I can make a template that, can say if my person.tracker is heading home?
And how long this will take?
I have a working zone, if I leave that (I could be heading home or to a drug store or to my hobby etc) but when I am driving for lets say 20-30min to my home, then the template should be return: on / or home or whatever.
Maybe it could return the time that I would need to drive home and when it continously decreases than it returns on. (Or triggers an automation)
How could I realize that?
Thanks πŸ˜„

marble jackal
plain magnetBOT
crimson lichen
#

Hi,
i have 2 list
List1: ['presnce_room1', 'presnce_room2' ,'presnce_room3', 'presnce_room4']
List2: ['speaker1', 'speaker2', 'speaker3', 'speaker4']
How to search from List1 and choose exactly at List2.
EG:
When test presnce_room1 and presnce_room4 is on then call exactly services TTS to speaker1 and speaker4

Many thank!

marble jackal
#

Create a list of dictionaries where you map them together. You can do that in YAML if you want in an automation or script.

Or.. use the area. You can put the presence sensor and the speaker in the same area, eg living room. Then determine in which areas presence is detected and find the speakers in those areas

floral shuttle
#

would appreciate some extra eyes on an issue I have with my custom-ui. bottom line: custom-ui can add custom attributes and can even template those. These templates, and the resulting attribute with value are displayed in the dev tools attributes list and the set state box. Until recently we could jinja template those attributes. As of 2023.11 (i think) that is no longer the case. Wonder if we had a change in HA backend template handling to cause that change

#

as the attribute is there, and HA template doesnt see it, it is a bug in HA, so hence the issue. Unless its somehow filtered purposely.

mighty ledge
#

the frontend isn't rendering the value

#

well, not sure how custom ui did it, but this is most likely a change that needs to happen in custom UI.

#

personally, I think you should kill that software.

floral shuttle
#

a thanks for having a serious look, and yes, Id love to kill it. HA just doesnt do things yet it should really do imho, so for now I am trying to minimize, but keep where required.

#

setting state dependent icons and color should really be part of core functionality. In themes preferably, or without. Card_mod does help in some spots too. for now, ill try to fix....

crisp hound
mighty ledge
#

the entity_id is created from the name. Editing via the UI comes from a unique_id

#

if you don't have a unique_id, then you can't edit it via the UI

marble jackal
mighty ledge
#

e.g. if your name is Abc XYZ, your entity_id would be sensor.abc_xyz

#

There's no way to have a nice friendly name and a separate controllable entity_id like the old configuration had.

#

without editing it via the UI

mighty ledge
#

So to recap, add a unique_id and set your name. Then go into the entity_id in the UI and change it to what you want.

#

Your other option is to set your name to what you want the entity_id to be, then customize the name via customize.yaml

#

there's no way to have it all in yaml in one place.

#

Lastly, I don't see this changing anytime soon. people have tried to account for this missing functionality in the past and it's always failed due to some random requirement.

#

it's one of those live with it or use the legacy format scenarios

crisp hound
#

I have a bunch of old legacy templated sensors and now create 3 new sensors in modern format.. but it seems Ha does nt like coexistence.. Should I keep them all in the same style?

mighty ledge
#

You can have both, it seems you are making a yaml mistake somewhere

hollow peak
mighty ledge
#

... that's not the template integration

hollow peak
#

Ok so that has to stay under sensor:

mighty ledge
#

you can only move templates to the new template style

#

and it's only a specific sub set of templates, like sensor and binary_sensor

hollow peak
#

Got it, thx

cursive crest
#

Can I, within a cover template, set a cover's position via a binary sensor? e.g. when binary sensor is reporting closed, I'd like it to report a 0% position

mighty ledge
#

yes

#

but it's not setting the covers position, you're making a new entity which will report that position

analog mulch
#

Hi. I am generating a list of entit_ids and then I map area_id on them to get a list of rooms. I would like to look up a different string for each room name from some dictionary and then concatenate the output into a string. Something like

{% set dic = {'salon': 'salonie', 'gabinet':'gabinecie', 'bedroom':'sypialni', 'kids':'u dzieci'}%}
{%set rooms = ([<entity_ids>]|select('is_state','on')|map('area_id')|list)%}

This gives me a list like ['salon','kids'] in rooms which I would like to replace with the mapping in dic

tight tundra
#

type: gauge entity: input_number.bathroom_time_counter name: {{ states('input_text.bathroom_timer_text') }}
Trying to have a gauge name display a text sensor. But it yields the warning...

The provided value for 'name' is not supported by the visual editor. We support (string) but received ({"[object Object]":null}).

Does input_text not store a state of type string?

lofty mason
#

frontend cards don't support templates

tight tundra
plain magnetBOT
marble jackal
#

@opal kayak Especially the month part is tricky, luckily for you I have just the thing for that relative-time-plus

plain magnetBOT
#

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

spark flame
#

@opal kayak

marsh cairn
#

Be aware of the rules regarding using ChatGPT to create "help" for others @spark flame

plain magnetBOT
#

ChatGPT and other "AI" systems do a fantastic job of generating well structured, convincing looking answers... that are either totally garbage or, if you're lucky, have subtle flaws. Don't use them to "help" others, and don't use them yourself.

spark flame
#

Hey I did validate it first at least

#

But I'll avoid helping again no worries

mighty ledge
#

That’s a terrible template too

#

Crapgpt

marble jackal
#

@opal kayak I took the relevant part out of my macro, this should give what you need

{%- set date = as_datetime(states('input_datetime.test')).date() -%}
{%- set current_date = now().date() -%}
{%- set yrs = current_date.year - date.year - (1 if current_date.replace(year=date.year) < date else 0) -%}
{%- set current_date = current_date.replace(year=current_date.year - yrs) -%}
{%- set mth = (current_date.month - date.month - (1 if current_date.day < date.day else 0) + 12) % 12 -%}
{%- set month_new = (((current_date.month - mth) + 12) % 12) | default(12, true) -%}
{%- set day_max = ((current_date.replace(day=1, month=month_new) + timedelta(days=31)).replace(day=1) - timedelta(days=1)).day -%}
{%- set date_temp = current_date.replace(month=month_new, day=[current_date.day, day_max]|min) -%}
{%- set current_date = date_temp if date_temp <= current_date else date_temp.replace(year=current_date.year -1) -%}
{%- set dys = (current_date - date).days -%}
{{ '{} year{}, {} month{} and {} day{}'.format(yrs, 's' if yrs != 1, mth, 's' if mth != 1, dys, 's' if dys != 1) }}
marble jackal
#

Small correction

thin pivot
#

How would i convert a 24 hour time to 12?

message: The time is {{ now().timestamp() | timestamp_custom(' %H %M') }}

instead of "16 15" Id like "4 15".
%H would need to be converted?

inner mesa
#

%I %M

thin pivot
#

copy that. thx!

inner mesa
#

you don't need to convert to a timestamp, either

#

message: The time is {{ now().strftime(' %I %M') }}

thin pivot
#

any way to strip leading zeros? This is for TTS in Willow.

#

%l

Hour in 12-hour format (1-12) without leading zeros

#

aha

#

bummer... %l doesnt work in HA...

inner mesa
#

see that link

#

it has examples

#

message: The time is {{ now().strftime(' %-I %M') }}

#

that's why I gave you the link πŸ™‚

thin pivot
inner mesa
#

sigh

thin pivot
#

heck, at least I tried πŸ™‚

hexed galleon
#

If I wanted to get a count of all entities in a domain that DON'T match a state, how would I go about that? Can get all that DO match a state easily enough, but can't seem to not the select('is_state', 'on') and can't find docs on the select filter.

inner mesa
#

reject

#

See the second link in the channel topic

hexed galleon
#

Ahh, yeah cool! Searching for not obviously isn't very efficient! So the idea with that is to make a list of objects to reject from the full list? Is there a pythonic way to do that in a single line of filters?

inner mesa
#

just like you did with select

hexed galleon
#

I don't think I'm following. The one I'm using for lights currently is like this: {{ states.light | map(attribute='entity_id') | select('is_state', 'on') | list | count }}. How would you apply the reject filter to it to only show "not on" lights?

inner mesa
#

replace "select" with "reject"

#

or select the ones that are off

hexed galleon
#

Ohh, haha. Of course.

inner mesa
#

perhaps you're overthinking it

hexed galleon
#

Well, that was just an example, this is actually for climate entities, which can have many different on states.

inner mesa
#

ok, then start with the real question πŸ™‚

#

anyway, you have the docs now

hexed galleon
#

Yep, works a charm thank you!

#

0 πŸšͺ | 16 πŸ’‘ | 2 ❄
Nice and clean template status for phone homescreen.

hexed galleon
#

Any way to use the append list feature in HA's Jinja implementation? Can create the initial list and append one item, then adding another gives access to attribute 'append' of 'list' object is unsafe.

inner mesa
#

Make a new list

#

set foo = foo + ['blah']

hexed galleon
#

A little longer than I'd hoped, but does the trick!

{% set doors_open = states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'door') | map(attribute='entity_id') | select('is_state', 'on') | list | count %}
{% set lights_on = states.light | map(attribute='entity_id') | select('is_state', 'on') | list | count %}
{% set climate_on = states.climate | map(attribute='entity_id') | reject('is_state', 'off') | list | count %}
{% set triggers = [] %}
{% if is_state('alarm_control_panel.alarmo',['armed','armed_night','triggered']) -%}{%set triggers = triggers + ["πŸ”’" + states('alarm_control_panel.alarmo') | capitalize]%}{% endif -%}
{% if doors_open > 0 -%}{%set triggers = triggers + ["πŸšͺ "+doors_open|string] %}{% endif -%}
{% if climate_on > 0 -%}{%set triggers = triggers + ["❄ "+climate_on|string] %}{% endif -%}
{% if lights_on > 0 -%}{%set triggers = triggers + ["πŸ’‘ "+lights_on|string] %}{% endif -%}
{{ triggers | join(" | ") }}
#

TY again for your help Rob!

crimson lichen
strange geode
#

Hey I have a led stip on lets say 400 pixel. in WLED.
An when i get a notification i want the pixel 200 to 300 to turn to a specific color and blink, lets say blue"
After 15 sec, i want the "200-300" pixels to go back into the normal state of the full led strip..

ive made an automation that makes it blink and show the right color..
But how do i get it back in the same color as the full strip with no blink ?

marble jackal
#

no templates required. create a scene before you let it blink, and restore that scene after 15 seconds of blinking. #automations-archived can help with that

proven wasp
#

hi all, looking for some help with what's (hopefully) a simple template automation. i've got a bunch of toggle helpers set up for chores for my kid, and they all have the string "chore_kid.chorename" in the name. what i'm trying to figure out is how to make a template trigger that basically says "any time anything with "chore_kid" in the name turns from off to on (like when my kid checks off a chore he did), call a service to increment a point counter

#

i can do 90% of it, but i'm struggling with the trigger syntax

marble jackal
#

You need a template sensor for that

#

count the ones which are on

#

when it changes state, check if it new state is lower than the old one, and assign a point in that case

lofty mason
#

I had suggested just trigger on state_changed event, and condition the automation on pattern matching the name of the entity that changed state.

marble jackal
#

that's also possible

#

but you can't filter on domain in the trigger itself

proven wasp
#

yeah what @lofty mason said was kindof the direction i was looking

marble jackal
#

so it will trigger many, many times

proven wasp
#

i wonder if i could make a template sensor that turns on if any of the other ones go from off to on, and then the automation looks for that one sensor to turn on, calls the service to increment the point counter, then turns the template sensor back off

marble jackal
#

if you want to be able to dynamically add or remove chores without having to change your automation, I would still go for the template sensor with the count

proven wasp
#

long story short i'm basically trying to do this:

#

but without an automation that watches each individual chore helper (to make it more dynamic)

marble jackal
#
template:
  - sensor:
      - unqiue_id: something_unique
        name: Count tasks completed kid
        state: "{{ states.input_boolean | selectattr('entity_id', 'search', 'chore_kid') | selectattr('state', 'eq', 'on') | list | count }}"
automation:
  - platform: state
    entity_id: sensor.count_tasks_completed_kid
    not_to: ['unavailable', 'unknown']
    not_from: ['unavailable', 'unknown']
condition:
  - "{{ trigger.to_state.state | float > trigger.from_state.state | float }}"
action:
  - service: script.add_one_point
#

btw, I assumed you really have chore_kid in the name of the entity, so lowercase and with underscore, or did you mean the entity_id?

proven wasp
marble jackal
#

Changed above

proven wasp
#

thx! so if i'm understanding it correctly, the template sensor just monitors for them changing from off to on, and keeps a count, and then the automation monitors for that count changing and increments accordingly?

marble jackal
#

That's the idea

proven wasp
# marble jackal That's the idea

great, thanks! just implemented it and it works fantastically. now i just have to figure out how to "lock" a boolean once it's turned on, because my too-smart-for-his-own-good child has already figured out he can just keep flipping a chore on and off for "infinite points!"

marble jackal
#

Yeah, that's something you need to take into account

#

The standard tap action will be to toggle it, you can replace that to only turn it on

lofty mason
#

Just wait till he figures out he can make API calls to toggle it in an infinite loop 😁

spice current
#
{% set devices = states | map(attribute='entity_id') | map('device_id') | unique | reject('eq',None) | list %}

{%- set ns = namespace(devices = []) %}
{%- for device in devices %}
  {%- set entities = device_entities(device) | list %}
  {%- if entities %}
    {%- set ns.devices = ns.devices +  [ {device: {"name": device_attr(device, "name"), "entities":[entities ]}} ] %}
  {%- endif %}
{%- endfor %}
{{ ns.devices }}
#

can someone help me add the friendly_name to each entity here?

lucid thicket
#

Instead of [entities ]

jagged ether
#

hey dudes, short question, i am using the {{ trigger.for }} in a state change automation. {{ trigger.for }} gives me in format 0:03:00, can some1 tell me how to only get the minutes? i googled but did not find anything useful here

marble jackal
jagged ether
acoustic arch
#

little annoyance. When i set brightness to say 40, then it ends up at 41.....

#

is that normal? I noticed lights didnt turn off after editing a script. Devtools said the light was +1 brightness LOL

marble jackal
#

that depends on your light, if your light has eg 100 brightness steps, it will be rounded to the closest step when you set your brightness

#

then it will report the brightness back to HA, and that will be rounded again

#

so it could be that you set it to 40 and it will be set to 41 in the end

acoustic arch
#

ok thx. I thought a light would use 0-254 scale. At least i turn them on that way. Still it jumps a spot.

#

ill just code a +2 to get things going then

#

I noticed its the shelly's doing this. So i think they translate it back and forth

#

zigbee do it correctly

marble jackal
#

it depends on the light itself, the light entity will have a scale from 0-255

#

but if the light is dimmed in 100 steps, 40 will be 0.156863 which is rounded to 0.16 (16%)