#templates-archived
1 messages · Page 133 of 1
2021-08-24 22:40:59 WARNING (MainThread) [homeassistant.components.rest.sensor] JSON result was not a dictionary or list with 0th element a dictionary
I didn't say {{ value_json.students }} for the attributes
look at some of the examples: https://www.home-assistant.io/integrations/sensor.rest
same error. i make a mirror of the file on my webserver and try it instead
and it works
hmm
i compare the header i use with curl with the packet capture i made on my web server of a request from home assistant
looks like i have the same headers in the packet capture as i specify when i run curl
only difference in the request is the host and get due to another uri
i do a workaround. a cron job at the webserver save the data to a file and home assistant can read it as often i wants 🙂
It works. Now i can make an automation that gives my son more internet time on saturdays if he get enough duolingo XP monday to friday 🙂
i also get data for my wife 🙂
They both need to learn Swedish 😄
This is a really nice idea, I love it.
before this summer i replaced my "ugly" bash scripts that used expect to log on to the firewall to enable and disable my sons internet access on his PC
My fortigate have a quite nice API and now i can also see if the firewall policy is on or off so the state is always up to date
The plan with duolingo was to extract data from the emails i get when he completes tasks. With the experience from the api call to my firewall I realised that i can get the data via the API. Developere tools in firefox gave me a nice formated one liner in curl
API's should always be the preferred way to get data 
to bad i couldn't skip the cron job at the web server
i prefer not to have any dependency on other machines for functions
Time do do as Tor Johnson said. "Time for go to bed" 😄
getting an odd message when trying to check config on a new sensor.template
Invalid config for [sensor.template]: [state] is an invalid option for [sensor.template].
sensor.template isn’t a thing. Share the configuration
I suspect that you’re mixing up the old and new template sensor formats
sensor:
- platform: template
sensors:
my_sensor:
state: "{{ states('media_player.living_room') }}"
[...]
That’s the old/legacy format, which doesn’t have state:
lol well that would explain it
is there an updated link to replace this: https://www.home-assistant.io/integrations/template/ ??
There’s a section at the bottom for the legacy format
You can use either, but you can’t mix and match in a single definition
so the new format is the one which would be represented as
sensor:
- platform: template
sensors:
- name: my_sensor
state: "{{ states('media_player.living_room') }}"
[...]
``` ??
- sensor:
- name: "Average temperature"```
That's your basic structure. It doesn't start with sensor: at the top, and it doesn't have platform: template anywhere at all.
Daad Day all, Why would this not import my templates.yaml "template: !include_dir_merge_list templates.yaml"
Because you haven't asked it to. Re-read the docs carefully to see the difference between the 4 include statements: https://www.home-assistant.io/docs/configuration/splitting_configuration#advanced-usage
Hint: ||templates.yaml isn't a directory||
In C++ you have a map function which maps a range to another range. int percentage = map(300, 500, 0, 100);. This I want to use for my CO2 sensor so that when the value is 400 I can set my mechanical home ventilation system to run at 50%. I can program this in my ESP32 and simple send it to MQTT broker as mechanical_home_ventilation_suggestion but I was wondering if this could also be done in home assistant. Any suggestions? (I'm guessing this is to advanced for automations so thats why i'm asking it here)
Use the compensation integration
Thank you petro. I'll be looking into this
I followed the "JSON Attributes Template Configuration" section of the MQTT sensor docs to extract individual attributes out with a template. It works generally, but any attribute returning a null value generates a TypeError: Object of type LoggingUndefined is not JSON serializable error.
To try and work this out I put {% set var = {"a": null} %}{{ var | tojson }} in the template editor, and got the same error. Is there a way I can properly handle these null values in JSON with a templte?
what does the json payload look like with null?
It's pretty big, I'll grab a pastebin
https://pastebin.com/twrM6adE Might be worth pointing out that I'm not actually referencing any of the null attributes in my template.
There are a few other examples, but one of the templates looks like this:
{% if value_json['fsSize']['E:'] is defined %}
{{ { 'fs': value_json.fs,
'size': value_json.size,
'used': value_json.used,
'available': value_json.available,
'use': value_json.use } | tojson }}
{% endif %}
None of fs/size/used/available/use are null , in this case that's the temperature and disksIO attributes.
Probably also worth noting that if I remove the whole json_attributes_template part from the config, the full attributes populate on the sensor, including the null ones.
you're probably trying to do this
{% if value_json['fsSize']['E:'] is defined %}
{% set value = value_json['fsSize']['E:']%}
{ 'fs': {{value.fs}},'size': {{value.size}},'used': {{value.used}},'available': {{value.available}},'use': {{value.use}} }
{% endif %}
Hmm I'm not sure that's it but it did make me realise a huge error I'd made with the json path. This seems to be working:
{% if value_json['fsSize']['E:'] is defined %}
{{ { 'fs': value_json['fsSize']['E:']['fs'],
'size': value_json['fsSize']['E:']['size'],
'used': value_json['fsSize']['E:']['used'],
'available': value_json['fsSize']['E:']['available'],
'use': value_json['fsSize']['E:']['use'] } | tojson }}
{% endif %}
I'm not sure how I got that mixed up with the null attributes...
yeah it was not it if you need json as the result. you can still replace value_json['fsSize']['E:'] with set
What would be the advantage of that? Just overall neatness of the code?
yes, and easier editing and multiplying of it
Hey guys. How do is evaluate for a single state attribute that is from a list?
Let's say there's two in a list [E8:07:BF:76:E8:F6, 68:E7:C2:20:2F:AA]
And I'm evaluating for if just one is in that list. I'm using this:
{{ is_state_attr('sensor.mealsmob3_bluetooth_connection', 'connected_paired_devices', '68:E7:C2:20:2F:AA') }}
But it only works if the list is size one.
You'd use the in operator to check for the presence of an item in a list:
{{ '68:E7:C2:20:2F:AA' in state_attr('sensor.mealsmob3_bluetooth_connection', 'connected_paired_devices') }}
D'oh, other way round... lemme edit
Like that
Sweet! Thank you. I was down the rabbit hole for too long..
Hi everyone. Having a history_stats issue that I can't wrap my head around. It's about setting up the timeframe template, so I hope this is the correct channel to ask it in.
I have a sensor that marks someone as sleeping based on some conditions that I have found very reliable. So now I want to set up a history stats sensor that gets the time of sleeping overnight for each day. So obviously I don't want that time to be cut off at midnight and start a new day.
I found the Next 4 pm example on the history_stats page:
end: "{{ (now().replace(minute=0,second=0) + timedelta(hours=8)).replace(hour=16) }}"
duration:
hours: 24
but I can't get my head around what timedelta does. Can someone explain?
as in your example, timedelta allows you to add/subtract an offset of the magnitude that you specify
add 1 minute, subtract 4 hours, etc.
So if I wanted to do from yesterday at noon to today at noon, I would do {{ (now().replace(minute=0,second=0) + timedelta(hours=12)).replace(hour=12) }}?
Or would it just be easier to define an end time in the morning and count back a set amount of hours from there?
that's equivalent to noon today if before noon or noon tomorrow if after noon
to get noon of yesterday, I would do {{ now().replace(hour=12,minute=0,second=0) - timedelta(days=1) }}
Ah ha. That is a lot simpler. Thank you!
when i moved my template sensors to an include, i.e. config.yaml w/ template: !include templates.yaml do i just start listing triggers & sensors or anything special? i had kept the template: key mistakenly...
you put everything that would have otherwise gone under template: in the file
Hi. I have a continuous sensor that has a value from 0.0 to 5.0. I'm trying to figure out a way to know what % of the maximum possible sum of readings over the last 24 hours (5 min interval readings). In other words, 1,440 minutes in a day / 5 minute intervals = 288 intervals. 288 intervals * 5.0 (maximum value of sensor) -> 1,440 again (max possible value for 24 hrs). If the sensor were flat at 2.5 for the past 24 hrs, I'd expect 720/1440 = 0.50. I was about to setup an automation to pull readings and do some arithmetic/store state but figured I'd see if there was anything simper I might have overlooked. I've been playing around with Riemann sum integrals and reading up on history_stats but haven't had any luck implementation-wise.
Hi all, I am trying to create a sensor that returns a value in hours/minutes from a timestamp and the current time. The timestamp sensor i have is sensor.daves_pc_idle which returns a value of 2021-08-26T12:59:23 I want to use the returned value in an automation and compare it to a set value of say 15 minutes or 1 hour and 10 minutes. Can anyone help with this ?
I worked it out. - platform: template sensors: daves_pc_idle_time: unit_of_measurement: "m" value_template: >- {{ ((as_timestamp(now()) - (as_timestamp(states('sensor.daves_pc_idle')))) /60) | int }}
If the timestamp is always in the past you can just use {{ relative_time( states('sensor.daves_pc_idle') ) }}
Dont use a unit, as the sensor will produce results like "7 days 5 minutes and 12 seconds ago"
Ok. Thanks.
Actually it will only return the biggest unit, so for my example it would return "7 days"
Is it possible with a tempate to get the highest temp for today and summary from the weather integration.
You're asking that without sharing the data you plan to get it from...
.share the data, then maybe we can say if it's possible.
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
did I miss the change in functionality of this: state: > {% set month = now().strftime('%m') %} {% if month in ['1','3','5','7','8','10','12'] %} 31 {% elif month in ['4','6','9','11'] %} 30 {% else %} {{'29' if states('sensor.year')|int//4 == 0 else '28'}} {% endif %} or is it caused by todays beta 2021.9...
apparently we can not use the month numbers without a leading 0 anymore? or use %-m
you're doing string comparisons there. what part do you think has changed?
This is also a really terrible way to work out leap years:
states('sensor.year')|int//4
Suppose you'll be dead before the next time it's wrong though 😂
In 79 years? Could happen.
Depends where you live, I guess. Life expectancies are heading in the wrong direction in some places.
now().month is a thing
returns an int of the current month
now().year does the same for year
{{ (now().replace(month=next, day=1) - now().replace(day=1)).days }}```
@floral shuttle
might have problems at the end of the year though
{% set next_month = 1 if n.month == 12 else n.month + 1 %}
{% set next_year = n.year + 1 if next_month == 1 else n.year %}
{{ (n.replace(year=next_year, month=next_month, day=1) - now().replace(day=1)).days }}``` now fixed
lol
let the thing that actually knows the calendar tell you the days 🙂
Tbh, I am not sure. This has been working since a long time ( ..) and now I noticed it being off. The -m fixed it though, but I honestly don’t think I had that before I migrated from legacy template to the new template: format.
You’re comparing against strings that don’t have a leading zero, so I guess the format string tokens might be different?
Seems unlikely though
%m 09 Month as a zero-padded decimal number.
Hi guys, I have a question... what do you use to sum up multiple energy plugs to have a per-room sensor to pass to the utility_meter integration?
I have one but it doesnt' work well, when a device goes offline it is counted as "0", so the sensor goes up and down depending on reboots.. causing the utility_meter to misscalculate usage
add an availability template to your entity and it won't go down to zero
Hello, I woul like to use Energy tab. I have the power used by the house and the power produced by the solar powerplant. So I should create an entity with differences if above zero (for example, power from the grid should be homepower-solarpower if >0 )
How can I do so?
Something like {{ [0, states('sensor.sensor_one') - states('sensor.sensor_two')] | max }} might do it. Just make sure you're doing the subtraction the right way round,.
That'll do the difference, even if it's a negative value, but return the largest value from the array each time (0 if the other one went negative).
thanks I will try! where I can find a "simple" guide about syntax, operators etc? I know everithing is well documented, but is not so simple entering in it
Simple? For Jinja? 😂
There are links to the docs (HA and Jinja) in the topic and pins here... but templating is difficult, so there's going to be no simple guide.
value_template: "{{ [0, '%0.1f' | format(states('sensor.power_home_energy_today')|float - states('sensor.power_powerplant_energy_today')|float) ] | max }}" doesn't work,
value_template: "{{ '%0.1f' | format(states('sensor.power_home_energy_today')|float - states('sensor.power_powerplant_energy_today')|float) }}" does, i suppose your idea was to take the bigger value in the array between 0 an the value, it shoul work, is there a syntax error?
I'm looking to get my tasmota switch set with switchmode 15 to toggle a zigbee light on and off but when the button is pushed i get a tele/lilly_light/SENSOR = {"Time":"2021-08-27T14:45:04","Switch1":"ON"} which im thinking i need a template in my automation to be able to grab the switch1 state, anyone have any ideas?
I used automation for something similar
when i enter the {} into the payload the automation does not work
not sure, I have tasmota integration, I think it will decode the json, and could use parameters in automation
{{'%0.1f'|format([0, (states('sensor.power_home_energy_today')|float - states('sensor.power_powerplant_energy_today')|float)]|max }}
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensors']['potenza_prelevata_rete']['value_template']. Got "{{'%0.1f'| format([0, (states('sensor.power_home_energy_today')|float - states('sensor.power_powerplant_energy_today')|float)]|max }}". (See ?, line ?).
need an extra ) after |max
yes, found, let's check
I would need to create a template that creates a list of entities of types X & Y from what is can find in my scenes files. I need this to supply to the scene snapshotting definition. Is there a good way of doing this, or perhaps a better way?
it looks working, thanks!!!!
I can't follow your question - please rephrase? What do you mean by "types X&Y"?
Oh, sorry. types I meant 'light', 'switch' etc
This because I have some outlets that are categorized as switches, and would like them as well in the list of light entities
those are "domains"
the rest of the question is still a bit of a jumble
you want a list of entities that are part of scenes?
from what is can find in my scenes files
?
I'll try again, sorry to be vague, not my intention
not vague, just hard for me to parse
I have a set of scene files. I'd like to extract the entities for select domains from these into a list
the fact that you've separated your scene definitions into several files doesn't matter (again)
ok, keep forgetting that. I guess i think in terms "file parsing"
assuming they're in
-> States, you can use expand() to generate the entities
Ah, that is interesting, I've seen some talk about expand before, never really got into what it could be used for. Will have a read on that. Thanks! 🙂
I couldn't make that work. This is a start: {{ states.scene|map(attribute="attributes.entity_id")|list }}
that gives a list of lists of entities and I'm trying to flatten it somehow
ha: {{ states.scene|map(attribute="attributes.entity_id")|sum(start=[])|unique|list }}
only lights: {{ states.scene|map(attribute="attributes.entity_id")|sum(start=[])|select('match', 'light')|unique|list }}
switches and lights: {{ states.scene|map(attribute="attributes.entity_id")|sum(start=[])|select('match', 'switch|light')|unique|list }}
I'm done with this: @pastel moon
This is so cool! Thanks! Haven't had time to test more than the top one yet, but will be fun. Thank you!!
I have now tested a bit and can only get the first line to work. I get UndefinedError: 'mappingproxy object' has no attribute 'entity_id' when trying any of the other ones... I have tried all ways I can think of to break it down but can't seem to get it to work. I did google, but didn't give me a reason for the error (I could understand)
they all work for me
you pasted exactly that?
maybe you have scenes with no entities
I do believe you, and am very grateful you helped me with it. Yes, copy & pasted the exact lines
I like the |select('match', 'switch|light') 
I aim to please
I will try using another browser, haven't done that yet
another browser won't help. post what you're actually using
Can confirm Rob's template works. Even created my first ever scene just to test it.
I made a very simple script to test this, but refuses to run with the error above https://pastebin.com/yu8LVhqH
I like the sum(start=[]) bit. that was new
Yeah, I wondered what that was at first glance. Nice that you can force it to do array concatenation instead of math 😄
Every time I think I'm getting good at templates, I see something new.
(found via Google search)
make sure they work in
-> Templates
That's where I started. I get the same error there. That's when I tried to google it...
Oh... and match allows proper RegEx? I thought that was missing before?
I just copied exactly the script you provided and it worked out of teh box
yes, match does regex starting at the beginning and search looks for substrings anywhere
added earlier this year
Was about to ask why match wasn't letting me query the middle 😅
Now when people ask how to 'glob' stuff, I can give them this:
|select('search', '\.tv')
I'm stumped.
there's no reason that the first one would work and the rest wouldn't with that error
It's probably a typo somewhere. As much as I hate pictures of text... share a screenshot of the dev tools with that template and the rendered stuff on the right visible.
It throws the error when I add "Sum(start=[])"
Sum?
sum
Ok. Screenshot it please.
I'm wondering if it's this... https://www.home-assistant.io/docs/configuration/templating/#limited-templates
Make the whole template visible please, even if it means formatting it on multiple lines.
Just do a line break before each pipe
but...I literally copied exactly that script into my instance and it worked
"limited templates", I think, only apply in triggers
I'm just thinking it's being used as a variable in a script... but it's showing the error in Dev Tools too, where full template features should work.
I run this on Firefox in Linux. Probably not it either, but something must differ
Templates are rendered by the backend.
put all the templates in there, starting with the first one
in dev tools?
It's like one or more of the scenes don't have entities. 🤔
Throw this in your Dev Tools too:
{{ expand(states.scene) | list }}
Let's see the full contents of your scenes.
thought 🙂 #templates-archived message
I had an empty scenes.yaml earlier today, but is commented out. I am sure I have restarted since... 🤔 Will do it now just to make sure
Haha. I missed that 😄
HA version different then?
it still has an entity_id: attribute
Works on 2021.8.3 for me.
This is one of them, the rest look the same https://pastebin.com/707cPLCP
running core-2021.8.8
A good mystery is always great, but no fun when it seems to work for everybody else...
And the expand one #templates-archived message
Just upgraded to .8 here and still works.
I will try defining one, and one only scene and test with that. Something is not right, question is what. Thanks for the effort guys! I'll post back if I get anywhere
Made some progress. Turned out stale entries in the scenes list caused this error for me. Will enable the rest and hope it will continue to work
Finally... sigh, took a while to figure that one too. Now I will enjoy the nice pieces of code @inner mesa created earlier. 🙂
is it possible to create a virtual switch that doesn't do anything itself but can be toggled on/off via service and used in automation conditions?
suppose an input boolean would work for this purpose
that is indeed the purpose of that integration
someone please tell me the "select" field i have to add to get the name of the team "wolves" by scraping https://www.manutd.com/en/matches/fixtures-results
I'm using the template bellow to show the weather forecast condition (in a custom card...) but it shows the condition in english instead of dutch. In the default weather card it show the condition in dutch. Is there anything i can do or add to the template to show the condition also in dutch in my custom weather card.
'temperature') }}°C <br/> Verwachting is {{
states('sensor.openweathermap_forecast_condition') }}```
Make the custom weather card use translations.
Any change to explain how to do that.
If you didn't write the custom card, then there's nothing you can do
Oh OK 🙂
Going to use another template and translate each condition, only thing i can think about it now that works;
yep, that's about all you can do if the custom card doesn't support translations
you can always write up an issue against the custom card to let the dev know he's missing functionality
Alright y'all.....I am a total templating newb. Have read through the docs and just cannot figure out how to do a simple sum on two state values. Trying to add two wattage numbers and store that to a new value. Any help appreciated!
sensor.service_entrance_shelly_em_channel_1_power
sensor.service_entrance_shelly_em_channel_2_power
{{ state1 | float + state2 | float }}
| float converts it to an integer?
To a float (decimal). States are strings.
Or if you want to do multiple without it getting really long, use filters:
{{ [state1, state2, state3, ...] | float | sum }}
And to access the states themselves, sub in the usual function (states('sensor.some_sensor_name'))
Perfect. Thank you mono.
might need to map it to float
{{ [state1, state2, state3, ...]|map('float')|sum }}```
tia having a bit of difficulties with a template sensor it works in developer tools but im doing something wrong when i put it into my template.yaml https://paste.ubuntu.com/p/ZtxM2fHpdz/
That looks nothing like the format shown in the docs.
Hi everyone! I've made a template that works in the editor, how do I go ahead and make it a sensor in my HA?
Quite a rudimentary question, I know, I apologize
To my understanding, I just need this?
template:
- sensor:
- name: "name"
state: "{{ code }}"
But it gets messy because I have many lines of code
state: >- for multi-line
and then just paste it all below?
state: >-
{%- set foo = 'bar' -%}
{{ foo }}
and then I get a sensor on restart?
assuming your template and formatting are valid
wow that's frickin cool
I will let you know in a moment
my config just had a stroke
hmm, something strange going on with websocket api, I've subscribed to state changes and when I change the brightness of a light I'm seeing 3 messages through with the brightness level flipping around, first msg goes from 166 -> 87, then 87 165 then 165 -> 87
and it does that every time I change the brightness
in the end the last msg I recv is correct but sometimes there is a delay so I see my UI flipping around and being incorrect for a second or two
You should try #developers rather than templates
oh I was in other, must have clicked templates at some point.. will move to devs
hello can anyone help me out with templating?
{{ trigger.event.data.folder}}|regex_replace(find=media/,replace=media/local/,ignorecase=False){{ trigger.event.data.file }}
this is what i have but dont understand very well how to use them =/
{{ "/media/"|replace('media','media/local') ~ "file" }}
{{ trigger.event.data.folder|replace('media','media/local') ~ trigger.event.data.file }}
I don't know what you're doing exactly, but hopefully that points you in the right direction
The whole thing is a template, so you shouldn't be splitting it up like you did
make sense?
Yes i see the issue now i will deploy it hopefully it works thank you!
the first one is an example that you can play with in
-> Templates based on what you're getting from the event
Haa good idea i can test it there and not get my phone full of failed notifications ja!
it is almost there but it is clipping the last subfolder i'm getting /media/local/**camerafolder**/**filename.mp4** but it is missing the subfolder of the date could it be because of the replace?
Run some tests in dev->template
got it, just changed, event.data.folder for path and worked
now that i have the correct path, i'm getting a message saying failed to load attachment response status code was unacceptable: 404
Is there a way to get a list of devices (or entities) within a given area using a template?
there's this coming in 2021.9: https://rc.home-assistant.io/blog/2021/08/25/release-20219/#new-template-functions-for-areas
ok, looks like it will probably come in the next build: https://github.com/home-assistant/core/pull/55228 @sudden fractal
nice!
I was taking a look at the source code as well, it looks like area_id is at least partially working in 2021.8.8. Though it looks like in some cases it's an id and some cases it's name.
Newbie here, just migrated from SmartThings. Installed button-card and have it working on PC using Vivaldi (chrome). When I open with Vivaldi on my mobile, the Dashboard shows 'custom element not found'. A thorough search turned up <null>
#frontend-archived can help
Hi Rob, sorry not sure how frontend can help make a custom element show up for a mobile device.
well, templates certainly can't 🙂
you're talking about the frontend of Home Assistant
right?
button-card was installed using HACS and is a lovelace custom element. Works fine to create custom button card to set icon, color, animation for device state. When I load the dashboard the card is on with a mobile device running Vivaldi browser, the card shows 'custom element not found'. Makes no sense as mobile is simply running HA through a browser so should work same way regardless of what device browser is running on. Retired IT/programmer so using code editor is a no brainer for me.
Makes no sense as mobile is simply running HA through a browser so should work same way regardless of what device browser is running on
Well, no... you're not running HA in any browser, you're accessing a frontend that's being served up (hence Rob pointing you to #frontend-archived ). Also, not all browsers are created equal, much to the chagrin of frontend developers the world over - so it's common for things to work in some and not others.
I selected Vivaldi (based on Chrome) because implementation across devices is supposed to be very close to the same. I have now tried running on all popular android browsers: Vivaldi, Chrome, Opera, Firefox and result is the same. The custom element is not getting accessed. It is referenced under Lovelace Dashboards/Resources.
Just tried opening another instance on a different tab on my desktop, logging in, and get the same error now. Not sure why it's working on instance where I installed the element but not on any new instance.
Issue resolved - had to reinstall button-card in HACS and it changed the resource URL in Lovelace. All working now.
Just a caching thing in your #frontend-archived then.
After only a few hours of programming custom cards, not up to speed on things like frontend yet but will get there eventually.
I am using the openweathermap integration which provides hourly forecasts and I would like to create a sensor which tells me if it will rain in the next 8 hours (first 8 objects of the forecast list) - how can I acheive this with a template?
Anyone have any examples of similar templates?
I can loop through the lists fine using this
{% for forecast in state_attr('weather.openweathermap', 'forecast') -%}
{%- endfor %}
and then forecast.precipitation will give me the number I want to check
{{ state_attr('weather.openweathermap', 'forecast')[:8]|selectattr('precipitation', ">", 0)|list|count > 0 }}
Beautiful. Thank you
Can anyone tell me how to create a template sensor that will act as a "delta" sensor. My goal is to create a sensor that can tell how much a temp sensor has changed in a given period of time.
Templates can't do that. They act on current values, not historic ones.
You'll want to ask in #integrations-archived about ways to do that.
Ok thanks
Hello there!
I want to build a template to return the area_id of an entity. Is it possible?
It will be in 2021.9
Ha. No. You can thank raman325 for that addition.
Morning everyone, i need some help with a template sensor. I wanted to create battery monitoring for one of my temperature sensors, which have the battery status as an attribute, so i created the following sensor, which unfortunately is always "not available", although the sensor gets updated every 30 min... anybody can tell me why ? --> https://www.hastebin.com/ibihifiyul.yaml
Idea was to set the sensor to "not available" if nothing has been reported for 1 hour
What does this return in the template editor: {{ (as_timestamp(now())-as_timestamp(states.sensor.kuche_raumtemperatur_3_101.last_updated)) }}
Sorry should have mentioned that 😉 Of course i already checked, the value is (currentely) 390.46965289115906, and when i compare it to 3600 it evaluates to "Tru"
True
So the sensor should be available right?
I had issues recently using this way states.sensor.kuche_raumtemperatur_3_101.last_updated
Did you solve them somehow or give up;-)
I used nodered to solve it
Hi All, I am new to templates, any idea why I cannot see the below Item in my entities list?
sensor:
- platform: template
sensors:WLAN AP devices are connected to
christiaan_ap:
friendly_name: Christiaan AP
entity_id: binary_sensor.christiaan_ap
value_template: '{{states.device_tracker.christiaan_pixel_5.attributes.ap_mac}}'
#wlan_ap_device_two:
# friendly_name: WLAN AP Device 2
value_template: >
{{ {"12:34:56:78:90:ab": "EG", "12:34:56:78:90:cd": "OG", "12:34:56:78:90:ef": "DG"}[states.device_tracker.christiaan_pixel_5.attributes.ap_mac] | default("N/A") }}
(dont know how to paste to hastebin) 😦
If I use the template editor I can correctly see the Result I need to see, But I cannot see this as an entity at all
don't know?
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://hastebin.com/ (sometimes may not allow you to save)
Please don't use Pastebin, since it can randomly add spaces to the main view.
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
there's nothing there
sorry about that
it's confusing with the commented-out portions, but it looks like you have two value_template: keys
Yea I'm a idiot for pasting it like that. I removed the "#" from the equation and added a footnote
did you run the config check as shown above?
Yes no issues found
and restarted HA?
yes feels like 800 times nopw
*now
wait I ran the full check
at it picked up 2 sensor values in my yaml
and all of the sudden it works. Thanks RobC
It seems that I have to group my light-groups or separate them somehow. ?
https://www.codepile.net/pile/dmQB80qG <- Edit: fixed example 🙂
don't repeat the light key in your yaml
remove the ones from the bottom 2
light:
- platform: group
name: foo
- platform: group
name: foo2
That worked perfectly. Thank you. 🖖
how do you query the value of a number entity rather than a sensor object e.g. I have number.evnex_maximum_current and want to return the value in that entity as part of a template. Do I still use
{{ states('number.evnex_maximum_current')|int)}}?
yes, it's just an entity with a state
@inner mesa Are you in every group 🙂
Sorry for pushing that, but does anybody have an idea why this is not working before I start to delete the availability property?
Don't put quotes around multi line templates.
Only around single line templates, and if you do use single line templates make sure the quotes outside the template are different from those inside the template. So like one of these two options: https://www.hastebin.com/equmufitib.yaml
Thank you
Hi all template noob here. I am trying to extract key value pairs from a long, nested json string from my solar inverter which I want to push into HA entities.The string is here https://pastebin.com/TJnxHU19 Using the template Developer Tool but not getting past this
{% for key, value in data1.items() %}
{{ data1[key].item }}
{% endfor %}Result type: string
This template does not listen for any events and will not update automatically.
@spring blade posted a code wall, it is moved here --> https://hastebin.com/hufesaxedu
{% for key, value in data1.items() %}
{{ data1[value].item }}
{% endfor %}
Returns the whole string with error UndefinedError: dict object has no element.
Hi Guys, Any Idea why I am getting a TemplateSyntaxError: expected token 'name', got '{' error on the following code?
{{ {"74:83:c2:26:75:15": "Office Sales", "e0:63:da:1d:bd:b0": "Back Garden", "78:8a:20:b0:76:81": "Bar", "f0:9f:c2:d6:51:a9": "Home", "fc:ec:da:f3:dd:d3": "Office Tech"}[states.device_tracker.christiaan_pixel_5.attributes.ap_mac] | {"N/A": "N/A", "Unavailable": "N/A"}[states.device_tracker.christiaan_pixel_5.attributes.ap_mac] }}
I am testing with the server:8123/developer-tools/template tool
You're iterating your key and value in data, and you're using the value to pull out the information you already have... as value. Do you understand what it's doing or are you just blindly trying code?
You'll need to provide more information, like the configuration of the template, not just the value you're placing in the template. You have an error outside the template.
I don't think the syntax you're trying works. You'll have to split it out like so:
{{ json[states.device_tracker.christiaan_pixel_5.attributes.ap_mac] }}```
You're trying to get a value from a dictionary by key name, but you can't just string that syntax on the back of the JSON itself.
it'll work fine accept the | crap after
the error name but getting { is a specific error related to malformatted yaml.
No Problem Petro, I have the template defined as such in the configuration.yaml https://www.codepile.net/pile/QlXBqBWw and the state of the attributes.ap_mac is responding with the MAC of the AP it is connected to. Just that sometimes the entity is no longer on the network (becoming "Unavailable" or "N/A" if i take a look at the raw json) So I wanted to transform the template to show N/A for both those scenarios. (I would have used a OR statement on the Condition but I see that is not available)
use the word or
| is for filters in jinja, not or
your yaml looks fine, so not sure why you're getting 'name', i would assume that error is unrelated to your template.
your template should be:
{{ {"74:83:c2:26:75:15": "Office Sales", "e0:63:da:1d:bd:b0": "Back Garden", "78:8a:20:b0:76:81": "Bar", "f0:9f:c2:d6:51:a9": "Home", "fc:ec:da:f3:dd:d3": "Office Tech", "Unavailable":"N/A"}.get(state_attr('device_tracker.christiaan_pixel_5','ap_mac'), 'N\A') }}
Agreed more the latter.
that responds perfectly thanks Petro!
Take a look at this post to understand what a dictionary and a list is: https://community.home-assistant.io/t/how-to-extract-from-nested-json/99768/4
use what you learn there to access the items that you want.
you're data has a combination of lists and dictionaries at each item
Understanding types to parse JSON https://community.home-assistant.io/t/question-about-template-states/214733/2
that last one has a ton of info
Thanks that's helpful. On a previous attempt I was close but not quite there.
So e.g. {{ data1.data[0].dataDict[8].value }} returns what I am after but why do I get it three times - I guess one for each of key, value, name?
I will be doing some reading up on the links to get my head right with his stuff.
you get it 3 times because you're putting it in your for loop. You don't need the for loop
the for loop is iterating through all key value pairs in the top level dictionary. It happens to have 3 key value pairs
Ok got it. This works {{ data1['data'][0]['dataDict'][8].value }} and is more in line with your last link. When I had tried this before it was without the [0] . Thanks again. Great work.
Hey! I want an action to trigger after every change on a template (every time the result from the template changes), any smart thought?
Every time that changes:
´ {{ states.binary_sensor
| selectattr('state','eq','on')
| selectattr('attributes.device_class','eq','motion')
| rejectattr('entity_id','in',['binary_sensor.yi_movement'])
| map(attribute='entity_id')
| list
| count}}´
I think I got it... I have already another template sensor that contains something that should contain this other sensor... so I check if the first one is in the second...
Let's see 😉
hello, in #analytics-archived I asked why my grafana shows for some temperature sensors up-to-time values, and for others dont.
basically, if temperature is the same, then it has no additional information from the sensor
so basically I want to add horizontal line to my graphs using templates
this is the example, can it be done in such manner, when I dont receive any data from my sensor for example 10min, to update value to itself (same value), just to have up-to-time graphs?
You wouldn't use templates for that.
Templates know what is, they don't guess what should be.
You need to fix the issue via integrations.
Wonder if you could cheese it by subscribing to time.
{{ states('sensor.my_sensor') if n else 0 }}```
That'll update it every minute regardless
That's beautiful and disgusting at the same time.
but where to put this? like in some automation, and trigger would be time /10 min?
no, make a template sensor
it'll log the state of the original every minute and whenever the original changes
so you'll have updates every minute at the least
Is there a way to add a template to a custom: button-card state to use another entity_picture between certain hours?
- value: mostlycloudy
entity_picture: /local/weather/cloudy.png
color: '#B6B6B6' ```
This is the one I use now but the problem is that I have two different icons for partly cloudy day and night.
It’s JavaScript within the template, so presumably yes
I’m far from good with this so is there any change you can show how to accomplish this.
You should at least try it before asking others to do it all for you.
There are hits on StackOverflow
This is also a #frontend-archived topic, since cards and JS have nothing to do with Jinja templates.
Thanks mono, and I don’t want to be lazy but I have just no idea how to start. 😉
A journey of 1000 miles starts with a Google search
Well you know how to show one picture. Now you Google how to do a condition in JavaScript... and continue the conversation in #frontend-archived if necessary (after trying for yourself).
I didn't know how to do any of this until I Googled stuff. Same goes for my day job as a software engineer... that started with Googling too (and hasn't really stopped if I'm honest).
i always wonder how my work would look like without google
I have the following template sensor: value_template: "{{ ((states('sensor.nordpool_kwh_blabla') | float) + (states('input_number.addcost) | float) /100) }}". In Lovelace the history is just a bunch of colors. How do I get a nice graph instead when clicking on the entity? EDIT: Nevermind. Just needed a unit_of_measurement.
re-directed from #beta #beta message I've been looking for a way to template and use the Areas of our devices/entities. Haven't found it though, so please have a look if you can help me out with eg 'All "on" switches in Area Living room'. Only thing with Areas right now I get working in templates is the new {{area_name(trigger.entity_id)}} but not the other way around state_attr('binary_sensor.front_room_sensor_motion','area_name')}} because area is no part of the state.
or a notification like: 'Can not turn on Alarm, because Area Livingroom still has 3 switches on (switch x1, switch x2 and switch x3').
area_name?
I don't see that in the docs and it doesn't work on 2021.8
Oh, you're asking how to use #beta stuff in the main support channels... yeah, nope.
From the looks of the conversation, that isn't even going to make it into 2021.9, so come back and ask in October.
that's a new PR that was still open the last time I looked
Until that gets merged and released, the next best thing is to customise your entities with attributes that denote the 'area' they're in, and use that attribute in templates instead.
More work, but I haven't seen a better workaround.
Another alternative would be to name all your entities so they can be searched via RegEx for a room/area.
But yeah, no support for unreleased / #beta features in here.
area_name and area_id is actually a thing in 2021.9
I'm already using them...
area_name(<name of entity_id>) returns the Area from this entity. how may I help you use them?
he wants a list of entities in that area, which is only available via a PR that's still open and not included in 2021.9
Yes, you're right he did wrote that 😛
Thanks for the tag, but I'm aware what he was asking 😉
tag
phanx
Isn't it possible to create a for loop and check the area for each entity and put them in a list if they match the area you need?
would be pretty clunky
probably
I tend to lose interest as soon as I can't solve a problem with a clever set of filters 🙂
once it goes to a for loop, I look for a different problem to solve
{{ states.sensor|map(attribute='entity_id')|map('area_name')|reject('eq', None)|list }}
good news, area_name is a filter
doesn't answer the question though
right, you lose the object and can't select based on the state or get back to the entities
have to do all of your state filtering before-hand
could make it generic instead of counts
{{ "Unable to comply. {} {} entities active".format(', '.join(areas), 'have' if areas|length > 1 else 'has') if areas|length > 0 else "ok" }}```
still, the goal was to end up with a list of entities to turn off, and I still can't work out how one might do that
i really need to learn to use the map filter
map is amazing
i notice from all your examples
that above example has both uses of that filter. You can either select an attribute to use (supports dot walking) or you can apply a filter against all items
actually, this could work. you can call homeassistant.turn_off with an area_id
yeah, I mentioned that. he wants to only target the ones that are on for some reason
that's where this started
service: homeassistant.turn_off
target:
area_id: >-
{{ states.binary_sensor|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|map('area_id')|reject('eq', None)|unique|list }}
but i don't think we can get to the state of the area itself
since i don't think it has one
ah
then use a group
and the state of that group
i still haven't found a good use of areas
could probably just call light.turn_off and switch.turn_off with that same template for area_id
assuming that field accepts templates
hi, back again... thanks for all the efforts. we must conclude what I hoped that would be possible, and shouldnt be too odd to want, simply isn't available yet. Ive explored what phnx tries to do, but they are all workarounds really. And, for now, don't get where we want the (use of) Areas to take us.
So try again in October.
a group as substitute for Area, or as Mono suggested, add a customized attribute for zone (which indeed would be the best option currently) are both substitutes for whats to come in 2021.10 hopefully..
This is what I do for things in a room:
{{ states | selectattr('attributes.room', 'equalto', 'study') | map(attribute='entity_id') | list }}```
At least it lets you filter before you map.
yep, thats what I meant above, thanks
still dont see the obvious I was steered at in #beta though...
I think they were just kicking you out because it's not related to this beta. It'll be in the next one.
no, they wouldnt.... 😉
I guess you can extend my template if you're doing it in automations:
{{ states | selectattr('attributes.room', 'equalto', trigger.entity_id.attributes.room) | map(attribute='entity_id') | list }}
But then you'd have to double up on attributes and areas 🤦♂️
Meh. Lemme edit...
I've probably mucked that up but you get the idea.
exactly, doing it right now, is a mess... but yes, I get it, been customizing against better judgement of certain dev's for 4 years now, getting where HA wont go..
btw see: https://youtu.be/CxrB7DmkDJQ?t=3141 (in the pipeline...says balloob)
im trying to print out the duration that a job ran using a custom template.
This is what I have so far
{% set secs = (trigger.to_state.last_changed - trigger.from_state.last_changed) -%}
{% set days = secs//8640 -%}
{% set hours = (secs - days*86400)//3600 -%}
{% set minutes = (secs - days*86400 - hours*3600)//60 -%}
Job ran for {{hours | int}} hours {{minutes | int}} minutes
It feels a bit verbose, is there a more concise way of doing it?
relative_time is an option, but may not granular enough: https://www.home-assistant.io/docs/configuration/templating/#time
{{ relative_time(states.switch.fr_table_lamp.last_changed) }} -> 30 minutes
Hi everyone, simple question this time. I just want to transfer the value I have calculated (stored in sensor.calculated_sp) into an existing entity (number.evnex_maximum_current). But all templates seem to be about creating a new entity, here I don't need a new entity, I just want to copy values between existing entities. How do I do this please
yeah the docs say "only the biggest unit is considered" which is not ideal for me...
That would be an automation that reads your template sensor and sets the value of an input number.
How often does the automation do this? Just once? Or do I need to set an automation that repeats every minute to update the result of the calculation?
That depends what you're actually trying to achieve 🤷♂️
The updated available power from my solar arrives every minute (from SolaX) I understand in templates that the calculation gets re-triggered when an input variable changes so this updates once per minute. I then want the available power, divided by 230 volts, to be added to the current power limit to my EV. I have this calculation working thanks to @inner mesa
So really it is every minute
I don't understand where the copying comes in.
My OCCP based EV charger allows me to write to its internal hardware to set the charge limit to the car. That is a pre-created entity called number.evnex_maximum_current So I need to send the value of my calculation to this entity
Right. So that's just what I suggested at the beginning. Use an #automations-archived .
And I can set the automation to run every minute?
trigger:
- platform: time_pattern
minutes: '/1'
```?
There's an entire channel for talking about #automations-archived.
It was even given a name that makes it obvious that it's about #automations-archived
OK but I was thinking this could be done in a template which is why I started here. I am trying to follow the rules 🙂
It's not a template. It's an automation. I thought I'd made that clear already (several times).
👋
Yes you have
group lights YAML
I have installed the new core-2021.9.0 as it better supports the energy page and has new templates. I wanted to create a new number entity. However, even following the guide, I am struggling.
sensor:
- platform : template
number:
- name: "Test for car"
min: 0
max: 32
step: 1```
I skipped state and set_value as I don't need them at this stage. First, why does the entity not have a name? The name field looks more like a 'nice name'
second, this passes configuration check but fails on restart
your space is not in the right place, to start
and you have number: under sensor?
it's wrong
it doesn't follow what was in the blog post
Where else do you put any entity?
Wrong integration
number:
- name: "test_number"
state: "{{ states('input_number.test') }}"
min: 0
max: 100
step: 1
set_value:
service: input_number.set_value
target:
entity_id: input_number.test
data:
value: "{{ value }}"
under template:
In configuration.yaml
You’re mixing the old configuration and the new style
there are some nice examples here: https://www.home-assistant.io/blog/2021/09/01/release-20219/#new-template-entities-number-and-select
You can only use the new style. I.e. platform:template is not the new style
OK, I actually started with that example page...but it got rejected by configuration check, will try again
This is a good start #templates-archived message
Put it under template section with a - in front of number
I have template: !include templates.yaml in configuration.yaml, and exactly the content above in templates.yaml
I threw it together to test your last issue 🙂
OK, I assume the input_number.set_value entity is something you also created under sensors, but I will not need, right?
I could just create: template: number: - name: "test_number" min: 0 max: 32 step: 1
and then I have a variable I can use in my testing
Invalid config
The following integrations and platforms could not be set up:
template
Please check your config and logs.
You need the - before number like I said
I don't think so
I tried exactly RobC code and it was accepted and worked
it has no - in front of number
It does however have a 'state' line
can I just use state: {{}}
that's not a very interesting entity
Its a dummy variable I can then use in automations
that's an input_number
So I can use to test the automation that is currently failing
Not sure why without the dash is working
It follows the same config as trigger
Which requires the dash
it has to be 'number' in the automation as eventually it writes to a number entity created by OCCP
the blog post shows both number: and select: without it
a dict vs. a list, in other words
Yes but the whole template section is a list
You can’t mix and match
It’s a list or a dict
I agree that the template sensor docs all show the sensors as a list
If I remove the 'set value' section it fails to load. Same error message as above
All I am really after is a number entity I can write to
like I said, input_number
those already exist
you're trying to use the wrong tool for the job
Does this mean that the occp writers, who have created a number entity, one that needs to be written to or used with a slider, should have created an input_number entity, noting of course that this is a value they read and write to/from inside the EV Charger?
I suppose, as you say, it's like trigger: (or condition: or sequence:), where one doesn't need to be a list, but more than one does
That would be my guess
no, integrations can create number entities, but can't create input_number. If an integration wants to take a number as input, it needs to use number. If you want a variable for yourself that you can set and read, then you can create an input_number
It doesn’t make sense otherwise
In dev tools templates I now have:```
sequence:
- service: number.set_value
target:
entity_id: number.evnex_maximum_current
data:
value: "{{ states('sensor.pv_to_car')|int }}"```
Cause it can’t be both a dict and a list, and I 100% treat my config as a list for templates
Unless number and select are outside the template section
This has '19' as the value for data, which is correct, but number.evnex_maximum_current is still reading 32. Do I have to reload this template or in some way restart it?
that's up to the integration
So why aren’t you using input_number?
If you have more than 1, it has to be a list because you can't have duplicate keys
saw something shiny and new in the blog 🙂
Ah
actually, I think the number entity there is exposed by the integration, as I mentioned above
Well, you can use trigger with number
yeah, we went over that earlier
so why is the sequence I pasted above not writing to the number entity?
the integration doesn't like what you're providing, or has an issue
it's coming from the integration, right? check your logs
where did that number entity come from?
Template that he just made.
Nope, it can from the OCCP integration
It’s not going to update because the set value doesn’t have a service and the service doesn’t impact the state of the number
Well disregard my comment then, was based on it being a template number
What’s occp, doesn’t come up in the docs, custom?
I can display this number.evnex_maximum_current on a page, it always shows with a slider. I can drag the slider and the EV charger responds, I can see it reducing its output power to match. I can type into the entity from dev_tools, also works
OCCP is a HACS integration
have you checked the logs?
so being able to write to it and use a slider does not mean I cand set_value?
Yes, I turned Russian there for a second, its OCPP
async def async_set_value(self, value):
"""Set new value."""
num_value = float(value)
if num_value < self._minimum or num_value > self._maximum:
raise vol.Invalid(
f"Invalid value for {self.entity_id}: {value} (range {self._minimum} - {self._maximum})"
)
so...check your logs
Two warnings in logs, both about set last_reset being deprecated
It supports it, just checked code
it's up there
I also set " custom_components.ocpp: debug" under logger in configuration.yam;
so nothing in the logs
last time you claimed that it was sending the string rather than the value, which I could not reproduce: https://discordapp.com/channels/330944238910963714/672220450977349653/882766580000378910
I can see my code running in dev tools templates. Every minute or so the 'value' changes to 17 or 18 or 19 based on my solar cells. But nothing is going into number.evnex_maximum_current
There’s no messages in the function that log anything so the logs will be useless
Yes, it was a string last time because the entity did not even exist. Its only created when the EV charger cycles up, which only happens when a car is plugged in that needs charging
ok, but I think you're still claiming that you can set it in dev tools, but not in the automation
Setting things in dev tools is not the same
no, when it did not exist it said 'unknown' in dev tools
of course it existed as an entity, since entities never die, you have to delete them
ooohh, I put 5 as the value instead of the number.evnex_maximum_current and now I have a message that says "This template does not listen for any events and will not update automatically"
so how do I get the sequence to run every time sensor.pv_to_car changes?
not what I meant
sequence:
- service: number.set_value
target:
entity_id: number.evnex_maximum_current
data:
value: 5
That is exactly what I have
I put 5 as the value instead of the number.evnex_maximum_current
that's not how I read that, but ok
anyway, does that set the number to 5? feel free to pick a better number
no
alright, you clearly have a mystery to solve
probably better taken up with the author of that integration
I was thinking, this is a value both read from and written to OCPP. Does that make trouble? for example does HA see that the value it has in HA is not the same as OCPP so overwites it?
Though under that basis you could never write to a read/write register in any external device...
that, also, is a question for the author of that integration
Luckily I know the author who put in the EVNEX charger personally
go buy them a beer
👍
I have nothing that exposes a number entity, and the one that I created as per the blog post works fine for reading and writing
OK, found an error in the log that is interesting:
https://paste.ubuntu.com/p/w2N3V66929/
the key is "AttributeError: 'Number' object has no attribute 'min_value'"
This is what number.evnex_maximum_current does have: initial: 32 editable: true min: 0 max: 32 step: 1 mode: slider unit_of_measurement: A friendly_name: evnex.Maximum_Current icon: mdi:ev-station
When you talk to the dev, tell them that this seems to be wrong: class Number(InputNumber):
Seems like it should derive from https://github.com/home-assistant/core/tree/dev/homeassistant/components/number
OK, have done so and also put it on the issues list on github
getting back to this: {{ states.binary_sensor|selectattr('state', 'eq', 'off') |map(attribute='entity_id')|map('area_id')|reject('eq', None)|unique|list }} please educate me on what I am seeing being returned: [ "51721157e7d0491abbffa49c9b069e7e", "df21e517d2624b49a682041fe632cddc", "b36ceff2389e4b189f528ede60ad291f", "c52f1c47fd9111eaa95e2bc99216c855", "stookhok" ] seems to be a list of area_id's, of which only one has been named by me, and the others are system generated?
do all devices have a system generated area_id until the user sets one? and, for the template at hand, can we filter out those?
wait... I discovered core.area_registry and the above numbers are id's for user set Area's. changing the template to ```{{ states.binary_sensor|selectattr('state', 'eq', 'off')|map(attribute='entity_id')|map('area_name')|reject('eq', None)|unique|list }}
but now the question is why do a few of the area's have name/id sets like: { "name": "Garden terrace", "id": "garden_terrace" }, { "name": "Garden backyard", "id": "garden_backyard" }, where others are system generated like: { "name": "Corridor", "id": "3b2a49ef6eef476ab8873510626542ac" }, { "name": "Dining room", "id": "93c3a87cc88945cdbdc859fc2495804f" },
moving that to #330990055533576204 I guess..
listing all available areas: {{ states |map(attribute='entity_id')|map('area_name')|reject('eq', None)|unique|list }} 😉
no way to template that directly? but this is a small enough hack..
I don't see how that's a hack
well, a workaround then. opposed to using something like {{areas|list}} if areas would have been available directly, we now have to go via the entities that have an Area set
Area id's used to be these kind of random strings. I renamed those to e.g. woonkamer_oud created a new area called woonkamer and then moved everything from the old area to the new one. After that you can remove the old area
So post a feature request for that. Or even better, submit a PR.
so this is 'old' versus 'new'?
well, Raman will develop the current Area options going forward to 2021.10, and maybe this will be included. Not really sure how to proceed in asking him, without a tag... and I am not allowed to ask in any of the #dev channels...
if it's old vrs new, then it's 'very old vs new'. I created my areas in january and they all have area_id's that match area_name, but lowercase and using underscore
yes, thats what I tried to describe in my https://community.home-assistant.io/t/why-some-areas-have-a-slugified-area-id-others-a-system-generated-number/334997 post.
i'm not sure why that's a question though
who cares about the id
it's an identifier
it's meant for code
not for humans
because it was suggested in a template yesterday, I started having a look to study that. And when noticed, tried to understand and make sense of it
what were you going to use the area_id for if it was suggested to use it?
this #templates-archived message was the template, and I was looking for a way to eg turn_off all 'on' switches in a certain area
ok, and that would work, so what's all the fuss about the output?
I think we concluded that waiting for https://github.com/home-assistant/core/pull/55228 would be best since that will introduce area_entities()
not exactly no.
Mono's suggestions comes closest, to add an attribute as customization with an area name and template on that attribute
how so, that service will turn off all devices in that area id that are on
unless the intention is to only target specific entity types
All devices, not just devices of a certain domain.
My goal was to turn off switches in let's say area 'Living room'. (remember we hadn't noticed the slugified id's yet, only working with the system generated)
use namespace and you can get the list now
was trying this:```{{ states.switch|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|map('area_id')|select('eq', 'Living')|list }}
{% set ns = namespace(entities=[]) %}
{% for s in states.switch | selectattr('state','eq','on') %}
{% if area_name(s.entity_id) == 'Living Room' %}
{% set ns.entities = ns.entities + [ s.entity_id ] %}
{% endif %}
{% endfor %}
{{ ns.entities }}
using map will not work because it changes the object to the mapped value.
after area_entities is added...
{{ states.switch | selectattr('entity_id', 'in', area_entities('Living Room')) | selectattr('state','eq','on') | map(attribute='entity_id') | list }}
just as ugly.
so, it's not like it'll be any better
or
thanks Petro, appreciated. Your template doenst work though, [] result
Ive got a rest sensor that give me some data,
But in the json attributes is shows text like <br> </>
- how can i excludes that in my sensor text ??
more efficient
{{ expand(area_entities('Living Room')) | selectattr('domain','eq','switch') | selectattr('state','eq','on') | map(attribute='entity_id') | list }}
they all will work, the last 2 will only work on 2021.10
namespace template gives me an empty list. 2021.9
Value from json file: "description": "HERE THE INPUT TESXT <br /> <br />WILL BE SHOWN.",
- platform: template
sensors:
sensor:
friendly_name_template: "Sensor name"
value_template: >
{{ state_attr("sensor.sensor","properties").title + ' / ' + state_attr("sensor.sensor","properties").description + ' / ' + state_attr("sensor.sensor","properties").lastModified }}
In the .description it shows <br /> <br />
i want to exclued that letter in the sensor so it wont show <br /> <br />
- platform: rest
name: Sensor name
json_attributes_path: "$.features[0]"
json_attributes:- title
- header
- description
- beginPeriod
- lastModified
- properties
- geometry
resource: https://storage.googleapis.com/filename.json
value_template: "{{ value_json.features[0]['properties']['title'] }}"
This is my rest sensor that creates info...
- from that i use a template sensor like the first i wrote...
Value from my rest sensor is: "description": "HERE THE INPUT TESXT <br /> <br />WILL BE SHOWN.",
- But in this i would like to hide : <br /> <br />
in this value_template
{{ state_attr("sensor.sensor","properties").title + ' / ' + state_attr("sensor.sensor","properties").description + ' / ' + state_attr("sensor.sensor","properties").lastModified }}
then just use .replace('<br /> <br />', '')
I had another template in the editor, whihc interfered apparently. I can now see a switch showing up! There's something odd though. using this template ```{{ states
|map(attribute='entity_id')|map('area_name')|reject('eq', None)|unique|list }}
works fine for me
So like this ? {{ state_attr("sensor.sensor","properties").title + ' / ' + state_attr("sensor.sensor","properties").description .replace('<br /> <br />', '') + ' / ' + state_attr("sensor.sensor","properties").lastModified }}
yep, but without the space between n and .
Okay so like this, sorry havent tried it before 😛
{{ state_attr("sensor.sensor","properties").title + ' / ' + state_attr("sensor.sensor","properties").description.replace('<br /> <br />', '') + ' / ' + state_attr("sensor.sensor","properties").lastModified }}
just test it in the template tester
Just did and it work thank u!
Is it possible to set Title name from a sensor with notify?
Hey guys, I need your help, I wish to make something like this, like putting another layout of logical operator in parentheses
{% if is_state('sun.sun' ,'below_horizon') and {if is_state('light.allhome' ,'on') or (not if is_state('input_select.maeva_home' ,'Inside') and is_state('input_select.tom_home' ,'Inside'))) %}
Simplier:
{.. and (.. and ..)
how can I?
By using parenthesis… just like you have
Arg, i might did a mistake then, thank youu, I'll come back later when I'll find it
You used if twice for some reason
you're a god thank you
If ( … and ( … and … )
That was simple as that 😮💨
Hi Guys, can somebody help me? I'm trying to write a template sensor, which shows the "Grid-uptake" of power. So I wanted the sensor to subtract the energy produced with the solar panels from the total energy consumption of the house.
This is what I tried:
value_template: >- {% set verbrauch = states.sensor.stromverbrauch_haus_gesamt_geglattet_taglich|float %} {% set produktion = states.sensor.stromproduktion_photovoltaik_taglich|float %} {{ (verbrauch - produktion)|round(1) }}
But I get always zero
because you are casting the object to a float which will always be 0
use states('sensor.whatever')|float
thank you so much !! I'll try this
It works! I don't fully understand why, but it does 🙂
states.domain.entity is the entity object, not a state
NaN|float will always -> 0.0
Thanks a lot. will study this. One more:
`type: entity
entity: sensor.total_energy_uptake_grid
style: |
- {
--primary-text-color:
{% if states("sensor.total_energy_uptake_grid")|float > 0 }
Green;
{% else %}
OrangeRed;
{% endif %};
}`
Did I miss something. Want a green value if the value of the sensor is positive
too may ;
that question doesn't make sense
templates update themselves
templates do not know state history
you'll need an input number and you'll have to store the lowest number in that input number for it to persist alltime, so this would be an automation
okay thats right, deleted a few ; 🙂
`type: entity
entity: sensor.total_energy_uptake_grid
style: |
- {
--primary-text-color:
{% if states("sensor.total_energy_uptake_grid")|float > 0 }
Green
{% else %}
OrangeRed
{% endif %};
}`
Is it possible, that my condition is wrong
Not with a template. They're based on current values only.
Integrations have access to historic data.
Maybe it is possible to update the value of another template sensor when the main sensor is higher then the old?
@primal canyon When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.
And no, that sounds silly. You'd use either an automation or an integration to achieve that.
There are several #integrations-archived which could do what you're asking, so I suggest you ask there.
Whenever the trigger fires, all related entities will re-render and it will have access to the trigger data in the templates.
a trigger-based template sensor could probably do it
Or a utility meter or SQL sensor 🤷♂️
But all of the things mentioned, including the template sensor are #integrations-archived
Does this look correct?
{{ ((trigger.event.data.type == 6 ) and ( trigger.event.data.event == 6 ) and ( trigger.event.data.event_label == 'Keypad unlock operation') and ( trigger.event.data.parameters.userId == [1, 2, 3, 4, 5] )) }}
It looks well-formed if that's what you're asking.
No need for the outer parentheses though. The ands will work without the whole statement being wrapped.
You could probably get rid of all of the parentheses if you wanted, since equality is going to be checked first.
Thanks….I struggle with setting variables in the template manager…knowing it is close will get me started.
Why did you delete your question and ask it again an hour later?
Don't do that again. Thanks.
Could someone help me figure out why my sensor isn't picking up a state?
I think my template is setup wrong
- trigger:
sensor:- name: "Tariff Price"
unit_of_measurement: USD
state: >
{% if is_state('utility_meter.monthly_energy', 'peak') %}
{{ 0.11951 }}
{% elif is_state('utility_meter.monthly_energy', 'offpeak') %}
{{ 0.11229 }}
{% endif %}
- name: "Tariff Price"
I'm referencing it using the following line in my config file
template: !include templates.yaml
the sensor shows up as an entity in developer tools
but the state isn't populating.
utility_meter.monthly_energy says offpeak
so that's working.
please format your code
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
it looks like you have a trigger: with no actual trigger
and that means that it will never update
that's the kiss of death
but he didn't have that either. 😕
following the docs > following some rando video
Trigger-based entities do not automatically update when states referenced in the templates change. This functionality can be added back by defining a state trigger for each entity that you want to trigger updates.
So it sounds like I just need to get rid of the trigger
That fixed it
thank you so much!
well, the price still isn't showing up in my energy dashboard, but now at least the sensor.tariff_price is populating correctly.
Hi. I have a template like this
- platform: template
sensors:
tesla_charing_at_home:
value_template: >
{% if is_state('device_tracker.tesla_location', 'home') %}
{{ (states('sensor.tesla_charger_power') | float)}}
{% else %}
{% endif %}
But the corresponding sensor is a state sensor not with values like it should. How could i fix this?
I like to fill the sensor.tesla_charging_at_home if the car location is at 'home' from the sensor.tesla_charger_power sensor.
You can’t just have an empty else like that
Please rephrase your first sentence? It doesn’t make sense
Ok, with the else i can fix.
The "tesla.charging_at_home" sensor contains in the frontend just the state like on/off not the value with an graph.
I cannot upload an image to visualize this.
it sounds like you put that under binary_sensor: instead of sensor:
It sounds, bit it is not. Its in the same folder like my other energy sensors i crated from plugs or other hardware.
Is something like that possible to do? Maybe HA is not captable to fill a sensor with a sensor value.
you mean in the frontend?
are you really getting on/off, or something else?
if you're getting values and they're just not displayed in a graph, then you need to add a unit_of_measurement
A screenshot of the sensor: https://imgur.com/a/Z5M956D
Also tried this.
you need to let the old data flush out, or purge that entity
unit_of_measurement string (optional, default: None)
Defines the units of measurement of the sensor, if any. This will also influence the graphical presentation in the history visualization as a continuous value. Sensors with missing unit_of_measurement are showing as discrete values.
Thx. the unit_of_measurement did the trick!
am I misreading this: https://developers.home-assistant.io/docs/core/entity/sensor/ shows a device_class of gas available, but when I'm trying to use it for an MQTT sensor it says gas is not one of the available options
What does?
It does
I hate that thing. It’s always so vague
Ignore the dev docs (they're meant for devs). Read the official docs: https://www.home-assistant.io/integrations/sensor/
any idea of those which is most appropriate for a gas meter?
I have an RTL-SDR that reads my power and gas meters to mqtt topics of readings/$DEVICEID/meter_reading and I'm trying to get those values into HA as sensors with the appropriate unit of measurement
maybe just leave it blank?
You've described what you've already done, not what you're trying to do next.
Either way, this doesn't seem to have anything to do with templates, and belongs in #integrations-archived
probably so, I started out in here because I needed to convert the number to a different value using templates, but I'm pretty sure I figured that out with just a / 100
guys, just a quick question:
i want a template to report true if a entity value is >0. Is this condition right:?
{% if states("sensor.total_energy_uptake_grid")|float > 0 }
‘Report’ would imply removing the if and using {{ }}
Oh, right. Sorry. You're right.
It happens occasionally 😅
Do that instead
thank you the 2nd percentage char did the job!
I don't think it did...
it is an if clause for a custom format of the value in lovelace
value should be formatted green if greater than zero and red if less 🙂
So a bit of term confusion then. Glad things worked out.
Of course 🙂 I'm a newbie ^^
we all are...
Ok, what am I doing wrong?
{% set trigger = {
"event.data.type": 6,
"event.data.event": 6,
"event.data.event_label":"Keypad unlock operation",
"event.data.parameters.userId": 1
}
%}
{{ (trigger.event.data.type == 6 ) and ( trigger.event.data.event == 6 ) and ( trigger.event.data.event_label == 'Keypad unlock operation') and ( trigger.event.data.parameters.userId == 1 ) }}
The first half isn't structured correctly. You're defining a dictionary with 4 keys, each of which are a quoted string.
UndefinedError: 'dict object' has no attribute 'event'
"event": {
"data": {
"type": 6,
"event": 6,
"event_label":"Keypad unlock operation",
"parameters": {
"userId": 1
}
}
}
}
%}```
Auh....ok
Assuming the second half is correct, it expects a structure like that.
that makes sense
Dot notation works for accessing nested properties of objects... but dots in key names don't denote nesting.
so when I set trigger.event.data.parameters.userId == 1 is evaluates as true
but when I set trigger.event.data.parameters.userId == [1, 2, 3, 4, 5, 6] it evaluates as false
I should be able to list a dict like that correct? or is it taking the comma as part of the dict?
The states object being a notable and disgusting exception since the following three lines are equivalent ```
{{states.light.bed_light}}
{{states["light.bed_light"]}}
{{states["light"]["bed_light"]}}
Only for accessing, though.
🤯
First and last are equivalent anyway, it's the middle one that's weird.
And I guess that's just because the state object holds references in both places.
Spot on. And the dictionary is also callable states("light.bed_light"). Hacky indeed.
Well, it helps with Jinja filters, so I’m onboard. They’re my favorite
| replace('u', '')
Hi All
I'm either not understanding total_increasing state_class or something might not be configured correctly. I am integrating into my unfi setup and am looking at tracking total traffic for some users however unifi works on sessions so the traffic will keep increasing until the user disconnects. One they reconnect it starts at 0 again. I'm looking for a way to have an ever increasing value in HA. So I configured the following:
- name: "Edward - Pixel 5 Total Traffic"
unique_id: sensor.edward_pixel_5_total_traffic
state: >
{{float(states('sensor.edward_pixel5_rx')) + float(states('sensor.edward_pixel5_tx')) }}
unit_of_measurement: "MB"
state_class: total_increasing
However when I look at the sensor value it seems to be going back to 0 instead of continuously aggregating. Herewith is a screenshot of the sensor values: https://imgur.com/a/BvvDUTz
Hi, guys!
Just need to get this confirmed, as something is wrong, not running what´s after this condition even when group.family is not__home
- condition: template ## Continue only if nobody is home
value_template: "{{ is_state('group.family', 'not_home') }}"
I want all services listet after this condition to be run if condition evaluates true. Is the condition correct, then?
The template looks fine to me. Have you tested it in dev tools so you're certain it works as expected?
If so, is your automation syntax correct? https://www.home-assistant.io/docs/scripts/conditions/#template-condition
From the examples:
conditions: "{{ (state_attr('device_tracker.iphone', 'battery_level')|int) > 50 }}" or
condition:
condition: template
value_template: "{{ (state_attr('device_tracker.iphone', 'battery_level')|int) > 50 }}"
Yes, I have tested it and it evaluated as expected in dev tools. I should test the short hand method from the examples, as I see I only use one condition: and the value_template
the shorthand - conditions: "{{ is_state('group.family', 'not_home') }}" evaluates with error:
Invalid config for [script]: [conditions] is an invalid option for [script]. Check: script->sequence->2->conditions. (See ?, line ?)
Your shorthand is wrong, yaml wise
- "{{ }}"
That example in the documentation should probably say condition: {{ (state_attr... without the plural...
...maybe...
Yeah, you're right Thomas. I tried conditions as the docs says. Didn't work.
So I guess it is a combination of wrong docs and the incorrect leading dash before condition (see petros's post).
Anyway, this works:
- id: '1630331287319'
alias: TEST
trigger:
- platform: state
entity_id: switch.<...>
condition: "{{ is_state('switch.<...>', 'on') }}"
action:
- service: notify.<...>
Yes, that would work because a single item list can be represented 2 ways in yaml:
- id: '1630331287319'
alias: TEST
trigger:
- platform: state
entity_id: switch.<...>
condition: "{{ is_state('switch.<...>', 'on') }}"
action:
- service: notify.<...>
or
- id: '1630331287319'
alias: TEST
trigger:
- platform: state
entity_id: switch.<...>
condition:
- "{{ is_state('switch.<...>', 'on') }}"
action:
- service: notify.<...>
Anyone possibly have any insight into why I might be seeing this behavior?
Would you use a template to create an entity that has a numerical value of of two entities states combined?
or would you do that another way?
I want to see the true cost of my mining rig in the dashboard. I use two plugs though. So I can see one at a time, but I'd like to see them both.
Same for a server I have dual PSUs on.
I guess creating a custom entity would be best? Is that possible?
This is my first attempt.
state_class: measurement
unit_of_measurement: kWh
device_class: energy
state: >
{{ state('sensor.emporia_power_plug_3_123_1d + sensor.emporia_power_plug_4_123_1d') }}
I feel like I'm so close.
{{ states('sensor.emporia_power_plug_4_123_1d')|float + states('sensor.emporia_power_plug_3_123_1d')|float }}
Testing, thank you
so the trick is states plural, and converting them to floats?
IT'S WORKING!
Thank you so much!
Hmm I can't add it to the indvidual devices space in the energy dashboard 😕
and you need to call states() for each entity
Is there a graceful way to get the value of a sensor from a specific time (in the past) without using a SQL query into homeassistant_v2.db? I’m after trying to get a value of a sensor from 3 days ago, so I can calculate the 3-day delta of it in a template. Seems like a common use case, but reading some stuff of it not being available and needing SQL. Have things changed with the introduction of long term stats?
Looks like history stats does something else. That allows for getting durations of a sensor being in a specific state. I am looking to query the historical value at a point in time.
gotcha, no idea then
super dumb question that has stumped me... when creating a template that uses "Entity" I am able to use [[[ return entity.entity_id ]]]
How can I use something similar when using "Entities"
I am trying to use custom switch-popup-card
wait no you're right.. This wont work then.. Thanks
Nope, you need to query.
Hello guys, a few months back there was a really helpful message about using "map", I'm trying to map different fans speeds of my fan (off, low, medium, ...) to the actual fan_modes that the fan-entity accepts. I'd like to use map to "translate" my off, low, ...-values to those that the fan accepts. Can anyone help me finding the example or help me otherwise?
Ah, I found another post (#templates-archived message) Wasn't what I remembered, but worked anyway 🙂
hi i'm trying to pull 3 values from a rest call and https://hastebin.com/ejutobuzug.yaml nearly works home assistant says my config is good i get 3 sensors but the values are unknown i think there should be 4 but ... i'm new to this it was a win to finally get it to validate
hmm i've broke it sensor.csensor. State max length is 255 characters
Ok. And you're doing it wrong anyway. Remember when you first asked about this and I asked if the order of the entries was always the same?
That's because you don't have keys to access the data with. You have to access the list of items based on their position.
Nothing you're trying to do with the JSON attributes will work. You need 3 separate sensors, like I suggested the first time round.
You were given the working code for the first one. Tweak it for the other two.
ok but does that mean i have to call the api 3 times like this https://hastebin.com/ireholepit.less lets try again the value of csensor is 862,306,4489 FORECAST_PEAK_TODAY862,LATEST_WIND_GENERATION306,MAX_WIND_OUTPUT4489
Yes, three like that.
I put all 3 as the state of c sensor the problem is how to break them out or set them as attributes of csensor
Anyone can help me to get a between time? I want to only show this icon between 22:00 and 06:00 🙂
[[[
if (states["weather.openweathermap"].state == "sunny" && states["sensor.time"].state < '17:00' ) return '/local/weather/Sunny.svg';
]]]```
Why would you want to do that? They're more useful as independent sensors, since they can be used directly on dashboards. Hiding that information as attributes makes it harder to get to.
#frontend-archived for frontend questions. That's also JavaScript, not a Jinja templte.
I'm trying to bypass login for a google nest nest (IP 192.168.1.2) and limit this to the google nest hub user , would that work, and would other user still be able to login (same subnet and other subnet)
auth_providers:
- type: trusted_networks
trusted_networks:
- 192.168.1.2 -- client IP / no sub
trusted_users:
192.168.1.2: !secret gcastuser
allow_bypass_login: true
- type: homeassistant
Trying this out in dev tools ```
{% set trace = ['motion-off', 'motion-on', 'manual'] %}
{{ 'motion-off' not in trace }}
Is there a contains clause perhaps? Searched for it but had no luck
#integrations-archived for integrations questions.
{{ trace | select('search', 'motion') | list | length == 0 }}```
First, filter so you only have the items from the original list that match the RegEx pattern /motion/, then work out the length of the new list and assert that it's 0.
Fantastic, works nicely! Thanks @ivory delta !
I'm trying to change my lighting based on the state of my apple tv when watching a netflix movie.
For this I want to use media_title. I can distinguish if its a serie or a movie based on the media_title attribute.
Namely series will start with S1: E1 and movies won't.
So in other programming languages I would use a regular expression which goes something like this /^(?!S[1-9]:)/gm. Which matches only if media_title does not start with S1-9:.
My question is. How can I do this with templates in combination with automation. I can choose NOT as a condition but don't know who to use a regular expression there?
- condition: not
conditions:
- condition: state
entity_id: media_player.woonkamer
attribute: media_title
state: 'S([1-9]):'
you don't
there's nothing in the docs that says you can use a regex there
you would need to use a template condition
I was hoping I could do something with templates but not sure how
Ok thank you for confirming atleast I should look any futher in the regular expression support for the condition section
any hint on were to look regarding templates?
something like "{{ not state_attr('media_player.woonkamer', 'media_title') is search('S([1-9]):') }}"
ah... is was looking at an if statement like
{% if regex_search(states.media_player_woonkamer.attributes.media_title, '^S([1-9]):', ignorecase=TRUE) %} {% endif %}
that's not a very useful "if" statement
in any case, you just need a boolean, which my expression produces
I see
yours uses a different command and has more characters and doesn't actually return anything 🙂
true.. its good to know a boolean is needed 🙂
and I can also confirm it works. Awesome!
The main reason to see if i can lighten the load i had maybe 20 of them and HA went to a crawl
That's not going to happen. HA could handle thousands of them 🤷♂️
i just created a template sensor - which is just working out the average of the three values they return. ive restarted HA and as well as the state being the average i expected, it includes median, mean, last value and other stuff and has the calculator average - does HA just automagically treat them as statistics sensors or something because ive performed arithmetic with the sensor values?
statistics sensors
Statistics or long-term statistics? The latter is a concept introduced recently with the energy feature.
i didnt think i had created either
- platform: template
sensors:
house_temperature:
friendly_name: "House Temperature"
value_template: >-
{%- set var = (states('sensor.living_room_temperature') |
float) + (states('sensor.kitchen_thermometer_temperature') | float) +
(states('sensor.upstairs_thermometer_temperature') | float) -%}
{{ (var/3) | round(1) }}
The former is a type of sensor you'd define. The latter is a 'feature' you'd get depending on certain characteristics of a sensor.
What are you trying to achieve?
just a simple average - i dont have a problem i just was surprised that the above sensor provided more than just the single average instead it provided additional attributes
i.e.
count_sensors: 3
max_value: 18
max_entity_id: sensor.kitchen_thermometer_temperature
mean: 17.82
median: 17.75
min_value: 17.7
min_entity_id: sensor.upstairs_thermometer_temperature
last: 17.7
last_entity_id: sensor.upstairs_thermometer_temperature
unit_of_measurement: °C
friendly_name: house_temperature
icon: mdi:calculator
Ok. It sounds like you have what you're after, just with additional detail. The statistics integration does a lot more on top. Long-term statistics enable this fancy stuff in the UI: https://www.home-assistant.io/lovelace/statistics-graph/
What you're seeing is normal based on what you've described. Ignore the attributes you're not interested in.
Hello! I wish to count all active automation, with attributes "current" != 0
I tried {{ expand(states.automation) | selectattr('current', 'ne', '0') | list | count }} but it doesn't seem to work, how would you guys do for that? Thank you for the help!
What doesn't work? What's it doing?
It's like the "current" attribute doesnt exist, because it gives me my number of automations
I am trying to modify a template, so I can check on a value being > 100 as opposed to being exactly 255 for instance.. can I modify this line somehow?
value_template: "{{ is_state('sensor.vision_zg8101_garage_door_detector_alarm_level', '255') }}"
Two changes:
{{ expand(states.automation) | selectattr('attributes.current', 'ne', 0) | list | count }}
(hi all - happy LDW!)
You weren't targeting the right attribute, and you need to compare against a number.
Incredible 
selectattr doesn't only look at attributes of a HA entity. It's a Jinja filter, so you have to be more specific about what to look for - Jinja means something different by attributes.
Thanks teacher! :p
This template stuff is black magic.. 🙂
is_state checks for equality. states returns the current value and you can do other stuff with it:
{{ states('sensor.vision_zg8101_garage_door_detector_alarm_level') > 100 }}
Gah, messed up the formatting 🤦♂️ All good now.
Thanks !! I'll try it - trying to fix garagedoor logic 🙂
Ah thats useful thanks.. is thats whats consider a limited template when its in a cover for instanc?
*instance
so for the icon template I could use it as this? :
icon_template: >-
{% if states('sensor.sensor.aqarav2_angle_x') > 70 %}
mdi:garage-open
{% else %}
mdi:garage
{% endif %}
(aqaraV2 is sensor telling me the angle of the garage door
the |float converts the string to a float to compate with the 70?
yes
Hmm I think I have the value template wrong ? Is this right? Its showing unavailable
@mental path posted a code wall, it is moved here --> https://hastebin.com/uzoduvidov
you don't have what I gave you
you also need it in the value_template
for the same reason
duh, ok how about this - value_template: "{{ if states('sensor.sensor.aqarav2_angle_x')|float > 70 }}"
now you added an unnecessary "if"
ah ok its different in the value template vs below? looks valid now at least, thanks!
makes sense.. top one resolves to a true false, below the true false renders the two icons.. ok i think i have it .. sorta.. thanks again 🙂
its not working though - sensor.aqarav2_angle_x does change from 2 to 72 when the door is opened, but the ui card doesnt change.. shows closed icon still 😦
@mental path posted a code wall, it is moved here --> https://hastebin.com/tikalipuri
Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).
Please take the time now to review all of the rules and references in #rules.
does the state change as expected in
-> States?
for the icon, just use device_class: garage as shown in the docs
ok let me check in states - i was checking in zigbee2mqtt
state for sensor.aqarav2_angle_x changes as expected 2 and 72 for closed and open respectively- history on the cover shows 'closed' all times even after a few up/downs. When i go to settings for the cover i have this message though "This entity ("cover.garage_door_2") does not have a unique ID, therefore its settings cannot be managed from the UI"
yeah restarted every change
thanks - i'll mess around with it. but the template looks good now? i put in device class instead of the conditional icon as well
is there a way to see waht value_template: "{{ states('sensor.sensor.aqarav2_angle_x')|float > 70 }}" evaluates to ? or even just the sensor.sensor.aqarav2_angle_x')|float part?
Yeah, put it into the Dev Tools under Templates.
So {{ states('sensor.sensor.aqarav2_angle_x')|float > 70 }} evaluates to false in dev tools while sensor.aqarav2_angle_x is 72 in states.. thats odd
oh, this is wrong: sensor.sensor.aqarav2_angle_x
you have two "sensor." in there
in both parts
@mental path
Hello, it's me again, I wish to make a list of "home" entities inside of a group like this, can you please help me out?
{% if is_state(state.entity_id, 'home') %}
🔺{{ state.entity_id }}
{%- endfor %}```
The group name is group.needs_multiprise_bureau
I successfully did it with an expand like this, but that's not how I want it to
🔺{{ expand('group.needs_multiprise_bureau') | selectattr('state', 'eq', 'home') | map(attribute='entity_id') | list | join('\n- ') }}
how do you want it?
your first "for" loop doesn't make sense - scripts have a state of on or off, not "home"
Like this kinda:
🔺device_tracker.pc1
🔺device_tracker.pc2
what is that triangle?
Yeah yeah I know for the "script" I just took that loop for the example, and the 🔺 is the an emoji that I use for the lists, instead of -
It's not about the emoji aha, that doesnt matter, I just don't know how to list entities in group ^^
ok, just a weird thing
I have a group named group.needs_multiprise_bureau and I would like to list all entities with state "home" that's all :p