#templates-archived

1 messages Β· Page 69 of 1

wary yew
#

i Just didn't like it being long πŸ˜… I preferred a shorter version. Maybe will test an iif too

inner mesa
#

you may also be able to use {{ message|default(state_attr('calendar.meals', 'message') , True) }}

wary yew
#

wait, what's the diff there? Isn't that also a filter?

inner mesa
#

yes

#

but I'm attempting to use state_attr() as the default

#

default is a filter

#

it does seem to work

wary yew
#

will stick to the if for my understanding given I'm still not familiar with those

inner mesa
#

{{ message|default(state_attr('sensor.aarlo_battery_level_catbox', 'device_class') , True) }} -> battery

#
{% set message = "foo" %}
{{ message|default(state_attr('sensor.aarlo_battery_level_catbox', 'device_class') , True) }}

-> foo

plain magnetBOT
haughty breach
#

No, you're defining variables based off a non-existent state attribute, not the response variable from the service call

wary yew
mighty ledge
#

where you getting agenda from?

wary yew
#

agenda is the variable from the service call

#
service: calendar.get_events
target:
  entity_id: calendar.meals
data:
  duration:
    hours: 24
    minutes: 0
    seconds: 0
response_variable: agenda
mighty ledge
#

then you use the variable agenda

#

literally just agenda

wary yew
#

but thtat's the entire list AFAIK

mighty ledge
#

you decided to add state_attr('calendar.meals', 'agenda')

wary yew
#

I just want the summary of the second event

mighty ledge
#

when it should just be agenda

wary yew
#

nah, that was chatgpt. I get now the mess it got me in...

#

I just didn't know the syntax to get it myself

mighty ledge
#

which is why we don't allow chatgpt because it doesn't know it's ass from a pancake

#

the sytnax to get the events would be {{ agenda['calendar.meals'].events[1].summary }}

wary yew
#

that's the thing I was looking for

mighty ledge
#

FYI in the docs we linked

wary yew
#

yeah, I saw it, but it didn't have the event index or the piece of info

#

so I still needed some help for the syntax. That was my problem 😦

#

and then I wrongly followed the suggested gpt change

#

thinking he would know xD

mighty ledge
#

Yeah, don't botehr with chatgpt for this service call because it didn't exist when chatgpt was trained

wary yew
#

I get it now

mighty ledge
#

so chatgpt makes up what it doesn't know

#

which is why chatgpt isn't allowed

#

if it didn't do that, it would probably be a better tool for you

wary yew
#

makes sense. In other fields I'm able to discern, but when you're a noob... I feel like any help is good help lol

#

but yeah, I'll be avoiding it from now on

#

sorry about the mess

mighty ledge
#

Yeah, just be wary about that kind of stuff

#

chatgpt also makes up integrations

wary yew
#

hah

mighty ledge
#

so, if you ask pointed questions about automations, it's pretty good

wary yew
#

nah, for me I'm usually just looking for syntax fixes or functions, which is where I'm more clueless about

#

it's a "I can read" but I can't write kind of thing

#

ended up working like this in the end {{ iif(message, message, state_attr('calendar.meals', 'message')) }}

#

just the variable name as condition is a good check for "exists", right?

#

seems to work at least

lethal bison
#

any way to search only the 'group' domain? I'm looking for all groups with the prefix 'group.phone*'

inner mesa
#

yes

#

{{ states.group|selectattr('object_id', 'match', 'phone')|map(attribute='entity_id')|list }}

nimble crane
#

hi all!
i am struggling here with the match template...
need to filter all entities that name ".0x" in the suffix.
examples:
sensor.0x00124b002268ea6b_battery
binary_sensor.0x00124b0023420d49_battery_low
number.0xa4c138d2589bb298_maximum_range

inner mesa
#

almost identical to the above

#

replace states.group with states

nimble crane
#

this was the best i could do... but did not want to list all the types

#
|map(attribute='entity_id')|list|join(', ')}}```
inner mesa
#

see mine

#

{{ states|selectattr('object_id', 'match', '0x')|map(attribute='entity_id')|list|join(', ') }}

nimble crane
#

love! πŸ™‚ thanks!

wary yew
#

btw @mighty ledge, have you guys in the team ever considered adding something like https://www.kapa.ai/ ? I have used it in another Discord from n8n, an automation tool that needed some coding, and it was f*ing amazing tbh. It exclusively uses the projects docs, but it took a massive toll out of community supporters like you. It was also a perfect tool for me since as I said I had plenty of syntax issues and questions. And it was all used from within Discord too. Basically support people only hovered around the threads created by the bot when they were testing it to add some additional info, etc. But the experience for me was amazing.

mighty ledge
#

I could pass it along to the people that matter, looks like it could help

wary yew
#

think of removing all the stupid basic questions from people that are actually answered in docs πŸ˜‚ but answered clearly, with proper sources and all

#

channel bot-help

#

hope it helps

mighty ledge
#

Well the docs aren't great for templates atm

#

they are 'ok'

#

definitely need some love

wary yew
#

forums can be used too, and tbh after battling myself, I end up finding out it was in the docs all along. In any case, it's better than nothing!

proper oak
#

Is anybody here, who uses a Garagedoor in HomeAssistant@and Homekit?
I am not able to get the status working. Opening is emedetly open without my 19s delay

inner mesa
#

is that related to a template?

proper oak
#

Yes it is

inner mesa
#

please share the template

#

anything, otherwise nobody can help

proper oak
#

Yeah I try it, but cant copy on the mobile app…. One moment

plain magnetBOT
inner mesa
#

I don't see any 19s delay there

#

it's entirely based on the state of input_boolean.garagentor_helfer

proper oak
#

Yeah u are right. I will explain, give me a second 😊

#

I use a shelly1 with addon a one magnetic switch on the ground. If this switch changed frokmon to off is use an automation to aet the state of this helper to on., because i have tonuse it only fot the upper direction.

#

My problem is, that I used ioBroker and now I have problems to change my thinking about the coding. Blockly is not yaml πŸ˜‚

inner mesa
#

you still haven't mentioned where this 19s delay is supposed to come from

#

since that seems to be the crux of your concern

#

you have an automation that triggers on the switch, and then you delay for 19s and then you turn the input_boolean entity on?

proper oak
#

you have an automation that triggers on the switch, and then you delay for 19s and then you turn the input_boolean entity on? Yeah correct

plain magnetBOT
proper oak
#

This is another code i try but i cant get it wirking

#

Working

inner mesa
#

in any case, if your concern is this:

Opening is emedetly open without my 19s delay
then you need investigate that automation, not this template cover

#

because it is simply reflecting the state of the helper

proper oak
#

The delay changed the icon in HomeAssistant, but the translation to Homekit isnt working. I know that HA is also working alone, but I want some parts working from everywhere and there homekit is simple to use (especially to my wife) 😊

inner mesa
#

ok, this doesn't sound like any sort of template issue

proper oak
#

@inner mesa u are right. But my first template is not working. If i touch the garage door button in Homekit, i can see in the log that open.cover vomes from Homekit to Homeassitant, but the door does nothing. When I delete the conditions for open or close it diesnt make a change

inner mesa
#

it's a template cover, but the problems that you're describing have nothing to do with the "template" part of that

proper oak
#

Any idea where the problem can be? For me it is a little difficult to understand the translation between HomeAssitant and Homekit.

inner mesa
#

If i touch the garage door button in Homekit, i can see in the log that open.cover vomes from Homekit to Homeassitant, but the door does nothing.
Test the service call manually. Open the switch entity in devtools -> States and switch it on and off to make sure it works

#

it's just straight-line code, so if you claim to see open_cover being called, but the door isn't opening, then it's that service call

glacial solar
#

Does anyone here know how to convert command below, to one for zigbee2mqtt to understand? service: zha.issue_zigbee_cluster_command
data:
ieee: 00:0d:6f:00:13:3f:fa:07
cluster_id: 1281
command: 4
command_type: client
cluster_type: out
args: [5, 30, 1, 0]
endpoint_id: 1

ruby vault
#

in a script/automation if an 'if' has multiple conditions (since it is a list) is it an 'and' or an 'any'?

marble jackal
#

and

#

That applies to all sections where conditions are used

thin spindle
#

Hey, I would like to sum the power of all known devices to track "hidden consumers"
currently my test template looks like this:

{% for s in states.sensor %}
  {% if s.object_id.endswith('_power') %}
    {% set ns.states = ns.states + [ s.state | float ] %}
  {% endif %}
{% endfor %}
{{ ns.states | sum | round(2) }}```

And I get the error ``` ValueError: Template error: float got invalid input 'unavailable' when rendering template '{% set ns = namespace(states=[]) %} {% for s in states.sensor %} {% if s.object_id.endswith('_power') %} {% set ns.states = ns.states + [ s.state | float ] %} {% endif %} {% endfor %} {{ ns.states | sum | round(2) }}' but no default was specified```
#

how can I exclude 'unavailible" values?

fickle sand
frank gale
#

Wouldn't just | float(0) work?

fickle sand
#

Even better

thin spindle
#

so like this?

{% for s in states.sensor %}
  {% if s.object_id.endswith('_power') and state.state != 'unavailable' %}
    {% set ns.states = ns.states + [ s.state | float(0) ] %}
  {% endif %}
{% endfor %}
{{ ns.states | sum | round(2) }}```

i get this:
```'state' is undefined```
#

meanwhile I tried it differently which seems to work:

          {% for state in states.sensor %}
            {% if "power" in state.entity_id and state.entity_id.endswith("_power") and state.state != 'unavailable' %}
              {% set ns.value = ns.value + state.state | float %}
            {% endif %}
          {% endfor %}
          {{ ns.value }}```
fickle sand
#

should be both s

thin spindle
#

thats it!

#

thanks man!

frank gale
#

It could also be simplified as:

{{ states.sensor
       | rejectattr('state', 'in', ['unavailable', 'unknown', None])
    | selectattr('object_id', 'search', '_power$')
 | map(attribute= 'state')
| map('float')
| sum }}
#

I'm on phone don't know if it works...

#

Sorry for the wrong formatting

plain magnetBOT
#

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

fickle sand
#

The first is a legacy format part of the sensor integration, the second is part of the new template integration

frank gale
#

That would work better for you:

{{ states.sensor
    | rejectattr('state', 'in', ['unavailable', 'unknown', None])
    | selectattr('device_class', 'eq', 'power')
    | map(attribute= 'state')
    | map('float')
    | sum }}
thin spindle
#

so the later is the preferred and better way, right?

fickle sand
#

yep

fickle sand
thin spindle
#

I would like to exclude one device
state.entity_id != 'sensor.shellyplugs_pv_power'

#

