#templates-archived

1 messages Β· Page 55 of 1

marble jackal
#

Maybe also because at the same time timer intents for Assist were added

#

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

sudden wraith
#

That seems straight forward

#

Then feed that into a timer or something to get an event?

marble jackal
#

What kind of event are you referring to?

sudden wraith
#

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.

marble jackal
#

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

sudden wraith
#

Interesting, lemme try that.

languid nova
#

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 ..."

compact rune
#

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)

fringe temple
#

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') }}"
marsh cairn
#

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

fringe temple
#

ahh, i missed the edit to binary_sensor from regular sensor. That did the trick

#

thanks @marsh cairn

marble jackal
#

Oh wait, you're creating a cover entity

#

My bad πŸ™‚

unborn acorn
#

Is it possible to change button/tile icon color from an automation or variable state?

marble jackal
torpid mural
#

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...

languid nova
#

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?

torpid mural
#

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.

languid nova
#

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.

torpid mural
#

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.

languid nova
torpid mural
#

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?

languid nova
#

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

torpid mural
torpid mural
# languid nova hmm. the "tariffs" seem to me more of a classification than a calculation. Does ...

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.

torpid mural
# torpid mural Thanks, Petro's template (https://community.home-assistant.io/t/diffrential-valu...

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.

torpid mural
#

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?

torpid mural
#

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!
plain magnetBOT
#

@willow wing I converted your message into a file since it's above 15 lines :+1:

willow wing
#

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.

marble jackal
#

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

willow wing
#

ok thats bad, so i need a helper right?

#

or a temp sensor okay, thanks Fes πŸ‘πŸ»

languid pendant
#

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.

sacred sparrow
#

whats the best way to display the sensor name with the largest number oh the attribute "last_called_timestamp"? out of 4 sensors?

rose scroll
#

Then you can do {% set l = l + ['whale'] %}

sacred sparrow
#

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 }}```
rose scroll
#

What does the above get you?

sacred sparrow
#

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

rose scroll
sacred sparrow
#

ah perfect thanks πŸ™‚

marble jackal
#

don't you want to sort on the timestamp as well, instead of the state?

sacred sparrow
#

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

marble jackal
#

yes

#

inster |map('as_datetime') before | first

sacred sparrow
#

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

marble jackal
#

why did you add |string?

#

you converted the list with timestamps to a string there

sacred sparrow
#

because when i remove string it says TypeError: argument must be str

marble jackal
#

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

sacred sparrow
#

I think the timestamp is weird. its "1696234131245"

#

it should be 10 digits right?

marble jackal
#

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

sacred sparrow
#

I just want to show the timestamp in DD/MM/YY HH:MM:SS

marble jackal
#

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

sacred sparrow
#

yeah caught that πŸ™‚

#

that worked - just need to convert to DD/MM/YY HH:MM:SS

marble jackal
#

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)

lethal galleon
#

(how) can I create a dict of entity_id: some_attr from a list of entities?

sacred sparrow
#
            | 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 πŸ™‚
marble jackal
lethal galleon
marble jackal
#
{% 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 }}
sacred sparrow
#

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

marble jackal
#

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')

lethal galleon
sacred sparrow
#

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```
marble jackal
#

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

sacred sparrow
#
          {{ 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 }}

willow wing
#

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 %}```
sacred sparrow
#

but this changes to "" eeven though the attribute hasnt changed

marble jackal
#

when does it change?

willow wing
#

lights when more than 1 light,, light then only 1 light

#

its only grammatic πŸ™‚

plain magnetBOT
#

@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.

marble jackal
#

but you use elif

#
{% set count_on = states... rest of template  %}
{% if count_on > 2 %}
  pink
{% elif count_on > 1 %}
  green
{% endif %}
willow wing
#

i mean the content, not the color, color works fine

marble jackal
#

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

willow wing
#

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)

marble jackal
#

you need to use == for a comparison

willow wing
#

same, no text 😦

marble jackal
#

post your complete template

willow wing
#
    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 %}```
marble jackal
#

you are not ending that if statement

#

it needs at least {% endif %}

willow wing
#

aaaaahhh fuck omg, thank you

marble jackal
#

my advice, first get it working in devtools > templates

#

it shows what is wrong

languid pendant
#

mmkay, I have a question; what type of data structure is outputted by state_attr() ?? its not a list, right?

inner mesa
#

it can be

#

depends on the integration and entity

languid pendant
#

ok, so state_attr('group.xxx','entity_id') comes out as (xxx,xxx,xxx)

