#templates-archived
1 messages · Page 144 of 1
feed count is an entity right?
I'm struggeling with the parametrization of a time condition. I have a string with a time 08:00:00 that im parsing into a template sensor
"{{ as_timestamp(today_at(states('sensor.alarm_clock_we_end'))) }}"If i read the value of the template sensor i get 1640073600.0 which seems ok
However when i put this sensor into a time condition the automation does not work. I don't get an error but the condition always returns false... and i don't see any values in the trace. Anyone an idea on what I'm doing wrong? If i use input_datetime it woks flawless so the automation logic seems ok.
what condition?
weekday:
- mon
after: 00:00:01
before: sensor.my_template_sensor
does it have a device_class: timestamp?
if i check the values of sensor.my_template_sensor it only has 1640073600.0 as its state
i tried to define device_class: timestamp in the template but then HA was giving a lot of errors during template initialization
you'll need to fix those
device_class: timestamp
value_template: "{{
as_timestamp(today_at(states('sensor.alarm_clock_we_end'))) }}"`.```
like this?
should be
hmm the moment i add device_class: timestamp to this one sensor i get a lot of errors in the log and the sensors disappear
hmm the error messages are related to other integrations, but still the sensors does not load after adding the device_class
for "{{ as_timestamp(today_at(states('sensor.alarm_clock_we'))) |timestamp_custom('%H:%M:%S')}}" i can define device_class: timestampbut for as_timestamp(today_at(states('sensor.alarm_clock_we'))) }}"
the same fails. but if i put the first one into the time condition I again end up with always false
looking through the docs, it says this:
timestamp: Datetime object or timestamp string (ISO 8601).
so I guess it's not actually a timestamp as an integer
i don't understand 😢
you need a datetime or a string
and you have a string
just stop turning it into a timestamp
{{ today_at('06:00').isoformat() }}
do that
i have three templates: sensors:
- the original string containing 08:00:00
- timestamp_custom wich also renders as 08:00:00
- the timestring wich reads 1640073600.0 as its state
neither works if i input this in the before:XXXXX section of the condition
if i manually enter a fixed value of an input_datetime it works
did you do what I suggested?
I'm on it, give me a sec 😄
i created the sensor as you suggested and i can read its content as
2021-12-22T09:00:00+01:00
but if i put this sensor into the before field on my condition it again only returns false
and what i realy dont understand: if i check the step details: for conditions with fixed values and input_timedate i can see details of the check
after: input_datetime.motion_night_mode_arbeitszimmer
before: '23:59:59'``` ```Result:
after:
__type: <class 'datetime.time'>
isoformat: '23:00:00'
now_time:
__type: <class 'datetime.time'>
isoformat: '00:42:42.235567'
before:
__type: <class 'datetime.time'>
isoformat: '23:59:59'
result: false```
for conditions having the template sensor i only get
before: input_datetime.motion_night_mode_arbeitszimmer
result: false```
HOLY SHIT! it works, i forgot to define the deice_class on the new sensor
THANK YOU @inner mesa !!!
I'm attempting to imitate a "breaker panel" on my lovelace dashboard.
I have made template switches, and they work great. I have made matching input_booleans that are tied to the template switch so that if the input_boolean is off, the turn on command is ignored. This accomplishes part 1.
However. Is there a simple way (without making a separate automation) to have the switch also turn off if the input_boolean is turned off?
This is my template switch: rm_air_con: friendly_name: "Air Conditioner" value_template: "{{ is_state('switch.rmaircon','on')}}" turn_on: service: switch.turn_on data_template: entity_id: > {% if is_state('input_boolean.rmaircon_breaker', 'on') %} switch.rmaircon {% else %} switch.null {% endif %} turn_off: service: switch.turn_off data: entity_id: switch.rmaircon
can I add something to that template switch to make it turn itself off if the input boolean is off?
Hi, to convert some attributes from minutes to hours, do i need a template?
I have an entity for vaccum that shows its Brush usage, filter usage etc but its reading in minutes and i need to convert to hours
i think i need to make a sensor for each attribute first?
Where do you need to see this? You could use a template in the markdown card in the front end rather than create sensors.
i have a vaccuum card
shows the hours but looks like minutes, in my vac app they show as 84 hours, 236 hours and 56 hours
That looks like the #integrations-archived is misconfigured I would think.
(Or written such that it's calculating the times wrong.)
Oh ok, I can check into that i guess, im a little bit of a noob
Its this https://github.com/Ligio/hacc-ozmo
and using this card https://github.com/denysdovhan/vacuum-card
No, but why are you using an input boolean. I'd wager there's a better way to handle the end goal instead of using an input_boolean.
I have a problem this morning: My netatmo devices are unavailable which is a pain as I am using them as my sensor for my generic thermostats. What I would like to do is use a template to use that sensor, and if it's not available, fallback to getting all the sensors in the area and filtering them for availability/none and then averaging them out.
Currently I have this: https://paste.debian.net/1224418/. I'm hardcoding the sensors though, and wondering if I can/should dynamically get the other sensors? And/or is there a better way to do this?
There's trade offs to dynamically getting a list of sensors
first and foremost, you need to understand how templates work
if you use just states in your template without a domain, i.e. states.xyz, the template is throttled to at most 1 update per minute
if you use states.sensor you have the same restriction
if you use states.anyotherdomain you're throttled to at most 1 update per second
so whenever you dynamically look for sensors, you're going to cause that template to update less frequently
unless you make an automation that creates a group
using a list of entities has no throttled updates
Aha, that is really useful to know!
Hi, I'm trying to get a button to start a timer based off of the (minute) value of a slider in a card. The template i have is testing correct in the template test tool, but i'm getting error when pushing the button to start it . can someone advise please?
- type: button
tap_action:
action: call-service
service: timer.start
service_data:
duration: >-
{% set t = states('input_number.heating_timer') | int %} {{
'{:02d}:{:02d}:{:02d}'.format(t // 60, (t % 60) , (t % 60) // 60) }}
target:
entity_id: timer.heating_timer
entity: timer.heating_timer
name: Boost
icon: mdi:radiator
error is
'''
Failed to call service timer/start. offset {% set t = states('input_number.heating_timer') | int %} {{ '{:02d}:{:02d}:{:02d}'.format(t // 60, (t % 60) , (t % 60) // 60) }} should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' for dictionary value @ data['duration']
'''
anyways, I dynamically create groups on restart, at midnight, and on template restart using states or states.domain.
Then in templates I use expand on the group
Oh genius. I will check your repo!
does this mean that templates don't work in service requests?
you can use this trigger
- platform: time
at: '00:00:00'
- platform: homeassistant
event: start
- platform: event
event_type: call_service
event_data:
domain: template
service: reload
with group.set
in an automation
The closest I have are counters for domains that behave the same way
in your case, you'd be making an automation
You can't template in Lovelace
Well you can, just only in the markdown card.
tap actions do not accept templates
So I'd use something like {{ states.vacuum | default([]) | count }} from there but switch vacuum to sensor and filter for the area and temperature?
I'd just make a temperature sensor list
Also, change the trigger to reload on groups
- platform: time
at: '00:00:00'
- platform: homeassistant
event: start
- platform: event
event_type: call_service
event_data:
domain: group
service: reload
and the service woudl be something like
- service: group.set
data:
object_id: my_temperature_sensors
entities: >
{{ states.sensor | selectattr('name', 'search', 'temperature') | map(attribute='entity_id') | list }}
ah ok 😦 bugger. any idea how i can do what i'm trying to do? (trying to make a 'boost' for my office heater so that it turns on for a defined amount of time)
Well you just wrote the whole thing right there for me, brilliant!!
eh, change 'name' to 'entity_id'
Excellent, and I can easily filter out window sensors with this too (those tend to be a lot colder than the other sensors so skew the average)
Make a script
I use scripts and/or input booleans/numbers/selects for this sort of thing. Then I set the input_XXX to whatever which triggers an automation.
script:
start_timer:
sequence:
- service: timer.start
target:
entity_id: "{{ timer }}"
data:
duration: >-
{% set t = states(number) | int %}
{{ '{:02d}:{:02d}:{:02d}'.format(t // 60, (t % 60) , (t % 60) // 60) }}
then call it in lovelace...
- type: button
tap_action:
action: call-service
service: script.start_timer
service_data:
timer: timer.heating_timer
number: input_number.heating_timer
entity: timer.heating_timer
name: Boost
icon: mdi:radiator
So some of my buttons are like this:
type: button
tap_action:
action: call-service
service: input_select.select_next
service_data: {}
target:
entity_id: input_select.electric_blanket_time_off_options
show_icon: true
show_state: true
entity: input_select.electric_blanket_time_off_options
show_name: false
And then an automation watches the input (select) in this case and adjusts things to that.
thanks. does that need editing to include my number/timer objects?
ah, let me editit
no, its fine. sorry i didnt mean for you to do more work. . i just didnt know if using the other terms would be replaced from the calling it in lovelace or not.
there's a million different ways to do what you want
I tend to script everything
because I like buttons and don't like dropdowns
scripts are easy to call from buttons, but you have to put your logic in the scripts
case in point, @silent seal does something different than i
In the example above, the input select has None, 5, 10, 15, 20 as the options, if it's set to anything other than None then the automation sets input_datetime.electric_blanket_off to {{ now() + timedelta(minutes=(states('input_select.electric_blanket_time_off_options')|int)) }}, which works perfectly for me. But that's because I created it for my use case. Elsewhere I might do what Petro does and call a script.
I’m open do ideas, I’m using an input Boolean because I need 3 entities. The real switch.entity, the Template switch (for the manipulated layer that can but not always turn the real switch on and off (this is the entity used in node red flows) and then I need the toggle that makes the template switch be enabled/disabled from Function
What is the problem you're trying to solve? This sounds complex, and there might be an easier way.
see what @silent seal said
I have switches I use in node red flows (like if room is too hot, call service turn on switch.rmaircon. I have a few different flows that might turn on this aircon.
It might be better to use events for those.
I also want a “panel” where I have a “toggle” that prevents switch.rmaicon from being functional, and when it’s turned off i would like it also to turn off
What changes that toggle?
Like walking over to a breaker panel and flipping a breaker to off. I want to hard kill the switch until it’s re enabled.
I do
You only change that manually?
When I’m servicing something like my fish tank need to turn off the pump and make sure nodered can’t turn it back on when my face is in the tank
That makes sense to have as an input boolean that you use as a validation check then.
And then when I’m done in the tank I will turn back on the toggle
I also will take advantage of the template switch if equipment is being replaced
If I change pumps, all of the instructions can be fixed by changing just the entity Id referenced in the template switch with one adjustment and no reason to change nodered flows
But like a breaker, flipping the validation check should also turn it off. But flipping validation switch back to on, should not turn the template switch to on, only allow it to be functional going forward
(It’s ok if it were to resume the previous state but that doesn’t matter, my flows makes sure the pump is always on if it’s off when it shouldn’t be)
Just not sure how to make the template switch become off and not just(only) “incapable of sending a turn_on” when I flip the input Boolean
If I’m about to work in the tank turning off input Boolean should turn off the pump as well if it’s on, but I don’t want to write flows to do this, it will take hours
(I have about 40 diff entities)
Well, automations are likely easier for this sort of thing to be honest.
with everything you've said, I'm not sure where 'turning off the boolean ' comes into play if you're manually turning it on. Wouldn't you manually turn it off too?
Yes but it (the template and actual switch) might be on currently
It should shut off when the input Boolean is disabled too
I turn off and on the Boolean I just don’t want to also have to go look if the template switch is off too.
You're not disabling it, you're setting it to true or false
Correct
But I would like to be disabling it
But I am currently just disabling the turn_on service
You can't. You need to check after the trigger is received if it should be run
So:
- trigger
- can I do this?
- Yes: do the thing
- No: Don't do the thing.
Well you technically can disablei t
With an automation you'd make it a condition that your override has to be on.
by making it unavailable
Correct but also trigger received, was the room already in an on state? Also Turn the state to off
Currently I use an ovveride input Boolean but a single one for the entire room
But before you do that, check if it should be running, and if not, just end.
So when I flip it to ovveride none of the flows can trigger - but I don’t want to make new overrides for every switch and also add specific overrides for each flow use if I don’t have to
And this also wouldn’t add the turning off if on either
How are you triggering the flows again?
Different sensor values, temp goes above this threshold, etc
real world example.
If water temp goes above 67, turn on switch.pump1
So that's reading directly from a device?
If water level goes below “ok”, turn off switch.pump1
If water level is above “low” (ok or optimal) , turn on switch.pump1, things like this
State:event flows. <those are my flow examples>
So it seems the template switch can’t react to the status change of the input Boolean unless it’s being done by a secondary automation
(Yes react would be an automation, but it’s more like state being forced to off due to the input Boolean being false that i would prefer)
That’s why I thought at the top of the template switch I could set (override) it’s value based on the input Boolean if false
(The disabling of the turn on service works great, by dead ending it)
You might have better luck asking in #node-red-archived, but I think your first action in any of those flows ought to be to check if your override boolean should prevent the flow from running.
Yes I do that
But that’s not the part I’m working on, that is essentially solved
It’s the turning off or forcing the status to be off (of the template switch), when the Boolean is false
But making 40 flows just to support this function is a lot of extra work that I would hope the template can accomplish on its own
if you want the state of the switch to be off when the input boolean is off, add it to the value_template
Correct - how can I accurately do that, my attempts haven’t worked
just add it as part of the logic, but only you'll know the logic
I assume right after >- and before the defining of the turn_on service, I can use an If statement
yes, add it to the template
Let me show you my attempts
do you want the switch to be on when both the input boolean and source switch are on?
and off otherwise?
@low blaze posted a code wall, it is moved here --> https://hastebin.com/ahinudeqec
value_template resolves to on
or true
for it to be on
so you're telling it to be on never
youre trying to tell it when to be off, you need to tell it when to be on
My template switch does not tell the real switch to be or become on
it only prevents the service turn_on from being functional or is off due to the boolean being false
your previous example showed you using a switch.aircon something or other
if the state of your switch is identical to the the state of the input boolean, then just grab the state and output that.
"{{ states('input_boolean.xyz') }}"
you're over complicating it
well i dont want my boolean being on to effect the template switch's status
only the template switch's turn_on ability
you just said you did
sorry i didn't meant o confuse
what do you want the state of the switch to be
if you're just trying to disable all functionality to a switch, then all you need to do is add a condition to the turn_on/turn_off services
I'm about to go into my tank. I don't know if the pump is on or off (that's a decision the tank makes all day long for different reasons). I want to flip the boolean to off, and when I do that - the pump should both not be able to be turn on, and also become off, if on.
So real switch.pump
template switch.thisisthetemplateswitch_pump
and boolean.thepump are the 3 entities
all day long, different flows send turn_on service calls to template switch.
template switch does its normal job unless I flip the boolean to false.
- platform: template
switches:
wrapped_pump:
value_template: "{{ states('switch.pump') }}"
turn_on:
- condition: state
entity_id: input_boolean.enabler
state: 'on'
- service: switch.turn_on
target:
entity_id: switch.pump
turn_off:
- condition: state
entity_id: input_boolean.enabler
state: 'on'
- service: switch.turn_off
target:
entity_id: switch.pump
yes that is what i have works great
just that turning boolean to false does not change switch.pump to be off
(also). it does and I want it to correctly do what you put there
just need the additional part
oh
I see
you did put it ther
its the condition line
thank you let me try that
that won't turn it off though when it turns off
wait sorry I'm confused
sorry to bother you again but i'm getting "Message malformed: extra keys not allowed @ data['script']" whenever i try to save the script
remove the word script if you're adding that to scripts.yaml.
is the condition use better than the if and dead end of the entities way I did it?
yeah i tried that. i'm adding to scripts in the gui.
either that or you remove the boolean and replace it with a template switch
ah ok. I think I understand. I can't both allow the switch to be "toggle/used" to chang it's own state - and also tell it what state (off sometimes) to be
do they take different formats?
no, script is the location it goes in configuration.yaml
If I remove the boolean and replace it with a template switch, would I lose he validation or no?
if you're using the UI, it's not needed
so I would have 1 switch, and 2 template switches
that's fine, even preffered - less helper creation
you'll still need the boolean to store the state of the template switch, you'll just use the template switch as the boolean instead and have it linked to the boolean
- platform: template
switches:
enabler:
value_template: "{{ states('input_boolean.enabler') }}"
turn_on:
- service: input_boolean.turn_on
target:
entity_id: input_boolean.enabler
- service: switch.turn_off
target:
entity_id: switch.pump
turn_off:
- service: input_boolean.turn_off
target:
entity_id: input_boolean.enabler
ah and the second template switch will turn off the 1st AND change the boolean
GREAT IDEA
ih ave lgoic reversed
there, edited
but you can turn the pump back on if you want in the turn off of the enabler
Personally, I'd create a single automation using templates that does all of that without the wrapper for each switch
I don't need to turn the pump on when I re enable
Just turn off if on when I disable
one of my pumps might be off when i disable it, I don't want to turn it on when i Re enable
if you name your switch pumps and enablers the same
1 automation can do everything without the need for a new wrapped switch
yes but I'd need to make 40 automations
no..
and a new one each time i add a switch/device
(I have at least 40 of these "pumps")
(they are not all pumps)
I'm ok with creating 1 boolean and 2 helper template switches for each real switch, just would like to do that rather than make 1 boolean, 1 helper template switch AND a flow/automation for each real switch
as template switches are easier to make than an automation
- alias: My turn offer
mode: parallel
trigger:
- platform: state
entity_id:
- list
- input_booleans
to: "on"
action:
- service: switch.turn_off
target:
entity_id: switch.{{ trigger.entity_id.split('_')[-1] }}
that will do everything if you name your input booleans
input_boolean.enable_pump
if your switch is named
switch.pump
so i'm on your page. That single automation will do this function for all booleans/template switch combinations
🙂
this why node red is bad IMO. It takes away your ability to think in bulk and forces you to think like '1 automation per entity`
agreed, thats why i came here because it was clear that node red was not the efficient way to accomplish this function even though an automation was the correct logic for doing it
yes it will as long as you name your helper and switch accordingly
(I haven't made any of the 40 I need, so a proper naming scheme was intended anyway)
example: You bought a pump for your living room... input_boolean.enable_livingroompump and switch.livingroompump
if you want to use _ in the names of the entities, then you might want to use something else as the separator
e.g.
- alias: My turn offer
mode: parallel
trigger:
- platform: state
entity_id:
- list
- input_booleans
to: "on"
action:
- service: switch.turn_off
target:
entity_id: switch.{{ trigger.entity_id.split('enable_')[-1] }}
I only used _ in the name of the entity so that I could differntiate between the template switch and the actual switch easily when making flows
this automation doesn't elminate the use of the template switches, only assists them right
it removes the need for the second template switch
got it yes.
so, i'd use the one I just posted
I'm reading it to see if I understand how it works (I understand what it does)
then name everything input_boolean.enable_x_y_z with switch.x_y_z
then you can use _ in your entity_ids and it'll work regardless of the number of _ you use
awesome
so triggered by a state change of any of these input booleans, in this "list" - turn off matching switch
list is defined as input booleans that contain 'enable_'
and switch to turn off (entity) is defined by the name of the boolean
Yeah just list out every input boolean
oh in this automation? I add them
and then come back to them each time I make one and add it? I thought above you meant it will be dynamic
You only have to list the booleans, the switch is dynamically chosen based on the input booleans name
Yep
- input_booleans
would be
- input_boolean.x_y_z1
- input_boolean.x_y_z2
and so on, not the word "list"
Yes but they need to be named input_boolean.enable_x_y_z
For the automation to work
You can name them the same too if you want
But the automation changes
so ```- alias: My turn offer
mode: parallel
trigger:
- platform: state
entity_id:- input_boolean.enable_t1_pump1
- input_boolean.enable_t1_airconditioner2
- input_boolean.enable_t2_pump3
to: "on"
action:
- service: switch.turn_off
target:
entity_id: switch.{{ trigger.entity_id.split('enable_')[-1] }}```
No
Yes but you need to understand that the enabled needs to be in the entity id of the input boolean
and switch.t1pump1 would exist (real switch) and switch.t1_pump1 is the template switch
So when you create the helper, that needs to be included
if you think that's too much, you can name them exactly the same
but the automation will change
I followed this, I just forgot it when typing that. I know that the entity id being used in the automation is defined by the fact that it can predict the entity id
if you want to not deal with naming them 'enable_'
naming them enable is fine, because it also helps identify the function of these booleans from a bunch of others
- alias: My turn offer
mode: parallel
trigger:
- platform: state
entity_id:
- input_boolean.t1_pump1
- input_boolean.t1_airconditioner2
- input_boolean.t2_pump3
to: "on"
action:
- service: switch.turn_off
target:
entity_id: switch.{{ trigger.entity_id.split('.')[-1] }}
I have other uses for booleans, this makes them easier to filter for when working in the entities list, etc
as long as the switches are named
- switch.t1_pump1
- switch.t1_airconditioner2
- switch.t2_pump3
yup
yes I see
curious tho
why does it need to split anyway? wouldn't splitting after the . be just as functional if the word enable is used in the name or not?
or does the re-use of "enable_" throw off the template unless it is accomidated for
No because the object ids are not the same
Enable is in the object id for the inputboolean it’s not in the switch
Hence why it’s removed
oh
got it
perfect I follow
the switch's identity is being generated, so it has to drop the "enable_"
to be accurate
when enable_ isn't used as a prefix, there is nothing to drop
(the switch being instructed, not the creation of the identity)
Thanks I think this is perfect
when adding a switch later on, I'll
- let HA have a new switch as usual
- Make an input boolean and template switch
- update the name of the input_boolean into this single automation
yep
- add the input_boolean to my "breaker panel"
in lovelace
This is so helpful @mighty ledge thank you very much
is the way you did the template switch above (using condition) instead of my method (using an if) more efficient?
this is how I did it before I was trying to shoe-horn an automation into a template switch.
friendly_name: "Air Conditioner"
value_template: "{{ is_state('switch.rmaircon','on')}}"
turn_on:
service: switch.turn_on
data_template:
entity_id: >
{% if is_state('input_boolean.rmaircon_breaker', 'on') %}
switch.rmaircon
{% else %}
switch.null
{% endif %}
turn_off:
service: switch.turn_off
data:
entity_id: switch.rmaircon```
just use a condition for the turn on instead of a template
like what I had above
(For purpose of learning) can you explain why 1 is better than the other?
Is it just less legwork for the template? (Or is it that it allows for the template switch to automatically not work until the Boolean is created)
well, you don't need a dummy switch
which will error if the dummy switch doesn't exist
I thought I wasn’t confused
But now not sure
Both ways there are 3 entities
1 real switch, 1 template switch
And 1 Boolean
Or by dummy you mean the entity.null
Yea
Technically that dummy/null switch is a failure of some kind, where the conditional is more accurate of a job
No need to make a dead end when you can just not drive to the place you are avoiding
switch.null is your dummy switch
Cool. We are on the same page thanks 😀
how can I convert a hex value e.g. 0x44175704 to a float (should be 605.359619141) inside template (value | float) does not work
{{ value | int(base=16, default=none) }}
float nicht int
you can't then
da kommt 1142380292 raus
i can't read non-english
sorry if I do your conversion its the wrong result
you can only convert hex to ints
I suggest using a python script and use the proper conversion methods
all the functions/methods you need to convert an int to a float don't exist in templating
@median citrus posted a code wall, it is moved here --> https://hastebin.com/eputebanuv
I (again) have a issue with the parametrization of an automation. i use an identical template in both a trigger and a condition in an action to parameterize the time. For the trigger it works but for the condition i get an error, why is that?
Rather than use automations for room occupancy/presence, I have been using templates like this: https://0bin.net/paste/7eaQzI0N#zmbp-wO/hIAu0iCa4Y0U5bdxWyX3a0LPu1AuFBXkhdq
I'm still tweaking things, but it feels like a good start.
i have been following this https://www.youtube.com/watch?v=Vjd6nJF0SLE
How does this pick up which room and assign the correct echo to use speech?
I don't use Echos, and that sensor is for one room, I have one sensor for each room to know if it's occupied.
ok
You can't template the for field inside conditions. Instead, name your trigger, and condition off that.
trigger:
- id: trigger1
platform: state
entity_id: input_boolean.test_toggle
to: 'off'
for: "00:00:{{states('input_number.my_number')| int}}"
action:
- choose:
- conditions:
- condition: template
value_template: "{{ trigger.id == 'trigger1' }}"
did you watch the full video? He hard codes the speaker to kitchen. It doesn't know which room and assign anything.
does anyone know whether it is possible to dynamically pick a scene based off of (for instance) a template sensor which outputs the name of the scene within a regular automation?
Or is this more a script thing?
- service: scene.turn_on
target:
entity_id: {{ states('sensor.day_and_night_lights_office1') }}
for example like so, where the sensor returns a string with the name of the scene I want it to use
I feel this might be a bit too complicated for an automation to do but I can't really find any information
i thought it was looking for last entity change looking for anme in entity and applying a label like kitchen then using the kitchen echo
that's a fine way to do it as long as you surround your template in quotes
ah. of course...
as long as your sensor is something like scene.xxxx
the sensor currently outputs the string scene.gaming_room_low_white
it depends on the time, which is why I wanted to do it with a template sensor and not with another set of nested choose levels
it's already getting hairy
@mighty ledge just looking for a way that ha knows what echo to use in which room that a person is in
lessee
that's fine, templates are great
yep that did it 🙂
if that is possible
awesome, thank you!
That can only be done through alexa media player
yep i have 9 of them
I have an automation that is giving me issues: https://pastebin.com/h0GEuzgs It usually fires and notifies me fine but in the logs it's showing: Template warning: 'float' got invalid input 'unknown' when rendering template '{% if states.sensor.wrens_bedroom_temperature.state | float < 21 %} true {% endif %}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
probably a red herring to the actual issue but something you should still address
ah ok, i see, will give it a try, thanks!
.. just out of curiosity, why is it that i can template the "for:" field in triggers and not in conditions?
selecting an ID for a trigger is a concept i was not familiar with but its super handy!
Cause someone didn’t develop that functionality
😉
ok i was expecting a more technical reason which was was not aware of 😄
your proposal works beautifully, thanks for thelp!
Np
Is the relative_time function broken at the moment when combined with device_class: timestamp in a template? it just seems to show as unknown in the frontend, but works correctly in the template editor. I'm not sure if I am interpreting this issue report correctly: https://github.com/home-assistant/core/issues/61035
Hi all. I'm working with generic thermostat. I understood that by setting it up (mine is nearly identical to the example in the documentation) that I would have a climate entity be made available, but when I add the thermostat card it does not see any climate entities as being available. Did I miss a step?
Did you reload climate integrations or restart?
Hi! I
@warped hornet posted a code wall, it is moved here --> https://hastebin.com/egikebivih
I've tried with trigger.json.values[0].value and trigger.json.values.0.value which does not work
template:
- trigger:
- platform: webhook
webhook_id: YULL90-data
sensor:
- name: YULL90 Data
state: "{{ trigger.json }}" # <- works
- name: YULL90 Temperature
state: "{{ trigger.json.values.2.value }}" # <- does not work
unit_of_measurement: °C
- name: YULL90 Humidity
state: "{{ trigger.json.values[3].value }}" # <- does not work
unit_of_measurement: "%"
@silent seal restarted
This is a special case. The word value in your json path also means get the raw value in template syntax (like the keyword value_json but not json formatted). So you have to use square bracket notation trigger.json.values.0['value']
@warped hornet Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://www.codepile.net/ (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.
Ah nice, I'll try that, thanks
don't edit your message to circumvent the bot
Sorry, didn't mean to cicumvent it
Still no luck :/ In the template editor it states that the value of states('sensor.yull90_data') is a dict - does that help anything?
Ah, it is same case for plural of value.. in the array key - now it works. Thanks!
So, i want to change a person's picture via template, is that not possible (anymore) ?
@median citrus there is actually a dedicated condition for that:
- condition: trigger
id: trigger1
Did not know that
Never too old to learn 🙂
speak for yourself 🤣
That was never possible.
Unless you used CustomUI
ah damn, oke thanks
i though you could through customize
No, customize does not accept templates by default. It can accept them if you use CustomUI.
If you stumbled upon forum posts claiming you can, they are using CustomUI or they are wrong. CustomUI was widely used at one point before it was abandoned, so I would assume that you're just stumbling upon CustomUI posts.
that might be it
well i can try to make a template sensor for it though
and use custom icons instead of a picture
You can template the picture on a template sensor
you just can't template in the customize section. So if you're going to create a template sensor to template the icon, you can jus ttemplate the picture instead.
yeah that was what i was thinking
When using the time trigger in an automation , is there a way to have the entity_id that did the time trigger? I tried accessing {{ trigger.entity_id }} but it didn't seem to do the trick
Are template entities pushed onto the HASS homekit bridge?
There are no entity_ids associated with time triggers. Post your trigger to verify
They should be
I'm assuming they mean if they reference an input_datetime in the time trigger
- alias: 'Test'
trigger:
- platform: time
at: input_datetime.boiler_scheduler_from
- platform: time
at: input_datetime.boiler_scheduler_to
I think I understand ... there goes my hope of making a unified automation to control both the start time and end time of my boiler within the same piece of code
I'll have to write a second one
Just add a trigger id to it
Then condition off the trigger id
I'll look into it! Thanks!
template:
- binary_sensor:
- name: "Outside cold"
state: >
{{ state_attr('weather.home','temperature') < 11 }}
delay_on:
hours: 24
delay_off:
hours: 24
you're comparing a string to a number
I need this switch to only trigger after the temp stayed below 11 for 24 straight hours
but I suspect it just adds a delay for when the temp dips below 11
like it dipped for just 1 hour and now my switch triggered after 24 h
probably better to use 2 automation and 2 input bools
ok but
about the delay
how does it work
does it just delay
or does it need the temp to stay below 11 for 24 h
1 automation to turn on the bool when it goes below 11. another to turn it back off when it goes above.
a third automation to turn on a 2nd bool when the first bool is on for 24h
I suspect that is not true here
could simplify to a template sensor without the delay and then automation + bool for "cold"
yeah, i forgot that attributes can be other things
but that way the switch display won't be relevant, I'll sww it turning on and off whenever the temp just dips below
then don't display it
lol
just display the input bool that gets toggled by automation
hmm, could work
but will it toggle after the temp stayed below 11 for 24 whole hours?
or just trigger after a delay of 24 hours after the temp dipped
you would trigger off that binary sensor going:
to: "on"
for: "24:00:00"
if it turns off the trigger resets
This. The docs explain it here https://www.home-assistant.io/integrations/template/#delay_on
delay_on time (Optional)
The amount of time (ie 0:00:05) the template state must be met before this sensor will switch to on. This can also be a template.
I remember reading this before asking
I found it ambiguous, otherwise I wouldn't have
in my mind, it makes sense, which is why I wrote the template like that
but maybe I got it wrong
right now my sensor is off even though it's -5 outside
24 hours ago, the temp went above 11 for like one hour
so there, that's why I'm asking, because it ties in with my second explanation
@gritty stratus posted a code wall, it is moved here --> https://hastebin.com/anihejisak
the problem is all states are stored as strings. try
"{{ states('sensor.pv_current_quantiles_5m').split(',')[0] }}
@gritty stratus
oh that will have the brackets still. ew
So quantiles stores as strings internally? That feels pretty icky to me. I'm wondering if there is a percentile-like thing that doesn't do that?
The problem on trying to solve is trying to figure out what my solar power is generating x% of the time so I can charge my EV at a sensible rate, but I found mean had the opposite problem
home assistant stores all entity states as strings
out of curiosity, what version of HA are you on?
Oh, even numbers? Heh.
2021.12.2-full
got it. HA was changed about a year (?) ago where templates would output proper data types, so i was wondering if maybe you were on an older version. but... you're not
hey i get the following error with this template sensor
template:
- binary_sensor:
- name: "People Home"
unique_id: "4d3004f9e7514ecb947715b5de3356c5"
state: >
{{ is_state('person.sam', 'home')
or is_state('person.melli', 'home') }}
2021-12-24 12:34:29 ERROR (SyncWorker_8) [homeassistant.util.yaml.loader] while parsing a block mapping
in "/config/packages/presence.yaml", line 106, column 5
expected <block end>, but found '-'
in "/config/packages/presence.yaml", line 110, column 5
i dont get whats wrong here
template: should be hard against the margin of configuration.yaml and it should only exist once.
i use oackages here
in this package template only exist once
this is the package @fossil venture
I can’t see anything wrong
this is super weird
i converted from the legacy template format to the new one
the old one worked without problems
The only thing I can think is you’re mixing tabs and spaces
I keep getting the no default error on this template
{% if states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') %}
{{ (states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') | int / 3600 ) | round(0) | int | default(0) }}
{% elif states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') == 0 %}
0 Hours (0%)
{% else %}
starting.....
{% endif %}
how can I fix it?
Try using is_state instead.
{% if is_state('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left', 'unavailable') %}
starting…
{% elif is_state('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left', '0') %}
0 Hours (0%)
{% else %}
{{ ((states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') | int) / 3600 ) | round(0) | int | default(0) }}
{% endif %}
Also, you needed to wrap the casting the states to an int in brackets most likely.
I think the error is when the state is unavailable though and something to do with not being an int
I’ve added that check. A warning: Some of those quotes are not straight so that will 100% cause an error, but I’m on my iPad and Discord got picky
thank you
I managed to fix the quotes!
My embarrassing first attempt at doing an IF ELSE statement in an automation seems to be failing with Message malformed: Service (code line 12) does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']
https://pastebin.com/GCXG3L4t
I find the templating docs a little hard to see through 😦
What's the thing I'm misunderstanding?
@nocturne chasm
Some additions/comments:
- the last statement now only gives a number, shouldn't it inlcude
hours? - why treat
0differently? The result of the formula would be0anyway.
I would probably do it like this:
{% if states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') | is_number %}
{% set dirty_left = ((states('sensor.xiaomi_vacuum_cleaner_sensor_dirty_left') | int) / 3600 ) | round(0) | int | default(0) %}
{{ dirty_left ~ (' hour' if dirty_left == 1 else ' hours') }}
{% else %}
starting.....
{% endif %}
I think your intent is off on the first if, are you using spaces or tabs?
@olive rover your template returns switch.turn_off(downstairs_lights) or switch.turn_on(downstairs_lights) which is not a valid service
you should only return switch.turn_off or switch.turn_on and put the light you want to turn off/on under target:
Ah I tried something like this before https://pastebin.com/jHyTqpMY
but it yields the same error message
homeassistant generic turn off / on is the one I actually want. Sorry about the typo.
my advice: create a light group for these lights (https://www.home-assistant.io/integrations/light.group/) instead of a normal group you have now, and just use light.toggle
No template needed at all
They are actually switches and not lights. Does that matter?
(I call them lights as they are physical lights attached to a power outlet switch to control them)
Maybe it would be important for me to describe what I want to achieve.
there is also a homeassistant.toggle
I have a physical button I want to use as an on/off switch for this group of outlets. It is possible that one or more of the outlets is manually turned off. This means that a simple toggle does not achieve turning them all on/off when the button is pressed.
So - I want to see what the majority state of the lights are, then do the opposite
If 2 of 3 lights are on, button press turns them all off.
If you want them to appear as lights you can use this: https://www.home-assistant.io/integrations/light.switch/
ah okay
I understand the problem now, in that case you do need a template, because both the group or light.group will be on when any light is on
Always useful to describe the desired outcome 😄 Sorry, I should have formulated my issue better.
How to format simple template in my notification , e.g My room temperature is (entity value) ?
this will probably work if you replace => with >=
"My room temperature is {{ states('sensor.your_temp_sensor') }}"
Holy crap it really was an operator typo. Thank you.
So tldr: I sync the states like this now: https://pastebin.com/w76PWWmM
and then run a second action to toggle all if needed.
Works a charm.
@marble jackal Thanks . As a noob i typed state instead of states
Other question is why on my frontend weather state is in my own language , but on messeges send to tv it's in English
That's becasase the frontend automatically translates it
rest:
- resource: http://192.168.xxx.xxx/meas.xml
binary_sensor:
- value_template: "{{ value_json.meas.O1.HN }}"
# state: "{{ value_json.meas.O1.HN }}"
device_class: running
I'm trying to re-do my sensors in the non-deprecated way, but with this HA complains that value_json is not found
where am I going wrong?
Unique Id isn’t valid on the root level
It’s also not valid on the sensor level
Thanks
fixed that
but I still get an erro in the logs:
Logger: homeassistant.helpers.template
Source: helpers/template.py:1791
First occurred: 16:59:45 (135 occurrences)
Last logged: 17:33:15
Template variable error: 'value_json' is undefined when rendering '{{ value_json.meas.O1.HN }}'
Verify that your resource is correct
hey guys i have a log error but the setup if working?
https://www.toptal.com/developers/hastebin/umuwarijef.pl
all info is in the pastebin
is it syntax? i cannot find whats wrong
Is it during startup? The time of the error and the Tasmota time stamps are quite different
no its all the time. got 100+ msg now. Timings is different because i just copy pasted some stuff
my automation is working fine using the ON an OFF provided by the sensor
got it: Tasmota uses RESULT for more chatter: stat/v1-badkamer-shelly1L/RESULT = {"POWER":"ON"}
which cannot be parsed ofcourse
I am not really sure why I had the 0 else in there to be honest. Seems like it is a remnant from some other attempt to fix an error message.
I prob should have also posted the rest of the template, it was just a percentage wrapped in parentheses and very similar to the first, so I just duplicated the changes from the first.
I struggle with templates so clean is not the goal, working is 😜
@bronze dirge posted a code wall, it is moved here --> https://hastebin.com/ebuxinedid
Please let me know if I am posting on the wrong channel.
I have that ^ template switch. Bascially turning the relay on and off with 300ms cooldown
I notice recently that after clicking the switch. There could be a huge delay before the relay gets triggered
Or that the relay could turn on then stay for much longer than 300ms (like 5s)
It used to work perfectly but it developed this issue.
I am not sure where that delay comes from.
When did it develop the issue? What changed?
Not sure...sorry
it could be HA update but it could be before the update
I didn't touch HA for a while
I wonder if the delay is
- after I click the template switch button but before it reaches HA thru internet
- after it execute the template "script"
- zigbee mesh connection issue
I am not sure how to distinguish between them
can I use templating for entity_id in condition part as condition-state?
target:
entity_id: "{{trigger.to_state.entity_id}}"
state: 'not_home' ```
it shows me an error in my logs: Invalid config for [automation]: Entity {{trigger.to_state.entity_id}} is neither a valid entity ID nor a valid UUID for dictionary value @ data['condition'][0]['conditions'][0]['entity_id']. Got None.
You need to check the logs. Press the switch and see when the entry appears.
I assume, that condition need to be type of template
sorry where the log is?
thanks. So I need to add write to log to different part of the whole process? because currently the system log doesn't log any of that
What kind of switch is it? How is it connected to Home Assistant? There should be logs in that.
I assume you mean Zigbee2MQTT? If so, listen to the events that are sent to Home Assistant.
I don’t think this is a templating issue (at least, more troubleshooting required). So for now you might be better off in the #zigbee-archived channel.
If you're having problems with your updates to your configuration:
- Check the troubleshooting steps
- Check your log file - remembering you may need to set logger to
infoordebug - Explain what the problem you're having is - sharing configuration, errors, and logs
This should help!
You’re welcome!!
can I write this shorter? {%- for s in states.scene if select == s.object_id.split('_')[:-1]|join('_') or select == s.object_id.split('_')[:-2]|join('_') or select == s.object_id.split('_')[:-3]|join('_')%}
What are you trying to do?
select in s.object_id.split('_')[:-1] is functionally similar but it casts a wider net so you might get things you don’t want.
please see: https://community.home-assistant.io/t/select-activate-hue-scenes-in-new-v2-api-setup/356057/12?u=mariusthvdb. I need to expand the template to also catch scenes with 3 words, like 'onder de boom' (under the tree.....)
though it already does what Petro says, cast a bit wider than desired
short story: I want to strip of the group names (which can be 1 to 4 words) and only list the scene names (which now can be up to 3 words)
having groups like Dining, and Dining table, doesnt make things easier,.... or Living, and Living ceiling spots 1... might have to change those for easier templating
my thought btw for the current template were to shorten something like [:{-1,-2,-3}], replacing the 3 or's.
Why not just replace the select in the name?
Usually replace will just not do anything if it doesn't match a substring.
Will try that after some sleep ;> thanks
Hi, I am converting dates back and forth to get rid of the milliseconds. Is there a "correct way" to handle this? I usually use now().strftime('%Y-%m-%d %H:%M:%S%z') to format the string I need, which is almost what as_local produces. Why are milliseconds shown in those commands? Is it possible to define own, custom macros? 🙂
It shows milliseconds because you tell it to, if your remove %z in the template it won't.
What I meant to ask if why as_local shows milliseconds. There should be a filter to remove just the unwanted parts... (know there isn't, but it's christmas... :D)
I don't understand. You can format it as you want using .strftime Just change the part between the brackets to your needs
Or convent it to a timestamp and use | timestamp_custom()
You can use | int on the timestamp to remove ms
Question is why as_local shows the milliseconds... I know I can format it as I want, just wondered if there was an easier way
as_local only converts a datetime object to local time, it doesn't change how it is displayed
Ok, got it. Thanks
How would I modify this {{ states | map(attribute='entity_id') | select('match', 'light') | list }} to also include entities with the word outlet in it's entity_id? I have tried adding another select('contains', 'outlet') statement, but have had no luck so far
Goal is to get a list of entity_id's of all my lights + one light that is actually a dumb one on a switch (outlet)
you made me rethink! thank you for that: filter: template: | {% set hue_group = states('input_select.hue_group_v2')|lower|replace(' ','_') %} {% set ns = namespace(scenes=[]) %} {%- for s in states.scene if hue_group == s.attributes.group_name|lower|replace(' ','_')%} {% set ns.scenes = ns.scenes + [{'entity':s.entity_id, 'name': s.object_id.split(hue_group +'_')[1]|capitalize|replace('_',' ') }] %} {%- endfor %} {{ns.scenes}}
trying the new 'slugify' filter, I can do this:``` filter:
template: |
{% set hue_group = states('input_select.hue_group_v2')|slugify %}
{% set ns = namespace(scenes=[]) %}
{%- for s in states.scene
if hue_group == s.attributes.group_name|lower|replace(' ','')%}
{% set ns.scenes = ns.scenes + [{'entity':s.entity_id,
'name': s.object_id.split(hue_group +'')[1]|capitalize|replace('_',' ') }] %}
{%- endfor %}
{{ns.scenes}}
but can not use it in the if hue_group == s.attributes.group_name|lower|replace(' ','_') line, resulting in TypeError: decoding to str: need a bytes-like object, LoggingUndefined found
filter:
template: |
{% set hue_group = states('input_select.hue_group_v2') %}
{{hue_group}}
{% set ns = namespace(scenes=[]) %}
{%- for s in states.scene
if hue_group == s.attributes.group_name%}
{% set ns.scenes = ns.scenes + [{'entity':s.entity_id,
'name': s.object_id.split(hue_group|slugify +'_')[1]|capitalize|replace('_',' ') }] %}
{%- endfor %}
{{ns.scenes}}
``` is better though, and yet less code 😉
Found it! A wildcard was all it took: "{{ states | map(attribute='entity_id') | select('match', 'light|switch.*outlet') | list }}"
good morning and happy holidays!
i'm trying to figure out how to make this call correctly, but keep getting a value_json does not exist error 🤔
- service: mqtt.publish
data:
topic_template: "homeassistant/sensor/bug_report/{{ bug_number }}/config"
retain: true
payload_template: >-
{
"name": "Bug Report #{{ bug_number }}",
"unique_id": "bug_report_{{ as_datetime(float(time)) | as_timestamp }}",
"state_topic": "bug_report/{{ bug_number }}",
"json_attributes_topic": "bug_report/{{ bug_number }}",
"value_template": '{{ "{{ value_json.message }}" }}'
}
i'm thinking it's trying to render that last template, when i actually need to send the template itself... any ideas?
actually, i just had the idea to use '{{ "{{ " + "value_json.message" + " }}" }}'
and that avoids the error, but that isn't actually publishing anything to that topic 🤔
haha i got it!
- service: mqtt.publish
data_template:
topic: "homeassistant/sensor/bug_report/{{ bug_number }}/config"
retain: true
payload: >-
{
"name": "Bug Report #{{ bug_number }}",
"unique_id": "bug_report_{{ as_datetime(float(time)) | as_timestamp }}",
"state_topic": "bug_report/{{ bug_number }}",
"json_attributes_topic": "bug_report/{{ bug_number }}",
"value_template": "{{ '{{ ' + 'value_json.message' + ' }}' }}"
}
Oh! This was useful, thanks! And Happy Holidays to you too! 🙂
hey great!
Since the winter solstice has passed I wanted to make a sensor showing me the change in daylight each day and I've made a custom sensor that uses this
value_template: "{{( state_attr('sensor.sunset', 'tomorrow') - state_attr('sensor.sunrise', 'tomorrow') ) - (state_attr('sensor.sunset', 'today') - state_attr('sensor.sunrise', 'today') )}}"
and it gives me a sensor with a timestamp like 0:01:11.942851 but how can I change that to something more readable like 1m12s or atleast 1:12
Great idea! 🙂 I can find next rising and setting, but where did you find those for the current day?
you can't really have the past ones unless you set it into an input_datetime or something else
i have a pretty complicated sunrise/sunset based automation that waits until sunSET of the current day, and then sets input_datetimes with the times for the NEXT day
Ah, figures 🙂 I saw them in the Logbook, but getting them from there proves a challenge... 🙂
that way i can work with them even after sunRISE of the next day
I installed this custom component https://github.com/pnbruckner/ha-sun2 to get the ones used!
This is the package I use for the sensors
https://gist.github.com/Naesstrom/ea0bb5dbcb977daaccb09245339051aa
If you create a template sensor that holds the value of sun.sun.attributes.next_rising then I think you could use that with a min/max sensor of type last (https://www.home-assistant.io/integrations/min_max/)
Oh NVM. Forgot how last works. It's not the previous value, it's the value of the latest entity to update of those watched. My bad
Yea getting a sensor with the previous value of another entity to when it updates is tricky. You could do it by listening for and triggering off the state_changed event directly since it contains current and previous values in it. But then it won't restore correctly after a restart
Can anyone help me convert this template, from equals Multivitamin to an contains Multivitamin?
{{"Multivitamin" in trigger.to_state.attributes.friendly_name}}
What you have is “contains”
Ok then the automation must have a different problem Thanks
@low cypress This will give you a count of all unavailable entities, it might help provide a start for what you want to achieve:
{{ states | selectattr('state', 'eq', 'unavailable') | list | count }}
Off to bed now 😴
I'll try iy, thanks
Specifically, {{ states | selectattr('state', 'eq', 'unavailable') | list | length > 0 }}
but this template gives me only number.
I want to create an alert "<triggered_entity> is unavailable"
I currently have 83 unavailable entities, I would not want to get notified about that
😅
But you can also create a template for that
That template can also be modified to output the list
thats true, but it will be triggered only for new unavailable entitties
How you define ‘new’ becomes the problem
yes, i get your point
Evening all! Merry Christmas!
{% set do_child1bins = is_state('sensor.child1_bins', 'today') %}
could someone tell me how I modify this so that that it check's to see if the sensor child1_bins is today (as above), AND input_boolean.chore_bins is true please.
Pretty straightforward
{% set do_child1bins = is_state('sensor.child1_bins', 'today') and is_state('input_boolean.chore_bins', 'on') %}
Thank you. I really appreciate that!
literally an and is all i needed. So sorry. I was working with another and statement in templates the otherday and it was not that straightforward!
Make sure to use the right quotes. My iPad is changing them to the wrong ones
And an input_boolean is never “true”, they’re always either “on” or “off”
does it need to be double spaced after the first close bracket?
Makes no difference
cool. Thank you.
Been giving your question some more thought. You could create a template sensor with the number of unavailable entities as state, and the list of unavailable entities as it's attribute. Then create an automation triggering on a state change of this sensor.
You can then determine which are new by taking the new state of the attribute, and rejecting everything in the old attribute state. What remains you can put in your message.
Is there a way to get an Automation to trigger every 2 weeks. Other than using the time pattern at 336 hours
Hi guys. Is someone experienced in mood to help me with templating, I'm really not good with this?
And would like that Alexa not speak entity IDs in response, but rather some friendly device name.
I would be glad to provide any additional info required, and not sure at all could this be done some simple way or it is too much complicated 🙂
You could for check on the week number, and weekday. So eg a time trigger at 6:00 and a condition to check if it is Monday in an even week.
How would I check for an even week?
{{ now().strftime('%U') | int is even }}
I would make this a template sensor or can this be a value template as a condition?
This returns True or False so you can use it in a template condition
Sounds good thank you.
The only issue is that sometimes a year has 53 weeks
In that case it will not run in week 53 and in week 1 of the year after, so there will be a three week window. If that is a big issue, you can use odd weeks in a year with 53 weeks. The template becomes a bit more complicated then.
I see and yes 2023 will have that
What is your goal? If it's something like checking for rubbish collection or similar there's a great HACS integration which I'm misusing for tracking lots of things!
Ok, so, answering to my self 🙂 I found solution, pretty dirty and so manual, but it is working and I'm ok with that. With lot of regex_replace's at the end of alexa_confirm.yaml , 3 for now, need to add ~20 more I think 🙂 https://www.toptal.com/developers/hastebin/avonesijij.lua
You could also trigger it every week, and use an input_boolean. Create a choose and when the boolean is off run your actions and turn the boolean on. When the boolean is already on, just turn it off. But since you don't need any templates then, that will be stuff for #automations-archived
When would the boolean be turned on and off though?
In the same automation in which you run your biweekly actions.
trigger: 06:00
condition: Monday
action:
choose:
- boolean is off: run biweekly actions and turn boolean on
- boolean is on: turn boolean off
Biut if you want to discuss it further I suggest we move to #automations-archived
Hi I'm trying to make a timer but it doesn't seem to work at all. The code looks like this.
sensor:
- platform: template
sensors:
atlas_sleep_timer:
friendly_name: Atlas sleep timer
icon_template: mdi:clock-outline
value_template: >
{% set t = states('sensor.time') %}
{{ relative_time(states.binary_sensor.openclose_33.last_changed) }}
Can't share images on here but it essentially just says "0 seconds" for some reason
maybe a typo in your entitiy_id? The template itself should work
or it could be that your trick to refresh it does not work 🙂
So it only refreshes on a change of the enttiy, and
then it sticks on 0 seconds
Time pattern of 336 hours wouldn't work btw since no hour is divisible by 336
That makes sense. Very simple. Thank you.
No typo, triple checked. Could there be another trick to make it update instead of just stick to 0?
Where are you checking the value to determine that it never updates?
That template reports the right value for one of my entities
On a glance card
The frontend doesn’t always update regularly
Check
-> States and follow up in #frontend-archived
trying to figure out how to get all the sensors i have with a specific entity "pattern"... like sensor.issue_*
i think this should be a selectattr, but i'm not quite sure how to accomplish it
{{ states.sensor | selectattr('entity_id', 'in', 'sensor.issue_*') | list }} doesnt work lol
mmm
or search, depending on whether the pattern starts at the beginning
keep in mind that it's a regex and not just a glob
ok wait, how do i get the entity_id from those?
just trying to get a list of the ids
oh got it
map(attribute='entity_id')
Newbie here, just installed version 2021.12.5. Installed integrations for all devices on my network, HACS. Most of the integrations were simple, Roku card works really well. The DirecTV integration has minimal function, trying to trying to get one of the remote cards to work with DirecTV. Tried TV remote card and Generic Remote Card and tinkering with the config using the information on Home Assistant site, but not making much headway. Does anyone have a template for DirecTV that I can use as a starting point or if complete even better.
next question: template like {{ states.binary_sensor | selectattr('entity_id', 'match', 'binary_sensor.issue_*') | selectattr('state', 'in', issue_state) | map(attribute='entity_id') | list }} does give me the right ids
['binary_sensor.issue_10', 'binary_sensor.issue_5', 'binary_sensor.issue_6', 'binary_sensor.issue_8', 'binary_sensor.issue_9']
but how can then sort those properly by their number?
so 5,6,8,9,10
or whatever the case may be
Not easily, since they’re not zero-filled. Fix that, and I think you can use |sort
Your list is actually already sorted alphabetically now
hmm, what if there were over 99? zero padding there would be even trickier
I was up for a challenge during a Christmas movie, this seems to work, even over 99. But i agree zero padding would be better
{% set ns1 = namespace(d = []) %}
{% set ns2 = namespace(d = []) %}
{% set ns3 = namespace(d = []) %}
{% for sensor in sensors %}
{% set d = sensor.split('_')[-1] | count %}
{% if d == 1 %}
{% set ns1.d = ns1.d + [ sensor ] %}
{% elif d == 2 %}
{% set ns2.d = ns2.d + [ sensor ] %}
{% elif d == 3 %}
{% set ns3.d = ns3.d + [ sensor ] %}
{% endif %}
{% endfor %}
{{ ns1.d | sort + ns2.d | sort + ns3.d | sort }}```
And it can probably be done with less code, but it works 😅
I guess you could do the zerofill in real time
value_template: {{ state_attr('sensor.electricity_price', 'Price level') in ['NORMAL','CHEAP'] }}
Can anyone spot the mistake it says i should add commas
What does?
{% set sensors = ['binary_sensor.issue_10', 'binary_sensor.issue_199', 'binary_sensor.issue_102', 'binary_sensor.issue_8', 'binary_sensor.issue_9'] %}
{% set ns = namespace(sensors = []) %}
{% for s in sensors %}
{% set e = s.split('_')[-1] | int %}
{% set ns.sensors = ns.sensors + [ (e, s) ] %}
{% endfor %}
{{ ns.sensors | sort(attribute='0') | map(attribute='1') | list }}
You're missing "" around it all
{% set sensors = ['binary_sensor.issue_10', 'binary_sensor.issue_199', 'binary_sensor.issue_102', 'binary_sensor.issue_8', 'binary_sensor.issue_9'] %}
{{ sensors
| map('regex_replace', '^.+_(\\d+)$', '\\1')
| map('int') | sort | map('string')
| map('regex_replace', '^(\\d+)$', 'binary_sensor.issue_\\1')
| list }}
I was kinda mad I had to use regex_replace again at the end but I couldn't figure out any other way to do concat as a filter lol
Side note, template challenges are fun. If there was a newspaper that had jinja puzzle of the day instead of a crossword I'd be all for it lol
The Geek Times
@mighty ledge Thanks
@marble jackal @mighty ledge @toxic dome thanks! will try these out!
does someone know what im doing wrong here?
template:
- sensor:
- name: sensor.storage_capacity
unique_id: unique_id_for_Tb_sensor
unit_of_measurement: "Tb"
state: "{{ (states('sensor.sabnzbd_disk') |float / 1000 }} | round(2)"
- name: sensor.storage_capacity
Your round filter is outside of the template
if i put it inside i cant get it to work either
Parens
Not like that
You’re missing a paren after the 1000
And you have “ inside the template
state: "{{ (states('sensor.sabnzbd_disk') |float / 1000 ) | round(2) }}"
like this?
Yes
lets see
You may need to add a default to float() if it will ever not be a number
https://imgur.com/a/WsipWBf Is state_attr the correct way of reading out the attributes?
Yep
this one works 🙏 thank you!
I think i'm having an issue with leading numbers in sensor names (which have been given by the homematic integration).
working: {{ state_attr('binary_sensor.office_power', 'friendly_name') }}
not working: {{ state_attr('binary_sensor.00095be98bXXXX_illumination', 'friendly_name') }}
BUT if i use this entity-id in an automation it works fine.
Is there any workaround I am not aware of?
need to use states.binary_sensor['00095be98bXXXX_illumination'].attributes.friendly_name I think
Hi all, does anyone knows if it is possible to use a input boolean in a template inside a blueprint?
I have created a input_boolean named "studio" and then a blueprint with an input to recall this blueprint
boolean_name: name: Room Name description: Name of the room in which are the lights default: false selector: text:
I then created variable:
variables: boolean_name: !input boolean_name
and a condition but it doesn't work:
` - condition: template
value_template: '{{ states(input_boolean.[boolean_name]).state == off }}'`
any hint?
Hey guys, i was wondering if these sensors, state: "{{ (states('sensor.sabnzbd_disk') |float / 1000 ) | round(2) }}" and state: "{{ (states('sensor.sabnzbd_free') |float / 1000 ) | round(2) }}" could be subtracted in order to gain a new sensor ie: sensor.sabnzbd_used ?
"{{ ((states('sensor.sabnzbd_disk') |float - states('sensor.sabnzbd_free') |float) / 1000) | round(2) }}"
im going to try this, i was already well on my way (i think :))
- sensor:
- name: sensor.storage_capacity_used
unique_id: unique_id_for_Tb_sensor2
unit_of_measurement: "Tb"
state: "{{ ( ('sensor.storage_capacity') | float) - ( ('sensor.storage_free') | float) }}"
The name shouldn't include sensor. otherwise your sensors I'd will be sensor.sensor_storage_capacity_used
hmmm, for some reason it puts out the same value as 'sensor.storage_capacity'
i saw this thanks, ive corrected that
And if you want to use the state of an entity in a template then you need to do states(<entity id>)
Use something like this in the value template: "{{ is_state('input_text.' + name_of_variable, 'day') }}"
You just have the name as a string
im going to fench with this thanks
i did that, but it seems to put out the same value as 'sensor.sabnzbd_disk'
- sensor:
- name: sensor.storage_capacity_used
unique_id: unique_id_for_Tb_sensor2
unit_of_measurement: "Tb"
state: "{{ ((states('sensor.sabnzbd_disk') |float - states('sensor.sabnzbd_free') |float) / 1000) | round(2) }}"
thank you!
I mixed up sensor and binary_sensor, so this had nothing to do with leading numbers.
But your reply led me to a workaround for the next problem: for some reason i have problems with state_attr('sensor.xyz', 'last_changed'), but states.sensor['xyz'].last_changed is working fine.
Got it to work!
That’s because it’s not an attribute, but a property. states.sensor.xyz.last_changed would also work
Makes sense. I’m going to fix this in the HA documentation (Homematic Integration) accordingly. It drove me nuts 😄
hello friends, im very new at this stuff so i need some help
i managed to get my one rf remote working to toggle a light, now i have another one that im kinda stuck with
i have the code needed, it gets detected when i listen with mqtt, but i cant get it to work in an automation, when i toggle the automation normally then the light toggles, just not with the RF remote
this is the binary sensor that worked for the other remote, as well as automation (not in the same file of course) https://www.codepile.net/pile/wv5q81v8
am i missing a step somewhere
For what
How can i concat or short a string ?
wanna compare these strings:
2021-12-29T09:30:00+00:00
2021-12-29T06:20:00+00:00
so first i gotta compare year , month , day , time
is there a faster way then just comparing them one by one ?
How can I find out what's causing this? https://pastebin.com/wLBEE7g8
currently i am checking if the person with the set alarm is home, if not i get a big value, then i readout the sensor alarm timer (2021-12-29T09:10:00+00:00) and remove everything till i get the yearmonthdaytime
as int
compare them and then take the alarm thats earlier
now i want to set that time 5 minutes before
do i have to first cut the string down to the time substrate 5 and then build it with concat ?
is there no easier method knowing its a device_typ: timestamp
Whoops. I figured out my issue and deleted the rest but missed one
You should be able to use as_datetime or as_timestamp with that string to end up with something that you can easily modify or compare
ohh
i will try that
ty as always senpai :D
{{ as_timestamp(states.sensor.kobito_next_alarm)}}
this returns "None"
{{ as_timestamp(states.binary_sensor.garage_door.last_changed) }}
thats from the doc
That’s not what you have or what you want
You want the state and there’s a whole section for that
ok so just {{as_timestamp(states('sensor.kobito_next_alarm'))}}
That looks better
so as_timestamp give me Time in Milliseconds: 1640769000000
how does that work ?
what kind of time is that ?
1640769000000
is a pretty big number
312160 years o.O
It’s in seconds
what's the actual state of your sensor.kobito_next_alarm
states('sensor.kobito_next_alarm') returns 2021-12-29T09:10:00+00:00
Then you're reading the number wrong
1640769000
not sure where you're getting 3 extra zeros
its the output from devtool when i use {{as_timestamp(states('sensor.kobito_next_alarm'))}}
1640769000.0
? thast why i didnt include the last 0
hence the confusion.
i still get 312 years
it should be 01.01.1970
so its seconds
big note in the docs:
UNIX timestamp is the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970. Therefore, if used as a function’s argument, it can be substituted with a numeric value (int or float).
its so weird that its says time in milliseconds:
works like a charm
the nextalarm entity got an anttribute named:
Time in Milliseconds: 1640769000000
oh
well it is
thats where i got the 3 0´s from
lul well not my day i guess i cant even go from seconds to years ... yickes
Can someone assist me in writing a template a service call can use? I need to update an input_number. (input_number_lifetime_earned_ava) using a value stored as a counter, do some math on it (to show allowance earned) then add that number to an existing number helper.
{% set value = states('counter.chore_ava_counter') | int %}
{% set prevalue = states('input_number.number_lifetime_earned_ava') | float %}
{% set newvalue = (value / (70) * 15) | round(2) %}
You Earned ${{ (value / (70) * 15) | round(2) }} Last Week
You've earned ${{ newvalue + prevalue }} total from chores
Thus far i can throw that in the developer template. but i have no idea how to translate that into a service call.
I want to add newvalue and prevalue, then post that to a service call to set the input_number
Pretty much exactly what you gave there
{{ newvalue + prevalue }}
service: input_number.set_value
target:
entity_id: input_number.number_lifetime_earned_ava
data: {
{% set value = states('counter.chore_ava_counter') | int %}
{% set prevalue = states('input_number.number_lifetime_earned_ava') | float %}
{% set newvalue = (value / (70) * 15) | round(2) %}
{{ newvalue + prevalue }}
}
doesn't seem to like this
How could I create a virtual light to represent my 433MHz light that does not report its state to HA, but is controlled by multiple "light switches" (rocker buttons) that HA can see sending their state? I'd want the virtual light to update its state based on the latest on/off event from any of the switches. I'm using tellstick add-on to let HA know what the switches are doing. I've tried FAQ, google and working myself on the templates and groups, but I just can not get my head around the logic how to build this.
Failed to call service input_number.set_value. Error rendering data template: Result is not a Dictionary
service: input_number.set_value
target:
entity_id: input_number.number_lifetime_earned_ava
data: >+
{% set value = states('counter.chore_ava_counter') | int %}
{% set prevalue = states('input_number.number_lifetime_earned_ava') | float %}
{% set newvalue = (value / (70) * 15) | round(2) %}
{{ newvalue + prevalue }}
You’re not calling the service properly
I wish i knew what that meant
Just the docs
service: input_number.set_value
target:
entity_id: input_number.number_lifetime_earned_ava
data:
value: >-
{% set value = states('counter.chore_ava_counter') | int %}
{% set prevalue = states('input_number.number_lifetime_earned_ava') | float %}
{% set newvalue = (value / 70 * 15) | round(2) %}
{{ newvalue + prevalue }}
first, you can't use templates in
-> Services. Second, did you see what I just posted?
welll that would be why that's not working.
it wasn't the only problem
?
should i throw it into an automation to test?
if that's where you planned to use it
I think you didn't add it properly
what does it mean "not a dictionary"
it means that your formatting is broken
this works for me:
set_test:
sequence:
- service: input_number.set_value
target:
entity_id: input_number.test2
data:
value: >-
{% set value = 1 %}
{% set prevalue = 2 %}
{% set newvalue = (value / 70 * 15) | round(2) %}
{{ newvalue + prevalue }}
it's a script that I wrote to test what I posted
maybe i could just call a script as the action
if it works as a script
i'll test
it works fine as a script but errors as a service call.
makes perfect sense.
oh well, have automations that call the script. Good to go, thanks for your help. it was valuable.
- platform: template
sensors:
rhys_phone_rounded:
friendly_name: Rhys phone battery rounded
unique_id: e7847441-896c-4d59-bd72-8e165c116f8c
value_template: >
{% set batt = states('sensor.rhys_phone_battery_level') %}
{% if batt >= 0 and batt < 10 %}
{% set rounded = 0 %}
{% elif batt >= 10 and batt < 20 %}
{% set rounded = 10 %}
{% elif batt >= 20 and batt < 30 %}
{% set rounded = 20 %}
{% elif batt >= 30 and batt < 40 %}
{% set rounded = 30 %}
{% elif batt >= 40 and batt < 50 %}
{% set rounded = 40 %}
{% elif batt >= 50 and batt < 60 %}
{% set rounded = 50 %}
{% elif batt >= 60 and batt < 70 %}
{% set rounded = 60 %}
{% elif batt >= 70 and batt < 80 %}
{% set rounded = 70 %}
{% elif batt >= 80 and batt < 90 %}
{% set rounded = 80 %}
{% elif batt >= 90 and batt < 100 %}
{% set rounded = 90 %}
{% elif batt >= 100 %}
{% set rounded = 100 %}
{% endif %}
{{ rounded }}
Can anyone tell me whats wrong with this, works fine in developer tools but shows as unavailable when implemented
You’re missing |float in the initial set
ffs i had that in earlier must have misplaced it
It could also be simplified greatly
any pointers im happy ive tried a few things but couldnt get them to work
{{ (batt/10)|int * 10 }} to start
wow ok that's embarrassing
haha yeah i have never got over 100 but will let you know if i do.
thanks @inner mesa
i needed numbered form of month & days in an automation script and have a template for it (below) .But get this error all the time in logs. Though everything seems fine i wonder whats the issue
Template variable warning: list object has no element 28 when rendering '{% set days = ["Mon", "Tue", "Wed", "Thu", "Wed", "Thu", "Fri", "Sat", "Sun"] %} {{ days[now().day-1] }}' 1:44:00 AM – (WARNING) helpers/template.py
Template
`sensor:
- platform: template
sensors:
month_long:
value_template: >
{% set months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] %}
{% set days = ["Mon", "Tue", "Wed", "Thu", "Wed", "Thu", "Fri", "Sat", "Sun"] %}
{{ months[now().month-1] }} - platform: template
sensors:
date_padding:
value_template: >
{% set days = ["Mon", "Tue", "Wed", "Thu", "Wed", "Thu", "Fri", "Sat", "Sun"] %}
{{ days[now().day-1] }}`
well, now().day is 28
Because it's the 28th day of December. Did you want the index of the day of the week?
If so, you want {{ days[now().weekday()] }}
or just {{ now().strftime("%a") }}
same with the month: {{ now().strftime("%b") }}
How to use template to display name of a user on Lovelace card?
there's an example of exactly that on the markdown card
Hello all, I found a template to calculate Vapor Pressure Deficit:
- platform: template sensors: vapor_deficit: friendly_name: 'vpd in kilo pascals' value_template: >- {% set T = states('sensor.itc_308_temperature')|float %} {% set RH = states('sensor.ihc_200_humidity')|float %} {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %} {% set VPD = ((100-RH) / 100) * SVP %} {{-VPD | round(2) -}} unit_of_measurement: 'kPa'
It works but sometime trigger a lot of this error and make spikes in Grafana graphs:
Template warning: 'float' got invalid input 'unavailable' when rendering template '{% set T = states('sensor.itc_308_temperature')|float %} {% set RH = states('sensor.ihc_200_humidity')|float %} {% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %} {% set VPD = ((100-RH) / 100) * SVP %} {{-VPD | round(2) -}}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1
Is there something I can do to avoid this error? I have last version of HA. Thank you
anyone with a count down template sensor to new year?....
I have a question about a kWh sensor and m3 gas sensor. The value is 3.787 kWh. I use the next sensor for playing it on my smart speaker:
- platform: template
sensors:
summary_smart_house:
friendly_name: "Overzicht huis"
value_template: >
You have today: {{ states('sensor.daily_energy') | float }} kWh used.......
The problem is that is pronounced not correctly because it is no comma (the system thinks that it is a thousand seperator). How can I replace the dot with a comma so that it is pronounced correct?
https://community.home-assistant.io/t/day-countdown-card/79900?u=rosemaryjayne
This might be helpful 😉
haha, yess, thanks. Id still need the template sensor though... i am using The Python script (birth)date count downer... but that doesnt account for hours,minutes.sec,, changing that would be somewhat overkill though
https://community.home-assistant.io/t/last-changed-xy-minutes-ago/149114/7?u=rosemaryjayne
{% set newYear = as_timestamp(strptime('31/12/' ~ now().year, '%d/%m/%Y')) %}
This might help, good luck!
thx! ```{% set newYear = as_timestamp(strptime('31/12/' ~ now().year, '%d/%m/%Y')) %}
{% set now = as_timestamp(now().astimezone())%}
{% set New = newYear-now %}
{%- macro phrase(name,divisor,mod=None) %}
{%- set value = ((New//divisor) % (mod if mod else divisor))|int %}
{%- set end = 's' if value > 1 else '' %}
{{- '{} {}{}'.format(value,name,end) if value|int > 0 else ''}}
{%- endmacro %}
{%- set values = [phrase('week',6060247),phrase('day',606024,7),phrase('hour',6060,24),
phrase('min',60),phrase('sec',1,60)]|select('!=','')|list %}
{{values[:-1]|join(', ') ~ ' and ' ~ values[-1] if values|length > 1 else values|first}}
hmm, 1 day off I guess...
{% set newYear = as_timestamp(strptime('01/01/' ~ Year, '%d/%m/%Y')) %}
{% set now = as_timestamp(now().astimezone())%}
{% set New = newYear-now %}
{%- macro phrase(name,divisor,mod=None) %}
{%- set value = ((New//divisor) % (mod if mod else divisor))|int %}
{%- set end = 's' if value > 1 else '' %}
{{- '{} {}{}'.format(value,name,end) if value|int > 0 else ''}}
{%- endmacro %}
{%- set values = [phrase('week',60*60*24*7),phrase('day',60*60*24,7),phrase('hour',60*60,24),
phrase('min',60),phrase('sec',1,60)]|select('!=','')|list %}
{{values[:-1]|join(', ') ~ ' and ' ~ values[-1] if values|length > 1 else values|first}}
I have a config template card. Found this example with 2 states:
${ states['cover.rolluik_achterdeur'].state === 'open' ?
'mdi:window-shutter-open' : 'mdi:window-shutter' }
That works fine, so far but I'd like to extend with 5 different icons based on the attribute current_position: xxx. Could someone help me how to change the code?
'Full' lovelace card yaml is:
entities:
- cover.rolluik_achterdeur
card:
type: entities
entities:
- entity: cover.rolluik_achterdeur
icon: >-
${ states['cover.rolluik_achterdeur'].state === 'open' ?
'mdi:window-shutter-open' : 'mdi:window-shutter' }```
I changed states['cover.rolluik_achterdeur'].state === 'open'to `` states['cover.rolluik_achterdeur'], 'current_position' === '100' just to see if the open mdi remains but that doesn't work
${ states['cover.rolluik_achterdeur.current_position'] = '100' ?
'mdi:window-shutter-open' : 'mdi:window-shutter' }```
seems to work, for a while... (to keep the shutter-open icon when the current_position is 100 but how create 4 more if's...
Read https://www.home-assistant.io/docs/configuration/templating/ and https://github.com/iantrich/config-template-card but really don't know how to get a valid working code. PLEASE HELP
That’s a #frontend-archived question
Asked question there but nobody replied...
Just tried:
variables:
covstate: |
covstate => {
if (covstate = 19) {
return 'icon = csi: shutter-O';
}
else if (covstate >= 20 && temp <= 40) {
return 'icon = csi: shutter-1';
}
return 'icon = csi: shutter-2';
}
covstate: states['cover.rolluik_achterdeur'].attributes.current_position
entities:
- cover.rolluik_achterdeur
card:
type: entities
entities:
- entity: cover.rolluik_achterdeur
icon: covstate'```
No luck
The code is used in lovelace frontend but the yaml is templating no?
template-card...
I struggle with template code syntax...
topic sais: we are here to help! 😉
This channel is for Jinja templates. That’s JavaScript for a card
The contributor mentions Typescript... I really don't know
Typescript is a form of JavaScript
No need
In the meantime I have found sometime that works. But is this the correct way to go?
{{ (states('sensor.daily_energy') | string | regex_replace(find=".", replace=",", ignorecase=False)) }}
There’s some extra stuff in there and it’s a bit heavy for what you’re doing
{{ states(‘sensor.daily_energy’).replace('.', ',') }}
okay i didn't now there is a replace method. This is much easer indeed. Thanks
Jinja uses Python objects, so Python methods work on them
okay
another question: Is it right that a template sensor value has a limit of 254 characters?
okay
maybe a crazy thing 🙂 But i was creating an overview sensor of my whole house with all kind of information in it and then use TTS to play it on my sonos speaker.
I noticed that from 254/255 characters the speaker was given: "unknown"
So i think the solution will be seperate sensors for this goal
Hi
How to work with static and dynamic lists of sensors?
need more details
https://community.home-assistant.io/t/how-to-work-with-static-and-dynamic-lists-of-sensors/372675
What i’d like to do is in case one or some of them are open - to notify me when i get back home.
My trigger for that automation is when my phone geo sensor tracks that im entering home and them the door opens.
The speakers then welcome me home.
What i’d like it to do is also let me know if some of those contact sensors are open.
For example:
“Welcome Ziv, the Coffee and Shower cabinets are open”.
In order to do that, i’d need:
To provide a static list of contact sensors to go over and see if they are “open” - how do i do that?
Create new dynamic list only with the “open” contact sensors - how do i do that?
Pass the list to the tts service - how do i do that?
I tried to search in the template syntax and in the forum with little to no luck (to my surprise BTW)
make a group of the sensors
{{ "Welcome Ziv, the following cabinets are open: {}".format(', '.join(on_sensors) if on_sensors else "Welcome Ziv. All cabinets are closed." }}```
can get more complex than that if you want to add an and in there but should suffice
thank you @dreamy sinew!
Let me see if i get that right.
- I need to use a group first. is there a way to list the sensors in this specific automation? or do i have to do it in the YAML file?
- attribute='name', what is that mean?
I think all the rest i got
just to be sure and not miss out on a maybe recently added option: we can only update template sensors each second by using an automation with - alias: Second updater id: Second updater trigger: platform: time_pattern seconds: '/1' action: service: homeassistant.update_entity ?
no other option in the template itself would trigger an automated update? (asking because I have this count down I like to see the seconds tick away #templates-archived message)
I have what I am sure is a simple issue, my trigger template sensor is not showing anywhere (e.g. I can't see it in dev tools). It's at the top of the file, the other (binary) sensors in the file are working 🤔
https://www.codepile.net/pile/1ra5eXrB
This is my template.yaml file which I have included in the configuration with template: !include template.yaml. Can anyone spot the obvious mistake?
Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.
- HAOS & Supervised use
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
The validator says it's fine, which is why I'm so puzzled!
(And rebooting works without an issue, but the core check says it's all ok 🤔 )
change trigger.id to trigger.entity_id
and take out platform: state in the sensor config.
Will do! Just doing a backup now.
you can list them directly in the automation if you want.
{% set on_sensors = expand('binary_sensor.sensor_1', 'binary_sensor.sensor_2')|selectattr('state', 'eq', 'on')|map(attribute='name')|list %}
attribute is a keyword argument for map it'll pull that attribute from all objects it collects into a new list
- trigger:
- platform: state
entity_id:
- binary_sensor.master_bedroom_sensor_motion
- binary_sensor.guest_room_sensor_motion
to: "on"
sensor:
- unique_id: last_occupied_room
name: Last Occupied Room
state: >
{{trigger.to_state.name}}
``` doing the job.
Hi, I am trying to replace the fixed value for kwh with a variable that I declared using the HACS Variable integration in the code below
- platform: template
sensors:
media1_cost:
friendly_name: Media1 Cost £/day
unit_of_measurement: £
value_template: "{{ (states('sensor.fridgefreezer_energy_today')|float*0.1838)|round(2) }}"
This works fines, but I have about 20+ sensors with power monitoring and dont want to keep changing it every time my tariff changes.
So I tried to replace the "0.1838" with the variable I created called var.electric_tariff in the template editor and get this error TypeError: can't multiply sequence by non-int of type 'float'
This is also not showing up, I think it's an issue with the file that it's on.
must be yes, because Ive explored it a but further, with:```
sensor:
- unique_id: last_motion_sensor_triggered
name: Last motion sensor triggered
state: >
{{trigger.to_state.name.split(' sensor Motion')[0]}}
attributes:
entity_id: >
{{trigger.entity_id}}
So, I rebooted, and now it shows 🧐
I shall put this under "quirks"
how odd. you needn't reboot though, simply reload template entities suffices...
Yup. I did that several times. But #beta gave me a reason. (I should have said restarted HA, not rebooted.)
ha ok, well, as long as you got it working 😉
You're good. it worked. thanks!
I am confused about how to access the last_updated property of given sensor state in the preferred way.
It's usually works like
states.sensor.xyz.last_updated.
But it fails for some entity-ids (auto-generated by homematic integration):
states.sensor.00095be98bXXXX_illumination.last_updated => invalid template (TemplateSyntaxError: expected token ')', got 'integer') for dictionary value @ data['binary_sensor'][0]['state'].
I got it working like
states.sensor['00095be98b5fb8_illumination'].last_changed
Then I got the hint, that I should not use states. at all. I can't use state_attr as I'm looking for a property, I tried states('sensor.sensor.00095be98bXXXX_illumination')
in different ways but couldn't figure out how to access properties.
last_changed is not an attribute, so state_attr() won't work in this case. You'll have to use states.entity_id.last_changed
I think it doesn't work without the square brackets because your object_id starts with a number
so nothing to improve 🙂 thanks
@rain geode posted a code wall, it is moved here --> https://hastebin.com/yirurajadu
I did not post code, sorry.
@rain geode posted a code wall, it is moved here --> https://hastebin.com/cilotoculi
Well, sorry but my copy paste is not working.