currently the template that I do understand and works looks like this:

          {% for state in states.sensor %}
            {% if "power" in state.entity_id and state.entity_id.endswith("_power") and state.entity_id != 'sensor.shellyplugs_pv_power' and state.state != 'unavailable' %}
              {% set total_consumer_power.value = total_consumer_power.value + state.state | float %}
            {% endif %}
          {% endfor %}
          {{ total_consumer_power.value }}```
#

well if there is not really a need to use the template from @frank gale I would just take the one I have and dont waste your time πŸ™‚

frank gale
frank gale
thin spindle
#

isnt mine doing the same?

#

and how can I exclude one specific entity from the sum?

#

I want to calculate the sum of all consumers. My solar system is also included as an entity from type "power", so I want that to be not part of that

frank gale
#

Yours looks the entity_id, if you have an entity that ends with power and isn't a power sensor, this will be included in the sum and all the power sensors without 'power' in their entity id will be excluded

#

It's your choice... Just wanted to simplify your template

#

Have fun!

thin spindle
frank gale
thin spindle
fickle sand
frank gale
#

The line is ok, your entities haven't apparently no device_class

thin spindle
#
       | rejectattr('state', 'in', ['unavailable', 'unknown', None])
    | selectattr('attributes.device_class', 'eq', 'power') 
 | map(attribute= 'state')
| map('float')
| sum }}```
frank gale
#

Try adding:
| selectattr('attributes.device_class', 'defined)
before this line

#

Ahhh yes my bad

#

attributes.device_class

#

Sorry

frank gale
thin spindle
#

I do have this {{ states.sensor | rejectattr('state', 'in', ['unavailable', 'unknown', None]) | selectattr('attributes.device_class', 'eq', 'power') | map(attribute= 'state') | map('float') | sum }}

#

this gives me 2x the value that would be correct

#

and this has an error {{ states.sensor | rejectattr('state', 'in', ['unavailable', 'unknown', None]) | selectattr('attributes.device_class', 'defined') | map(attribute= 'state') | map('float') | sum }}

#

ValueError: Template error: float got invalid input '2024-02-29T05:35:31+00:00' when rendering template '{{ states.sensor | rejectattr('state', 'in', ['unavailable', 'unknown', None]) | selectattr('attributes.device_class', 'defined') | map(attribute= 'state') | map('float') | sum }}' but no default was specified

frank gale
#

On the second one you should have added the line not remove the other one

fickle sand
thin spindle
#

so like this {{ states.sensor | rejectattr('state', 'in', ['unavailable', 'unknown', None]) | selectattr('attributes.device_class', 'eq', 'power') | selectattr('attributes.device_class', 'defined') | map(attribute= 'state') | map('float') | sum }} ?

#

still double the value of what would be right

frank gale
fickle sand
#

Or double entities indeed

thin spindle
mighty ledge
#

defined should be before eq power

#

these are filters

thin spindle
#
| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'power') 
| map(attribute= 'state')
| map('float')
| sum }}```
mighty ledge
#

they are applied in order

frank gale
thin spindle
#

its still 2x the real value

mighty ledge
#

why aren't you making a sensor group?

#

because you want it to auto generate based on all power entities?

thin spindle
thin spindle
#

my HA is growing fast and I prefer to include this "dynamically"

frank gale
#
| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'power') 
| map(attribute= 'entity_id')
| list }}```
#

What does this return?

thin spindle
#

it returns this:

plain magnetBOT
#

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

thin spindle
#

no double entities

mighty ledge
#

you have entities pointing to your phone's power consumption and other things

thin spindle
#

well it does!!!

#

the last one!

#

its the sum of all πŸ˜„

#

wait a second

mighty ledge
#

you should really use a sensor group and select all your power entities that matter. Otherwise this template will require multiple filters from you removing entities that you don't want in the calculation

#

it'll be the same maitenance as a sensor group where you add things manually. But it will be harder for you to manage because you don't know templates.

thin spindle
#

ok, now Im getting more to the real value

#

the template also includes the forecast of the solar production

#

sensor.power_production_now

#

without this everything is correct

mighty ledge
#

yep, you have to reject that entity

thin spindle
#

finally!

| rejectattr('state', 'in', ['unavailable', 'unknown', None])
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'power') 
| map(attribute= 'state')
| map('float')
| sum  
- states('sensor.power_production_now') | float(0)
- states('sensor.shellyplugs_pv_power') | float(0)
}}```
mighty ledge
#

...

thin spindle
#

thanks @frank gale @fickle sand and @mighty ledge πŸ™ πŸ™ πŸ™

frank gale
#

You will have more - entities in the future

mighty ledge
#

| rejectattr('entity_id', 'in', ['sensor.power_production_now', 'sensor.shellyplugs_pv_power'])

thin spindle
#

but not more, that produces power

brazen harbor
#

I am trying to figure out how to sort a list by the attribute state value. The issue I seem to be running into is that the state value is a string and not an int/float. How can I convert the state to an int/float in the sort function? The below example does not sort correctly.

Truncated example:

{% set sorted_list = ns_sensors.values | sort(attribute='state|int', reverse=False) %}
marble jackal
#

You can't, you need to store the states as numbers in your namespace

plain magnetBOT
#

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

mighty ledge
#

you have quotes all over the place for no reason

#

and not in the correct spot

#

and you're missing and {% endif %}

#

and input_number.orderstopprocess isn't declared, assuming you want the state from that entity, which means you should wrap that in states('')

#

and you have a >- after data

#

that should be on value if you plan on using multiline notation with your template

#

the second service you wrote also has incorrect quoting, that will not work. Not sure how it is

#

if you have a template, your exterior quotes should not match your interior quotes

#

e.g. "{{ 'something' }}"

twin compass
#

ok let me try

#

Would this be it?

data:
value:
{% if trigger.json["OrdersToProcess"] != "NULL" %}
"{{trigger.json['OrdersToProcess']}}"
{% else %}
"{{states(input_number.orderstoprocess)}}"
{% endif %}

#

input_number.orderstopprocess is a helper

mighty ledge
#

you need multiline notation, the >-

#

and you still have quotes all over the place around your ouputs

#

which arer teh {{ }} lines

#

and you're missing quotes for the states() function's entity_id

#

You can test this in the template editor by the way, instead of guessing

#

use
{% set trigger = {'json':{'OrdersToProcess': 'blah'}} %}
for testing

twin compass
#

Thanks so much!! It worked!

proper oak
bronze prawn
#

Is there an easy way to pull the icon used for an entity? I'm working on a custom card. Passing the entity via a text helper but not sure how to get the icon assigned to that entity

lofty mason
#

Unless there's a way to get it with templates.... I'm not aware that there is.

mighty ledge
#

We should add entry_attr

frank gale
mighty ledge
#

Doesn’t work anymore

#

Icons aren’t attrs anymore

frank gale
#

Just tested on Template Editor

mighty ledge
#

Then you’re using something custom

frank gale
#

What do you mean by custom? Isn't that working for you?

mighty ledge
#

It only works if the icon is listed as an attribute

#

2024.2 made a change that removed that attr off most entities

inner mesa
#

I still have a lot of them

#

including core integrations

mighty ledge
#

Customize.yaml?

inner mesa
#

no

#

like Synology

mighty ledge
#

πŸ€·β€β™‚οΈ

inner mesa
#

if you go into devtools -> States and type "icon" into the attributes field, you don't see any?

mighty ledge
#

I’m sure there are a bunch, but I do goofy shit in my system

#

And most of my icons are set through lovelacegen

bronze prawn
inner mesa
#

if you don't see it in devtools -> States, that's why

bronze prawn
# inner mesa if you don't see it in <:devtools:619094051878207520> -> States, that's why

Yep. You're correct. So these lights do show the mdi:light in my dashboard but it is not assigned to them. I went in and changed one to explicitly have the mdi:light icon and now I have that available in the attributes. Looks like most of my other sensors all have that icon attribute but not the lights. Weird. I've been running HA since 0.36 so maybe it's a legacy thing and these were never assigned even though they show up correctly.

marble jackal
#

They are just using the default icon for a light entity

inner mesa
#

integrations can provide their own default icon for each entity as a property

proper oak
hardy moon
#

hm I see- the issue could just be with covers in general?

devout dragon
#

gah, how can i store a value for later use .. i want to make a copy of the nordpool today and tomorrow prices as they get moved around/removed etc and messes up all my calculations ..

#

dont know if its a template question tho ...

scenic verge
#

hi all. i have a very simple virtual light....but how do i get this assigned to a group?

#
  - platform: template
    lights:
      alexa_virtual_lights:
        friendly_name: "Living Room Lights HA"
        turn_on:

        turn_off:

        set_level:```
#

(set in configuration.yaml)

pallid moth
#

Hi,

I want to set up a notification based on a condition and just wanted to check if my template is correct

I use Aqara TRVs for my heating and the current temperature is fed to them by an external aqara temperature sensor. This mostly works stable but sometimes it gets out of sync and then the heater is not action properly. For this cases I want to get notified.

The TRVs temperature is stored in the state attribute current temperature of the climate entity. The external temperature has it's own sensor for the temperature.

I came up with this template, can anyone check briefly if that would work (or tell me how to check myself)?