inner mesa
#

note the "list" there

languid pendant
#

state_attr('media_player.xxx,'entity_id') }} comes out as [xxx, xxx, xxx]

inner mesa
#

what's the issue?

languid pendant
#

if they're both put in at the same time, the output is different

inner mesa
#

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

languid pendant
#

ok -- so what I'm looking for is the set

inner mesa
#

is there an issue?

languid pendant
#

can i turn a list into a set?

inner mesa
#

I think you're off in the weeds

languid pendant
#

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...

inner mesa
#

if you start with the problem, then perhaps there's a solution

languid pendant
#

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 ()??

mighty ledge
#

() -> 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

languid pendant
#

ok, so that might be where I am stuck

mighty ledge
#

so, you still aren't explaining yourself well

#

are you trying to combine them and get all unique items?

languid pendant
#

actually I think you may have answered my question with tuple.

mighty ledge
#

basically this doesn't make sense

run a replace() on that set

languid pendant
#

so the items in the output of state_attr(group.xxx) is a tuple

mighty ledge
#

are you purposely trying to not explain what you want to do?

languid pendant
#

lol .. no; is it ok that i post a screenshot?

mighty ledge
#

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"

languid pendant
#

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)

inner mesa
#

I think you're way overthinking this

#

And confusing yourself by focusing on types

languid pendant
#

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

mighty ledge
#

You just want a list of media players that have input booleans with the same object id?

inner mesa
#

It's as simple as {{ state_attr('xxx', 'entity_id')|map('replace', 'whatever', 'whatever')|list }}

languid pendant
#

i want a list of input_booleans that have the same name as the media players after i have removed (replace()d with '')

mighty ledge
#

I still think this is an xy problem

inner mesa
#

Petra is probably not using a phone, so I tag out...

mighty ledge
#

I am

#

πŸ˜…

inner mesa
#

It's like some sort of cruel and unusual punishment

mighty ledge
#

Haha yes

languid pendant
#

look, it's just as frustrating trying to explain it

#

:/

mighty ledge
#

Explain the whole endgoal

#

Not your specific problem with whateve mr code you came up with

plain magnetBOT
#

The XY problem is asking about your attempted solution rather than your actual problem.

languid pendant
#

ok, let's try this:
UI helper group (media_players)->replace() into input_booleans-> template sensor

inner mesa
#

That's..not useful. You're still starting with what you think is the solution

mighty ledge
#

Besides that, rob already gave that to ya

mighty ledge
#

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.

languid pendant
#

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.

marsh cairn
#

You have a group of media players... what do you want to have in the template sensor at the end?

hexed wing
#

Thanks πŸ‘

#

LOL me being the example

#

misread "don't" in that sentence

#

sorry about that @languid pendant

languid pendant
#

you're alright Frenck

marsh cairn
jagged obsidian
#

Cancel Frenck!

inner mesa
#

Petro started it πŸ™‚

mighty ledge
#

πŸ˜‚ I was thinking ??????????

hexed wing
languid pendant
#

Ok, so. group of mediaplayers

mighty ledge
#

Was very confused πŸ˜‚πŸ€£

languid pendant
#

corresponding (although not named exactly the same) input booleans

#

right?

mighty ledge
#

Yes, we’ve been over that

marsh cairn
#

@languid pendant Forget about the booleans at the moment or the complete way up to that point

mighty ledge
#

But at this point, we still have no idea what you want.

marsh cairn
#

What should be the final result in the template sensor (like "it should show the loudest speaker")

languid pendant
#

lol its not about the media players, lol it's about the input booleans

mighty ledge
#

If you just want a list of entity ids that came from media player entity ids, then rob already gave you that

languid pendant
#

i need to know which out of those corresponding booleans was the last turned off

marsh cairn
#

Ah!

languid pendant
#

which i already have the working stuff for that

#

BUT

#

only for a hard-coded old-school group

mighty ledge
#

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

wispy lodge
#

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'
plain magnetBOT
wispy lodge
#

Thanks

mighty ledge
#

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

languid pendant
#

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

wispy lodge
#

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')" ?

torpid mural
#

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?

languid pendant
#

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

inner mesa
#

seems a little overly complicated πŸ™‚

languid pendant
#

i know,

inner mesa
#

