#templates-archived
1 messages ยท Page 148 of 1
so value_template: "{{ states('sensor.weather_wind_dir') }|float }" and not value_template: "{{ states('sensor.weather_wind_dir') }}" ?
You did it in the first one
dooh yes saw it now
btw... the file is saved as UTF-8 but i cant use the special danish chars we have in the alphabet ( ร ร ร ) they are replaced with ? so the wind directions look stupid
have i made another fail?
https://pastebin.com/fqWTkecu
does not work, icon is still the watching eye
figured it
@buoyant pine - Just wondering if you had any time to look at that MQTT integration for that json output from whatsminer
Curious if anyone has a template that will show on the sidebar when the front door is locked or unlocked....
@zenith junco yeah, i sent you some DMs on sunday
Oh... Shoot I didn't see them, it didn't flag it as message waiting for me. I'll take a peek. Thanks much
Wow - that is awesome - I'll work on it tonight
i was wondering if i had just scared you away ๐คฃ
Nope, just never saw it, Very excited!
unfortunately i have no way of testing it, so if there are issues, i'll be relying on you for logs
Sounds good!
Figured one out...
- platform: template
sensors:
front_door_status:
friendly_name: "Front Door Status"
value_template: >-
{% if is_state('lock.front_door', 'locked') %}
Locked
{% else %}
Unlocked
{% endif %}
value_template: "{{ states('lock.front_door').title() }}"
you made it easier haha
i added this to my raw config for my sidebar. The status changes from locked to unlocked just fine, but I want to add an icon to change based on locked/unlocked.
<li>
The front door is {{states('sensor.front_door_status')}} {{'\U0001F512'}}
</li>
@main spade posted a code wall, it is moved here --> https://hastebin.com/iqofokujav
lmao
This is probably really easy but i'm missing something.
I'm trying to provide a local image to the TV notification service, but i believe the output is missing quotes.
path: '{{state_attr(''camera.front_door'', ''entity_picture'')}}'
turns to
/api/camera_proxy/camera.front_door?token=xyz```
I believe /api/camera_proxy/camera.front_door?token=xyz needs to be surrounded in "" quotes. How can I do this in the template?
ah nvm i think the issue is that my path is not public?
Does the current icon work? If so, you can do something like:
The front door is {{states('sensor.front_door_status')}} {{'\U0001F512' if is_state('sensor.front_door_status', 'locked') else '\U1234ABCD'}}
Yeah.. icon works.. Just tried that code snippet and it doesnt seem to work though
I assume you changed the 2nd icon to something actually existing, and not the gibberish I've put there
Hey guys, my data_template seems to be broken but i can't figure out what's wrong: https://pastebin.com/0upYS8yv
It says i'm missing a comma?
the first one
ugh i just found it. it's incorrect indentation, not comma. I'm using the file editor add-on
BTW, you could simplify them if you use an `{% else %} to default to the most frequent option
eg the last one could be:
{%- if is_state("input_select.vent_vsr500_mode", "High") %}
4
{%- elif is_state("input_select.vent_vsr500_mode", "Medium") %}
3
{%- else %}
2
{%- endif %}
Hmm there still seems to be an issue with the ventilation get mode
thanks! Good idea
You did not define a result for some of the options in the ventilation get mode
If you format your template like I did, it would be clear immediately
hmmm ok i think i see it. It's the ones with the switch in them
Yes... The front door is {{states('sensor.front_door_status')}} {{'\U0001F512' if state('sensor.front_door_status', 'locked') else '\U0001F513'}}
@marble jackal posted a code wall, it is moved here --> https://hastebin.com/zanulivito
Right, thanks ๐
Whoops :), well look at the link
I had a typo.... worked @marble jackal thanks!
You had state instead of is_state
argh it's still saying i have an issue
Invalid config for [automation]: [data_template] is an invalid option for [automation]. Check: automation->action->0->target->data_template. (See /config/configuration.yaml, line 9).
Well, data_template is already depreciated for ages now
what should be used instead?
data: and you should remove 2 spaces in front of it, you now placed it under target:
i see it
also remove 2 spaces in front of option: and leave the template where it is. It should be intended 2 spaces
it's becoming worse hehe
Invalid config for [automation]: template value should be a string for dictionary value @ data['action'][0]['data_template']. Got None. (See /config/configuration.yaml, line 9).
Well, if you renamed data_template to data, then this is about another automation
I see you did not do that
Check the template in
> template
it probably doesn't give a result
the first error is the old one
testing it now. And yeah it's complaining about a missing paretheses
fixed that
now it seems to give a result. i didn't know about the template developer tool
Well, now you do ๐ Really nice to build your template there before you add it to your config
yeah absolutely
How do I get 20:00 from 2022-01-28T20:00:00Z ?
what have you tried
How can I use the value of an input select in an automation ?
I know about is_state but I want the value and not checking each value
A lot of weird things. ๐ For instance | timestamp_custom('%H:%M:%S',default=none) as postfix. Did nothing.
states() @lime radish
post your full attempts and we can point out what's wrong
for example, post the full attempt you have there, because it's close
Because that's what it is? https://www.home-assistant.io/docs/configuration/templating/#states
{{state_attr('sensor.something', 'Pickup start') | timestamp_custom('%H:%M:%S')}}
So i wanna use my last called alexa, i got a sensor that states the last used alexa (sensor.last_alexa)
timestamp_custom requires a timestamp. Is Pickup start a timestamp, string, or datetime object?
now i wanna use the notify service but
notify.{{states('sensor.last_alexa')}} doesnt work
Pickup start: '2022-01-28T20:00:00Z' says devtools. Does that mean string?
post your entire notification, also make sure you're using the correct notification service and it matches the alexa_media_player requirements for a service call to a media_player.
I.e. look at the alexa_media_player docs
don't use the offical docs because alexa media player is custom
yes
so you have to convert it to a timestamp (which is an integer)
- service: notify.{{states('sensor.last_alexa')}}
data:
message: ok
data:
type: tts
before i used a set echo via
and what's the state of sensor.last_alexa?
- service: notify.echo_kitchen
data:
message: ok
data:
type: tts
Ah, thanks. {{as_timestamp(state_attr('sensor.something', 'Pickup start')) | timestamp_custom('%H:%M:%S')}} worked
notify.{{states('sensor.last_alexa')|string}} returns notify.media_player.uhr
as a string
does notify.media_player.uhr look like a valid entity_id?
yep
np
@glossy aurora posted a code wall, it is moved here --> https://hastebin.com/baregacapa
i have used the {{trigger.to_state.name}} field to let me know which device triggered a automation however i have a automation set up that when my people group is not_home to check all my door sensors and if one of them open to alert me. how would i do the same type of thing but reference a condition instead of a trigger??
as in which condition was true? conditions are "and" by default
yeah
and with a more complex condition, there's no straightforward way to identify the thing that caused it to be true because it's a condition and not a trigger
gotcha. yeah basically i just have a simple automation when everyone leaves, check if all the doors are closed, if 1 door is open send me a notification telling me a door is open. it would be awesome if it could tell me "which" door is open
you can do that with a choose: or a template in the action
You'd have to do it in the body of the script. Use a choose block. If all doors are closed, do your thing, else figure out which door is open and notify.
a template would be straightforward and could be embedded directly in the notification
Absolutely. Both work.
i dont see a choose section or anything on the template literature?
alright thats where im reading currently
Quick question for you all. What is the scope of variables set in templates? (e.g. {{ set b = 0 }}.
I try to do a loop that ramps up brightness to a light fixture over time. I'd really like to have a variable that is the current brightness and just increment that by a step value until it exceeds a max. I tried doing that with {%...%} syntax but am getting undefined errors.
local scope
you can use automation variables that extend the scope to the entire automation
however, the scope will still be limited to the loop only if you define the variable inside the loop
looping like that has to be done with the repeat action
Makes sense. So can I modify a script variable within a template statement?
Or is there any other way to modify an existing script variable?
You can't overwrite what's passed to the script
so, just create a new variable
using a variables action
Yeah, I'm not passing anything to the script, just defining some vars via the variables statement. Can those then be modified later in the script somehow (template or otherwise)?
Hi there, I'm trying to trigger an automation with the following template code but can't seem to get it working, any ideas what I'm doing wrong?
platform: template
value_template: >
{%- set output = namespace(sensors=[]) -%}
{%- for state in states.sensor | selectattr('attributes.device_class', '==', 'battery') -%}
{%- if 0 <= state.state | int(-1) -%}
{%- if state.state | int <= 20 -%}
true
{%- endif -%}
{%- endif -%}
{%- endfor -%}
that won't return true/false
that will return true, true, true, true, true
also your if statement for 0 <= state seems suspect, that's going to always resolve true unless the state is invalid
Hi, sorry for Interruption your chat. I have a issue with my garage door. I have created a
- platform: template
covers:
garage_door_left:
device_class: garage
# ...
It's working so far, Only thing what's annoying is that when I open the door and let's say after 2 seconds I stop it. I can't click open (up arrow) because it's greyed out
Thanks @mighty ledge, I'll try to work out how to return true/false.
your value_template doesn't account for that state then
what's the end goal with that trigger
@plucky wyvern posted a code wall, it is moved here --> https://hastebin.com/dugavewufo
To send a device low battery alert to my phone
Ok cool. I will have a look at that. Thank you very much ๐
np
platform: template
value_template: >
{%- set output = namespace(sensors=[]) -%}
{%- for state in states.sensor | selectattr('attributes.device_class', '==', 'battery') -%}
{%- if 0 <= state.state | int(-1) <= 20 -%}
{%- set output.sensors = output.sensors + [ state ] %}
{%- endif -%}
{%- endfor -%}
{{ output.sensors | length > 0 }}
keep in mind, it will only trigger when you go from zero low batteries to n low batteries. Each additional battery will not trigger this.
@topaz cave
lovelace doesn't accept templates and if it did, you're missing the outside quotes
Sorry, I don't know what I am doing wrong. At the moment my code looks like this:
value_template: >-
{% if is_state('binary_sensor.garagentor_links_auf_status','on') %}
open
{% elif is_state('binary_sensor.garagentor_links_zu_status','on') %}
closed
{% endif %}
I have two sensors for open and closed as you can see. How can I tell HA the middle state?
you have to define them
you have 4 cases
on-on, on-off, off-on, and off-off
I would wager that on-on is impossible
so you only have 3 cases you need to check
only if error
{% set auf = is_state('binary_sensor.garagentor_links_auf_status','on') %}
{% set zu = is_state('binary_sensor.garagentor_links_zu_status','on') %}
{% if auf and not zu %}open
{% elif zu and not auf %}closed
{% elif not zu and not auf %}opening
{% else %}none
{% endif %}
@mighty ledge Thanks so much.
Unfortunately it's also not working. My up arrow is still greyed out and my door is now in the middle of open and closed
if it's partway open, it should work as long as the state is opening
Hi guys,
I'm currently trying to dimm some light's. Since there are multiple of them I added their names to a input_select. And then build a template_light around that. Now I need the template_light to accurately report the current brightness level of the selected light. I just can't seem to figure out how to get it.
- platform: template lights: lichter_unten: friendly_name: "Lichter unten" level_template: ?? turn_on: service: light.turn_on target: entity_id: "{{states('input_select.lampen_unten')}}" turn_off: service: light.turn_off target: entity_id: "{{states('input_select.lampen_unten')}}"
@onyx juniper "{{ state_attr(states('input_select.lampen_unten'), 'brightness') }}"
Thank you @marble jackal , that did the trick ๐
That did it. Thanks. I'm now trying to get the friendly names of the sensors in sensors to use in the action (notification) part.
hi all How can i convert the below text into 2 switches in home assistant using Json??
tele/GNSPanel01/RESULT {"NSPanel":{"ctype":"group","id":"1","params":{"switch":"on","switches":[{"switch":"on","outlet":0}]}}}
tele/GNSPanel01/RESULT {"NSPanel":{"ctype":"group","id":"1","params":{"switch":"off","switches":[{"switch":"off","outlet":0}]}}}
tele/GNSPanel01/RESULT {"NSPanel":{"ctype":"group","id":"2","params":{"switch":"on","switches":[{"switch":"on","outlet":0}]}}}
tele/GNSPanel01/RESULT {"NSPanel":{"ctype":"group","id":"2","params":{"switch":"off","switches":[{"switch":"off","outlet":0}]}}}
You mean something like this?
{%- set sensors = [ 'sensor.aqara_1', 'sensor.aqara_2', 'sensor.aqara_3' ] %} {{ expand(sensors) | selectattr('last_changed', '<', now() - timedelta(minutes=15)) | map(attribute='attributes.friendly_name') | list }}
Hey, not sure how to search for the answer to this so thought human interaction might get faster results... What is the [[[ ]]] notation for in templating?
thats JS templates and it only exists for custum button card and Custom UI
if you don't have those custom items, then those templates are meaningless to you
@peak lynx posted a code wall, it is moved here --> https://hastebin.com/oyejomafic
I have those templates and I'm trying to learn more about it. Where is this documented?
Hey folks, quick question - can set a variable in the middle of a template?
I know I can do
{% set foo = "bar" %}
{{ foo }}
But what do I do if that's a place that's expecting just a print statement?
(for example, a template sensor)
Can I do this?
value_template: >-
{% set foo = "bar" %}
{{ foo }}
Yes, that works fine
it wasn't working for me, but I think maybe I was doing something wrong, then
Cool, thanks - by the way, is there a way to make HA re-reat the state of certain sensors without restarting HA?
i.e: If I want to make changes to my template sensor, restarting HA multiple times is somewhat tiresome.
Reload template entities from server settings
I don't have that option
It should be there, as long as you had at least one template entity the last time HA started
I have
- Location & customizations
- Automations
- Groups, group entities, and notify services
- Input booleans
- Input date times
- Input numbers
- Input selects
- Input texts
- People
- Rest entities and notify services
- Scenes
- Scripts
- Timers
- Zones
I'm running Home Assistant 2021.12.8
Well, except for the first one they are ordered alphabetically, it should be between Scripts and Timers.
But are you sure you already have a working template entity?
I mean, I thought so...I have a "working" template sensor that's pulling in data (albeit the wrong data)
is there a way to check?
That should do the trick. Not what's the issue with the wrong data?
Oh, y'know what...I'm an idiot ๐คก
I don't have any template sensors
I have a rest sensor that's using templates to manipulate the data
๐คก
Then you should reload Rest entities and notify services
Yeah :p
Though, saying that - the data I'm getting back from it still doesn't make sense.
So, here's my REST sensor:
- platform: rest
resource_template: "https://www.republicservices.com/api/v3/holidaySchedules/schedules\?latitude\={{ state_attr('zone.home', 'latitude') }}\&longitude\={{ state_attr('zone.home', 'longitude') }}"
name: 'trash_holidays'
json_attributes_path: '$.data'
value_template: "OK"
json_attributes:
- date
- description
- name
- specialNotes
I would expect the value of that sensor to be "OK"
Right now it's showing (probably stale) data from the API endpoint.
With value_template: "OK" I would also expect that
I should point out - those escape sequences in that URL are wrong, so I've fixed that...but it's still not getting me "OK"
So if you put that template in
> templates and paste the result in your browser, you get some json?
The resource_template
yeah
The "states" tab in dev tools is showing me stale JSON data again
I'm also seeing errors in my logs that don't make sense
Template variable error: No first item, sequence was empty. when rendering '{% set date = value_json.data | map(attribute="date") | map('as_datetime') | select('gt', now()) | list | first %} {{ (value_json | selectattr('LOB', 'equalto', 'Residential') | selectattr('date', 'search', date.isoformat().split('+')[0]) | first).name }}'
I previously had that code in value_template to parse the JSON returned from the server, bu tI took it out for debugging and HA seems to think it's still there.
I'm running HA in a container - I wonder if my updates to the config are somehow not being persisted into the container
Nope, looks like it's there.
Maybe a silly suggestion, but did you save your changes before reloading?
Yeah I did
...offs.
I was editing config/sensors/date.yaml
The actual sensor being referenced is in config/sensors.yaml
๐
๐คฆโโ๏ธ
Please excuse me while I move to mongolia, where I will live out the rest of my life as a goat.
๐
Anyway - one actual question I did have....in what order are the manipulations applied?
So, I can obviously manipulate the data returned using value_template
...but also the values returned using json_attributes
The API returns something like this:
{
status: 200,
data: []
}
I'm tweaking my value_template so that it filters the $.data and gets the first result, but I'm not sure in what order those two things affect each other if that makes sense
So, if I make my value_template return an object, will that break json_attributes?
I don't have experience with these sensors, but I would say the value_template is what the state of the entity will be. It has no effect on the attributes
Right, but I'm trying to figure out if value_template gets fed the output from json_attributes or the other way round
Neither I think. For the value_template you can use all the data in the json (and even other data from HA). The attributes are a select part of the json data
But again, based on no experience with these kind of sensors ๐
But as the attribute data is a part of the full json data, you can use the attributes in your value_template
Wait....so json_attributes provides the actual attributes and value_template provides the actual state value.
...oh.
I mean, I guess it was kind of obvious but...
For some reason, I thought they both provided the state attributes.
I take it, one can't manipulate the json_attributes?
In this example you could add .status to get 200
Okay? Why might I do that?
Because that might be the value you're interested in instead of the complete dict
It was just an example
Gotcha.
Yeah - so this is the website of the company that does my trash pickup.
That status will likely never be anything other than 200
data is a list of upcoming holidays and whether or not it affects trash pickup
lemme get you an example
@tired sandal posted a code wall, it is moved here --> https://hastebin.com/igeqakamaf
[
{
"date": "2022-01-01T00:00:00.0000000Z",
"description": "Your pickup will be delayed by one day due to the holiday.",
"name": "New Year's Day",
"specialNotes": ""
},
{
"date": "2022-05-30T00:00:00.0000000Z",
"description": "Your pickup will be delayed by one day due to the holiday.",
"name": "Memorial Day",
"specialNotes": "Service will be on a one day delay due to the Holiday this week. Please place your cans out by 7 A.M. the day after your normal scheduled pickup day. Happy Memorial Day from Republic Services."
}
]
There.
So, right now I'm getting back New Year's Day because it's the first element in the list.
Really, what I want is Memorial Day because New Year's day is passed and I don't care about it.
Thinking about this some more, perhaps it would make sense for the value to simply be true or false to indicate whether or not there is a disruption. And then, the state attributes to contain the dict explaining what the interruption is.
The only issue is that I can manipulate the value- but not the state attributes. So I can manipulate the value to search for the entry I want that's after today...but there seems to be no way to do that for the attributes.
Do the attributes provide a list with all data in the json data?
is this automation is ok?
I want to try for first time trigger.id in automations..
I don't think light.turn_off allows brightness
but there is some kind of error, if I put just this in my yaml file
- platform: time
at: "00:00:00"
trigger_id: "on"
- platform: sun
event: sunrise
trigger_id: "off"
action:
- service: >
light.turn_{{trigger.id}}
entity_id: light.bedroom_wall_wled```
But you can template the entire data section:
data: >
{{ {} if trigger.id == 'off' else { 'brightness': 1 } }}
some kind of error ๐ง
I mean, they could - why?
Ah, right. I missed that
I could probably set json_attributes_path: '$.data' and that would just load all the events into attributes.
..wouldn't it?
Don't know, but if you have the data of more than just the first date, you can use templates to actually get the information you want (like the next date the pickup date will be different)
how do I do that though?
By use of templates
Not in the sensor itself, but you can create an actual template sensor (the ones you can reload with the template entities button) based on that data
Yeah - what about this for an idea
- I screw with the
value_templateto represent the next holiday date. - I then use that date in a template sensor to query the data and pick out the stuff I need.
Does that seem like a reasonable way to do this?
Well, 1 should not be a big problem to actually achieve though
Yeah. I already have the code to do that (more or less)
If I have a REST sensor - can I use templates inside json_attributes_path?
make a template sensor out of it:
attributes map (optional)
Defines templates for attributes of the sensor.attribute: template template REQUIRED
The attribute and corresponding template.
Right, but that still doesn't really solve anything
why?
...let me rephrase - I can't figure out a way to make that work
you wanted a template, and that lets you use a template
Right, but I want a dictionary and afaik you can't have a dictionary as the state value....can you?
Because I need a way to store the dictionary. Seemingly I can only do that in state attributes, and I can't find a way to set arbitary attributes in state.
I'm aware
set the attributes however you want with a template
with whatever data type you want, from whatever source
So, I can use templating for state attributes in a template sensor?
Right, and I can do that without having to have one sensor for each attribute?
Right.
So that brings me to my next problem.
I make the REST request to get the data from that endpoint, I filter it down and extract the date of the next trash holiday
I need...somewhere to store the rest of the data so that I can then query that data using the date
So. For example..
sensor.next_trash_holiday - the state of that sensor is 2022-02-21T00:00:00+00:00
(I made it a datetime device class)
But that isn't helpful unless I can somehow store the list of objects somewhere...
in the attributes
Yeah, I tried that - I got an error.
One sec lemme paste my code.
if you go straight to the actual problem, it will go faster
it sounded like you just needed a template
I'm not entirely sure what I need
- platform: rest
resource_template: "<URL>"
name: next_trash_holiday
device_class: timestamp
json_attributes_path: '$.data'
json_attributes:
- date
- name
I've snipped out the value_template field
Anyway, that gets me this error: " JSON result was not a dictionary or list with 0th element a dictionary "
Which is odd because as far as I know, the API response looks like this:
{
status: 200,
data: []
}
there's no date or time in there
Right. Each element in data is an object that has name and date
and that's a list
Yeah. It's expecting a dictionary, or list that has a dictionary as the 0th element
you see that data there is an empty list?
Forget all of what i wrote - here's the complete API response: https://www.toptal.com/developers/hastebin/waxaresesu.json in a (p|h)astebin
You might need something like $.data[*], but I'm no JSON path expert. I'm just poking around here: https://goessner.net/articles/JsonPath/
Yeah, maybe - I'm playing with this: https://jsonpath.com/ and just $.data seems to work - but it's likely a completely different implementation from the HA/Python one.
Y'know what....on that link I posted using just $.data wraps the whole thing in an array
In any case, I don't think a template is what you need here
Good to know, thanks.
magic
Yeah, I was looking at the json path syntax but didn't spot that.
I was trying [.] etc.
this set of examples seemed useful: https://goessner.net/articles/JsonPath/index.html#e3
Hmm....$.data[*] looks to have just returned the 0th element
I'll keep digging though
I would just have to play with it
Yeah, I was going to ask if I could play with this in the templates thingy
does that have a json path parser?
that's for Jinja
Thought so.
Wasn't sure if json path was some kind of magic run though jinja or not though
guess not
Ah, it seems to be working now with $.data.* but it looks like the state attributes just stores the 0th element
I think this is why I thought I needed a template.
...yeah - I can't get it to let me store a list in the attributes for a sensor, only a dictionary. Is there something I'm missing?
Hello all, I search an idea to make a template for make a multi price (time base) for electricity from one general counter
so now().weekday is 0 to 6 and now().month is 1 to 12 ?
EDIT: day to weekday
Correct
And day 0 is Monday
ty alot
Wait a sec, I was mistaken. now().weekday() is 0 to 6
now().day is 1 to 31
mb
i used weekday
so my 0 to 6 is right
sorry
is there a delay function via templates ?
delay what
i wanna use it in a tts msg
How do you mean? A template can't perform an action, do there is nothing to delay
you'll have to elaborate because that still doesn't make sense
if you want to delay the notification, add a delay service call before the notification
Hi my name {%wait 2 sec%} slimshady
that's not possible
I doubt any notification service would support that either
it'll be 2 notifications, separated by 2 seconds
you can do that with choose
how would that look like ?
{{ [
'xyz.',
'zwerw.',
'twetw.',
'454353',
'234234 (HERE I WANT TO WAIT 5 SECS) 2354252'
] | random }}
yep, you can still do that with choose
alright will look into it
you'll need to use variables to set up the random choice and then your actions will be based on that choice using choose
How to get the data from history and make calculation on that? For example, there is a step counter from android which stores the data as cumulative (total_increasing). How can I extract the data for , say each day? The History_Stats platform does not help as it needs a specific state and the state in this entity changes based on the steps
The sql sensor is the only way
Hmm. Will use appdaemon then much simpler for me
Iโd be surprised if appdaemon has access to history unless itโs a new addition
I want more organic tts msg, so i created random answers. Now i got a script for "Interruptions" like "pardon me", "sorry to interrupt" etc.
Now I wanna use this script before other tts scripts. The problem is i cant define a static delay since every interrupt msg has a different playtime. Is there a way to check if the tts is done before doing the next tts
right now my 2 tts msg clip into each other
and i dont wanna add the interruption part to every tts msg i need . it
would be alot of copy&pasted code
cant I define the random part as an overall function
then just call {{ randommsg() }} in my scripts where i need it ?
cant check if my media player is idle or not
got a work around see #automations-archived
Hi, can I pass a variable from the trigger template to the action in an automation? I see that I can use trigger.entity_id but what if the trigger is a template?
The available template trigger variable are listed here https://www.home-assistant.io/docs/automation/templating/#template
Thank you very much
Does that mean that if I have this in the trigger:
{%- set sensors = [ 'sensor.aqara_1', 'sensor.aqara_2', 'sensor.aqara_3' ] %}
{{ expand(sensors) | selectattr('last_changed', '<', now() - timedelta(minutes=15)) | list | count > 0 }}
I cannot use sensors in my action?
Correct.
Is there a way I can use a template to check if a specific event happened within the last minute? I found something that works for last_triggered towards an automation, but I want to check if an event coming from an actionable notification has happened in the last minute...
FWIW, here is the template I get to work on the automation:
{{ (now()|as_timestamp - state_attr('automation.notify_if_garage_door_is_open_at_night','last_triggered')|as_timestamp) < 60 }}
Entities have a last_changed object
But events are not entities, are they?
No, my bad, didn't read properly
Is it really one specific event? You can create a binary_sensor with the event as trigger
It is really one specific event. So I have an actionable notification triggered at 10pm every night to remind me to close the garage door. If I click the action on my phone to close the door, and th state still is open a minute later, I am sending a reminder notification that warns me that something might have blocked the door from closing. But I don't want the reminder notification to be sendt if I did not click to close the garage door to begin with... If that even makes sense...?
Makes sense
So I was thinking that I can put a condition in there, that only allows sending the reminder notification if the event from the notification has happened during the last minute or so
But, I cannot see if there is a way to check that...?
You can also use a wait_for_trigger which waits for the event, with a timeout of 1 minute, and sends the reminder on wait.completed
๐๐ผ
What ended up working was your inital idea of using the template binary sensor with an automatic 65s timeout... That way, when the minute (wait/delay) has passed, if the sensor is on, the reminder is sent. It works perfectly! ๐
I believe it is there for sometime already. https://appdaemon.readthedocs.io/en/latest/HASS_API_REFERENCE.html#appdaemon.plugins.hass.hassapi.Hass.get_history However, constantly accessing it is not advised, hence will be creating separate store (say 1 daily record) based on initial access.
Morning all! Trying to take an attribute from Sonoff S31 for power and current into its own sensor. The values shown in Developer are floats like 0.08 and 5.11.
This isn't working. Hopefully something simple for you all.
- sensor:
- name: Wheelchair Charger Plug Power
state: '{{ switch.sonoff_10011f94d9.attributes.power | float }}'
unit_of_measurement: 'Watts'
state_class: measurement
- name: Wheelchair Charger Plug Current
state: '{{ switch.sonoff_10011f94d9.attributes.current | float }}'
unit_of_measurement: 'Amps'
state_class: measurement
Good afternoon
You should use state_attr('switch.sonoff_10011f94d9', 'power')
And casting it to a foat is useless, as the state will be a string anyway
unexpected scalar at node end
probably because you also use single quotes outside your template
use different ones inside and outside the template (I always use double quotes outside, that's why I used single quotes in my example above)
What you had is advised against, and you should have put states. in front of it
ahh so states.switch.[..]
ok double quote resolved the error...restarting
GG, worked like a champ using first example. Thanks!
You dont't have to restart, you can reload template entities from server controls
hello I would like to pull a topic to a sensor state, and every 10 seconds refresh the sensor, and when I do that I would like to retrive the current sensor:
- trigger:
- platform: mqtt
topic: "room_presence/+"
payload: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-100-1"
value_template: "{{ value_json.id }}"
- platform: time_pattern
seconds: "/10"
sensor:
- name: Room Updates
state: >
{% if trigger and trigger.topic %}
{% set sensor = trigger.topic.split('/')[1] %}
{% else %}
{% set sensor = this.state %}
{% endif %}
{{sensor}}
this works with the mqtt trigger, but when I get the time trigger I get a error
"'this' is undefined"
is there a way to retrive the current state and the current entity_id?
"this" is for information about an automation or script, not a specific instance or trigger
so we can't use the this in the template of a sensor
I don't know what it would represent there. If it's saying that it's not defined, no
you can just use states('sensor.xxx')
I want to show the week number in a lovelace dashboard. I suspect i can do this setting up a Template sensor.
Anyone have any idea how i would do this?
This returns week 5 for today, however, there are different ways to determine the week number
{{ now().isocalendar().week }}
Wonder if someone can help me at all. I have an API endpoint that returns a list of data. I'd like to load the one element from that list into state attributes based on a criteria (rather than just the first element, which seems to be the default). How do I do this?
{
data: [
{ "date": "2022-01-01", "name": "Event 1" },
{ "date": "2022-02-09", "name": "Event 2" },
{ "date": "2022-03-14", "name": "Event 3" },
],
}
Right now, if I point json_attributes at $.data for json_attributes_path it'll just load $.data.0 into state attributes, and there doesn't seem to be a way to control that behavior.
I can write code to manipulate the sensor value, but that doesn't really get me anywhere because that can only ever be a single value.
Which one do you want?
Is there a standard as to how your .yaml files should be, what to include where, how to reload on that part etc etc. I keep meaning to tidy stuff up and I never get around to doing it. My configuration.yaml is a mess. I only recently made a templates.yaml file and even then I'm not sure what actually goes into it? Right now I'm about to create a rest sensor and I've no idea where I should put it..
hello all! I have several warnings in my config, most of them on boot time, that say "{{ states('sensor.time')|as_timestamp }}", got invalid input 'unknown' when rendering template. I know the reason, just don't know the best way to solve this. I tried default, but does not assume "unknown" as a rigger to default. What is the best way to solve this that does not need me to add a bunch of lines to my yaml checkig all as_timestamp if the variable is loaded or exists?
The integration docs tell you exactly where to put them. As for managing your config https://www.home-assistant.io/docs/configuration/splitting_configuration/
Checkout the 4th pin
and you might want to use now() instead of states('sensor.time')
That was not my question... I would like to know if there is a default equivalent that matches unknown.
I use this sensor when I need a refresh lower than 1 minute...
none
Well {{ states('sensor.time') | as_timestamp }} gives null for me in
> Templates
So I doubt that is what you want
do you have a sensor called "sensor.time" ? that is way ๐
as_timestamp never worked on HH:MM format
so that will always return none
null/none
template:
- trigger:
- platform: time_pattern
seconds: "/10"
sensor:
- name: "time"
state: "{{now()}}"
anyways, to explicitlly answer your question: none is what you want to use
i only use this sensor to trigger the refresh in some sensor every 10 seconds
ah, you're using a template sensor to create sensor.time, not the built in sensor.time
that explains it
the problem is when HA is starting the sensor is not loaded... and I get a lot of warnings
here
here
here
I assumed you were referring to the standard sensor.time created by the platform: date_time sensor. ๐
Which I had in my config
Cool, so if I created "sensor: !include sensors.yaml" what server control button would reload this?
potentially many or none
depends on the sensor platform and if it supports hot reloading. templates do for example, so reload templates would reload any template sensors in that file
Ah got ya! So it actually doesn't matter what sensors are in the file it will only reload the platform that supports it, eg templates? I don't see rest listed so I assume it's not supported
and restarted
(which is the case for anything that supports hot reloading)
Oh so the button will actually appear once I've created something that uses it (and restarted HA)?
may appear
depends on the integration
and the platform that it's using
add -> restart -> check if button exists, if yes, use button, if no, cry
however, some integrations allow for a reload service, but the button does not exist in the reload page
I'll give it a go and hope I don't cry!
it's inevitable with HA
Tears of joy, maybe
how
how what
to make it lool like soloam sent erlier
you can't
... well this wil do.
sensor_type: server_power_readings
unit_of_measurement: "W"
value_template: '{{ ilo_data.present_power_reading }}'```
you mean format?
HP ILO Power Usage 2
(166, 'Watts')```
nice
anyways, your '{{ ilo_data.present_power_reading }}' isn't valid
explain what you expect it to do
the config.ya... is:
sensor_type: server_power_readings
unit_of_measurement: "W"
value_template: '{{ ilo_data.present_power_reading }}'```
output is:
```sensor.hp_ilo_power_usage_2
HP ILO Power Usage 2
(166, 'Watts')
i want a pure result i can input in energy tab
was that understandable?
not at all
would be easy to send pickture but..
everything about that configuration is wrong
unless you aren't using the normal template sensor
nono i have a platform and host.. just sent the data i have trouble with
what integration
hp_ilo
ok, so then that is a valid template
host: XXX.XXX.XXX.XXX
username: XXXX
password: !secret ilo_password
monitored_variables:
- name: Power Usage 2
sensor_type: server_power_readings
unit_of_measurement: "W"
value_template: '{{ ilo_data.present_power_reading }}'```
whoever made that went against all HA rules and chose a random ass variable name instead of using the standards
is the state of the sensor (166, 'Watts')?
yes
value_template: '{{ ilo_data.present_power_reading[0] }}'
i want a result i can input in Energy tab. any ideas?
aaa
so close i have tried ".currentreading[0]"
that integration is a perfect candidate for config_flow without needing templates
GR8 its exactly how i wanted it! THX
np
Hi.. Did something change lately? This construct does not evaluate to true any more... {{ as_timestamp(now()) >= as_timestamp(states('input_text.morning')) }}
helper contains a datetime
nothing changed recently. Check for errors in your logs.
Ok. will try that then.....
I suppose there are no better ways to compare this, or datetime objects?
datetime objects but input_text.morning will always be text
why even use an input_text when you have input_datetimes or just regular sensors
I found them earlier today, so yes, agree they would seem to be abetter fit, but still compares as string though
right, but it ensures that it's a valid datetime for conversion
true
where as there's no safety with input_text
and your template doesn't have safety either
{{ now() > states('input_text.morning') | as_datetime or now() }}
make sure your text datetime string contains a timezone, otherwise this won't work.
Cool! It is timezone aware, will try this, thanks!
Thanks @mighty ledge! It unlocked so much, works great ๐
Hi,
I have a problem with an API answer I get. It should be json but is somehow wrong formated from the provider of the API.
What I get is:
"{"DeviceResponse":[{"DeviceID":"abc","DeviceName":"xyz","Medium":"Oil","LastUpdate":"2/1/2022 7:40:02 AM","MaxVolume":"5000","ActualVolume":"3645","ActualVolumePercent":"73","Battery":"2.7","Temperature":"33","MessData":"57"}]}"
the escaps with \ before each " are not shown in the chat
I also can't test it in the Developer Tools - Template as I get: TemplateSyntaxError: unexpected char '\' at 124
my workaround is using command_line and to: 'sed "s/\//g" | sed "s/"{/{/" | sed "s/}"/}/" | jq'
would be there a better way to clean the response?
is something like this legit storing to a variable to shorten the actual if/else lines:
- name: Wheelchair Charger Status
state: >
{% set chg_current = (state_attr('switch.sonoff_xxxxxxxxxx', 'current') | float) %}
{% set chg_state = states('switch.sonoff_xxxxxxxxxx') %}
{% if chg_state == "off" %}
Off
{% elif chg_state == "on" and chg_current >= 0.04 and chg_current <= 0.09 %}
Fully Charged
{% elif chg_state == "on" and chg_current > 0.09 %}
Charging
{% elif chg_state == "on" and chg_current < 0.04 %}
Idle
{% else %}
Off
{% endif %}
ya but you can make it easier by using is_state('xzy', 'on')
then your ifs would be
NM, after finding one set example I now edited what I posted. I tested with templates developer and it did work
ahhh nice but the one i want "off"
0.04 <= chg_current <= 0.09
nice didn't know could do that with the in between
yep
if I do is_state() how would the first "Off" be written does "!" == not
if not chg_state
np
can I tie in an icon change with same logic and in the state: or do I have to replicate it under the icon:
Is it possible to get info from attributes if the attribute is an object? or an array of objects?
Yes
Can you give a more clear example? Maybe a copy of what is shown in
> states
If it is a lot of info, use:
~share
Hmm, bot is unresponsive
Well, a code share site
Yes, I'll put it on codepile... hang on...
I would like to get price and lastupdated from stationdetails[1]... https://www.codepile.net/pile/VqkP8ejE
state_atrr(entity, attribute)[1].price
Oh, nice... Works like butter (and it's case sensitive, I just found out), but you knew that. THANKS!
Everything in YAML/Jinja is case sensitive
I was hoping I could set entity_picture on a template sensor, but that seems to be impossible... Is this right? Do I need to add it in customize.yaml?
And for the legacy format:
https://www.home-assistant.io/integrations/template/#entity_picture_template
Doh... My reading skill needs an update... Thanks โบ๏ธ
hi =) if defining a template sensor. is there a good way of referring to the current sensor. i saw something like states('sensor.this_sensor') while googling around. but i'm not sure if that actually works or not.
you reference the entity_id that is created by the configuration
ok so there's nothing generic that you can use without knowing the entity_id within the template sensor ?
nope
ok =) thought so. thanks !
i've been getting this error at startup for a while now:
Logger: homeassistant.components.automation.david_leave_home
Source: components/automation/__init__.py:461
Integration: Automation (documentation, issues)
First occurred: February 1, 2022, 7:49:43 PM (1 occurrences)
Last logged: February 1, 2022, 7:49:43 PM
Error rendering variables: TypeError: 'in <string>' requires string as left operand, not LoggingUndefined
i can obviously tell which automation it's coming from, but not which line... how can i debug that? what does it mean? lol
i uploaded the bit of my blueprint that has anything "in": https://www.toptal.com/developers/hastebin/nuvoxuqaze.yaml
i'm thinking it's whenever the entities i'm referencing haven't been initialized yet (at start)
selectattr('attributes.source_type', 'in', 'bluetooth') or selectattr('attributes.source_type', 'in', 'router')
left operand means the left side of the test
your test is: something in 'bluetooh'
those... are strings right?
yes, bluetooth is a string, but the left operand is not
ok so it's as i suspected, something that hasn't been initialized
so maybe an "if attributes.source_type" before that?
select('attributes.source_type', 'defined')
if that doesn't solve it, rejectattr('attributes.source_type', 'eq', none)
or both, with defined first
i guess eq might make more sense here too
every time i prepare to take a major update i try to clean up log stragglers so it's about that time lol
eq may solve it
it depends on if the attribute exists
using defined and eq will definitely solve it
too
is there a variable you can get last HA restart from or similar ?
uptime ?
yep
nice thanks . i'll check it out.
Is it possible to make a template and saving the result without without storing the initial values but only the result? in my case im reading octets from a router but converting it to megabits per second, i have no use for the original values
you'll have to elaborate on how you set this up, including your sensor that comes from the router
SNMP - getting an ever increasing counter, derivative to get the change between intervals and template to turn into megabits per second
like so - https://pastebin.com/Nne5Kgpb
which results in "WAN in", "wan_in_der" and "WAN in Mbps" all getting stored in the database, of which i only need the Mbps (same goes for out)
snmp allows for you to template the state directly in the configuration
however, because you're using derivative as an inbetween, you're stuck using the current method you have
I guess alternatively i could just store the initial SNMP values and then convert it in my graphs / output instead
i also got the impression that templating the state directly is no longer recommended from reading https://www.home-assistant.io/integrations/template/#legacy-binary-sensor-configuration-format
"This format still works but is no longer recommended" - this note is for binary_sensor but i figured it applied to other data sources also
there's also no explanation of why it would no longer be recommended :/
some of my templates will fail to render in upcoming version , will they not work anymore ...?
There's a new template format, the old format isn't recommended for use.
That is correct, take a look at pin 4.
guess i must have misunderstood ๐ thanks for the feedback @mighty ledge - i'll dig some more and see what i can figure out
the new format is directly above what you linked
keep in mind, it currently only affects binary_sensor and sensor
gotcha ๐
and there are no plans to remove it
so no reason to change it
I.e. only change it to the new style if you need the 'new' template options
if it aint broken ๐
exactly
I have this template that I got help on last week. It grabs the "min" value from the group of calendars. #templates-archived message
I am wondering if it is possible to get the attribute ("message") from whichever event is selected by "min"?
I'm trying to get data from attributes, but the attribute is an array of objects.
The problem is that the number of objects in the attribute varies, so I can't use "state_attr(entity, attribute)[index].key1", I need to find the index where key2 == criteria.
To be spesific, I need the price from the object where type = D. In this case, index will be 2, but it could be something else in a different sensor.
https://www.codepile.net/pile/LEnvr9E1
Is this possible?
To retrieve the price you might need something like this {{ x.stationDetails | selectattr('type', '==', 'D') | map(attribute='price') | list }}, but am not sure if I can help with getting the index
Let me try...
Yes, now I got a list with one item, and it seems to find the right object. Thank you!
No problem. Just bear in mind you are still getting a list, so if there will be more D's you will get them all
hi folks, i was told you guys can help me with this it should be super simple: esentially when dishwasher starts to run I trigger this timer. all i want is know what time is the timer gonna be done. essentially sending a message with the end time (ex: dishwasher will be done by 8:34PM). something like state_attr('timer.dishwasher_timer', 'finishes_at') the whole trigger is here https://community.home-assistant.io/t/message-finishes-at-from-a-timer/387352
If you put {{ state_attr('timer.dishwasher_timer', 'finishes_at') }} to /developer-tools/template, does it return something?
it says result type string
i even tried this: (as_datetime(state_attr('timer.dishwasher_timer', 'finishes_at')) - now()).total_seconds() | timestamp_custom('%H:%M:%S',
false)
And the value is empty? Just want to ensure myself - the attribute finishes_at exists, right?
well i got finishes_at from the developer/tools/States and this is what I got: duration: '1:35:00'
editable: true
finishes_at: '2022-02-02T20:38:08+00:00'
remaining: '1:35:00'
icon: mdi:dishwasher-alert
friendly_name: Dishwasher Timer
so yes
If you got it from states, then the retrieving should work. So if you got back to template you should see the value 2022-02-02T20:38:08+00:00 under Result type, while having this line {{ state_attr('timer.dishwasher_timer', 'finishes_at') }} in template editor.
yes that worked: 2022-02-02T20:38:08+00:00
so how do I know convert this to just time in my timezone?
now*
Yes, I am picking the first item for my value.
finishes_at is giving you time in different time zone? If so I think it would be easier to get remaining attribute and add to now()
ya is giving it to me in UTC. i can do that route too. same result. i thought this would be easier. any idea what would be syntex for that?
try {{ state_attr('timer.dishwasher_timer', 'finishes_at') | timestamp_custom('%d.%m.%Y %H:%M:%S') }}
it didn't take it same result as without the formating
tbh am not good at all in converting date/time in JINJA, for me the easiest way is to use timestamps. I would do something like this:
{% set remaining = '1:35:00' %} {% set remaining_timestamp = remaining[:1] | int * 3600 + remaining[2:4] | int * 60 %} {% set now = as_timestamp(now()) %} {{ (remaining_timestamp+now) | timestamp_custom('%H:%M:%S') }}
I would need some help too. Am getting list of devices using filter and retrieving their states like that:
{% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | list
The problem is the state is float but am getting it as string and I need to make an average. How could I possibly convert the string to float? I tried use filters (but am not sure if it is even possible) and also use for loop, but nothing worked. Obviously | sum(attribute='state') does not work, since the result is list of strings
So {% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | float | list isn't working? (Maybe I'm missing some parentesis or twelve...)
Yeah the code is working am able to retrieve the entities and their values in a list like ['21.0', '22.0', '23.0']. But I can't summarize them since they have been retrieved as string.
So the code {{ therm_obj[0] is float }} returns False
OK. BTW, where can I learn this "magic" with selectattr, map, whatever?
dude that totally worked. how can I buy you a coffee
Haha, good for you. Send it to HASS devs. Am learning too
WHAT! I actually helped? I'll take a virtual beer, thanks ๐
No, it wasn't me... Sorry!
you also helped! THANK YOU both
I tried...
Well, that's bit complicated I'm just dived in topics all over the Google and then testing HIT/MISS in Templates, so no specific place.
But this may help little bit https://jinja.palletsprojects.com/en/3.0.x/templates/, I just seen there that you should be able retrieve loop.index while using for loop, so possibly if you still need that index in your project, maybe check this.
The state of sensor.next_event is 2022-02-02 15:00:00. Is there a better way to strip out the time so I effectively get 2022-02-02 00:00:00? This worked but seems redundant. The end goal is to compare it to sensor.date to determine if the next event is Today.
{{ as_timestamp(states('sensor.next_event'),false) | timestamp_custom('%Y-%m-%d') | as_timestamp }}
.split(' ')[0] ~ ' 00:00:00'
Or just convert to a local datetime and output .date()
| as_datetime | as_local).date()
Probably should add an as_date filter
Hmm
Come I please have some help creating a sensor template? I want to create status for a machine of "Off" "Idle" "Running" based off the watts on a power monitoring socket.
so Off = 0W, Idle = 1-100W, Running = above 100W
what would the .split... replace? Where would I put it?
states('sensor.next_event').split(' ')[0] ~ ' 00:00:00'
play with it in
-> Templates to get what you want
Wonder if someone can help:
I have a markdown template that shows all my power sensors by doing something like {%- for entity in states.sensor -%} ...
And I've noticed something really weird:
If I time the time that takes HA to return a static js file I get it in 30-50ms (curl <ha>/frontend_latest/250cbdbd.js)
but If I have the frontend opened on 5 tabs on my browser
Then it takes HA 5-10 seconds to return the same exact static js file
if I open some more tabs, well, you get the picture.
so, 1) how can I make the template have a custom rate-limit, so I can let it update say once every minute, not every second and avoid this
2) is this FE/webserver behaviour known? I wouldn't expect templates to have this much impact on HA HTTP server
I have the below template that correctly returns the minimum value (next event) from the entities in "event1". The entities also have a "message" attribute. Is it possible to get the "message" attribute from the entity that is "min"?
{% set event1_min = as_timestamp(expand(event1) | selectattr('attributes.all_day', 'defined') | selectattr('attributes.all_day', 'false') | selectattr('attributes.start_time', 'defined') | map(attribute='attributes.start_time') | min) %}
not after you do the map(), but you could use that output to select from the original list
{{ expand(event1) | selectattr('attributes.start_time', 'eq', event1_min)|map(attribute='attributes.message')|first }}
thanks, I will probably have to get event1_min back into the same date/time format right?
You didn't manipulate it, so I don't see why
It does assume that there's only one item with the start_time you care about
I manipulated it in an earlier part of the template so it would be a UNIX timestamp for the min function
Bot you could re-add all those filters if you want
Ah, indeed
That's not what you did, though
the original format was was '%Y-%m-%d %H:%S:%S'
your |min is just based on the attribute
you are right, but when I execute {{ event1_min }} it returns 1643888700.0 but the input attributes are '%Y-%m-%d %H:%S:%S'. Why would that be?
doesn't this as_timestamp(expand(event1)...) convert to UNIX time?
because you did the conversion afterward
This is returning "<generator object sync_do_map at 0x7f5d18bdb4a0>"
you missed the |first
yep, i was. It is now returning nothing, not error, just blank
Hi all, anyone able to help me with following? Am getting list of devices using filter and retrieving their states like this:
{% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | list
The problem is the state is string but information inside is float . How could I possibly convert the string to float? I tried use filters (but am not sure if it is even possible) and also use for loop, but nothing worked. Obviously | sum(attribute='state') does not work, since the result is list of strings
Because you're converting it to a timestamp afterward
you are correct. I am doing that to compare with another entity but I can do that in the comparison instead. Thanks again for the help
the markdown card has a entity_id to give an entity to control renders. if I give it a timer of 30sec, it should only render the card every 30sec right?
{% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | list %}
{{ expand(therm_obj) | map(attribute='state') | map('float', default='unavailable') | reject('eq', 'unavailable') | average }}
Wow, am impressed. This actually works. Thank you very much TheFes ๐ช ! I see for the first time expand function, so will google it a little bit.
You can of course do it in one go, without expand.
{{
states.sensor | selectattr('entity_id', 'in', area_entities(area))
| selectattr('attributes.device_class', '==', 'temperature')
| map(attribute='state')
| map('float', default='unavailable')
| reject('eq', 'unavailable')
| average
}}
In this case expand wasn't needed actually, because you didn't use map in your expression. This will also work.
{% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | list %}
{{ therm_obj | map(attribute='state') | map('float', default='unavailable') | reject('eq', 'unavailable') | average }}
Yeah I tried it right away and worked too.
expand is used when you have a list of eg entity_ids and you want the other data of the entities (like states, attributes etc)
I didn't know I can use several map filters in the same code, it bit changed my thinking about what is the purpose of map :D.
really appreciate your help again
No problem
getting this logged, what do I need to change?
2022-02-03 10:27:48 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'int' got invalid input 'unknown' when rendering template '{% set battery_level = state_attr('sensor.downstairs_tablet_info', 'batteryLevel')|int('unknown') %} {% set battery_round = (battery_level|int / 10)|int * 10 %} {% if battery_level == 'unknown' %}
mdi:battery-unknown
would changing int('unknown') to int(default='unknown') do it?
nope it does not
any ideas?
well, you first set battery_level to "unknown" (as default) and then try to do a calculation with it
what is the full template?
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
@atomic python posted a code wall, it is moved here --> https://hastebin.com/cozuhuyose
I'm guessing it always worked but just wasn't logging the warning until recently
I know I had to do similar updates where I had float conversions, to float(0)
but not sure what the fix is here
{% set battery_level = state_attr('sensor.upstairs_tablet_info', 'batteryLevel') %}
{% set battery_round = iif(battery_level | is_number, (battery_level|int / 10)|int * 10, 'unknown') %}
{% if battery_round == 'unknown' %}
mdi:battery-unknown
{% else %}
{% if battery_round >= 100 %}
mdi:battery
{% elif battery_round > 0 %}
mdi:battery-{{ battery_round }}
{% else %}
mdi:battery-alert
{% endif %}
{% endif %}
Multiple fixes possible, but this is one of them (assuming you are on 2022.2)
changed warning now to None
[homeassistant.helpers.template] Template warning: 'int' got invalid input 'None' when rendering template
might just be something when HA starts, I never see it after
those attributes come via json from a rest sensor
maybe change this {% if battery_round == 'unknown' %} to or is = None?
if you use the fes's template, it should not produce errors on startup.
Your original template is failing because you're defaulting it to 'unknown' then casting to an int afterwards, which defeats the purpose of using a default
your default should be an int, not the word unknown. unless you want to catch it.
yes the new None warning is with his template
Not sure how it does. but you can try this instead
{% set battery_level = state_attr('sensor.upstairs_tablet_info', 'batteryLevel') | int(none) %}
{% if battery_level is none %}
mdi:battery-unknown
{% else %}
{% set battery_level = battery_level // 10 * 10 %}
{% set postfix = battery_level < 0 | iff('-alert', '-' ~ battery_level) %}
{% set postfix = battery_level >= 100 | iff('', '-' ~ battery_level) %}
mdi:battery-{{postfix}}
{% endif %}
or this
{% set battery_level = state_attr('sensor.upstairs_tablet_info', 'batteryLevel') | int(none) %}
{% if battery_level is none %}
mdi:battery-unknown
{% elif 0 < battery_level < 100 %}
mdi:battery-{{ battery_level // 10 * 10 }}
{% elif battery_level >= 100 %}
mdi:battery
{% else %}
mdi:battery-alert
{% endif %}
you have alot of options
thx will try it right now
the take away is: Only cast int 1 time.
@mighty ledge @atomic python I know why my template isn't working. I keep forgetting that iif evaluates both the true and false option, even though the statement is false. This will work:
{% set battery_level = state_attr('sensor.upstairs_tablet_info', 'batteryLevel') %}
{% set battery_round = (battery_level|int / 10)|int * 10 if battery_level | is_number else 'unknown' %}
{% if battery_round == 'unknown' %}
mdi:battery-unknown
{% elif battery_round >= 100 %}
mdi:battery
{% elif battery_round > 0 %}
mdi:battery-{{ battery_round }}
{% else %}
mdi:battery-alert
{% endif %}
also removed the nested if, which was not needed
soooo I guess I can't put off upgrading my fan templates any longer...
why...
cos I just upgraded and the old ones are making complaints
@royal rampart posted a code wall, it is moved here --> https://hastebin.com/ixayebutur
lol, so yeh that's what I had until today
actually it might be something in my !include
yup that cleared the warning
this works also thanks both ๐
ok, had too goes at this, and now I'm getting hot cos I broke the running fan lol.
I have a few fans in this house and they're all available as a series of switches
switch.fan_$room_off, switch.fan_$room_low, switch.fan_$room_medium, switch.fan_$room_high
how on earth do I squeeze that into the new % based configs
even wrote a script that took entity_prefix cos I figured that'd save me a bunch of lines of yaml ๐
Failed to call service fan.set_percentage. not a valid value for dictionary value @ data['entity_id']. Got None odd
post your new config that you're trying
https://pastebin.com/XGnmYgwK this gets me a different error, Failed to call service fan.set_percentage. Template rendered invalid entity IDs: "switch.bed_5_fan_high" so that's an improvement
oh, take out the quotes fixed
7 more fans to do ๐
is fan speed preserved when fan is off?
next thing is figuring out how to split up my config again... fan: !include fan.yaml, which has first line of - platform: template doesn't seem to work any more
I don't see a reason why that would not work
oh that might just be vscode
ah, there is indeed a bug in vscode
sweet thanks, this is all working now! and I have a script so I can save 7 lines of yaml per fan ๐
(by the time I got it working the first time I was so tired copy pasta was the answer)
is there any way to reduce this further? set a variable at the top of the fan template? ๐
not really
https://go.dev/play/p/Ibt4OuI-PhC sorted ๐
Can anybody help me with line 6? only want it to fire when the delay is greater than 5 https://www.codepile.net/pile/oBk8jNQ3
that will trigger if it transitions from less than or equal to 5 to greater than 5
yeah just saw need >= right?
whatever you want
the point is that it will trigger on the transition from false to true
yeah so now it triggers if the delay is 5 or >5?
{{state_attr('sensor.fangschleuse_bahnhof_grunheide_mark_to_zoologischer_garten_bahnhof_s_u_berlin','delay')
| int > 5 }}
but with >= it triggers when it hits 5 or more
how can i make it trigger when the canceled status switches from false to true?
what "canceled status"?
the sensor also got canceled
what does that mean?
which can be true and false, now i want to trigger when it switches from false to true
the train got canceled
its an integration which is using a sensor
you're being very vague ๐
deutsche bahn integration
in the end, you either have a state or an attribute, and you use an appropriate trigger for the appropriate one
I have no idea what that does
i dont really understand how this part works
let me point you to the docs
I thought you wrote that, but must have copied it from somewher?
i got help with that
ok, it's pretty straightforward
I have no idea
mhmm can i use something like string == true ๐
there's a whole section in the docs for stuff like that
I recommend not guessing and peruse that instead. Then try what you want in
-> Templates
Arduino Output
If I want to create a virtual entity for my electric fireplace, what would be the best thing? The fireplace exists in three states: off, lights only, lights + heat... I want to be able to track which state the fireplace is in and run automations to switch between states. Does that make sense?
hi, I have an issue with template that I want to use in UI for opacity control. It works in developer tools, but not in lovelace. {{ (states["input_number.slider1"].state) |int / 100 }}
You canโt template in lovelace unless itโs the markdown card
it works when I use light as driving source. opacity: "${states['light.hue_lightstrip_2'].state === 'on' ? (states['light.hue_lightstrip_2'].attributes.brightness / 255) : '0'}"
How do I create a sensor for weather for date 0? I want today's high temperature. The issue I see is the integration uses the date for 0, 1, 2 rather than the number ,i.e datetime: '2022-02-03T12:00:00+00:00'.
Probably something like {{ state_attr('weather.your_entity', 'forecast')[0].temperature }}
So 0 will pull today's date data?
[0] will take the first item out of the list of forecasts
Thanks. Worked great.
I'm trying to substitute the value of a datetime helper for the value of "start" and "end" times in an automation but whenI save the automation and return to it the template is changed to "[object object]": null
Anybody have an idea why this would be? its driving me nuts
This is what I type in : service: babybuddy.add_sleep target: device_id: ab979a9aa5e2021fe8784ae4a4254a75 data: start: '{{ states('input_datetime.samantha_sleep_start_time') }}' end: '{{ states('input_datetime.samantha_sleep_end_time') }}'
This is what it look slike when i save and then come back to it:
service: babybuddy.add_sleep target: device_id: ab979a9aa5e2021fe8784ae4a4254a75 data: start: '[object Object]': null end: '[object Object]': null
Will do. Thank you.
Is my above issue related to "limited templates"?
Or do I need to convert the value of the datetime helper to a string or something? I'm really not sure what the issue is
What custom card is that? Looks like the templating card which is not the same code as jinja templates
Moved to Node-Red
Are you using Node-Red?
Crap forgot i wasn't in that channel...thought i was.
I can post there, but you have a plan ๐ ?
Nope.
anyone else not able to get the new button template working?
i copied the example from the blog post and reloaded template entities - nothing
i would have expected the yaml to look like other templates, but it's different. usually you start with
button:
- platform: template...
- name: my_button
but instead, the example is
template:
button:
- name: my_button
it seems backwards...
The latter is the new format introduced months ago
oh hmm. so only the latter will work - should work?
can you mix both in the same config file?
Just follow the docs
i see the docs. but i am not sure if i need to rewrite my whole config file to use the new format or not
No, you just add what it says
Hi everyone, in an attempt to deal with any left over template warnings before updating to 2022.2 I wonder if someone can point me in the right direction on the following:
Template variable warning: 'mappingproxy object' has no attribute 'current' when rendering '{{ (states.timer | selectattr('state', 'ne', 'idle') | list | count <=0) and (states.automation | selectattr('attributes.current') | list | count <=0) and (states.script | selectattr('attributes.current') | list | count <=0 ) }}'
{{ (states.timer | selectattr('state', 'ne', 'idle') | list
| count <=0) and (states.automation | selectattr('attributes.current') | list
| count <=0) and (states.script | selectattr('attributes.current') | list | count <=0 ) }}
It always renders correctly but always logs the error as well, any input greatly appreciated
thanks
A warning is nog an error.
Maybe some more experienced people have a better option, but as far as my knowledge goeds you can either ignore this warning, or use a for loop ๐
{%- set ns = namespace(automation = []) %}
{%- for auto in states.automation %}
{%- set current = auto.attributes.get('current', 'nothing') %}
{%- if current != 'nothing' %}
{%- set ns.automation = ns.automation + [ auto ] %}
{%- endif %}
{%- endfor %}
{{ ns.automation | count == 0 }}
Cool, I will try swapping it out for the above and see what happens, also above typo as didnt mean error in the true sense of the HA word, just wanted to better understand why there is any warning at all when the template appears to function exactly as designed. Thank for the input, appreciated.
i have a binary sensor with the following content and the following data parsed from a mqtt json blob
json_attributes_topic: "BlueIris/driveway/Status"
json_attributes_template: >
{
"trigger": {{ value_json.trigger}},
"memo": {{ value_json.memo}},
"type": {{ value_json.type}}
}
data:
memo: car:92%
trigger: ON
type: MOTION_A
How would i go about parsing out the "car:92" to split them out into 2 values?
something like this: {{ value_json.memo.split(':') }} and if you are only interested in the percentage, it will be {{ value_json.memo.split(':')[1] }}
how would I remove the percentage sign to make it an integer that homeassistant can understand?
{{ value_json.memo.split(':')[1] | replace('%', '') }}
maybe, but what I posted will also work
alright, i'll plug that in
you can cast it to an integer after that if you want
This is not yaml, this is jinja
oh, well there you go. i know nothing
{{ value_json.memo.split(':')[1] | replace('%', '') | int }}
{{ value_json.memo.split(':')[1].strip('%') | int }} also works
yeah, that's what i figured but i went your first way now
It is templating card. Do you know how to fix it?
Yes, use js templating and it's indicators instead of Jinja and it's indicators.
Thank you petro. Got it working.
- platform: mqtt
device_class: motion
name: 'testd'
state_topic: 'BlueIris/driveway/Status'
value_template: "{{ value_json.trigger }}"
json_attributes_topic: "BlueIris/driveway/Status"
json_attributes_template: >
{
"trigger": {{ value_json.trigger}},
"object": {{ value_json.memo.split(":")[0] }},
"confidence": {{ value_json.memo.split(":")[1].strip('%') | int }}
"type": {{ value_json.type}}
}```
so i've created this now but it doesn't work, where have i gone wrong?
i've got a screenshot of what it puts out and its very strange. it just shows "trigger: ON" and "memo:" (empty). confidence and object don't even exist
Hi, I need to set hue_power_on_behavior for several lights and would like to script it. I think this is what I need, question is how I can run it in a script? What would be the correct way to do it? https://paste.debian.net/hidden/8546c5df/
command to set the parameter works on the command-line, just unsure how to make it run in a script?
Configure HA to talk to the MQTT broker and use this: https://www.home-assistant.io/docs/mqtt/service/#service-mqttpublish
Great, will check it out. Thanks ๐
hi i have an array of some data [ {task: "description", done: true}, ... ] id like to build a template that lops over this data so i can display each item in the array as a line
๐ค The loop part proves tricky, please help me out... I have the action, which I need to run once for each entry in the list of lights, but how? https://paste.debian.net/hidden/ad55b416/
yeah, this part makes no sense:
- condition: template
value_template: >
{% for light in lights%}
you should use a counter loop and index into the list
that makes sense... didn't think of that, will give it a shot, thank you ๐
- platform: mqtt
device_class: motion
name: 'testd'
state_topic: 'BlueIris/driveway/Status'
value_template: "{{ value_json.trigger }}"
json_attributes_topic: "BlueIris/driveway/Status"
json_attributes_template: >
{
"trigger": {{ value_json.trigger}},
"object": {{ value_json.memo.split(":")[0] }},
"confidence": {{ value_json.memo.split(":")[1].strip('%') | int }}
"type": {{ value_json.type}}
}```
i've got a screenshot of what the sensor and its very strange. it just shows "trigger: ON" and "memo:" (empty). confidence and object don't even exist. Any ideas?
no comma aftger confidence
good eye, thanks
I'm having trouble converting "timestamp" from octoprint into a simple time to use in messages...
Basically i want to turn 2022-02-05T11:26:43+00:00 into just 11:26
It depends on whether it's really a datetime or just a string. This works for one of my entities where the attribute is a string:
{{ (state_attr('sensor.this_device_next_reminder', 'process_timestamp')|as_datetime).strftime("%H:%M") }}
if it's really a datetime object, then you shouldn't need the |as_datetime part
device_class: timestamp
{{ (states('sensor.octoprint_estimated_finish_time')|as_datetime).strftime("%H:%M") }}
Shouldn't this work?
entity: sensor.octoprint_estimated_finish_time
state: 2022-02-05T11:29:58+00:00
device_class: timestamp
friendly_name: OctoPrint Estimated Finish Time
does it?
Nope
Failed to call service notify.mobile_app_pixel_2_xl. template value should be a string for dictionary value @ data['message']. Got None
data:
message: {{ (states('sensor.octoprint_estimated_finish_time')|as_datetime).strftime("%H:%M") }}```
{{ ("2022-02-05T11:29:58+00:00"|as_datetime).strftime("%H:%M") }} -> 11:29
all I did was replace the states() call with the string your claim it returns
you need to surround your template in quotes
rule #1
OMG, found out what it was:
message: test {{ (states('sensor.octoprint_estimated_finish_time')|as_datetime).strftime("%H:%M") }}
that works
but without the "test" it doesn't :S apparently it doesn't class it as a string i supppose
yes, rule #1
surround your template with quotes
here
service: notify.mobile_app_pixel_2_xl
data:
message: "{{ (states('sensor.octoprint_estimated_finish_time')|as_datetime).strftime('%H:%M') }}"
grr... YAML and Python is pissing me off, coming from PHP, Javascript and C++... These syntax differences xD
Thanks alot, it works now ๐
because YAML is a superset of JSON, it interprets the { as the start of a JSON structure and barfs on the rest
you need to tell it to consider it to be a string
im trying to add a mqtt light with rgb support and effects. I've been trying to follow the homeassistant guide for adding it to my configuration but every time i think ive added it all i see is a brightness slider rather than a rgb pallet and an effects drop down
@tropic breach posted a code wall, it is moved here --> https://hastebin.com/gugozupiki
Hi! Should this template condition work?
condition:
- condition: and
conditions:
- condition: template
value_template: >-
{{ trigger.event.data.new_state.attributes.device_class == "on" and
trigger.event.data.new_state.attributes.device_class == "door" }}- condition: state
entity_id: trigger.entity_id
state: 'on'
for:
minutes: '1'
Still makes no sense
you mean this:
{{ trigger.event.data.new_state.attributes.device_class == "on" and
trigger.event.data.new_state.attributes.device_class == "door" }}
Yes
wait
Yeah
maybe i copied the wrong text, hang on
this should look better?
`condition:
- condition: and
conditions:- condition: template
value_template: >-
{{ trigger.event.data.new_state == "on" and
trigger.event.data.new_state.attributes.device_class == "door" }} - condition: state
entity_id: trigger.entity_id
state: 'on'
for:
minutes: '1'`
- condition: template
@merry dawn posted a code wall, it is moved here --> https://hastebin.com/irajicogon
- platform: command_line
switches:
door_lock:
friendly_name: "Door"
command_on: !secret command_lock
command_off: !secret command_unlock
icon_template: >
{% if is_state('sensor.door_lock_last_event', 'unlock') %}
mdi:lock-open-variant
{% else %}
mdi:door
{% endif %}```
Hey, i cant get this Switch to change icon, everything looks good under the template designer, but it seems it doesnt apply the icon anyway.. any ideas?
Why i use this over lock is because i run a curl commando to open a door.
How do i template this the best way? Or should it work as i made it below?
- service: notify.device
data_template:
title: xxxxxx
message: > xxxxx
data:
actions:
- action: "OPEN"
title: "Open Google Maps"
uri: "https://www.google.com/maps/dir/?api=1&origin={{sensor.mydevice.state}}&destination=home"
I would like the google travel time origin and destination in the URI action.
I tested it out, and it seems to work:
uri: https://www.google.com/maps/dir/?api=1&origin={{state_attr('device_tracker.iphone', 'latitude')}},{{state_attr('device_tracker.iphone', 'longitude')}}&destination={{state_attr('zone.home', 'latitude')}},{{state_attr('zone.home', 'longitude')}}
๐
any idea why this is not triggering an action?
But this will trigger immediately when a binary sensor turns on, and then the condition will always be false
I made a suggestion in the automations channel
That too
You can create a template sensor with a count of binary sensors which are open for more then 30 minutes, and the entity ids as attribute. Then you can trigger on that
Without testing: {{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'in', ['door', 'window']) | selectattr('last_changed', '<', now() - timedelta(minutes=30)) | list | count }}
And for the attribute: {{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'in', ['door', 'window']) | selectattr('last_changed', '<', now() - timedelta(minutes=30)) | map(attribute='entity_id') | list }}
ok thank you. I have to understand which to put where in the logic... have not spent much time with automations/templates in ha yet
@marble jackal the first template sensor has to go to configuration.yaml as new sensor, right?
Create a template sensor using https://www.home-assistant.io/integrations/template/#state-based-template-sensors
The second one should be an attribute of that sensor, see https://www.home-assistant.io/integrations/template/#attributes
But test them first in
> templates
thxxxxx
You can change the number of minutes in the timedelta for testing
will do and come back with more educated questions ๐
I'm on mobile, so I did not test it, and maybe made some errors
Might be able to get some help here, I need to pull the "frm_payload" out of a json blob but seem to be formatting it wrong
https://paste.debian.net/hidden/82675e90/
https://paste.debian.net/hidden/a25c1006/
Does anybody have a clue how to parse a JSON as a sensor which has the following layout:
{"fields":[
{"name": "ABC", "value": "123"},
{"name": "XYZ", "value": "789", "unit": "123"}
]}
And I want to extract the value (of "value") linked to name "XYZ".
I've been googling this for 2 hours, but getting stuck...
{% set data = {"fields":[
{"name": "ABC", "value": "123"},
{"name": "XYZ", "value": "789", "unit": "123"}
]}
%}
{{ data.fields|selectattr('name', 'eq', 'XYZ')|map(attribute='value')|first }}
-> 789
Actual code now looks like:
- name: DSMR Power Consumption Actual Total value_template: "{{ value_json.actual | selectattr('name', 'eq', 'power_delivered') | map(attribute='value') | first | float }}" device_class: "power" unit_of_measurement: "kW" - name: DSMR Power Returned Actual Total value_template: "{{ value_json.actual | selectattr('name', 'eq', 'power_returned') | map(attribute='value') | first | float }}"
Any pointers where I could find more background documentation? python.org docs can't find selectattr
dishwasher_energy_total:
friendly_name: "Dishwasher Energy Total"
unique_id: dishwasher_energy_total
unit_of_measurement: kWh
device_class: energy
state_class: measurement
state: >-
{{ states('sensor.dishwasher_smartplug_energy_today')|float }}
Created this template to bring the correct reading out of a smart plug to go into my energy dashboard, looks fine in the template section of
- but when I check configuration before restarting, I get an error.
Jinja Template Designer Documentation
For more examples and samples, visit see this page.
Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('sensor.dishwasher_smartplug_energy_today')|float", None)])"
I created a manual alarm_control_panel. I want to be able to to change the arming_time before arming the home. I tried to set the arming_time in the alarm_control panel with a template: {{ states('input_number.arming_time_zone1') | int }}
. The template seems to work fine but I can't find out how to put it in the config for the alarm_control_panel. Is that impossible or should I be able to put it in?
alarm_control_panel:
- platform: manual
name: Alarm Zone 1
arming_time: {{ states('input_number.arming_time_zone1') | int }}
trigger_time: 60
disarmed:
trigger_time: 0
armed_home:
arming_time: 0
delay_time: 0
This did not work as expected...
in action on an automation how can i make this work, i think the error could be in line 14
http://dpaste.org/8qtX
whats confusing me it works in template editor
brightness_pct:
{% if states('sensor.chimney_temp') | float <= 89 %} 100
{% elif states('sensor.chimney_temp') | float > 90 %} 40
{% elif states('sensor.chimney_temp') | float < 125 %} 20
{% else %} 0
{% endif %}
i thought it was the same, sorry
Nobody is going to re-paste what you pasted, just for giggles