{% endif %}```
inland stag
#

Hello, I have MQTT sensors set up to pull the energy values from my Victron inverter. But every time I restart HA, it temporarily sets them to 0.0 and then to the value read from MQTT:

      state_topic: "venus/N/xxx/vebus/289/Energy/OutToInverter"
      value_template: "{{ value_json.value | round(2) }}"
      device_class: energy
      state_class: total_increasing
      unit_of_measurement: "kWh"

I tried adding this to the template, but then it always stays unavailable:

      availability:
        topic: "venus/N/xxx/vebus/289/Energy/OutToInverter"
        value_template: "{{ value_json.value | is_number }}"

Any idea why it shortly reverts to 0? I didn't find any default value for round() as it exists for example for float()

marble jackal
#

Use the same topic in your availability section as for your state topic

#

As you are checking on the same value

marble jackal
pallid moth
marble jackal
#

You probably want something like:

{{ (state_attr('climate.arbeitszimmer_heizung_links', 'current_temperature') or state_attr('climate.arbeitszimmer_heizung_rechts', 'current_temperature')) != states('sensor.arbeitszimmer_temperatursensor_temperature') | float(0) }}
inland stag
marble jackal
#

ah wait

#

that outputs true or false

inland stag
#

ah, I have to set payload_available and payload_not_available respectively?

marble jackal
#

or do this

      availability:
        topic: "venus/N/xxx/vebus/289/Energy/OutToInverter"
        value_template: "{{ 'online' if value_json.value | is_number else 'offline' }}"
inland stag
#

it worked with setting payload_available, but it still sets it to 0 first

#

I have these entities since December and never had this issue when HA restarted, but I also did not find any changes in 2023.12/2024.01/2024.02 changelogs

#

just doing a "Reload Manually Configured MQTT Entities" has the same behavior, first a 0, then the real value

lost locust
#
{{ states.binary_sensor | 
   selectattr('attributes.last_tripped_time', 'defined')
}}

this returns binary sensors with None in their last_tripped_time. is that to be expected? is the integration what's setting None or is that a HA default? I'm currently piping it to rejectattr to get rid of the nones but was wondering why that's needed.

mighty ledge
#

difined means "does the attribute exist"

lost locust
#

oooh, not "does it have a value." my bad πŸ˜…

mighty ledge
#

and it does exist, it just doesn't have a value

#

rejectattr('...', 'none')

lost locust
#

yeah, I need that after the selectattr because otherwise it'll error on entities not having that attribute

#

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'last_tripped_time'

#

(which makes sense to me)

mighty ledge
#

right

lost locust
#

last q: is friendly name not an attribute?

<template TemplateState(<state binary_sensor.alarm_zone_1=off; last_tripped_time=2024-02-29T17:27:59.635397, zone=1, bypassed=False, open=False, fault=False, alarm=False, tamper=False, low_battery=False, device_class=motion, icon=mdi:motion-sensor, friendly_name=Living room motion @ 2024-02-29T17:28:01.135575-05:00>)>
#

if i | attr("friendly_name") }} I get

'homeassistant.helpers.template.TemplateState object' has no attribute 'friendly_name'

#

ah, got it.

attr('entity_id') | state_attr('friendly_name') }}
inner mesa
#

what is attr('entity_id') supposed to do?

#

what you want is state_attr('someentity_id', 'friendly_name')

lost locust
#

I don't have the entity id at that point

inner mesa
#

it's not a thing

lost locust
#
{{ expand(integration_entities('envisalink_new')) | 
   selectattr('attributes.last_tripped_time','defined') | 
   rejectattr('attributes.last_tripped_time','none') | 
   sort(attribute='attributes.last_tripped_time', reverse=true) | 
   first | 
   attr('entity_id') | 
   state_attr('friendly_name')
}}
inner mesa
#

you can do {{ 'sensor.aarlo_battery_level_catbox'|state_attr('friendly_name') }}

#

I still don't think it's a thing

lost locust
#
{{
  expand(integration_entities('envisalink_new')) |
  selectattr('attributes.last_tripped_time','defined') |
  rejectattr('attributes.last_tripped_time','none') |
  sort(attribute='attributes.last_tripped_time', reverse=true) |
  first |
  state_attr('friendly_name')
}}

this gives me an error

#

AttributeError: 'TemplateState' object has no attribute 'lower'

#

but putting attr('entity_id') before the state_attr gets it to work

inner mesa
#

🀷

#

{{ states.sensor|selectattr('entity_id', 'search', 'catbox')|map(attribute='attributes.friendly_name')|list|first }}

#

waits impatiently for petro to prove me wrong

lost locust
#

haha

inner mesa
#

what I have above is how I would get the friendly_name

mighty ledge
#

that error means it's trying to treat the TemplateState object like a string

#

so you're feeding one of the functions wrong info

#

oh, it's that state_attr bs you have at the end

lost locust
#

lol yeah, I'm trying to get the friendly name

lost locust
#

state_attr seemed like a good way to get the friendly name, but I needed to pipe it an entity id for it to work

mighty ledge
#

well, when you use first, you chose the first object

lost locust
#

yep. I only want the most recently triggered sensor

inner mesa
#

I would just replace

  first |
  state_attr('friendly_name')

with

map(attribute='attributes.friendly_name')|list|first
mighty ledge
#

if you put map(attribute='name') before | first you get what you want

lost locust
#

will that break my sorting on last triggered?

mighty ledge
#

no

#

yoiu need the |list in there tho

#

like rob has

#

cause it's a generator after you map it

inner mesa
#

I agree that map(attribute='name') is better

#

it will choose friendly_name first

lost locust
#

word πŸŽ‰

#
{{
  expand(integration_entities('envisalink_new')) |
  selectattr('attributes.last_tripped_time','defined') |
  rejectattr('attributes.last_tripped_time','none') |
  sort(attribute='attributes.last_tripped_time', reverse=true) |
  map(attribute='name') |
  first 
}}
mighty ledge
#

it's just shorter and im lazy

inner mesa
#

yeah, I guess you don't need |list. |first does it

#

it's still a generator, but it works

lost locust
#

we did it. go team βœ‹

#

we all jumped and did an air high five at the same time, right?

inner mesa
#

it takes a village to write a template

#

I learned that I can probably remove some |list filters

lost locust
#

sed -i 's/| list//g' .* what could go wrong?

mighty ledge
lost locust
#

it'll be fine. that's what backups are for!

pallid moth
# marble jackal if you want to use it in a condition, it should output `true` or `false`

Thanks, WAI.

I try to push it further. This is my current template:
{{ (state_attr('climate.arbeitszimmer_heizung_links', 'current_temperature') or state_attr('climate.arbeitszimmer_heizung_rechts', 'current_temperature')) != states('sensor.arbeitszimmer_temperatursensor_temperature') | float(0) }}

Within the notification, I would like to take the state attribute friendly name of the climate that made the condition true to know which one to check Is it possible to do that? My current static approach is
⚠️ Heizung {{state_attr('climate.arbeitszimmer_heizung_links', 'friendly_name')}} prüfen.

plain magnetBOT
#

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

#

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

inner mesa
#

please stop

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.

inner mesa
#

you didn't say what isn't working

#

entity isn't showing up? entity doesn't work when you try to control it?

#

your icon_template could result in nothing, which will be a problem

steep bloom
#

Sorry…I’m clearly very new to Discord, too

#

The entity doesn’t even show

#

I’m going to try stripping out the icon_template

inner mesa
#

where did you put all that?

steep bloom
#

Configuration.yaml

inner mesa
#

you're also missing the name of the switch

#

see the example there, specifically the skylight: line

#

you don't have one of those

#

and:

plain magnetBOT
inner mesa
#

do that to check your configuration

steep bloom
#

Config works. It was the dumb name…I had it in an earlier version and was struggling with my tabs πŸ™ƒ THANK YOU!

marble jackal
small sparrow
#

Hello togehter,
just a, hopefully little, question to you experts here πŸ™‚

I've added a helper card to my dashboard which showing me a power consumption by daily reset.
Any option to shrink the shown amount to 2 decimal places ?

type: entities
entities:

  • entity: sensor.heizstab
    show_header_toggle: false
    state_color: false
    title: Heizstab KW/h

Right now its showing:
4,528188 kWh but I want to have like 4,52 kWh

Dont know if I'm righthere in templaes channel oO

marsh cairn
#

If you go to the sensor's details page, you can set the accuracy for many ones

feral spade
#

I get a template error I don't quite understand, as I would think I guard against it:

2024-03-01 11:47:42.803 ERROR (MainThread) [custom_components.openhasp] TemplateError('ValueError: Template error: int got invalid input 'unknown' when rendering template '{%- if not is_state('sensor.location_to_location_duration','unknown') %} {{states("sensor.location_to_location_duration")|int  | timestamp_custom("%Hh%Mm", false)}} {%- endif %}' but no default was specified') while processing template 'Template<template=({%- if not is_state('sensor.location_to_location_duration','unknown') %} {{states("sensor.location_to_location_duration")|int  | timestamp_custom("%Hh%Mm", false)}} {%- endif %}) renders=4>' in entity 'None'
marble jackal
#

@feral spade no, that doesn't work

#

is_state() always returns false when the entity doesn't exist (yet)

#

so not is_state('sensor.not_existing', 'unknown') will return true when the sensor doesn't exist

#

use {%- if states('sensor.location_to_location_duration') != 'unknown' %} instead, or maybe even better {%- if 'sensor.location_to_location_duration' | has_value %}

feral spade
#

thx. Once I actually managed to copy that it works

small sparrow
mighty ledge
#

jorg answered your question

marble jackal
#

@marsh cairn answered your quest... 🐌

small sparrow
#

oh dam I'm totaly sorry 😦
Did not recognized it that it was related to me because there was no detail page of this view. but he was talking about the settings of the sensor (in this case a helper) itself.
1000 times thx

spark vortex
#

why I can't use a template sensor like this in the statistic card?
`

  • sensor:
    • name: Totale total cost
      unit_of_measurement: "€"
      state: "{{ ((states('sensor.totale_consumi')|float(0)) * (states('input_number.price_per_kwh')|float(0)) ) | round(2) }}"`
mighty ledge
#

because you don't have the necessary requirements on that entity to generate statistics

spark vortex
#

what is missing?

mighty ledge
#

device_class, state_class, unique_id

spark vortex
#

uhm, what kind of device and state class should I use for it?

mighty ledge
#

Well, take a stroll over to the sensor documentation and read through the available device classes and paired unit of measurements

#

as for state_class, you probably want measurement

spark vortex
#

yes

mighty ledge
#

as a side note, utility meter does this for you

#

without needing a template

spark vortex
#

yeah, I see, but how can I create a similar utility meter?

mighty ledge
#

have you looked at the utility meter docs?

spark vortex
#

I mean in the conf, not in the UI

mighty ledge
#

also, if you just attach the cost sensor in the energy dashboard, it will do all the calculations for you

spark vortex
#

I want to use it in my dashboard graph and not in the energy dashboard

mighty ledge
#

there's an energy card specifically designed for this

spark vortex
#

wait, I can create widgets for my own dashboard from the energy one?

#

I am struggling with apexchart because it doesn't support group by month, so trying to build my own

mighty ledge
#

I know I've said docs a few times now, it would benefit you well if you got comfortable using the documentation

#

there's a whole dashboard section that shows you all available cards that you can place in your frontend, and a plethora of energy cards

#

one of them being cost

spark vortex
#

what kind of doc are you referring to?

mighty ledge
#

the home assistant documents

#

there's a whole website dedicated to documentation for home assistant

#

already linked it above

spark vortex
#

ok, I was thinking that there were a way to configure the widget, but they just use the energy configuration, so for example I cannot group by some time with this card type

#

but I can replicate the date picker and the bar chart in my own dashboard

mighty ledge
#

my man

#

the first card option for energy is the energy date picker

#

add the energy date picker, and the energy card you want, and you'll get monthly

#

I seriously urge you to read the documentation, don't just skim it

spark vortex
#

yes, I did it

#

`type: vertical-stack
cards:

  • type: energy-date-selection
  • type: energy-usage-graph`
#

but I dont see how to add also the costs

#

in the Energy page there is "source" table with the cost column, I don't see it in the card types

lofty mason
#

It's there, "Energy sources table" (energy-sources-table)

spark vortex
#

ah the full table, ok

#

not exactly what I sas looking for, but close

devout dragon
#

how do you know what attributes etc of sensor that you can template? im trying to set energyscore energy_treshold to a in input_number but failing at it πŸ™‚

mighty ledge
#

developer tools -> states page

sullen crow
#

suggestions for a card I can use with a Helper Template that identifies lights in my Basement Area that are on? I want to make a slider that controls on the lights that are on, the way you can do in the Hue app. I already made the template.

#

idk if this is possible

#

the template:

  states.light 
  | selectattr("state", "eq", "on")
  | selectattr('entity_id', 'in', area_entities('Basement'))
  | map(attribute='entity_id')
  | list 
}}
inner mesa
tender stump
#

Hey y'all.

Im trying to track my time spent working at my job. I would like to track a) time started, b) time finished and c) hours spent working. I will only "start work" and "end work" once a day (like a normal office job). Im also doing this to visualize the data. Im especially looking forward to seeing at what time i actually show up to the office each day visualized in a nice line graph like those "avg temperature each day" graphs.

Due to the nature of my work, I want to be able to automate start and end time via node-red, as well as having the option of manually entering a time for a day. I would like to use node-red due to too many factors for a simple Homeassistant automation (using geofencing, but also pinging if laptop is in wifi and some other stuff).

My Idea was to use 2 input helpers (input_datetime) for starting time and ending time, setting these via node-red and also having them in the homeassistent dashboard to be able to manually overwrite them. My plan was to then use a time-based-trigger (shortly before midnight) on template sensors to save a) time started, b) time ended and c) time spent working. This way, I would have exactly one datapoint per day and also the ability to have my node-red automations run during the day with me being able to overwrite them by setting the custom input_date in the UI during the evening before the trigger runs shortly before midnight.

The reason im asking for advice are the "input_datetime" entities. It seems to save the state as a string formatted as "hh:mm:ss". Im not sure how I would be able to visualize each datapoint per day via a linegraph down the line. I could make this into a unix-timestamp or take the last_modified timestamp, but then I would have the day as well, when i just need the time. I guess i could also separate the string and multiple hours by 24*60 and minutes by 60 to get the seconds past midnight. But then the charts will look ugly. Any advice?

(Hope this is the right place to ask. Running homeassistent in docker, got hacs set up and working, node-red etc. and all the tech-stack you would expect. Also work on IT...appreciate any inputs)

shadow summit
#

I'm trying to create a custom date&time sensor for use on a dashboard. I have used the HA date/time integration so I have sensor.time set up already. On the HA website, I got this code as a template for custome sensor. I've only changed a couple of the date/time attributes, nothing else. But when I reload my yaml I'm getting a template error message. Am I doing something wrong here?
https://dpaste.org/MzEze

haughty breach
shadow summit
haughty breach
#

The top-level key for your templates.yaml file should automatically be template (unless you did something weird πŸ™ƒ ), so that is the correct place for the second sensor in your example.

shadow summit
#

Here's the error log. Does this help narrow it down?

Logger: homeassistant.config
Source: config.py:597
First occurred: 12:40:45 PM (7 occurrences)
Last logged: 1:26:05 PM

Invalid config for 'template' at templates.yaml, line 12: 'platform' is an invalid option for 'template', check: sensor->0->platform Invalid config for 'template' at templates.yaml, line 12: required key 'state' not provided Invalid config for 'template' at templates.yaml, line 13: 'display_options' is an invalid option for 'template', check: sensor->0->display_options

inner mesa
#

You shouldn't have template: in that file. It goes in configuration.yaml

shadow summit
#

I have this in config.yaml: "template: !include templates.yaml"

inner mesa
#

You shouldn't have any platform: lines in that file either

shadow summit
inner mesa
#

What is in the file? And from what website?

shadow summit
haughty breach
#

Not all sensors are Template sensors. Sensors like Time and Date need to be in a file with sensor as the top-level key.

inner mesa
#

that doesn't go under template:

#

the example there doesn't show it

shadow summit
#

ok so the first part (with platform) goes in config? then the bottom half in template?

inner mesa
#

the whole thing can go in configuration.yaml if you don't already have a sensor: or template: tag in there

#

if you do, then you need to adapt it to your specific case

shadow summit
#

ok. that's helpful. I think I know what I need to do then. I'll give it a shot. Thanks.

copper narwhal
#

When writing a fan template...is it possible to incorporate the oscillation control into the entity?

https://dpaste.org/WDTsy

#

Pic shows an example from a different integration of what I'm trying to accomplish. Code is what I have so far but only gives control of speed and on/off

lofty mason
shadow summit
# shadow summit ok. that's helpful. I think I know what I need to do then. I'll give it a shot. ...

I think I'm getting close but the new date/time entity has a state of 'unavailable'. When I put the as_timestamp code into the template editor I get the following error:

ValueError: Template error: as_timestamp got invalid input '14:41, 2024-03-01' when rendering template '{{ as_timestamp(states('sensor.time_date')) | timestamp_custom('%A %B %-d, %I:%M %p') }}' but no default was specified

Is this where I need a date/time helper?

inner mesa
#

No

shadow summit
#

I'm working on the default part right now. I might have it.

inner mesa
#

Just use {{ (states(xxx)|as_datetime|as_local).strftime('%H:%M') }}

#

With whatever format string you want

shadow summit
#

Ok I'm really confused. So I'm building off sensor.time_date. That sensor is showing the correct date and time for my time zone.

When I plug it into here: state: "{{ as_timestamp(states('sensor.time_date'),0) | timestamp_custom('%A %b %d, %I:%M %p') }}" , it's giving me a result of Wednesday Dec 31 at 4pm.

inner mesa
#

You could use what I gave you

shadow summit
#

of course, replacing the xxx's with my sensor

inner mesa
#

{{ (states('sensor.date_time_iso')|as_datetime|as_local).strftime('%H:%M') }}

shadow summit
#

same error 😭

inner mesa
#

That will exist if you followed the docs

#

Doubtful

shadow summit
inner mesa
#

🀷

hollow quest
#

I have a list of entities that I want to select a single one from the list, based on matches. In other words, run match and if it gets no result, try the next match, and so on. Is there a concise way to do this other than if/else if?

shell nacelle
#

Any way to change what the upper and lower bounds of a color temperature for a bulb? I have a bulb that goes from 3000-6000k, and HA thinks it goes from 2000-6500k, which makes something like adaptive lighting display an incorrect color temperature when it updates. The slider functions through the entire range (setting it to 2000 displays 3000, and setting it to 6500 displays 6000, but anything in between is a mystery, I assume it scales by percentage), but I want a way to have the slider display the correct numbers

shadow summit
# inner mesa 🀷

idk either. not letting me paste a screenshot of mine but it's the same error.
Just to confirm, I have this:
""sensor:

Minimal configuration of the standard time and date sensor

  • platform: time_date
    display_options:
    • 'date_time_iso'""
      ...in my configuration.yaml. I have this:
      ""- sensor:
    • name: "Date and time"
      state: "{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%A %B %-d, %I:%M %p') }}"
      icon: "mdi:calendar-clock"""
      ...in my template.yaml
#

I made it work. I ended up using {{ as_timestamp(now()) | timestamp_custom('%A %b %d - %I:%M %p') }}

Thanks for helping point me in the right directions πŸ‘πŸΌ

normal rapids
#

Greetings, I have been playing wit a sensor template to scale an existing sensor.. and it is now working, but there is some existing data that I would like to delete (mistakes were made).. is there a way of removing the historical data/resetting ? I can comment out my definition in the YAMLand then delete the sensor entity, but when I enable my YAML definition the histroical data is still there.

#
  • Is old data cleaned up at all? (if the sensor has been deleted?)
#

(I suspect that I could change the id of my template for a fresh start.. but I am curious what the process is for old data)

void robin
#

So I want to send a notification when the fire alarm triggers and include what area the entity is tied to. Is this possible using templates?
Chatgpt didn't solve that. :/

wary yew
#

I'm getting several errors in the log related to templates:
Error while processing template: Template<template=({% if states('sensor.wiser_lts_heating_demand_guest_bedroom') | float > 0 %} red {% else %} grey {% endif %}) renders=2>

Why would that render a number? I have some issues with the wiser sensors. Might that be the cause? Maybe if the sensor is unavailable that happens?

lucid thicket
lucid thicket
#

Assuming you are using state trigger for your automation

wary yew
# lucid thicket Yes if the sensor is `unavailable` or `unknown` that template will fail because ...

what about this one:

Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=14>
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=16>
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=18>
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=20>
Error while processing template: Template<template=({{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}) renders=22>

I also get errors rendering a number.

lucid thicket
#

Share your code

plain magnetBOT
#

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

lucid thicket
#

And if that template is supposed to render a number it certainly does not

wary yew
lucid thicket
#

Make sure you are trying out your template in the template editor tool. devtools -> templates

wary yew
#

the template works, it returns what I want AFAIK

#

but I get those errors in the log often

lucid thicket
#

The consumption entity is sent to the round filter and will fail if it is unavailable

#

Are these source sensors going unavailable often?

wary yew
#

yeah, they're from custom integrations and have some bugs often and warnings with api calls. Might be that.

#

I have a few reported atm, but still ongoing.

mighty ledge
#

just provide a default for the round

#

your iff is wrong too

#

under icon

#

too many )

#

it's also wrong on badge_icon

#

and icon_color

#

wait, no, ignore me

wary yew
#

damn, I'm good, am I?

#

oh

mighty ledge
#

too early

wary yew
#

it was working fine tbh

mighty ledge
#

missed the is_state(

wary yew
#

just those logs

#

cool, np

mighty ledge
#

anyways, round(2, default='Na')

wary yew
#

just noticed @lucid thicket your point, it actually said in the log

homeassistant.exceptions.TemplateError: ValueError: Template error: round got invalid input 'unknown' when rendering template '{{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}' but no default was specified

#

still throwing me the error. It's weird. The code has the default, but the log doesn't show it.
{{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2, default='Na') }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}

homeassistant.exceptions.TemplateError: ValueError: Template error: round got invalid input 'unknown' when rendering template '{{ states('sensor.boiler_today') }}h / {{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_consumption_kwh')|round(2) }}kWh / Β£{{ states('sensor.octopus_energy_gas_e6e07423872221_1596914907_current_accumulative_cost') }}' but no default was specified
lucid thicket
#

I’m not good with #frontend-archived issues but I think you’ll have to make sure any browsers get refreshed, or just reboot ha. Do you have any tablets around the house that display that dashboard constantly?

wary yew
#

lemme reboot a second time then

#

clearing cache too

#

no tablets or other permanent dashboards, no

#

hmm yeah, looks like it's not showing up now. Must have been a browser cache then

#

thanks!!

#

aaahh, the pleasure of an empty log... so close!

mighty ledge
#

clear your cache and refresh the page on all devices displaying that card

#

that's the drawback of using frontend cards with the template engine

#

the frontend holds on to old templates until you refresh the page

#

no reboot, just refresh

lost locust
#

if I do a for a in areas(), the first area is a guid-like number. any idea what it is?

3ebde695493244268f79f03134f255a9
laundry_room
basement
upstairs_bathroom
...snip...
#

oh it's area IDs

#

πŸ˜…

#

is there a shorter/better way of writing this binary sensor template?

{{iif(is_state('binary_sensor.alarm_zone_7', 'on') or is_state('binary_sensor.alarm_zone_8', 'on') or is_state('binary_sensor.alarm_zone_9', 'on') or is_state('binary_sensor.alarm_zone_10', 'on'), "on", "off")}}
#

using range() or a for loop feels worse?

lost locust
#

I guess I could just use a group

void robin
lucid thicket
bronze prawn
#
{% set slots_unit = "hours" %}
{% set slots_name = "60" %}
{%-  if slots_unit == "seconds" -%}
  set multiplier = "1"
{%- elif slots_unit == "minutes" -%}
  set multiplier = "60"
{%- elif slots_unit == "hours" -%}
  set multiplier = "360"
{%- endif -%} 
{{ slots_unit }} * {{ slots_name}}
mighty ledge
#

You’re not actually doing math there and all your numbers are strings, which aren’t able to do math

bronze prawn
#

I'm struggling and could use a push. I am trying to set a timer using assist and want to disect things. If user says 'set timer for 2 hours' I want to take that part, know that 360 hours, then multiply.

@mighty ledge Right. I know my syntax is all wrong but thought if I put this it would be easier than trying to explain in words

mighty ledge
#

Secondly, multiplier won’t be accessible outside the if statement

bronze prawn
#

Ah okay. So really what I'm wondering is how to do this? I'm really a novice

mighty ledge
#

well, you an just do this

#
{% set info = {slots_unit: slots_name | int } %}
{{ timedelta(**info) }}
#

if you want to get a simple timedelta to offset a time

bronze prawn
#

WOW!

#

Okay, just tried. Not exactly what I need. Here's a couple examples:

Set timer for [60] <seconds> = 60 * 1 = 60
Set timer for [60] <minutes> = 60 * 60 = 360
Set timer for [60] <hours> = 60 *360 = 3600

The resultant value is the timer in seconds and then I am able to past that numerical value over to the timer. Should be a float in case someone says 'one and a half minutes'

mighty ledge
#

no, it's exactly what you need

#

if you need total seconds out of it...

#

{{ timedelta(**{slots_unit: slots_name | int}).total_seconds() }}

shrewd moat
#

Hey i have this template in a mushroom-template-card. The card gets auto generated with auto-entities.
replaced_entity just writes the name of the entity, not the value. Any ideas? I think I miss something as i'm new to HA and Jinja2

secondary: >
  {% set replaced_entity = entity|replace("switch", "sensor")|replace("schalter", "leistung") %}
  Leistung: {{replaced_entity}}
mighty ledge
#

60 * 60 * 24

bronze prawn
#
{% set slots_unit = "hours" %}
{% set slots_name = "60" %}
{% set info = {slots_unit: slots_name | int } %}
{{ timedelta(**info) }}

This returns :

2 days, 12:00:00

What I'm wanting is in time format hh:mm:ss

mighty ledge
#

try the second template I posted.

#

that will give you the total seconds which you can put into the service call

#
service: timer.start
target:
  entity_id: timer.mytimer
data:
  duration: "{{ timedelta(**{slots_unit: slots_name | int}).total_seconds() }}"
#

although, I migh thave to look up the args that timer accepts

shrewd moat
mighty ledge
#

so, that will work

#

you just have to declar slots_name and slots_unit in a separate variable step

#

or you can just use the slot directly there

bronze prawn
mighty ledge
#

change the int to float

bronze prawn
inner mesa
#
{% set trigger = {"slots":{"unit":"5", "name":"hours"}} %}
{{ trigger.slots.unit }}
``` -> `5`
mighty ledge
#

