#templates-archived
1 messages Β· Page 55 of 1
That would be something like cheapest_energy_hours('sensor.your_sensor', hours=3, look_ahead=true, include_tomorrow=true, end='14:00')
That should give the start time of the next consecutive 3 hour with the cheapest prices
That seems straight forward
Then feed that into a timer or something to get an event?
What kind of event are you referring to?
For me I have an event when the door of my dishwasher closes.
So I just want it so that when it closes, it finds a suitable time and auto starts.
And then it wont auto start unless it's been opened and closed again.
If it's opened* before it starts, I hope I can cancel the timer.
Create a trigger based template sensor. Trigger on the door closing, and give it device_class: timestamp
You can then use that sensor in a time trigger
Interesting, lemme try that.
I'm just struggling with my energy-dashboard configuration. I get a solar-refund that is adapted quarterly and the new value is published a few days in advance. To get the correct calculation, I manually have to enter the new value in the night before sunrise of a new quarter. Is it possible to create a sensor that accepts a table with value and from-to date, that picks the right value fitting current date?
I already managed to grab the value from the website, but then again, it's 1-2 days off. Unfortunately the provider does not provide an API, only a general website with "starting with Q4 2023, the refund will be ..."
if nothing else, you could probably write an if-statement into a template sensor and update it periodically. If you wanted to get a little fancier and the rollover dates are always the same for each quarter, you could do something like have 4 different input_numbers that you use (one for Q1, one for Q2, etc.) and then have the template sensor pull from the correct one for whatever is the current quarter (so you could e.g. update the input_number for Q4 days or months in advance, but the template sensor wouldn't start using it until whatever day you configure)
what is the correct value_template for a template garage door cover entity in order to accurately reflect the binary sensor for the door? Below is my template, but when the door is open, the cover shows closed.
cover:
- platform: template
covers:
garage_door:
device_class: garage
friendly_name: "Garage Door"
value_template: "{{ is_state('sensor.lumi_lumi_sensor_magnet_aq2_opening_3', 'on') }}"
In addition, true is valid as a synonym to open and false as a synonym to closed.
Your value template renders to true if the state is "on" (btw. are you sure it is a sensor and not a binary_sensor?),thus the cover is deemed open
ahh, i missed the edit to binary_sensor from regular sensor. That did the trick
thanks @marsh cairn
As it is already a binary sensor, can't you just change the device class in the entity settings?
Oh wait, you're creating a cover entity
My bad π
Is it possible to change button/tile icon color from an automation or variable state?
That's a #frontend-archived question
Any suggestions on how to create a sensor that has the same functionality as one of the cost sensors created by the energy dashboard? i.e. I have a sensor that has the lifetime energy usage, stored as a running total (and kept as a statistic with state_class: total or state_class: total_increasing). Plus I have an input_number that holds the current price for the energy used. How to create a template for a sensor that has the running total of the costs over the lifetime usage? I would like to store that cost too as a statistic by adding the state_class: total_increasing attribute. It's not as simple as multiplying the usage sensor's value by the price because the energy is stored as a running total and the price value varies over time. I think only the difference since the last energy 'measurement' should be multiplied with the price, then added to the previous value of the cost sensor. But I have no clue how to do this...
If the energy dashboard is configured with your "total_increasing" sensor and you point the price to your "actual_cost" sensor, wouldn't the normally hidden "sensor.{total_increasing}_cost" hold just that value?
Yes, it would. But I want to register the costs/compensations for additional energy sensors in the same fashion as those are registered. At least I want to keep track of the costs for my total consumption (= home usage * price for grid-in ) and compensation for total energy produced (=solar production * price for grid-out). Using these two values I can then calculate when I have earned the investment of my solar installation back.
Maybe it could be an option to just register those sensors as regular energy-sources, like the main meter. These would be listed, weighted and summed. Since you probably cannot cover ALL of your energy use with this, you then would need to change the current main-meter reading against "main-(sum of all other)" to account for the rest.
I already have all energy sensors I need, I just need their costs/compensations calculated and stored as the energy dashboard does it. If I add these sensors to the energy dashboard's config, that will disrupt the correct working of the energy dashboard itself.
Had you took a look at this integration ?
https://www.home-assistant.io/integrations/utility_meter
Yes, I did. It allows to reset a running total at set intervals, or make a resetting running total into a non-resetting one. But I don't see how that helps me calculating costs?
It does mention tariffs in there too, but that is only to split one running total into two or more depending on a tariff indicator a.f.a.i.k. Or am I wrong?
hmm. the "tariffs" seem to me more of a classification than a calculation. Does still look promising for me, if you set the "resetting" to some time way into the future (CRON), in the past or something, so the counter will essentially never reset.
This guy managed to calculate sensor differences out of the statistics, so you still may just multiply the difference with your price
https://community.home-assistant.io/t/diffrential-value-for-energy-consumption-sensor/104962/6
Thanks, Petro's template (https://community.home-assistant.io/t/diffrential-value-for-energy-consumption-sensor/104962/5) in that thread looks promising. Let me try something with that...
You don't even have to trick the utility_meter by setting some future or past dates, utility_meter allows to set "Meter reset cycle" to "No cycle", which does exactly what you mention: never reset. This can be helpful if you only have a resetting sensor, using this "No cycle" you can remove all resets and essentially create a non-resetting running total. But that is of no use to me now, I think.
Nah, that doesn't work either. My running total energy sensor doesn't have the mentioned 'change' attribute, so the template doesn't return a value. Plus, the template sensor doesn't allow me to create a template with device_class: energy and state_class: measurement, it says User input malformed: 'measurement' is not a valid state class for device class 'energy'; expected one of 'total', 'total_increasing' . Which is a ridiculous restriction, because the difference of 2 energy measurements is still energy and it can go up and down and is thus a measurement, not a running total.
Now trying the statistics integration https://www.home-assistant.io/integrations/statistics/, I think if I give that a sampling_size: 1 and state_characteristic: change that could give me the difference between this and the last change. Which I could then multiply with the current price to get this last sample's costs. Now restarting after adding the template...
so far I see no values coming in, even though new values did come in on my source sensor. Do I need to increase sampling_size to 2?
Yes! Thank you @languid nova. I've got the difference covered by this definition:
name: "Envoy 121831009724 Lifetime Energy Consumption Difference"
unique_id: sensor.envoy_121831009724_lifetime_energy_consumption_difference
entity_id: sensor.envoy_121831009724_lifetime_energy_consumption
state_characteristic: change
sampling_size: 2```
Have to go to sleep now, but at least I'm one step closer!
@willow wing I converted your message into a file since it's above 15 lines :+1:
Output: The condition key is not expected or supported by the visual editor.
The value_template key is not expected or supported by the visual editor.
you can't use templates in a conditional card, basically you can only use a state condition
you can create a template binary sensor using that template, and use that in the conditional card
ok 3rd attempt to ask my question ... cant quite figure out how/what I am asking -- first part I guess is this: can I create a list using Jinja, in ha - at all? when using 'x.append()' in the templater, at least, would throw this: access to attribute 'append' of 'list' object is unsafe.
whats the best way to display the sensor name with the largest number oh the attribute "last_called_timestamp"? out of 4 sensors?
Sure. Just declare it as a list in Jinja. {% set l = ['foo','bar'] %}
Then you can do {% set l = l + ['whale'] %}
something like this I guess, but I can't ifgure out the attribute part:
| selectattr('state', 'is_number')
| sort(attribute='state', reverse=true)
| map(attribute='name') | first }}```
What does the above get you?
ah worked it out π thanks anyway!
{{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot')
| selectattr('attributes.last_called_timestamp', 'is_number')
| sort(attribute='state', reverse=true)
| map(attribute='entity_id') | first }}
if a timestamp is showing as "1696232948788" how would I convert that to a date where I can show which one is most recent? I can't tell what why the timestamp is 1696232948788 and not a date
as_datetime(...)
https://www.home-assistant.io/docs/configuration/templating/#time
ah perfect thanks π
don't you want to sort on the timestamp as well, instead of the state?
yep - sorry I edited it
is there a way to wrap this in as_datetime: expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot') | selectattr('attributes.last_called_timestamp', 'is_number') | sort(attribute='attributes.last_called_timestamp', reverse=true) | map(attribute='attributes.last_called_timestamp') | first
it says its not a string - (TypeError: argument must be str)
but when I do:
| selectattr('attributes.last_called_timestamp', 'is_number')
| sort(attribute='attributes.last_called_timestamp', reverse=true)
| map(attribute='attributes.last_called_timestamp') | string | map('as_datetime') | first }}```
it says null
because when i remove string it says TypeError: argument must be str
then you should use | map('string') to map the list items to a string
but that should not be needed, this works fine.
{{ [1, 2, 3] | map('as_datetime') | first }}
and those are not strings
I think the timestamp is weird. its "1696234131245"
it should be 10 digits right?
no
it's the number of seconds since 1st of January 1970, so it can be any number of digits, however, it can be too big indeed
which it seems to be
looks like it is the number of miliseconds
I just want to show the timestamp in DD/MM/YY HH:MM:SS
use this:
{{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot')
| selectattr('attributes.last_called_timestamp', 'is_number')
| sort(attribute='attributes.last_called_timestamp', reverse=true)
| map(attribute='attributes.last_called_timestamp') | map('multiply', 0.001) | map('as_datetime') | first }}
fixed a typo
use .strftime() on the result. see https://strftime.org for how to do that
or | map('timestamp_custom', '%H:%M') instead of | map('as_datetime')
(that will only give the time, see the website on how to add the year)
(how) can I create a dict of entity_id: some_attr from a list of entities?
| selectattr('attributes.last_called_timestamp', 'is_number')
| sort(attribute='attributes.last_called_timestamp', reverse=true)
| map(attribute='attributes.last_called_timestamp') | map('multiply', 0.001) | map('timestamp_custom', '%d/%m/%y %H:%M') | first }}``` thank you once again π
using a namespace and a for loop
thanks. Would you happen to have an example?
{% set l = [ 'light.foo', 'light.bar' ] %}
{% set ns = namespace(your_dict={}) %}
{% for e in l %}
{% set add = {e: state_attr(e, 'your_attr')} %}
{% set ns.your_dict = dict(ns.your_dict, **add) %}
{% endfor %}
{{ ns.your_dict }}
last thing - how do I turn {{ state_attr('sensor.alexa_last_called', 'Entity') }} which is 'media_player.alexa_sonos_beam' to 'notify.alexa_media_alexa_sonos_beam' so pretty much remove 'media_player' and replace it with 'notify.alexa_media_'
won't let me add the _'s to the last part of that sentance
use code tags to avoid it using formatting on your text
text between underscores is converted to italics
text betwee _code tags_ is not
anyway, just use | replace('what it currently is', 'what it should be')
Thanks, that seems to be working!
is there a way to add a not_from for:
attributes:
Summary: >
{{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot')
| selectattr('attributes.last_called_timestamp', 'is_number')
| sort(attribute='attributes.last_called_timestamp', reverse=true)
| map(attribute='attributes.last_called_summary') | first }}
I don't want it to change if its from '' or 'alexa'
when this was an automation I had:```
not_from:
- ""
- alexa```
you lost me here
not_from is used on a state change
in a trigger
templates work with the current state values, not on changes
{{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot')
| selectattr('attributes.last_called_timestamp', 'is_number')
| sort(attribute='attributes.last_called_timestamp', reverse=true)
| map(attribute='entity_id') | first }}``` shows me media_player.alexa_sonos_beam
thew above code is {{ state_attr('sensor.alexa_last_called', 'Entity') }} which is media_player.alexa_sonos_beam
media_player.alexa_sonos_beam has an attribute of last_called_summary
is therea way to make a template show the last_called_summary of the entity the above code gives?
I have {{ expand('media_player.alexa_sonos_beam', 'media_player.alexa_echo_show', 'media_player.alexa_echo_spot', 'media_player.alexa_echo_dot') | selectattr('attributes.last_called_timestamp', 'is_number') | sort(attribute='attributes.last_called_timestamp', reverse=true) | map(attribute='attributes.last_called_summary') | first }}
Hey how can i change the content between 1 light and 2 lights (if else works there?)
content: '{{ states.light|selectattr(''state'',''equalto'',''on'')|list|length }} lights on'
icon: mdi:lightbulb-group
icon_color: >
{% if states.light|selectattr('state','equalto','on')|list|length > 0
%}
orange
{% else %}
grey
{% endif %}```
but this changes to "" eeven though the attribute hasnt changed
when does it change?
@willow wing To format your text as code, enter three backticks on the first line, press Shift+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.
but you use elif
{% set count_on = states... rest of template %}
{% if count_on > 2 %}
pink
{% elif count_on > 1 %}
green
{% endif %}
i mean the content, not the color, color works fine
if this is for a mushroom template chip, you don't need the {% else %} grey as that is the default
you can do the same for content
hmm strange was not working, i try it again
like this?
{% if states.light|selectattr('state','equalto','on')|list|length = 1 %} light on
because then the text is complettly away (copied from working icon_color)
you need to use == for a comparison
same, no text π¦
post your complete template
content: >-
{% if states.light|selectattr('state','equalto','on')|list|length == 1 %}
light on
icon: mdi:lightbulb-group
icon_color: |
{% if states.light|selectattr('state','equalto','on')|list|length > 0 %}
orange
{% else %}
grey
{% endif %}```
aaaaahhh fuck omg, thank you
mmkay, I have a question; what type of data structure is outputted by state_attr() ?? its not a list, right?
state_attr('media_player.xxx,'entity_id') }} comes out as [xxx, xxx, xxx]
what's the issue?
if they're both put in at the same time, the output is different
One apparently is a set and the other a list, but doesn't matter generally. And you can see the output of my group
it's not a set
ok -- so what I'm looking for is the set
is there an issue?
can i turn a list into a set?
I think you're off in the weeds
well, yes and no ...
i've been trying to figure out what it is exactly i'm trying to ask first so that I can make more sense...
if you start with the problem, then perhaps there's a solution
so, i have 2 groups, one with group: , one created in UI with helper (group.xxx vs media_player.xxx). so state_attr on the group returns a set, and state_attr on the helper returns a list. got it (now). I would like to convert the list [], into a set () -- run a replace() on that set, which in turn I would expand() and extrapolate.
so, I guess, can I turn a list, [] ... into a set ()??
() -> tuple
[] -> list
set -> set
both helper groups and old school groups have entity_id which should be a list, not a set
it's possible that old school groups return a tuple
ok, so that might be where I am stuck
so, you still aren't explaining yourself well
are you trying to combine them and get all unique items?
actually I think you may have answered my question with tuple.
basically this doesn't make sense
run a replace() on that set
are you purposely trying to not explain what you want to do?
lol .. no; is it ok that i post a screenshot?
just say with words what you want to do with the 2 lists, assume they are lists
"I want to combine the 2 lists"
"I want to remove items from one list from the other"
Okay ... I think this is the best explanation Im going to be able to come up with:
in the templater, when you put BOTH
state_attr('group.ac_enabled','xxx') <-- old school group, contains input booleans
AND
state_attr('media_player.xxx','entity_id') < -- UI, contains media players
the input booleans render as a tuple(?), the media players a list[].
in my case, the input booleans and the media players cooincide with eachother: input_boolean.name == media_player.name I am trying to replace(media_player,input_boolean)
Indeed. Realized my mistake in the shower, couldn't correct π
I think you're way overthinking this
And confusing yourself by focusing on types
when I try to expand('media_player.xxx'|replace(blabla)) it does not replace what I have requested
but it DOES when i use the oldschool group
You just want a list of media players that have input booleans with the same object id?
It's as simple as {{ state_attr('xxx', 'entity_id')|map('replace', 'whatever', 'whatever')|list }}
i want a list of input_booleans that have the same name as the media players after i have removed (replace()d with '')
I still think this is an xy problem
Petra is probably not using a phone, so I tag out...
It's like some sort of cruel and unusual punishment
Haha yes
Explain the whole endgoal
Not your specific problem with whateve mr code you came up with
The XY problem is asking about your attempted solution rather than your actual problem.
ok, let's try this:
UI helper group (media_players)->replace() into input_booleans-> template sensor
That's..not useful. You're still starting with what you think is the solution
Besides that, rob already gave that to ya
Here
Iβm pretty sure you think we are being asses but you arenβt making yourself clear when you think you are. Itβs clear you arenβt a coder, and thatβs ok. Just describe what you want the entire template to do with the inputs that you have.
No, I dont think y'all are being asses... Im just as frustrated because I dont really don't know how to convey what I'm trying to ask.
You have a group of media players... what do you want to have in the template sensor at the end?
Let's not call names, everybody is doing their best here. Still this is chat, and things can come across harder in those cases (just a result of using text). We are all still human, please keep that in mind. Saying things like that, will not make other want to help you any further.
Thanks π
LOL me being the example
misread "don't" in that sentence
sorry about that @languid pendant
you're alright Frenck
We saw nothing π
Cancel Frenck!
Petro started it π
π I was thinking ??????????
LOL like a real CBS tvshow π
Ok, so. group of mediaplayers
Was very confused ππ€£
Yes, weβve been over that
@languid pendant Forget about the booleans at the moment or the complete way up to that point
But at this point, we still have no idea what you want.
What should be the final result in the template sensor (like "it should show the loudest speaker")
lol its not about the media players, lol it's about the input booleans
If you just want a list of entity ids that came from media player entity ids, then rob already gave you that
i need to know which out of those corresponding booleans was the last turned off
Ah!
which i already have the working stuff for that
BUT
only for a hard-coded old-school group
what are your groups?
the actual entity_ids
anyways, play with this
{% set entities = expand('group.x', 'media_player.y') | map(attribute='entity_id') | map('replace', 'media_player.', 'input_boolean.') | list %}
{{ expand(entities) | selectattr('state', 'eq', 'off') | sort(attribute='last_updated', reverse=True) | map(attribute='entity_id') | first | default }}
should do what you want
Hi friends!!
How can I resolve this error?
TemplateError('UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last_period'') while processing template 'Template<template=({{ ( ((states.sensor.energy_tomada_tv_sala_monthly_total.attributes.last_period) | float(0) * 0.1587 + 30.0 * 0.2038 ) * 1.23 ) | round(2) }} β¬) renders=6408>' for attribute 'Estimativa Factura Anterior' in entity 'sensor.monthly_energy_cost_tomada_tv_sala'
@wispy lodge I converted your message into a file since it's above 15 lines :+1:
Thanks
use state_attr('energy_tomada_tv_sala_monthly_total','last_period') | float(0) instead of states.sensor.energy_tomada_tv_sala_monthly_total.attributes.last_period
Sorry I had to step out for a min (smoking) β I think you may have figured out what Iβm trying to do petro
Iβll check when I get back in
Thank you very much!
I tried it but it gives me a different value. It gives me a lower result on the bill... Don't I have to add "sensor" behind the entity? Like this: "(state_attr('sensor.energy_tomada_tv_sala_monthly_total','last_period')" ?
I don't know where to ask for the 3rd part of this problem I've been working on. If this is not the place, please let me know where I should go:
I'm still trying to create a custom sensor that mimics the *_cost and *_compensation sensors created by the Energy Dashboard. These are stored as Long Term Statistics (LTS), and hold a running total of the costs for an energy sensor, which is a running total itself.
First 2 parts (which I have covered) are:
1 - from an energy sensor I get the difference between the current value and the previous value using the statistics integration,
2 - to calculate the costs for the energy consumed in this period I use a template {{ states('sensor.envoy_121831009724_lifetime_energy_consumption_difference') | float * states('sensor.electricity_meter_energy_consumption_price') | float }}
Those two steps gave me the cost for every new energy measurement. Can someone point me to some way to make this into a running total?
ok, so I'm happy to report that all the frustration was not in vain:
{% set l = namespace(test=[]) %}{% for entity in (state_attr('media_player.ac_helper','entity_id')) %}{% set l.test = l.test + [entity|replace('media_player.vlc_','input_boolean.ac_')|replace('_kodi_mini','')] %}{% endfor %}
{% set entities = expand(l.test, 'media_player.ac_helper') | map(attribute='entity_id') | map('replace', 'media_player.', 'input_boolean.') | list %}
{{ expand(entities) | selectattr('state', 'eq', 'off') |sort(attribute='last_updated', reverse=True) | map(attribute='entity_id') | first | default }}
allows me to get rid of the group created in yaml,
takes the UI created helper, map the respective (replace()'d) input_booleans, and then give me the last one that was turned off
Sorry for all the confusion, but also thank you for bearing with me
seems a little overly complicated π
i know,
{% set entities = expand(l.test, 'media_player.ac_helper') | map(attribute='entity_id') | map('replace', 'media_player.', 'input_boolean.') | list %} takes a list of entity_ids, turns it into a set of states, turns it back into a set of entity_ids, then replaces stuff, then turns it into a list π
in any case, if you got what you wanted out of it, π
Hi all, i'm trying to combine 2 senors (temperature and humidity) but new sensor report unknow status :
- name: "thermosensor2" state: "{{states('sensor.temperature_bureau_adrien_temperature')}} CΒ° | {{states('sensor.temperature_bureau_adrien_humidity')}} %"
Any idea ?
I sugggest:
state: "{{ states('sensor.temperature_bureau_adrien_temperature') ~ 'CΒ° | ' ~ states('sensor.temperature_bureau_adrien_humidity') ~ '%' }}"
nope π¦
Try running your template in Developer tools - Templates to see what is going on...
seems to be good
Type de rΓ©sultat: string
"23.01 CΒ° | 76.15 %"
if nothing else works, you can try an alternative approach:
{{ "%.1f CΒ° | %.1f %%" | format(states('sensor.temperature_bureau_adrien_temperature')|float, states('sensor.temperature_bureau_adrien_humidity')|float ) }}
Did you add a device class, state class and or unit of measurement?
no
It might be expecting a numeric state
@trail solar I converted your message into a file since it's above 15 lines :+1:
i think that i'm missing somthing
I'm also wondering what that Γ is doing there. But that won't stop it from working
my second and third guesses are - didn't reload template entities or didn't trigger the sensor via the webhook
that discord that do this
trigger are for my pool information, that come from scripts on another Rpi that take value directly from the pool manager device), the thermosensor is not concerned by that
missed that thanks ! so can i add a sensor block under template ? (not yaml expert sorry)
yes
tried this :
@trail solar I converted your message into a file since it's above 15 lines :+1:
you still have sensors:
thermosensor is working (happy) but Piscine * are not in entities anymore π¦
already mentioned earlier
ok thanks, i don't know why before adding the thermosensor, other are working
No one can tell me how to create a sensor that sums each new value to all previous values?
Or utility meter with delta_values: true if you donβt want to define a max age or a sample size
Hi All, is there any good way to deal with a template sensor if the source is unavailable? This is what I have at the moment:
{% if states('sensor.tasmota_hx711_weightraw') != 'unavailable' %} {{ (states('sensor.tasmota_hx711_weightraw') | float - 927) / 1000 }} {% endif %}
Just set a default value for float to use if the sensor doesn't return a number, eg. float(0). And you should set availability: "{{ has_value('sensor.tasmota...') }}"
Hi guys
I'm pretty new to HA. only a few days actually.
I'm also very new the all this yaml/python/perl whatever all that is. I did some programming in school before during the days of pascal, cobolx foxpro etc. I think I'm able to learn.
I need the 123 starting points to be able to help myself. Please help me in this regard.
At this point I'm trying to create some templates. I have 5 devices that were published to MQTT by the Batmon addon. in the future I may also get additional devices so I want a way to dynamically retrieve these devices to include them in a card without having to manually define them.
This is my current card template
@fast token I converted your message into a file since it's above 15 lines :+1:
I would like to dynamically load that set. this will enable new devices to autopopulate
please give an idea
Welcome to HA. There are many rabbit holes for you to explore.
- Template-based entities are generated by Jinja templates in yaml
- Card templating does not use Jinja templating by default. What you are trying to do in your code requires either custom components (eg. Lovelace Gen or Decluttering Card) or yaml anchors. Some custom cards do support templating but they use JavaScript.
ok
There are other areas in HA that support some sort of code reuse (eg. Jinja macros, blueprints for automations/scripts, MQTT auto discovery) but they are advanced topics. I'd advise for you to work with the entities you have first to get the hang of the logic and structure of HA, before going into code reuse.
Try #frontend-archived for suggestions on cards
ok thanks for that heads up
Hi all, I have since a while a "Template loop detected while processing event" warning in my logs.
The affected template is https://pastebin.com/Q6PCBEub
Any idea on how to fix ?
try this:
{% set ignore_list = [
'sensor.custom_unmonitored_power',
'sensor.quadro_phase_a_active_power',
'sensor.quadro_quadro_total_active_power',
'sensor.ups_potenza_reale_nominale'
]
%}
{% set monitoredpower = states.sensor
| rejectattr('entity_id', 'in', ignore_list)
| rejectattr('entity_id', 'search', '^sensor.consumi_')
| selectattr('attributes.unit_of_measurement', 'defined')
| selectattr('attributes.unit_of_measurement', 'eq', 'W')
| selectattr('state', 'is_number')
| map(attribute='state')
| map('float')
| sum
| round(2)
%}
{%- set totalpower = states('sensor.quadro_phase_a_active_power') | float(0) -%}
{%- set delta = totalpower - monitoredpower -%}
{{ delta if delta > 0 else 0 }}
wait, I forgot one part adjusted above
WoW, looks way better than mine ! Thx a lot, will test it right now
@rigid pier I converted your message into a file since it's above 15 lines :+1:
@rigid pier this is offtopic for this channel, ask agan in #integrations-archived after you reviewed the documentation
Hey Fes, to be fair, I have been getting those warnings too, and I'm a little curious where the configuration has supposedly moved 'to', as the docs state they go in configuration.yaml (I'm not re-asking, just noting that the docs for this may not be clear.)
not the right channel, yes, this just happens to be where i saw his question
Unfortunately it doesn't solve the issue. It even got worst: now I have a warning at each single change, while before it was more sporadic.
the configuration moved to it's own command_line integration, instead of being configured under the entity domain integrations (like switch for a command line swithc, and sensor for a command line sensor)
@marble jackal gotcha - I followed up in #integrations-archived also, but thanks for the confirm
Unfortunately it doesn t solve the issue
Is there a way to query in a template whether a sensor has been active in the last x minutes?
for example, i want to check whether the sensor.solarman_pv_power value was over 300w in the last 5 minutes
{{ (states('sensor.energy_next_hour_total') | float(0) >= 0.2) and (states('sensor.solarman_pv_power') | float(0) >= 300) }}
you can't do that directly
you can create a binary sensor which turns on when the value is above 300W, and has a delay_off of 5 minutes
then you can use that to determine if the sensor is above 300 now, or has been the last 5 minutes
thanks, that worked. I saw that there is also a time limit for template queries in the automations. this would have worked for me too
Only if you use it as trigger, it won't work for a condition
You didn't specify that
thats correct, my fault π
Thank you, the utitlity_meter integration with delta_values: true did do the trick. One extra addition though: Periodically resetting must be set to false too. I left it at the default of true initially and this resulted in the value to reset at times somehow.
Good to know, thanks! I havenβt used that with source sensors that go to unavailable or reset to zero
hey guys!
i made myself a gas meter readout based on impulses. Is there a way i can calculate a flow rate out of an absolute increment value?
like that it calculates the volume per minute or such and discards it if its below some threshold
that's what a Utility Meter sensor does
if you want to manipulate the value as you described, then you need to create a template sensor and then use it in one of those integrations
i think i see, thanks!
I installed https://github.com/TheFes/cheapest-energy-hours using HACS and verified that the jinja file is in config/custom_templates/, but for some reason it isn't available in HA, did I miss something? I tried restarting HA as well.
This is my code
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{% cheapest_energy_hours('sensor.energi_data_service', hours=3, look_ahead=true, include_tomorrow=true, end='14:00') %}
Not sure the first part is needed, I just saw some examples that did that.
Getting this error:
TemplateSyntaxError: Encountered unknown tag 'cheapest_energy_hours'.
Where did you put that?
Developer tools template thingy
Oh, you just called the function with no output
Just use the example from the docs
Which says to use that surrounded by {{ }} and not {% %}
Hello good people, I am looking for ways to create light group entity (of type light) to be able to use the mushroom:lights card to have a sleek overview / control of all lights within one area.
I've created an automation that generates groups of type group for me, but those groups are terribly useless to me currently, as the mushroom card won't usethem.
https://gist.github.com/misse/7cb10203d7ea0c8492ee9714f48434c0
Yeah, just did, now I'm getting a different error, I'll try and see if I can solve that.
@elder mural I converted your message into a file since it's above 15 lines :+1:
@marble jackal the source I have for electricity prices doesn't contain anything that can be used as the start key for cheapest_energy_hours. Is there any way I can get it to just use todays date?
I guess it might be possible to nest templates π€
Settings > Device and services > Helpers > + Create helper > Group > Light group
So I grab my sensor data, add the date I want and then use that as the sensor for the cheapest_energy_hours macro.
Which attributes does it provide?
- Current Price
- Unit
- Currency
- Region
- Region code
- Tomorrow valid - indicates if it has prices for tomorrow already.
- Today - 24 prices, one for each hour
- Tomorrow - 24 prices, one for each hour
- Raw Today - 24 prices including the datetime
- Raw Tomorrow - 24 prices including the datetime
- Today min
- Today max
- Today mean
- Tomorrow min
- Tomorrow max
- Tomorrow mean
Okay, so the raw_today and raw_tomorrow are the ones you want to use (and are used by default)
Oh wait
I get this error though: UndefinedError: 'dict object' has no attribute 'start'
Which I assume means it's trying to find a start value.
Ah wait, I didn't read properly
The raw_today entries have a "hour" key and "price" key.
Should I do time_key="hour"?
Hi @hallow cove and thank you! I'm aware of this manual approach, but I'd like to have my groups be automatically updated whenever I add lights to an area. I haven't found anything in the hass documentation or forums on how to create light groups through a service call, nor can I find anything about templating within the configuration file. Do you know if this can be achieved?
Alternatively - I'd like to just control all lights within one area with the mushroom light card - but I haven't found a way to do so either
Most probably
Okay, that did the trick, sorry to be wasting your time @marble jackal
I'm fumbling a bit here.
I added time_key="hour", value_key="price" and it now works.
I imagine you can check if the key exists and then manually throw an error. I can try and give it a go and make a PR if it works.
Adding lights to an area or group is a manual approach as far as I know so I would create a group light, put that group light in an area and every time I add a new light I add it to the group instead of an area.
ok -- per suggestion elsewhere, how would I clear/reupdate a template sensor
@inner mesa is prolly getting ready for a beer lol
hmm
better. How can I modify this to accomplish that:
{{ expand(volume) |sort(attribute='last_updated', reverse=True)|map(attribute='entity_id')|first|default }}
i know it'll be something with the last_updated attribute
ope -- found it
Already added it in v2.1.0 now
Ah, awesome, thanks!
My first automation has been set up, going to be interesting to see if it works. π
Alright friends, I've got a template that works... until I restart HASS. Despite the fact that the button keeps the last time it was pressed as persistent, the template shows the last time that HASS was restarted. Any ideas?
{% set last_changed = as_local(states.input_button.gus_fed.last_changed) %}
{% set current_time = now() %}
{% if last_changed.date() == current_time.date() -%}
{% if last_changed.hour < 12 -%}
{% if current_time.hour < 16 -%}
<ha-alert alert-type="success">Gus was given his breakfast at {{ last_changed.strftime('%I:%M %p') }}</ha-alert>```
I've truncated the snippet to avoid the bot eating it. The logbook shows "October 3, 2023 at 6:26 AM triggered by service Input button: Press 6:26:09 AM - 8 hours ago - Supervisor" as the last event for the button, but the template is showing the last time HASS restarted as last_changed
EDIT: The solution that I found is here: https://community.home-assistant.io/t/persistent-version-of-last-changed-for-the-ui/467163/67
Maybe store the time in an input_datetime?
this line, taken from my template sensor, seems to update at a willy nilly interval... is there a way to make a template sensor update at a smaller interval?
{{ (x[0].entity_id if now() - x[0].last_changed < timedelta(seconds=1) else '') if x | count > 0 else '' }}
that template will update once a minute on the minute, or whenever your reference entity(s) updates
hmm. is there a way to make it update, say 0.5s after the reference entity updates, or is there a way to do it with an automation?
You have to add a trigger to tell it what to look for
not sure why you'd need that. it won't change the state
what are you trying to do with this template result?
big picture
change volume on media player
yes
so why not just sort by last_updated
er, last changed
basically, what I'm saying is, 9 times out of 10, there's better ways to achieve your goals
no no no .... i am the best at everyting. π€£
genius lives in that 10%
are you just trying to play announcements at a volume level and have it return to the previous level?
no, its for multiple input_numbers (volume controls) for the media players in our house
so if the input boolean is on, when you press a volume up the matching media players only increase volume levels?
FYI these are the kind of descriptions we are looking for when we say "what's the big picture"
so that big stupid 'overly complicated' π @inner mesa template that we finally figured out the other day??? It's kindof related to that. so when the last input number is changed, it will change the volume on it's corresponding media_player
why not just make a template number for the media player?
?
like a tempalte number that adjusts the current media player
I'm just trying to figure out what you're trying to do
because it seems way too complicated
and i'm the king of complication
big picture; "base" scripts and automations, and "template" configs that contain the needed entities (timers, booleans, etc)
to do...?
alarm clocks, multi-room audio, seperate radio players, etc.
ok, so your templates "auto find" things?
just curious why you aren't just making parallel 'base scripts' that accept variables
with an automation that just fires based on the derived input
uhhm, I guess you could kindof say they auto find them ... mostly just the last entity used for the groups
Yeah, but why even have the groups
thats actually what i am doing with the variables
so, you have something that triggers, you pass the triggering entity_id around to various scripts that do things you want them to do
w/ parallel automations
correct
right
you're welcome to see what I mean by looking at my automations and scripts
I exclusively do this
makes maintaining automations typically a 1 line change when I add or remove something
right
thats basically what I have done
that template that we worked on let's me know (which kid) was the last to push a button or what not, and then sends the info to their device
push the physical button or in the UI?
ui
yeah, you can get that info without all that templating
using the context object
basically, get the user that clicked a button in the UI
well, that's actually what I thought I was doing
do your kids have logins for each screen they use?
no, just seperate dashboards
If you make them separate users, you can get the user that pressed the button
assuming this is a tablet in each room
if it's a shared tablet, then your templates will have to suffice
i had to split 1 tablet for the 2 oldest's room(s) so, I think that's what really sparked it this way
which, leaves me with templates
Yep, so basically you just want to have the UI for each kid adjust thier media player?
basically
and with 3 kids, a guest room, the livingroom, outdoors, office, and master suite ...
sounds like a script that takes an input for the current media player and the resulting volume level. A template inside an automation that determines which inputs are being used
the route you're going is going to have problems if they are all adjusting at the same time
it's easier to copy pasta the essential entities and then push them
I did think of that, and although it is possible, i may just have to accept the possibility that it happens
right, but you can avoid that all together by going a different route
have an automation that looks at the controls that change that will determine what entities to adjust. Not based on time, simply based on what is triggering.
it's a rock solid approach.
it involves templates, but not "guessing"
not to mention, you wont have to name your entities crazy names to get the job done
just make a configuration that links them in 1 spot
no groups
I think, though I might be wrong, I have a hybrid of that idea
lemme see if I can put the alarm clock contraption I have up on github and maybe you can see better what I mean.
I'll have to take a look at that in the morning and get back to ya
thats fine... Im always up to do something more efficient
I already see some improvements that should make things easier, family time now tho
i get it. thanks
Is there a way to do something like this:
{{ state_attr('weather.kphl_daynight', 'forecast') | first | .detailed_description }}
I'd like to access the detailed_description attribute of the dict that is passed in after first.
{{ (state_attr('weather.kphl_daynight', 'forecast') | first).detailed_description }}
thats exactly what I need. Thanks for answering!
You bet
Is there any way to make it so when a template goes unavailable, it retains the last value it had instead of going unavailable?
Actually, just to prevent any XY problem issue, right now I have a template to get the time where it's cheapest to start my dishwasher. However, at midnight it stops working because the source sensor doesn't have all the data it needs anymore. But if the time was after midnight, it then doens't trigger the automation I have setup because it goes from like "3 hours until" to "unavailable".
What's your full code for the template sensor now
{% from "cheapest_energy_hours.jinja" import cheapest_energy_hours %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_key="hour", value_key="price", look_ahead=true, include_tomorrow=true, end='14:00') }}
The issue is, my sensor.energi_data_service doesn't have a valid raw_tomorrow attribute until sometime after noon. So at midnight the raw_tomorrow attribute disappears.
Right now, the code above gives the following error
TypeError: can only concatenate list (not "NoneType") to list
It worked fine as long as it hadraw_tomorrowavailable.
Would it make sense to conditionally include the include_tomorrow=true depending on time of day so the sensor just always works, maybe?
Rather than retaining a value from 12 hours before, basically
Ah, that's a good point, I guess I could configure the include_tomorrow to only be true if raw_tomorrow attribute exists.
(TheFes will probably have a better/ideal solution, but that's what popped out to me)
Something like this maybe
{% from 'cheapest_energy_hours.jinja' import cheapest_energy_hours %}
{% set do_include_tomorrow = 'raw_tomorrow' in states('sensor.energi_data_service') %}
{{ cheapest_energy_hours('sensor.energi_data_service', hours=3, time_key="hour", value_key="price", look_ahead=true, include_tomorrow=do_include_tomorrow, end='14:00') }}
According to the developer tools, it's listening to updates in time and updates from the sensor.energy_data_service.
So it should recalculate the value as soon as raw_tomorrow becomes available.
I think states(...) doesn't return attributes, just a string of the main state, but otherwise that approach seems to make sense to me
Ah, I need to check that when raw_tomorrow become available.
I see a state_attr function, maybe I need to use that.
Yeah, that or is_state_attr probably, if the "missing" value of that attribute is something consistent (that you can throw a not in front of)
Yeah, makes sense.
I'll test some more when raw_tomorrow is available, appreciate the help.
That's only the template itself, I meant the full YAML
Oh, for the automation?
@sudden wraith I converted your message into a file since it's above 15 lines :+1:
This is how I set it up, essentially, at the time of the cheapest_energy_hour, check if the door is closed, then turn on the dishwasher, wait a bit, then start the eco50 program before finally turning the automation off. Then the plan is to have a different automation that turns this one on again if the dishwasher is opened and closed again.
To avoid it running additional times after the first one.
It might be better if you ask specific questions on this template in an issue on GitHub, as it's quite difficult to answer for people who don't know what the macro does
Yeah, that makes sense.
No, for sensor.dishwasher_start
This gave me a sensor that holds the running total for the costs I would have paid if I did not have my solar installation. i.e. by calculating hypothetical_cost - cost_for_grid_in + compensation_for_grid_out all at the same time stamp, I can now determine when my solar system has paid for itself and how much I'm winning (or losing?) from having it. I also have one for the total of the compensations I would have received had I fed all generated solar energy into the grid, just in case I want to do some other calculations at a later time (most likely related to a battery).
Is there any way to filter entities in an array of areas?
i.e. to get all the entities from areas: ['Living room', 'Kitchen'] without using {% for ... etc.
Yes, using area_entities
area_entities accepts a string not an array... I need a filter that uses the array and not have to repeat for each element, using a for
{{ ['Family Room', 'Kitchen']|map('area_entities')|list|join }}
hmmm clever! thank you
I, personally, would have made area_entities smarter by figuring out what it's provided and working with it, but π€·
Having the area as attribute in the entity would be more helpful... We are moving slowly to area (room) based automatizations
also is there any way for the filter | selectattr('state', '>', 2) to work properly and continue filtering after that?
### Chip Power Consumption ###
chip_power_consumption:
template:
- "chips"
- "ulm_translation_engine"
triggers_update: "all"
label: |
[[[
var amount = variables.ulm_chip_electric_price != "" ? true : false
if (amount){
return "β‘ " + states[variables.ulm_chip_electric_price].state + variables.ulm_translation_currency;
} else {
return "β‘ " + states[variables.ulm_chip_electric_consumption].state + states[variables.ulm_chip_electric_consumption].attributes.unit_of_measurement;
}
]]]```
I am trying to limit states[variables.ulm_chip_electric_price].state to 2 decimal places - any tips on how to do this?
also, what do the [[[ and ]]] brackets mean? I cant find any documentation on them, only the curly brackets?
[[[ and ]]] I believe are javascript templates for custom frontend cards. It's not technically part of home assistant, so that's why you don't find any documentation.
it would be documented hopefully in whatever custom card you're using them in
I would use
{{ ['Family Room', 'Kitchen'] | map('area_entities') | sum(start=[]) }}
Only using a for loop
Ah thanks - its from the lovelace minimalist UI so will look there
@thorn harness I converted your message into a file since it's above 15 lines :+1:
@thorn harness there's really a lot wrong there, this might work
conditions:
- condition: template
value_template: >
{{ now() - this.attributes.last_triggered > timedelta(minutes=min_update_minutes) }}
- condition: template
value_template: >-
{% set number_entity = device_entities(ally_device) | select('search', '^number.') | list | first %}
{{ ((states(number_entity) | float(0) - states(temp_sensor_id) | float(0)) * 100) | round | abs > 10 }}
I assumed there is only one number entity in that device
thank you π
i have this now: https://paste.debian.net/1294025/
but it gives me error: Failed to load blueprint: while scanning a simple key in "/config/blueprints/automation/bnapalm/danfoss_trv_ext_temp_z2m5.yaml", line 66, column 5 could not find expected ':' in "/config/blueprints/automation/bnapalm/danfoss_trv_ext_temp_z2m5.yaml", line 70, column 48
seems to be a formatting issue?
look at line 66
you have a stray '
you can tell from the color of action: that the problem was just before it
there seem to be a lot of issues in there π i looked at yamlchecker.com
didnt knew that before
are there some auto debug tools available?
@warm elbow I converted your message into a file since it's above 15 lines :+1:
i got it error free now, but now when i want to create an automation, its tells me extra keys not allowed @ data['conditions'].. :\ https://paste.debian.net/1294038/
believe you need condition: not conditions:
lol. that was it π THANK you! π
In both cases, it pointed to the error
now i hope, it works as it should
hm, it does not work :\ the conditions will not match in automation
Error: In 'template' condition: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'
condition: template
value_template: >
{{ now() - this.attributes.last_triggered >
timedelta(minutes=min_update_minutes) }}
Error: In 'template' condition: UndefinedError: No first item, sequence was empty.
condition: template
value_template: >-
{% set number_entity = device_entities(ally_device) | select('search',
'^number.') | list | first %} {{ ((states(number_entity) | float(0) -
states(temp_sensor_id) | float(0)) * 100) | round | abs > 10 }}
Ah, you need to account for the first time it triggers
what does that mean?
condition: template
value_template: >
{{ now() - this.attributes.last_triggered | default(as_datetime(0), true) > timedelta(minutes=min_update_minutes) }}
The first time an automation triggers there is no value in the last_triggered attribute, it will be none
ah okay
So it will compare the current time with none which will result in an error
okay, that makes sense π
but second will also not match
i tried this now, but also not works
I made it a bit shorter
It will not get to the second condition if it fails at the first one
Please format your code as code
To format your text as code, enter three backticks on the first line, press Shift+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.
ah okay, first condition now works
second not
Error: In 'template' condition: UndefinedError: No first item, sequence was empty.
maybe its because, there are several number.* entity names from that thermostat? Maybe its possible to exactly filter and match that "number.tcv_badezimmer_external_measured_room_sensor" ? The first match is maybe "number.tcv_badezimmer_algorithm_scale_factor" i think?
It doesn't select number entities anymore after your change
but how does it know which one it should take?
Oh wait, you changed it again
i mean: there are several number.* entities.. i think, it does not know which to take
Or not, I'm confused, you had something else earlier
I also don't know π you need to provide the information on what the template should filter on
ah okay. π i need the number.tcv_badezimmer_external_measured_room_sensor" number.*_external_measured_room_sensor"
I'll have a look tomorrow, I'm going to bed now
np π will do so too. thanks very much for your help π
@mighty ledge - I wanted to let you know that I think I may have found a better solution to my setup that doesnt require as many templates
I changed up one of the automations I was using to listen to state changes of a sensor with the template that we dont talk about. Instead of listening to the template sensor, I fired up the event bus
is there a better way to do this:
https://hastebin.com/share/uxoqiyuvuf.csharp
You could put the seasons/temperatures into an associative array and use it as a lookup (would require turning to integers)
Basically {% set temperatures = { "summer" : [ "cold", "cold", "warm" ] } %} etc, and then {{ temperatures[season][temperature] }}.
(might want to do max(min(temperature-20, 9), 0) or something so you don't have to store an absurd number of values)
Should point out though that your <22 <25 >25 scheme means if your value is exactly 25 it won't match.
Try {{ (25.0|float) < 25 }} and {{ (25.0|float) > 25 }} in the template editor, both return false. Should make one of those <= or >=
Can't necessarily offer you better, certainly different though π
Ok, let me write out the whole thing
So something like this
"summer": [ "Cold", "Cold", "Cold", "Warm", "Warm", "Warm", "Hot", "Hot", "Hot", "Hot" ]
} %}
{% set season = states('sensor.season_astronomical') %}
{% set temperature = states('sensor.living_room_feels_like_temperature')|int %}
{{ feels[season][min(max(temperature - 20, 0), 9)] | default("N/A") }}```
The -20 means the first element in the array is 20Β°C, second 21Β°C
Just saves a lot of repeated lines
Ohh I see! so it goes up to 29 - how can I make it go above that?
Just put more entries in the array and adjust the numbers, but the min(max( means anything above 29 will be the 29 value, and anything below 20 the 20 value
oh wow thats really cool - let me test it out. thanks so much
'mornin y'all
when doing {% if x and y in z %} is that the correct syntax or should it be {% if x in z and y in z %} ?
'asking for a friend'
how would I do the multiple seasons though?
I beleive it to be the latter
corect
Hello and thank you π I think it is giving me erros "Message malformed: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'integer') for dictionary value @ data['variables']['max_update_minutes']"
Sorry, was pretty sick yesterday, couldn't think straight
do't worry about it
May someone could take a look what could be wrong there? With yaml-checker i didnt find any problems.. Got this error message: (TemplateSyntaxError: expected token 'end of print statement', got 'integer')
line 43, you're missing an else before 30
nice, thank you π
You're welcome
Quick question. If I use a template as a trigger in an automation, will it trigger as soon as the value of the template changes? For instance, if an entity within the template changes a value, will the template change its value immediately, or is there some delay?
it depends on the template
template triggers only trigger when the template resolves false, then later on true
so that's the first caveat
templates in general resolve whenever the source entities change state
there is a throttling that occurs in order to keep computation heavy templates from running frequently
Ah okay.
that throttle only occurs when you use states as an object. I.e. states | selectattr(.... In cases like this, the template will update on every state change, however it's throttled to at most 1 resolution per minute.
if you use the states.<domain> object, the throttle is at most 1 per second
if you use a list of entities, without using the above objects, everything will be instant and live w/o throttling
Okay. I think it reacts within 1 second here and that's exactly what I want.
Thanks for the explanation!
np
Well, if that guy who had half hour dynamic prices ever comes back, my macro now supports that (it supports any dynamic price period now, so if energy providers start updating them every minute, it should work)
not tested though, my test sensor had quarterly changes
Just add them to the set:
{% set feels = { "summer": [], "autumn": [], "winter": [], "spring": [] } %}
dictionary, not set
I couldn't remember the word jinja used. I still write probably more perl scripts than is necessary, was trying to think of the word that wasn't "hash"
Not sure if this templating, but using a filter entity I can get a time weighted average over 24 hours that has a numerical value that differs from using the "Average Sensor" HACS integration. Is this just a difference in how the averages are calculated, or is TWA not doing quite what I thought it would do?
For background: I'm trying to calculate local AQI using an air quality sensor and for this, I need a 2.5 particulate sensor averaged over 24 hours
could this be made faster?more efficient? If I check the dev templates, it states to listen to all 120 integration entities, while I had hoped it would only listen to the 20 power entities... {% set outlier = states('sensor.power_zonnepanelen_outlier')|float(0) %} {{expand(integration_entities('solaredgeoptimizers')) |selectattr('entity_id','search','power') |map(attribute='state') |select('is_number') |map('float') |select('<',outlier ) |list |count > 0 }}
you could create a group with only the power entities as members
yes, I considered doing that, and it would also be helpful for the other challenge I am facing in creating several statistic sensors for those same entities.. yet I always try to minimize groups (since these need to be updated continuously also). last resort would be listing them inside the template itself I guess... {% set outlier = states('sensor.power_zonnepanelen_outlier')|float(0) %} {{expand(['sensor.power_1_1_20', 'sensor.power_1_1_19', 'sensor.power_1_1_18', 'sensor.power_1_1_17', 'sensor.power_1_1_16', 'sensor.power_1_1_15', 'sensor.power_1_1_14', 'sensor.power_1_1_13', 'sensor.power_1_1_12', 'sensor.power_1_1_11', 'sensor.power_1_1_10', 'sensor.power_1_1_9', 'sensor.power_1_1_8', 'sensor.power_1_1_7', 'sensor.power_1_1_6', 'sensor.power_1_1_5', 'sensor.power_1_1_4', 'sensor.power_1_1_3', 'sensor.power_1_1_2', 'sensor.power_1_1_1']) |map(attribute='state')|select('is_number') |map('float') |select('<',outlier ) |list |count > 0 }}
but would the latter be more efficient (than a group)? given the number of entities, I feel I need to be careful
Why expand them first and then immediately take the states
You can use | map('states') on the list of entity id's to get the same result without the need to expand them to full state objects
If you need them in multiple places you could also create a list in a jinja file in custom_templates and import that
My withing sensor goes unknown when the server restarts at night or during the day until I get in bed or out of bed. I've made a template sensor to show In or Out depending on a few other sensors so that my morning and night time automations still work properly:
is_state('input_select.bedroom_status', 'Sleep') | iif("In",
is_state('input_select.bedroom_status', 'On') and now() - (as_datetime(state_attr('sensor.bedroom_tap_switch', 'last_triggered')) < timedelta(minutes = 60)) | iif("In","Out"),
is_state('binary_sensor.withings_in_bed', 'on') | iif("In","Out")
))
}}```
but I am getting error TypeError: '<' not supported between instances of 'datetime.datetime' and 'datetime.timedelta'
last_triggered: 2023-10-06 08:07:48.680679+11:00
this works by itself: {{ now() - as_datetime(state_attr('sensor.bedroom_tap_switch', 'last_triggered')) < timedelta(minutes = 60) }} so I don't get why it doesn't work in the full code
Your parens in the full code are wrong, I think
The now() is outside the parens so it tries to compare the raw time and the delta rather than producing a delta by subtracting from now() and then comparing the two deltas
So I think if you move the paren just before as_datetime to just before now() that might do it
could also include them in another set of parens
you're trying to get just the delta, correct?
or as_date_time(delta)
thank you! {{ is_state('binary_sensor.withings_in_bed', 'unknown') | iif( is_state('input_select.bedroom_status', 'Sleep') | iif("In", is_state('input_select.bedroom_status', 'On') and (now() - as_datetime(state_attr('sensor.bedroom_tap_switch', 'last_triggered')) < timedelta(minutes = 60 )) | iif("In","Out")), is_state('binary_sensor.withings_in_bed', 'on') | iif("In","Out")) }}
got it to work π
Hi there, I am looking for a way to put the set point of a thermostat into a value field only if it was changed manually (either in the app or on the physical thermostat) but not by an automation ... is there an easy way to achieve that ?
You can look at the context. See the bottom of this page in the docs:
https://www.home-assistant.io/docs/configuration/state_object/
Also here is a good example:
https://community.home-assistant.io/t/state-context-to-ui-automation/427861/24
Hi all, anyone that can help me out? The deprecation of the forecast attribute broke my template sensor. previusly i was using:
{{state_attr('weather.dwd_weather_berln', 'forecast')[1]['templow']|int}}
as part of a larger more complex sensor for my epaper display. I somehow cannot wrap my head around how I can adapt to make use of the weather.get_forecast service in this
Full code is here https://hastebin.com/share/owanojinot.csharp
Nothing will be broken for 5 months
Deprecation isn't removal (yet)
It's fine to adapt early, but you have time
Mhm i see but somehow all sensors became broken as of the last update. Maybe the custom integration Deutscher Wetterdienst dwdremoved support
Ex14 ζε I converted your message into a
My receiver and TV get power(230v) in the morning when waking up. But I need to reboot a kodi box once for sound to work.
My wish:
when TV turns on with remote(LG integration/ easy), but only for the first time today, then reboot Kodi box.
The question is about the "do it, but only once today"
I was thinking a Boolean helper that resets after midnight, but maybe anyone has a more clever idea?
How does the Riemann Sum sensor work if I'm using a template helper sensor to calculate wattage of something, but one of the values doesn't update if the value itself doesn't change? Will Riemann still work over time? Or should I put a time trigger in the template too to force it to write a value? Example being {{ states('sensor.ups_load') | int /100 * states('sensor.ups_nominal_real_power') | int }}
In this example, sensor.ups_load is a % age load, but if that load is constant, the state of the sensor will only update when it changes (the other sensor is a constant).
The docs for Riemann mention that the method should be left if you expect values to stay the same, is that all that's required?
if they don't have the forecast attribute, you either need to use the service call, or just revert back to the previous version in which the forecasts are still included
all core integrations will have the forecast attributes until 2024.3
sorry I missed this , but I believe Ive just done just that? {% set mean =states('sensor.power_zonnepanelen_gemiddeld')|float(0) %} {% from 'optimizers.jinja' import opti_power %} {{expand(opti_power) |map(attribute='state')|select('is_number') |map('float') |select('<',mean/2 ) |list |count > 0}}
and woth the map states: {% set mean =states('sensor.power_zonnepanelen_gemiddeld')|float(0) %} {% from 'optimizers.jinja' import opti_power %} {{opti_power |map('states')|select('is_number') |map('float') |select('<',mean/2 ) |list |count > 0}}
guess theres no way around mapping the full object when I want to do this in the attributes: {% set mean =states('sensor.power_zonnepanelen_gemiddeld')|float(0) %} {% from 'optimizers.jinja' import opti_power %} {% for o in expand(opti_power) if o.state|float < mean/2 %} {% if loop.first %} {{loop.length}} Optimizer met problemen: {% endif %} {{o.name}}: {{o.state}} {% else %} Alle optimizers ok {% endfor %}
{% set mean =states('sensor.power_zonnepanelen_gemiddeld')|float(0) %}
{% from 'optimizers.jinja' import opti_power %}
{% for o in opti_power if states(o)|float < mean/2 %}
{% if loop.first %} {{loop.length}} Optimizer met problemen: {% endif %}
{{states[o].name}}: {{states(o)}}
{% else %} Alle optimizers ok
{% endfor %}
I mean, yes... but there's also the literal message right above it which is definitely #templates-archived.
@mighty ledge any idea what would cause this issue (don't spend a lot time on it, just wondering if you can tell where ValueError: Undefined is not in list would come from)
Ya, Iβll take a look a bit later this morning
On the surface, I would assume youβre running a filter where the object youβre checking for is undefined.
I.e you have a dictionaryβs value as the βsearchβ param in the test/filter
Thanks, I will try to figure out how I can do that, seems to be what I look for ! π
Ok, seems to work for the condition, but now, how can I grab the temp that was set into the thermostat to copy it into a number helper ?
Which is unrelated to your issue. If you sensor does not update, no matter what kind it is the Riemann Sum will not update. That's how the integration works.
Assuming you are using a state trigger to trigger on the change of the target temperature attribute of your climate entity:
action:
- service: input_number.set_value
data:
value: "{{ trigger.to_state.attributes.temperature | float }}"
target:
entity_id: input_number.my_helper
Yo, just looked into more
it's 100% his error not yours
I put details in the issue that point to the problem (which you found first but may not have realized it)
Thanks!
So what you're saying is that the problem is actually with the #templates-archived as the template sensor doesn't have a time trigger to update it, instead relying on changes to the state? I'm confused.
Or would adding a time trigger do nothing if the state hasn't changed?
Youβre seeing an issue common to many integrations that operate off other sensors. Hereβs a workaround you can use. The issue you are having is definitely an #integrations-archived issue but the workaround is to use #templates-archived
And a time trigger by itself, as you guessed, would do nothing.
https://github.com/home-assistant/core/issues/83496#issuecomment-1724688024
Yeah cool, TYVM for confirming! I'm still not entirely sure it is an issue though for Riemann sum specifically with left mode. I think [my logic here](#energy-archived message) checks out because it's not that the sensor isn't updating - it's that the value returned isn't changing (intentionally). And from what I understand of how that formula works with left mode, it grabs the last value multiplied by the time delta when the value changes.
yeah no
that's how left is calculated
the issue is that your sensor isn't updating so left pulls the area under the curve, i.e. by design
it's a flaw in the 'only provide updates when things change' system that HA has implemented
it also affects the derivative integration as well
or any other integration that performs calculus
Itβs hard to know whatβs going on in your graph, the images you posted, as karwosts mentioned, are the statistics which are updated every 5 minutes. You have to click on βshow moreβ to see the plot of the data that is actually in the states table of the database. Iβm still not clear if youβre having the issue you think you are having
here's a detailed description of the calculation -> https://community.home-assistant.io/t/calculating-watts-kw-and-kwh/173250/3
But isn't that just confirming what I said. Say that parent sensor returns exactly 0.2 for 2 minutes, refreshing every 5 seconds, then it returns 0.25 at 2m 5s. The first change to that template happens at 2m 5s, but the state from 0s to 2m is still correct, it just hasn't changed.
you're saying the flaw is in the calculation
which is wrong
the flaw is in the design of the system
and it can't be changed
calculus is calculus and the formula for left is implemented properly, the problem is how HA handles state changes
And again: #integrations-archived
In HAβs world, the sensor had 0.2 at 0m0s, and 0.25 at 2m5s. Nothing happened in between. There was no refreshing every 5 seconds. Not even for the parent sensor itself. Regardless that the parent sensor is attempting to push its same state every 5s.
I created a sensor for my Garbage day collection and my goal is to try and display in whole numbers the amount of days until collection. Then on the day of collection, show "today",
Is this possible? Here is the template I've created:
{{ (state_attr('calendar.garbage','start_time') | as_timestamp -today_at('00:00') | as_timestamp) / 86400 }}
Also, do we know how to change it as a whole number as opposed to decimals? I can't find a precision drop down on the sensor helper config
I think if you want a precision selector it has to be a numeric type sensor, either by giving it a uom or setting a numeric device class.
sorry you lost me there... you mean create a different type of sensor? Or can I not create that type of sensor with the way I've created this sensor?
no it's still a template sensor, but if you don't assign the template a device class, and you don't assign it a unit_of_measurement, than I believe it's just treated as a "string" type sensor, and it doesn't show a precision selector.
got it. Unfortuantely "days" is not a UOM
uom can be any arbitrary string
that's a win!
Thanks for that... not sure why I didn't think to just type in days
Now I just need to figure out how to display this into my dashboard
I just used a markdown card myself
{% if now() >= state_attr("calendar.garbage", "start_time")|as_datetime|as_local %}
<ha-icon icon="mdi:trash-can"></ha-icon> Current Trash: {{ state_attr("calendar.garbage", "message") }}
{% else %}
<ha-icon icon="mdi:trash-can"></ha-icon> Next Trash: {{
state_attr("calendar.garbage", "message")
}} in {{
((state_attr("calendar.garbage", "start_time")|as_datetime|as_local
- now()).total_seconds() / 60 / 60 / 24) | int + 1
}} days
{% endif %}
You should have put out the trash yesterday
My weeks alternate yard waste vs recycling, so that updates the message.
A bit more flexible than trying to cram it all into a single sensor.
yes can use any string, but "d" is a recognized UOM: https://github.com/home-assistant/core/blob/d7ac4bd65379e11461c7ce0893d3533d8d8b8cbf/homeassistant/const.py#L414C5-L414C5
I have a sensor template like this:
- trigger: - platform: state entity_id: binary_sensor.alarm_sensorbb0017 to: "on" id: "off" - platform: state entity_id: binary_sensor.alarm_sensorbu0017 to: "on" id: "on" binary_sensor: - name: sensore_stairs_state state: "{{ trigger.id }}"
how can I add device_class? I need the state open/closed and not on/off
you just add it... device_class: opening or door
Are templates in service calls somehow more restricted than in other places (i.e. the template tester in the dev tools)? I can't get to work a templated service call, but if I copy the resulting yaml from the dev tools, it works as expected.
Are you trying to template the service call name itself? I believe you can template the data section there now (used to not be supported), but I don't know about the service name
Nope, just the data section. It does work in other, simpler automations, where I only insert some values here and there. I am trying to fill a list with a for loop, maybe that is too complicated.
Shouldn't matter how complex they are. A template is a template
That's what I thought as well
Share what isn't working there
@limber trench I converted your message into a file since it's above 15 lines :+1:
You're trying to construct the YAML representation of a list and you should construct and output the actual list
Ah alright, so HA is taking the value of "payload" as a string and templating it separate from the whole service call? I was expecting it to do the whole service call as one template, not every attribute separately. Will try, thanks!
It has to end up in the format that that service call is expecting, and what you're trying to provide is a YAML representation of a list. I don't know what it's actually looking for
It is expecting a list indeed
Thanks a bunch @tardy cipher, putting it into the payload: >- and outputting the list did the trick!
Dear experienced users,
I started my HASSIO 2 month before and now I'd like to extend some things in YAML/JINJA/PYTHON. Found already some API documentation Could you please direct me to a good entry point? I am bit familiar with Jinja2, have an idea about Yaml and are interested in learning Python (until today, I only have plenty experience in C, C++, bash).
What I am searching for is to understand concepts, f.i. "your yaml code will be called by XX if you name the callback YY and place it in file ZZ" as well as "An entity is always a python class consisting of ... value ... physical unit and time stamp (?) and you can/not transform it to another type because ...".
Any suggestion where to find? Or how did you started your learning?
start with the developer documentation
Thanky you, @mighty ledge for directing me to https://developers.home-assistant.io/ - it looks exactly like what I need to read.
Aside of this, I also found https://hacs-pyscript.readthedocs.io/en/latest/ which is for (unsupported but mighty) HACS extension. Just in case others or myself are asking again.
just noticed the developer tools > template accepts caps letters ;
sun is {{ states("SUN.SUN") }}
Yes the states method slugifies the entity_id
that is tricky, cause like my templates were OK with some caps, but my automation were not able to find the entity because of the caps
was easier to spot after a good night
I'm seeing odd results in a template with {{ states(....) or states(....) }} (two binary sensors) - the 'or' doesn;'t look at the second sensor at all, only sees the first one. + concats both... This behavior changed a couple of months ago - it used to work. Interestingly, making the two states() assignments instead of direct causes both to show in 'entities' but now only the second one shows in the 'or' condition instead of the first. Strange...
How can I make an automation run 30 minutes before this time?
entity_id: sensor.sunrise
state: 2023-10-07T05:18:17+00:00
device_class: timestamp
And state is autoamticly updating so it should refer to state - 30 minutes
Not really following that. Are you just describing short circuit logic? If the first test in an 'or' is true, it doesn't look at the second one
And your statement implies that you're just outputting true or false, not a concatenation of the two states
Try {{ is_state(..., 'on') or is_state(..., 'on') }} or {{ states() | bool or states() | bool }}
States are strings, not booleans
And strings are always true
I can't imagine that behavior changed, or that it was what you wanted before
{{ "foo" if "bar" else "blah" }} -> foo
{{ "foo" if "false" else "blah" }} -> foo
π
templates provide endless satisfaction
I think empty strings are falsy? But I'm not sure states() can ever return an empty string anyway
Empty strings are falsely. But I think an entity with an empty string as it's state will report unknown. Not completely sure on that though
@next forge I converted your message into a file since it's above 15 lines :+1:
Any thoughts?
Wow years of using expand and I just realized it actually expands the entities listed for a given entity's entity_id attribute (e.g. groups with a list of entities listed under it's entity_id attribute). Maybe this is its purpose, but I always thought it just "expanded" a entity_id to be a state object.
This just made what I thought was going to be a difficult hack into a 1 line addition to a template lol
Hiho, I have a MQTT sensor implemented into HA. It provides the values properly (under tools - states) but I saw this right now in the logs and can not get it, why the error is thrown: Error while processing template: Template<template=({% set t = states('sensor.zaehler_waermepumpe_netznutzung') | float %} {% set s = states('input_number.heizstromzahler_vorwoche') | float %} {{t - s}}) renders=2>
it seems that this error is independant from the mqtt sensor and also related to other templates which calculates a value
Post the full error
http://pastie.org/p/3BaUpxxfPhOtiW2AGL3f9E this is a full error and this is the template sensor http://pastie.org/p/20Po1gUL8ORNg4XPpb3CJe
The issue is that eg just after a restart the template is rendered before your source sensor is loaded yet
Add a default to the float filters or add an availability template
I prefer the latter
I try the availability, thanks!
Can i use the availability also in a calculation sensor?
In this case I would use:
availability: "{{ states('sensor.ccu3_sv_svenergycounter_3_7') | is_number and states('input_number.vortag_ankleidelicht') | is_number }}"```
Thanks!
states('sensor.ccu3_sv_svenergycounter_3_7') | float(0) <<<< This is the first way, to add a default you mentioned, right?
Sorry, dont get it
Yes, that's the first way
Interesting. Because it still complains about the unknown value.
Im gonna wait a bit maybe it fog clears later bettee
Are you sure you're not looking at old log messages
And what is the code for your template sensor now
With the Alert integration, can the state be templated? The docs show relying on a templated binary sensor (for battery below 10%) to be true for the alert to trigger, but the message can accept a template.
If the state can be templated, wouldn't negate the need for the binary sensor?
Hello,
I need help to integrate my roller shutters (Tuya TS130F) inside my home assistant board. I created a cover in my HA configuration file but for example getting position from the percentage does not work. Does anyone know anything about templating with this module (https://www.zigbee2mqtt.io/devices/TS130F.html#tuya-ts130f)
I have this code, basically I need it to set a time to charge my car, then the next sensor to take 4am then minus off the time to charge, but it just says unavalable. https://paste.debian.net/1294428/
{{ start_hour|round|int ~ ':' ~ "%02d"|format(start_minute)|int }}
{{ start_hour|round|int ~ ':' ~ "%02d"|format(start_minute|int) }}
Closing parenthesis was out of place
I'm sure this was clear from the logs
Hi guys, Iβm doing template sensor which is trigger based. It update the value at fixed time at night. However instead of mentioned time in sensor it is running after 5 to 10 or minutes.
template:
- trigger:
- platform: time_pattern
This will update every night
hours: 0
minutes: 0
sensor:
Keep track how many days have past since a date
- name: "cost"
- platform: time_pattern
Or you do
{% set hours_required = states('sensor.time_to_charge_to_100')|float %}
{{ (today_at('04:00') - timedelta(hours=hours_required)). strftime('%H:%M') }}
Thanks, can you me understand how it working.
@main mango To format your text as code, enter three backticks on the first line, press Shift+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.
This one I have to set under template sensor.
Hi guys! I am looking for inspiration for a daily counter. I have a voltage detector on a pump which returns boolean on/off and I have calculated the flow rate of this pump in advance, this is a fixed number; let's say 1200l/hour.
How can I make a card that shows how much has been pumped that day, which updates on the spot as long as the pump is running and resets daily?
seems like this is a starting point: https://www.home-assistant.io/integrations/history_stats/
Hi, Is there any way to use templates for making the 'name:' in apexcharts-card dynamic?
Still getting the same problem, really confused with this now
Probably not Jinja templates. That's a question for #frontend-archived
I'll try there then
Are you sure this entity_id is correct sensor.time_to_charge_to_100
Did you test the template in devtools > templates
I did not realise I could
I'll try that
Weird, it works fine there
Ah!
UOM was set to time
Yes, that doesn't work
That should be the device_class
Which will be visible in the logs
Yes, I'm sure. Did I missed anything in my understanding of template availability? I get an error: http://pastie.org/p/76mgngVWWjmhinGTDhtUyv
That's not what I proposed to use for the availability template
its a different sensor, yes
The availability template should return true or false, not the same as the state template
It should be similar as this #templates-archived message
Check if all entities you use in your calculations are actually returning a numeric state
got it!
finally β°(Β°β½Β°)β―
Why is it not possible to have a device class energy and stateclass measurement? I mean, why cant an energy template which measures the consumption?
energy (Wh/kWh) is not an instantaneous measurement but a value that accumulates over time. the instantaneous measurement is usually power (W/kW)
but when currently consuming power (light on) the energy is also instantaneous increasing
atleast from a template which calcuates the daily usage. (this was my point of view)
A measurement is a value at a single point of time, like the current speed of your car, or the consumption of your house
Energy is not a value at a single point in time, but a value over time (an hour, a day, the total lifetime)
I'm struggling to understand MQTT. I bought some Shelly duo lights thinking I could add them to HA using the shelly integration but they don't support COINT like my shelly motion sensor I have. I believe I need to update my template to include the the lights but I'm having some trouble
What template?
my bad, the guide I was following stated to add the following to the bottom of the configuration.yaml
template: !include template.yaml
Then add the lights to the new template.yaml. Probably just overcomplicating it though

lol same...
you haven't shown a template yet
Trying to find that site that allows you to share code easier, forget the name
Shelly Duos are CoIoT capable, as well as MQTT. But that's an issue for#integrations-archived
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
thanks! https://dpaste.org/WFKjv#L11
Definitely not my code, I found my topics using the node red debug
What guide is that?
That's what I was following. Pretty dated
I'll see if someone can help me resolve the integration piece. It seems like it would be much easier to get it working with CoIoT instead
Too dated. The configuration for MQTT has been changed
And in your example, some topics still include the string "[friendly name]".
It's weird that I don't see the CoIoT section in the GUI for the bulb and there isn't a firmware upgrade available
I noticed that too, I fixed it
But nevertheless, that's not a templating issue
Got it. Thanks for checking! I'll bug someone in the integrations area.
This would be the new MQTT lights documentation:
https://www.home-assistant.io/integrations/light.mqtt/
Thank you!
But the CoIoT integration will be easier for you
The CoIoT settings are usually at the same place as the MQTT settings in Shelly's UI (eg.
"Advanced - Developer Settings")
yeah that's where it is on the motion sensor
Have you looked at the "Cloud" section?
I'll enable the cloud real quick and see if CoIoT shows up. I would like to stay away from using the cloud
Is it possible to populate group entities with a template that generates a list of entity id's?
CoIoT isn't available after enabling the cloud
Seems like this is the solution, but seems at least a tad bit hacky:
https://community.home-assistant.io/t/create-a-group-with-all-lights-and-more/367365/6
Can someone point me to an example of a "Trigger-based Template Sensor" (https://community.home-assistant.io/t/wth-are-there-no-variable-entities-in-ha/467548/15) that's simple, say a basic counter, like this https://github.com/rogro82/hass-variables/blob/master/examples/counter.yaml I'm trying not to have to pull in HACS to have to do this... Thanks
thanks
How can i template this android next_alarm sensor like 2023-10-10T05:15:00+00:00 to find out if its weekday or weekend?
I got this atm {{is_state('sensor.mobiel_marjolein_next_alarm', 'unavailable')}} But when set on monday till friday, it still renders true in the weekend
that sensor shows the next alarm, regardless if it is today, the next day or in 3 days
but to get if it is a weekday, you can use as_datetime(states('sensor.mobiel_marjolein_next_alarm')).weekday() < 5 if 'sensor.mobiel_marjolein_next_alarm' | has_value
This seems so basic but I can't figure it out. How do I extract a single attribute from a list of objects so I can use the list in a line graph or whatever. State in template sensors have a max of 255 characters and does not seem to be made to store a list/array but rather a single value.
Say I want the temperature from my weather forecast:
state_attr("sensor.weather_forecast_hourly", "forecast")|map(attribute="temperature")|list
How do I create an entity to store this? I would like to solve this without some specialized card, since I want to be able to use the values in multiple types of cards.
you can store it in an attriubte of a template sensor
@marble jackal Aha okay, thanks a lot, I will try that!
@marble jackal thanks for the template! I can work with that
Im trying to create a rest sensor for tide levels. Using this URL: https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?date=latest&station=8467150&product=water_level&datum=MLLW&time_zone=lst_ldt&units=english&format=json What would be the correct expression for the value_template: line to return the value for 'v'?
nevermind, got it to work
value_json.data.v
I added a template helper. It has a red exclamation point next to it. When I click on it, I have the ability to change the template and Submit it. I cannot delete it. I also noticed in the helper list that it does not have an entity id. I can call the entity id from an automation. If I go to Developer tools and type in the entity id, it doesn't seem to exist. Same thing if I go to Integrations>>Entities. It's not there. Quite puzzling. Any ideas on how to fix this? I was going to delete it and do a yaml template sensor instead, but I can't seem to find a wat to delete it.
Does my mqtt config look correct in my configuration.yaml? The light bulbs show up as read only under entites
https://dpaste.org/LGCxp
That's something for #integrations-archived
ahh, sorry!
Have you tried to clear the browser cache (Ctrl F5) ?
Cleared the browser cache, closed all windows and even tried Edge.
Just tried a different computer too.
Looking for a condition that if the lights that are on are increasing that it will trigger a notification. So far, all of it works except I can't get the condition right. Anyone can assist me?
@gentle smelt I converted your message into a file since it's above 15 lines :+1:
What's the issue with the condition?
it's double quoted. You have "'{{ }}'"
it should not be doulbe quoted, stick with single quotes or double quotes only
1 set.
e.g. "{{ ... }}" or '{{ ... }', not "'{{ ... }}'"
Doh..
I was expecting that the issue was that he was also receiving a message after a restart because of the state change from unavailable to a numeric state π
Evening all,
I'm looking to create a template that will add x amount of hours and minutes to the current time. The amount that needs adding will be in the format of, for example, 1.5. This should add 1.5 hours to the current time.
What would be the way to achieve this?
"{{ now() + timedelta(hours=1.5) }}"
Ohhh, that simple - Amazing.
Thanks for your help both
I have template sensors set for time of day, such as daytime, dawn, dawn2, evening and night, which is based on other sensors; dark__inside, dark__outside etc. Tese are used to control lighting inside and outside of the house. Now, I want to get rid of the last sensors, only relying on the time of day-sensors.
state: >-
{% if is_state('binary_sensor.dark_inside', 'off') and
is_state('binary_sensor.dark_inside_2', 'off') and
is_state('binary_sensor.dark_outside', 'off') %}
daytime
{% elif is_state('binary_sensor.dark_inside', 'on') and
is_state('binary_sensor.dark_inside_2', 'off') and
is_state('binary_sensor.dark_outside', 'off') %}
dawn
I need to test for several conditions an need some tip on how to accomplish this in the above template code. Any tips is appreciated π
Maybe a dumb question, but where in the UI do I add a template device. Looking to add "cover:" of "- platform: template". When I go to helpers and try to add "Template" it gives me binary sensor and sensor as options.
I get that, but I'm trying to add the YAML file and it's not clear where to add that.
Do I need the "file editor" integration, or is there a button I can push to add the yaml file so it shows up as a device.
There is a file editor add on, and a studio code server add on
I'm fairly familiar with Yaml and writing code in general, just trying to find where/how to add the file.
You need to change configuration.yaml
How you can access that is depending on your installation method
I'm using a Home Assistant Yellow. It was an automated install.
But this channel is only for the actual jinja templates, this is more a topic for #general-archived
Then install one of the above mentioned add-on's
So the term "template" (from what I've gathered) refers to the bracket {} syntax but also a custom device?
What are you trying to do. What would the template do?
I'm trying to wire up a MimoLite (dry contact sensor & relay) to a cover (garage door).
Migrating from custom software I had running for a few years to Home Assistant π
I would advice to start with setting some variables
state: >-
{% set dark_inside = is_state('binary_sensor.dark_inside', 'on') %}
{% set dark_inside2 = is_state('binary_sensor.dark_inside_2', 'on') %}
{% set dark_outside = is_state('binary_sensor.dark_outside', 'on') %}
{% if not dark_inside and not dark_inside2 and not dark_outside %}
daytime
{% elif dark_inside and not dark_inside2 and not dark_outside %}
dawn
The things between the curly brackets are templates.
There is configuration which relies on them which are using the template integration or platform: template
thanks. But I would like to get rid of the dark__inside sensors
Your suggestion is more neat, though π
Then define the variables using the code you now have for the binary sensor
Instead referring to it
Ah the studio app is much easier than the file editor one. Easier to navigate. Also VS Code is use daily. I see automations.yaml has all the automations I created in the one file. I'm guessing that the platform: template devices all exist in configuration.yaml rather than separate files?
That's up to you to setup
But all offtopic here, please move the questions on how to setup the YAML file structure to #general-archived
Ah gotcha. I see automation: !include automations.yaml. So if I wanted to break it out I could just import it as a separate file.
Great input @marble jackal. Thanks π
The current code for the binary_sensors would need to be refurbished to the form of a numeric_state, using lux above/below xx: I guess getting this to work is my main concern here π
- platform: numeric_state
id: "morning"
entity_id: sensor.utendors_lysstyrke
above: 60
below 200
Also montitoring sun.sun rising == true if morning
That's it! Thank you!
Cover template
When I'm testing calls in devtools, how can I see the response of those who give me a response? Like:
service: webostv.command
data:
entity_id: media_player.lg_webos_tv_uh605v
command: api/getServiceList
I thought it's pretty obvious, it fills out the "Response" section on the bottom half of the page?
hmm there;s no response section in my page :S
got it, you're right
weird, that call I was testing should respond something
thanks tho
Thanks able to do it through template trigger automation.
Where in home assistant do I put a template?
I would like to subtract one sensor from another and display the result on a dashboard.
make the template sensor from the helpers tab
When I restart HA this becomes "true" instead of "in" or "out" ``` {{ is_state('binary_sensor.withings_in_bed', 'unknown') or is_state('binary_sensor.withings_in_bed', 'unavailable') | iif(
is_state('input_select.bedroom_status', 'Sleep') | iif("In",
(is_state('input_select.bedroom_status', 'On') and (now() - as_datetime(state_attr('sensor.bedroom_tap_switch', 'last_triggered')) < timedelta(minutes = 60 ))) | iif("In",
(is_state('input_select.bedroom_status', 'On') or is_state('input_select.bedroom_status', 'Mood') or is_state('input_select.bedroom_status', 'Standby') and (now() - as_datetime(state_attr('sensor.bedroom_tap_switch', 'last_triggered')) > timedelta(minutes = 60 ))) | iif("Out",
is_state('input_select.bedroom_status', 'Off') | iif("Out","In")
)))
,is_state('binary_sensor.withings_in_bed', 'on') | iif("In","Out"))
}}```
I have no idea why its saying true since is_state('input_select.bedroom_status', 'Off') is true so it should be "out"
this part will just return "true"
is_state('binary_sensor.withings_in_bed', 'unknown')
just the first one, I guess. Perhaps you wanted an additional set of parentheses
(is_state('binary_sensor.withings_in_bed', 'unknown') or is_state('binary_sensor.withings_in_bed', 'unavailable'))
seemed to have fixed it
thanks π
I have a sensor that sometimes shows 0 instead of the correct value. What can I put in a helper template to display the last non-zero value?
I have tried {% set soc = states('sensor.battery_soc')|int(0) %} {{ soc if soc != 0 else trigger.from_state.state }}but that gives me Unavailable when the value changes to 0.
do you actually have a trigger?
I don't think so. The helper says This template listens for the following state changed events: Entity: sensor.battery_soc
then you don't have a trigger variable
try this.state instead: https://www.home-assistant.io/integrations/template/#template-and-action-variables
Thanks. This seems to be working
{{ soc if soc != 0 else this.state }}```
Is there an easy way to keep this value over OS reboots?
Perhaps if you add a unique_id to the sensor definition
if you created the sensor in the UI, it probably already has one
The state, including attributes, of trigger-based sensors and binary sensors is restored when Home Assistant is restarted.
so only trigger-based template sensors have their state restored
In that case, I won't worry about it.
can a template sensor (in my case I've been using the new helper ones) output attributes as well as a state? I've been looking but couldn't find anything, either it's not a thing or it's extremely simple
Yes, but you can only do that in YAML
how would I do that in yaml?
is that just a template sensor? the old kind or something?
- sensor:
- name: foo
state: "{{ now() }}"
attributes:
test: "{{ this.state }}"
that one
I see, thank you
the template helper is just a basic version of that one, with limited options (only state, device_class, and state_class)
template helper is what got me into templates
Gateway drug.
before that it was too much of a hassle to experiemnt
but now there is a missing link, if I have to do the same template for different things but with different sensors, is there some sort of function functionality? a template for templates? are macros what I'm looking for?
I swear google is useless, none of this ever pops up for me
so yes, macros would be used for that
this page is linked in the topic description
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
this looks relatively easy
it works and it's amazing
do the macro files need to have a .jinja extension? doesn't look like the config editors I'm using pick them up as editable files
not sure, but which config editors are you using?
There are several jinja extenstions for VS Code
unfortunately I'm running HA as a container so I can't use addons, the HACS config extension doesn't pick them up and the casaos editor doesn't open them as editable files
which means I'll have to set up vscode through remote ssh if I want to edit them with as little hassle as possible
you can of course test it, but I assume the service call to load them will specifically load .jinja files
I'll also try that, after I set the remote
I confirm if it's not .jinja it won't load
but now I have vscode set up so it's ok
How do I get rid of a binary_sensor which (as it seems) somewhere stored with "restored: true" ?
that's not a question for this channel, this channel is for the jinja templates themselves
but anyway, I assume this is a YAML created template binary sensor then?
Can anyone take my hand and show me in detail how I can make made up entity number add up every 10 seconds by a fixed amount while a boolean sensor value is true?
a trigger based template sensor on a 10 second time pattern
and then in the state template add your fixed amount if the input_booelan is on, else return this.state
template:
- trigger:
- platform: time_pattern
seconds: "/10"
sensor:
- unique_id: e02a02dd-1026-4810-ad70-6f281094c7d3
name: Some name
unit_of_measurement: whatever
icon: mdi:test-tube
state: >
{% set increment = 10 %}
{% set boolean_entity = 'input_boolean.whatever' %}
{% set increase = is_state(boolean_entity, 'on') %}
{{ this.state | float(0) + increment if increase else this.state }}
@jagged rivet 
Oh waw thank you so much! Would you mind if I ask some details in private chat as to not clutter this space?
I'd rather keep the conversation here π
Is it possible to get the minimum from a list of floats?
'float' object is not iterable
if you're getting that error, then you're trying to get the minimum from the individual index not the entire list
that's what the error is telling you
With expand(sensorsfoo) | map(attribute='state') | map('float') | map('min') | list
Sensor states are 62.xx for
example
reverse list and min, and you're doing it wrong
you just use the min filter, not map min
e.g. | map(attribute='state') | map('float', default=None) | reject('none') | list | min }}
I figured it was the position of list
That default=none filters out unavailable states? Non floats?
yes
default=none defaults non numeric states to none, the next steps filters them out
Awesome thanks
@mighty ledge see I do ask home assistant related questions every now and then lol
Ok so when I put this into a template sensor in the helper section
`template:
- trigger:
- platform: time_pattern
seconds: "/10"
sensors: - unique_id: e02a02dd-1026-4810-ad70-6f281094c7d3
icon: mdi:test-tube
state: >
{% set increment = 3.33}
{% set boolean_entity = 'binary_sensor.home_pump_float_gpio3_bottom_blue' %}
{% set increase = is_state(boolean_entity, 'on') %}
{{ this.state | float(0) + increment if increase else this.state }}`
I get the error
invalid template (TemplateSyntaxError: unexpected '}')
- platform: time_pattern
Yes thank you
Why is it saying "This entity is no longer being provided by the template integration. If the entity is no longer in use, delete it in settings."
if you moved it to the UI, it's going to be a different entity
Also I flipped binary_sensor.home_pump_float_gpio3_bottom_blue to on in develop and the template sensor I just made is still showing as unavailable
Yes, because you're looking at the old entity
not the one you created in the UI
also keep in mind that the UI template entities only update when thier input entities update
so you won't be able to replicate the triggering every 10 seconds in the ui.
If I moved it to the UI ... You lost me. I submitted the template sensor, it now shows an exclamation mark. What do I need to do to make this work?
you said:
-> Templates