#templates-archived
1 messages Β· Page 9 of 1
ok
Ahh there is also 2 more scenarios to take in account, the physical sensor sends 3 codes:
1: on - off which is door open and closed
2: low battery signal
3: tamper switch if the sensor is removed from the door or window
So in HA I have 3 binary sensors for each phisical sensor following this naming:
So for intance door 01a has these 3 binary sensors:
doorbr01a
doorbr01abatt
doorbr01atamper
Dont know if that info is usefull but i thought its worth mentioning to make sense of the template
sorry got sidetracked
is batt and tamper in the binary_Sensor window / door names?
binary_sensor.doorbr01a
binary_sensor.doorbr01abatt
binary_sensor.doorbr01atamper
or
binary_sensor.doorlr01a
binary_sensor.doorlr01abatt
binary_sensor.doorlr01atamper
or
binary_sensor.doorkitchen01a
binary_sensor.doorkitchen01abatt
binary_sensor.doorkitchen01atamper
ty
binary_sensor.doorbr01a (last letter a in this case could be a b or c) and all sensors following same naming convention
for windows the same thing:
binary_sensor.windowbr01a
binary_sensor.windowbr01abatt
binary_sensor.windowbr01atamper
or
binary_sensor.windowlr01a
binary_sensor.windowlr01abatt
binary_sensor.windowlr01atamper
or
binary_sensor.windowkitchen01a
binary_sensor.windowkitchen01abatt
binary_sensor.windowkitchen01atamper
can anybody tell me what is wrong with this?
properties:
"text": >
{%- if is_state('weather.openweathermap','unavailable') %}
(not available)
{%- else %}
{%- set con = state_attr('weather.openweathermap','forecast')[1]['condition'] %}
{%- if con == 'clear-night' %}
Clear night
{%- elif con == 'cloudy' %}
Cloudy
{% endif}
{%- endif %}
this is in configuration.yaml
@lapis quarry what are your room numbers equal to?
doorbr, windowbr
br means bedroom but what does the number mean?
sensor number?
so not room number?
Room number
why do you have a room number when you already have a room name
All rooms are named the same
Br
The number after is the room number
Br01 br02 erc
same with kitchen?
ok
So room 1 might have 1 door and 2 windows
So doorbr01a and windowbr01a and windowbr01b
Same for kitchen and same for living room
@lapis quarry what about the 'home' thing
right, what's the entity_id for that?
im using groups:
for rooms its group.room01, group.room02 etc
for living room its group.living01, group.living02
For kitchen its group.kitchen01, group.kitchen02 etc
I have no idea what that's supposed to be. At the very least, it has some extra " in it, but you'll need to provide some more context
living??? not LR??
inside those groups i have all entities that detect presence in that space and the group will be home or not_home
wrenches I tell you, wrenches
yes excatly as posted
its the best i could manage to do man i was pretty proud of it dont be to hard on me π
also this code was written 2019 many of the solutions you have now available where not implemented back then
im sure i would do it better if i stareted from scratch today (at least a little better)
that's how you can use variables to not reuse code
after alias add an id to it so you can trace the automation
- alias: "Windows Automation"
# mode: restart
id: windows_automation
mode: parallel
yes, it does
same thing
make the room a variable, the number a variable, the room name a variable, the sensor name a variable and then you don't repeat yourself
it would be alot less code if you named things better
wait i need a few minutes to recover and read what you just sent if i can undestand anything LOL
none of this lr crap means livingroom and living and living room
stick with 1 name
br = bedroom
lr = livingroom
kr = kitchen
if you did something like that and named everything in accordance to that it would be easier
also, if you had separated the identifiers out with _, you wouldn't need the fancy regex that I had to use
either way, that should work, but I can guarentee there are errors because i dont' have any of this stuff
you were constantly checking the same crap when you didn't need to
if you have the check in the beginning, it won't be needed in the middle
like the sensor name being door or window
you had that check everywhere
but it didn'tneed to happen in the middle of your script because that's not changing.
take your time, I have to walk away anyways
im using openhasp to display the weather on a display this part is sending the type of weather but i want the result in an nicer way like: Clear night instead of clear-night of Cloudy instead of cloudy .....
hey men thanks ill send you some coffe
np, and thanks
but i still need to grasp all this and understand it because i see a lot of dark magic going on there
ill be back with questions
that's what the trace is for
so you can see the variables and their output when it triggers
trace?
automations have traces now
let me show you
you can look at the changed variables and see where things fail
changed variables are all the variables in the automation and how they resolved when a trigger occured
Also honest and very serious question: is there any benefit to all this besides this being elegang code to you devs?
Because one primordial thing for me is understang the code, and the code i wrote i understood and worked and this i cant grasp, at least yet..
3 things for me are important:
- Eficiency in the code, menaning im not using resources ineficiently
- Scalability in the code meaning my templates should acomodate for expansion (which you allready sugested some more tips I just need to process everything)
- And understading it and being able to maintain it
if you take the time to understand it, you'll realize you don't have to add anything to this to make it work
i.e. if you add a new room and sensors, that's all you add. Just name them and this will work.
without touching the code
where u see this?
in the automation list, each automation will have a ...
in that list is the word traces
traces are only available if your automation has an id
it has to be unique
- alias: My automtion
id: my_unique_id_for_this_automation_to_enable_traces
... the rest of the owl ...
Im laughing my ass off because all i wanted it to get rid of the warning in the logs and now im in this rabiit hole (again) seems there are infinite rabit holes every time i try to do something here π€£ π€£ π€£ π€£ π€£ π€£ π€£
let me see if this passes config test
chances are... medium
I'd have to see all the errors
post them in a dpaste and @ me. I'll have to look later
sure, i also need to run, + i need some time to grasp all this, def ill be getting back
thanks again π π₯°
np
I found it I forgot an %
sensor: >
{% set s, r, n, t = new_state.object_id | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z])') | first | default(['', '', '', '']) %}
{{ {'name': s, 'room': r, 'room_number': n, 'sensor': t} }}
I guess I need to spend some time learning regex
i'll break it out for you
(window|door) -> the word window or door, capture this group of characters.
([a-z_]+) -> capture n length lowercase letters & underscore
([0-9]{2}) -> capture 2 numbers in a row
([a-z]) -> capture any single lowercase letter
and just spelling out that last one pointed to a bug, I need a + there
each () defines 1 item in the list, so theres 4 (), so you'll get 4 items
if htere's no capture, first will fail, but the default will catch it and put in empty strings
so [] basically means this character range
normal regex lets you assign names to groups so you get a dictionary out
but you can't do that in HA's regex, it just returns the values π
is that true? It uses Python's re library underneath
I guess there isn't a function that just returns what it returns - it always has a modifier
I didnβt look at the code but I did attempt name the groups and it still returned a list of values instead of a dict
I found that grouping works as you'd expect only when in a multi-line template
but I haven't tried naming the groups
Itβs been a while@since I used named groups, I thought it always returned a dictionary. Might be an object tho
Pardon my ignorance, but is moment.js incorporated into jinja? I'm trying to parse and humanize a timedelta (hh:mm:ss).
Morning guys
Petro I kind of follow the code, still need some more time to process everthing and undestarnd it
the regex is black magic LOL
I dont understand this statement
also I noticed something here where you call the script:
sequence:
- service: script.turn_ac_on
data:
location: bedroom
room_number: "{{ sensor.room_number }}"```
location: bedroom (should be either "bedroom", "kitchen" or "living" based on what kind room that is triggering the automation)
so there needs to be a variable there
regarding the config checker i get this error: Error loading /config/configuration.yaml: expected '<document start>', but found '<scalar>'
in "/config/automations/Windows Automation Template Petro.yaml", line 59, column 1
also I think I confused you because i didnt explain well enough the aircon thing i mentioned:
My AC units follow the same kind of naming convention airconbr01a for instance, (but they are all regular sensors or switches, there is no binary_sensor for the AC unit itself) so its not needed in this template
also another thing i noticed is the delay:
- delay: "{{ room_delay }}"```
should be 0 when switching AC on, delay only applies when group is not_home it should wait before switching the AC off
I kinda get this, but why the | first filter?
I have a problem with template covers in the configuration.yaml.
Only 1 cover is shown but I have three.
I cant answer your question but testing the regex for binary_sensor.doorbr01a it outputs:
sensor: >
{'name': 'door', 'room': 'br', 'room_number': '01', 'sensor': 'a'}```
it my 2 year old daughter birthday today so will be kind of busy, will checking when i can π
Can I configure a universal media players enitity state like this: state_template: switch.monitor?
Where switch.monitor is just a smart plug which can be either turned on or off
No, you need to use a template
state_template: "{{ states('switch.monitor') }}"
because regex_find_all returns a list of found regex's. The regex I made returns a list of captures. So the regex_find_all will return a list of lists.
ok, more changes https://dpaste.org/1EeSQ
Ah, clear
room_delay: >
{% if
{{ state_attr(delay_datetime, 'timestamp') }}
I'm missing the {% endif %} here
@modest sigil posted a code wall, it is moved here --> https://hastebin.com/loxalofuwe
Ah just remove the if, was a prethought
I was wondering how you solved it now
select_source:
service: input_select.select_option
data_template:
entity_id: input_select.monitor_arne_source_list
option: >
{{ source }}
if:
entity_id: input_select.monitor_arne_source_list
option: "HDMI1"
service: switch.turn_on
entity_id: switch.hdmi1
else:
service: switch.turn_off
entity_id: switch.hdmi1``` Why does homeassistant throw a mapping error at the line before the else statement?
You need to add a - before every action in the sequence
And you if is missing a condition
And the then
@ornate patio posted a code wall, it is moved here --> https://hastebin.com/aceququvaw
Now I'm asking myself why it doesn't trigger the switch
Thanks Petro, been a long day, will go trough it when I have some time but at quick glance looks better now π
I have another question related the state_changed trigger:
I did this small change to my old working install:
Old working install: ```yaml
trigger:
- platform: event
event_type: state_changed
I added this yesterday:
trigger:
- platform: event
event_type: state_changed
event_data:
domain: binary_sensor```
so basicaly adding the domain to the trigger so it only triggers on binary_sensors
But started getting calls today AC where not switching on π π
My question is: Are you guys sure this is right? and if yes, was this allways like this or was it added sometime after 2021.4.6 (the release im running there)
because when i add the event data and domain the automation stops trigering, removed it and its working again
Hmm, I'm checking the state changed event data, and I don't see it
So, I might have been wrong he m there π
Think I had it mixed up with the service_call event
ok... no big deal it was a esay fix, but would have been cool to be able to filter out events like that
this is why im hesitant to chang to much in the code, my bunch of crap might not look nice but it works and i cant really afford to break anything π
and I also guess that means petros code might need some changes because there needs to be a check to make sure its triggering from a binary_sensor
i guess its easy enough just adding it to the first condition before any action
{{ new_state.state not in ['unavailable', 'unknown'] and (enabled and (auto_on or auto_off)) and new_state.entity_id in room_sensors }}```
{{ new_state.state not in ['unavailable', 'unknown'] and new_state.domain == 'binary_sensor' and (enabled and (auto_on or auto_off)) and new_state.entity_id in room_sensors }}```
right?
Still getting this error when trying to load the code to test it:
Error loading /config/configuration.yaml: expected '<document start>', but found '<scalar>'
in "/config/automations/Windows Automation Template Petro.yaml", line 60, column 1
Remove the {% if line
Is there a possibility to check if an area exists with templates, and if it does, markdown shows exist for example?
So like check if the Area name "Living Room" exists
ok, fixed that and the config checker keeped complaining about other lines, i think i fixed a few adding quotes here and there but cant find this one now: expected '<document start>', but found '<scalar>' in line line 58, column 1
Ah wait I think i got it
yes and the id i also had added π
yah sure
still complaining line 59
I don't see anything wrong
i cant see it either π
I'm not sure what text editor you are using but there's hidden characters in your paste
they aren't added from the software I was using
True
{% else %}
NONE
{% endif %}```
Im getting a syntax error, cant seem to find the issue...
"{{ 'True' if area_id('Living Room') else 'NONE' }}"
Thanks!
im using notepad++
entity: template
template: "{{ "True" if area_id('Living Room') else "False" }}"
states:
True:
type: markdown
content: Area Detected
False:
type: markdown
content: No Area```
Hmmm, it has to be {% %}
How would I approach this
no...
{{ }} means output value
{% %} means don't output, just execute
you're using the same quotes inside and out
" inside and outside the template make π₯
inside should all be '
cool your last paste passed the config test π
I know in Automations you can get what caused it to run by referencing the trigger variable. Is there a variable in Scripts that will provide what called it, like an Automation or another Script? I have several Scripts that are called from Automations or Scripts that expects variables to be passed. I want to test if a needed variable was not provided and provide a message that includes the calling Automation or Script name.
var is defined
I know I can test if the var is defined. I want to know what Automation or Script called the Script so I can log a message and know where to make the correction.
service: script.xyz
data:
var: 1
Oh, I missed that
context.parent_id
Or the context object
But you have to take the id and match it back to the automation.
Or script
Can you provide an example?
E.g. {{ states.script.airplay_through_receiver_on.context.id }}
Thatβs how you get the id from an entity
Then you match it with the context id provided by the script which is just context.parent_id
Sorry on mobile, but thatβs all you need to do
Thanks. I will have to do some testing. I may be back with more questions.
Does running like 100 lines of template on frontend make it extremely slow?
Only if itβs bad code
I created an auto generating mushroom card
π€·ββοΈ
style: |
ha-card {
background-color: rgba(20,20,20,0);
padding: 10px;
}
card:
type: vertical-stack
cards:
- type: custom:state-switch
entity: template
template: '{{ "True" if area_id("Foyer") else "False" }}'
states:
'true':
type: vertical-stack
cards:
- type: custom:button-card
show_icon: false
entity: input_boolean.1autogen_expand_foyer
name: Foyer
styles:
name:
- text-align: start
- justify-self: start
- font-size: 22px
- font-weight: 600
- text-shadow: 2px 2px rgb(0,0,0)
card:
- padding-left: 15px
- background-color: transparent
- padding-bottom: 13.5px
- padding-top: 18px
- type: custom:state-switch
entity: input_boolean.1autogen_expand_foyer
transition: swap-up
transition_time: 350
states:
'off':
type: vertical-stack
cards:
- color_type: blank-card
styles:
card:
- width: 0px
- height: 0px
type: custom:button-card
'on':
type: vertical-stack
cards:
- type: custom:auto-entities
card:
square: false
columns: 2
type: grid
card_param: cards
filter:
include:
- domain: light
area: Foyer
options:
type: custom:mushroom-light-card
use_light_color: true
show_brightness_control: true
show_color_control: true
show_color_temp_control: true
collapsible_controls: true
card_mod:
style: |
ha-card {
background-color: rgba(20,20,20,0.8);
}
'false':
type: vertical-stack
cards:
- color_type: blank-card
styles:
card:
- width: 0px
- height: 0px
type: custom:button-card```
@obsidian lintel posted a code wall, it is moved here --> https://hastebin.com/nisehadabo
How could I optimize it
Thereβs no template there
Its repeated like almost 30+ times so the entire code is like 5000ish lines
That small template wonβt cause issues
template: '{{ "True" if area_id("Foyer") else "False" }}'
Itβs likely the card itself
Could be any one of them
What does that mean?
hi is this right place to ask about apexchart formatter code?
No. That's #frontend-archived
really simple but stupid question
hey can someone tell me if a LOGICAL AND is valid in jinja?
or rather - can someone tell me HOW to do a logical AND in jinja
{% if states("sensor.clt_pump_status") | float < 1386 and states("sensor.clt_pump_status") | float > 1000 %}
value 1
{% elif states("sensor.clt_pump_status") | float > 12245 and states("sensor.clt_pump_status") | float < 18000 %}
value 2
{% else %}
{{ states("sensor.clt_pump_led_status") | float }}
{% endif %}
That looks fine
thx rob
you can test any template in
-> Templates
I have been trying to test the template but I cant get this to pass the first condition before any action
I simplified the condition down to only testting ```yaml
- condition: template
value_template: {{ new_state.entity_id in room_sensors }}
I also noticed in the regex you are using the word sensor twice:yaml sensor: > {% set s, r, n, t = new_state.object_id | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z_]+)') | first | default(['', '', '', '']) %} {{ {'name': s, 'room': r, 'room_number': n, 'sensor': t} }}
in the begining and also use the same name at the end 'sensor': t
I guess it should be something like```yaml
sensor: >
{% set s, r, n, t = new_state.object_id | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z_]+)') | first | default(['', '', '', '']) %}
{{ {'name': s, 'room': r, 'room_number': n, 'sensorletter': t} }}
Not sure but im suspecting that might be a problem, i tried the above but didnt make a difference
this is the state_change im triggering on https://dpaste.org/ReNtw
Is there anyone who can help me with a sensor that counts the days to a certain date?
anmyone knows why logical 'OR' doesnt work in a template but AND does (obvioulsy with a different result)?
{{ (states("group.p1_p2") or states("group.p1_p3") or states("group.p2_p3")) }}
The only time the output is true is when group.p1_p2 is true. When group.p1_p3 is true the output is false
This works tho
{{ (states("group.p1_p2") and states("group.p1_p3") and states("group.p2_p3")) }}
When all three are true the output is true
Revert the changes and look at the trace. Post the trace variables. Itβll tell you where it failed
give me a sec i suspect i found the reason, im managing to figure your code out digesting it bit by bit and commenting everything so i can read it easier π
where can i find the trace variables?
it fails here acording to the traceyaml condition: template value_template: | {{ new_state.entity_id in room_sensors }}
on the trace page, changed variables tab
Bit random everyone, but my template switches are all unavailable (not even showing in dev tools) since a 2022.9 update. Also my wake on lan and broadlink switches have become unavailable too. Really stumped and nothing in logs, any ideas? Thx
ok give me a sec to restore your code and i will send
Check the entities your template switches are uses. 2nd: Verify they didn't get a new name, e.g. switch.xyz_1
Thanks, theyre all actually using script.turn_on or automation turn on
Cant see any new unknown switches
right but they are only unavailabe based on their value_template, not what they turn on or off. If that cannot resolve a value, it will be None which means unavailable. Or the entities have a new name.
I have found it I think, two switch: entries in my config π€¦ββοΈ
It just dawned on me that none of them were working, WOL, broadlink, template...
So found a late night copy paste that wasnt observed well enough, and we're fixed. Thanks for entertaining me π
I restored your code but dont know what the heck is is going on now the automation is not executing when i open or close a window and traces are not updating either, I even rebooted HA
that doesn't make sense
i know
You're doing something wrong π
fount it
its was this
those lines need to be removed π€¦
corrected the link
i can see the regex sensor is not being populated acording to this, right?
same result
that doesn't make any sesne
its weird
change the sensor line to
searching: "{{ new_state.object_id }}"
regex_result: "{{ searching | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z_]+)') }}"
sensor: >
{% set s, r, n, t = regex_result | first | default(['', '', '', '']) %}
{{ {'name': s, 'room': r, 'room_number': n, 'sensor': t} }}
and run again
still unpopulated
hang on this one triggered by wrong entity, let me send you a good one trigered by a door
corrected link above, still ame result
change
searching: "{{ trigger.event.data.new_state.object_id }}"
regex_result: "{{ searching | regex_findall('(window|door)([a-z_]+)([0-9]{2})([a-z_]+)') }}"
sensor: >
{% set s, r, n, t = regex_result | first | default(['', '', '', '']) %}
{{ {'name': s, 'room': r, 'room_number': n, 'sensor': t} }}
and
# Only continue if we have a valid state, we are enabled or automatic and we ahve a window or door sensor.
- condition: template
value_template: >
{{ trigger.event.data.new_state.state not in ['unavailable', 'unknown'] and (enabled and (auto_on or auto_off)) and trigger.event.data.new_state.entity_id in room_sensors }}
run again, post trace
ok, here it is https://dpaste.org/4o1s6
but this is weirder, i run it like 10 times and every time the trace says it was triggered by automation.windows_automation instead of the binary_sensor.doorbr01a im testing with
that last trace is not the correct sensor
so it won't run with that.
you can't press the run button
but that is what i just said
i closed/opened the door 10 times i allways get this trace
with the last change
ill keep trying
look at previous traces
you have 5 spooled traces
the automation will be in there because the state is changing
this is why using state changed events is frowned upon BTW
because every state change will cause the automation to fire
the good news is that it seems like it's working now
because the automation state is changing
can i increase it to more than 5?
yes i forget how tho
you can trigger the automation and turn it off so it doesn't fire on other state changes too btw
so open the door then disable it quickly
or try to catch the trace
for debuging you mean right? yes might be better idea
but i would have to do it in the code im not quick enough
uh what do you mean?
there's a ... menu next to the automation and then a disable button
all from the ui
im triggering the automation witrh the set state meny, by the time i move the mouse over the trace is gone
was thinking first action when it triggers true would be a line of code to switch off the automation and be able to see the trace with the variables
you dont happen to know the code to do that ?
if yes, have 2 browsers open. 1 with the automation page, one with set state page. Set the state, then disable the automation.
its what im doing but im not fast enough, as you said this trigger multiple times per second
how many traces do you have?
it only seems to populate the last 2 or 3, if i go any further back it shows nothing
change your trigger to only have the entity_id you're testing
- platform: event
event_type: state_changed
event_data:
entity_id: ...
like this?
trigger:
- platform: event
event_type: state_changed
event_data:
entity_id: binary_sensor.doorbr01a
ok
there seems to be some weird behaviour in the trace menu
you can't stay in the trace page
it always shows the trace based on it's ID
so you have to refresh the page or go backward/forward
i see
this didnt seem to work i still have traces triggered by other sensors
π€·ββοΈ this is something youβll have to figure out. I have no idea how you got the first traces but canβt get the current ones.
Increase your traces to 100
Disable then search.
ok
Just @ me when you figure it out
All the variables look good
is room_number: '01' supposed to be in quotes?
ok
Your timers and delay seem like the wrong entity
So figure that out and the rest should work
Gonna be MIA for a bit
ok ill keep testing things, thanks for the help, i also need to go for lunch π
@mighty ledge This is the corrected and commented code: https://dpaste.org/ADAaJ
This is the trace: https://dpaste.org/oEcSt#L4
It doesnt get past the first choose condition, i think its this line but cant figure out how to write it:
- condition: template
value_template: >
{{
enabled and auto_on
and expand(room_sensors) | selectattr('state','eq','on') | list | count > 0
and expand(room_aircons) | selectattr('state','eq','off') | list | count > 0
and is_state(group, 'home')
}}````
What I would to happen is this:
All the room_sensors should be off for the condition to be true.
If any of the room_aircon switches is off the condition should also be true.
and the template should also pass if group is 'home' but also if group is 'on'
as groups can either be home or not_home but also on or off based on what kind of entities it contains
{{ is_state_attr('sensor.detroit_lions', 'kickoff_in', "in 33 minutes") }} How could I do math on the number potion, so let's say anything less than <10?
Is the format of that attribute always like that?
@marble jackal The formatting of the text changes. pre game it shows as "in XX minutes" after the game has started the text portion changes to say "XX minutes ago". But for my purposes I would only care about the pregame format of in XX minutes.
But also when it's like days in the future, it will show minutes?
If all the room sensor should be off you should use expand(room_sensors) | selectattr('state','eq','on') | list | count == 0
I'm pretty sure it would change from " in X days" "in X hours" and then " in X minutes"
But will it actually say in 100 minutes?
No, I forgot to put set in front of it
yes gopt that far and got it working π
how can i make this trigger with home state and also with on state?
is_state(group, 'home')```
i would do yaml - condition: template value_template: > {{ enabled and auto_on and expand(room_sensors) | selectattr('state','eq','on') | list | count == 0 and expand(room_aircons) | selectattr('state','eq','off') | list | count > 0 and is_state(group, 'home') or enabled and auto_on and expand(room_sensors) | selectattr('state','eq','on') | list | count == 0 and expand(room_aircons) | selectattr('state','eq','off') | list | count > 0 and is_state(group, 'on') }}
but again im repeating code there must be a better way to write it
π
@marble jackal It's giving a syntax error: Encountered unknown tag 'time'.
@marble jackal I see now the attribute has switched over to an hour ago. Perhaps that is causing trouble because there is no number to interpret.
No, I forgot to put set in front of it
value_template: >
{{
enabled and auto_on
and expand(room_sensors) | selectattr('state','eq','on') | list | count == 0
and expand(room_aircons) | selectattr('state','eq','off') | list | count > 0
and (is_state(group, 'home') or is_state(group, 'on'))
}}```
is the above right?
{% set t = (state_attr('sensor.detroit_lions', 'kickoff_in') | default('a b c', true)).split(' ') %}
{{ 'in' in t[0] and 'minutes' in t[2] and t[0] | int(11) <= 10 }}
Hello everyone . I need help with a cover template. Iβm converting a light entity to a cover using the cover template. When I turn the cover off the entity becomes unavailable. Iβm testing the brightness int for > 0 else closed but the brightness attribute disappears when the cover is completely turned off.
@hollow rampart posted a code wall, it is moved here --> https://hastebin.com/avurixacoz
That's the way lights work
Add a default to the int filter
can someone point me in the right direction with this please because if been banging my head for an hour and cant seem to figure out how to write it correctly , the last part how to make it trigger both with 'home' and 'on' π
@marble jackal what do you mean by adding default to int filter.
and states(group) in ['home', 'on']
yes that workedπ π₯°
ok so first condition to switch ac on done and working, the second condition to switch ac off is not working either
There's a link to all you need to know in the pinned posts
Iβm sorry Iβm trying to follow. Is there any specific link you are referring to?
I built the code based on the code you had π€·ββοΈ
Maybe explain what you actually want
im trying to digest it pc by pc and undertand it and test everything, but my code worked 100%
so the second condition is pretty simple
when group becomes either not_home or off delay should aply based on what room it is and after that switch ac off
I donβt know how it did, there was a bunch of undeclared variable use when I went through it
to be fair variables didnt exist when i wrote it almost 3 years ago
π
but you example has been really helpfull to see the new posibiulities the current releases offer
- conditions:
#> Check window function is enabled window auto_off is enabled for this room
- condition: template
value_template: >
{% set ns = namespace(result = []) %}
{% for x in expand(room_sensors) | selectattr('state', 'eq', 'on') %}
{% set lc = now() - x.last_changed %}
{% if 'window' in x.object_id and lc.seconds > window_timeout or 'door' in x.object_id and lc.seconds > door_timer %}
{% set ns.result = ns.result + [ x.object_id ] %}
{% endif %}
{% endfor %}
{{
enabled and auto_off and ns.result | length > 0
and states.switch | selectattr('object_id', 'search', aircon_search) | selectattr('state','eq','on') | list | count > 0
}}```
this portion i cant figure out yet
and it doesnt trigger
Itβs literally the code you had
With all the unnecessary rechecking of the same things removed
The only thing thatβs new is the selections at the bottom
If you remember I told you that door and window timer were probably wrong based on the last traces you sent. They didnβt have a value meaning the entity id is not what your old code claimed it was
i fixed that it was a typo in your code
The name space loop counts sensors and doors that have been open longer than the timer
and its not literally the same code you changed a few things and naming, but hey not complaining, the oposite im blown away from the help received
Itβs intent is the same
does it stay in that loop until the time is + than the timers i have set?ΒΏ
my code did because it was a delay
it waited there for x seconds and then continued
if this loop checks in the monent it triggers if time is greater than timer of course it wont be because we havent waited it to be
Your old code didnβt wait, your old loop was calculated exactly when it was executed. We arenβt talking about the delay thatβs applied in another service
so wehy are you checking lc.seconds > window_timeout i dont quite understand
That loop simply counts sensors that are on beyond the specified duration
hmmm
#hotel-management
Last changed > duration
Lc
or, perhaps, a thread?
up to you mods i dont know how to do that
should i continue the conversation there? btw its not a motel LOL
Yea, rob is fearful of the bates motel support
Ok I'm not a coder but I tried to make a change per attached but it is still not working. I understand that my cover entity must never go unavailable.
value_template: "{{ 'open' if state_attr('light.dining_room_blind_isy', 'brightness' ) | int(default=0) > 0 else 'closed' }}"
i'm having trouble understanding adding default to int filter.
hi all, any suggestions how i can setup this template to ignore 0 values?
specifically sensor.met_eireann_solar_today as it will update at night to 0 and ruin the calculation for the day. π¦
- name: "Solar Forecast Accuracy"
unique_id: sensor.solar_forecast_accuracy
unit_of_measurement: "%"
state: "{{ ((states('sensor.solis_daily_generation') | float / states('sensor.met_eireann_solar_today') | float) *100 ) | round (3) }}"
i looked at filter but i couldn't figure out how to add it
Now it will return 0 if that light is off
Before the template would return an error
You can use this.state to refer to the current state in case that sensor equals 0
Yep that worked like a charm. Thanks for your help!!!
@marble jackal I think I got it sorted now, thanks
Hi all. Trying to figure out the simplest way to do this. I would like to have a button I press to set a datetime for when the button is pressed, then have a sensor that is counting the days since that button was pressed. I have already created a button helper, and noticed that the state just sets to a datetime of the last time the button was pressed. I tried to do a {{ now() - states('input_button.appliances_cleaned') }} template, but that gives an error that I'm trying to compare a datetime to a string. How do I convert the state of the button to a datetime to be compared?
Tried to do an as_timestamp too, but get a number that is way too large.
a few of my sensors go to unknown value on restart of HA. I've searched but cannot figure out how to stop this.
sensor.meteireann_solar_radiation_today which is used in the calculation is updated twice a day by a python script. I don't really want to call it each time HA reboots as this is for a forecast - so don't want a current value.
How can I get HA to update the sensor on reboot? the underlying sensor for solar radiation has a value. If I put the template into developer tools then it will return a value... but still I have unknown. :/
- name: "Met Γireann Solar Today"
unique_id: sensor.meteireann_solar_today
unit_of_measurement: "kWh"
device_class: energy
state: "{{ ((states('sensor.meteireann_solar_radiation_today') | float )*(0.185*23.104/1000)) | round(2) }}"
sorry for a total noob question, but i have a MQTT sensor which shows me numerical number. In home assistant IΒ΄d like to se them as the text instead of numbers . How do use templating to show me the state in text instead? the is 4 different numbers depending in the states, starting, running, stopped, stopping. i have found in the templating documentation how it can be done but i have no idea where and how i do implement it
@ancient lynx I think DST may mess this up though. Something to consider if you have that in your location...
{{ ((as_timestamp(now()) - as_timestamp(input_button.appliances_cleaned.last_changed)) / 86400) | int }}
That seems to have completely glitched out my HA. The Template page in developer tools just has a pinwheel that won't stop while trying that template.
I did. Same result.
@ancient lynx sorry missing states. I guess when I swapped out my switch it got lost
{{ ((as_timestamp(now()) - as_timestamp(states.input_button.appliances_cleaned.last_changed)) / 86400) | int }}
That was it! Thank you.
I have the following variable in my template:
{% set lightgroup = 'light.bedroom' %}
I want to pull the name of the room from that variable. How can I use the replace function inside a variable? Something like this
{% set room = lightgroup.replace('light.',) %}
you're missing the thing to replace that string with
but this is easier: {{ lightgroup.split('.')[1] }}
if you wanted to replace with nothing, you have to say that. You can't just put a comma and then nothing
it's a string replacement, so you would need {% set room = lightgroup.replace('light.','') %}. But anyway, see above for a better option
thank you. I actually need to remove more than what's before the dot, just used that as a quick example since I had to translate to english, so I think replace works better since I'm going to remove the same text for every template
but won't calling replace or split on "light" affect the light variable itself?
I need it to stay the same
I think it's working, thank you
you might consider adding an attribute to each entity via customization that you can reference directly
that's a tactic that a lot of folks use
encountered another problem, replace is case sensitive
I'm trying to grab the room name from the entity_id but the room name in the entity name is capitalized
I could grab it from the name instead of the entity I guess
or you can just do |lower
I need the output to be capitalized
is there a command to capitalize the first letter?
the entity_id can't be capitalized
I mean after I extract the room name and assign it to a variable
{{ "foo bar"|capitalize }}
or {{ "foo bar"|title }} if you want each word capitalized
thank you β€οΈ
or, as you say, just use the entity name
one more thing
I need to join an empty space to the room name
tried "join" on its own but it says it's undefined
hmm
{% set room = join(' ', light.replace('light.','')|capitalize) %}
yeah, that's not how to do that
I understand why it's saying that but I don't understand what to call join on
yes, before the room name
join is a filter that acts on an interator
{{ "foo" ~ " " ~ "bar" }}
like taht?
if you really wanted to use join, you would do this {{ ['foo', 'bar']|join(' ') }}
both result in foo bar
I have another idea
I'm just gonna call another replace at the end
replacing space comma with just comma
yeah sorry for not giving an example
it was spitting out Bedroom , Kitchen ,
works great now
Has WoL switch configuration changed massively in the last few versions?
with regard to templates?
I tried to update my config yaml with a MAC address that had changed when I replaced a PC motherboard. Now I'm getting errors telling me that the WoL integration is no longer providing the switch
I don't think I'm using a template for it, just the simple toggle switch with the wake_on_lan as the platform called
then taht would be #integrations-archived
and it clearly still supports a switch: https://www.home-assistant.io/integrations/wake_on_lan/#switch-configuration
Oh .. okay. I didn't even think of checking in that room. Thanks. Would it be better to use a template for something that is simply an on switch and an indicator to show that it's on?
no, you just picked the wrong channel
Cool. Thanks for the nudge to the right channel
Iβm using a template to detect when some zigbee sensors over mqtt stoppes working (which they do somethimes) and the template itself works however iβve noticed that the counter (time since last change) resets everytime HA restarts. Is there anyway to change this so it looks at if the actual value changes or similar?
Full template
{{ expand(integration_entities('mqtt')) | selectattr('domain', 'eq', 'sensor') | selectattr('last_changed', 'lt', now()-timedelta(days=2)) | rejectattr('entity_id', 'search', 'batteri') | rejectattr('entity_id', 'search', 'lamplage') | rejectattr('entity_id', 'search', 'luftfuktighet') | rejectattr('entity_id', 'search', 'tryck') | map(attribute='name' ) | join('\n ') | default('none', True) }}
For all entities the last_updated object changes to the HA start time after a reboot
what is your full yaml for this sensor
state: >
{{ expand(integration_entities('mqtt')) | selectattr('domain', 'eq', 'sensor') | selectattr('last_changed', 'lt', now()-timedelta(days=2)) | rejectattr('entity_id', 'search', 'batteri') | rejectattr('entity_id', 'search', 'lamplage') | rejectattr('entity_id', 'search', 'luftfuktighet') | rejectattr('entity_id', 'search', 'tryck') | map(attribute='name' ) | join('\n ') | default('none', True) }}
Thatβs it
So, if I understand correctly, you want to only select those mqtt-sensors which did not have a state change in the last two days. But currently you are unable to do so because the last_changed is updated after a HA reboot?
Correct
Hello
Can someone tell me how to have a variable that shows what minute of the current time we are?
Thank you
{{now().minute}}
Thanks a lot.
How can I create a variable with that information?
Variable in what context?
Yaml: {% set minute_now = now().minute %}
Automations:yaml variables: minute_now: "{{now().minute}}"
I need to have a numeric variable with the current minutes of the hour, to export it to nodered and operate with it.
As an entity: https://www.home-assistant.io/integrations/template/
pretty sure you can get this info in node red
Though I find it hard to believe NR wouldn't have some kind of current time functionality built in.
I'm also interested in having her in HA
How would I create a sensor with this information?
Thank you very much, this works for me.
@half pendant I don't think there is an easy solution for this, especially not if you want to have it dynamically, and not use a fixed lists of sensors to keep track of.
@marble jackal i see. That's a shame. Would it be possible if I had a group of all sensors i wanted to mange? Or would I have to set it up per sensor?
Probably, with a trigger based template sensor you could keep track of the datetime there is an actual state change
But I'd have to do that for each sensor I wanna track. Does not seem scalable unfortunately
you can do it in one template sensor
but I was trying to do it dynamically, could not get that working yet
That's something for #frontend-archived
Oh derp... Thought i clicked on frontend
How would that look?
Well, easiest is to do it like this:
trigger:
- platform: state
entity_id:
- sensor.1
not_from:
- unavailable
- unknown
not_to:
- unavailable
- unknown
sensor:
- state: "{{ 'OK' }}"
attributes:
last_changed: "{{ this.attributes.get('last_changed', []) | rejectattr('entity_id', 'eq', trigger.entity_id) | list + [ dict(entity_id=trigger.entity_id, last_changed= states[this.entity_id].last_changed) ] }}"```
add an name and unique_id under sensor
and all entities under the trigger
it will fill itself on every change
Add all entities under entity_id:? Or one trigger per entity?
Where do you state the criteria for how long until they become unresponsive?
No one trigger for all
I didn't test it though
Now I did, and it seems I did make a mistake somewhere, however, I have to pick up the kids from daycare now
Will have a look later today
Is there a template that can list all entity ids within a given domain? For example if I wanted all the lights in my house listed out, is there a template that will list them out?
This test version works for me https://dpaste.org/wCJDy
Just realized that you can make ik dynamic using a state_changed event trigger and then use the template you were already using to determine if the entity_id should be added/updated in the attribute
But it's bedtime here, so that will be for another day
Looking forward to this tomorrow then! Thx for your help so far!
Hi, someone help me im need, when is timer bedrom active = 1, timer boiler active = 2, when both active = 3, timer bedroom + boiler idle = 0
{% if is_state('timer.heating_timer_bedroom_radiator', 'active') %}
1
{% elif is_state('timer.heating_timer_boiler', 'active') %}
2
{% else %}
0
{% endif %}
{% set radiator = iif(is_state('timer.heating_timer_bedroom_radiator', 'active'), 1, 0) %}
{% set boiler = iif(is_state('timer.heating_timer_bedroom_radiator', 'active'), 2, 0) %}
{{ radiator + boiler }}
thx so much
what are "templates"?
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 https://www.codepile.net/ or https://paste.debian.net/ to share code or logs
is this a response to my question?
tldr?
hey guys. I have an entity with an attribute containing a date (it's a string) in the '2022-10-02 16:00:00' format. how can I template the number of days from now() until that date?
hi how can i create a template than can be used in autoentities card?
what are autoentities?
that doesn't mean it's a string. What's the entity, post it here.
sorry it is custom auto entities card , I came here because someone in forum said its possible by creating templete.I would like to add conditions for each bar card soo when value of sensor is 0 it does not show up(hide)
code: https://pastebin.com/DHqbdH0b
that's a loaded question, it depends on what you're trying to do.
I have like 5 sensors with sensor.app* the above code doesnot allow me to add contiditions for each bar card...is it possible by creating templates?
I want the bar to hide when sensor value is 0
sry, you are right, it's a date
it's the start_time attribute from a calendar entity
then your template is simply {{ (now() - state_attr('calendar.xyz', 'start_time')).days }}
the date was in the future (at least the example)
just use a state filter for the autoentities, no need for a template.
timedeltas are abs
unless i'm remembering wrong
remembering wrong, just reverse them then
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime' looks like it's a string afterall
{{ (state_attr('calendar.xyz', 'start_time') | as_datetime | as_local - now()).days }}
trigger:
- platform: state
entity_id: input_boolean.test
sensor:
- name: TEST sensor
unique_id: 70d778bc-f1d9-48bf-85fd-d4b475e842d3
state: >
{{ now() }}
attributes:
test: " {{ { 'test': now().isoformat() } }}"
test2: "{{ now() }}"
can I somehow save the date in the attribute of this example as a datetime?
test2 works fine, but the attribute test only works as a string
Result of current version```yaml
friendly_name: TEST sensor
test:
test: '2022-09-20T15:22:36.765224+02:00'
test2: '2022-09-20 15:22:36.765779+02:00'
result without .isoformat()
friendly_name: TEST sensor
test: >-
{'test': datetime.datetime(2022, 9, 20, 15, 24, 44, 436604,
tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam'))}
test2: '2022-09-20 15:24:44.436795+02:00'
test is not even a dict anymore
you can set test to a datetime, but it won't persist over shutdown
whatever you're using to view the information (assuming it's the states page) can't recognized unformatted objects so it it doesn't validate correctly
just use a state filter for the
got my doorbel sounds in an automation with an input_select.doorbell , i want to disable that automation to add seasonal/birthday doorbell sounds, bit baffled that there is no date trigger ... what's the best way to approach this ?ΒΏ
like on birthdays/halloween/x-mas disable default input_select.deurbel automation and run doorbell with seasonal sounds
@north locust posted a code wall, it is moved here --> https://hastebin.com/upucadecen
seems correct .. ?
hmm have to make multiple automations for my doorbell on all specific dates like halloween, all birthdays , can i put it into one automation somehow
You can use them template in the trigger, there is no need to let this automation trigger every day at 1:00
ah was just about to ask add multiple dates in template triggers, assign them trigger ids then change doorbell automation according to trigger id
like this but how do i change automation according trigger id
this should work i guess ΒΏ
https://hastebin.com/ipinuvikuc.yaml
can i assign the same trigger id like birthday to multiple date templates ?
yeeeeeeeeeeeees
nice thank you
like 4 birthday templates tied to one action
hmm how do i revert back to the default doorbell automation when those dates are over ΒΏ
hey everyone, I have a template sensor, that receives a phone number. Only problem: When using the sensor in the frontend, it is displayed with decimal points (eg. 123.456.789.000, when it should be +123456789000. HOw do I change that?
The phone number seems to be input as a string, this: https://hastebin.com/ofemesizir.yaml the yaml I'm using
you'll never get it to display + then the number
well, actually, the way youre doing it, you will be able to get it in the attribute as + then the number
but you wont be able to get it as the state as it will remove the +
- trigger:
- platform: event
event_type: sms.incoming_sms
sensor:
- name: newest_sms
state: '{{trigger.event.data.text}}'
attributes:
phone: "{{ {'number': '+' ~ trigger.event.data.phone.replace('.','')} }}"
date: '{{trigger.event.data.date}}'
then to access it
{{ state_attr('sensor.newest_sms', 'phone').number }}
the problem is, templates will resolve the type, and it will resolve a number. Which means it'll treat it like a number without the +
so you have to get around that.
the only way to get around that is to output a complex object that contains your value, which is what I just showed you.
your other option is to replace the .'s with - and add the + before it. If you're trying to make it clickable.
Thank you very much!
@prime sandal posted a code wall, it is moved here --> https://hastebin.com/gapigozude
It wasn't a code wall lol
Anyway, this is the view
class WarehouseDetailView(DetailView):
model = Warehouse
context_object_name = "warehouse"
it's a text wall
the bot counts the number of lines
over 15 lines -> codewall
anwyays, what your posting with the python code doesn't help
are you sure you're on the right server?
No XD
lol my. I just the search bar and thought it stayed on the server xD
Nana it's Django
Totally my bad haha
@thorny snow your product doesn't have an ammount
the product class only has name on it
Yeah it's the m2m field
Don't know how to access it from the template tho. I might just do a custom query
right, but it returns the product
.all would most likely return a list of products
which doesn't have that attribute
property*
Yeah, I have to figure out how to use m2m in templates
just do this
class Product(models.Model):
name = ...
amount = models.IntegerField()
you're passing the model into that object
or you have to make a new class for
class ProductWarehouseAmount(models.Model):
product = models.ForeignKey(Product, related_name="product", on_delete=models.PROTECT)
warehouse = models.ForeignKey("Warehouse", related_name="warehouse", on_delete=models.PROTECT)
amount = models.IntegerField()
def __str__(self):
return f"{self.warehouse} has {self.product} ({self.amount})"
a class where products have ammonts
and you call that object there for procduct=
then again, i've never used that api
so I could be wrong
short (maybe dumb question): In order to clean up my config, I moved all templates to a templates.yaml file, but now all template sensors stopped working. Is it not possible to move the templates?
it's possible to move anything anywhere for the most part, so you did something wrong with your configuration
yeah, found the bug just as you wrote π
I have some trouble with parsing a template value to a service.
service: fritz.set_guest_wifi_password
data:
device_id: 123456789123456789
password: >
"{{ states('input_text.password') }}"
The string in input_text.password is e.g. abcd1234.
The service is triggered, but in my FritzBox the password "abcd1234" (with quotes) is set.
If I remove the quotes I get the error "invalid value or type for dictionary value @ data['password']. Got None".
Can anyone give me a hint, what I have done wrong or how to get rid of the quotes?
remove the surrounding quotes. You don't need them
and use >- instead of >
or...just put it on a single line
service: fritz.set_guest_wifi_password
data:
device_id: 123456789123456789
password: "{{ states('input_text.password') }}"
I tried both. In both cases I get that error message.
fyi device_id doesn't need to be hidden from us, it's unique to you and it's meaningless for security to hide it
the only guidance that I can give is that you shouldn't include quotes surrounding the template in a multiline template
- Use the single-line form with surrounding quotes or
- Use the multiline form with
>-and no surrounding quotes
It works, if the string contains at least 1 character. If those are just numbers, it throws that error.
you have to do this then
it probably interprets it as an integer
service: fritz.set_guest_wifi_password
data: >
{{ {'device_id': '123456789123456789', 'password': states('input_text.password') } }}
That one is working. Thanks a lot!
You can probably move the device id to target to simpify it a bit
service: fritz.set_guest_wifi_password
target:
device_id: 123456789123
data: >
{{ {'password': states('input_text.password') } }}
can someone vouch me how to create a day counter?
from now - 1/12/2022 and output as number of days ( like "25")
{{ (now() - "2022-01-12 00:00"|as_datetime|as_local).days }}
thanks for quick response...it shows as -72 days for 2022-12-01..how to remove that "- " value?
also i want to use date helper to set the countdown....
is it possible to use something like this?(this does not work ..sorry Im newbe )
{{ (now() - {{ states('input_datetime.date')}}|as_datetime|as_local).days }}
that negative is correct, since you're starting in December
while I was starting in January
and yes, as long as you don't nest your templates like that
{{ (now() - states('input_datetime.date_test')|as_datetime|as_local).days }}
is it possible to do from date - now()?
i tried this but does not work
{{ (states('input_datetime.date') - now()|as_datetime|as_local).days }}
yes, you don't understand
okay i get it
{{ (states('input_datetime.date')|as_datetime|as_local - now()).days }}
the point of that is to modify the state
yeah
one last question..instead we use date with time ("2022-01-12 00:00") cant we use just date("2022-01-12")?
as_datetime wants a particular format
it should work
I don't think it did for me
as long as the order is the same
which is why I added tat
oh, I'm wrong. musta been doing something else
oh, I remember. I was using slashes as delimiters and it didn't like that
so I added a time, then changed the delimiters
is it possible to do this?
Tried with just date but no luck
{{ (now() - "2022-01-12"|as_datetime|as_local).days }}
-> 251
what were you doing?
and my input_datetime entity just had a date as well
Really no idea i just tried the same thing and it showed me error ": missing " something let me try again
this is all about attention to detail
Sorry ...let me try once power is back here π
Based on some advice I got here, I have an automation based off of {{ ((as_timestamp(now()) - as_timestamp(states.input_button.appliances_cleaned.last_changed)) / 86400) | int }}. However, it seems that sensor resets every time I start Home Assistant. Is there a way to get the time I press the input button to stick and keep counting up across restarts?
HA doesn't know what may have happened while it wasn't running, so that property resets on a restart. You can use an automation to store the current time in an input_datetime whenever the state changes and use that instead
or, even better, you can use a trigger-based template sensor
even better, the state of an input_button is a timestamp of the last time it was pressed π€·
so just use that
Yeah, is that not what states.input_button.appliances_cleaned.last_changed gives?
What you say is exactly what I was trying to do, but that seems to be what resets every time HA restarts.
no, states.input_button.appliances_cleaned.last_changed is not the state
it's the last_changed property
@inner mesa can you explain ms this part "2022-01-12"|as_datetime|as_local
I under now() generate somthing like 20220921004318
it takes a string, turns it into a datetime object, and then assigns it the current timezone
I don't know what you mean by
I under now() generate somthing like 20220921004318
that's not at all what it reports
{{ now() }} -> 2022-09-20 17:45:03.651568-07:00
Okay ... I did some google and took me to mysql funtions console page and it showed output somthing like that
quick question:
is it possible to define a sensor template with one or more attributes?
I mean, other than the state value, for writing less code i need to have also another value in the same sensor (ie: a string with an html color)
is that possible, or i need 2 sensor templates (value and html color)?
You can have multiple attributes in a template sensor.
how would i add a time to this ?
{{ now().month == 4 and now().day == 11 }}
you're going to have to elaborate on that.
now() >= today_at(12:00) and now().month == ...
probably easier to just do a time condition.
seeing that you have all those template triggers.
ah thank you !
@woven folio
template:
- sensor:
- name: ...
unique_id: ...
state: ...
icon: ...
attributes:
attribute1: {{ template }}
hmm cannot save this in automation...
"{{ now() >= today_at(14:30) now().month == 9 and now().day == 21 }}"
sorry, need quotes around the time
my mistake
You're also missing the and
hmm
"{{ now() >= today_at(14:30) and now().month == 9 and now().day == 21 }}"
still not accepting it π
cause you didn't do what I said π
see this
single quotes btw, because you have double quotes as the exterior quotes
hey guys, when doing a value.split the first part is index [0], correct?
yes
can i # out conditions or triggers in automations ?
In yaml, yes
nice thnks
got my seasonal doorbell switching doorbell sounds now , but how would i get it to switch back to the default bell automation after a certain date ?
If i wanted to aggregate a couple of energy sensors how would i do that?
For triggers you can also use enabled: false to disable them
Oh, that works for conditions as well
The same as you did too enable the seasonal sound
Yeah, was just looking. Triggers, conditions, and action steps
I found it in the automation trigger docs
Seems it is not added to the condition docs
But I could add it in the GUI
Ah, oh course. I was looking here, without actually reading the contents https://www.home-assistant.io/docs/automation/condition/
I have this template:
{{ expand('group.bedroom_lights')|map(attribute='entity_id')|list }}
I'm trying to remove one entity_id from that list, what's the correct way to do it?
I could use replace but that doesn't seem right
I'm looking at the jinja docs and it seems like I need to use rejectattr
depends where you place it
Before the map filter you can use rejectattr('entity_id', 'eq', 'light.not_this_one')
After the map you can use reject('eq', 'light.not_this_one')
When should I encapsulate variables in a namespace?
If you need to reference it both inside and outside of a loop
So if I set a variable outside a loop, then try to modify it inside and then access it after the loop it wont work?
Correct
Ahh, cool. I didn't know that, thanks π
Another question. I have a feeling this could be done with a filer somehow?
Instead of creating a new list, just filter the original one?
{% for price in prices %}
{% if price.end > now() %}
{% set ns.prices = ns.prices + [price.value] %}
{% endif %}
{% endfor %}```
{% set items = [
{"price":1, "end": now() + timedelta(minutes=1)},
{"price":2, "end": now() + timedelta(minutes=1)},
{"price":3, "end": now() - timedelta(minutes=1)}
] %}
{{ items|selectattr('end', 'gt', now())|map(attribute='price')|sum }}
-> 3
I knew it π I'm coming from the traditional (php) style of coding, where can I find a reference for the template language?
It's Jinja2 right? Like the map() you're using, where I can read how that works?
in the channel topic
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 https://www.codepile.net/ or https://paste.debian.net/ to share code or logs
ππ»
Is there any way to write several commands/lines within a single {% %} block or do I have to wrap everything?
you need to wrap each logic statement with {% %} and each output statement with {{ }}
I can't do this somehow?
{% set prices = states.sensor.nordpool.attributes.raw_today + states.sensor.nordpool.attributes.raw_tomorrow
| rejectattr('value', 'in', [None])
| rejectattr('end', 'lt', now())
| list
%}```
You can. That's just logic, and it's one line
No, it outputs nothing
It sets the prices variable
I didn't check your logic
I don't know what's in that attribute
A string like this: 2022-09-21 01:00:00+02:00
there's no "end" or "price" in that
or "value"
I'm talking about this: states.sensor.nordpool.attributes.raw_tomorrow
'start': datetime.datetime(2022, 9, 21, 0, 0, tzinfo = zoneinfo.ZoneInfo(key = 'Europe/Stockholm')),
'end': datetime.datetime(2022, 9, 21, 1, 0, tzinfo = zoneinfo.ZoneInfo(key = 'Europe/Stockholm')),
'value': 2.77
}
That's one element from the prices array
this works fine for me:
{% set items = [{
'start': "2022-09-21 00:00"|as_datetime|as_local,
'end': "2022-09-21 01:00"|as_datetime|as_local,
'value': 2.77
}] %}
{% set prices = items
| rejectattr('value', 'in', [None])
| rejectattr('end', 'lt', now())
| list
%}
{{ prices }}
I suggest breaking down the expression on your system to see what's wrong
I get an empty list, and if I change the "end" date to '2022-09-23 01:00' I get that entry
Could it be that my list have the datetme.datetime() as a string and you're converting it to an object?
that is an object
from my example (which you can also try)
{% set items = [{
'start': "2022-09-21 00:00"|as_datetime|as_local,
'end': "2022-09-23 01:00"|as_datetime|as_local,
'value': 2.77
}] %}
{{ items }}
->
[{'start': datetime.datetime(2022, 9, 21, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles')), 'end': datetime.datetime(2022, 9, 23, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles')), 'value': 2.77}]
Found the issue.. I was merging two lists: list1 + list2 | .... Of corse it applied the filters to the last list then merged. Wrapped in () it works π
Ping on this since i donβt know where to start
clear
if by "aggregate" you just mean "add them together", it's easy
{{ states('sensor.foo')|float + states('sensor.bar')|float }}
Yeah i mean add the values together. And get history for it
make a template sensor out of that
So that i can use it in my energy dashboard as well
if you add the proper fields when you create the template sensor, yes
which is a topic for #energy-archived
Haha, #energy-archived sent me here
creating a template sensor with a variant of that template is straightforward
ensuring that it has the right units and class and such is something that #energy-archived can help with
Ok
@proud cradle posted a code wall, it is moved here --> https://hastebin.com/ukowovapev
you didn't actually use the optimization I provided initially
so...
and you have a ton of stuff in that namespace that doesn't need to be there
Just thought I should keep all variables in one place but that's bad practice with the namespace
you don't need the namespace at all if you do what I suggested in teh beginning
you asked, then didn't actually use it
@proud cradle posted a code wall, it is moved here --> https://hastebin.com/oyehevujif
[Rule #6](#rules message): Please do not post codewalls (text longer than 15 lines, including whitespace) - use sites such as http://pastie.org/ (select YAML for the language), https://dpaste.org/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
Please take the time now to review all of the rules and references in #rules.
you don't need both "prices" variables - you can just add the two filters to the first one
I don't understand what "threshold" is doing there
Tried but it really do not like that:
UndefinedError: 'float object' has no attribute 'value'
you did something wrong
That's for sure π
{% set rawPrices = (states.sensor.nordpool.attributes.raw_today + states.sensor.nordpool.attributes.raw_tomorrow)
| rejectattr('value', 'in', [None])
| rejectattr('end', 'lt', now())
| map(attribute='value')
| sort
%}
Ahh it was the | list that was the problem
The threshold variable is the 25 percentile of the list
ok
Thanks for all the help @inner mesa π
whats wrong here
{{float((('sensor.energi_data_service','today_min')+(('sensor.energi_data_service','today_mean')--('sensor.energi_data_service','today_min')) / 2 )) }}
A lot
You are not getting the state of these sensors
And you are only applying the float filter once, while all states are strings
multiple minus signs
in a row
{{ (state_attr('sensor.energi_data_service','today_min') + state_attr('sensor.energi_data_service','today_mean') - state_attr('sensor.energi_data_service','today_min')) / 2 }}
Ah wait, these area indeed attributes, no float filter needed
TypeError: unsupported operand type(s) for /: 'dict' and 'int'
also, removing the parentheses as you have done, changes the math I'm trying to do
your parenthesis were all out of whack, so I made a guess
also, if you're getting that error, that means the values you're trying to add aren't numbers
take a screenshot of sensor.energi_data_service in the developer tools -> states page in the grid below. Make sure to include the attributes.
@toxic raptor Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
no, you are right. today_min contains both a timestamp and the value i'm after, "price"
That wont fit on my screen, nor as text in this text box, and it appears i cant attach a document or image either?
edit; these should be the important bits:
today_min:
hour: '2022-09-21T04:00:00+02:00'
price: 2.765
today_max:
hour: '2022-09-21T19:00:00+02:00'
price: 5.344
today_mean: 3.534
tomorrow_min:
hour: '2022-09-22T13:00:00+02:00'
price: 2.566
tomorrow_max:
hour: '2022-09-22T19:00:00+02:00'
price: 5.581
tomorrow_mean: 3.608
Thatβs why the bot had a link to the share site π
Really?
Why tf should I help you if youβre gonna be an ass
I'm sorry? I don't know what you're offended by
I have a template trigger with multiple sensors. Is it possible to get the area name of the device which actually triggered and should be stored in the trigger variable?
yes
trigger:
- platform: state
entity_id:
- sensor.sensor_1
- sensor.sensor_2
to: ~
variables:
area: "{{ area_name(trigger.entity_id) }}"
great thank you
I'm trying to create a variable where the first characters is an *
yaml does not appear to like this. How can I escape it. I've tried using single, double and backslashes
dkim_line: "*@{{ dkim_domain }} {{ dkim_date }}._domainkey.{{ dkim_domain }}"
does this maybe work?
dkim_line: "{{ '*@' ~ dkim_domain ~ ' ' ~ dkim_date ~ '._domainkey.' ~ dkim_domain }}"
Hello iam trying to create an entity wherin 2 time values are substracteted. am i thinking in the wrong way?
http://pastie.org/p/1SK36dKBKOE7EidKqV9WVH
"{{ (states('sensor.arbeit_start') | as_datetime - states('sensor.arbeit_ende') | as_datetime).seconds / 60 }}"
that easy?
How can I get all light entities from MQTT integration ? Is that possible ?
should be
{{ integration_entities('mqtt') | select('search', '^light.') | list }}
Hello people from templates π Can someone point it out what in doing wrong here? I want to write the value that is in the template to helper in automationservice: input_number.set_value data: value: | {{ (state_attr('sensor.new_home_to_work_2', 'duration') |string).split('.')[0] }} target: entity_id: input_number.slider
@mighty ledge thanks a lot, this I have been searching for 1 hour
Β΄integration_entities('mqtt')Β΄
You should have looked in the docs π€£
I have but must have missed it
Need new glasses π€£
the template docs need to be broken out by method
value: "{{ state_attr('sensor.new_home_to_work_2', 'duration') | int }}"
Thanks will try when i will get home π
I have this template
unique_id: livingroom_heater_daily_consumption
unit_of_measurement: kWh
device_class: energy
state_class: total
state: >-
{% set a= (states('sensor.livingroom_left_day_consumption') | float(0) ) %}
{% set b= (states('sensor.livingroom_right_day_consumption') | float(0) ) %}
{{ '%0.3f'|format(a+b) }}
availability: >-
{% set sensors = ['sensor.livingroom_left_day_consumption', 'sensor.livingroom_right_day_consumption' ] %}
{{ expand(sensors)|rejectattr('state', 'is_number')|list|length == 0 }}```
That i want to re-use for a bunch of different energy sensors. The problem is that i will add a lot more sensors in the template and since they are both used in the `state` part and the `availiability` part thatβs gonna mean i have to repeat a lot of code. Is there anyway to move them to a variable somehow, so that they can be reused in both parts of the template sensor?
Obviously it works inside of the `state`part (since i do it with a and b) but iβm not sure if it works for the whole sensor?
(Also how do you do inline code blocks in discord?)
is it possible to only update a template sensor if one attribute of a certain event has a specific value (reason: I'm receiving status updates from different devices vis sms and sort those messages into different template sensors) I'm currently using a trigger template sensor to store the newest received sms message but of course that's not very device specific
only way is using anchors, and it doesn't really decrease the amount of yaml
- trigger:
- platform: state
entity_id: &xyz_entities
- sensor.x
- sensor.y
variables:
entities: *xyz_entities
sensor:
- state: &state >-
{% set value = expand(entities) | map(attribute='state') | map('float', 0) | sum %}
{{ '%0.3f'.format(value) }}
availability: &availability >-
{{ expand(entities)|rejectattr('state', 'is_number')|list|length == 0 }}
- trigger:
- platform: state
entity_id: &abc_entities
- sensor.a
- sensor.b
variables:
entities: *abc_entities
sensor:
- state: *state
availability: *availability
I'm dumb today, figured it out π
EDIT: I'm really dumb as it doesn't work as expected
you can only do it with a trigger template sensor
What does &xyz_entities and *xyz_entities do?
those are yaml anchors
would you mind giving me a little hint? π
makes a variable, plops in in another spot. & declares it, * plops it
look up
But in the rest of your code you donβt write xyz, you just write entities?
Also are yaml anchors specific to a sensor or to a file?
- trigger:
- platform: template
value_template: "{{ state_attr('sensor.xyz', 'attr') == 4 }}"
sensor:
- name: ...
state: >
{{ your template }}
yes, because those are separate from anchors
trigger variables have nothing to do with yaml anchors
are you able to distinguish yaml from templates?
Right, thats what i meant
{% jdalfkjsal %} {{ }}
Ish
that's the code
&something and *something are yaml only items, and they do not affect templates (Jinja, i.e. {{ }} and {% %})
all they do is copy the contents from the & and paste the contents where the * is
essentially
the trigger itself has entities variable
that's where the entities in the code is coming from
would it be possible to instead of sensor.xyz use event data? π
yeah, that was a mistakt sorry
if you want event data, you'd have to go a different route
Rn, I would think Trigger Template Sensor that reacts to every event (S1, storing Message and Phonenumber) -> Trigger template sensor that only reacts if the "phonenumber" attribute of S1 is a specific one would be a good way accomplish my goal?
or would there be a better way?
So, I'm trying to use this here "{{state_attr('sensor.newest_sms', 'phone') == !secret phone_sprinter }}" template but it doesn't work because of the whole !secret part. Is it possible to a secret here?
No
Where are you using this? If it's an automation, script or trigger based template sensor, you can put the secret in a variable
That's true. You can only use a secret in a value for a key
in the end, I settled on just using# the value, not a secret. However, it still doesn't work. https://hastebin.com/bowabuceve.yaml is the code I'm using but I don't really find any miskates and no error logs
Is the attribute a string or an integer? I'm guessing it's a string
So you need to surround it in quotes
well, I'n not quite sure actually but yesterday I had a problem, where the phone number was displayed with decimal points (eg. 123.456.789 instead of 123456789)
I dint know what to say about that
You can test it in
> templates
{{state_attr('sensor.newest_sms', 'phone') is string }}
it seems like the number is stored as an integer
Representing a phone number as an integer would be weird
{{state_attr('sensor.newest_sms', 'phone') is integer }} -> true
Then it's a string
oops, wrong
And you need to use quotes around it in your comparison
there should be integer, not string
{{state_attr('sensor.newest_sms', 'phone') is integer }} -> true
{{state_attr('sensor.newest_sms', 'phone') is string }} -> false
would be the correct thing
Ah, okay
sorry
Did the attribute change, or was the previous sms from the same number?
previous sms was from the same number
Then it won't trigger, as the template was already true
oooh
It has to change from false to true
well, then sadly the whole thing doesn't fit my need. See, I'm trying to receive gps position data from certain devices over sms (there is only a 2G network and no wifi where these devices are located and mobile data is kinda expensive compared to an sms flat). Location data comes in from multiple devices and I'd like to update a sensor for each device if new location data comes in from that specific device (but like every time new data comes in, even if there's data two times in a row from the same device)
- trigger:
- platform: state
entity_id: sensor.newest_sms
attribute: date
variables:
number: !secret phone_number
sensor:
- name: sms_sprinter
state: "{{ trigger.to_state.state if trigger.to_state.attributes.phone == number else this.state }}"
icon: mdi:message-text
attributes:
date: "{{ trigger.to_state.attributes.date if trigger.to_state.attributes.phone == number else this.attributes.get('date') }}"