i'd be verys surprised if the slots aren't typed

#

if they are always strings, then that's an odd choice, especially if numbers come through

bronze prawn
#

I am running into an issue with the sentence I created so I think you are right. I think some are predefined and I can't just throw in {units} .. Will ask on #voice-assistants-archived

mighty ledge
#

make sure your predefinition keeps them at hours minutes, and seconds

#

any deviation (non-plural) will result in that template failing

bronze prawn
#

Right. It's a bit shaky as it is now but a little more logic would sure it up I think. If contains 'seconds' then set to 'second' type of thing

mighty ledge
#

yes but that can be done with a map

bronze prawn
#

Unfortunately I'm just an old guy who knows just enough to be dangerous πŸ™‚

mighty ledge
#

e.g. {% set translation = {'second':'seconds', 'minute': 'minutes', 'hour':'hours'} %}
{% set key = translation.get(trigger.slot.unit) %}
{% set info = {key: trigger.slot.name | float} %}
{{ timedelta(**info).total_seconds() }}

#

note, you'll have to include all the plurals in the translation dict

bronze prawn
#

you are a champion! Thanks so much for the help

plain magnetBOT
#

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

marble jackal
#

This is the YAML config of a trigger based template sensor

bronze prawn
# marble jackal This is the YAML config of a trigger based template sensor

