#templates-archived
1 messages · Page 74 of 1
You are right! Fixed and it now seems to be working! Thank you!
Really annoys me that the UI YAML editor won't throw an error if there's an error in your template. Thank goodness I finally thought of the Template developer tool.
?
Oh wait, you say YAML editor.. VSCode should be able to render templates in your YAML if you use the HA extension
Oooh, I didn't realize that was an option. I should look at it.
Spent a few days trying to figure out one of my 3 templates wasn't working. Turns out I'd missed a ) which I couldn't easily see because the line was too long. 😂
Template checker immediately pointed it out to me.
The HA Extension for VSCode will also check your jinja on such things
@vapid olive I converted your message into a file since it's above 15 lines :+1:
you can see (unless you are colorblind, but there are probably themes for that) that the opening curly brackets are yellow, but the closing ones are white, this indicates an issue with paranthesis
Yeah in vscode, but I was just editing via UI YAML, which has fewer colors.
@vapid olive what do you mean with a 4 way switch?
I'm not sure I can easily use the vscode extension as I'm hosting on a Pi.
the problem is most probably in your scripts, which you didn't share
@marble jackal I turn it on (turns on things), then i turn it off (only the icon color changes to gray), then I turn it on again (it turns off things) then I turn it off again (only the icon color changes back to gray).
that must be in your scripts then
wait
you are turing a script off
that probably doesn't do what you think it does
that turns a script off while it's running it's actions
well the script is simple
i'll paste a screenshot of it
well, I can't, don't know why, but here is the yaml version
metadata: {}
data: {}
target:
entity_id:
- switch.tv
- switch.parlantes
- switch.pieza
On purpose, because you were going to post a picture of text 🤷
His point was that script.turn_on causes a script to start running and script.turn_off causes it to stop if it's waiting for something. Yours doesn't wait, so turn_off does nothing at all
Seems like you just always want to run the script...
it makes sense, i'll try adjusting that part, maybe just using toggle instead of turning on/off (?)
No
Please re-read
Your script already toggles the switches. Just turn the script on whenever you want that to happen
There are very few cases where turning off a script or toggling one makes any sense
This is not one of them
not really, i was going to post the GUI version, but yeah
I understand, thanks for your help 🙂
YAML text is the only way to post in a way to get help here
As script is only on when it has a delay in it. Otherwise it's stateless
so you can't toggle it
well, you can, but it has to have a delay
to clarify robs statements, this channel is for #templates-archived which is code. Other channels like #frontend-archived allow images because it's not code
great! now it works as intended, many thanks!
♥️
any way to get 'cloudy' 'sunny' in local language when templating the weather state?
the UI tells me local language. calling the state in a template does not
Try {{ state_translated("weather.example") }}
Templating - state_translated
nice! thx
How can i check if state_attr('sensor.algemeen','entries')[0]['summary'] exists?
If i read it and it does not exist my markup does not parse
I'm working on some assist custom sentences for weather related stuff. Right now I can do things like 'What will the high temperature be tomorrow' and 'Will it rain today'. Those are easy as I know today is item 0 and tomorrow is item 1 in the forecast entity.
The thing I would like to expand to is saying 'Will it rain Thursday'. Is there any easy way to translate what today is (like Sunday 0, Monday 1, Tuesday 2...) and then use that value to get the correct index? If that makes sense. Target day of week minus today day of week equals index sort of thing.
You need to take the current weekday with now().weekday() (Monday = 0)
And then calculate how many days there are between that and the wanted day
Nice one. With a little searching I see Petro posted this clever way to determine what the current day is:
{{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}
I've modified it to use it this way:
{% set day_to_find = 'Friday' %}
{% set position = days.index(day_to_find) if day_to_find in days else None %}
{{ (position - now().weekday())|abs - 1 }}
I THINK this will give me what I need
if you have the forecast, there's no reason to even know the day
choose the first day with rain. If it's today, say today, else say the name.
if you know the day already via voice, you'd want to reverse the map
if you're asking "is it going ot rain thursday"
Yeah, you need to map Thursday to the weekday, but you can already do that in your custom intent
So Thursday will be 3. Then you need to find out how many days that is from now, and take that item out of the forecast
Also note that there are weather integrations that don't include today in the forecast
They do all have the iso format datetime string, so you can also use that
Yeah, that's what I think I'd like to try. I don't know how to do it though.
{% set day = "Thursday" %}
{% set t = today_at() %}
{% set ns = namespace(days=[]) %}
{% for i in range(7) %}
{% set dt = t + timedelta(days=i) %}
{% set ns.days = ns.days + [(dt.strftime('%A'), dt.date()|string)] %}
{% endfor %}
{% set days = dict.from_keys(ns.days) %}
{% set forecast = response['weather.home'].forecast | selectattr('datetime', 'contains', days['Thursday']) | first | default({}) %}
Thanks for this. I'll have to digest it. I'm getting a response undefined but it is probably because my forecast entity is different. Tried changing to
{% set forecast = response['sensor.daily_forecast'].forecast| selectattr('datetime', 'contains', days['Thursday']) | first | default({}) %}
But did not work.
well yeah
you have to use a service call to get the forecast with get_forecasts and assign it to response
oh. I see now. I have a sensor that updates rather than on demand. My provider only has daily forecast so I don't see the need to update on demand via service call.
Hello everyone, I have another question/case: I have a sensor (energy_total) that registers the energy in a cumulative way (increasing number) and I need a daily value realtime value. I am sure there must be a million ways to do it, but I think the easiest would be to: 1. Store the value of the sensor at a fixed time every day (sensor_fixed). 2. Create a new sensor with the value of the difference: energy_daily=energy_total-sensor_fixed.
Does that look like a good idea? how can I store the value of the sensor at a predetermined time?
I see that there's an integration called "utility_meter", but I am not sure if that returns a real-time value, or just calculates a value at the end of the day
--> Solved!! the utility_meter does give dynamic results, it was even easier than I expected, I used the utility meter and just created a new sensor with the daily value of the original one, I have already added it to the automations and seems to work correctly.
You're not updating it on demand, the way you get forecasts in HA now is through the get_forecasts service call. It doesn't actually refresh the data, it gets the current cached forecast information.
Thanks for this. Did not know. I am really having a hard time wrapping my head around this change. I guess I should go look at the post and reread it.
Does anyone know of a way with light groups, to check (easily) if any of its children are having any issues/unavailability. I basically have a fairly good dashboard at this point, showing various groups of lights in each room. From time to time some of my lifx light strips within some groups go offline, but the overall group itself doesn't report it (I guess by design) and looks available.
I was wondering, without writing custom logic to check per entity within the group if they are having issues, if there was some feature/attribute on the group entity itself that can highlight eg 1 / 5 strips are unavailable, 4 / 5 are on, etc.
{{ expand('light.group') | rejectattr('entity_id', 'has_value') | list | count }}
This will give you a count of group members which are not available
really? with entity_id?
Oh wow, thats great, many thanks!
{{ state_attr('group.downstairs_lights', 'entity_id')|reject('has_value')|list|count }}
Yes, has_value works on entity_id's
ok, wouldn't have thought to use it that way
I was going to propose that next, with the additional comment it only works if you don't include subgroups as member of the group
yeah, makes sense
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|length >= 1 else 'None'}}
Looking for some advice. This is how I am determining which microphone device is active for devices that use HA to determine if wake word is said. This works great.
I am now trying to incorporate devices that use onboard wake word (ESP32S3 satellites). These use a different type of detect (binary sensor). I am think of adding another group of just those devices and doing something like:
{%- set sensors_onboard_wakeword = expand(['group.assist_onboard_wakeword'])|selectattr('state', 'eq', 'on')|rejectattr('last_changed', 'eq', None)|list -%}```
I would then want to compare the sensors and sensors_onboard_wakeword variables in a similar way to the second line above. Does that make sense or is there an easier way to get the one entity value returned?
Is it possible to extract the data from the weather forecasts? I have an entity called weather.metno (met.no weather data). When I use states to see the state attributes I don't see any numbers from the forecast. But when I add a forecast card it has all kinds of numbers in it.
{{ states.weather.metno }} gives me this, which does not seem helpful.
<template TemplateState(<state weather.metno=partlycloudy; temperature=58, dew_point=46, temperature_unit=°F, humidity=63, cloud_coverage=39.8, pressure=29.87, pressure_unit=inHg, wind_bearing=56.7, wind_speed=6.03, wind_speed_unit=mph, visibility_unit=mi, precipitation_unit=in, attribution=Weather forecast from met.no, delivered by the Norwegian Meteorological Institute., friendly_name=Forecast Wayne Manor, supported_features=3 @ 2024-04-17T17:43:12.651212-05:00>)>
so does that service.get_forecasts bit go in an automation/script?
Yes, or in the action block of a trigger-based template sensor (as shown in the Examples)
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|length >= 1 else 'None'}}
{%- set sensors_onboard = expand(['group.assist_voice_mics'])|selectattr('state', 'eq', 'on')|rejectattr('last_changed', 'eq', None)|list -%}
{{ sensors_onboard|max(attribute="last_changed")|attr('entity_id') if sensors_onboard|length >= 1 else 'None'}}
Still working on this. So I have this returning both but I want to only return one. There SHOULD only be one of these active at a given time. How do I return sensor if it is not set to none or sensors_onboard if it is not set to none? I think I have what I want but I just can't figure out how to return the value
{% set ent_list = state_attr('group.assist_mics', 'entity_id') + state_attr('group.assist_voice_mics', 'entity_id') %}
{{ (expand(ent_list | select('is_state', ['on','start'])) | rejectattr('last_changed', 'eq', None) | max(attribute='last_changed'))['entity_id'] | default('None', true)-}}
~~Hey, i was using the following template to get the precipitation probability of certain times in a day. Not sure what exactly changed in the updates but for a few days, maybe even a week this does not seem to work anymore:
(state_attr('weather.openweathermap', 'forecast') | selectattr('datetime',
'ge', now().replace(hour=11,minute=0).isoformat()) | selectattr('datetime',
'lt',now().replace(hour=12, minute=0).isoformat())) |
map(attribute='precipitation_probability') | list | max | round(0)}}```
this just gives the error `UndefinedError: No aggregated item, sequence was empty.` if i go under dev tools and check the template, but if i remove the `| max | round(0)` i get an empty list `[]` Guessing the first error is expected when the list is empty, i just don't get why the list is empty 😄
The weather card for this entity works and also shows all the precipitation_probability correctly for the diffrent times. Anybody able to help me with this? i am not to familiar with the templates and getting the last one to work took me ages~~
actually i just saw the issue with a message above, the forecast attribute is deprecated, well gotta figure out how this weatherget forecasts service works then
Edit: got it working as a template sensor that basically works the same as before but uses the weather.get_forecasts service 👍
When creating a template sensor in yaml I can add a delay_on value. Is it possible to do when creating a template entity via the UI?
No
Thanks for this. I didn't realize you could have a list like that. This greatly simplifies things as I can mix both mic 'types' in the same group. Woot!
Trying to make a template sensor of the deviceclass timestamp.
I've checked it in the template examples part in HA and reports back a time.
But the created sensor in HA displays "unkown" , the logs dont show any errors about it....
this is the sensor:
- name: "Tijd warmte lamp uit" device_class: timestamp state: "{{ strptime(states('input_datetime.uv_lamp_uit'), '%H:%M:%S') - timedelta(hours=2) }}"
input_datetime.uv_lamp_uit has the following predefined state: 08:00:00
This is a lot easier:
state: "{{ today_at(states('input_datetime.uv_lamp_uit')) - timedelta(hours=2) }}"
That works pretty nice ! It does seem that the time being shown in the sensor is not the same as doing in the template enviroment of HA
Should | as_local be added?
This is shown in in the template example HA
state: "2024-04-18 18:00:00+02:00"
So it seems that i'm missing those +02:00 hours 😄
and this is the sensor state: 2024-04-18T16:00:00+00:00
It's the same time
One is in UTC, the other is in your local time
But it's exactly the same time
It's the way ISOwhatever works 🙂
afternoon guys... am presuming this is simple.. but am relatively new to HA... I have two ESPHome sensors at home... one in the bedroom.. and one in the living room... I have them tracking the RSSI of my Galaxy Watch4... and they are reporting its distance... how would I go about creating a sensor that reads these two values.. and whichever is lowest.. it can set it to that room... I'll them need to display that on my dashboard.. also.. sensor values for the RSSI look like this "-62 dBm" etc... so I have no idea how I would check if one is lower than the other.. can anyone point me at a template and sensor I could adapt for this? and please remember I am kinda new to this automation stuff... thanks in advance..
am presuming I need a template for this... I add those to configuration.yaml, right?
never done a template before.
In the met.no forecast results, what is precipitation? Is it the chance of precipitation or the total amount expected?
pretty sure it's the amount expected:
precipitation: 0.01
{'condition': 'partlycloudy', 'datetime': '2024-04-18T17:00:00+00:00', 'wind_bearing': 330.0, 'temperature': 56, 'templow': 45, 'wind_speed': 16.53, 'precipitation': 0.0, 'humidity': 33}
the LLM of My washing maschine sometimes want to post none working twitter links on his mastodon acount. How can i filter out any word containing twitter from a string?
regex_replace('\b\Stwitter\S\b', '')
So using this in an automation would trigger it on the right time? Will give it a try thanks !!
It's the expected amount of rain, some integrations also provide precipitation_probability
This is everything I see in a daily forecast
- datetime: "2024-04-19T00:00:00+02:00"
condition: rainy
precipitation_probability: 80
wind_bearing: 308.5
cloud_coverage: 79
temperature: 10.7
apparent_temperature: 8.7
templow: 5.8
pressure: 1009
wind_speed: 30.8
precipitation: 7.6
wind_gust_speed: 56.6
uv_index: 3
dew_point: 7.9
humidity: 86
Oh wait, you had hourly, I have this there
- datetime: "2024-04-19T09:00:00+02:00"
condition: rainy
wind_bearing: 283
precipitation_probability: 92
cloud_coverage: 100
uv_index: 0.1
temperature: 9
apparent_temperature: 5.2
dew_point: 7.8
pressure: 1007.1
wind_speed: 25.9
precipitation: 0.2
humidity: 93
I have a rgb strip connected through dynalite but it creates the rgb channels different not into one rgb light ? Can Somebody please tell me that how can i use template to convert it into a rgb bulb in homeassistant.
is it possible to render a template through the home assistant RESTful API?
what do you mean
Please! tell me if this could be done or not ?
you can combine the 3 lights in one template light
I have tried it but i can't make it as a working rgb bulb. Also new to home assistant so sorry for anything stupid said by me
Mainly curious.. if I could do a ha template from a py or if i have to do a template sensor in ha and grab the state from that entity
You want HA to render a template for you? Is that what youre asking?
Like feed a template to an api and it responsds with a result?
Yeah? Or is that weird? As i said im just curious.. since I can do it from siri shortcuts
not wierd
there's a websocket api and a rest api. You don't need template sfor the websocket api, but the rest api has the ability to render templates
You have to provide more info, yes it can be done. Without knowing what i nformation you have, we can't help.
I was just there, how did I miss it, facepalm.
Thanks
"universal" )| select('search', "chromecast" ) |
select('is_state', 'playing') | list | map(attribute='last_changed') | sort(reverse=True) | first | default(now()) }}```
This gives me the timestamp of the last chroemcast that turned to play. How can I see it's entity id, while keeping the sorting?
| sort(attribute='last_changed', reverse=True) | map('entity_id')
I get TemplateRuntimeError: No filter named 'entity_id'.
map(attribute='entity_id')
That results in "UndefinedError: 'str object' has no attribute 'last_changed'"
Just {{ integration_entities("universal") | select( search', "universal" )| select('search', "chromecast" ) | select('is_state', 'playing') | list | map(attribute='last_changed') | sort(reverse=True) | first | default(now()) }} works
{{ integration_entities("universal") | select('search',
"universal" )| select('search', "chromecast" ) |
select('is_state', 'playing') | expand | sort(attribute='last_changed', reverse=True) | map(attribute='entity_id') | first | default(None) }}
I get null
you're mixing state objects and entity_ids
you can't get an attribute from a non-state object
so I need to use the throttled state.* ?
no, use what I wrote
I have a rgb controller which i have added using philips dynalite integration but it adds it in seperate 3 channels of red green and blue, I want to combine them and create it as a rgb bulb. I can also send you the screenshot, if you'd want
Hi, can someone tell me how I would find todays highest temperature as a state? I want to send that data point to tts and I haven't been able to find it in states.
Temperature of what? Your CPU? Living room thermostat? Body temperature? Weather forecast?
Hi all,
I was trying to finish the work on my garagedoor opener, I started a while ago.
I currently have this template that works:
service: system_log.write
data:
level: error
message: >
{% if python_script_output['authorized'] == True %} "Approved!" {% else %}
"Denied!" {% endif %}
It writes to the system log when the output of a previous python script was True.
I also have a relay that automatically toggles back to "off" when turned on. But... I have no clue how to integrate this relay into the above template.
I tried to follow this text: https://www.home-assistant.io/integrations/switch.template/
But in confuses the heck out of me. The opening text makes it sound like it's what I need, but in the body it's about reading a sensor?
Anyone who could point me in the right direction?
Is there any documentation describing the order in which HA processes things like the values of custom sensors which use templates.
When referencing certain sensors in the developer tools as well as some custom sensors which also reference such sensors, there seems to be a visible lag between when they update.
I'm not sure for example if an automation triggers because sensor x changes, if that automation references inside some custom sensors y (which uses a template that also references the value of x) am I guaranteed sensor y will have its updated value once referenced in said automation or could it update a second later meaning the automation ends up seeing the old / non updated version.
@crude crest I converted your message into a file since it's above 15 lines :+1:
No that is not possible. You can see this in the documentation.
@mighty ledge Help plz
Hello! I haven error in my logs and I'm having trouble finding out where the error comes from:
Logger: homeassistant.helpers.template
Source: helpers/template.py:771
First occurred: April 18, 2024 at 11:47:09 AM (15 occurrences)
Last logged: 12:00:37 PM
Error parsing value: 'value_json' is undefined (value: , template: {"in_progress": {{ iif(value_json['update']['state'] == 'updating', 'true', 'false') }} })
Error parsing value: 'value_json' is undefined (value: , template: {{ value_json['update']['installed_version'] }})
Error parsing value: 'value_json' is undefined (value: , template: {{ value_json['update']['latest_version'] }})
How would I go to find which template is causing the error? I have no clue where that could be. Obviously there's a double-i in the if ...
iif() is a valid function.
search for the template itself. If you can't find it, it's coming from MQTT
Am I doing something wrong here?
{% set some_list = ["a", "b"] %}
{% macro test(some_list_arg, some_bool) -%}
{{ some_list_arg | length > 1 and some_bool }}
{%- endmacro %}
{{ test(some_list, true) or test(some_list, false) }} {# Returns True #}
{{ test(some_list, false) or test(some_list, true) }} {# Returns False #}
Do macros use some sort of weird caching? Why would it suddenly return false in the second statement 🤔
Oh I thought it might have had to do with list filtering but that's not even it
{% macro test(some_bool) -%}
{{ some_bool }}
{%- endmacro %}
{{ test(true) or test(false) }} {# Returns True #}
{{ test(false) or test(true) }} {# Returns False #}
Am I using macros completely wrong here?
Welp
Thanks Petro <3
Is there currently an efficient (1-liner) way to generate a list of entity_ids assigned to a floor that have a specific label applied to them?
Hi everyone, is it possible to have relative_time in right locale ?
@weary elk https://github.com/TheFes/relative-time-plus
{{ floor_areas('first_floor') | map('area_entities') | sum(start=[]) | select('in', label_entities('some_label')) | list }}
@marble jackal Thank you! I has just stumbled across another post you shared which was similar and got it to work. I appreciate the help.
I guess I'll take my line of questioning a little further...I'm trying to create a template sensor that triggers whenever one of the entities matching the filter above changes state, but is not 'unknown' or 'unavailable' (which appears to require the use of 'has_value'.
Basically, I'm trying to dynamically trigger a sensor update from entities with a certain label.
Is such a configuration possible? I'm a little confused by how template triggers work (or don't) with more than one entity.
So you want to trigger on any state change of such an entity. You can create a template sensor which has the most recent last_changed value of those sensors, and trigger on a state change of that template sensor
Template triggers only fire when the value they render goes from false to true. As TheFes commented it is often easier or necessary to use an intermediary sensor so you can access the other trigger types.
Unfortunately, creating intermediate sensors is what I'm trying to work around. The goal of triggering based on something tagged with a label is to avoid having to manually creating helpers for those labeled entities.
Perhaps I am better off triggering on State Changed events end evaluating labels from there.
It 's possible to define global variable for a card, for example to factorize this code ?
https://pastebin.com/dbskuY9V
For exemple, count the number of light at the beginning of the card, and not 2 times in the card :
{{ label_entities('lumieres') | expand | selectattr('entity_id', 'in', area_entities("[[room]]")) | selectattr ( 'state' , 'eq' , 'on' ) | map(attribute='entity_id') | reject('is_hidden_entity') | list | count }}
not in that card
and in which one we can do that ?
where would I do that? But that said, i guess it's coming from z2m then ...
you cna't do anything about it if it's coming from z2m
sure, but I also can't tell if it actuall is coming from z2m. I was just checking my logs trying to resolve a bunch of errors it throws.
can you elaborate what you mean with "search for the template itself"? knot in my brain prevents me from making sense of it.
You should just make a template sensor for that and then reference it wherever you need it
the problem is that it depend of [[room]] variable
where does that come from?
decluttering card
ah, gets even more complicated
you can presumably make a Jinja macro and use that. beyond that, you're already doing a bunch of stuff that I have no experience with
i have a generic card for all my rooms, but i hate the fact that i need to compute the same data 2 or 3 times in the card ...
Only tested for basic use so far...
{% set ts = now() - timedelta(seconds=1) %}
{% set newest = expand(floor_areas('Your Floor') | map('area_entities')
| sum(start=[]) | select('in', label_entities('Your Label') | select('has_value') | list ))
| sort(attribute='last_changed', reverse=1) | map(attribute='last_changed') | first | default(ts, 1) %}
{{ newest > ts }}
I am still rushing with pulling all entities from an area 😦
I tried both:
| sum(start=[]) | select('match', '^light.') | select('is_state','off') |
unique | list }}```
```{{ area_id("binary_sensor.group_kitchen_motion_occupancy") | map('area_entities') | map('area_entities')
| sum(start=[]) | select('match', '^light.') | select('is_state','off') |
unique | list }}```
I am not sure why this is not working. But I am very noob with Jinja2
Derp, I was missing square brackets somehow.
| sum(start=[]) | select('match', '^light.') | select('is_state','off') |
unique | list }}``` works
"isn't working" isn't enough
Sorry, it's outputing nothing.
Why do I need to have square brackets around the area_id() ? Knowing how it works would help me memorize it
because you're using map()
And map needs an array?
it iterates
{{ area_id('Kitchen')|area_entities }}
you were iterating over each character in the area_id
Aaaaah!
Ok thanks. Sorry, I have no formal coding formation. Well, beside a 100hours class during my tech support course
Still learning stuff every day
Ooh…interesting. I’ll play with this. Thank you.
in developer > states, I notice that the state of the entity doesn't match what is shown in the device view.
For example, state of climate.izone_controller_200011148 is fan_only, where on the device page, logbook or climate card, it shows as Fan only
Is this more human friendly name available somehow? I'm using {{states('climate.izone_controller_200011148')}} in a card but would prefer the latter. I'm sure this is described better somewhere I just don't have the right terminology to find it.
well look at that. Once again, there's a feature for it.
I think that could be applied in A LOT of places throughout my dashboards. yeesh.
Anyone any solution for this ?
My man, you have to provide more info. We have no idea what entities you have and what their states are. Secondly, no one is going to write the whole thing for you. Try something , anything, then ask questions when the things you try don’t work.
Sorry, The channels which are lights have brightness attribute, also i have tried it by creating the template from chatgpt but it dosen't work properly. Would it help if i send you the screenshots ?
Post what you've tried here, as text. No screenshots.
Make sure you format it properly.
so it reads as code, not text
Ok, I'll Paste it
@languid sandal I converted your message into a file since it's above 15 lines :+1:
So the brightness of each light is the color rgb value?
where are the rgb values coming from? And how do you adjust the rgb values?
that definitely looks like a Chatgpt thing making up crap, it doesn't appear to actually use anything in yoru system.
I'm trying to get a value, 0, that returns from a json as true but I can't tell what I'm missing, any ideas?
message: >- You have an alert: {{ trigger.json.monitor.name }} is down and {{ trigger.json.heartbeat.status }} {% if ('trigger.json.heartbeat.status') == '0' %} really down {% endif %}
trigger.json.heartbeat.status does come back as 0, when I test it with tts, it says '0'.
message: >-
You have an alert: {{ trigger.json.monitor.name }} is down and {{ trigger.json.heartbeat.status }} {% if
trigger.json.heartbeat.status == '0' %} really down {% endif %}
``` but are you sure that `trigger.json.heartbeat.status` is actually returning `'0'` (zero as a string) as opposed to `0` (zero as a number)?
that, I'm not sure. When I looked at the json from the webhook it was 0 in the field and not zero.
This is the json for the heartbeat:
{ "heartbeat": { "monitorID": 38, "status": 0, "time": "2024-04-22 14:43:41.958", "msg": "connect EHOSTUNREACH 192.168.2.240:443", "important": true, "duration": 0, "timezone": "America/New_York", "timezoneOffset": "-04:00", "localDateTime": "2024-04-22 10:43:41" },
the only other thought is that it returns '0,' and not '0' ...?
nah, it's returning 0
sigh, right
did you make the tweak that i shared above though?
I'll try that now
didn't work, tts said blah is down and 0, but didn't say 'really down'
ya did something wrong still
lol, yes, I did
trigger.json.heartbeat.status == 0
oh whoops yeah, that was the implication that i didn't actually state out loud lol
that and he had 'trigger.json.heartbeat.status' in quotes
so just remove all the quotes?
just use if trigger.json.heartbeat.status == 0
yeah i took that out of my example though
🤷♂️
right, I get theyre' not the same, so what are they?
'0' is a string, 0 is a number. computers interpret those differently
thanks!
sigh, I appreciate the help and the teaching
but there are some occasions where a number might be a string, just not here, right?
yeah, if it's in quotes
which clearly in the json it wasn't
correct
thanks again
thanks!
As in the code that light.fall_red ,green and blue are the different channels of rgb but are imported as different light by the philips dynalite integration. So, i want to use them and make make a rgb bulb and they only have brightness attribute
{{ [area_id('binary_sensor.group_office_motion_occupancy')] | map('area_entities') | sum(start=[]) | select('search', 'speakers') | select('is_state','playing') | unique | list }}
How would I go about adding the integration_entities('universal') filter to this template? I want to limit the pulled entities by only checking for devices in that integration
I tried a few permutations with no luck.
Amongs them : {{ [area_id('binary_sensor.group_office_motion_occupancy')] | map('area_entities') | integration_entities('universal') | sum(start=[]) | select('search', 'speakers') | select('is_state','playing') | unique | list }}
{{ [area_id('binary_sensor.group_office_motion_occupancy')] | map('area_entities') | select('in', integration_entities('universal'))|sum(start=[]) | select('search', 'speakers') | select('is_state','playing') | unique | list }}
that's a roundabout way to do that, though
Roundabout? What is that?
what is your goal with the first part there?
you're giving it a specific entity, only to get the area from it?
just start with area_entities('whatever')
I am user trigger.entity_id in lieux of the hard coded binary sensor
ok, still
{{ area_id('light.dr_light_group')|area_entities }}
making a list and then using map() are extra, unnecessary steps
Thanks for the info, i'm very noob with templates
Is there a way to work with state durations in templates? Like determining if an entity has been in a given state for a certain duration
Searching the docs isn't hitting any keywords I'd expect
Sensor is showing 79 but the template is still showing 'Good'. What am I doing wrong here?
{% if aqi >= 0 <= 50 %}
Good
{% elif aqi >= 51 <= 100 %}
Moderate
{% elif aqi >= 101 <= 150 %}
Poor
{% elif aqi >= 151 <= 200 %}
Very Poor
{% elif aqi >= 201 <= 250 %}
Severe
{% else %}
Very Severe
{% endif %}```
Just do
{% if aqi < 50 %}
Good
{% elif aqi < 100 %}
Moderate
...
What you're doing now isn't the proper way to define a range, but you also don't need to be that specific
ah great! thank you 🙂
would you know why it wouldn't work for this:
https://pastebin.com/8UMCkixX
What isn't working? You don't have an else which would be an issue if it's 300 or higher
the colours aren't changing
I can do {% elif states(config.entity) | int <>300 %} for the other fix
Oh you can't use templates there
It works when it's not in a conditional
Orly
haha yeah weird!
I did it so the colours are on the main entity and not on the conditional instead and it works now so I'll settle for that
sensor.keul_last_update_time shows this: 2024-04-22 21:25:31.474553-06:00
I'm Trying to extract day (and time) from this sensor
{%- set day = (states.sensor.keul_last_update_time).strftime('%w') %}
{%- set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %}
{{- days[ day | int -1 ] }}
I get this Error: 'homeassistant.helpers.template.TemplateState object' has no attribute 'strftime'
It works on another sensor but not this one.
You're calling that on a state object
{{ ("2024-04-22 21:25:31.474553-06:00"|as_datetime).strftime("%A") }} -> Monday
A simple (ish) question if anyone has any ideas.
I have a switch that I am wanting to put either a PIN or a CONFIRMATION in front of. I have looked at using Alarm Panel (Manual) but before I head down that route, I am wanting to know if there are any other tricks out there that I can use?
||{{ ("2024-04-22 21:25:31.474553-06:00"|as_datetime).strftime("%A") }}
Gives Monday as output but this gives a template error
{%- set day = (states.sensor.keul_last_update_time |as_datetime).strftime('%w') %}
{%- set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %}
{{- days[ day | int -1 ] }}
An entity is in its current state since the last time it changed. So now() - states['your.entity'].last_changed will be the duration it has been in that state
@thin pivot You are using as_datetime on the entire state object
You need to use it on the state
Sure there is
{%- set day = (states('sensor.keul_last_update_time') |as_datetime).strftime('%A') %}
That outputs
Result type: string
This template listens for the following state changed events:
Entity: sensor.keul_last_update_tim
Not the day.
I'll post it on the forums.
It listens to state changed events of that sensor and it outputs the day. Isn't that what you wanted to acheive?
Amazing, someone answered right away . This works
{{ (states('sensor.keul_last_update_time')|as_datetime).strftime('%A') }}
That's exactly the same as TheFes posted, but he put it in a variable, so to get the output you had to at:
{{ day }}
For reference see this pinned message #templates-archived message
I've now got exactly the text output i was trying to get but I want to add a line feed after the day/time. I tried /n and /r to no avail
{{ (states('sensor.keul_last_update_time')|as_datetime).strftime('%A %I%M%p')}}
/n {{states('sensor.keul_detailed_description')}}
Is there a trick to escaping chars?
Use {{ '\n' }} for a new line
Hi!
I have an attribute ( sensor.mySensor.myAttribute ) which contains an array.
Now I wanna check, if the average is X, Y or Z.
Don't know, where to start.
Any hint ist appreciated!
Thanks - M.
{{ state_attr('sensor.your_sensor', 'your_attribute') | average in [x, y, z] }}
Something like that?
Thanks, that sounds like it would work well!
service: light.turn_off
target:
entity_id: >-
{{ states.light | map(attribute='entity_id') | reject('eq',
'light.wled_christmas_tree_master','light.wled_christmas_tree','light.wled_christmas_tree_star')
| list }}
this template used to turn off all my lights bar my christmas tree when that is being used. it no longer works. has something changed with templating or ha that won't allow this?
error says Failed to call service light.turn_off. Error rendering service target template: TypeError: eq expected 2 arguments, got 4
{{ states.light | map(attribute='entity_id') | reject('in',
['light.wled_christmas_tree_master','light.wled_christmas_tree','light.wled_christmas_tree_star'])
| list }}
eq expects only one item to search for, while in can iterate over a list with multiple items
ah right
wonder why it used to work and not anymore, thanks @fickle sand !
Failed to call service light.turn_off. Error rendering service target template: TypeError: test_in() takes 2 positional arguments but 4 were given
still getting this unfortunately
actually working now, my bad!
Hahah, you also needed to convert the entities into a list
{% for calendar, events_list in events.items() %}
{% set all_events = all_events + events_list %}
{% endfor %}
why gets all_events reset outside the for loop?
O thanks. that notice helped.
can i use dutch words like vandaag(today) and morgen(tomorrow) in time defined functions? voice my voice assistant to show the agenda of today tomorrow?
Is it possible to query the state_changed event and get the last_changed time but only if it was triggered by a specific id/parent_id/user_id?
yes, you would use a condition based on the context
Yep, I'm trying to get rid of a timer which is started based on a specific id/parent_id/user_id. And change it into a condition, so the condition will be true after 1 hour after a specific a specific id/parent_id/user_id changed the entity for the last time.
I cant get the namespace to work inside a automation service call. works fine in template
You can't use namespace across multiple templates
inside a single service call
would be a shame i can hear my agenda for today in the morning but cant use it with a voice command.
looks fine, so it must be your service call getting the response data
metadata: {}
data:
start_date_time: '{{ now().strftime(''%Y-%m-%d 00:00:00'') }}'
end_date_time: '{{ now().strftime(''%Y-%m-30 23:59:59'') }}'
target:
entity_id:
- calendar.persoonlijk
- calendar.verjaardagen
- calendar.feestdagen_in_nederland
response_variable: data```
OH WAIT
thanks
you need to iterate the data dictionary
today is no agenda. holy macaroni
im listening
wait...
old code..
im making bad mistakes..
turn of coding mode watching a movie or something..
{% for entity_id, evts in data.items() %}
{% for event in evts %}
...
{% endfor %}
{% endfor %}
secondly, you don't need namespace
{{ data.values() | list | sum(start=[]) | sort(attribute='start') ....
not sure what you're doing with that match... if you're trying to get for today... then...
I thank your helping efford petro. but im toast for today.
will bug you again in some days.
it is home assistant needs to be fun.
well anyways
{{ data.values() | list | sum(start=[]) | sort(attribute='start') | rejectattr('start', '>', (today_at() + timedelta(days=1)).isoformat()) | map(attribute='summary') | join(', ') }}
trying to do things the "proper" way and use an input_helper for an upcoming datetime -- is there any way to set it to "off" or null? or must it always contain a date?
my use case: I want a helper that shows the next upcoming game on a schedule if it's in the next two weeks -- otherwise, I want it to have no value
It always has to have a value, but you can set it to midnight 1st of January 1970 or 31st of December 2999
okay, figured -- thanks for the confirmation 🙂
Hi All, Is there any way to work around this error in a template helper - if so how please? The plex player is currently offline due to the TV being off 🙂
2024-04-24 09:40:16.877 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'media_library_title' when rendering '{% if 'Movie' in states['media_player.plex_plex_for_samsung_tv_2020'].attributes.media_library_title %} true {% else %} false {% endif %}'
sure
Good point, I should not just ask if there is a way todo it 😄
{{ states.media_player.plex_plex_for_samsung_tv_2020.attributes.media_library_title is defined and 'Movie' in state_attr('media_player.plex_plex_for_samsung_tv_2020', 'media_library_title') }}
if you're ever return "true" or "false", you should just return the test itself
Thanks! I see - always learning.
anyone have any experience with creating shopping lists with the mealie api? I'm struggling with getting them to sync...using this post for reference
https://community.home-assistant.io/t/mealie-in-ha/603560/27 (ref my.spider.died
Michael post)
how can I check if a sensor value is unavailable or unknown?
nvm , I just figured out how to do at least a one way sync to HA, now to figure out the other way...
has_value as either a function or a filter. See https://www.home-assistant.io/docs/configuration/templating/#states
@sonic pivot I converted your message into a file since it's above 15 lines :+1:
@sonic pivot which integration is this, are you sure that field supports templates?
Anyway, your template can be simplified, expand is not required.
And you should not use a hyphen there, use the template directly as input for the field.
entities: >
{{
states.light
| selectattr('state', 'eq', 'on',)
| rejectattr('entity_id', 'in', area_entities('Master Bedroom'))
| map(attribute='entity_id')
| list
}}
Anyone can help me debug this?
sensor: - platform: rest resource: "https://graph.facebook.com/v19.0/oauth/access_token?grant_type=fb_exchange_token&client_id=XXX&client_secret=XXX&fb_exchange_token={{ states('sensor.facebook_access_token_rest') }}" name: "Facebook Access Token REST" value_template: "{{ value_json.access_token }}" json_attributes: - access_token scan_interval: 00:01
I keep getting this error when I process it
'dict object' has no attribute 'access_token' when rendering '{{ value_json.access_token }}'
I double checked that the resource is correct when initiating and "access_token" is a response in the GET
is there a way I can see what the return of the call is?
This is an example of the call's response:
{ "access_token": "EAAN2AUUqHjEBO6HhiRGGMdrUh137c3jWlJDO0XDJj905AQCqGCi3Ioe3gp9vVd4KUYDhKEljLildk9GFTRZBc86ZCj78nE2bUg4kzHDZBTUSZAXUSluwf5YxPjxwx0jFtqvxEpGuZCfe94Wpf9jIsKoykS4h8SgdP0Fue2UlZBFoRAJ80towdF7vKQDsPsRtivDBTRjhUK4rQyHg85", "token_type": "bearer", "expires_in": 5169136 }
uh, circular reference
you're creating the entitty that the resource is using
chicken-egg
Yeah, the call is probably giving back garbage or an error because the token is old or missing
Yep
That is on purpose as I am trying to refresh the tokens everytime
I give it the initial value and then i want it to keep refreshing it daily
I actually managed to do it with node-red 🙂
and storing it in a sensor 😄
if you want to do that, then you can do that with
https://graph.facebook.com/v19.0/oauth/access_token?grant_type=fb_exchange_token&client_id=XXX&client_secret=XXX&fb_exchange_token={{ states('sensor.facebook_access_token_rest') if states('sensor.facebook_access_token_rest') | has_value else "other token" }}
Fout: Error rendering data template: TypeError: can only concatenate list (not "dict") to list
I'm back feeling better. time to tackle this one
did you use the template exactly? It's a list of events not a dictionary
let me look
{% for entity_id, evts in data.items() %}
{% for event in evts %}
{{event}}
{% endfor %}
{% endfor %}
gives me the events i need to sort. I dont know where the {{data.values() | list enz comes in place
I dont get why my template with namespace is not working in the automation
which service are you using?
list_events or get_events?
your response variable is data
and you aren't using it in any template
nm, I see it
it works in the templating.
data.events should not work
because data is going to return a dictionary of entity_id: event list pairs
oh. then i have errors. in the template test data. A window where you can past yaml data in the template to use would be a nice feature
ok, i see what's wrong
{{ data.values() | map(attribute='events') | sum(start=[]) | sort(attribute='start') | rejectattr('start', '>', (today_at() + timedelta(days=1)).isoformat()) | map(attribute='summary') | join(', ') }}
OKe that gives something.
oke also sorts correctly how do i add the time in HH:mm?
this is the bonus points question
If you need both the summary and the start time, you need a namespace and a for loop
{% for events in data.values() | map(attribute='events') | sum(start=[]) | sort(attribute='start') %}
{{events.summary}}
{% if events.start.split('T')[1] %}
om {{events.start.split('T')[1][:5]}}
{% endif %} {
% endfor %}
I'm not sure why you use the goofy spacing, it makes it harder to read and write
ha made it googfy
{% set ns = namespace(items=[]) %}
{% for event in data.values() | map(attribute='events') | sum(start=[]) | sort(attribute='start') | rejectattr('start', '>', (today_at() + timedelta(days=1)).isoformat()) %}
{% set t = event.start | as_datetime | as_local %}
{% set ns.items = ns.items + [ t.strftime('%H:%M - ') ~ event.summary ] %}
{% endfor %}
{{ ns.items | join(', ') }}
regression.
it works for today only I want it also work for tomorrow. and your solution shows the 00:00 time of all day events
you can add those into the loop, just add timedelta(days=2) instead of 1
and you can skip the events if the time == 00:00
does days=1 works if all data is of tomorrow?
it's a time delta
it's taking midnight today_at() adding 1 day to it
and it's rejecting all events beyond that time
if you want events for tomorrow and today, just change the 1 to a 2
in the end I want a voice command for today tomorrow or a day of the week. So it should ignore it and use all data in the scope of the given data.
{% set ns = namespace(items=[]) %}
{% for event in data.values() | map(attribute='events') | sum(start=[]) | sort(attribute='start') %}
{% set t = event.start | as_datetime | as_local %}
{% if t.strftime('%H:%M') == '00:00' %}
{% set ns.items = ns.items + [ event.summary ] %}
{% else %}
{% set ns.items = ns.items + [ t.strftime('%H:%M - ') ~ event.summary ] %}
{% endif %}
{% endfor %}
{{ ns.items | join(', ') }}
Is there a way i can get the name of a day in dutch with out manual translation?
you can make a list of the days in order starting on monday. Then use thelist[t.weekday()]
Hello, I'm having some troubles creating a template. I want to display it as door in HomeKit and reading the documentation, I understood that I have to create a cover template and set the device_class as door.
The problem is that I also have to use "set_cover_position" but the device I want to trigger is a lock that only has open/closed states.
I created a template that works but when I trigger it in Apple Home, it does get stuck to "unlocking" state. I would like to change it to closed after some seconds, likes the lock actually does. Any hint?
Thanks petro got it worked out.
In an effort to make the installation of my project easier, I'd like to try and create an extension integration at least for use of setting up the custom sensor devices I'm currently using. One big problem with this approach: I don't know much of anything about building these and the docs are really involved.
Does anyone know of an example custom component that illustrates how the sensor configuration can be done without the extra stuff for the control of those devices? I think if I can find just the part I need I can probably modify that enough to accomplish my goal.
what's an 'extension'?
Pardon. Using the wrong term. Meant integration
the development documentation covers creating integraitons
for help, use the #developers or #devs_core-archived channels
I have a webhook trigger which includes some data (let's say an animal). I want to have a dashboard card with the latest animal received through that webhook and another card with all recent animals it sent. What is my best option for that? A text helper?
Thanks, I'll take a look!
Thanks. I may be ahead of my skill level on this one. I have read through these docs. I find it easier to see examples specific to what I'm trying to accomplish. I'll check in devs. Thanks
Pick an integration in CORE that does something similar to what you're trying to do
- name: AssistSat_ViewLR
attributes:
type: view_audio
mic_device: "sensor.firehd_7_stt"
mediaplayer_device: "media_player.tabletfullkiosk"
display_device: "sensor.tabletfullkiosk_browser_path"
browser_id: "Tabletfullkiosk"
I'm really wanting to create something that will allow the user to set these attribute values and have the other attributes (not listed) set up as defaults. This would greatly simplify the need for the users to have to edit YAML. I'm trying to make it easy to add and manage these devices through the UI
I'll take a look at what is provided in core and see if there is something that does similar. Eventually I may try to figure out how to move some of the handling I'm doing from automations to integration but for now the sensor creation via the UI would be ideal for usability.
My template sensor is not getting recognised as an entity (at least that's what I would expect it to become)...
Am I doing something wrong?
template:
- trigger:
- platform: webhook
webhook_id: id
sensor:
- name: "last_animal"
state: "{{trigger.json.animal}}"
Where did you put that?
In a yaml file in my sensor folder
it goes in configuration
Yeah a template sensor though
So slightly confusing in a way
but I must have glanced over this in the docs, thanks 🙂
It's supported by the template integration
And integrations can create any of the base entity domains. Little by little, HA is moving from domain/platform to integration/domain style
How can i show the day wen the sensor last started? The sensor shows "2024-04-25T05:43:53+00:00" as a state and the template below is working but it just shows the short day and not the short day wen the sensor is last started.
state: >
{% set days = ['Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za', 'Zo'] %}
{{ as_timestamp(states.sensor.inverter_opstarttijd.state) | timestamp_custom(days[now().weekday()] ~ ' %I:%M' + 'u') }}
that shows the short day and the time it started
so what exactly is the problem?
you want a long day?
No i want to show the short day the sensor is actualy started.
So now it just show the day (short) of the week. If the sensor was last started tuesday lets say 8am it show Tue 8am on Wednesday 7am because the sensor is not yet started (changed state...) for that day.
state: >
{% set days = ['Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za', 'Zo'] %}
{% set t = states('sensor.inverter_opstarttijd') | as_datetime | as_local %}
{{ days[t.weekday()] ~ t.strftime(' %I:%Mu') }}
Thanks allot Petro!
I have a binary sensor that was made in config (via HACS) and that doesn't have a unique ID. I'd like it to have one, ideally, so I can assign a label to it in the UI. I've had success adding a "unique_id: <UID>" line for a lock template to the yaml, but when I tried doing that with this binary_sensor template, I got an error that said that unique_id is not an expected variable for binary_sensor (or some similar error message). Is there any way to add a UID for a binary sensor (or some other workaround to add labels to it via the UI)?
You can't add unique_id's to entities
you have to create new entities that point to non-unique_id entities using tepmlate entities
and template binary_sensors support unique_id
Thanks for the quick reply! If you have the time and patience, could you explain a little more? I'm having a hard time understanding why I can add a unique_id to this:
`lock:
- platform: template
unique_id:
...but not to this:binary_sensor:- platform: template
sensors:
...`
binary_sensor:
- platform: template
sensors:
example_binary_sensor:
unique_id: xxxxxxxxx
value_template: "{{ now() == now() }}"
Colonel Sandurz: Just now.
Dark Helmet: When will then be now?
Colonel Sandurz: Soon.
Dark Helmet: How soon?
I guess you need a really fast machine for that to return true
It depends on how now now really is
survey says:
that's it. time itself is broken
physics is dead
Einstein warned us about this stuff
It is all relative... until the next release
They are rendered after each other, so there are milliseconds microseconds difference
i would bet on less than milliseconds, but the timestamps are quite high resolution.
Thank you! I'll try that. I see the difference (even if I don't understand why it's necessary!)
Because you are using the legacy format. And in that a template binary sensor is something completely different than a template lock.
Hi, I think I'm in need of a template but if there's a better way to do this without a template, please let me know. I have 3 people in my Home Assistant. When only 1 of them is home (regardless of who it is), I want to trigger an announcement. How can I operationalize the counting of persons who are home and then automate when that number = 1?
the state of zone.home will be the number of person entities in that zone
well how about that? thanks I found it
i want to create switch or button with changeable icon. How to solve it? relay_regulator: name: Relay regulator icon: > {% if is_state('input_boolean.relay_regulator', 'on') %} {%mdi:electric-switch-closed %} {% else %} {%mdi:electric-switch %} {% endif %} but not work and i can not show icon.
Show the full code
Also there should not be {% %} around the mdi icons
It is not a statement
same not work but concept is right?
in input_boolean.yaml relay_regulator: name: Relay regulator icon: > {% if is_state('input_boolean.relay_regulator', 'on') %} mdi:electric-switch-closed {% else %} mdi:electric-switch {% endif %} That is all code.
you can't make up configurations for integrations
input_boolean does not support icons or templates
aanhan!!! How to create switch or button with changeable icon and name?
Create a template switch or template button
@mighty ledge @marsh cairn Thank you guys.
How can I boolean or everything in a list in a filter?
I guess I could just do select('true') and see if the count is > 0. Is there a way to do like a reduce operation though?
if true in []
Thanks that works
I am kinda curious if you can do some kind of reduction operation though
Or for an or operation id just need to find the first. Anyways, that way is probably the easiest to read
{{ expand('group.assist_satellites') |map(attribute='attributes.display_device')|list }}
this returns:
"sensor.tabletmaster_browser_path",
"sensor.thinksmart_lr_browser_path",
"sensor.tabletfullkiosk_browser_path"
]```
I have a group of custom sensors that all have the attribute display_device . Above is a template that lists the sensor stored in that value. Can I somehow use these values as a trigger template? I am looking to see if any of the devices in the returned list has had its state change for the trigger
I am wanting to use this in an automation but thought this might be the more appropriate spot to ask
Hello, any help with template for sensor changing output ?
hey, so i am trying to create an mqtt event that is triggered when an mqtt message is received i tried this but it doesn't seem to be working and i am not sure where the issue is 😅 . https://pastebin.com/vaewAMnh
yes it is a thing 😅 but unfortunately the documentation doesn’t have much information https://www.home-assistant.io/integrations/event.mqtt/
Indeed. You're not following that format
It shows some example YAML and yours doesn't look like that
thank you. i did not have the for loop part. i was mostly taking reference from the templating documentation and didnt really think the loop was important 🤭
rewrote it as this and now works! https://pastebin.com/1QCQZycF
Hey there, i have a template i setup via the Helpers area, but now i cant delete…. https://imgur.com/a/mwgYT7i Any ideas?
Try adding a valid template in there and then submit and then reopen it and see if you can delete it.
Yea does not work, somehow it does not have any entiry ID.
Is there a way to get the "friendly" value of a state in a template? In other words, how it looks on the frontend taking into account it's device class and such? For example, I have a sensor that has duration in hours with a state of 4.5 that I'd like to display as 4:30.
Does state_translated() do it?
Doubtful, all that formatting is handled by JavaScript.
Duration does t work with that stuff but other sensors do. rounded=true as an argument for the states method
I was hoping, but no
I was able to get what I wanted using time_delta(), but yeah didn't find any kind of general purpose method
What is the null operator in lambda?
id(volume_status).publish_state(0); <= would like null where the zero is 0
None
Thank you
Derp. lol I thought it was just poorly formatted 🙂
Hi All. I was wondering if someone can lend a hand and apologies in advance if this was covered earlier.... I have an existing sensor with additional attributes that I would like to create a new sensor of the basis of a calculation. I was able to prove the calculation in developer section of HA, which looks like the following: {{ state_attr('sensor.truenas_datasets_p1','Used')/ state_attr('sensor.truenas_datasets_p1', 'Used' + state_attr('sensor.truenas_datasets_p1', 'Available' )) *100 }}. It seems that this is possible, however, I'm having some challenges in execution, probably due to my inexperience with YAML setup. Ive stubbed out a template.yaml file to do this in and am simply hitting a brick wall. Ive tried countless times and am currently sitting on the following entity setup:- sensor:
p1_percent_free:
friendly_name: "Pool 1 Percent Free"
unit_of_measurement: "percent"
state_class: measurement
state: >-
"{{ state_attr('sensor.truenas_datasets_p1','Used')/ state_attr('sensor.truenas_datasets_p1', 'Used' + state_attr('sensor.truenas_datasets_p1', 'Available' )) *100 }}". Any help would be greatly appreciated!!
You are missing some parentheses. And states and attributes are strings. You have to convert them to integers or float numbers to calculate with them.
And if you are using state: with a >, you don't have to surround the template with quotation marks
state_class is not supported in the legacy format you are using, you need to use the modern format
Thanks so much! All excellent suggestions! 😀
attributes can be anything, so they are not strings by definition.
States are indeed always strings
@sonic pivot I converted your message into a file since it's above 15 lines :+1:
The light group doesn’t support templates for the entities iirc
ah dang it
I have started manually putting in the groups but was really hoping to have it be something I wouldnt have to mess around with once I assigned it to an area. oh well - poor use of a few hours but was fun 😛
Hi there. I have a template binary sensor that was using Android's presence detection, but some combination of the app + my phone is simply not allowing it to work anymore. So I hacked together a script that SSHs to my DD-WRT router and checks its active associations for my phone's MAC address. I need to add a time trigger and an action to it. Here's what the old templates.yaml looks like:
- binary_sensor:
- name: "TiZPhone on Home WiFi"
unique_id: "tizphone_on_home_wifi"
state: >
{{ is_state('sensor.tizphone_wifi_connection', "Plush Town 2G") or
is_state('sensor.tizphone_wifi_connection', "Plush Town 5G") }}
- name: "TiZ is Home"
unique_id: "tiz_is_home"
delay_off: "0:10:00"
state: >
{{ is_state('person.tiz', 'home') or
is_state('binary_sensor.tizphone_on_home_wifi', 'on') }}
I know I need to add this:
trigger:
- platform: time_pattern
minutes: /2
action:
- service: shell_command.phone_on_wifi
data: {}
response_variable: phone_on_wifi
But I'm not sure where I'm supposed to add it. Because various combinations of where I put it break something or other.
@dim lodge I converted your message into a file since it's above 15 lines :+1:
It should work if you put it at the same level as the binary_sensor entry — below or above, order doesn’t matter. Just make sure you are not defining multiple binary_sensors in the same key, since they will all only update on this trigger.
should this work?
data_template:
temperature: >-
{{ state_attr('climate.kjokken', 'temperature') -
states('input_number.temperature_offset_fellesrom') | float }}
target:
area_id: {{ area_id('climate.kjokken') }}```
fields:
duration:
selector:
time: {}
default: "00:00:20"
name: Dauer bis ausschalten
- service: light.turn_off
metadata: {}
data:
transition: {{ dauer }}
target:
entity_id: light.nachttischlampe_licht
How do I insert the fields value in the transistion?
the tempalte for area_id should be quoted. But why not target the entity_id? Do you have multiple climate entities in that area?
also here, your templates should be quoted
and I assume this is a snippet from the actual script, but your field is named duration, but you use dauer in the template
Thanks, I’ll try that. Yes, the idea was to make a reusable automation that alters climate in the area of the sensor (door/window) that triggered the automation 🙂 edit: yes, some areas have multiple
Will try that, thank you
Error: expected float for dictionary value @ data['transition']
what did you use now?
oh wait
transition should be a duration in seconds
you are providing something like `"00:00:20"
yes
that should simply be 20
fields:
duration:
selector:
time: {}
default: "00:00:20"
name: Dauer bis ausschalten
- service: light.turn_off
metadata: {}
data:
transition:
duration: {{ duration }}
target:
entity_id: light.nachttischlampe_licht
Should I use this then?
no
your field should be a number type field
https://www.home-assistant.io/integrations/light/#service-lightturn_on There it is indicated that transition expects the following value:
Number that represents the time (in seconds) the light should take to transition to the new state.
How to convert this?
you should use a number selector instead of a time selector
https://www.home-assistant.io/docs/blueprint/selectors/#number-selector
still expected float for dictionary value @ data['transition']
what do you have now?
if it is a blueprint, or does that also work for scripts?
it works for blueprints for scripts, but not scripts themselves
unless something changed
@inner mesa your hint to template states helped! I have now an own slider for my bulbs to dim them
Now I want to update the slider of the brightness changes from another controller
service: input_number.set_value
metadata: {}
data:
value:
{{ states('light.esstischlicht.brightness') }}
target:
entity_id: input_number.dimmer_moes_esstisch
this does not work. can anybody point me in the right direction?
expected float for dictionary value @ data['value']. Got None
you're missing multiline yaml indicator >
service: input_number.set_value
metadata: {}
data: >
value: {{ states('light.esstischlicht.brightness') | float }}
target: >
entity_id: input_number.dimmer_moes_esstisch
like this? does not work either
service: input_number.set_value
metadata: {}
data:
value: {{ states('light.esstischlicht.brightness') | float }}
target:
entity_id: input_number.dimmer_moes_esstisch
now its in one line
expected float for dictionary value @ data['value']. Got None
you didn't do either of our suggestions...
ok sorry misunderstood you
after the value means like this?
value: > {{ states('light.esstischlicht.brightness') | float }}
the template needs to be on a second line if you use the multiline notation
yes, but your template needs to be indented beyond value
ah thanks this looks better
I still have a problem with the int to float conversion
{{ states('light.esstischlicht.brightness') | float }}
is this incorrect?
Error rendering data template: ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ states('light.esstischlicht.brightness') | float }}' but no default was specified
if you're trying to get the brightness from a entity, you need to use state_attr(), not states()
{{ state_attr('light.esstischlicht', 'brightness') | float }}
you don't need the |float, but yeah
I think it will be a problem when the light is off, though
ah without float it works fine
I don't recall if that was changed to be 0 or None
thanks @inner mesa and @mighty ledge !!!
none, so maybe int(0) makes sense then
I think this maybe better suited here, but How do I shorten last-changed state so it shows as 2hr instead of 2 hours ago?
I want it to apply system wide, not just per card
That's not possible using templates, if it's possible (which I doubt) #frontend-archived might know
it's going from something explicit to something ambiguous
Ah okay, I just posted there got no response, will post again thanks
not possible?
🤷
as TheFes said, it's a #frontend-archived thing
I am not aware of anything like that, and it doesn't seem like somethign they would support
because it's going from something obvious to something ambiguous
Meaning it can only be applied per card, I posted in frontend now
No Rob means that the meaning of 2 hours ago is really clear, but with 2 hrs it's not clear what the meaning is
Ah okay, I guess 2hrs ago would be a better format
@lament salmon I converted your message into a file since it's above 15 lines :+1:
I have a questions:
- {{ is_state(state_attr(rolladen_id, "window"), "on") }}
- {{ is_state_attr(rolladen_id, "window", "on") }}
Why is there a big difference? I saw the python code behind, but it works different here... + Line works as expected, - Line not, but why? I use this as a trigger template for my automation. Have anyone the same behaviour seen?
the first one looks wrong
is_state() takes an entity_id and desired state to compare. Does state_attr(rolladen_id, "window") return an entity_id?
RobC, what do you think im doing wrong?
the second one is assuming that rolladen_id is a variable that refers to an entity_id
😭
yes behind the state_attr(rolladen_id, "window") it is a entitiy_id saved as string (eg. binary_sensor.window_id)
Do i missunderstood this is_state_attr?
Hmm ok thank you @inner mesa for your help 🙂 I thought, that are the same
the first is checking if the state of that entity in the "window" attibute of rolladen_id is 'on', and the second is checking if the value of the window attribute of rolladen_id is "on"
the latter is clearly wrong because you said it should have an entity_id in it
Ah ok, the order is not the same, right?
has nothing to do with the order
There's something you're miss understanding revilo
not sure what
what does state_attr(rolladen_id, "window") return?
eg. binary_sensor.window_state
Ok, so will the text binary_sensor.window_state ever equal the text on?
i'm talking the literal text
does b equal o? does i equal n, does nary_sensor.window_state equal ``?
short answer: No, they are not equal
that's what you're doing when you use {{ is_state_attr(rolladen_id, "window", "on") }}
"Is the result of the attribute window from rolladen_id equal to on"
Hopefully that clears things up
Ahhh now I understand, the status of the string (which is in this case a binary_sensor) is not queried, but only the string is checked 👍
Thank you @mighty ledge for clarification 👍
I'm not sure what this means exactly. Like, "multiple binary sensors in the same key", to be specific.
Also, it ended up not working. The binary sensor which is basically just supposed to be the wifi sensor but waits for ten minutes before turning it off
https://www.toptal.com/developers/hastebin
Could some tell me the value_template format to access the json parameters under channels:
The yaml is for my MQTT: entities. The two shown work perfectly for whole of house production and consumption. I'm now trying to create 3x more entities for consumption on each of my three phases (which to do I need to use the separate channels data). Just don't know hte syntax to use.
omg i just found this: https://jsonpathfinder.com/
Hi all! I’m struggling making a template fan from for RF remote codes. Does anyone know if the template fan requires a helper select, or is it possible to store state information as attributes?
I'm trying to read notifications on my Android phone and trigger an automation. But the text in this notification is not always the same except for eg. 123. So some times it will be ABC123, 123XYZ, 123456.
How do I tell HA to run when it contains '123'?
condition: template
value_template: "{{ '123'
entity_id: sensor.pixel_6a_last_notification
enabled: true
state: ""
I'm stuck here
{{ '123' in states('sensor.pixel_6a_last_notification') }}
Still not getting it
condition: template value_template: "{{ '123' in states('sensor.pixel_6a_last_notification') }}" entity_id: sensor.pixel_6a_last_notification state: true
Is that correct?
no
condition: template
value_template: "{{ '123' in states('sensor.pixel_6a_last_notification') }}"
that's all
okay let me try, sorry I know I have a lot to learn
you are making a mismatch of a template condition and a state condition
Great, it works now!
I see, I think I got confused because I am editing it via the GUI
Hi! I've given up on googling my way to figure this one out.
I'm trying to make a value template that retuns true/false depending on if a sensor has returned true at any point over 24 hours.
So if it has been false for 24+ hours, return false.
If it has at any point been true in the last 24h, return true.
I can't check for if the current false state has a duration of 24h+ because I need to check 4 different sensors that all reset at the same time if any of them go true/false.
history stats sensor. Track the state you desire in number of hours. Then make a template sensor that checks the number of hours being greater thatn 0.
Hi, I have a sensor sensor.double_take_officetable1 that outputs https://i.imgur.com/vXfV3yT.png this data. I want to be able to make a trigger when 'match' == 'true', can someone correct me on how to reference it? I tried state_attr.sensor.double_take_officetable1.matches.match but that didn't work, do I need to reference this a json?
matches is a list
I assumed it was a json, that was wrong
{{ state_attr('sensor.double_take_officetable1', 'matches') | selectattr('name', 'eq', 'mike') | selectattr('match', 'eq', True) | list | count > 0 }}
a list is json
is the whole thing a list within a list?
it's a list of dictionaries
what I posted above will be a template you can use for the template trigger
if you want to look for any matches, remove | selectattr('name', 'eq', 'mike')
selectattr with the pipe acts as filter
but if I wanted to match camera with officetable I wouldnt need to use selectattr?
{{ state_attr('sensor.double_take_officetable1', 'camera') == 'officetable1' }}
no, you still need select attr if it's inside matches
if you're just checking the camera attribute, then you'd just use state_attr
but your parethesis are wrong
and you're missing a quote
smh, thanks petro I get what you're saying, I think. Because it's inside a dictionary I need to use selectattr
you have to use selectattr when you're trying to find information in a list of dictionaries
it's only applicable to your matches attribute
in the example I linked, is box another dictionary within matches?
okay, I get it. Are dictionaries ever nested?
objects can have any shape
you can have lists of dictionaries which has keys that are a list of dictionaries
whatever the author dreamed up
got it, above my paygrade! Thanks for explaining it to me
@soft rock I converted your message into a file since it's above 15 lines :+1:
Could anyone tell me if there is a table with all the template commands?
No table, but the documents cover it
several links in teh channel topic
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
how can i use a template to extract the name (mike) from this example payload? https://imgur.com/vXfV3yT
Are you a bot?
no - the other user and i both ended up here after trying to figure this out together on the double-take discord.
I suggest you post what you're actually trying to do and I can provide a full example
right now, you keep asking pointed questions
explain the whole scenario and I'll provide a template that does it
@soft rock I converted your message into a file since it's above 15 lines :+1:
so, if match = true, i'd like a notification that says '<name of person> is at the mudroom doorbell.'
gotcha
sorry, should have elaborated earlier.
I'd approach this differently then
there's a number of ways to handle this, but I'd probably make a template sensor.
template:
- sensor:
- name: New Double Take
device_class: timestamp
state: >
{% set t = state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') %}
{{ strptime(t, "%B %d, %Y at %-I:%M:%S %p %Z") }}
attributes:
who: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'matches') | selectattr('match', 'eq', True) | map(attribute='name') | list }}
then your automation will be
trigger:
- platform: state
entity_id: sensor.new_double_take
condition:
- condition: template
value_template: "{{ trigger.to_state.attributes.who | count > 0 }}"
action:
- service: notify.mobile_app_galaxy_s24
data:
message: "{{ trigger.to_state.attributes.who | join(', ') }} is at the mudroom doorbell."
sorry, edited again
is this correct? i've never created a template sensor before: https://imgur.com/a/QBOu9ug
No, you have to create this in YAML
where is that option? i'm looking under the helper menus.
there is no option, you add the sensor in your configuration.yaml file
have you edited configuration.yaml before?
yep - just added it and am restarting now.
if the main state of the template is not working, we can adjust it
is it expected that the sensor is showing as unavailable after restarting?
Double-Take Mudroom Doorbell Helper became unavailable
11:57:07 AM - 2 minutes ago
that isn't very helpful.
go to your actual logs, not the UI
TemplateError('ValueError: Template error: strptime got invalid input 'None' when rendering template '{% set t = state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') %} {{ strptime(t, "%B %d, %Y at %-I:%M:%S %p %Z") }}' but no default was specified') while processing template 'Template<template=({% set t = state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') %} {{ strptime(t, "%B %d, %Y at %-I:%M:%S %p %Z") }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.double_take_mudroom_doorbell_helper'
and
Error while processing template: Template<template=({% set t = state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') %} {{ strptime(t, "%B %d, %Y at %-I:%M:%S %p %Z") }}) renders=2>
I don't know - maybe this is more helpful?
homeassistant.exceptions.TemplateError: ValueError: Template error: strptime got invalid input 'None' when rendering template '{% set t = state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') %} {{ strptime(t, "%B %d, %Y at %-I:%M:%S %p %Z") }}' but no default was specified
we need some hold music
template:
- sensor:
- name: New Double Take
device_class: timestamp
state: >
{% set t = state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') %}
{{ strptime(t, "%B %d, %Y at %-I:%M:%S %p %Z") }}
attributes:
who: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'matches') | selectattr('match', 'eq', True) | map(attribute='name') | list }}
availability: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') is not none }}
Now just this one error:
TemplateError('ValueError: Template error: strptime got invalid input '2024-04-30T10:23:46.072-05:00' when rendering template '{% set t = state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') %} {{ strptime(t, "%B %d, %Y at %-I:%M:%S %p %Z") }}' but no default was specified') while processing template 'Template<template=({% set t = state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') %} {{ strptime(t, "%B %d, %Y at %-I:%M:%S %p %Z") }}) renders=2>' for attribute '_attr_native_value' in entity 'sensor.double_take_mudroom_doorbell_helper'
interesting
ok
template:
- sensor:
- name: New Double Take
device_class: timestamp
state: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') }}
attributes:
who: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'matches') | selectattr('match', 'eq', True) | map(attribute='name') | list }}
availability: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') is not none }}
makes the template easier
no errors this time. testing the automation now.
okay, that works! a few questions:
- the name it sounds over (first last) isn't capitalized. is there a way to do that with the template?
- i received multiple notifications for it. is that something i need to work with the double-take team to resolve?
- the payload also contains a filename that can be appended to a url to view the snapshot from the camera. how would i capture and add this to the notification?
- You can
| map('title')in the who attribute after mapping the name before the| list
- If the input sensor is changing alot, we'd have to modify the template.
- Depends on where the snapshot is stored
it is firing several times, but i'm not sure how to work around that.
what does the state look like each time? What data is changing? The state or the who attribute?
it looks like it's running the same thing over and over every 10 seconds with new images passed from my nvr (frigate).
seems like i need to work that behavior out with the double-take or frigate teams.
that's how frigate is designed to behave
You should look into the frigate notification blueprint and see hwo they handle it with actionable notifications
good news - i was able to sort out the duplicate notifications. the only thing left is to figure out how to append the the filename from the same payload to a url to be displayed in the notifications.
going to try adding a new attribute to my template to be called in the notification:
`template:
- sensor:
- name: Double-Take Mudroom Doorbell Helper
device_class: timestamp
state: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') }}
attributes:
who: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'matches') | selectattr('match', 'eq', True) | map(attribute='name') | map('title') | list }}
image: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'matches') | selectattr('match', 'eq', True) | map(attribute='filename') | list }}
availability: >
{{ state_attr('sensor.double_take_mudroom_doorbell', 'timestamp') is not none }}`
- name: Double-Take Mudroom Doorbell Helper
update: it doens't like that.
fixed it - tab error.
will this be sufficient?
service: notify.frigate data: message: >- {{ trigger.to_state.attributes.who | join(', ') }} is at the mudroom doorbell. data: attachment: url: >- https://<url>/api/storage/matches/{{trigger.to_state.attributes.snapshot}}
hi there, how do i make a custom climate entity from a template?
i saw the generic thermostat template, but that is for making an actual virtual thermostat in home assistant
IIRC HA doesn't have a template climate entity. I think there's a custom component that can do it but I don't know how well it works.
huh
I am trying to pull an attribute from a command line sensor json, and it is giving me an error, when I run this in dev tools it pulls the correct info
template:
- sensor:
- name: "Solar Production"
unit_of_measurement: kW
device_class: power
state_class: measurement
state: {{ state_attr('sensor.inergy','Solar_kW') }}
missed comma between flow collection entries. What am I missing?
quotes around the template
always something simple thanks
next time you say "give me an error", please also say what the error is
looks like you still have all your attributes in a single sensor? like I said in #energy-archived that's not the right way to do it
yeah, I'm still trying to figure out how exactly to do that, I'm sure I'm missing a key concept.
I think I'm hung up on the value_template:
I did and now I just get unknown
or state length 1188 max 255 chars
command_line:
- sensor:
name: Inergy
command: "python /config/inergy3.py"
value_template: "{{ value_json }}"
scan_interval: 5
unique_id: "Inergy Solar"
I can't seam to get the value_template to work
what does ienergy3.py do?
can you post the code?
or at least, post what you used to have for the command_line configuration
@pseudo cape I converted your message into a file since it's above 15 lines :+1:
the script connects to my demand controller and pulls the data, which is in a format simular to xml but is not and looks proprietary, It converts it to json and allows HA to pull in the data
ok
So, I think the way you're doing it currently is the best way
command_line isn't set up to run a single command and separate the data into separate sensors
@pseudo cape I converted your message into a file since it's above 15 lines :+1:
So, keep your current config, then make template sensors for each attribute in the command_line sensor
but @fallen kernel says its not the best way to do it
that is the best way to do it for the command_line integraiton
ah ok
Yeah, other integrations like rest, can target 1 endpoint and deliver the information to mulitple sensors.
unfortunately, command_line cannot
Yes, that's what he was doing
no he's using attributes instead of the state
Hey trying to get list card to pull a BBC RSS feed I can't get it pull anything back
type: custom:list-card entity: sensor.topstories title: Top Stories Feed_attribute: entries columns: null
Anyone know what could be wrong
Set up feedreader properly
The post you linked is only possible because the state is less than 254 characters
i.e. he has to use attributes, he has no choice
ah yeah. forgot about that
@pseudo cape I converted your message into a file since it's above 15 lines :+1:
Feed_attribute should probably be feed_attribute, outside that, this is a #frontend-archived question
Ah my bad
Anybody got a Idea, why my auto-entities card wont work with templating the name? I am trying to use templating to set the display name of the entities of my auto-entities card, so I am able to replace some strings. This is my config:
card:
square: false
type: entities
filter:
include:
- domain: switch
area: Wohnzimmer
options:
name: |
{{ state_attr('this.entity_id', 'friendly_name') }}
exclude: null
show_empty: true
The output name of each entity is like the following: {{ state_attr('switch.hmip_ps_00021569971e70', 'friendly_name') }}
So the card fills out the 'this.entity_id' but does not use the template itself
@tidal surge are you sure that supports templates?
I doubt it does
also, this.entity_id shouldn't be in quotes
if it is templateable
secondly, you shouldn't even need to do that
if you're just outputting the friendly name
as discussed in this thread here: https://github.com/thomasloven/lovelace-auto-entities/issues/110#issuecomment-1221438175
There should be no problem with using the template for the display name
Ive tried with and without quotes, makes no difference
yea just for testing, next step would be to attach something like | replace('Switch-Control_', '') to replace part of the name
changing it to {{ state_attr(config.entity, 'friendly_name') | replace('Schaltsteckdose', '') }} does also not work
cant find any logs in settings -> system -> logs, where would i find the template errors?
every time the template renders, you should see an error
open your logs with a text editor
the last entries are almost from an hour ago, and I cannot find anything related to templates in the logs from Homeassistant core
do I have to change some kind of log level, to also show lovelace errors in the logs?
Yea, I mean many other people are using this field with a template, so it should technically work
Only thing I would imagine is that it got removed along the way, but I havent found any info on that
Yes but that's in combination with template-entity-row card
not entities card
So I'm 99% sure you cannot template that
if you want to, you need custom:template-entity-row
Jep your right... I just saw this workaround mentioned in another discussion about the topic and I got mislead by there only beeing the options part of the config, which I tried to add
then onto looking for another solution, thanks for your help! 😄
Just get that card
Takes like 2 seconds to add with HACS
You can do it without that custom card too, but I’d probably have to write the template for you
problem is I would like to use card type grid and not entities
Grid of what
Grid of entities
grid of entity cards?
yea
of custom:mushroom-light-card to be exact
I mean i could just use a horizontal card with two custom auto-entity cards inside
try
type: custom:auto-entities
card:
type: grid
card_param: cards
filter:
template: >
[{% for e in area_entities('Wohnzimmer') | select('match', '^switch.') %}
{{ {'type': 'custom:mushroom-light-card', 'entity': e, 'name': state_attr(e, 'friendly_name') | replace('Schaltsteckdose', '')} }},
{% endfor %}]
show_empty: True
works perfectly!
how does one make a state report 0 if the value goes negative?
state: "{{ state_attr('sensor.inergy','Current_Demand')|float * 1000 }}"
{% if state_attr('sensor.inergy','Current_Demand')|float > 0 %}
{{ state_attr('sensor.inergy','Current_Demand')|float * 1000 }}
{% else %}
0
{% endif %}
Or
{{ [state_attr('sensor.inergy','Current_Demand') | float(0), 0] | max * 1000 }}
Please help me with the coding of it as i want to convert those brightness values into rgb value or into the rgb tuple
I have a script that uses fields to bring in a custom variable and I am trying to reference one of those variables in a {{ state_attr('camera.{{camera_name}}', entity_picture') }}
what is the correct syntax?
{{ state_attr('camera.' ~ camera_name, 'entity_picture') }}
ty, I actually tried ~camera_name~
the ~ acts like a + which you could also use here
like in python
the difference is that it will convert both parts to a string
1 + 1 # 2
1 ~ 1 # 11
`foo` + 1 # error
'foo' ~ 1 # foo1
Is there any way to filter out entities that have a label on them?
I want to make a setup that turns off all lights at night Except the ones labelled as night light. I could just make groups but with many similar exclusions it would get hard to maintain fast
{{ states.light | map(attribute='entity_id') | reject('in', label_entities('night_light')) | list }}
That's probably what you are looking for
ahh reject need to learn this whole template lang a bit more
I deliberately don't use + for concatenate precisely because of what it does to numbers.
Is there any way to make this into an actual group?
that would dynamically be updated? I saw the solution with automation that updates a group at startup but those seam to be a generic groups and not be usable in other service calls or when placing on the dashboard
no, dynamic updates of light groups are not possible
Will they some day?
nope, group.set is something which wouldn't be allowed nowadays anymore
so it exists because it was created when there were less strict rules. But using service calls to change entity config isn't allowed in core
it could be something for Spook
any chance for nonservice based dynamic groups?
how would you change them then?
like give that template instead of the manual list
like on the UI littel button in the corner to switch to YAML editing or similar
You can always file a feature request for it
true 🙂
TBH, if you're dynamically labeling a group of entities, there's really no reason to use the label
just skip it and make a template sensor
wait, you could of course create a template light instead of a helper light group
I read it as that he wants to apply the labels manually, but wants to create a light group out of that
so all lights exept the labeled ones
Yes that would be nice to have
yeah that is the idea
I add a new light and just have to add the labels to define it's behaviour
you can do that with a template light
but if you also want to adjust brightness and color temp and such it will require some templating
Hello
I Hope it makes Not to much Problems
@arctic sorrel Haves help me but I dont know what I make wrong
@coarse dawn To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
{{ states("sensor.wr_rs485_leistung_pv_string_1") | float / (10*440) 100 | float | round(0) }}
Help us help you ☝️
yes i have do it
What template were you originally given? Before you changed it?
this was the original code
name: "Energy-PercentPV1"
state : '{{ states("sensor.pv_garage_big_growatt8k_powerpv1") | float / (16420) 100 | float | round(0) }}'
unit_of_measurement: '%'
(16420) 100 🤔
Either you've missed something, or the person who gave you that never tested it
i think the people have forget the *
Because that template is, as already said, quite broken
I'm getting this into an automation: Error: Template rendered invalid entity IDs: "['light.livingroom_window_light', 'light.livingroom_tv_light', 'light.livingroom_behind_tv_light', 'light.livingroom_center_light', 'light.office_tv_light', 'light.quotra_livingroom_light', 'light.livingroom_wall_light']"
When trying to pass this variable
variables:
on_lights: >
{{ [area_id(trigger.entity_id)] | map('area_entities') | sum(start=[]) |
select('match', '^light.') | select('is_state','on') | unique | list }}
(and broken in more than one way)
Oh, this is the service:
service: light.turn_off
metadata: {}
data:
transition: 60
target:
entity_id: |
"{{ on_lights }}"
I switched the | to > and it reverted after saving
my plan is
i have PV with string 1 4400W and the People sayd make this and you see the effecienty
or get rid of the "|" and put it on the same line
Let me try that
the problem is that it's treating the list as a big string
Why do I sometimes need the quotes and sometimes not within the HA automations?>
What is the rule about that, it would help me understand!
removing the quotes worked btw
you only need quotes if you need to have the YAML parser treat it as a string instead of a malformed dict
basically, { is a special character in yaml, so when it's used in a spot where it could be parsed by yaml you need to quote it
in other words, surround the template in quotes if it's on the same line as the key, and don't if it's not
the > and | in yaml start a multi-line string, so they act similarly to quotes
so putting quotes inside a multi-line string double-quotes it :)
Gotcha
Try
{{ (states("sensor.wr_rs485_leistung_pv_string_1") | float / (10*440) * 100) | float | round(0) }}
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
that second float does nada
What do you mean ?
Converting a float into a float does nothing
Float, floatier, floatiest
Doesn't round do that too? 🤔
Yep
I remembered something 
ah yes but i dont know i have become this code XD
thank you i have no error morning i see
thanks
Yeah... wasn't bothering to fix the rest of that clusterfuck
a template is no longer working good since upgrading HAOS it seems: https://i.imgur.com/J77SUpI.png
and my configuration.yaml contains the following: mqtt: sensor: - name: "Living Room Audio Sensor (9=silence)" state_topic: "frigate/living-room/audio/rms" device_class: sound_pressure state_class: measurement value_template: "{{ ((value | float) | round(2)) }}"
anyone have a idea about this?
dude

🍿
It's so floaty
I'm trying to use a template in the value for a service call, and while I'm not getting any visual errors, I'm not seeing it work as expected. The template I'm using in the dev tools is:
service: climate.set_temperature
target:
entity_id: climate.thermostat_mode
data:
temperature: '{{ ( state_attr("climate.thermostat_mode", "temperature") | float ) - 1 }}'
which works fine when tested in HA UI, but when i use the value for temperature, with or without the surrounding single quotes it just doesn't do anything when used in the widget.
I do see a resulting error in the HA logs however:
voluptuous.error.MultipleInvalid: expected float for dictionary value @ data['temperature']
So it's sending something but not the value I'm expecting... What's the correct way to use data templates in the android wiget?
Try asking in #android-archived Maybe widgets don't support templates. The template syntax looks correct.
Hmm. Seems they do: https://companion.home-assistant.io/docs/integrations/android-widgets#template
But possibly only for display and not service calls?
You can call a script and use the templates in the script
how do i test if a trigger.device_id is null?
depends on your device trigger
look in your automation trace
if yo udon't know where to look, post a trace here.
download the trace and post it in dpaste.org
so what's the problem? you don't know how to check for null?
in jinja it's abc is not none
where abc is whatever you're checking
is null is not accepted
ah ty
i.e. abs is none or abc is not none
how to write an template to list all device trackers in zone.home?
{{ states.device_tracker | selectattr('state', 'eq', 'home') | map(attribute='entity_id') | list }}
Please help me with this
Is there a cleaner way to write this card mod styling? I'm wanting to color the icon and the text which works when I tell it primary-text-color even though I expected that to not color the icon:
- type: entity entity: sensor.house_temp card_mod: style: | :host { --primary-text-color: {% if (states.sensor.house_temp.state | int <= 65) %} cyan {% elif (states.sensor.house_temp.state | int >= 74) %} orange {% else %} var(--primary-color); {% endif %}; }
As a note this works perfectly. I just want to know if it can be cleaner.
how do i convert a date like Fri, May 03 05:34 PM from gmt to amsterdam with daylight savings?
Beginner question - I have a template lock; is there a way to create a "locking" or other intermediary status for it? I see only binary states in the lock spec, but yet my non-template ("native?") locks display an intermediate status in dashboards while they're in the process of locking. I'd be interested in recreating that behavior in the template lock, if possible, and even if it's just a fake delay (when the state is toggled, switch to "locking" for five seconds before displaying the toggled state, if that makes sense).
You’d have to build all that logic in your template. It’s a pain in the butt
I guess I shoudln't have expected it to be anything but(t) ... still, it's good to know that it's at least (theoretically) possible! That way, I can put it in the to-do list (even if I never get around to doing it). Thanks for the quick reply!
The only thing I would probably do with your code is to set the house_temp as a variable at the very beginning even though it is only repeated twice.
Are you trying to avoid repeating the IF statement for the icon and then the text? You could restructure the statement so the IF is on the "outside" and the return variables are in the inside (if that makes sense.) Take a look at this example that I put together: Card modding a button card's icon and icon color. Look at the comparing numbers example.
I have a dropdown helper with each day of the week as an option (Monday, Tuesday, etc): input_select.reminder_day
I have a template helper: sensor.day_of_the_week = {{ ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] }}
in the dev tools page I'm trying to figure out how to compare the two which I thought was this: {{ is_state('sensor.day_of_the_week', 'input_select.reminder_day') }}
but that returns false
if i do hard coded comparrision it returns true ( {{ is_state('sensor.day_of_the_week', 'Friday') }} )
so i assume HA doesnt like the type or something but i'm a little lost what else I can do to make it work
{{ is_state('sensor.day_of_the_week', states('input_select.reminder_day')) }}
oh... it was litterally comparing the text "input_select.reminder_day" wasnt it
Your way was just checking the state of the day of the week sensor against the literal string.
Yup
sigh thank you
No problem 🙂
i figured it would be something simple but was hoping it wouldnt be simple AND dumb 😛
lmao those are the best ones to flub on though!
In HA dashboard this shows as "Away" {{ states('person.esperance') | title }} but when I put it in a template it says Not_home. Is there a way I can make it show what the dashboard is showing instead of the state?
I'm trying to write an automation to send a short command to an RS232 device via a USB/RS232 adapter. The command would have this form:
shell_command:
serial_command: echo -e -n '{{command template}}\x0D' > /dev/ttyUSB1
The issue I'm running into is the command template itself. Each character of the input string should be converted to the ASCII representation of that character. For example, 'Z' would be \x5A. In theory, it seems like the following would work:
{% for char in command_text %}\x{{ '%02X' % ord(char) }}{% endfor %}
However, when I try this template in Developer tools, it reports:
'ord' is undefined
Anyone have thoughts on whether this might be resolvable?
Answer:
{% for char in command_text %}\x{{ '%02X' % (char | ord) }}{% endfor %}
type: entity
entity: sensor.house_temp
card_mod:
style: |
ha-card {
{% set state = states('sensor.house_temp')|int(0) %}
{% if state >= 74 %} --primary-text-color:orange;--paper-item-icon-color: orange;
{% elif state >= 64 %} --primary-text-color: cyan;--paper-item-icon-color: cyan;
{% else %} --primary-text-color: var(--primary-color);--paper-item-icon-color: var(--primary-color);
{%- endif -%};
I'm trying to write an automation to
Any idea why this is not working?
style:
mushroom-state-info$: |
.secondary:before {
visibility: visible;
content: |
{% set status = state_attr(climate.vicare_heating, 'hvac_action') %}
{% if status == 'heating' %}
Hallo;
{% endif %}
}```
are you trying to use "climate.vicare_heating" as an entity_id?
if so, you didn't surround it in quotes
like every other string you have there
Just tested it with quotes surrounded but it still seems not working.
Like this it works fine.
visibility: visible;
content: '{{ states('sensor.room_temperature') | round(1) }} °C - {{ states('sensor.room_humidity') | round(0) }} %'
}```
But i want to return more than one state...
you used the same quotes inside and out
and you have a nested template in there