{% 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, πŸŽ‰

trail solar
#

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 ?

inner mesa
#

I sugggest:
state: "{{ states('sensor.temperature_bureau_adrien_temperature') ~ 'CΒ° | ' ~ states('sensor.temperature_bureau_adrien_humidity') ~ '%' }}"

inner mesa
#

:sad panda:

#

debug in devtools -> Templates

torpid mural
#

Try running your template in Developer tools - Templates to see what is going on...

trail solar
#

Type de rΓ©sultat: string

"23.01 CΒ° | 76.15 %"

torpid mural
#

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 ) }}

marble jackal
trail solar
#

no

marble jackal
#

It might be expecting a numeric state

plain magnetBOT
#

@trail solar I converted your message into a file since it's above 15 lines :+1:

trail solar
#

i think that i'm missing somthing

marble jackal
#

I'm also wondering what that Γ‚ is doing there. But that won't stop it from working

inner mesa
#

my second and third guesses are - didn't reload template entities or didn't trigger the sensor via the webhook

trail solar
inner mesa
#

it's under it 🀷

#

it won't update if it doesn't get the trigger

trail solar
inner mesa
#

yes

trail solar
#

tried this :

plain magnetBOT
#

@trail solar I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

you still have sensors:

trail solar
#

thermosensor is working (happy) but Piscine * are not in entities anymore 😦

inner mesa
#

already mentioned earlier

trail solar
#

ok thanks, i don't know why before adding the thermosensor, other are working

inner mesa
#

parallel universe

#

hallucination

trail solar
#

^^

#

many thank for you help πŸ™‚

torpid mural
#

No one can tell me how to create a sensor that sums each new value to all previous values?

inner mesa
#

with sum

lucid thicket
torpid crag
#

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 %}

rose scroll
fast token
#

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

plain magnetBOT
fast token
#

I would like to dynamically load that set. this will enable new devices to autopopulate

#

please give an idea

rose scroll
#

Welcome to HA. There are many rabbit holes for you to explore.

  1. Template-based entities are generated by Jinja templates in yaml
  2. 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.
fast token
#

ok

rose scroll
#

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.

lucid thicket
fast token
#

ok thanks for that heads up

hard apex
#

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 ?

marble jackal
#

well, you don't need that for loop

#

maybe that will fix it

marble jackal
# hard apex Hi all, I have since a while a "Template loop detected while processing event" w...

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

hard apex
#

WoW, looks way better than mine ! Thx a lot, will test it right now

plain magnetBOT
marble jackal
#

@rigid pier this is offtopic for this channel, ask agan in #integrations-archived after you reviewed the documentation

plain magnetBOT
languid pendant
#

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

hard apex
marble jackal
languid pendant
marble jackal
#

Unfortunately it doesn t solve the issue

tight canopy
#

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) }}

marble jackal
#

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

tight canopy
#

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

marble jackal
#

Only if you use it as trigger, it won't work for a condition

#

You didn't specify that

tight canopy
#

thats correct, my fault πŸ™‚

torpid mural
lucid thicket
#

Good to know, thanks! I haven’t used that with source sensors that go to unavailable or reset to zero

lunar crater
#

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

inner mesa
#

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

lunar crater
#

i think i see, thanks!

sudden wraith
#

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'.

inner mesa
#

Where did you put that?

sudden wraith
#

Developer tools template thingy

inner mesa
#

Oh, you just called the function with no output

sudden wraith
#

Ah true, but that shouldn't affect the error right?

#

I guess it might

inner mesa
#

Example is in the docs

#

No, you can't do what you did

sudden wraith
#

Interesting

#

Let me try a helper then.

inner mesa
#

Just use the example from the docs

#

Which says to use that surrounded by {{ }} and not {% %}

vivid dirge
#

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

sudden wraith
plain magnetBOT
#

@elder mural I converted your message into a file since it's above 15 lines :+1:

sudden wraith
#

@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 πŸ€”

hallow cove
sudden wraith
#

So I grab my sensor data, add the date I want and then use that as the sensor for the cheapest_energy_hours macro.

marble jackal
sudden wraith
#
  • 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
marble jackal
#

Okay, so the raw_today and raw_tomorrow are the ones you want to use (and are used by default)

#

Oh wait

sudden wraith
#

I get this error though: UndefinedError: 'dict object' has no attribute 'start'

#

Which I assume means it's trying to find a start value.

marble jackal
#

Ah wait, I didn't read properly

sudden wraith
#

The raw_today entries have a "hour" key and "price" key.

#

Should I do time_key="hour"?

vivid dirge
# hallow cove Settings > Device and services > Helpers > + Create helper > Group > Light group

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

