#templates-archived
1 messages Β· Page 59 of 1
Oh.
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
ahh
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
Yup, I was going to code that in since pin_code also has status in the field.
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 ;
create an entity that will store the forecast like this guy -> https://community.home-assistant.io/t/new-forecast-service-how-i-can-create-a-forecast-entity/613507/40
then use taht in your template sensor, or go straight to the data you care about in a template sensor.
thanks for the tip, will check it out!
@opaque sentinel I converted your message into a file since it's above 15 lines :+1:
Maybe I need to increment another sensor with the value at the end of every hour?
without the trends of the other sensors over that period, i"m not sure how anyone can help
Weekly use: https://i.imgur.com/1ArPEe6.png
Hourly tariff (it seems to follow my output, but inverted, now that I think about it): https://i.imgur.com/bbC4Br0.png
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)
the upward hops are coming from the nordpool entity's downward movement.
so it looks like you found the source
Yeah I get that, but I'm not sure what you want the template to do
if you have 2 separate binary sensors, what else do you need?
Thanks, yes, but I don't think I'm smart enough to convert it to a solution to my intent - to summarize the cost savings/non-savings over the week. I would expect a less downwards trend in my graph when the nordpool sensor increases, but still downwards, as the nordpool sensor value is bigger than my hourly rate (which is 0.68 SEK/kWh)
I'm not sure why you'd expect downward trends
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
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?
you want the weekly value?
Yes
just use utility meter
With my template as the source?
no, with your sources as the source
@quaint grotto I converted your message into a file since it's above 15 lines :+1:
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
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
thanks - i'll give that a go!
Right. I guess where I'm stumbling then is that I don't get any options for tariffs in the utility meter (in the ui). Just setting a float value doesn't seem to work. Can I modify a template so that it is being picked up as a tariff?
use utility meter in yaml if you want a variable tarrif
IIRC it supports a sensor for the tarrif value
I'll give it a go. Much appreciate your time and patience π
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.
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}}
just show us the template
this gives me "false" in the developer tools
yep
and this is how I tried to implement it
@raven garden I converted your message into a file since it's above 15 lines :+1:
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 π
and you aren't getting errors in y our logs?
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 π
@mighty ledge any reason why this isn't working:
@dense swan I converted your message into a file since it's above 15 lines :+1:
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.
The sequence: block is used only in scripts. In automations it should be actions:
The trigger object is only available in automations, and wonβt be available if you manually run your automation when testing
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
no
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...
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...
I had it there, just put the snippet for the action.
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}}' ?
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
@dense swan I converted your message into a file since it's above 15 lines :+1:
@dense swan what issues are you having? that script looks wrong
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 π
well, your conditions aren't correct
- condition: template
value_template: "{{ trigger.payload_json.action is defined and trigger.payload_json.action }}"
It was a nested issue in the payload. I fixed it.
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
Yea, it is working now with some minor tweaks.
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.
Nice, I see the logic there.
fixed a few typos FYI
@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" }, } }
yep, fixed
Interesting if I do if user for pin it won't trigger. I had to remove the if line. But user is set...
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 }}
I bet I have to do if user isn't blank since 0 = being considered false?
can you post the trace variables here?
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"
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
Key slots are string integers or the way z2m reports it.
or rework it
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
π
@opaque sentinel I converted your message into a file since it's above 15 lines :+1:
I've also noticed that I havent added device_class: monetary, should this be needed?
Hi everyone,
Could you help me to fix below issue?
https://community.home-assistant.io/t/how-to-setup-the-sensor-display-binary-via-protocol-of-modbus/641500
Is there a way to not update a template sensor after it was triggered by time_pattern?
without getting a unavailable error
refer to this.state on that trigger
yes, but this updates the last_updated doen't it?
only if attributes change
but why would you want this?
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],
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.
what's the format of that pickup_start attribute
I'll respond in an hour or so
this card example is the only working template i found which makes the click on the card go to TGTG app ( you know what i mean):
https://github.com/Chouffy/home_assistant_tgtg
I prefer making my own mushroom clickable entities that open the app, but fail, so i use this one.
anyway, the format:
pickup_end: 2023-11-16T16:15:00Z```
so i need UTC --> as_local (CET)
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
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
just use strftime to get the values you want out.
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") }}
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"
the first one is the correct one
w/o seeing what data is in entries we can't help any further.
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
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"
Yeah, |int filter then
yeah, I got occupied in some meetings, but I wanted to know if it already was a datatime or not, as as_datetime gives an error on a datetime object
incrementing [0] will provide other urls from "entries":
YES. that was it π Thank you!!
can now finish building a better RSS newsfeed custom card with images
@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
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.
I believe my previous question above is somehow template related or where would you suggest I post it? thx!
As I said, #frontend-archived
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
Done. Thanks!
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```
it's a bit complicated
Was hoping to gather what the forecast will be for the day. Odd that its not just a regular attribute
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?
You can use a template right in the target: section
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)
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.
that's not proper Jinja, though
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
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' }}"
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
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
yeah, you are right. i guess it's late π
Just curious..whats so complicated about it?
Sorry, was away and forgot I said that.
This post here highlights it -> https://community.home-assistant.io/t/new-forecast-service-how-i-can-create-a-forecast-entity/613507/40
@neat crown ^
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 }}"
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
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
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
{%- 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)}}
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}}"}
nice
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
Ah, I should have actually checked the repo, didn't remember providing translations for the months, but apparently I did
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.
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
yes thats is
motion (should be direction) is obvious... required for several binaries and alerts
direction as in + or -?
yes that would be fine too I guess
although, I use that string too... hmm must have another look
I still don't know what you mean by direction
I'm guessing
what's the translated words you expect in english?
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
ahead/backwards forward/back, not sure what would the best https://www.timeanddate.com/time/dst/spring-forward-fall-back.html
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
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:
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
can't you just make a utility meter out of your day sensor?
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
No, your strptime has no timezone.
so it's being considered as UTC
use | as_local
Ya I did try that but it doesnβt change the day and it remains friday in all casesβ¦
I think I just made some syntax errors myself π
ah, sorry, needs to be date.weekday()
{% 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)
the datetime test will be helpful if you want to add it
that test will be helpful for a lot of marco's in that set
Yes it will
haha, yes. whatever make the final user template as simple as can be, so adding that functionality would be great
these all seem to be correct: {{date.month}} {{ month(date) }} {{month(date.month)}}
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
can you make a FR for those so I remember?
I'll FR that, thanks in advance
thanks!
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
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.
no I get it
i.e. as a datetime or using durations
It's in respect to the current TZ but it occurs in the other TZ
yeah, it'll trip ya up for sure but it's the correct time
haha no, I was just wondering why the difference between the 2
ah ok
so I can safely change all of that repetetive yaml of the original sensor to these nice and short imports
Thank you, will have a stab at it today and hopefully not get to frustated lol
'that's why getting the 2nd DST out is not possible '
I get it its not possible for the exact time, but we could be getting the correct date couldnt we? I mean, the time is less relevant to most people anyway (since it was chosen to do so midnight when asleep as much as possible....). Adding that 2nd change would really be nice
uhm.... something must be off (my config, your macro) here too since I copied the exact code there...
that's quite a DST change
hahah I wish
It's 53 years
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)
ok, apparently don't use the 2 macros together. I see the same thing when I use both macros in the same template
or maybe not???
hmm
huh, apparently it's an issue w/ easy_time
{{ easy_time(3600) }}
returns 53 years
@cerulean karma I converted your message into a file since it's above 15 lines :+1:
I'm having a problem using a template in a script. Where is the best place to go for help?
Here
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}]
Surround the template in quotes
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.
The quotes did help, but I could have sworn I tried that.
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']
I will point to this again: #templates-archived message
Remove them
If you need a list, make a real list in the template
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
Where are you defining this variable light_list
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']
If you have this: #templates-archived message
Simply do this:
entity_id: "{{ members }}"
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.
The second link in the channel topic
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.
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.
@quiet creek I converted your message into a file since it's above 15 lines :+1:
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..
{{ integration_entities('myintegration')|select('match', 'switch.')|list }}
there are many ways to do it
@inner mesa Thanks! works fine!
and how do I filter or group per device within one integration?
Here is the code https://pastebin.com/F93WenZm that I'm testing in the template editor but cannot make it work. Any pointers will be appreciated!
You're nesting your templates
Remove {{ }}
It's not really doing anything useful, though
Ok I see, now I'm getting "true" for both battery levels but this is incorrect as the second battery is at 0.72 so should be "false". I converted the states(b) through the float pipe but it does not seem to be working.
{% 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!!
Ok
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
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
@floral shuttle easy_time was updated to include all the crap we talked about yesterday plus some other crap
Thanks for the new crap !
Can I set climate current_temperature attribute to a specific value?
More crap is always better than less crap...
Unless you are digging out a septic tank.
You can't change attributes, you can call services like climate.set_temperature to perform actions.
I'm not sure if it is an attribute or a service
Itβs an attribute, what I provided you was the service
Have what I think is an easy syntax problem. How do I filter by only entities in a specific area?
Trying to get a list of all lights / fans turned on in a specifc room. Struggling to make it work... area isnt an attribute(?), and when I use the area_entities('bathroom_master') I get a list of entities that I cant additionally filter by (for light / fan domain and state = on)
ie somthing like this: {{area_entities('bathroom_master') | selectattr('domain', 'eq', 'light') | list}}
{{ area_entities('Family Room')|select('match', 'light.')|select('is_state', 'on')|list }}
ohhh, clever. Thanks π
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?
Not without turning it into a for loop. You could if we get what TheFes mentioned here: #templates-archived message
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?
yes, that's a straightforward mapping
{% set map = {'high': 80, 'medium': 50, 'low': 20} %}
{{ map['high'] }}
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?
it's a variable that I just created
that's a template
and you're in #templates-archived π
you can turn that into a macro if you want to use it in other places
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
{% macro speed(level) %}
{% set map = {'high': 80, 'medium': 50, 'low': 20} %}
{{ map[level] }}
{% endmacro %}
{{ speed('high') }}
-> 80
it's all just Jinja
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
can anyone see an issue with this?
looks fine
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
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
forgot about the template editor, i bet that's it, thanks
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?
"\r", "\n", and "<br>" all generate a newline
found the issue for some reason the device id is not on the entity so i'll have have to manually list the entity
annoyingly had to end up hard coding the entities
eventually found i could do device_entities(device_id('switch.pc_speakers')) as a starting point
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 ]]]"
JS templating is #frontend-archived
sorry
No worries, just pointing you in the right direction
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
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?
this isn't something you can do with a helper?
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
How about trigger-based template sensor that is triggered on a webhook? I assume when you say you want to update it over API you mean you want something to connect to your HA instance and update it? Otherwise if instead you want your HA instance to reach out to an API to grab a value, you would want to create a REST sensor
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.
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
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>.
Ah, so from_state.state?
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).
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?
Can you clarify your question...? Do you want to return the time when your first template changes from rendering true to rendering false?
Your template can be simplified to
{{ now() - states.binary_sensor.car_status.last_changed < timedelta(minutes=15) }}
But I also don't understand the question
Yes, its to test at the specific time.
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
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?
Maybe not what you were asking for but I like working in seconds like this:
{% if now().timestamp() - states.sensor.home_assistant_v2_db_size.last_changed.timestamp() > 43200 %} true {% endif %}
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) }}
Do you mean like this?
{{ now() - today_at('18:59:41') < timedelta(minutes=15) }}
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.
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
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.
That's the same as
If I remember correctly you need to use timedelta or similar and cannot use e.g. seconds directly if you don't add the timestamp. But that is from memory.
Using the if because there is also an else not shown here π
You can use seconds as well, but in my opinion the timedelta makes it much more clear what the actual time period you are comparing to is
{{ (now() - states.sensor.home_assistant_v2_db_size.last_changed).total_seconds() > 43200 }}
Trying to state to a specific number kept failiing, until I sent the increment payload to that endpoint, which works - but is not suitable for my purpose. I will keep digging thank you for your help.
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
hmm, apparently the template is wrong too
Is R27G26B26 the payload you are trying to split?
there is no comma in there, so it won't actually split anything
{{ ('R27G26B26' | regex_replace('R|G|B', ',')).split(',') | select('is_number') | map('int') | list }}
great! and where do I put it within an automation? I know actions don't take templates
alternative
{% set payload = 'R27G26B26' %}
{{ (payload[1:] | regex_replace('G|B', ',')).split(',') | map('int') | list }}
wait, the payload is going to differ each 16th of a second (60fps)
and service calls accept templates
there;s gonna be a different payload value for each r g b
yeah, you should replace the string with your example with the payload variable
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 }}
yes
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 ^^?
hey
you need the | list
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(',') }}]
description: ""
trigger:
- platform: mqtt
topic: /hals
condition: []
action:
- service: light.turn_on
data:
rgb_color: "[{{ payload | regex_findall('[RGB]([\d]{1,3})') | join(',') }}]"
target:
entity_id: light.main
mode: single
Like this?
yes
I don't know if I'm putting it where it's supposed to be
Ok
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') }}
yaml
then what are you talkinga bout "wouldn't let me save it"
the bar at the left becomes red
and the save button disappears when I paste the template instead of the old one
whatever you're using to view it doesn't understand that it's valid
use a normal text editor
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
Are you not copying and using exactly what you wrote above?
yes, i was copying from your message
this right here, copy/paste
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
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.
ok, corrected indent, now says the same thing as before
2804:48 does this mean the 48th character in the line?
it does
sure
in dpaste.org so I can see what you did
you can just do the last 2
Yeah, you for some reason changed the outside quotes to single quotes
rgb_color: "[{{ payload | regex_findall('[RGB]([\d]{1,3})') | join(',') }}]"
well, not for nothing, if someone says "copy/paste", you kinda expect them to copy/paste, not rewrite π
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
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
yes thats what I used " and not 2 '
and if your text editor is doing this to you, stop using whatever it is
file editor addon
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
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
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(',') }}]
what's the error now?
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
can you post it in dpaste again?
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
I'm guessing rgb_color is at the same indentation level as the template
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?
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
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
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
check the automation trace
Error rendering data template: UndefinedError: 'payload' is undefined
change it to trigger.payload
works! cheers
but it's slow for some reason. It may be the client, I can't really tell
yeah
any ideas on how to trim last 10 char from trigger data
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
what's the output of data?
post an example here, and the value you want
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
MultiDict('Test - Location at 01:55 PM': '') is how the webhook trigger data looks
is that what you need?
yes
give me a moment
thank you
{{ trigger.data | regex_findall("MultiDict\(\'(.+) at") | first | default }}
@void flax ^
Thank you this is working but i got the string wrong, are you able to help still with this MultiDict('Motion detected on Test - Location at 01:55 PM': '')
i also get Person and Vehicle instead of Motion
ok, give me a moment
{{ trigger.data | regex_findall("MultiDict\(\'(?:Motion|Person|Vehicle) detected on (.+) at") | first | default }}
Amazing thank you sooo much
IS there a method returning entity attribute from entity_registry?
Similar to device_attr(...) ?
what specifically are you looking for?
there is no function but we need one
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
what type of entities?
e.g. what does the unique_id offer that device class does not?
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
making assumptions about how the unique_id is generated seems prone to failure
it's just intended to be unique, not parsed
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?
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
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
true as well. However for many of my cases examining the suffix would just work.
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?
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
do I have to call it in a script, or can i use it in an automation directly?
you can use it in an automations action section, which is a script
copy that, thanks
@teal umbra I converted your message into a file since it's above 15 lines :+1:
What whould be my best option? And i hope its understandable
Use @marble jackal's macro that does this for you
Thx @mighty ledge this is exactly what i need
Wow... that's an actual thing. I scrolled back looking for 'Fes's macro'.
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%}
Thanks @inner mesa !
You could use a custom template macro
Thanks. I'll look into it, but I've already solved it for now with good old copy and paste and changing the entity.
Hey folks, I'm trying to get HA to create a new sensor using a CSV file that's on an External FTP server.
sorry
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"
i currently have it like this, but it feels kind of redundant: https://dpaste.org/4D8hG
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 %}
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
how often are my sensors updated, then?
every time your trigger triggers
i thought you said that i'm not using a trigger-based template sensor?
oh you meant your current sensor, it is updated every time one of the sensors you mention in it change state
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 }}"
but isn't that kind of redundant?
no, because now it will only update on numeric states
to use a template trigger when this just updated whenever the source entity updates (which is exactly what my sensor already does?)
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
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
that's because you didn't provide a name
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]
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: >
{% set new = trigger.to_state.state | float %}
{% set current = this.state | float(0) %}
{{ [new, current] | max }}
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
the sudden peaks are in your energy dashboard I presume
well, it's in the source energy sensor as well
yes, but on the energy dashboard?
that's because the drops to 0, that's seen as a reset
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
yeah, but the drops to 0 is ok, the template trigger you wrote above will solve that
as it will only use the biggest values of the two
correct
there is probably no sudden spike, the energy dashboards shows a spike because of the wrong interpretation of the change to 0
Is the only other way looking at the domain of the entity and filtering?
no, i see the spike in the source entity, not in the dashboard
ah, yo should remove those then
{% set var = 'sensor.banana' %}
{{ states[var].last_updated }}
Ah yes I think I have seen that before but forgot.
suggestions to method to do that?
If you have a spike in your data, you can correct this in dev-tools->statistics. Find the sensor there, and press the icon at the end of the line. You then can either:
Find the faulty value, and set it to 0.
Add a correction value in the same hour, which is the opposite of your faulty value.
i'd rather not be doing this manually
that kind of beats the point π
Then you should look at the source and why you get these spikes
it's a wall heater that's integrated over mqtt
is the configuration set properly on it?
i.e. how is it being added into HA? auto-discovered or manual (via yaml)?
auto-discovered
for the most part it gives correct values, but not and then, i see a sudden spike
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
what do i need to use to get that?
You can use MQTT explorer or something similar
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
and that looks like this: https://dpaste.org/JM6cJ
this is how the entity looks in h-a: https://pasteboard.co/mv0Ryo5Up3ra.png
@mighty ledge any idea?
sorry, back
actually the discovery info is good
that means your device is outputting 0
well, no, it is outputting zero, then when it goes back to it's normal value, you get the huge spike
it should not output zero. this should be a total increasing
correct
based on the discovery info you linked, the source of the 0 is the sensor itself
or zigbee2mqtt
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
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?
Ahh
you can interate a devices entities and get the most recent entity that changed and look at it's last_changed
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
- platform: state
entity_id: light.abc
to: ~
for: "00:15:00"
I have to trigger off the lux sensor state because it might be 30-90s after the light state changes
ya, same principl
e
the to: ~ looks at any state change
remove that and it'll be any state object change
I need to check if the light has changed tho recently in my template code after the lux sensor updates
right, then that would be the original trigger π
just change your for duration to less than 15 minutes
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?
why, if you have a trigger that can do it for you
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 π
BTW, you can see what's in the attributes yourself in
-> States, no need to take Petro's word for it :). It is in the state object: https://www.home-assistant.io/docs/configuration/state_object/
||MY WORD IS LAW||
I thought you had to remove the entire to: to get any state object change? Null to: just triggers on state value change.
Yeah that's what i meant by remove that. I.e. Remove the whole to: field
sorry if I wasn't clear
I guess I've not referenced state.last_changed of an object before so was just trying to wrap my head around it vs attributes
Cool. I thought you meant just remove the tilde.
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
I don't get it, why should it return []? Shouldn't it return [{'volume': 0.3}] then?
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 π
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 }}"
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"
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 }}
Thank you both so much.
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!
The template is quite simple. But it will not plot anything on its own
I found some templates over internet, but i got some errors. I need to mention that I'm pretty noob :\
What have you tried and what error do you get?
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') }}"
- name: Temp Dif
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'>)
seems like you're not sharing the full configuration
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.
that's complaining about device_class, which is not set according to your unformatted snippit
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') }}"
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?
Also the unit of measurement looks wrong. Β°C - Β°C doesn't result in %
the error is probably coming from recorder
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
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
if you want to set it to temperature, then device_class: temperature
exactly like that
and state_class: measurement
no capitals, no spaces
Are you using the stuff inside of a template helper in the UI?
yes
You are using the YAML configuration. The UI helper just accepts the template itself
can you say this again with more words so I can also understand? :))
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.
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) }}
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?
The values are stored from now on - for 10 days by default.
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!
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??
Some remarks:
- This channel is for the Jinja templates only, your questions more for the #integrations-archived channel
- using
platform: templateis outdated, I would recommend using the modern format - Provide a
unique_idto avoid the duplication
What do you mean with creating a binary_sensor? Does the entity_id start with binary_sensor or if it a sensor with a binary state like True or False
in my configuration.yaml I create a sensor like this: - platform: template sensors: konn_z3_siren: #unique_id: 1sensorkonnz3siren1 friendly_name: Sirena status value_template: >-
@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?
That is a poorly formatted and incomplete template configuration π€·
Yes, that's the legacy format, as also shown in the documentation from the bot message (and incomplete as Rob mentions)
I still say it should be resolved at the source, it shouldn't show these spikes.
However you could use the current state of the template sensor if the state of the source sensor is eg more than double of the current value
fine. bu t why do I have duplicates then? binary_sensor.konn_z3_siren, binary_sensor.konn_z3_siren_2, binary_sensor.konn_z3_siren_3, sensor.konn_z3_siren_2
Because your unique_id line is commented out
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
Just to double check, when you uncomment that line, is the indentation correct? Please paste the sample code here of what it looks like uncommented. Just want to make sure that isn't the problem. Also are there any logs about failures?
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
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)
That's because friendly_name is no longer used in the modern format, it's replaced by name
Oh Scott already mentioned that π
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 π
The proximity integration can do that
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!
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
thank
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
see: https://github.com/home-assistant/core/issues/104190 please if you have a moment
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.
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.
its most likely related to this line https://github.com/Mariusthvdb/custom-ui/blob/87f41bfc107d2880a0ecbc71ada8157f35fb2863/custom-ui.js#L44C71-L44C81, when attributes are null it returns the untemplated attributes in to the entity.
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....
well, if only name: is given the entity_id and friendly_name get the same values for this entity. I assign a shortest possible value for entity_idand more explanatory value in friendly_name ,, I can give long name value via UI and then it create the friendly name . But why I annot assign all values while configuring my sensor and keep it all at one place? Do I miss something?
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
In the legacy format the object_id (the part after the dot in the entity_id) and the name could be set independently. In the new format the entity_id is determined by the name
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
this explains.. ok. Thanks!
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
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?
You can have both, it seems you are making a yaml mistake somewhere
I have these sensors written under the legacy method. Can this be re written as nested under template: ? https://www.home-assistant.io/integrations/systemmonitor/
... that's not the template integration
Ok so that has to stay under sensor:
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
Got it, thx
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
yes
but it's not setting the covers position, you're making a new entity which will report that position
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
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?
frontend cards don't support templates
Great, thanks
@opal kayak I converted your message into a file since it's above 15 lines :+1:
@opal kayak Especially the month part is tricky, luckily for you I have just the thing for that relative-time-plus
@spark flame I converted your message into a file since it's above 15 lines :+1:
@opal kayak
Be aware of the rules regarding using ChatGPT to create "help" for others @spark flame
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.
@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) }}
Thx a lot, works perect
Small correction
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?
copy that. thx!
you don't need to convert to a timestamp, either
message: The time is {{ now().strftime(' %I %M') }}
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...
see that link
it has examples
message: The time is {{ now().strftime(' %-I %M') }}
that's why I gave you the link π
Got it. I was looking at https://docs.oracle.com/cd/E23389_01/doc.11116/e21038/timeformat.htm
sigh
heck, at least I tried π
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.
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?
just like you did with select
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?
Ohh, haha. Of course.
perhaps you're overthinking it
Well, that was just an example, this is actually for climate entities, which can have many different on states.
Yep, works a charm thank you!
0 πͺ | 16 π‘ | 2 β
Nice and clean template status for phone homescreen.
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.
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!
Many thank.
I'm success with Dictionaries
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 ?
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
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
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
I had suggested just trigger on state_changed event, and condition the automation on pattern matching the name of the entity that changed state.
yeah what @lofty mason said was kindof the direction i was looking
so it will trigger many, many times
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
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
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)
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?
Entity ID actually, and then all have friendly names
Changed above
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?
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!"
Yeah, that's something you need to take into account
You could handle that on the #frontend-archived
The standard tap action will be to toggle it, you can replace that to only turn it on
Ohhh good call
Just wait till he figures out he can make API calls to toggle it in an infinite loop π
{% 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?
entities | map('state_attr', 'friendly_name') | list
Instead of [entities ]
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
{{ today_at(trigger.for).minute }}
THX!
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
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