#templates-archived
1 messages · Page 83 of 1
so for the calender condition use macro instead?
Based on the original, I would go for something like https://dpaste.org/ich5S...
so I have updated my automation to the automation you made. It runs the automation but nothing happens. as no alexa speaks or text appers but it says finish automation.
Trace logs: https://dpaste.org/Z8DAY
on your conversation agent notification text. When i copy this part over i get an error. The rest of the text is fine
{%- endif -%} {%- endfor %} {%- endif %} {% endmacro %} {% for c in select_cal %} {{ agenda_maker(c) }} {% endfor %} {{ prompt }}
on your conversation agent notification
Hey all. I'm trying to template an attribute into a binary sensor and I'm having a heck of a time. The sensor and its attributes are thus:
`BluetoothDevices:
- Id: Bluetooth#bluetooth-archivede8:48:b8:c8:20:00-00:6a:8e:16:c5:b5
Name: Mpow M5
Kind: AssociationEndpoint
Paired: false
Connected: false
LastSeenUtc: '2024-08-22T01:50:02.6527607Z`
In particular I am trying to look at that Connected attribute. I want my binary sensor to be true when it is true.
So, this is the template I'm attempting to use:
{{ is_state_attr('sensor.meteion_bluetoothdevices','Connected', true) }}
The syntax looks good, but it evaluates to false no matter what I do to it, even when I can see the state of the sensor attribute is true.
....aw crap, I see the problem. Those aren't actually individual attributes. It's just one big long attribute with all the information in it.
{{ state_attr('sensor.meteion_bluetoothdevices', 'BluetoothDevices')[0]['Connected'] }}
... assuming that's the correct entity ID.
Thank you, will give it a try tomorrow
It worked! Thank you!
Hello. I hope this is the right place to ask this. I am trying to use a custom chip template in order to use it in UI-Lovelace-Minimalist dashboard, in order to avoid changing things on the premade chip templates.
I am trying to figure out where to put the my_chip.yaml and make and use it in my dashboard yaml.
Sounds like something for #frontend-archived. This channel is for questions about the jinja templates
oh excuse me and thanks!
@cold geode I converted your message into a file since it's above 15 lines :+1:
Hello, how can i add a second if-statement to my current template? I can't get it to work. This is my current code:
{% if as_timestamp(now()) | round - as_timestamp(states.input_datetime.dachboden_plants_monstera_deliciosa_lastwatered.last_changed) | round > 10 %}
red
{% else %}
green
{% endif %}
I want another if statement which is exactly like the other one, except that the seconds are not 10 but 20. If the second statement is true the color should be orange. The else statement with the green color should stay like that.
you want {% elif xxx %}
you didn't say what you tried and didn't work
Jinja syntax is described here: https://jinja.palletsprojects.com/en/3.1.x/templates/
specifically: https://jinja.palletsprojects.com/en/3.1.x/templates/#if
Okay i got it as the following now:
{% if as_timestamp(now()) | round - as_timestamp(states.input_datetime.dachboden_plants_monstera_deliciosa_lastwatered.last_changed) | round > 10 %}
red
{% elif as_timestamp(now()) | round - as_timestamp(states.input_datetime.dachboden_plants_monstera_deliciosa_lastwatered.last_changed) | round > 30 %}
orange
{% else %}
green
{% endif %}
However only the red and green works, orange is basically just "skipped"
Solved it know just simply had do flip the > symbol around😅 I also simplified it now so it looks like this:
{% set timePassed = as_timestamp(now()) | round - as_timestamp(states.input_datetime.dachboden_plants_monstera_deliciosa_lastwatered.last_changed) | round %}
{% if timePassed < 10 %}
green
{% elif timePassed < 20 %}
orange
{% elif timePassed < 30 %}
yellow
{% endif %}
yes, anything that's > 10 is also > 30 🙂
Yeah i didnt think of that because i used a template of the ha forum where the time was calculated and just focused on changing the entities to mine. Been trying all different things the whole day just for it to be that simple😂
Could someone have a look at my template sensor please?
With every reboot of home assistant it goes to zero untill the source_sensor is available again during startup.
Template sensorcode on pastie.org
Now, I know I need to implement availability and value_template, allthough I am wondering what the best way is to do this:
Doing this inside this sensor, or checking for states like (unavailable|unknown) on the source sensor? What would be the most robust and prefered way todo this? Kind of lost in the documentation...
Remove the if and put that check in the availability template
question, i created a couple of rest sensors and they were working fine for a while but lately they all say unavailable.
here is one i created
`rest:
- resource: https://api.quotable.io/random
method: GET
headers:
User-Agent: Home Assistant
Accept: application/json
scan_interval: 86400 # Fetches a new quote every 24 hours
sensor:- name: "Quote of the Day"
unique_id: quote_of_the_day
value_template: "{{ value_json.content }}"
json_attributes:- author
- tags`
- name: "Quote of the Day"
At least with some DNS servers... that host is having resolution issues
Hi. Trying create an announcement every time a window or door is opened. Can I use a template to trigger when a door or window class is opened (need it to be generic as I have a lot :-)) and then make an announcement sayng that door x or window x has been opened. Can it be done this way?
I'd say maybe an automation with event trigger on any state changed event. You can have conditions that filter for specific entity domains.
@lofty mason I think I was looking at this the wrong way and your have just put me on the right path. How would the announce message look? Would that need to be a template?
I guess you would use something like action tts.speak https://www.home-assistant.io/integrations/tts/. But the exact implementation may vary with your speaker type. I don't use TTS so can't comment too much about it. Yes it will probably be a template.
The trigger variable with have information about what entity_id has triggered, so you could make a template with that information.
@lofty mason I think it's tome for me to have a dig around, thank for your help
Could also use a group for your contact sensors and then use a template to figure out which door or window opened. BUT, I’ll tell you from experience it gets very annoying, very quickly to TTS announce every door and/window opening or closing. Especially when you are playing music or watching TV. 😉
Hi,
I want to create a multi modal sensor to track different states like 'awake', 'sleep', 'go to bed' and others. The value of this sensor could be changed and requested by automations to change the behavior of them for different states.
Can anybody point me to resources where I find advice on this topic or an example solution?
you seem to be describing this: https://www.home-assistant.io/integrations/input_select/
or https://www.home-assistant.io/integrations/template/#select, depending on what you want
This looks promising. Thank you for the resource.
Hi all! I wanted to have a sensor that’ll estimate the time to a complete (dis)charge. I couldn’t find any examples on the internet so I decided to make my own and publish it here!
Hi, for my zigbee shade controllers: https://www.sunricher.com/zigbee-curtain-motor-controller-sr-zg9080a.html#product_tabs_resources
I'd like to make work this template: https://community.home-assistant.io/t/configurable-cover-entities-to-invert-close-open/409595/17 or any other workaround to have the frontend
- up/down arrows available when my shades are completely down/up
- open/closed status corresponding to my shades being not completely down/being completely down
I've read many threads concerning this issue, but have not seen a simple step by step guide how to proceed. I have little experience editing configuration.yaml - I'm using Studio Code Server. I'm aware of fundamental sources of info such as: https://www.home-assistant.io/docs/configuration/yaml/ and https://www.home-assistant.io/docs/configuration/templating/ or https://www.home-assistant.io/integrations/cover.template/ but I am not sure how to employ them.
Is this thread appropriate to discuss this topic? Can you please indicate what could be my best next steps?
Is the configuration.yaml the only place where I should try to build my code? Or are there more places such as the template editor (developer-tools/template)?
Somewhere I read that I would need to create a new entity (an inverted "copy"?) of each of my shades - please can you confirm and eventually point to appropriate info on how to create new entity?
What have you tried with all that documentation, yet?
Thanks for asking:
I have copied the template code into my configuration.yaml and tried to adjust it to my environment (e.g. replace original "cover.raamverduistering_stookhok" by one of my shade entity id my "cover.sunricher_hk_zcc_a_16e193fe_window_covering"). A few moments that troubled me at these very initial steps:
- after pasting the copied code to my configuration.yaml I got "bad indentation of a mapping entry" and "missed comma between flow collection entries" warnings which make me hesitate whether the original code is well formatted. I suppose it is, bu no clue why then I got warnings of this kind after simple copy paste
- among the initial lines I read "raamverduistering_stookhok_inverted" - refering to the "_inverted" part of the string this is maybe the new entity (the inverted copy) that I am maybe supposed to have created first? If so, how do I create it?
- also I am confused whether "raamverduistering_stookhok_inverted" is any kind of friendly name of what otherwise would appear (in my environment appears) with the full entity ID - in my case e.g. "cover.sunricher_hk_zcc_a_16e193fe_window_covering" and if so whether I just replace this string by my full entity ID or whether I have to do another step to comply with this part of the code
How can i filter emoji's way from a string of text?
That error says, that the indentation of the example has to be adapted to your configuration.yaml
I don't know what your inverted entities are. Those are the template ones supposed to be.
"raamverduistering_stookhok_inverted" seems to be part of an entity ID. A friendly name can be anything you want
Thanks, I have removed one space in lines where the number of spaces was odd. Seems to be a step forward, since I get no more warnings.
Hum. Do I understand right, that by placing this code into my configuration.yaml I am creating an entity? I share my configuration.yaml with the above referenced code pasted and modified by me including the entity ID of one of my shades:
http://pastie.org/p/4mdOSAMk9tUqdr5IuBvYnW
After Restart Home Assistant, I got:
Invalid config for 'cover' from integration 'template' at configuration.yaml, line 30: expected dictionary for dictionary value 'covers', got None, please check the docs at https://www.home-assistant.io/integrations/template
Invalid config for 'cover' from integration 'template' at configuration.yaml, line 31: 'shade_bedroom_inverted' is an invalid option for 'template.cover', check: shade_bedroom_inverted, please check the docs at https://www.home-assistant.io/integrations/template
Any clue how to move forward please?
Is there any use for me of the template editor I see under developer-tools/template? Can you please explain me what is good for compared to trying to code within the configuration.yaml via Studio Code Server?
It's a way to test templates in realtime without adding them to your HA config
The indentation of shade_room_inverted is off
Thanks, indenting all including and below helped, I have moved forward - I have the inverted entity that I can see and control.
Thank you very much Jorg for your help!
Flatten filter not available - WTF? :)
trying to make a template to get the amount of lights on with a certain label
just specifically light domain, and only with a label
{{ label_entities(‘label name’) | select(‘is_state’, ‘on’) | list }}
I didn’t test it, but it should be close.
Hi I set up a TTS automation for last notifications but keep getting "null" messages from the messenger app
I would like to set up a condition template that when it sees "null" to ignore the message but I can only get it to ignore all but ones with "null". This is what I have
{{ 'null' in state_attr('sensor.pixel_7_last_notification', 'android.title') }}
@lapis nimbus you are checking for the string "null" but most probably it is actually none (so nothing, nada, the absence of a value)
which is what state_attr() returns when the attribute doesn't exist
so use
{{ state_attr('sensor.pixel_7_last_notification', 'android.title') is none }}
I'm confused at the new way of handling weather forecast data. Rather than storing individual metrics in sensor.x entities, I would like to build a weather entity that contains the forecast for the next hour. I think a weather template is the most elegant.
In the root of my configuration.yaml, I've added:
weather:
- platform: template
name: "Next hour weather"
temperature_template: "{{ ???? }}"
humidity_template: "{{ ???? }}"
Now, I thought I could insert {{ hourly['weather.home'].forecast[0].temperature }} in those templates, but I guess that misses the input from weather.get_forecasts.
Searching the web yields examples of weather.get_forecast and warnings that this is very different from the _forecasts action. So I've not been able to find an example of how I can built a weather entity. Does anyone perhaps have a pointer for me?
(What I'm trying to achieve is ONLY the next 1 hour forecast, while standard frontend shows the next 5 hours. And the only way to achieve this seems to be building a new entity.)
This would be my solution (with that caching technique, I talked about). This creates a sensor with all forecast data (can later be used for different template sensors, if needed) and a weather entity for the next hour (at least with the met.no response), which can be used with a weather card. Unfortunately precipitation cannot be used with the template weather.
Had to correct a typo:
https://dpaste.org/mKQsD
Aaahhh, now I understand what you meant by storing the forecasts in the attributes!
Thank you for taking the time to upload that for my understanding. Much appreciated.
It might not be the best solution and needs to be adjusted to your weather provider - but it works fine for me
Why is precipitation not possible in the template weather entity? Any idea?
It is no available template option for template weather
Seems an odd oversight.
It just seems to be in forecasts
Weather forecasts in general and precipitation warnings specifically are notoriously unreliable where I am. But it would still be nice to have!
I use the Apple WeatherKit integration, in an attempt to get back my beloved DarkSky! 🙂
You can use the dev tools to use that action call and look what your weather provider reports. You can add more attribute templates to your weather entity, if you can extract it.
Apple WeatherKit provides precipitation forecasts. To work around the shortcoming of the template weather entity (no precipitation attribute), I could just store that value in a different template sensor to sensor.precipitation_forecast_next_hour or something? Does that make sense?
Wait ... that's weird. the Template Weather Provider helper has a precipitation_unit, but not a precipitation_template attribute? Thats particularly wild 🙂
That's how I store the precipitation.
The unit is used for the precipitation in the forecast (which can be added theoretically with another template)
Maybe you could add it that way, but I guess the forecast template would have to be formatted in a specific way.
Meh, temporary workaround of creating two dedicated precipitation_forecast_next_[hour,day] templates is fine for me. It all seems so odd, that I can't imagine it hasn't already been raised as an issue.
I didn't have the time and motivation yet, to tinker that value in the weather entity
I mean ... I could also hijack an existing attribute to store the precipitation? I have no purpose for ozone_template ... i could just store the value in there, I guess. But that feels a bit too hacky.
It also strikes me as odd that the 'unit of measurement' is stored in an attribute. Dont we have unit_of_measurement settings for that?
Not every weather provider uses the same UoM
I guess a uom applies to a state, not an attribute?
Well... if you look at the temperature attribute template. How should HA know if the value 48 is meant to be in F or C?
Right. That's my point. HA allows setting a uom for a state only, not for an attribute. So if you're storing values in an attribute, you must find a different way of storing the uom. It makes sense.
Oh ... forecast data for the daily is different than for the hourly. Sigh.
k .... going to pick this up another day
Thanks again for your help!
No it doesn't. For weather entities you can set the UoM for various things
Yes, but not with the usual unit_of_measurement in yaml.
And I think that’s because in general, uom can be set only for a state and not for an attribute. I think.
But I know nothing, so could be talking out of my ass!
not for a normal template sensor indeed, but you were creating a template weather if I'm not mistaken
But doesn't the yaml config define the UoM of the source, so that the frontend UoM can be converted?
Yeah, I guess you need to provide a UoM in the YAML config for the template weather so HA knows which UoM it should use as the basis
I have a display showing time left of washer. But it showed something weird suddenly. It showed 2024-08-26 13:11:46+00:00 and the template is {{ time_until(states('sensor.vaskemaskin_washer_completion_time')| as_datetime, 2) | replace('hours', 'timer') | replace('hour', 'time') | replace ('minutes', 'minutter') | replace ('minute', 'minutt') | replace ('seconds', 'sekunder') | replace ('second', 'sekund') }} How is that possible? How can it show a date when I use time_until()?
Or wait... if the time has passed?
if you put a date in the past into time_until it just returns the input date
Ah, thanks. 🙂
hi
I'm desperate.
I try to convert the time: '2024-08-27T02:00:00+02:00' to local time.
I want to show 2024-08-27T04:00:00
timestamp_local still shows with +02:00
I'm a bit puzzled, what is your local timezone, is it +2?
hmm i am now realizing the time after the + dont has to be added -.- it is only an indicator which timezone am in right?
yeah I think T02:00:00+02:00 means "2am in the +2 timezone"
it's already in your local time
i am so stupid...
timezones are hard 🤯
i thought i have to add this value to know what time is it
Any way to make a dynamic entity list that shows name state and an attribute based on entity id?
Example... Peplink_aefed2122376 "online" 192.168.1.56
Should this be available in the action of a trigger-based template? I am trying to refer to the attributes of the entity there:
- variables:
last_dt: "{{as_datetime(this.attributes.get('previous_datetime',now()))}}"```
and the log complains
```Template variable error: 'this' is undefined when rendering '{{as_datetime(this.attributes.get('previous_datetime',now()))}}'```
no
so how should i refer to its own attributes?
i mean I want to do some logic in the variables part before writing things into the state/attributes
ok thanks. I see the issue...
I was similarly confused earlier
is there a way to display a list of entities that contain the word "peplink" in their entity_id along with their status?
By "display" do you mean on the dashboard?
Yep, that's what I was going to recommend
it keeps freezing my gui, unfortunately.
Are you using a template for the filter or one of the other methods?
i'm about to use template, the include is making HA think too hard
Are you running HA on a repurposed toaster? I don't have any issues with auto-entities, an I'm not using really fancy hardware
Is it possible to create a template sensor where the frontend will display a 'human readable' number?
I've just created a bunch of utility_meter entities for tx/rx bytes reported by my router. Totally useless, but oh well. And I'm now thinking ... is there a way to have this shown as MB → GB → TB as things grow each month?
Maybe a template sensor where you divide by 1000s
Yeah, I know I can convert it using a template sensor. But I'd like it to display in a human-readable format which means the unit changes. I guess more of a #frontend-archived thing.
Add the unit of measurement to the state, any statistics will be useless anyway if the uom keeps changing
Hey,
I just finished this simple template {{as_timestamp(states('Sensor that outputs time')) | timestamp_custom('%H:%M')}}, but it outputs time as a string and I need as a datetime object. Any way to do that?
{{ states('sensor.expires') | as_datetime }}
and
as_datetime(value, default) converts a string containing a timestamp, or valid UNIX timestamp, to a datetime object. If that fails, it returns the default value or, if omitted, raises an error. When the input is already a datetime object it will be returned as is. in case the input is a datetime.date object, midnight will be added as time. This function can also be used as a filter.
I do have to include the custom timestamp for removing the date
Wait
Is it still possible to convert it back or am I undoing my own work?
so you only want time?
Ok
Might be a dumb question, but are there any cons of migrating legacy template files (yaml) to the Template Helper?
you lose all the advanced functionality
no attributes, no availability for example
like availability templates, attribute templates, icon templates, etc
Ah okay, will these be gradually be implemented in future updates, or simply not possible?
So theres this sensor, lets call it sensor.example, which outputs a dynamic time and date (like this: 2024-08-27T10:45:00+00:00). I only want the timestamp, not the date, so I tried with the template as a custom sensor but said sensor just outputs a string not a datetime object.
a sensor state will always be a string
probably not
Don't set the device_class on the helper entity, set it to None.
maybe some form of availablity where the template sensor will be unavailable when any of the source sensors is
i.e. use your original template, and don't change "Show As"
Alrighty, thank you both
but if I set the sensor to a timestamp it outputs unknown, is it because a timestamp always needs a date or smth?
yes
it's because you're using show as
oh, that explains it
Don't use show as, leave it None or empty
now the sensor shows up as unavailable, but the log and the preview in the config show it "outputting" (?) the wanted string
are you looking at the correct entity?
if you restarted, check your log for errors
you likely need a default as @full crescent said
but for as_timestamp
{{as_timestamp(states('sensor.xxx'), default=0) | timestamp_custom('%H:%M')}}
are you 100% sure you're looking at the correct entity?
you can use imgur to share images
yeah that does not confirm that it's the correct entity
How do I confirm it then?
by looking at the entity_id, not the name
where exactly?
it's correct
there's an entity_id field
is that what is used on your frontend?
wherever that last pic was taken
when I click on it just says "This entity is unavailable
And the id is in fact correct
OMG IM DYING INSIDE WTFFF
also, you didn't supply the default as stated above
How can I make it to return the value if the state below 70 and above 40 ?
{% if is_number(state) and state | float > 70 %}
{{ states('sensor.mi_scale_mass') }}
{% endif %}```
{% set state = states('sensor.mi_scale_mass') %}
{% if is_number(state) and 40 < state | float < 70 %}
{{ state }}
{% endif %}
Thank you a lot
@tropic breach I converted your message into a file since it's above 15 lines :+1:
want to get the energy cost for some of my Smart plugs. I made this sensor but it does not show up
- platform: template sensors: energy_cost: friendly_name: "Energy Cost" unit_of_measurement: "USD" value_template: > {% set energy_usage = states('sensor.washing_machine_plug_current_consumption_2') | float %} {% set cost_per_kwh = 0.13 %} # Average cost per kWh in the US {{ (energy_usage * cost_per_kwh) | round(2) }}
You can't use in-line comments
@tropic breach just add a value_template
yeah, this I know but I am looking for the right code 😄
did you create that yourself or copy/paste?
myself
just add `"value_template" to the dictionary
if you want the dictionaries value to retain a string that contains jinja, use {% raw %} and {% endraw %}
something like value_template: {{ value / 1000 }}
But I dont understand how to get the actual value
value_json will be an object you can use in jinja
value is just a string, so you'd have to convert it to a number if you want to perform math
ah so it would be value_json.value / 1000
except for this bit:
value is just a string, so you'd have to convert it to a number if you want to perform math
so...
{{ value_json.value|float(0) / 1000 }}, assuming there's a key by that name
something like value|float does not work?
under the mqtt topic there is a simple int. no key/value or json
I have no idea where "value" came from. I just jumped into amplify petro's comment
OK, I found out what my problem is. I am constructing a mqtt discovery payload that lets HA add a certain sensor. HA interprets what I want to simply write to the mqtt publish:
Can I escape the whole value of this key: value pair
"value_template": "{{ value_json }}",
from being interpreted?
Cough
you should get that looked at
haha I was thinking too complicated...
"value_template": "{% raw %} {{ value|int / 1000 }} {% endraw %}" does it 😄
sorry for my ignorance
may i ask what is an "in-line commentS"
{% set cost_per_kwh = 0.13 %} # Average cost per kWh in the US
comments on the same line as code
Hi! I'm writing a script to use the current value of helpers to run certain plex playlists on certain media players. I'm struggling to figure out how to get what I want with templating.
I have two templating challenges:
- I want a template in my script which will use the input_select.which_playlist value to return a different, but one to one string to go into the media id. like a dictionary lookup but in a template.
- I want to use a set of 4 binary inputs to populate the list of device ids.
so,
device id:
- xxxxxxxxx if input.east_mini
- xxxxxxxxx if input.west_mini
etc```
but I'm not sure if I just need a template if for each line, or the best way to do that.
I think I have a good handle on 1. from https://documentation.bloomreach.com/engagement/docs/datastructures
but I'm unsure of the best approach for 2.
i fixed it
{% set energy_usage = states('sensor.washing_machine_plug_current_consumption_2') | float %} {% set cost_per_kwh = 0.13 %} {{ (energy_usage * cost_per_kwh) | round(2) }}
Hello, I'm trying to get a light template working with brightness increase/decrease. It's an RF light that I control by a Broadlink. I've learnt the commands and can use scripts to control it but want to get into a template / light entity to make it nicer.
The commands on the remote are a single toggle button for on/off and then a brightness increase, and a brightness decrease buttons. There are 6 brightness steps between lowest and highest brightness.
I've got a very basic template and can use it turn on and off but I'm still relying on buttons that just call scripts for brightness control. Is what I want possible? I've searched but can't find anything simple for me to follow. The template example on the home assistant site doesn't make sense to me at my level and I've got the added complexity of using the Broadlink I guess.
This is my very basic light template that I'm trying to add brightness control too.
lights:
office_fan_light:
unique_id: template.office_fan_light
friendly_name: "Office fan light"
turn_on:
service: script.office_fan_light
turn_off:
service: script.office_fan_light```
that script just sends the toggle command to the broadlink.
Can someone tell me if there's an easy way to test if a variable exists? I'm testing and getting an undefined. The variable I'm testing for may or may not exist depending on the automation flow.
x is defined
I just discovered the weather template 👌. From what I understand we are restricted to the configuration variables listed on the page? We can't make our own to add?
Please can you help with an error I got after I had done (maybe too much and too fast) modifications in my config?
After HA restart, all seems ok, nothing in logs. But when I then manually reload ZHA (I do it because I suspect it to come and want to get rid of it), I get an error in logs:
Logger: homeassistant.components.template.template_entity
Source: components/template/template_entity.py:197
integration: Template (documentation, issues)
First occurred: 09:06:06 (1 occurrences)
Last logged: 09:06:06
TemplateError('ValueError: Template error: int got invalid input 'None' when rendering template '{{100 - (state_attr('cover.shade_bedroom_non_inverted','current_position')|int)}}' but no default was specified') while processing template 'Template<template=({{100 - (state_attr('cover.shade_bedroom_non_inverted','current_position')|int)}}) renders=6>' for attribute '_position' in entity 'cover.shade_bedroom_inverted'
My configuration.yaml, package_covers.yaml and groups.yaml
The (only) cover I made the template for is working as expected. I have cleared my browser cache before the last restart.
|int cannot process strings like "unavailable" or "none" and will throw an error.
You mitigate that by either defining a default value (e.g. |int(100)) or creating an availability template, which makes that entity unavailable before that problem happens.
in this case I would advice to add an availability_template to your template cover. I also highly doubt this template cover will work in all cases. I also invert some covers, but I would except the cover.close_cover action under open_cover and vice versa
Hi im trying to manipulate some sensor data and make two new sensors, but im bit stuck on how to approach something like that. I made some example code in C.
float HW_total_prev=0;
float import=0;
float export=0;
HW_total=HW_import-HW_export;
if (HW_total-HW_total_prev>0)
then
import+=HW_total-HW_total_prev;
else
export+=HW_total-HW_total_prev;
end
HW_total_prev=HW_total;
Does anyone have some tips to get started, do i need to maken local variables to save the previous value.
Hey all,
I have a larger discussion on #automations-archived (https://discordapp.com/channels/330944238910963714/672220450977349653/1278649358153285642) but I have a specific question around template formatting for JSON. Does anyone know how to receive JSON from a webhook and send it to MQTT without the format changing? I'm using {{ trigger.json }} as the payload field in the automation for mqtt.publish. Any ideas if this is correct? The data appears in the broker, but with single quotes instead of double quotes, etc. and the template entities that hang off MQTT don't update.
in this case I would advice to add an
Thanks for your advice (as well as to TheFes), it seems to be working, I helped myself for formatting also with this post.
now i know why i wanted to calculate it. I have a apex chart where i put the data in. but it shows it as the 2 hours shifted...
i have to use time_delta: +2h ...
but now is the Now not at the correct time -.-
Hopefully this is the right place to ask this: is there a timeout on shell commands? I have an SSH command that works fine but there will be times where it could run for 20-30 minutes and I don't know if that will cause a problem.
Ok, then I'll have to have it run as a cron on the destination, thanks for the info!
Well it's a template that runs a shell command, so I assume that makes no difference in the 60s
like a template switch?
Exactly like that
no, it makes no difference. you're asking about a shell_command
I assumed as much, looking at the nohup, I've not tried that before
it detaches the process from the shell and attaches it to init, so it won't exit when the shell exits
Ah, so it kind of threads it in the background then and exits when done?
in a way, yes
ending with &, yes
Ah, ok, so ditch the trailing 1 but the rest is good
Ahhh, thank you for clarifying
nohup it and put in the background
I'll try that out, thanks again 🙂
@inner mesa works perfectly, thank you for the assist!
So I have this:
{% set modifier = "hours" %}
{{strptime(today_at().date() ~ ' ' ~ "3:00 PM", '%Y-%m-%d %I:%M %p')+ timedelta(hours=5)}}
2024-08-29 20:00:00
but this:
{% set modifier = "hours" %}
{{strptime(today_at().date() ~ ' ' ~ "3:00 PM", '%Y-%m-%d %I:%M %p')+ timedelta(modifer=5)}}
TypeError: 'modifer' is an invalid keyword argument for __new__()
How can replace the hours word with the variable contents?
AFAIK, you can't use a variable for a keyword. What is the actual goal?
User can say things like:
Remind me to wash the dog in 5 hours
Remind me to eat lunch in 20 minutes
I want to pull both the time int and the time type and use it to adjust the date time based on that without having to do a bunch of conditional statements
so timedelta(hours=5) would be timedelta(time_type=time_int) sort of thing
that would be the good life
What about using seconds as the keyword and turning time_type into a multiplier?
{% set d = {"hours": 3600, "minutes": 60, "seconds": 1}%}
{{ timedelta(seconds=time_int * d[time_type]) }}
I think that will work too! Great thinking and thanks! I'll give this a go
I have this script which turns two of my scripts into a switch however in the goal of reducing my total script load I've brought all the commands for this TV into a single script using selector fields. Is there a way to reference that in a switch template or do I need to keep the on and off scripts seperate from an overall script for the tv
bedroom_television:
unique_id: bedroom_tv_switch
friendly_name: "Bedroom Television"
value_template: "{{ 'false' if is_state('media_player.firestick_tv', 'off') else 'true' }}"
turn_on:
service: homeassistant.turn_on
target:
entity_id: script.lg_television_power_on
turn_off:
service: homeassistant.turn_on
target:
entity_id: script.lg_television_power_off
doesn't that just pass a variable into the script?
yeah it would pass it into the script and then the choose action would select it and run the appropriate command to the tv
@naive swan I converted your message into a file since it's above 15 lines :+1:
you need a space after the :, but yes, if that's what the variable is called in the script
ordinarily you would use script.turn_on as the docs say
or use the other form in the docs
sweet I'll give it a whirl. If i can get this i can bring my scripts down from like 240 to about 30 at most
Works a treat, thanks Rob
why are you using homeassistant.turn_on and not script.turn_on?
And your value template can just be "{{ not is_state('media_player.firestick_tv', 'off') }}"
Shrug, I can't remember what i was thinking when I set it up but it worked, I've never been the best at templates so I just tend to say job done once one is doing what i want it to do
if it works, it works 🙂
i realize the irony of saying that when I've turned 153 scripts into 5 in the last 2 hours thanks to fields 😂
@compact pond I converted your message into a file since it's above 15 lines :+1:
Copy - pasted to the correct channel, sorry!
your templates don't make sense
and your indentation is messed up
and there is no elif
there is a lot wrong here
Meh, i hoped that i started to learn yaml a bit. Guess still not
there is also no need for templates at all, you could use numeric state conditoins
But how can i use 1 numeric state to do 2 completely different actions? Like when temperature < 18 set to heat, and > 22 set it to cool?
action:
- choose:
- conditions:
- condition: numeric_state
entity_id: climate.zolder_airco_2
attribute: current_temperature
below: 18
sequence:
- service: climate.set_hvac_mode
data:
hvac_mode: cool
target:
entity_id: climate.zolder_airco_2
- conditions:
- condition: numeric_state
entity_id: climate.zolder_airco_2
attribute: current_temperature
above: 22
sequence:
- service: climate.set_hvac_mode
data:
hvac_mode: cool
target:
entity_id: climate.zolder_airco_2
I used what you had (which is 2 times the same action)
@willow wing I converted your message into a file since it's above 15 lines :+1:
This looks neat
you should also remove that condition on automation level
as you are checking if it's above 22 there, so it will never be below 18 in the action part
Hh yea true, good point!
@compact pond I converted your message into a file since it's above 15 lines :+1:
should work, indentation is not 100% but valid
Superb, many thanks!
have you got any advice to me how to learn YAML and Jinja2? At this moment i try to do it via youtube but i guess there are better ways
I've learned by doing 🙂
@willow wing you are only checking for currently active events, so not events which were earlier that day, of more than 10 minutes in the future
Ah okay, then i guess i will continue what im doing xD
but it is a full day event, so it must be ok or?
In case it's only full day events, that should not be a problem then
but why not check on the full day then?
was a code snipped from the forum, im no tempalte pro 😁 ,when i use now it use only the curretny date+time right, but the end needs to be 23:59:59
@willow wing I converted your message into a file since it's above 15 lines :+1:
that won't work as you don't use the service call there
you need the trigger and the service call
yeah only a snipped from that 🙂
but your approve with the snipped, and think that could solve my problem?
no, what you have doesn't work
where did those lambda's come from
Is some AI hallucinating this?
yes
well, it's utter 💩
state: >
{% set google = termine['calendar.email_googlemail_com'].events
| map(attribute='summary')
| select('search', 'Urlaub|Krank|HomeOffice', true)
| list | count %}
{% set feiertage = termine['calendar.feiertage'].events | count %}
{{ google + feiertage > 0 }}
attributes:
event_string: >
{%- set ns = namespace(list=[]) %}
{%- for event in termine['calendar.email_googlemail_com'].events %}
{%- for test in ['Urlaub', 'Krank', 'HomeOffice'] %}
{%- if event.summary is search(test, true) %}
{%- set ns.list = ns.list + [test] %}
{%- endif %}
{%- endfor %}
{%- endfor %}
{%- if termine['calendar.feiertage'].events | count > 0 %}
{%- set ns.list = ns.list + ['Feiertag'] %}
{%- endif %}
{% set result = ns.list | unique | join(' ') %}
{{ result if result else 'None' }}
thank you i try this 👍🏻
Having an issue when trying to do this:
variables:
time_values: '{"hours": 60, "minutes": 1}'
time_int: '{{ (trigger.slots.when).split('' '')[0] }}'
time_type: '{{ (trigger.slots.when).split('' '')[1] }}'
time_set: '{{ time_int * time_values[time_type] }}'
Getting this error:
Error: UndefinedError: 'homeassistant.util.yaml.objects.NodeStrClass object' has no attribute 'minutes'
Am I not defining the dictionary correctly?
Try:
time_values:
hours: 60
minutes: 1
That was it. Much nicer formatting too. Thanks
@willow wing I converted your message into a file since it's above 15 lines :+1:
i wanna have all events from my calender in a sensor
termine['calendar.test_googlemail_com'].events
instead of "termine.events"?
Yes
ah okay thank you 👍🏻
{% set snooze_time = 1 %}
{% set start_time = (now() + timedelta(minutes=snooze_time)).strftime('%Y-%m-%d %H:%M:%S') %}
{% set end_time = (start_time + timedelta(minutes=1)).strftime('%Y-%m-%d %H:%M:%S') %}
{{ start_time }}
{{ end_time }}
I'm wanting to create end_time as one minute after start_time. I am getting error with the above that reads:
TypeError: can only concatenate str (not "datetime.timedelta") to str
I'm guessing I need to make start_time not a string in the end_time declaration?
start_time is returning what I expect so the error must be with end_time definition
you're turning start_time into a string and then trying to add it to a timedelta
don't do that 🙂
{% set start_time = now() + timedelta(minutes=snooze_time) %}
Yep. Makes sense. So a related question, Do I need to have my time formatted a certain way to use it to set the calendar or can I use it in the format this returns?
2024-08-30 16:43:00.473730-05:00
2024-08-30 16:44:00
First is start_time not as a string and second is end_time as string. Both are valid for setting a calendar event?
<looks up calendar documentation...>
sorry brother 🙂 Moving that direction
okay. I think I can manage with what you've given me. Thanks
action: calendar.create_event
target:
entity_id: calendar.device_automation_schedules
data:
summary: "Example"
start_date_time: "{{ now() }}"
end_date_time: "{{ now() + timedelta(minutes=1) }}"
{% set snooze_time = 1 %}
{% set snooze_begin = now() + timedelta(minutes=snooze_time) %}
{% set start_time = snooze_begin.strftime('%Y-%m-%d %H:%M:%S') %}
{% set end_time = (snooze_begin + timedelta(minutes=1)).strftime('%Y-%m-%d %H:%M:%S') %}
{{ start_time }}
{{ end_time }}
Not the prettiest but neither am I
variables:
snooze_time: 10
snooze_begin: '{{ now() + timedelta(minutes=snooze_time) }}'
start_time: '{{ snooze_begin.strftime(''%Y-%m-%d %H:%M:%S'') }}'
Just when I thought I was understanding, I am getting this when trying to do the same as what I shared above in jinja in the automation. Getting:
Error: UndefinedError: 'str object' has no attribute 'strftime'
The snooze_begin is showing up in 2024-08-30 16:43:00.473730-05:00 format. am I doing the start_time to string incorrectly?
I don't see how you're getting that error with that code
{% set snooze_time = 5 %}
{% set snooze_begin = now() + timedelta(minutes=snooze_time) %}
{% set start_time = snooze_begin.strftime('%Y-%m-%d %H:%M:%S') %}
{{ start_time }}
-> 2024-08-30 15:09:07
Right. What I have posted is working fine in dev tools -> template but not in my automation.
tried swapping the ' and " around to make sure that wasn't it and it isn't.
trying to figure out what type my snooze_begin variable is but does not seem that pipe to type works.
For the record, this is how I am trying to translate from jinja above to the automation variable block:
variables:
snooze_time: 1
snooze_begin: "{{ now() + timedelta(minutes=snooze_time) }}"
start_date_time: "{{ snooze_begin.strftime('%Y-%m-%d %H:%M:%S') }}"
end_date_time: "{{ (snooze_begin + timedelta(minutes=1)).strftime('%Y-%m-%d %H:%M:%S') }}"
test_time:
sequence:
- variables:
snooze_time: 10
snooze_begin: '{{ now() + timedelta(minutes=snooze_time) }}'
start_time: '{{ (snooze_begin|as_datetime).strftime(''%Y-%m-%d %H:%M:%S'') }}'
- service: persistent_notification.create
data:
message: "{{ start_time }}"
it doesn't assign a datetime to snooze_begin, so you need to convert it
variables:
snooze_time: 10
snooze_begin: "{{ now() + timedelta(minutes=snooze_time) }}"
start_date_time: "{{ (snooze_begin|as_datetime).strftime('%Y-%m-%d %H:%M:%S') }}"
end_date_time: >-
{{ (snooze_begin|as_datetime + timedelta(minutes=1)).strftime('%Y-%m-%d
%H:%M:%S') }}
Thanks so much. Got this working now. I'm learning a lot about all this!
Hey is there a way to put one or two space before this command?
{{ states(entity) }}
{{" "}} does not work
{{ “ “ ~ states(“entity”) }}
nope does not work 🙂
Where are you trying to do this?
i have a badge with a lable and wanna have the state in the middle
Ah. In a template badge?
jup from muschroom
Hmmmm… Not sure how to do that. ljust/rjust also don’t seem to do it there either.
okay no problem is only a nice to have 🙂
Maybe ask in #frontend-archived as that’s something that might be able to be done with some CSS missing perhaps.
The template parser will trim strings
Yup. That’s what I found out. TIL. lol
thats bad, you have maybe an idea for that?
Try {{ " " ~ states(entity) }}`
this made 1 space but not multiple :), i think i try card_mod to middle it
I used this before the space https://www.editpad.org/tool/invisible-character
Put that before every space
Question: in template what does these delimiters mean? {%- -%}
{% %} are the statement delimiters, which are used for control structures i.e. all those things that control the flow of a program - conditionals (i.e. if/elif/else), for-loops, as well as things like macros and blocks. The - add whitespace control.
OK ... got it ... thanks
So used to trim leading and/or trailing white space off whatever text the statement returns
With {% macro ... } it looks like you can dynamically create statement blocks based on current states and execute them with (% call ..., true?
I don't think I've ever actually had a need to use a call statement for anything in HA, but yes they are available.
What is the correct way to make a template sensor that derives a value from another sensor become unknown/unavailable if the sensor it derives the value from is unknown/unavailable?
{% set sensor_value = states('sensor.meter2mqtt_garage_w_total') %}
{% if sensor_value in ['unknown', 'unavailable'] %}
{{ sensor_value }}
{% else %}
{{ sensor_value | float * -1 }}
{% endif %}
This only results in "Sensor None has device class 'power', state class 'measurement' unit 'W' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'unknown' (<class 'str'>)"
{% if sensor_value in ['unknown', 'unavailable'] %}
{{ none }}
{% else %}
This results in "Unknown", which is an improvement
college_teams:
lsu football:
team_id: LSU
conference_id: '8'
league_path: college-football
sport_path: football
How do I set something like this in dev tools -> template so I can troubleshoot?
I am trying to see if 'lsu football' is in college_teams using this:
{{ (trigger.slots.team)|lower in college_teams }}
do I need to write it as json?
Yes json. something like this:
{% set college_teams = {
"lsu football": {
"team_id": "LSU",
"conference_id": "8",
"league_path": "college-football",
"sport_path": "football"
}
} %}
{{ "lsu football" in college_teams }}
Got it. Thanks!
The best way is to define an availability, but that is only available when configured in YAML, not as a Helper.
@oak kiln in case you are creating a template helper, you can let it return none
{{ states('sensor.meter2mqtt_garage_w_total') | add(1, default=none) }}
In case it returns none the state of the sensor will be unknown
Okay so a new wrinkle. My service call requires the conference_id to be quoted otherwise it throws and error. When the dictionary gets set in the automation this just shows up as a number with no quotes. How can I return this value quoted so that I can pass it to the service call?
A template results which looks like an integer is parsed to an integer, if you need a string, use the string filter
conference_id: "{{ college_teams[(trigger.slots.team)|lower]['conference_id'] }}"
I'm setting the variable like this
so just pipe to string?
That won't help, the template parser will convert it to a string again
What's the full service call?
Probably easiest to show you this way. It will jump to the section. condition check, then variable set, then service call
You need to template the entire date section
I am trying to run the service from dev tools and when it is not quoted it gives 'an unknown error occured'
data: >
{{
{
"sport_path": sport_path,
"team_id": query_team |lower,
"league_path": league_path,
"conference_path": conference_id | string
}
}}
ahhh! Okay. I'll give that a go. Thank you!
That's what I needed. Thanks for teaching me a better way!
I have a motorized curtain system that I send byte commands to for position. Is there a way to make a cover template and define a command for each position? For example open 20% -> command1 open 21% -> command2 and so on?
Probably best to create a script that can do it, then call that script (and pass along the position variable) from the set_cover_position block. Also the “multiple covers” YAML example further down the page shows exactly how to call a script and pass the variable.
Thanks thats the approach I was going to try
I need this to return true/false and just can't figure it out. {{ states(trigger.event.data.entity_id) == timer.timer_office }}
{{ trigger.event.data.entity_id == ‘timer.timer_office’ }}
Forgot to remove the states call.
can't believe that I tried every way except for the obvious. Thanks
lol no worries. 😊
Hello, there is a code in templates that does not work. I don’t know how to fix this code. I would appreciate it if you could help. The non-working part is between 1700 - 1800 watts
@agile jungle I converted your message into a file since it's above 15 lines :+1:
The code is in the message above
This part will always return 'on'
{{ 'on' if states('input_boolean.ami_charging') != 'on' else states('input_boolean.ami_charging') }}
Please can you direct my effort to make a template be applied to each of my seven covers?
I have a template to invert the cover control applied to one of my covers, after adjustments with your kind help it does what I expect it to do. Now I would like to apply the exactly same template to all of my seven covers. Later I'd like to add some more enhancements such as icon color based on state.
Is it realistic to have my template and the future enhancement(s) applied to a cover group defined by group ? Or do I have to repeat the code block for each of them in my files?
My configuration.yaml, package_covers.yamll and groups.yaml.
guys, i'm trying to create a template to store lat/long attribute values from a device tracker, which updates only when the car stops.
cannot figure out the syntax, driving me nuts
entity is called device_tracker.id4_position
attributes are latitude and longitude
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.
can anyone pls help?
share what you've tried
@inner mesa in configuration.yaml:
template:
sensors:
id4_latitude:
value_template: '{{ states.device_tracker.id4_position.attributes.latitude }}'
id4_longitude:
value_template: '{{ states.device_tracker.id4_position.attributes.longitude }}'
got it from the web somewhere
did that
and you came up with that?
tried also with sensor:
i cant see straight anymore lol
tried also the "STATE BASED BINARY SENSOR - DEVICE TRACKER SENSOR WITH LATITUDE AND LONGITUDE ATTRIBUTES" example syntax
but mine is not binary sensor
basically i see the location of the tracker entity "history" on a map card if i use "hours to show",
i want to reproduce this in grafana somehow
so i need to get the data to influx first
but i heard influx doesn't import attributes, only states....so suggestion was to create this freakin template
I replied to you in #analytics-archived
@tulip ibex I converted your message into a file since it's above 15 lines :+1:
as you thought, this won't work:
| selectattr('state', 'lt', '20')
there isn't a way to do that in one line because there isn't a way to cast-and-compare in a filter
So is it a numeric only problem? Because I'm able to implement something similar with boolean entities:
- platform: template
sensors:
update_watchdog:
value_template: >
{{ states.update | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') | map('regex_replace', ' update| firmware', '') | join(', ') }}
friendly_name: 'Update watchdog'
yes, it's because states are strings and you're trying to compare with a numeric value
you need a for loop
one day maybe we'll have a solution to this type of problem, a general solution has been elusive
A for loop doing what? ascii to number conversion for each char?
no, iterating through each entity and check if the numeric value of the state is less than your threshold
this is a super-typical issue. I'm sure there are posts here and forum threads on how to do this
if you just want to display them, you can use this: https://community.home-assistant.io/t/low-battery-entity-list/421417>
This one works and is similar to what I'm trying to achieve, but I'm having some trouble modifying the condition:
- platform: template
sensors:
low_battery_watchdog:
value_template: >
{% set ns = namespace(below=[]) %}
{% for s in states.sensor
if 'battery' in s.entity_id and 'power' not in s.entity_id and 'state' not in s.entity_id and s.state != 'unknown' and s.state|int < 20 %}
{% set ns.below = ns.below + [s.entity_id] %}
{% endfor %}
{{ ns.below | reject('in', [] ) | join(', ') }}
friendly_name: 'Low Battery Watchdog'
Why doesn't it like 'in'?
Not really sure, because this works:
if s.entity_id.endswith('battery_level') and 'power' not in s.entity_id and s.state != 'unknown' and s.state|int < 20 %}
But this doesn't(?)
if 'power' not in s.entity_id and s.state != 'unknown' and s.state|int < 20 %}
what's not working about it?
It return unavailable instead of the list
and is there errors in your logs?
None that I spotted scrolling through them
well that would be the only way it's unavailable
That or you're looking at the wrong entity_id after you reloaded
You don't have a unique_id, so reloads will likely create new entities
And plug it into
-> Templates to test
I completely forgot about that, lmao.
It just wanted a default declared for the casting.
Thanks!
I am getting the error below for my template sensor and not sure what i am doing wrong.
`# Average Enphase Solar Output - 30 Days
- trigger:
- platform: state
entity_id: sensor.envoy_202318115695_energy_production_today
to:- '0.0'
- '0'
not_from: - unknown
- unavailable
sensor:
- name: "Average Daily Solar Production (Enphase) - Monthly"
unique_id: e82dab6d-c52d-4a25-b912-126195d9d133
state: "OK"
attributes:
history: >
{% set current = this.attributes.get('history', []) %}
{% set new = [trigger.from_state.state|float(0)] %}
{{ (new + current)[:30] }}
- platform: state
- sensor:
- name: "Average Daily Solar Production (Enphase) - 30 days"
unique_id: 2989a565-9419-48de-970a-81147ccea7a2
state: "{{ average(state_attr('sensor.average_daily_solar_production_enphase_monthly', 'history')) }}"
state_class: measurement`
- name: "Average Daily Solar Production (Enphase) - 30 days"
The error message references an enphase_monthly sensor which you have not posted here.
sorry same error for all of them, they are all duplicates, fixed
the error is much longer, one sec
error is now gone
only suspect thing I see is accessing attributes when it may not exist.
2024-09-03 11:00:42.176 ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template<template=({{ average(state_attr('sensor.average_daily_solar_production_enphase_monthly', 'history')) }}) renders=2> Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 603, in async_render render_result = _render_with_context(self.template, compiled, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2638, in _render_with_context return template.render(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/jinja2/environment.py", line 1304, in render self.environment.handle_exception() File "/usr/local/lib/python3.12/site-packages/jinja2/environment.py", line 939, in handle_exception raise rewrite_traceback_stack(source=source) File "<template>", line 1, in top-level template code File "/usr/local/lib/python3.12/site-packages/jinja2/sandbox.py", line 394, in call return __context.call(__obj, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
` File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 2172, in average
raise TypeError(f"'{type(args[0]).name}' object is not iterable")
TypeError: 'NoneType' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 715, in async_render_to_info
render_info._result = self.async_render( # noqa: SLF001
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 605, in async_render
raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: TypeError: 'NoneType' object is not iterable
2024-09-03 11:00:42.180 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('TypeError: 'NoneType' object is not iterable') while processing template 'Template<template=({{ average(state_attr('sensor.average_daily_solar_production_enphase_monthly', 'history')) }}) renders=4>' for attribute '_attr_native_value' in entity 'sensor.average_daily_solar_production_enphase_30_days'`
ah
{{ average(state_attr('sensor.average_daily_solar_production_enphase_monthly', 'history') or []) }}
or add an availability template
availability: "{{ state_attr('sensor.average_daily_solar_production_enphase_monthly', 'history') is not none }}"
Any feedback please? Is it too simple? Or too complicated?
Thank you, seems like that cleaned it up. If i have a template sensor that is totaling a bunch of data, but sometimes the sensor is unavailable vs an INT, how do you write that, so i can reduce log errors?
Ex.
- sensor: - name: "Total Monthly Solar Production" unique_id: '8de9e5f5-32f2-49b9-b90d-428bbbd63102' unit_of_measurement: "MWh" state: > {{ ((float(states.sensor.solar_array_sunpower_monthly.state) + (float(states.sensor.solar_array_enphase_monthly.state) * 1000 )) / 1000) | round(3) }}
how would i use delay_off when my template sensor was created in the ui?
can't. remake it in yaml
okay, thanks!
I have an automation that I don't want to run unless there are unlocked doors or lights left on. The automation worked when it was only monitoring for locks not locked fully configured via the GUI (OR (NOT (LOCK1 LOCKED), NOT (LOCK2 LOCKED), ETC), but I switched to a template that returns a positive value in developer tools instead and now the automation is failing. I'm trying to troubleshoot it myself, but I'd like to sanity check the condition. Should the following code return true from the conditional section of an automation if any door is not locked or any light is not off, or do I maybe have some sort of formatting error?
condition: or
conditions:
- condition: template
value_template: "{{ states.lock|selectattr('state','ne','locked')|list|length }}"
alias: Doors not locked
- condition: template
value_template: "{{ states.light|selectattr('state','ne','off')|list|length }}"
alias: Lights not off
alias: Doors Not Locked or Lights Not Off
Alternatively, am I incorrect that "truthy" things work for conditions?
I think you need an actual test and Boolean result and not just a truthy value, but I don't know for sure
It's as simple as adding > 0, though
The template condition tests if the given template renders a value equal to true. This is achieved by having the template result in a true boolean expression or by having the template render True.
Alright, thank you both.
could someone help with with this template?
kelvin: "{% if use_color_temp %} {{ color_temp }} {% endif %}"
brightness_pct: !input brightness
rgb_color: "{% if use_color %} {{ color }} {% endif %}"
transition: 1
Seems like it's not resolving that if correctly for whatever reason. not sure if there's a better way to do that
You'll want to share the whole blueprint on a code share site along with the full error
well it's quite a long blueprint and i'm not really getting an error (or I don't know where to find it) other than it just doesn't work. use_color(_temp) are boolean variables, color_temp is an integer and color and array. I have verified that the variables get assigned the correct value. so really my only question is how I make the value of kelvin null / remove it if use_color_temp is false
it's generally a bad idea to have a key that could potentially have no value
you either have a key with a value, or you don't use that key at all
it's a service call, but I want to decide when implementing my blueprint if I want to use color temperature or the rgb_color. is there any better alternative to do that?
the easiest is to make separate service calls based on which keys you want to provide
the more complicated way is to template the entire data section of the service call
So i figured i could also add a condition in the helper instead, not that im against yaml ofc:
{% set power = states('sensor.washing_machine_outlet_power') | float %}
{% if power > 0.9 %}
true
{% elif power == 0 and (as_timestamp(now()) - as_timestamp(states.binary_sensor.washing_machine_status.last_changed)) > 60 %}
false
{% endif %}
What happens on power == 0 and that time difference <= 60?
Neither true nor false
Or power between 0 and 0.9
Do you want to turn a binary sensor on at power >0.9 and turn off, if it is below that for 60 seconds?
I got a template, that has an input going unavailable from time to time. This throws an error in the logs. That's expected I guess as thanks to "availability" it will only result in my templated sensor being shown unavailable, which in this case makes sense. Or should I try to script around this error?
What error are you talking about?
Errors in the log that string is not int for example, which makes sense as "unavailable" is not the supposed number I am expecting.
You have two options. Either add an availability template in the yaml configuration or define a default value for the int filter
if you properly accounted for this in the template entity, you won't get any errors.
Post your template
Guess i should add an else below with false :D thanks for pointing that out.
and yes.
I did not account for the string in the template as I was assuming the availability config would take care of it automatically. Aka when the template fails the sensor will show unavailable. I assume that is true, but would leave the error. Could handle this via an if statement I reckon you are suggesting?
it will, something is amiss, which is why I'm saying to post the template
template:
- sensor:
- name: "Pool Temperature Adjusted"
unit_of_measurement: "°C"
state_class: measurement
state: >
{{ (states('sensor.pool_sensor_temperature') | float -2.5) | round(2) }}
In that case a simpler template would be sufficient.
template:
- binary_sensor:
- name: Sensorname
state: "{{ states('sensor.washing_machine_outlet_power') | float(0) > 0.9 }}"
delay_off:
minutes: 1
You don't have an availability template on that
Thought the availability defaults to true. Or does it only default to true, if configured without an option?
template:
- sensor:
- name: "Pool Temperature Adjusted"
unit_of_measurement: "°C"
state_class: measurement
state: >
{{ (states('sensor.pool_sensor_temperature') | float -2.5) | round(2) }}
availability: "{{ states('sensor.pool_sensor_temperature') | is_number }}"
availability defaults to true
which means it's always available
which means, you'll get errors when the state template has exceptions
Thanks! my brain is always thinking of more complex ways to do things.
not necessarily better.
My example might have an error in it. Wrote it on mobile during work. 😅
Use the config check and adapt it to your needs.
@mighty ledge thanks got it all resolved now.
Yeah i used my previous attempt of a binary template sensor, the only differences are that i have availability unique_id and device_class defined. Also no leading - in front of binary_sensor
Not sure what the leading - is for. i see it with and without in many examples
it's yaml
what would be the condition to use it and to not use it?
the sensor works without it at the moment.
list:
- name: item 1
info: item 1 info
- name: item 2
info: item 2 info
so its for multiple sensors
- is the start of the object & it's containing information
first item ends when the second - is seen by the yaml parser
ah okay
So in this case it would be:
template:
- binary_sensor:
- name:
at the moment i have
template:
binary_sensor:
- name:
it works but i suppose it will become an issue once i start adding more template sensors in yaml
if you add trigger based binary sensors, you'll have issues
otherwise you can list them all under binary_sensor: without the dash and you'll be fine
trigger based template entities require you to create a new section so that the binary_sesnor tag is paired with a trigger tag.
i.e.
template:
- trigger: ...
binary_sensor:
...
- binary_sensor:
...
ah okay, i understand, thank you :)
the best practice to avoid future headaches would be to use dashes
will do, i added it :)
Is there a way to iterate over the exposed entities to assistants? I saw a bunch of people online mention
{%- for entity in exposed_entities: %} but it does not seem to work for me when used as part of an LLM prompt - the for loop never executes. I verified that templates do work in LLM prompts however with a simple for loop over a list of numbers, and printing them out.
Better way to get entities in an area with a given label?
{{ set(area_entities('living_room'))
.intersection(label_entities('light'))
| list }}
I would have just used a select('in', label_entities('light'))
Ah yeah I kinda like that better I think. Let me try it out
or...
{{ area_entities('living_room')|select('match', 'light.')|list }} if you're really just looking for all the lights
Hey all,
Is it possible in an automation or script to do something like this and if it is could someone get me on the right track:
If device has label X and battery is low do send a notification? ( Creating dynamic automations or scripts so people dont have to add a device to the automation or script any time theres gonna be added one )
I tought to be smart using groups instead of labels, but that aint gonna work unfortunately since i have multiple types of sensors.
didn't you already create a template sensor which worked with both numeric battery sensors and text based sensors?
I have done nothing yet with templates and battery states 🙂
it was someone else then. But is that the issue? That you have both numeric and text based sensors
Its not really an issue, but i do like to know where i have to start with. I want to add more of these " dynamical templates " later on for example notifications and lightbulb flashing whenever the alarm rings on whichever floor you are and such
You'll need to use labels to get this done
otherwise you'll have to manage a trigger
you can use something like that to list all entities with state low and which are below 20 (within a label)
Looks good!
It could be adjusted to work wiht a single label (like battery)
Ive got a label named "battery" for example which has grouped all the battery related devices together
Imma going to have some fun with this as soon as i picked my daughter from school. thanks! 😄
this will give a list of all entites from the label battery which are either low or below the set threshold
{% set low_threshold = 25 %}
{# Filter string sensors with state 'low' #}
{% set low_string_entities = label_entities('battery')
| select('is_state', 'low')
| list %}
{# Add numeric sensor names below threshold #}
{% set ns = namespace(low_entities=low_string_entities) %}
{% for s in label_entities('battery') if states(s) | is_number and states(s) | float <= low_threshold %}
{% set ns.low_states = ns.low_states + [s] %}
{% endfor %}
{# Output combined entity list #}
{{ ns.low_entities }}
Hi there, i try to make an tamplate with folowing code:
Many thanks!
Question, what are you trying to get with the 'friendly_name' attribute?
@analog owl I converted your message into a file since it's above 15 lines :+1:
in templates.yaml
the name of the entity. That was becasue the topic starter of the linked topic wanted that
But i get no Entity with last_arrival_home entry
but I just changed the code above to list the entity_id's
Ah okay, thanks 😄
templates.yaml is included with template: !include templates.yaml in configuration.yaml
the entity_id is derviced from the name, and only the first sensor listed in your code snippet is following the proper format, the others a mismatch of the old legacy format
i need filter with "Ben's Letzte Ankunft Zuhause"?
use state instead of value_template and don't try to define the object_id, as you can't do that using the modern format
you first need to fix the actual YAML
if you define a unique_id you will be able to rename the entity in the GUI
and if your templates are as simple as this (so no trigger, no availability) you can also create them under Helpers as a Template helper
although for that 3rd one I would advice to create a trigger based template sensor
pls w8t 😛 Thats too fast 😛
What you currently have won't survive a HA restart or template reload
@analog owl I converted your message into a file since it's above 15 lines :+1:
you need to remove last_arrival_home: and last_departure_home:
give me a sec
you can't define that in the modern format
ahhh okay
Trying to make more use of labels and be explicit by labeling.
Otherwise I'm toggling an led on a board with the rest of the rooms lights lol
is there a way to use a group instead of each user?
Maybe a stupid question, but how can i see what entity's has been saved into the variable?
like device_tracker.pixel_8_pro_$user.state
{{ ns }} i guess
{{ ns.low_states }}
Many thanks! 🙂
The code needs all instances of ns.low_states replaced by ns.low_entities
whoops
{{ n.l }} Minimum verbosity reached. 🤣
not too minimum tho
also, it's likely that no sensors have the state low
they are binary most likely, so it would be 'on'
Hahaha lets keep it readable for this noob xD, ill keep it wordy but change the low_states to low_entities if its nessecary
Im trying this but it aint givig any output: {% set test = expand(label_entities('Battery')) %} {{ test }}
It’s not. We’re just having fun.
Oh haha, okay 😛
it can be done in go
{% set low_threshold = 25 %}
{# Filter string sensors with state 'low' or below threshold #}
{% set ns = namespace(low=[]) %}
{% for s in label_entities('battery') if is_state(s, ['low', 'on']) or (states(s) | is_number and states(s) | float <= low_threshold) %}
{% set ns.low = ns.low + [s] %}
{% endfor %}
{# Output combined entity list #}
{{ ns.low }}
if you're forced to use namespace too, no point in separating the list when you have to iterate label_entities anyways
guess that's what you meant 🙂
But still misses the binary sensors that will be on
{% set threshold = 25 %}
{% set filter = ('low', 'on') %}
{# Filter string sensors with state 'low' or below threshold #}
{% set ns = namespace(items=[]) %}
{% for s in label_entities('battery') if is_state(s, filter) or (states(s) | is_number and states(s) | float <= threshold) %}
{% set ns.items = ns.items + [s] %}
{% endfor %}
{# Output combined entity list #}
{{ ns.items }}
added
That’s also assuming that ALL battery entities are labeled. Personally, I’d go with device_class, but even then there might be misses due to custom integrations.
20,000,000 ways to skin the cat…
problem with device_class is that you're now forced to use the states table and you'll be held to it's update policies
You’re not wrong.
I prefer labels myself
As do I, but sometimes I forget to label when I add a device.
See, that's where spook comes into play
What do you mean? Spook can auto-label or notify if a label is missing? What did I miss?
Yes, you can do anything with labels in spook
That's where you'd use a template to traverse the states table to add/remove labels. Doesn't matter if that's throttled, as long as your template doing the work is not throttled
Hmmmm, so I'm envisioning something in my midnight automation that would look at the states table, check for battery devices that are missing the label and then add it. TBH, that never even occured to me. Thanks petro!
device_class: battery will be numeric, so a battery sensor with state low won't have that device class
Many thanks all for your great input :D, im going to definiatly use it! 🙂
One question, sure that label_entities is the correct syntax? My list looks pretty empty.
{% set test = expand(label_entities('Battery')) %}
{{ test }}
Output: [ ]
I confirmed it has entities in it. 3 pieces 🙂
Yeah, I'm guessing there would have to be multiple filters for things like that. Or, just ignore anything with a 'low' state. I tend to disable those entities anyhow unless the device doesn't have an actual battery entity.
Try:
{% set test = expand(label_entities('battery')) %}
{{ test }}
I've noticed that label_entities sometimes struggles with casing. Other times, it's fine.
Still no output
ik works both on the slug and on the name
did you actually assign a label to those entities?
Yes, 3 entities has that label
entities or devices?
Devices
That's why
Assign the label to the entity, not the device.
Yea, i have assigned them to the devices as it seems
Yup, that would do it.
assign it to the entity as well
you can use label_devices() but a device could have another sensor which will then be used, like another binary sensor, or another numeric sensor for eg connection strength
also, I don't think it doesn't make much sense to add the label to the device, the device itself is not a battery device, on of the enitites is a specific battery sensor
No, you are right
I havent tought about it to give entities a label instead of the devices
I have a "Battery Device" label that I use just to be able to filter quickly on all devices that have batteries. But I also label the entity as well.
Thats a nice idea aswell, but why have you choosen for a label instead of a group?
Is it normal that i get all the sensors as output even tho i only selected the battery sensor?
This is the output now:
[<template TemplateState(<state sensor.serre_bewegingsensor_battery=99; state_class=measurement, unit_of_measurement=%, device_class=battery, friendly_name=Serre: Bewegingsensor Batterij @ 2024-09-05T02:30:40.111731+02:00>)>, <template TemplateState(<state sensor.gang_sensor_voordeur_battery=100; state_class=measurement, unit_of_measurement=%, device_class=battery, friendly_name=Gang: Sensor-voordeur Batterij @ 2024-09-04T22:31:49.688582+02:00>)>]
Ah so its normal behaviour then 🙂
I have a simple automation that turns the living room lights on wen the lux from the outdoor sensor is below a certain value. But sometimes it turns the lights back on wen I switch them off. Will something like this as a condition prevent the automation running twice?
{{ as_local(this.attributes.last_triggered).date() != now().date() }}
If you add that it will only trigger once per day
Is it true that when defining a sensor using a value_template, regardless of what I put in the template, the return type will always be 'string'? Is there an agreed best approach to handle this;, ie all users of that sensor try to convert it back to a list. ChatGPT suggests converting the list 'tojson' in the original value_template and all users then can convert that back 'fromjson'.
Is this the best way to do it or can I avoid this?
sensor states are always strings, but you can put more complex datatypes in an attribute if you want
ohhhh ok got you, thanks for the tip
@rotund pond I converted your message into a file since it's above 15 lines :+1:
@rotund pond - try this instead:
value_template: "{{ hourly['weather.forecast_home'].forecast[0].precipitation }}"
When you call the service your forecast is in the hourly variable, it is not a state_attr of the weather entity anymore.
I have changed it now, unfortunatly it still says unavailable
or doest the standard weather integration support precipitation?
call the service in devtools and see what you get
temperature: 21.1
dew_point: 20.7
temperature_unit: °C
humidity: 96
cloud_coverage: 100
pressure: 1010
pressure_unit: hPa
wind_bearing: 242.6
wind_speed: 16.6
wind_speed_unit: km/h
visibility_unit: km
precipitation_unit: mm
attribution: Weather forecast from met.no, delivered by the Norwegian Meteorological Institute.
friendly_name: Forecast Home
supported_features: 3
that's state attributes, not the forecast
ok where would i find the forecast?
found it
it does have a value for precipitation
at the bottom of the Response box click Copy Template, paste that in your devtools template and try
sorry i am quite lost right now, by devtools template you mean my configuration.yaml?
see thread
oh you might have to wait for the next hour to trigger the template
I don't think it will run on start, unless you add a trigger for that
or add another trigger for testing
hi -- has something changed with templates and using is defined and/or this.state and/or value_json (with MQTT) (probably in 2024.08)? some documentation for another project (meshtastic) has gotten a ticket claiming a bunch of stuff that was working fine in 2024.07 is now broken, and as a major contributor to that documentation I'm trying to figure out what's going on there; the proposed fixes appear to not work on 2024.07. https://github.com/meshtastic/meshtastic/issues/1400 is the issue in question
(and in case anyone notices that the docs there should probably be using template sensors with an MQTT trigger, I know 😉 but haven't had time to port it over, and if the templates are having issues the same question might apply)
I have a template with (float(states('sensor.friggitrice_consumi_yearly'))* float(states('input_number.price_per_kwh'))) | round(2) if I run it in dev tools it works and I get the number, but in the logs I often have this error ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ (float(states('sensor.friggitrice_consumi_yearly')) * float(states('input_number.price_per_kwh'))) | round(2) }}' but no default was specified') while processing template 'Template<template=({{ (float(states('sensor.friggitrice_consumi_yearly')) * float(states('input_number.price_per_kwh'))) | round(2) }}) renders=10>' for attribute '_attr_native_value' in entity 'sensor.friggitrice_yearly_cost' how can I fix it?
if I add round(2, default=0) should solve?
no, because the error is coming from the float function, not from round
float got invalid input 'unavailable'
float also support default?
not default=0 ?
it's needed for round because there is also a parameter to define the round mode (round up or down)
for float it is the only paramter, so you don't need to provide default=
ah, and what is the float default? still 0?
it won't hurt if you do
that's what you need to to provide
"unavailable" | float(15) will return 15
float("unknown", "hello") will return "hello"
"99" | float(default="banana") will return 99
"I'm not numeric" | float(default="banana") will return "banana"
ok, makes sense
👍
thanks
I've just had a look at the new lock screen widgets on the ios app, and I'd really like to get my outdoors temperatures sensors data to be displayed, but I'm a bit lost on how to get the min/max data templated.
I'm pretty sure that there is a very simple straightforward way to do this, essentially I'd like to set the minimum gauge value to the lowest value measured today and the same with the maximum. But how do I template this?
Anyone got good examples for the lock screen gauge?
min max of todays temperature for that sensor?
yes
there's no simple way to do this
If you use a statistics card, you can simply output the info there selecting today w/ min or max selected.
it's really specifically about the ios lock screen widget, it would make a lot of sense to use those values there ...
hi, is this the best channel for help with a rest/rest sensor/json question?
Good afternoon. I've been beating my head against the wall for a bit with this {% set low_battery_sensors = states.sensor | selectattr('entity_id', 'search', 'battery') | selectattr('state', 'is_number') | selectattr('state', 'lt', '80') | list %} Where i get all values below 80 and all instances of 100. What bad voodo have i begat?!
You can't compare states like that because they are strings
I answered exactly this question a few days ago
I can hardly make discord work, my apologies. Searches and following threads here are not my strong suit. THanks for the link.
yes
i'm trying to use the rest sensor to get data from this page (i'll templatize date) [https://api.mealviewer.com/api/v4/school/VirginiaHighlandElementary/09-06-2024/09-06-2024] . the specific jsonpath to get the items i want is:
$.menuSchedules[0].menuBlocks[1].cafeteriaLineList.data[0].foodItemList.data[?(@.item_Type=='Entree')]].item_Name
but for the life of me i can't work out how to get that exact output into a sensor or the attributes of a sensor. i can work out how to get the first item but not all of them
however you get the first item, to get the second you use a 1 instead of a 0
you can't create a dynamic list of items
oh
you can put them in an attribute, but you can't have them as separate entities
how do i put them all in an attribute?
separate entities would require you to write an integration
just point to the object that holds the list and use the list as the json_attributes
what if it's just an array and not an object at that point? if that makes sense
i.e. your path would be $.menuSchedules[0].menuBlocks[1].cafeteriaLineList.data[0].foodItemList and the attribute you'd list would be data
doesn't matter if the attribute is an array, you can't output the array items, but you can output the entire array
so if i do that i get a super long array with lots of items that aren't just item_Names
yep
you can sill use the attribute in templates to do whatever you want
if you want these as separate entities, you'll have to write an integration
they def don't need to be separate entities, in fact i really want to make them into one string
so if I do:
resource: https://api.mealviewer.com/api/v4/school/VirginiaHighlandElementary/09-06-2024/09-06-2024
method: GET
sensor:
- name: "lunch"
json_attributes_path: "$.menuSchedules[0].menuBlocks[1].cafeteriaLineList.data[0].foodItemList"
value_template: "OK"
json_attributes: "data"```
it then puts the whole of the array as the attribute. how would i filter that down to just the item_Names and where the item_Type == 'Entree'?
You can’t, json attributes can’t do that
i guess i need a separate template? 😅
Yep, a template select or something similar
You could use a rest command instead of a rest sensor. Use that in a trigger based template template entity, and call the rest command in the action section.
You'll have more freedom on what to do with the JSON value
And also more freedom on when to update the data
either way going to have to work out how to parse it all in a template so let me start on that 😅
{%- for item in lunch_json -%}
{%- if item.item_Type == 'Entree' %}
{{ item.item_Name }}
{%- endif -%}
{%- endfor -%}
well whaddya know, that seems to work
{{ state_attr('sensor.lunch', 'data') | selectattr('item_Type', 'eq', 'Entree') | map(attribute='item_Name') | list }}
thanks, fancy 😁
Is it possible to use a template to add an attribute to an existing entity?
No, unless the entity is already defined in YAML (from a template integration).
What if it's defined from a rest input in yaml?
Then yes. You would use the json_attributes property.
Thanks!
Is is possible to create a template sensor that shows 'when is the last time someone left a zone' without storing the timestamp in a datetime helper?
Yes, with a trigger-based template sensor defined in YAML
oh, of course!
trigger when the zone changes ... and at that point give the sensor the value of the datetime?
Yep, exactly
so silly ... why did i have to bother you with such a stupid question! 🙂
i've not had coffee yet. this is my excuse.
We all need a push in the right direction at some point
such a gracious response!
{{ state_attr('device_tracker.themrs', 'latitude'),state_attr('device_tracker.themrs', 'longitude') }}
To be used in weblink generation, I'd like a template sensor to create a string that shows the two values with a comma in between. Problem is that the comma makes the template output type into a list.
I've tried a bunch of different things using + concatenation and |string filters, but so far have not found the proper combination. Best was when it added the lat and lon together into a single number! 😉
Any suggestions?
The state of a template sensor is always a string
I suspect you're just looking at it in the template dev tool, which interprets the result
I was. Ok, thats great. So I can just use that value to create a web link on the fly then. Thanks!
So, instead of states.<entity_id we've been told to use states('entity_id') as much as possible for quite a while now, I believe. But to get the last_changed of an entity, I can't seem to use states('entity_id').last_changed. Is that correct?
No, you cannot
Ok, so I keep using the states.<entity_id>.last_changed?
Yes
This has been the case for a long time. Do you know why the two methods (states. and states()) exist?
It's explained in the template docs
In this case, you're referencing a state object property and not the state itself
Right. But ...
Anyway, I'll read the documentation 🙂
Hi all, how can i filter the urls out when i speakout (tts) a notification message like this: Atentie Niels, {{trigger.notification.message}} ?
Not sure what you mean here… are there urls in the notification message? If you know a format, you could use regex_replace in a template.
Yes, like when a new device is discovered etc.
could you show me how that would look like?
@rain lodge I converted your message into a file since it's above 15 lines :+1:
But it gives me:
Message malformed: expected float for dictionary value @ data['value']
What am I doing wrong?
I’ve not used it, but this should help: https://community.home-assistant.io/t/using-regex-replace-in-automation-actions-doesnt-work/507392
You cannot use a template in a device action
I’m not sure you can use a template in a device action like that. Converting it to an entity action might allow it.
Just use the number.set_value service call on the entity
thanks for the links, sadly i have still no clue how to use it.
thanks it worked!
How do i find out why my template isn't working? i defined it in yaml and i keep having this problem for some reason. it became unavailable 2 days ago and i have no idea why.
logs are clear as well
how can I get the energy and power sensors from 's' in this loop? {% for s in states.sensor %}
it just states 'This entity is no longer being provided by the template integration' yet im looking at it in my config..
Do i have to make a choice between UI template sensors and YAML template sensors for it to work?
No, you can have both
There's nothing to go on with the info you gave
My random guess is that you didn't give it a unique_id and HA decided to create another entity ending with _2 or something. But 🤷
@inner mesa
My configuration.yaml: https://pastebin.com/nzgThKhe
the template_sensors directory contains 2 files:
https://pastebin.com/ejWHWUe8
Neither of them are showing up
you said it was working before?
The washing machine sensor did work 2 days ago
so you added a second one and it stopped working?
No, i wanted to add it today, i did, noticed it didnt show up and then i noticed the first one stopped working as well
I did change some things to the washing machine status sensor, which was availability but removing availability does nothing.
are you reloading template entities when you change things?
the reload config option in developer tools?
i do, each time, i even rebooted HA several times for good measure
when you do, review the log
when something doesn't show up in
-> States, there should be something in the log to indicate why
they can't be empty
your problem is that you should be using this:
template: !include_dir_merge_list template_sensors
the template integration takes a list, not a dict
No need for that, they're confusing and not named intuitively. But I wonder why it ever worked
maybe with only one file it just pulls it in directly
and it didn't give me an error, either, and I don't know why it didn't complain
Yeah thinking about it, it may actually have never worked
I ran into an issue with a template sensor named the same way via the ui, i needed to do additional configuration which is only available in yaml (delay_off). so what i saw in states was probably a remnant of the removed helper
that would make sense
regardless, i would likely never have figured this one out, thank you very much.
@compact pond I converted your message into a file since it's above 15 lines :+1:
you need to surround your template in quotes
how can I access to device_class in this object? <template TemplateState(<state sensor.pranzo_cortesia_power=0.0; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Pranzo Cortesia power @ 2024-09-06T23:08:09.152912+02:00>)> it is a loop {% for s in states.sensor %} s.device_class is not correct
or even, in the loop there are object where device_class doesn't exist, how can I skip them?
Ah that's the issue, thanks!
{% for s in states.sensor | selectattr('attributes.device_class', 'defined') %}
I have 4 floors with all different area's. In all these area's there are entities. How can i per floor access only those entities which are on that particulair floor?
Thank you 😄
An example to get all the entities from all the areas on a floor into a single list would be:
{{ floor_areas('first_floor')|map('area_entities')|sum(start=[])|list }}
Sweet, thanks. I tried this but seems you cant use "states" in a for loop?
{% for room in floor_areas('Begane grond') %}
{% states.light | rejectattr('entity_id', 'in', label_entities('Group'))
| selectattr('entity_id', 'in', area_entities(room))
| selectattr('state', 'eq', 'on')
| list
| count %}
{% endfor %}
This one liner fits my needs tho, thanks for it ❤️
if I try to list states.sensor.domain I don't see the 'light' entities, they are all 'sensor', how can I list only light entities?
I can't find it in the attributes
Lights start with light. I believe
The entities should start with light.
For example: light.front_door
they are sensor.something
in the UI I see light.something, but if I loop states.sensor I don't see the light,something, but sensor.something even for loght entries
I just need to loop for light entities, but if I use states.sensor light entities seems included, but with sensor.entity_name
Can you explain what you are trying to do?
so i can do this:
scan_interval: 3600
sensor:
- name: "Next Forecast"
json_attributes_path: "$.properties.[0]"
value_template: "{{ state_attr('sensor.lunch_data_json', 'data') | selectattr('item_Type', 'eq', 'Entree') | map(attribute='item_Name') | list }}"
json_attributes:
- "name"
- "detailedForecast"```
but that puts the value in the status. how can i put that template as an attribute? i think if i do it in json_attributes it will need to find it in the JSON?
Made this one (with some help from youtube and the input from some of you) :).
Is there any way to simplify this?
{% set entities = floor_areas('Begane grond')|map('area_entities')|sum(start=[])|list %}
{% set ns = namespace(total=0) %}
{% for i in entities %}
{%
set ns.total = ns.total + expand(i) |rejectattr('entity_id', 'in', label_entities('Group'))
|selectattr('entity_id','match','light*')
|selectattr('state','eq','off')
|list
|count
%}
{% endfor %}
{{ns.total}}
Isn't this just what the NWS integration will do for you?
It is... I have another weather clock entity that I want to include other info than the weather, and for some reason it only will allow attributes of the weather entity, so I'm trying to add another attribute from a diff template... Does that make any sense? 😁
I guess that makes sense, you could also get this info from nws.get_forecasts_extra which uses the cached NWS response. Then you wouldn't have to hit the NWS server twice for the same info.
Since the NWS weather entity already has this information.
No need for the loop:
{{ floor_areas('Begane grond') | map('area_entities')
| sum(start=[]) | reject('in', label_entities('Group'))
| select('match','light*') | select('is_state','off')
| list | count }}
Superb, many thanks 😄
Ive tried a similair thing, but that didnt work for me. Yet this code works, perhaps because of the is_state? This was mine:
{{ floor_areas('Eerste verdieping')
| map('area_entities')
| selectattr('entity_id','match','light.*')
| selectattr('state','eq','off')
| sum(start=[])
| list
| count}}
You're trying to filter on state objects when you only have entity_ids
Is it so that with the selectattr you only select on one attribute, and if you use select you go through all the data of that entity?
Just for my understanding
is there a 'current' python set_state script (installable via HACS)?
As Rob said, you have a list of just entity ID strings. Those strings don't have any attributes to select by, so selectattr won't work. As shown in my previous post, you can use select with tests like is_state that are designed to work with entity IDs. Another option would be to change that list of entity IDs into a list of state objects with all the attributes using the expand filter.
Ah i see, thanks for this clear explaination 🙂
Im trying to add this into my yaml file, but i get a invalid key error message. Any clue? The code works flawless into the developer tools...
Counter: Lamps begane grond
- platform: template
sensors:
counter_lamps_begane_grond:
value_template: {{ "floor_areas('Begane grond') | map('area_entities')
| sum(start=[]) | reject('in', label_entities('Group'))
| select('match','light*') | select('is_state','off')
| list | count" }}
You need quotes around the template not inside...
"{{floor_areas('Begane grond') | map('area_entities')| sum(start=[]) | reject('in', label_entities('Group'))| select('match','light*') | select('is_state','off')| list | count }}"
O srsly,,, i put them wrong... XD
Sorry
Thanks allot 🙂 Works now indeed xD, ive put the quotes inside of the brackets
Trying to get next dawn time in 12h time
platform: template
sensors:
simple_time:
friendly_name: "Next Dawn"
value_template: >
{% set t = states('sensor.sun_next_dawn') %}
{{ as_timestamp(now()) | timestamp_custom('%I:%M %p') }}
adding to configuration.yaml but it tells me "Error loading /config/configuration.yaml: mapping values are not allowed here"
You are mixing up the old and new formats
Got it
sensor:
- platform: template
sensors:
simple_time:
friendly_name: "Next Dawn"
value_template:
"{% set t = states('sensor.sun_next_dawn') %} {{ as_timestamp(t) | timestamp_custom('%I:%M %p') }}"
thanks
and \n for YAML newlines
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.
Hi all, there i am again,,,,
Ok so im busy now with creating another template. Id like to get the watts from the entity's via label. I have this now, yet it does not work. It does not found any entities. However, i verified that the entities which i expect to appear does have the label( Entities, not the devices).
I have this now:
{{ states.sensor | selectattr('identity_id', 'in',label_entities('ENTITY: Rail switch_Vermogen')) | list }}
Omfg, im stupid >.> thanks! I do get output now lol
Pity, this wont work either,,, {{ states.sensor | selectattr('entity_id', 'in',label_entities('ENTITY: Rail switch_Vermogen'))|select('match','sensor.meterkast*') |list }}
Think im filtering on the wrong attribute
Your 'select()' filter is expecting strings and you're giving it state objects
You're confusing select() and selectattr()
You have to consider what you're providing and use the right one
This is the same issue you keep having here
I get to much information back from the command I asked before. Im getting this
[<template TemplateState(<state sensor.meterkast_groep_1_zigbee_power=0; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Meterkast: Groep 1 Zigbee Vermogen @ 2024-09-07T23:22:33.545343+02:00>)>, <template TemplateState(<state sensor.meterkast_groep_1_vermogen=59.7; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Meterkast - groep 1 Vermogen @ 2024-09-08T00:29:43.132726+02:00>)>, <template TemplateState(<state sensor.meterkast_groep_2_vermogen=1101.4; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Meterkast - Groep 2 Vermogen @ 2024-09-08T00:41:17.461879+02:00>)>, <template TemplateState(<state sensor.meterkast_groep_3_vermogen=14.1; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Meterkast - Groep 3 Vermogen @ 2024-09-07T23:53:19.289813+02:00>)>] however i have to filter it to only get the power amounts back
I see
You need to map() something. You're getting a list of state objects
Aahh
You keep hitting the same issue
Ikr, i wonder if i will ever learn this
I want to calculate the sum of all energy consumption for all light sensors
How can HA know which energy sensors are measuring the consumption of your lights?
You could use labels
hey guys!
how do i make this pseudo-code into yaml which I can have in my configuration.yaml for my garage door template cover?
if closed_sensor == true && open_sensor == false:
current_state=closed
if closed_sensor == false && open_sensor == true:
current_state=open
if current_state == open && open_sensor == false && closed_sensor == false:
current_state = closing
if current_state == closed && open_sensor == false && closed_sensor == false:
current_state = closing
Im guessing this is how it's done, but im trying to program a garage door which uses an open and a closed sensor.
I believe a generic climate entity (which looks like it’s how I bundle a bunch of entities into a climate entity, a climate template if you well?) will not work in my situation.
I have a/c, IR remote, temperature sensors, I know (not assumed) when the a/c is on. I could throw all these into a basket and hope a climate entity comes out …. BUT … there is no way this information can replace the built-in thermostat of the a/c …. Which I think a climate entity tries to be.
Is that a fair assumption?
the entity_id already has the energy consumption, they are shelly sensors, I just need to loop all of light shelly sensors
I get this {% set device_ids = integration_entities('shelly') | map('device_id') | list | unique %} now how I can get all device_ids attributes?
Not sure why you would need the device_ids, but it would be map(attribute=‘device_id’).
I don't need device id, I just need to loop all shelly devices and check a couple of attributes, so a way to access each device attributes, what should I use to loop by integration name?
{% set devices = integration_entities(‘shelly’) %}
{% set ns = namespace(entities=[]) %}
{% for s in devices %}
{% set ns.entities = ns.entities + [state_attr(s,”attribute_name”)] %}
{% endfor %}
{{ ns.entities }}
Since you said you need to check a couple of attributes, you can expand the {% set ns.entities = line to capture multiple attributes and then build a dictionary or whatever.
How do i clean out old regstered entity_ids? I have an old sensor from a .yaml-file that still hangs around so I can't make a new one from the UI with the same id...
the old .yaml is removed and i have rebootet a few times...
Any tips?
Hi all,
How would I go about receiving a true/false for any lights turned ON in a given area. Living room for example?
I've experimented with this approach, but am unsure how to receive a Boolean response:
{{
expand(states.light)
|selectattr('entity_id', 'in', area_entities('Living Room'))
|selectattr('state', 'eq', 'on')
|list
}}
Would this make sense or is there a more elegant way?
{{
expand(states.light)
|selectattr('entity_id', 'in', area_entities('Living Room'))
|selectattr('state', 'eq', 'on')
|list
|length > 0
}}
there is a less computationally expensive way:
{{ area_entities('Family Room')|select('match', 'light.')|select('is_state', 'on')|list|length > 0 }}
Somehow it works on it's own in developer tools but not in a template card for coloring the icon - any clues:
icon_color: >-
{% if {{ area_entities('Living Room')|select('match',
'light.')|select('is_state','on')|list|length > 0 }} %} orange
{%endif%}
OK, resolved it myself - too many wrappers... syntax issue on my part
Yes, you nested your templates
Hello, can someone please assist on why this sensor not working. I would expect the sensor output as float via input number sensor:- peak/offpeak.
- platform: template
sensors:
energy_price_current:
friendly_name: "Current peak Price"
value_template: >-
{% if is_state('select.daily_energy', 'offpeak') %}
{{(states('input_number.energy_price_offpeak'))}}
{% elif is_state('select.daily_energy', 'peak') %}
{{(states('input_number.energy_price_peak'))}}
{% else %}
0
{% endif %}
unit_of_measurement: '$'
how doesn't it work?
The sensors input_number are not available that tells me something is wrong and sensor output energy_price_current is " unknown"
if the input_number entities are not available, that dosn't have anything to do with the template sensor
did you test the template in
-> Templates?
Yes it says
This template listens for the following state changed events:
Entity: input_number.energy_price_peak
Entity: select.daily_energy
and
value_template: >-
unknown
unit_of_measurement: '$'
that part isn't interesting
what is the output? is there an error?
you should review all the entities you're using in
-> States
basic debugging:
{{ states('select.daily_energy') }}
{{ states('input_number.energy_price_offpeak') }}
{{ states('input_number.energy_price_peak') }}
I am only using two sensors and they both have values so not sure where is the issue
('select.daily_energy', 'offpeak as in sensor.daily_energy_offpeak Daily Energy offpeak 5.08
and
('select.daily_energy', 'peak') as in sensor.daily_energy_peak Daily Energy peak 0.69
there are three there
what does that mean
Gotcha
peak
unknown
unknown```
so there ya go
your input_number entities have a value of "unknown". That has nothing to do with the tmeplate sensor
where did you set them? What did you set them to?
earlier, you mentioned sensor.daily_energy_offpeak
that is not the same name
I did not even create those. I assumed it would create those input_numbe based on
the If "" then make this sensor input_number and pass the value of daily_energy_"peak/offpeak"
I don't know where that came from
no, they are not magically created
they are helpers that you create and assign a value to
Interesting so that creates another problem for me.
I have peak and offpeak cost and the aim of above template(I assumed) would produce the current price.
So even if I create input_number sensor and initiliaze w '0' then it should work?
yes this is the sensor which outputs the current kWh
sensor.daily_energy_offpeak as in Daily Energy offpeak 5.08
if that's really what you wanted, then just use that
why are you using the input_number entities in the first place?
New to this so I dont have an answer.
so you didn't actually write that?
No
alright
lol should have started with that
yeah
My bad
so how do I use it here then
{% if is_state('select.daily_energy', 'offpeak') %}
{{(states('input_number.energy_price_offpeak'))}}
replace the input_number entity_id that you didn't want with the sensor that you do
you also have some unnecessary parentheses in there
did this come from ChatGPT or something?
Hi all,
Is it possible to make calculations with the following command:
{{states.sensor | selectattr('entity_id', 'in',label_entities('ENTITY: Rail switch_Vermogen'))|map(attribute='state')|list}}
Now i get back a list of states ( which i ask ), but id like to have those calculated. Is that possible in a oneliner or do i need a forloop for this?
calculated to what? Summed? Multplied with each other? Subracted from each other?
What does calculated mean?
So basically you want to sum the states of entities with that label?
Yes
{{ label_entities('ENTITY: Rail switch_Vermogen') | map('states') | map('float', 0) | sum }}
no reason to iterate over all your sensors, you can just start with the entities with that label
Oh cool, i didnt know that would be possible to! Nice! Thanks allot 😄
Im getting a error message: No filter named<Function forgiving_float at ...>
Perfect, many thanks 🙂
I have Shelly 3EM to 3 circuit system and on one side duct HVAC (3 phase) and PV inverter (3 phase) are hooked together so HVAC consumes energy directly from PV if ther'es enough energy produced, otherwise imports from grid, I'm trying to measure HVAC energy consumption but PV energy sensor is updated every 5 min while Shelly 3EM updates sensors every 15 seconds - is there a way to use a kind of time trigger to slow down template updates? To calculate energy consumed from PV generated-> PV_total - Shelly3EM_exported = HVAC_energy_consumed_from_PV; then I just need to add Shelly3EM_imported to cover night time HVAC energy usage
Hi. I just added a Moes TV01-ZB to z2m in homeassistant and i wonder why it doesnt expose the local Temperatur as Number or Sensor. It only exposes the temp. calibration temperature. Is there anything i can do, to make it expose the "External" temperature?
I could see here that it should expose it in HA https://www.zigbee2mqtt.io/devices/TV01-ZB.html#moes-tv01-zb
In the Developer Tools State i can see this:
Well, i can see This:
hvac_modes: off, heat
min_temp: 5
max_temp: 30
target_temp_step: 0.5
preset_modes: none, auto, manual, holiday
current_temperature: 19.9
temperature: 5
preset_mode: manual
friendly_name: Heizung SZ
supported_features: 401```
current_temperature is there, but i cant use for a senosr wich shows the actual Temp and a curve over the last X hours/days, or for Better Thermostate Add On as external Temperature Sensor
some on #zigbee-archived told me that i could help here:
Create a template sensor
{{ states('climate.whale_heater','current_temperature') }}