Okay, so different question. I have a bunch of sensors that are platform: template is that different than how these are configured? What I'm really wanting to do is create a custom entity that has attributes that I can assign arbitrary names to . Is that possible? I know that if I try as a platform:template type I get errors

marble jackal
#

platform: template indicates you are using the legacy format, but both in the modern format and in the legacy format you can add attributes to your sensor

bronze prawn
#

Excellent. Thank you!

#

I've been using HA since the early days and don't keep up with all changes

#
template:
  - sensor:
      - name: AssistView_LR
        state: "idle"
        nightmode: "off"
        message: "test"

Just tried adding this to config.yaml but it does not appear in dev tools state after a reboot. Am I missing things totally?

inner mesa
bronze prawn
#

Got it now. Thank you both

bronze prawn
tidal meteor
zealous ibex
#

Can I write my own function so that every automation can use that function directly?

marble jackal
#

You can write macros and place them in the custom_templates folder so you can include them

tidal meteor
marble jackal
#

The one to your GitHub, are you sure it's public?

#

Now it works

tidal meteor
marble jackal
#

How do you include this folder?

tidal meteor
marble jackal
#

Okay, and what is the issue with this weather forecast sensor then?

tidal meteor
marble jackal
#

Did it already trigger?

#

It should have triggered at 11 CET 53 minutes ago, so it should have a state now

tidal meteor
marble jackal
#

Then there should be something in your logs

tidal meteor
#

found it:
Logger: homeassistant.helpers.script.trigger_update_coordinator
Source: helpers/script.py:1805
First occurred: 10:00:00 (6 occurrences)
Last logged: 11:00:00

Trigger Update Coordinator: Running script requires passing in a context
Trigger Update Coordinator: Error executing script. Error for call_service at pos 1: Weather entity 'weather.home' does not support 'hourly' forecast

marble jackal
#

There you have it

#

You need to add a second integration for met.no with the hourly forecast

#

Or wait until 2024.3

#

They will be both available in one integration as of then

tidal meteor
#

just enabled the hourly entity in the met.no integration
now just wait until 12:00

tidal meteor
marble jackal
#

Add an additional trigger, maybe a state trigger on an input boolean, or an event trigger on a custom event

tidal meteor
marble jackal
#

You're welcome
Graag gedaan
Ikke nevne det

inner mesa
#

regel een kamer

#

πŸ™‚

heavy crown
#

Hey all... I have a for-me unexpected result from a mqqt template sensor.

#
Entity sensor.linky_consumption_annual_blue_hc_eur (<class 'homeassistant.components.mqtt.sensor.MqttSensor'>) is using state class 'total_increasing' which is impossible considering device class ('monetary') it is using; expected None or one of 'total'; Please update your configuration if your entity is manually configured, otherwise create a bug report at https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue+label%3A%22integration%3A+mqtt%22
#

why can't a monetary value be total_increasing? This topic is my energy-consumption (total_increasing) x price/kWh

#

in my view this is still total_increasing (as it will do perpetually....until I die)

#

is this a bug indeed?

heavy crown
#

example (I have 6 of them):

#
    - state_topic: myelectricaldata/xxxxxx/consumption/annual/current/thisYear/tempo/BLUE_HC/euro
      value_template: "{{ value_json }}" 
      unique_id: linky_consumption_annual_blue_hc_eur
      name: linky consumption annual blue hc eur
      icon: mdi:lightning-bolt
      device_class: monetary
      unit_of_measurement: EUR
      state_class: total_increasing
tardy saddle
#

Invalid config for 'binary_sensor'. I am trying to make a yaml for binary sensors. In the configuration yaml I have binary_sensor: !include binary_sensor.yaml and then the binary sensor yaml is - name: freezer_warming2 unique_id: freezer_warming_sensor2 state: > {{ states('sensor.kitchen_freezer_temperature') | int > 20 }} device_class: problem I am getting an error ... Invalid config for 'binary_sensor' at binary_sensor.yaml, line 1: required key 'platform' not provided+ . How to fix?

inner mesa
#

Just as it says, you didn't include a platform line

#

You mixed up the old and new formats

#

Pick one

marsh cairn
#

Franken-YAML shksClap

inner mesa
#

the head of one format, the tail of another, and no torso

marsh cairn
tardy saddle
#

I read that integration template document until I’m blue in the face and I can’t figure out what I’m supposed to add.

inner mesa
#

as I said, you're mixing up the two formats

#

I suggest reading from teh top of that page, though

marsh cairn
#

If it is in binary_sensor:, it is the old legacy format (and needs the platform defined).
If it is in template:, it is the new recommended format.

tardy saddle
#

I only just started doing HA and I don't know the old format and the new format. I just copied stuff and changed a few words. I copied it directly off of that document.

#

OK, so I need to delete the binary sensor yaml file and put everything in the template yaml

marsh cairn
tardy saddle
#

so you put sensors and binary sensors all in the template Yaml file

inner mesa
#

If you just want the answer:

template:
- binary_sensor:
  - name: freezer_warming2
    state: "{{ states('sensor.kitchen_freezer_temperature')  | int > 20 }}"
    unique_id: freezer_warming_sensor2
#

put that in configuration.yaml

tardy saddle
#

I thought the idea was to put all of this in separate files, so it was easier to find

inner mesa
#

you can if you want

#

you cannot put that under binary_sensor: because it doesn't belong there

tardy saddle
#

that's why I was putting it in the binary sensor why yaml file

inner mesa
#

which was wrong

#

it doesn't belong there

#

it belongs under template:

tardy saddle
#

but it is a binary sensor, so why would it not go in the binary sensor file?

inner mesa
#

no

#

like I keep saying

#

it starts with template:

tardy saddle
#

sorry I'm being really dense I don't mean to be stupid

inner mesa
#

you're also welcome to read the link above that shows how to use the legacy format, which does belong under binary_sensor:

#

but then you need to write it properly for that format

tardy saddle
#

like I said, I don't know the old format so I'd rather just use the new stuff. And it sounds like what you're telling me is everything goes in the template and forget the whole idea of putting it in the separate binary sensor file.

inner mesa
tardy saddle
#

thank you very much for being patient with me! I appreciate it. I think I got it working.

bronze prawn
#

Is there a way to check a variables value to see if it contains numerals or if it contains alphabetic characters? I'm wanting to check "10" and "minutes" to know which is the number and which is a word describing the units

inner mesa
#

The is_number filter/test

bronze prawn
#

DId some searching but not seeing this. Is the concept to try and convert string to int and if it gives error you can assume it does not contain only numbers?

inner mesa
#

Many examples

haughty breach
#
{% set x = '20 minutes' %}
{% set unit = x.split()|reject('is_number')|first %} {{unit}}
{% set qnty = x.split()|select('is_number')|first %} {{qnty}}
bronze prawn
#

Thank you both for the help

crimson lichen
#

{{ trigger.event == 'enter' }} is correct?
For Zone trigger

marble jackal
crimson lichen
#

I often use conditionals {{ trigger.to_state.state != trigger.from_state.state }}
Is it accurate?
I'm not sure but it still works

crimson lichen
#

Do i can change from {{ trigger.to_state.state != trigger.from_state.state }} to {{ trigger.to_state != trigger.from_state }}

marble jackal
#

As you can see in the linked docs, trigger.event will either be "leave" or "enter"

#

For a platform: zone trigger that is

#

So not trigger.event.data

crimson lichen
#

thanks

#

in the linked docs is trigger.from_state and trigger.to_state
But i find many guidline templates is trigger.to_state.state and trigger.from_state.state
So which one is correct?

marble jackal
#

trigger.to_state will be the entire state object of the entity that caused the trigger

#

The state will be one of the objects of the state object

#

So trigger.to_state.state will give you the new state of the entity which caused the trigger

crimson lichen
sonic sand
#