marble jackal
sudden wraith
#

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.

marble jackal
#

Okay, great

#

I'll check if I can return some error messages for that

sudden wraith
#

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.

hallow cove
#

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.

languid pendant
#

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

marble jackal
sudden wraith
#

My first automation has been set up, going to be interesting to see if it works. πŸ˜„

thin zodiac
#

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

lofty mason
#

Maybe store the time in an input_datetime?

languid pendant
#

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 '' }}
mighty ledge
languid pendant
#

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?

inner mesa
#

You have to add a trigger to tell it what to look for

mighty ledge
#

what are you trying to do with this template result?

#

big picture

languid pendant
#

change volume on media player

mighty ledge
#

ok, and this template will return the entity that is what?

#

the last media player?

languid pendant
#

yes

mighty ledge
#

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

languid pendant
#

no no no .... i am the best at everyting. 🀣

inner mesa
#

genius lives in that 10%

mighty ledge
#

are you just trying to play announcements at a volume level and have it return to the previous level?

languid pendant
#

no, its for multiple input_numbers (volume controls) for the media players in our house

mighty ledge
#

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"

languid pendant
#

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

mighty ledge
#

why not just make a template number for the media player?

languid pendant
#

?

mighty ledge
#

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

languid pendant
#

hahahahaha

#

you may have met your match, boss

#

lol

mighty ledge
#

maybe I have

#

🀣

languid pendant
#

big picture; "base" scripts and automations, and "template" configs that contain the needed entities (timers, booleans, etc)

mighty ledge
#

to do...?

languid pendant
#

alarm clocks, multi-room audio, seperate radio players, etc.

mighty ledge
#

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

languid pendant
#

uhhm, I guess you could kindof say they auto find them ... mostly just the last entity used for the groups

mighty ledge
#

Yeah, but why even have the groups

languid pendant
#

thats actually what i am doing with the variables

mighty ledge
#

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

languid pendant
#

correct

mighty ledge
#

you end up maintaining only 1 list, in your trigger

#

without the group

languid pendant
#

right

mighty ledge
#

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

languid pendant
#

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

mighty ledge
#

push the physical button or in the UI?

languid pendant
#

ui

mighty ledge
#

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

languid pendant
#

well, that's actually what I thought I was doing

mighty ledge
#

do your kids have logins for each screen they use?

languid pendant
#

no, just seperate dashboards

mighty ledge
#

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

languid pendant
#

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

mighty ledge
#

Yep, so basically you just want to have the UI for each kid adjust thier media player?

languid pendant
#

basically

#

and with 3 kids, a guest room, the livingroom, outdoors, office, and master suite ...

mighty ledge
#

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

languid pendant
#

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

mighty ledge
#

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

languid pendant
#

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.

languid pendant
mighty ledge
#

I'll have to take a look at that in the morning and get back to ya

languid pendant
#

thats fine... Im always up to do something more efficient

mighty ledge
#

I already see some improvements that should make things easier, family time now tho

languid pendant
#

i get it. thanks

timber flume
#

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.

obtuse zephyr
#
{{ (state_attr('weather.kphl_daynight', 'forecast') | first).detailed_description }}
timber flume
obtuse zephyr
#

You bet

sudden wraith
#

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".

marble jackal
#

What's your full code for the template sensor now

sudden wraith
#
{% 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 had raw_tomorrow available.

compact rune
#

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

sudden wraith
#

Ah, that's a good point, I guess I could configure the include_tomorrow to only be true if raw_tomorrow attribute exists.

compact rune
#

(TheFes will probably have a better/ideal solution, but that's what popped out to me)

sudden wraith
#

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.

compact rune
#

I think states(...) doesn't return attributes, just a string of the main state, but otherwise that approach seems to make sense to me

sudden wraith
#

Ah, I need to check that when raw_tomorrow become available.

#

I see a state_attr function, maybe I need to use that.

compact rune
#

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)

sudden wraith
#

Yeah, makes sense.

#

I'll test some more when raw_tomorrow is available, appreciate the help.

marble jackal
sudden wraith
#

Oh, for the automation?

plain magnetBOT
sudden wraith
#

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.

marble jackal
#

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

sudden wraith
#

Yeah, that makes sense.

marble jackal
torpid mural
# lucid thicket Good to know, thanks! I haven’t used that with source sensors that go to unavail...

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).

frank gale
#

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.

inner mesa
#

Yes, using area_entities

frank gale
#

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

inner mesa
#