@marble jackal I moved to #templates-archived .
What should I put on the template to do the tricky stuff on sending actionable notification depend on the person that enters the home zone? How complicated is that gonna be? also is it harder to create an option that if Robot Vacuum hasn't cleaned for 3 days it will send us an actionable notification that asks if he can run even tho' there's people in the home zone and they haven't left (together) for 3 straight days?
That's wife requirements hehe πŸ˜‚
[http://pastie.org/p/0UUZHQpF6iVK8M8Em4HcZl]
Thanks for helping and I appreciate that very much!

bronze prawn
#
  - name: chore_drying
    state: >-
      {% if states('input_boolean.dryer') == 'on' and states.input_boolean.dryer.last_changed|float < (as_timestamp(now()) - 180) %}Drying{% else %}Idle{%endif%}
    attributes:
      finish_time: ''
      attention_time: '{{ (as_timestamp(now()) - states.sensor.chore_drying.attributes.finish_time) | timestamp_custom("%H:%M:%S", false)}}'     
      needs_attention: 'off'

Here's a template sensor I'm working on. When drying finishes I set the finish_time with the as_timestamp(now()) from a python script that can set that attribute. I know that the attention_time is only updated once every 30/60 seconds but when it does I lose the value in finish_time and attention_time shows as null. Am I going about this all wrong?

mighty ledge
#

the themplates are wrong

#
{% if is_state('input_boolean.dryer', 'on') and states.input_boolean.dryer.last_changed < now() - timedelta(minutes=3) %}Drying{% else %}Idle{%endif%}
#

and

#
{{ now() - state_attr('sensor.chore_drying', 'finish_time') }}
#

but keep in mind, you have to ensure finish_time has a valid datetime

haughty breach
#

Also, don't use the python set attribute script... just move finish time to its own trigger-based sensor.

bronze prawn
# mighty ledge the themplates are wrong

Thanks for sure. Truth be told this just got moved from the old sensor definition over to the modern template format so I guess syntax changed or is different. That bit has worked for years.

bronze prawn
mighty ledge
#

it's never been valid syntax

#

states.input_boolean.dryer.last_changed is valid, and |float is valid, but combining the two will always result in an error

#

especially without a default for float

#

and it's gone

bronze prawn
#

Hoped I was quick enough. My problem was that I had what I needed commented out. Will take a break after I get this going.

#
  - name: chore_drying
    state: >-
      {% if is_state('input_boolean.dryer', 'on') and states.input_boolean.dryer.last_changed < now() - timedelta(minutes=3) %}Drying{% else %}Idle{%endif%}
    attributes:
      finish_time: 0
      attention_time: >-
        {{ now() - state_attr('sensor.chore_drying', 'finish_time') }}
      needs_attention: 'off'

Here's what I have now. State does not change when I toggle input_boolean.dryer on or offand attention_time does not show up in attributes.

#

I'm forcing finish_time to 0 which I thought would satisfy what you mentioned above but I suppose it doesn't

#

I'm not positive of what that value should look like. Is it unix time format?

mighty ledge
#

finish time should not be zero

#

why don't you have finish time calculated there?

bronze prawn
#

I'm not understanding the question. On HA restart this needs to have a value correct? If so, what value can I use as a place holder? Is this impacting the state change from input_boolen.dryer from being evaluated?

mighty ledge
#

it's impacting attention_time

#

that can't calculate if finish_time doesn't have a valid datetime

#

and in general, there's nothing that's going to make finish_time change

#

so what's the use of finish_time, if you're using something goofy to set finish time, you're not using HA or it's attributes properly

#

and all you'll be doing is causing yourself pain

#

(like this)

#

At this point, I think it would be better to describe your whole goal instead of focusing on this small single template

bronze prawn
#

Thank you for your continued patience. I am coming from a place where I know what I'd like to accomplish but not sure how to go about doing it.

For this case, I had a template sensor in the old format that was used to determine if my dryer was 'idle' or 'drying'.

Now I am wanting to extend this so that I can know how long it has been since the sensor went from 'drying' to 'idle' so that I can use that value to send a reminder to action taking out the clothes and/or displaying this on my dashboard.

#

I already get notifications when the state changes as mentioned but I'd like to know if it's been hours since it was taken care of. I have this set for both washer and dryer with washer more critical to get into the dryer on time.

mighty ledge
#

These are going to be simple template entities

#

utilize the built-ins that HA offers

#

for example, a template sensor that knows the time the input_boolean was turned on

#
template:
- trigger:
  - platform: state
    entity_id: input_boolean.xyz
    to: 'on'
  sensor:
  - name: Last on
    state: "{{ now() }}"
    device_class: timestamp
#

put that anywhere in your UI and it will be translated to the last time it ran, i.e. 15 min ago

#

you can do the same for when it turns off

#

then just build automations off that

#

or if you want a notification if it was turned off 3 hours ago, completely avoid the template and use a trigger

#

in your automation

bronze prawn
#

Understood. I was trying to consolidate things rather than have a lot of different 'helpers'

mighty ledge
#
- platform: state
  entity_id: input_boolean.xyz
  from: 'off'
  to: 'on'
  for:
    hours: 3
#

you don't need helpers, you can probably do all this without helpers, but it seem slike you're stuck in the past

#

HA has changed alot

#

start using the new stuff

#

if you want to display something in a dashboard, you will need helpers

#

notifications though, most likely no helpers needed. Just an automation

bronze prawn
#

When I said helpers I meant more that what you are suggesting is a separate entity helping rather than included in the attributes.

mighty ledge
#

and that's what I'm saying, you'll need these things to display them on the dashboard

bronze prawn
#

HA has changed alot

Yeah, this is a good thing but does mean learning new stuff. I'm good with it for sure but a bit difficult when I'm not tracking everything that has changed. I'll get there.

mighty ledge
#

attributes do not allow for translations

#

states do

#

i.e. more helpers

#

less attributes

bronze prawn
#

Understood and thanks again. I will rethink/rework my approach.

marble jackal
# sonic sand <@723160143314812971> I moved to <#672223497736421388> . What should I put on th...

you need something like this:

trigger:
  - platform: state
    entity_id:
      - person.a
      - person.b
    to: home
condition: state condition vacuum is running
variables: 
  notify_mapper: # should match the persons from the trigger
    person.a: notify.mobile_phone_foo
    person.b: notify.mobile_phone_bar
action:
  - service: "{{ notify_mapper[trigger.entity_id }}"
    data:
      message: Watch out for the vacuum robot
devout dragon
#

in jinja is it possible to select all values in an list that is greater than a given value ?

#

or do i need to do a for loop and count then myself? πŸ™‚

inner mesa
#

It's trivial

#

{{ [1, 2]|select('>', 1)|list }}

devout dragon
#

Ah, sure it might be but i could not find a single example on it and been searching for 10mins πŸ™‚ either i suck at google or its not very common πŸ™‚

devout dragon
#

any idea of doing a range between two float numbers with a step of say 0.1 ? πŸ™‚

wary yew
#

This error started popping in my log lately, even when these templates have existed for a few months.
https://dpaste.org/5WHch
Looking at the comon one among the errors there is no single common sensor causing this. I think the culprit is when calling the last_changed value on any of the sensors. The errors show up when rebooting HA. They don't seem to occur again later.
Can you help me debug the issue?

#

I recall reading in the docs that using states.sensor... could cause issues when booting and the sensor was not still available. This seems something like that, but unsure. Anyway, there's no other way AFAIK to get the last-changed value. Also it never showed up before, not sure why now.

bronze prawn
#
{% set my_test_json =  {'artists': [], 'albums': [], 'tracks': [{'item_id': '4VywXu6umkIQ2OS0m1I79y', 'provider': 'spotify', 'name': 'Better Together', 'uri': 'spotify://track/4VywXu6umkIQ2OS0m1I79y', 'external_ids': [['isrc', 'USMC60400027']], 'media_type': 'track', 'duration': 207, 'artists': [{'item_id': '3GBPw9NK25X1Wt2OUvOwY3', 'provider': 'spotify', 'name': 'Jack Johnson', 'version': '', 'sort_name': 'jack johnson', 'uri': 'spotify://artist/3GBPw9NK25X1Wt2OUvOwY3', 'external_ids': [], 'media_type': 'artist'}], 'album': {'item_id': '7tTc46dNdE6GGuiQsssWxo', 'provider': 'spotify', 'name': 'In Between Dreams', 'version': '', 'sort_name': 'in between dreams', 'uri': 'spotify://album/7tTc46dNdE6GGuiQsssWxo', 'external_ids': [], 'media_type': 'album', 'year': 2005, 'artists': [{'item_id': '3GBPw9NK25X1Wt2OUvOwY3', 'provider': 'spotify', 'name': 'Jack Johnson', 'version': '', 'sort_name': 'jack johnson', 'uri': 'spotify://artist/3GBPw9NK25X1Wt2OUvOwY3', 'external_ids': [], 'media_type': 'artist'}], 'album_type': 'album'}}], 'playlists': [], 'radio': []} %}

{{ my_test_json['tracks'] }}
#

Can someone tell me how I can structure the template response to grab the 'uri' value from within 'tracks'

#

I'm able to pull 'tracks' but don't know how to index to grab 'uri' within

dreamy sinew
#

my_test_json.tracks[0].uri

#

that'll get the first one

inner mesa
#

or {{ my_test_json['tracks']|map(attribute='uri')|list }} if there's more than one

dreamy sinew
#

^

bronze prawn
#

perfect. Thanks to you both

daring swift
#

They don't show up as entities

inner mesa
#

So many issues

#

There's no way a config check passes

daring swift
#

Fortunately it does and haven't had problems until tonight

inner mesa
#

I suggest re-reading the template sensor docs

daring swift
#

I just switched the templates back to the templates.yaml file with the include

inner mesa
#

It's just a mishmash of old and new formats

#

Your indentation of packages: is wrong, so I'm curious what it does with that

daring swift
#

I had to indent that because it threw an error when I had it indented like the rest

daring swift
#

So now I have to put - sensor before each of them?

inner mesa
#

It is a list, and you need to follow that format. And then you switched formats halfway through

daring swift
#

Why if I copy and paste those into developer tools template does it work fine?

inner mesa
#

Because it doesn't care at all about the YAML format

daring swift
#

I have all of the binary sensors working now but the sensors are not

inner mesa
#

You have a value_template in there

#

Should be state:

daring swift
#

That fixed it plus adding the - sensor before each one

#

Thank you @inner mesa!

#

Now to get this thing counting how many times my sump pump runs

inner mesa
#

You don't need - sensor: before each one

daring swift
#

You are correct again. Fixed that. I think I have my sump pump tracker going too. It's running way too much

sonic sand
sonic sand
#

--
In the first automation I got the template

{{ (this.attributes.last_triggered | default(0 | as_datetime, true) | as_local).date() != now().date() }}

I'm trying to set the this to the vacuum entity (which have no attribute of last_triggered) and it gives me an error in dev tools of 'vacuum' is undefined
I also tried to change the entity to sensor.roborock_s8_pro_ultra_last_clean_begin which has a state of timestamp, it gives an error of 'sensor' is undefined

marble jackal
#

{{ (states('sensor.roborock_s8_pro_ultra_last_clean_begin') | as_datetime(as_datetime(0)) | as_local).date() != now().date() }}

#

this only works on 2034.2 or higher

sonic sand
#

so if it's true the condition pass right?

marble jackal
#

yes

sonic sand
#

so why is it not triggering the automation? after changing to the right template in the condition part

http://pastie.org/p/7kSPkmZxBIIx2QxgbwZZzn
zone.home state shows 0
and
template returns true on Developer Tools.

marble jackal
#

the state has to change form above or equal to 1 to below 1

#

there has to be a state change

#

change it to 1 in devtools states, then change it back to 0 and wait 45 minutes

#

also, if you make a change to the automation in this 45 minute period (or restart HA), it won't trigger anymore

sonic sand
marble jackal
#

there is a good example on actionable notifications in the companion docs

silent vector
#

Does anyone know of an easy way to calculate variance in jinja from a list of numbers?

mighty ledge
#

make each variable as you loop

#

with namespace

#

no different then any other equation

sonic sand
haughty breach
#

I use a macro for variance:

{% macro variance(values=[], is_pop=false) %}
{%- if values is not list %}Values must be in the form of a list.{%- else %}
{%- set p = 1 if not is_pop else 0 %}
{%- set l = values|select('is_number')|map('float', 0)|list %}
{%- set m = l|average %}
{%- set n = l|count %}
{%- set ns = namespace( z = []) %}
{%- for L in l %}{% set ns.z = ns.z + [(L - m)**2]%}{%endfor%}
{%- set var = ((ns.z|sum)/(n-p))|round(3, 0) %}
{{- var }}{%- endif %}{%- endmacro %}
mighty ledge
#

this is where numpy would be great

#

but man would it suck to integrate numpy into jinja

silent vector
#

What is is_pop for?

#

oh population?

mighty ledge
#

seeing that it's the denominator in the equation, yes it would seem it's is_population

#

and it's 0 or 1, so it reduces n by 1

#

or 0

silent vector
#

Sounds good

bronze prawn
#

['Baking Powder', 'Fabuloso', 'Aluminum Foil', 'Frozen Corn', 'Clear Caulk', 'Eggs', 'Bread', 'Blueberry Bagels', 'Muffin Mix', 'Tortillas', 'Ground Meat', 'Avocados', 'Chocolate Instant Pudding']

I've got this array coming in as a response variable. I would like to do a find/replace for the single quote character but I cannot figure out how to do this. I know some other times in other instances I've been able to use ' or "'" type thing but can't get those to work with templating.

#

To be clear when I'm showing these on my card the values are showing with the single quotes and I'm trying to get rid of them.

marble jackal
#

{{ ['Baking Powder', 'Fabuloso', 'Aluminum Foil', 'Frozen Corn', 'Clear Caulk', 'Eggs', 'Bread', 'Blueberry Bagels', 'Muffin Mix', 'Tortillas', 'Ground Meat', 'Avocados', 'Chocolate Instant Pudding'] | join(', ') }}

bronze prawn
marble jackal
#

first 10:
{{ ['Baking Powder', 'Fabuloso', 'Aluminum Foil', 'Frozen Corn', 'Clear Caulk', 'Eggs', 'Bread', 'Blueberry Bagels', 'Muffin Mix', 'Tortillas', 'Ground Meat', 'Avocados', 'Chocolate Instant Pudding'][:10] | join(', ') }}

last 10
{{ ['Baking Powder', 'Fabuloso', 'Aluminum Foil', 'Frozen Corn', 'Clear Caulk', 'Eggs', 'Bread', 'Blueberry Bagels', 'Muffin Mix', 'Tortillas', 'Ground Meat', 'Avocados', 'Chocolate Instant Pudding'][-10:] | join(', ') }}

bronze prawn
#

Thanks for your patience. I said that was the last thing but this has broken a different part. I was doing a substitution for the separator and replacing it with a line break:
"{{ shopping_response['items'][-10] |regex_replace(find=',', replace='<br />')| join(', ')}}"

So what I'm wanting is the output to show the first/last 10 items but have each start on a new line. I'm not sure how to accomplish that now

#

I got it

marble jackal
#

join it with <br /> instead of a comma

bronze prawn
#

haha... so much easier. I'm getting closed to finished. Thanks again for the help and patience

devout dragon
#

hmm, in sensors etc im using attributes for different things that belongs to the same sensor... but in those attributes they can reference other attributes in the same sensor .. is that bad practice? like "sensorname.price_max" checks the max "sensorname.prices | max" for example

mighty ledge
#

if it works, it's not bad practice

#

bad practice with templates & template entities is using an automation to set attributes via some weird python script

#

if you post everything involved in what you think is bad practice, we may be able to simplify your process.

devout dragon
#

was thinking mostly cause im getting template errors in the logs that its a None Object, but it all still works so i guess its when the template is loaded something is "calculated" to early

#

seems to be when i reload the templates it happends πŸ™‚

mighty ledge
#

yes, that means there is room for improvement

sonic sand
cerulean oyster
#

I've run into a problem today which I could solve somehow, but I will ask, if someone can explain me, why this had happened and if I can solve it in another (better way).
In a decluttering-card I calculate several time the battery charge percentage:

  card:
    type: custom:mushroom-template-card
    secondary: >
      {% set level = calcBatteryLevel %}
    icon: >
      {% set level = calcBatteryLevel %}
    icon_color: >
      {% set level = calcBatteryLevel %}

Then upon the level I display different text, icon and or color.
If I use the variable "level" in every case (like above), on one HASS it works, on another one i.e. the icon had not the color I specified, t was gray:
Using different variable names, like "txt_level", "icn_level", "col_level" it works.
Why does this happen? Can I calculate the level once?

inner mesa
#

each template is independent, they don't share a scope

#

I don't really understand that use case - you're just assigning a variable and not using it anywhere

cerulean oyster
#

I understood, that each template is independent. "calcBatteryLevel" is a funktion like this:

      {% set bat_level = ((states('[[entity]]') | int - '[[lower-limit]]'|int) / ('[[upper-limit]]' | int - '[[lower-limit]]'|int) *100) | round(0) %}

Having this expression in the template several times, the icon_color does not work on one HASS but on the other one.
The code is the same in both.
And sure, I have further a bunch if if-statements, I only wouldn't post them here.

mighty ledge
#

is that psudeo code? That's not valid jinja

#

if you want to reuse jinja code, use custom_templates

fickle sand
#

Guess it's meant to be used with decluttering card

mighty ledge
#

doesn't decluttering card us JS?

fickle sand
#

Yes it does

mighty ledge
#

then it's definitely not going to work

cerulean oyster
#

No, it is not pseudo code, I only wouldn't post all the code, since it is a lot.
And yes, it is decluttering-card and it works, I'm working in yaml-mode, not UI-mode.

My problem was, that it didn't work when I use everywhere the same variable "level", but it works using a a different in the cases.

fickle sand
mighty ledge
#

so, your only option is to copy/paste

#

cluttering card in this situation

cerulean oyster
#

I have no problemn with copy/paste the equation, my problem was, why the variables have to have different names.

#

Btw, I've tried this withis the decluttering-card:

    secondary: >
      {% from 'test.jinja' import battery_level %}
      {{ battery_level('[[entity]]') + ' %' }}

with the macro:

{% macro battery_level(entity_id) %}
{% set level = ((states(entity_id) | int - 2800) / (3600 - 2800) *100) | round(0) %}
{{ level }}
{% endmacro %}

and it works.

mighty ledge
#

states.binary_sensor.stairs_motion_sensor_occupancy doesn't exist in the state machine

#

error probably only occurs on startup

#

if the template is in the frontend, consider moving it to the backend.

wary yew
mighty ledge
#

Template sensors, they don’t persist through startups like the frontend will

wary yew
#

you mean creating a sensor that returns the value of the last_change of the sensor I want and using that in the dashboard instead?

mighty ledge
#

Yeah that’s one way

wary yew
hazy yacht
#

Experimenting with templates I often phase the challenge that the value of a state changes to something which throws an error in the template. Even worse this might happen anytime later an that makes debugging very difficult. Is there any way to test templates with all kind of different states, unlike letting me change the values manually by hand one-by-one?

#

I also came up with the idea that it might be very helpful if a mouse-hover-popup could be added to the template editor, so that one can see the current value of a state keeping placing the mouse over an entity. If you think that sounds nice, I would formulate a feature request on github

haughty breach
#

a list and a loop...

mighty ledge
#

use {% set value = states('xxxx.xxx') %} in your actual template, but when you test replace it with {% set value = 'whatever you want to test' %}

mighty ledge
hazy yacht
#

Thanks I will do so.

hybrid halo
#

Hi! I am looking for a solution how I could make a sensor that would monitor the calendar entity as shown below, I would like to get the data in the order of the events which are more recent first and for the next 7 days. The current code displays the next event for each calendar separately, which can be several months apart and there can be multiple events within the same calendar within 7 days. ```yaml
Start at: {{ state_attr("calendar.prazniki_v_sloveniji","start_time")}} {{ state_attr("calendar.prazniki_v_sloveniji","message")}}
Start at: {{ state_attr("calendar.krscanski_prazniki","start_time")}} {{ state_attr("calendar.krscanski_prazniki","message")}}
Start at: {{ state_attr("calendar.pravoslavni_prazniki","start_time")}} {{ state_attr("calendar.pravoslavni_prazniki","message")}}
Start at: {{ state_attr("calendar.zodiac","start_time")}} {{ state_attr("calendar.zodiac","message")}}
Start at: {{ state_attr("calendar.f1","start_time")}} {{ state_attr("calendar.f1","message")}}
Start at: {{ state_attr("calendar.moto_gp","start_time")}} {{ state_attr("calendar.moto_gp","message")}}
Start at: {{ state_attr("calendar.odvoz_odpadkov","start_time")}} {{ state_attr("calendar.odvoz_odpadkov","message")}}
Start at: {{ state_attr("calendar.dom","start_time")}} {{ state_attr("calendar.dom","message")}}
Start at: {{ state_attr("calendar.robert","start_time")}} {{ state_attr("calendar.robert","message")}}

haughty breach
hybrid halo
hybrid halo
haughty breach
#

It needs to go either directly in your configuration.yaml or in a file that is merged with the top-level key template...

#

Look in your configuration.yaml to see if you have a line like template: !include some_file.yaml, if you do, put it in the named file.

haughty breach
#

Please clarify what you're asking by that...

hybrid halo
plain magnetBOT
#

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

haughty breach
#

What makes you think you did something wrong?

hybrid halo
haughty breach
#

The values will not populate until a trigger fires.

#

If you want to manually make it to populate, you need to add a trigger that you can control.

hybrid halo
haughty breach
hybrid halo
plain magnetBOT
haughty breach
#

Just get rid of the single quotes so you are using the variable
... selectattr('entity_id', 'in', area_entities(area)) ...

open vapor
mighty ledge
#

all the alternatives involve template sensors of some sort

#

there's endless template entites you can come up with, so alternatives are not really discussable

wary yew
#

I've gone down that route but I don't think I'm doing it right. I'm getting even more errors than before. Here are the 3 created sensors.

- platform: template
  sensors:
    front_door_last_changed:
      value_template: >-
        {{ relative_time(states.binary_sensor.front_door_contact.last_changed) }}
    back_door_last_changed:
      value_template: >-
        {{ relative_time(states.binary_sensor.back_door_contact.last_changed) }}
    side_door_last_changed:
      value_template: >-
        {{ relative_time(states.binary_sensor.side_door_contact.last_changed) }}
mighty ledge
#

teh first error is the only one related to those templates

#

the other errors are still your frontend

wary yew
#

oh right, checking them now, mb

mighty ledge
#

you'll have to add availability tempates to those template sensors

#

availability_template: "{{ 'binary_sensor.back_door_contact' | has_value }}"

scenic verge
#

is it possible to make the following "less then"?

#
  hours: 0
  minutes: 0
  seconds: 0```
#

so person detected, but for LESS then 2 minutes.

#

the usual is 2 or more.

mighty ledge
#

only with templates

#

if it's a condition, you can use 'not' to get less than

#

because for is technically greater than or equal to

scenic verge
#

hmm? can you link me a example please? ^^

#

about "not"

mighty ledge
#

go into the UI for your automation, search not in the condition area

#

I don't have the yaml memorized

wary yew
#

a single log error left after fixing the templates, I'm so happy 😭 😭 😭 😭 😭 😭

plain magnetBOT
#

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

scenic verge
mighty ledge
#

I believe it would

scenic verge
#

thanks!

obsidian kayak
#

Hello, I have made a helper a sensor that calculates the realtime power used by taking the sum of solar generation (e.g. 1000 watts) and the amount that my meter measures going back to the grid (e.g. -800 watts) resulting in a use by my home of 200 watts. however, at night times the helper sensor goes to 'unknown' as the transformer shuts off and the generation sensor becomes unavailable. what would be the easiest way to fix this problem? thanks for any insights :)