{{ ['Family Room', 'Kitchen']|map('area_entities')|list|join }}

frank gale
#

hmmm clever! thank you

inner mesa
#

I, personally, would have made area_entities smarter by figuring out what it's provided and working with it, but 🀷

frank gale
#

Having the area as attribute in the entity would be more helpful... We are moving slowly to area (room) based automatizations

frank gale
#

also is there any way for the filter | selectattr('state', '>', 2) to work properly and continue filtering after that?

frosty merlin
#
### 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?

lofty mason
#

[[[ 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

marble jackal
frosty merlin
plain magnetBOT
#

@thorn harness I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

@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

thorn harness
#

thank you πŸ™‚

#

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?

inner mesa
#

look at line 66

#

you have a stray '

#

you can tell from the color of action: that the problem was just before it

thorn harness
#

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?

plain magnetBOT
thorn harness
lofty mason
thorn harness
#

lol. that was it πŸ™‚ THANK you! πŸ™‚

inner mesa
#

In both cases, it pointed to the error

thorn harness
#

now i hope, it works as it should

thorn harness
#

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 }}

marble jackal
#

Ah, you need to account for the first time it triggers

thorn harness
#

what does that mean?

marble jackal
#
condition: template
value_template: >
  {{ now() - this.attributes.last_triggered | default(as_datetime(0), true) > timedelta(minutes=min_update_minutes) }}
thorn harness
#

i tried to lower the time and warmed up the temperature sensor

#

πŸ™‚

marble jackal
#

The first time an automation triggers there is no value in the last_triggered attribute, it will be none

thorn harness
#

ah okay

marble jackal
#

So it will compare the current time with none which will result in an error

thorn harness
#

okay, that makes sense πŸ˜„

#

but second will also not match

#

i tried this now, but also not works

marble jackal
#

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

plain magnetBOT
#

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.

marble jackal
#

You removed the | list | first part

#

Now it's a selector

thorn harness
#

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?

marble jackal
#

It doesn't select number entities anymore after your change

thorn harness
#

but how does it know which one it should take?

marble jackal
#

Oh wait, you changed it again

thorn harness
#

i mean: there are several number.* entities.. i think, it does not know which to take

marble jackal
#

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

thorn harness
#

ah okay. πŸ™‚ i need the number.tcv_badezimmer_external_measured_room_sensor" number.*_external_measured_room_sensor"

marble jackal
#

I'll have a look tomorrow, I'm going to bed now

thorn harness
#

np πŸ™‚ will do so too. thanks very much for your help πŸ™‚

languid pendant
#

@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

sacred sparrow
autumn flower
#

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 πŸ˜‰

sacred sparrow
#

great point about >=

#

all thew rest went over my head haha

autumn flower
#

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

sacred sparrow
#

Ohh I see! so it goes up to 29 - how can I make it go above that?

autumn flower
#

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

sacred sparrow
#

oh wow thats really cool - let me test it out. thanks so much

languid pendant
#

'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'

sacred sparrow
languid pendant
marble jackal
#

corect

thorn harness
# marble jackal https://dpaste.org/LdFHd

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']"

mighty ledge
languid pendant
#

do't worry about it

thorn harness
#

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')

obtuse zephyr
#

line 43, you're missing an else before 30

thorn harness
#

nice, thank you πŸ™‚

obtuse zephyr
#

You're welcome

deep marsh
#

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?

mighty ledge
#

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

deep marsh
#

Ah okay.

mighty ledge
#

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

deep marsh
#

Okay. I think it reacts within 1 second here and that's exactly what I want.

#

Thanks for the explanation!

mighty ledge
#

np

marble jackal
#

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

autumn flower
mighty ledge
#

dictionary, not set

marble jackal
#

I've seen some stuff about sets lately

#

What is a set?

autumn flower
#

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"

primal garden
#

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

floral shuttle
#

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 }}

marble jackal
#

you could create a group with only the power entities as members

floral shuttle
#

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

marble jackal
#

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

sacred sparrow
#

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

compact rune
#

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

languid pendant
#

could also include them in another set of parens

#

you're trying to get just the delta, correct?

#

or as_date_time(delta)

sacred sparrow
#

got it to work πŸ™‚

neon bolt
#

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 ?

median citrus
#

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

inner mesa
#

Nothing will be broken for 5 months

#

Deprecation isn't removal (yet)

#

It's fine to adapt early, but you have time

median citrus
#