obsidian kayak
inner mesa
#

definitely some odd choices

obsidian kayak
#

hey I never used this before :-) this already better I think?

{% set current_power = states('sensor.p1_meter_power') %}
{% if is_number(states('solar_power')) %}
{{ solar_power + current_power }}
{% else %}
{{ current_power }}
{% endif %}```
inner mesa
#

all states are strings, so you need |float to convert them to numeric values if you want to perform math on them, optionally also providing a default like |float(0)

#

otherwise, yes, that's a better attempt

obsidian kayak
languid sandal
#

I have a rgb strip and i have connected it using dynalite integration. Can somebody please help me in making a template which can combine the channels created as lights to be a single rgb light in home assistant

marble jackal
#

As long as the first one is "0" the result will look correct

obsidian kayak
quiet creek
#

Trying to make a template to display the amount of specified lights and switch entities as lights on. Here is what I currently have that is not working

#
          {% set light_states = states.light | selectattr('entity_id', 'in', entities) | selectattr('state', 'eq', 'on') | list %}
          {% set switch_states = states.switch | selectattr('entity_id', 'in', entities') | selectattr('state', 'eq', 'on') | list %}
          {% set count = light_states | length + switch_states | length %}
          Lights {{ count }} on```
haughty breach
#

You have a stray ' in the set switch_states statement, but you can do it easier just selecting with the is_state
test:

{% set entities = ['light.aidan_s_bedroom_light', 'light.monitor_ambilight', 'light.3d_printer_light', 'switch.power_strip_socket_1', 'switch.garage_lights', 'switch.chicken_coop_socket_1'] %}
{% set count =  entities | select('is_state', 'on') | list | count %}
Lights {{ count }} on
hardy laurel
#

I am using the Mushroom Template card to display some information about my dishwasher. There is a sensor that keeps track of when the cycle will be complete.

I'm trying to display that in the format of something like in x minutes

I am using this as the template value:

{{ states('sensor.dishwasher_dishwasher_completion_time') | relative_time }}

However, it's still displaying it in the datetime format

2024-03-07 05:51:28+00:00
lucid thicket
bitter ledge
#

Perhaps a dumb question, but I'm trying to figure out what's going on with my very simple dusk to dawn helper sensor. {{states('sensor.sun_solar_elevation') < '-6' }} bounces between states around sunset and sunrise. Any idea why or how I could solve this?

#

This is the logbook
Turned on
7:11:30 PM - 4 hours ago
Turned off
6:46:04 PM - 5 hours ago
Turned on
6:16:34 PM - 5 hours ago
Turned off
6:48:49 AM - 17 hours ago
Turned on
6:19:27 AM - 17 hours ago
Turned off
5:58:40 AM - 17 hours ago

inner mesa
#

States are strings

#

And comparing a string with a string like that is guaranteed to not be what you want

bitter ledge
#

Ah, ok. Makes sense. Will revise. Thank you.

inner mesa
#

{{states('sensor.sun_solar_elevation')|float(0) < -6 }}

#

Or you can use state_attr('sun.sun', 'elevation') < -6

#

You don't need the other sensor and attributes retain their types

bitter ledge
#

Even better. Thanks a bunch!!!

marble jackal
crimson lichen
#

thank

sonic sand
marble jackal
#

can you check in the trace where that error comes from

sonic sand
marble jackal
#

probably this would solve it

  - alias: Check if the values are correct
    condition: template
    value_template: >
      {{ 
        values is defined and values.value is defined and values.timestamp is defined
        and not (values.value == 'unknown' and values.timestamp == 'unknown')
      }}
#

at least avoid the error message πŸ™‚

sonic sand
#

still
Error running action Error rendering data template: UndefinedError: 'values' is undefined

marble jackal
#

are you running it manually?

sonic sand
#

Yeah the telegram photo part

#

Should I try to trigger it and not manually?

marble jackal
#

how do you mean?

#

can you send the json download of the trace?

#

conditions are not checked if you trigger it manually, so changing a condition won't solve it if you run it manually

sonic sand
#

this is the trace of normal trigger (fed them right now)

marble jackal
#

you pasted the entire condition as template in the condition

#

you now have:

  - alias: Check if the values are correct
    condition: template
    value_template: >
      - alias: Check if the values are correct
        condition: template
        value_template: >
          {{ 
            values is defined and values.value is defined and values.timestamp is defined
            and not (values.value == 'unknown' and values.timestamp == 'unknown')
          }}
#

you can just change anything in that attribute in devtools > states to trigger the automation again

sonic sand
#

oh i haven't slept tonight that's for sure, just fixed it. sorry

#

let me try to trigger again now

#

Thanks It's working now πŸ™‚
also got a question related to the Robot Vacuum automation you helped me with template there.
http://pastie.org/p/5Q7jBoOIKmEQD2XZhF5gcl
It is changing the value to true after midnight (by date) right?
so that's why I have set up that condition is time after 10:30AM, but it will have to re-trigger itself to make it run, no?

marble jackal
#

With that condition it will start cleaning after 10:30 when everybody has left the house for 45 minutes

#

if the vacuum didn't clean earlier that day

sonic sand
#

or should we enter zone and leave it again to make it work?

marble jackal
#

yes

#

that will work

#

not specifically at 10:30 AM though

#

it will trigger when you leave the house

sonic sand
#

yeah because of the 45 minutes check, right?

marble jackal
#

not at 10:30, that is not a trigger

sonic sand
#

yeah yeah I know

#

Wife asked for a feature to this automation to send actionable notification if vacuum hasn't cleaned for 3 days, how can I approaches that to make it work in your opinion?
Thanks for helping man!

marble jackal
#

what should be the trigger then? At a certain time? When it has exactly been 3 days? Something else?

sonic sand
#

well I got sensor.roborock_s8_pro_ultra_last_clean_begin sensor which shows timestamp of the last clean time, I thought of using that as a starter

marble jackal
#

yes, so you want to get a notification exactly 3 days after that date?

#

which could be any time of the day

sonic sand
#

by the way, I have tried to put the same fishing fed telegram notification automation in my Room Automation (I know you not gonna like this idea.. but I wanted to group all of them in one automation) and it's not sending the telegram photo...
This is the json of the traces - (The specific automation is called there 13 / line 1399
http://pastie.org/p/3rzfzdH4DID9jeXCFw1fIl
I guess it's has to do something with the variables.

marble jackal
#

you are making it way to complex if you combine them all

sonic sand
marble jackal
#

you need to move the creation of the variable, and the check if it has valid data in the section for that specific message

sonic sand
#

Move it to be under the then part?

sonic sand
#

The conditions are disabled so don't mind them^

marble jackal
#

those wait templates don't make sense, there is nothing to wait on

#

and they are already checked in the conditions (if you would enable tthose)

sonic sand
#

Yeah, so where should I move the creation of the variable you mentioned?

sonic sand
#

Okay it's working, I added the variables to the bottom of the automation yaml.
Thanks @marble jackal .
Now is there a chance you can help me with the Vacuum thingy we talked about earlier?

marble jackal
#
trigger:
  - platform: time
    at: your desired time
condtion:
  - condition: template
    value_template: "{{ now() - states('sensor.vacuum_last_time_whatever') | as_datetime | as_local > timedelta(days=3) }}"
action: 
  - send actionable notification according the example in the companion app docs
sonic sand
marble jackal
#

whatever you want. Combining automations adds additional complexity and the only advantage is that your list of automations is shorter

lost locust
#

is getting the trigger of a device trigger the same as an entity trigger?
I.e., ```
{{ trigger.to_state.attributes.friendly_name }}

marble jackal
#

depends on the device

#

some device triggers are state based, some device triggers are event based

lost locust
#

this one... is based on a "diagnostic binary sensor"

marble jackal
#

then it inherits the state trigger variables, and your template above should work

lost locust
#

thank you πŸ˜„

marble jackal
#

{{ trigger.to_state.name }} would work as well

lost locust
#

oh nice

haughty skiff
#

Good afternoon all. Is this the best place if I'm looking for assistance with some yaml code? Relatively beginner HA user, have only ever really used the GUI for most of my stuff up until this point.

fickle sand
haughty skiff
#

I think Jinja comes into play here? I'm trying to get a button to use call service Number: Set to set a speaker entities volume to either 0 or 100 when pressed, and only those values.

#

show_name: true show_icon: true type: button tap_action: action: call-service service: number.set_value data: value: '0' target: entity_id: number.tapoc111_speaker_volume entity: number.tapoc111_speaker_volume show_state: true icon_height: 50px hold_action: action: none
This works to set the speaker to 0 if it's at 100. I don't know how to continue the logic to do the inverse. Not sure where to read up on this. This is new waters for me.

fickle sand
#

The default HA button-card does not support templating

#

So your best bet is to let a script handle the logic and call that script

haughty skiff
#

Thank you! Need to step away for a bit but I'll jump in those channels shortly!

quasi frost
#

hey there, i want to create a sensor wich calculate the value kb/sec to MB/sec
i have this code:
- platform: template sensors: total_bandwidth: friendly_name: 'Total bandwidth Upload NAS1' value_template: "{{ state_attr('sensor.nas1_upload_durchsatz') / 1000 }}" unit_of_measurement: "Mbps"

#

but the sensor is not available. Can someone help me whtas wrong?

marble jackal
#

all states are strings

#

you need to convert it to a number first to be able to divide it by 1000

mighty ledge
#

in sensor.nas1_upload_durchsatz settings, change the units to Mbps

quasi frost
mighty ledge
#

it will convert the value too

quasi frost
#

i try

#

works πŸ™‚