Mhm i see but somehow all sensors became broken as of the last update. Maybe the custom integration Deutscher Wetterdienst dwdremoved support

elder mural
#

Ex14 ζ„Ÿε‹• I converted your message into a

acoustic arch
#

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?

hexed galleon
#

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?

marble jackal
#

all core integrations will have the forecast attributes until 2024.3

floral shuttle
#

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 %}

marble jackal
hexed galleon
marble jackal
#

@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)

mighty ledge
#

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

neon bolt
neon bolt
fossil venture
lucid thicket
neon bolt
#

Excellent ! thanks

#

Working just fine πŸ™‚

mighty ledge
#

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)

marble jackal
#

Thanks!

hexed galleon
#

Or would adding a time trigger do nothing if the state hasn't changed?

lucid thicket
hexed galleon
# lucid thicket You’re seeing an issue common to many integrations that operate off other sensor...

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.

mighty ledge
#

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

lucid thicket
#

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

hexed galleon
mighty ledge
#

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

fossil venture
lucid thicket
grim topaz
#

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

lofty mason
#

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.

grim topaz
lofty mason
#

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.

grim topaz
lofty mason
#

uom can be any arbitrary string

grim topaz
#

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

lofty mason
#

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 %} 
inner mesa
#

You should have put out the trash yesterday

lofty mason
#

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.

grim topaz
#

how did you drop a picture in here?

#

thanks

spark vortex
#

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

mighty ledge
#

you just add it... device_class: opening or door

limber trench
#

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.

inner mesa
#

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

limber trench
#

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.

inner mesa
#

Shouldn't matter how complex they are. A template is a template

limber trench
#

That's what I thought as well

inner mesa
#

Share what isn't working there

plain magnetBOT
#

@limber trench I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

You're trying to construct the YAML representation of a list and you should construct and output the actual list

limber trench
#

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!

inner mesa
#

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

limber trench
#

It is expecting a list indeed

#

Thanks a bunch @tardy cipher, putting it into the payload: >- and outputting the list did the trick!

tired vector
#

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?

mighty ledge
tired vector
north summit
#

just noticed the developer tools > template accepts caps letters ;
sun is {{ states("SUN.SUN") }}

mighty ledge
#

Yes the states method slugifies the entity_id

north summit
#

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

grizzled storm
#

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...

vagrant monolith
#

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

inner mesa
#

And your statement implies that you're just outputting true or false, not a concatenation of the two states

marble jackal
inner mesa
#

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 mindblown πŸ˜‹

#

templates provide endless satisfaction

compact rune
#

I think empty strings are falsy? But I'm not sure states() can ever return an empty string anyway

marble jackal
#

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

plain magnetBOT
next forge
#

Any thoughts?

atomic blade
#

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

ember saffron
#

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>

ember saffron
#

it seems that this error is independant from the mqtt sensor and also related to other templates which calculates a value

marble jackal
#

Post the full error

ember saffron
marble jackal
#

Add a default to the float filters or add an availability template

#

I prefer the latter

ember saffron
#

I try the availability, thanks!

#

Can i use the availability also in a calculation sensor?

marble jackal
#

In this case I would use:

availability: "{{ states('sensor.ccu3_sv_svenergycounter_3_7') | is_number and states('input_number.vortag_ankleidelicht') | is_number }}"```
ember saffron
#

Thanks!

ember saffron
marble jackal
#

Yes, that's the first way

ember saffron
#

Interesting. Because it still complains about the unknown value.

#

Im gonna wait a bit maybe it fog clears later bettee

marble jackal
#

And what is the code for your template sensor now

slate fossil
#

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?

marble jackal
celest bone
#

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)

royal tree
#

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/

inner mesa
#

{{ start_hour|round|int ~ ':' ~ "%02d"|format(start_minute)|int }}

royal tree
#

I'll give that a try now thank you

#

Says unknown now

marble jackal
#

{{ start_hour|round|int ~ ':' ~ "%02d"|format(start_minute|int) }}

#

Closing parenthesis was out of place

inner mesa
#

I'm sure this was clear from the logs

main mango
#

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"
marble jackal
# royal tree Says unknown now

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') }}
main mango
#

Thanks, can you me understand how it working.

plain magnetBOT
#

@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.

main mango
#

This one I have to set under template sensor.

jagged rivet
#

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?

inner mesa
amber tinsel
#

Hi, Is there any way to use templates for making the 'name:' in apexcharts-card dynamic?

royal tree
inner mesa
amber tinsel
#

I'll try there then

marble jackal
royal tree
#

sensor.time_to_charge_to_100

#

Confirmed in my developer states

marble jackal
#

Did you test the template in devtools > templates

royal tree
#

I did not realise I could

#

I'll try that

#

Weird, it works fine there

#

Ah!

#

UOM was set to time

marble jackal
#

Yes, that doesn't work

#

That should be the device_class

#

Which will be visible in the logs

ember saffron
marble jackal
#

That's not what I proposed to use for the availability template

ember saffron
#

its a different sensor, yes

marble jackal
#

The availability template should return true or false, not the same as the state template

#

Check if all entities you use in your calculations are actually returning a numeric state

ember saffron
#

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?

compact rune
#

energy (Wh/kWh) is not an instantaneous measurement but a value that accumulates over time. the instantaneous measurement is usually power (W/kW)

ember saffron
#

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)

marble jackal
#

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)

orchid blade
#

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

marsh cairn
#

What template?

orchid blade
#

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

marsh cairn
orchid blade
#

lol same...

inner mesa
#

you haven't shown a template yet

orchid blade
#

Trying to find that site that allows you to share code easier, forget the name

marsh cairn
plain magnetBOT
#

Please use a code share site to share code or logs, for example:

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.

orchid blade
#

Definitely not my code, I found my topics using the node red debug

marsh cairn
#

What guide is that?

orchid blade
#

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

marsh cairn
#

Too dated. The configuration for MQTT has been changed

#

And in your example, some topics still include the string "[friendly name]".

orchid blade
#

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

marsh cairn
#

But nevertheless, that's not a templating issue

orchid blade
#

Got it. Thanks for checking! I'll bug someone in the integrations area.

marsh cairn
orchid blade
#

Thank you!

marsh cairn
#

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")

orchid blade
#

yeah that's where it is on the motion sensor

marsh cairn
#

Have you looked at the "Cloud" section?

orchid blade
#

I'll enable the cloud real quick and see if CoIoT shows up. I would like to stay away from using the cloud

atomic blade
#

Is it possible to populate group entities with a template that generates a list of entity id's?

orchid blade
#

CoIoT isn't available after enabling the cloud

atomic blade
lean ivy
lean ivy
#

thanks

acoustic arch
#

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

marble jackal
#

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

hot adder
#

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.

marble jackal
#

you can store it in an attriubte of a template sensor

hot adder
#

@marble jackal Aha okay, thanks a lot, I will try that!

acoustic arch
#

@marble jackal thanks for the template! I can work with that

cosmic oxide
cosmic oxide
#

nevermind, got it to work

mighty ledge
#

value_json.data.v

humble oasis
#

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.

orchid blade
#

Does my mqtt config look correct in my configuration.yaml? The light bulbs show up as read only under entites
https://dpaste.org/LGCxp

orchid blade
#

ahh, sorry!

marsh cairn
humble oasis
#

Cleared the browser cache, closed all windows and even tried Edge.

#

Just tried a different computer too.

gentle smelt
#

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?

plain magnetBOT
#

@gentle smelt I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

no need to repost that, especially without any markdown

#

it's garbage in the repost

marble jackal
#

What's the issue with the condition?

mighty ledge
#

it should not be doulbe quoted, stick with single quotes or double quotes only

#

1 set.

#

e.g. "{{ ... }}" or '{{ ... }', not "'{{ ... }}'"

marble jackal
#

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 πŸ˜…

gusty pulsar
#

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?

mighty ledge
#

"{{ now() + timedelta(hours=1.5) }}"

gusty pulsar
#

Perfect - Thanks Petro πŸ™‚

#

Can I use a sensor to fill in the hours?

marble jackal
#

Sure

#

states('sensor.your_sensor') | float instead of the 1.5

gusty pulsar
#

Ohhh, that simple - Amazing.

Thanks for your help both

earnest cosmos
#

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 πŸ™‚

bright widget
#

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.

marble jackal
#

You can't do that in the GUI

#

That's all done in YAML

bright widget
#

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.

marble jackal
#

There is a file editor add on, and a studio code server add on

bright widget
#

I'm fairly familiar with Yaml and writing code in general, just trying to find where/how to add the file.

marble jackal
#

You need to change configuration.yaml

#

How you can access that is depending on your installation method

bright widget
#

I'm using a Home Assistant Yellow. It was an automated install.

marble jackal
#

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

bright widget
#

So the term "template" (from what I've gathered) refers to the bracket {} syntax but also a custom device?

earnest cosmos
bright widget
#

Migrating from custom software I had running for a few years to Home Assistant πŸ™‚

marble jackal
# earnest cosmos ```yaml state: >- {% if is_state('binary_sensor.dark_inside', 'off') and ...

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
marble jackal
earnest cosmos
marble jackal
#

Then define the variables using the code you now have for the binary sensor

#

Instead referring to it

bright widget
marble jackal
#

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

bright widget
#

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.

earnest cosmos
# marble jackal Then define the variables using the code you now have for the binary sensor

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

gentle smelt
coral granite
#

Cover template

wary yew
#

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
lofty mason
#

I thought it's pretty obvious, it fills out the "Response" section on the bottom half of the page?

wary yew
#

hmm there;s no response section in my page :S

lofty mason
wary yew
lofty mason
#

must be your service doesn't return one?

#

try the weather forecast and see

wary yew
#

got it, you're right

#

weird, that call I was testing should respond something

#

thanks tho

main mango
honest ravine
#

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.

mighty ledge
#

make the template sensor from the helpers tab

sacred sparrow
#

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"

inner mesa
#

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

sacred sparrow
#

(is_state('binary_sensor.withings_in_bed', 'unknown') or is_state('binary_sensor.withings_in_bed', 'unavailable'))

#

seemed to have fixed it

#

thanks πŸ™‚

honest ravine
#

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.

inner mesa
#

do you actually have a trigger?

honest ravine
#

I don't think so. The helper says This template listens for the following state changed events: Entity: sensor.battery_soc

inner mesa
#

then you don't have a trigger variable

honest ravine
#

Thanks. This seems to be working

{{ soc if soc != 0 else this.state }}```
honest ravine
#

Is there an easy way to keep this value over OS reboots?

inner mesa
#

Perhaps if you add a unique_id to the sensor definition

honest ravine
#

How would I do that?

#

I have Entity ID: sensor.battery_memory

inner mesa
#

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

honest ravine
#

In that case, I won't worry about it.

hushed nacelle
#

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

marble jackal
#

Yes, but you can only do that in YAML

hushed nacelle
#

how would I do that in yaml?

#

is that just a template sensor? the old kind or something?

plain magnetBOT
fossil venture
#
- sensor:
  - name: foo
    state: "{{ now() }}"
    attributes:
      test: "{{ this.state }}"
marble jackal
#

that one

hushed nacelle
#

I see, thank you

marble jackal
#

the template helper is just a basic version of that one, with limited options (only state, device_class, and state_class)

hushed nacelle
#

template helper is what got me into templates

fossil venture
#

Gateway drug.

hushed nacelle
#

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?

hushed nacelle
#

I swear google is useless, none of this ever pops up for me

marble jackal
#

so yes, macros would be used for that

#

this page is linked in the topic description

plain magnetBOT
#
The topic of this channel is:

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

hushed nacelle
#

this looks relatively easy

hushed nacelle
#

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

marble jackal
#

not sure, but which config editors are you using?

#

There are several jinja extenstions for VS Code

hushed nacelle
#

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

marble jackal
#

you can of course test it, but I assume the service call to load them will specifically load .jinja files

hushed nacelle
#

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

ember saffron
#

How do I get rid of a binary_sensor which (as it seems) somewhere stored with "restored: true" ?

marble jackal
#

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?

jagged rivet
marble jackal
#

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 this

jagged rivet
marble jackal
#

I'd rather keep the conversation here πŸ™‚

silent vector
#

Is it possible to get the minimum from a list of floats?

#

'float' object is not iterable

mighty ledge
#

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

silent vector
#

With expand(sensorsfoo) | map(attribute='state') | map('float') | map('min') | list

Sensor states are 62.xx for
example

mighty ledge
#

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 }}

silent vector
#

I figured it was the position of list

#

That default=none filters out unavailable states? Non floats?

mighty ledge
#

yes

marble jackal
#

default=none defaults non numeric states to none, the next steps filters them out

silent vector
#

Awesome thanks

#

@mighty ledge see I do ask home assistant related questions every now and then lol

jagged rivet
# marble jackal ```yaml template: - trigger: - platform: time_pattern seconds: "...

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 '}')
mighty ledge
#
      {% set increment = 3.33}
#

do you see what's missing?

jagged rivet
#

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."

mighty ledge
#

if you moved it to the UI, it's going to be a different entity

jagged rivet
#

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

mighty ledge
#

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.

jagged rivet
mighty ledge
#

you said: