#templates-archived

1 messages · Page 27 of 1

mighty ledge
#

is this the xiaomi vacuum?

ripe steeple
#

Yes 🙂

mighty ledge
#

if yes, there's only 1 way to get around the , being used as a list

#

you have to template the entire data: field

#

so that the resolver doesn't change it to a list

ripe steeple
#

Ty for the tip 🙂 I had another approach in mind but will definitely take a deeper look into your code after a good night's sleep

#

Basically all voice commands will build up a room "to clean" queue in an input text. An automation will

  • fetch input text,
  • store first item
  • update input text with slice 1:]
  • start cleaning 1st room
  • wait for trigger "vacuum returning to dock"
  • repeat until input text is empty
#

This way rooms can be dynamically added to the queue without interrupting the vacuuming process. Maybe a bit dirty of a workaround but I think it will do its job

#

All of this because Speech to text don't work from Google Assistant >> Home assistant*🙄

thorny snow
#

Hi everyone,
I have a number of Riemann sum integrals in yaml that I would like to convert to helpers. But I don’t want to lose my statistics in my energy dashboard. Is there a way to convert to helpers keeping the same id?

buoyant fractal
#

OOPs, nevermind, I got rid of the quotes and now it is numeric... DUH....I wrote a temperature template but it wont work on a gauge card because the state is numeric. How can I get it to show the float value I am sending?: template:

  • sensor:
    • name: average_temperature
      unique_id: 'AvgTemp'
      unit_of_measurement: "F"
      device_class: temperature
      state: >
      "{{ (((states.sensor.Bedroom_temperature.state) | float) + ((states.sensor.Bathroom_temperature.state) | float) + ((states.sensor.kitchen_temperature.state) | float) + ((states.sensor.livingroom_temperature.state) | float)) / 4 | float }}"
inner mesa
#

remove the surrounding quotes

#

and your case is all over the place

#

entity_ids are all lowercase

#

and you should be using states() instead of states.xxx.yy.state

#

and you're converting 4 into a float

#

there's much weirdness 🙂

#

and you can do all of that with a helper in the UI now

#

if you wanted to

undone falcon
#

I have a mini split integration that's working great, but i just noticed it doesn't have the hvac_action attribute. hvac_modes is a list (off, heat_cool, cool, heat, fan_only, dry), so I'm wondering if there is a way to use a template to track which mode is currently in use. Is that possible? None of the tutorials I've found on youtube are getting me there.

lofty mason
undone falcon
# lofty mason Am I understanding correctly that the integration does not give you any feedback...

That's what's weird. Right now I can see it is set to "heat", but there doesn't appear to be any way to see a history of each option within the hvac_modes (for instance, when it the mode is changed). Separately I have a Nest in my house and I can easily chart the state changes using hvac_action because it returns a string. I can't seem to do the same with hvac_modes, I believe because it returns a list.

lofty mason
#

Can you copy from the developer tools exactly what the integration provides you, including all attributes? Assuming it is a climate entity?

undone falcon
#

hvac_modes: off, heat_cool, cool, heat, fan_only, dry
min_temp: 62.5
max_temp: 86
target_temp_step: 0.5
fan_modes: auto, low, medium, high
preset_modes: none
swing_modes: off, both, vertical, horizontal
current_temperature: 52
temperature: 62.5
fan_mode: high
preset_mode: none
swing_mode: off
icon: mdi:air-conditioner
friendly_name: Mini Split
supported_features: 57

lofty mason
#

I believe the "state" of climate entity is the current mode. Mode "heat" means "this will heat when the temperature falls below the setpoint". Action "heating" means "this is actively pumping out heat at this moment".

#

And what is the state?

undone falcon
#

heat

lofty mason
#

Understand that hvac_action is different than mode. hvac_action is not "the current mode", it's something else.

undone falcon
#

I see.

lofty mason
#

I guess this mini split just does not report back the current action, or the integration is not doing it properly

undone falcon
#

You may be right.

#

I'm looking in Grafana at a table and the state.last is blank for the past several time increments, and as i scroll down i get to a "heat".

lofty mason
#

Ok but again: the state is the current mode. hvac_action is the current action. Without an hvac_action key, you will not know if it is heating or idle.

undone falcon
#

that makes sense. i've been thinking about this all wrong

#

thanks!

cedar anchor
#

Hi, I need help with the sun and sometimes I get tired of it and there's nothing I can do.
I would like to set "true" from sunrise to 11pm.
I tried different ways and none of them work.
"{{ state_attr('sun.sun', 'elevation') > 1 and now().strftime('%T') < '22:59:59' }}"

solemn frost
#

You can use today_at()

#

{{ now() < today_at('23:00') }}

cedar anchor
# solemn frost You can use `today_at()`

Seriously, I was convinced it was the same 🤦‍♂️
So let's say something like this:
"{{ state_attr('sun.sun', 'elevation') > 1 and now() < today_at('23:00') }}"

feral bloom
#

Hi there. Can someone help me create a sensor to pull data from yesterday but only for a window of time. I have a sensor that measure my houeshold power consumption in kwh. I want to have a new sensor to provide predicted consumption for the next 2 hours based on the data from yesterday. Your help would be greatly appreciated!

marble jackal
#

templates can only access current data, not historic data

obsidian lintel
#

{{ (now().timestamp()-5260000) | timestamp_custom('%B %Y') }}

Is there a better way to get the previous month?

#

As each month is pretty much a different day, I get inconsistency at the end of each month

silent seal
#
{{ now().month }}

This output the current month

#

But you could also subtract a timedelta of 1 month which would be better

#

Except that timedelta doesn't take months 🤔

silent seal
obsidian lintel
#

It will be inconsistent

silent seal
#

Yes, except if we know the real problem, we can probably find a neater solution

obsidian lintel
#

https://pastebin.com/qaEBXnWq

I have an energy graph, it shows me 4 months of forecast, hence I need the label to state what month the forecast is displaying.

silent seal
#
{{ now() }}
{{ now().month }}
{% set year = now().year %}
{% if now().month == 1 %}
  {% set year = now().year - 1 %}
  {% set month = 12 %}
{% else %}
  {% set month = now().month - 1 %}
{% endif %}
{{ year ~ "-" ~ month ~ "-" ~ now().day }}
#

Someone smarter than me can definitely improve that, but that's a quick proof of concept for outputting a string.

#

You could modify the last line to turn it into a timestamp if needed.

{{ year ~ "-" ~ month ~ "-" ~ now().day | as_datetime }}

Of course, you may still end up with Feb 31st, but it sounds like you don't need days

obsidian lintel
#

I dont need days

silent seal
#
{{ year ~ "-" ~ month }}
#

This does go back a year when needed

obsidian lintel
#

Except, now its more complicated hahaha

#

{{ now().month }} is there a way that I can get this to show February instead of 2

inner mesa
#

{{ now().strftime("%B") }}

obsidian lintel
#

Ah thanks!

cedar anchor
#

Sunrise < - > 23:00

analog mulch
#

I want to use the new enum device_class to describe the states of my coffee maker, deriving them from a template based on power draw. Does anyone know the syntax?

compact robin
#

Another question for you: I have a sensor for my Fish Tank (in the glass), that shows some fluctuation when the Heater is ON or OFF.
But since it's OUT of the water, it has a variation of 2.5ºC below of what I want to actively show.

I thought "Ok, this is easy, I will create a helper input_number as ºC with 2 in the value, and create another sensor, with a sum sensor tank + 2ºC sensor. But it shows as unavailable?!

#

How can I achieve that "2.5ºC sensor" to SUM with the actual temperature of the Fish Tank sensor and make it display a proper value?

#

Since my go-to solution clearly failed hard lol

mighty ledge
#

there's most likely an error in your syntax

compact robin
#

I'm using the Helpers UI, I can't show in code. Let me screenshot v quick

inner mesa
#

I just created a helper adding a sensor and input_number and it worked

compact robin
#

That's the fake helper I created, and then I did a regular "sum sensor" combining the fake and real one. But it shows as unavailable on the "final" sensor.

#

Is it the unit I'm using?

#

Both are meant to be in ºC

inner mesa
#

what value does it have in devtools -> States?

#

you're not giving it a value there

compact robin
#

unit_of_measurement: ºC

inner mesa
#

taht is not a value

compact robin
#

The value is 2.5, in the "Informações" tab

lofty mason
#

screenshot the full devtools attributes for the sensor and the input_number?

inner mesa
#

I would just make a template sensor 🙂

compact robin
#

Will do, give me a second. I'll SS the 3 sensors.

#

I thought about the same Rob, but in this case, I also kinda wanna try and learn how to "fix it" so I know in the future :p

#

If possible, ofc

inner mesa
#

{{ states('sensor.fishtank')|float - 2.5 }}

floral steeple
#

hey all, I have about 30 binary sensors (binary_sensor.xxx) from my security system that has an attribute called "Tampered", with value of false or true. I'd like to create a trigger based on this this, that if any of these sensors gets tampered (i.e. true) to let me know. I'm not exactly sure how to listen to all the sensors with attribute and how to bring in the name of the sensor into the trigger ID so it becomes part of the message. I can do it for one specific sensor, but to do it all 30...not sure how? thanks for your help

inner mesa
#

the most straightforward way to do it is just to list them all in a state trigger

compact robin
compact robin
#

Please can you check what I'm doing wrong on the sensors themselves so I understand where I'm "f-ing up".

inner mesa
#

you can't create a template sensor in the UI

floral steeple
inner mesa
#

no, I mean list them all in a state trigger

floral steeple
#

ahh

#

yes, that would work!

inner mesa
#

ideally you could use a template, but that gets more complicated

compact robin
#

Fixed it, created a template sensor. I can't seem to make the measurement work with the helper. Thanks!

analog mulch
# mighty ledge syntax of what...

In the pull request for this there is some mysterious reference to “options” which are define for the enum device which then appear as a select in the UI for writing automations.

mighty ledge
#

enum is on sensor only

#

so, this is why I'm asking

#

there is no syntax

#

for the enum device_class

#

You can make input selects or template selects

mighty ledge
#

You may be able to set an options attribute on a sensor entity via customize.yaml or a template sensor that has a list of options combined with device_class enum. But there's no guarantee's that it will work.

steep plume
#

Hi, I'm facing a weird issue where using a sensor's name in a template sensor makes the template sensor entity not work/show up in developer tools. Is this a known issue or I'm doing something wrong?

{%- for sensor in window_sensors -%}
{{ sensor.name + " - " + ("Open" if sensor.state == "on" else "Closed") }}
{%- endfor -%}

Using sensor.name like here makes the entity not work, but when I remove the reference to the name or substr it with [:3], the entity works.

mighty ledge
#

what does windows_sensors contain a list of?

steep plume
#
{% set window_sensors = states.binary_sensor 
            | selectattr('attributes.device_class', 'defined') 
            | selectattr('attributes.device_class', 'eq', 'window')
            | list %}
mighty ledge
#

then it should work

#

what error are you getting when you include sensor.name?

steep plume
#

no weird characters in the names itself either

#

I think there's no error at all - it works when testing in developer tools template, but when actually using in configuration.yaml sensor object in or in template object, the behavior is that it works when the name is not referenced

#

so that's really intriguing

mighty ledge
#

not really, 9 times out of 10, it's your yaml that's bad in that case

floral steeple
#

@inner mesa looking to your automation here:

        entity_id: input_number.zones_violated
        value: >-
          {% set orig_value = states('input_number.zones_violated')|int %}
          {{ orig_value|bitwise_or(2**state_attr(trigger.entity_id, 'index')) }}

look like you made input helper, and your attribute is 'index'
just curious, what this bit does?

inner mesa
#

just ignore that, I was playing around

floral steeple
#

ok! sounds good

mighty ledge
#

so, post your entire yaml

floral steeple
#

and this part, will show the friendly name of the trigger.
message: "Zone: {{ trigger.to_state.name }} Violated"

steep plume
#

@mighty ledge https://pastebin.com/CCVEwf4i here it is. removing sensor.name from L56 makes the entity work, otherwise it's not appearing anywhere

#

the strange thing is, the name reference in moisture sensors works just fine

#

one difference I can see is that one of the window sensor's has a hyphen in its name. let me check that..

mighty ledge
#

that shouldn't matter

#

if it did, you'd see an error

#

in your logs or wherever

#

I don't see anything wrong with the template and it should work with what you have

steep plume
#

it works until sensor.name[:8] , then (9+) the entity stops working. 8 is when a space appears in the window sensor's opening entity name

mighty ledge
#

possibly character encoding

#

but you'd still get an error in your logs

steep plume
#

Okay there is an error actually lmao 😛

homeassistant.exceptions.InvalidStateError: Invalid state encountered for entity ID: sensor.home_status. State max length is 255 characters.
#

this might be it

#

So I'm trying to make a status message to send via IM periodically, and looks like it will exceed 255 characters. What's the best way to work around it? I could paste the template in the actions itself, but then I don't have a single source of truth for it and not really a good solution imo

#

One thing I can think of is making an automation which generates the string and writes to an input_string and then in the destination flows triggering that automation and reading that input_string

#

Alright, thanks a lot for helping me debug this 🙂

mighty ledge
steep plume
#

Oh. So I should probably do the same with other sensors. Thanks a lot!

haughty breach
amber hull
#

I am getting a template error on a sensor that has worked for months. ```
TemplateError('TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'') while processing template 'Template("{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') *1000}}")' for attribute '_attr_native_value' in entity 'sensor.bill_gradient'

#

Runs fine in developers tools

#
sensors:
  bill_gradient:
    friendly_name: "bill_gradient"
    unit_of_measurement: '%'
    value_template: "{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') *1000}}"
marble jackal
#

The state_attr() function will return none when the attribute is not available, and you can't multiply none with 1000

#

Use a default or availability template to prevent the error

amber hull
#

So is this a restart of HA issue only?

#

Where does the default or if available go?

marble jackal
#

That would be a probable moment for this error to occur

#
sensors:
  bill_gradient:
    friendly_name: "bill_gradient"
    unit_of_measurement: '%'
    value_template: "{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') | default(0, true) * 1000 }}"

Or

sensors:
  bill_gradient:
    friendly_name: "bill_gradient"
    unit_of_measurement: '%'
    value_template: "{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') * 1000 }}"
    availability_template: "{{ state_attr('binary_sensor.bill_bath_humidity_trend', 'gradient') is not none }}"
amber hull
#

Saw is_state_attr() in the template docs. Is this an option as well?

marble jackal
#

Nope

{{ is_state_attr('sensor.a', 'b', none) }} #False
{{ is_state_attr('sensor.a', 'b', None) }} #False
{{ state_attr('sensor.a', 'b') is none }} #True
amber hull
#

Thanks as always for your quick response and fix for me

marble jackal
#

To be clear, I don't have a sensor.a 🙂

#

No worries

grizzled grove
#

Can someone help me brainstorm this:

plain magnetBOT
#

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

grizzled grove
#

And, now, at 1pm, instead of '0' it gives '1'.

#

So I tried adding:

#
{% if states('sensor.time') >= '08:00' %}
#

At the top. But it still doesn't give the else: 0

lofty mason
#

I think you're just doing string comparisons, which is unlikely to do what you want. What is this actually trying to achieve? The number of hours since 8am or something?

grizzled grove
#

It's connecting to scrape sensors, that give net(solar) radiation by hour.

#

I'm just using numbers to simplify it.

lofty mason
#

you can't do direct comparison of strings like "08:59". You need to convert to datetimes or timestamps or something.

#
{% set h = states("sensor.time") | as_timestamp() | timestamp_custom("%H")|int %}
{% if(h < 8 || h > 17) %}
0
{% else %}
{{ h - 7 }}
{% endif %}
#

how about this

inner mesa
#

well, as long as you use 24-hour time and zero-fill, you can 🙂

grizzled grove
#

The strange thing is that it was working well during the day. Could it be related with the sensor.time going '00:00' and forward...

#

At '18:00' the value was '0'. As it should be.

#

Well, it seems that if I add:

#
{% if states('sensor.time') <= '08:00' %}
0
#

I'm able to constrain it after midnight.

#

Not the most elegant solution, but still...

marble jackal
#

I would do {% if now() < today_at('08:00') %}

#

No need for a sensor.time for templates

grizzled grove
#

into a template?

#

I've been trying for a while now, without much luck....

still plank
#

when using selectattr filter, how can i exclude entities where the attribute is unavailable

#

or must i use if in the actual iteration of the result?

marble jackal
#

selectattr('attributes.your_attribute', 'defined')

still plank
#

it's the main state that is sometimes not defined though, not an attribute

#

for example,
{% for state in states.sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', '==', 'battery') %} {{ state.name }}={{state.state}} {% endfor %}

#

produces this:-

#

Aqara Roller Shade E1 battery=unavailable

Aqara Temperature 5ef3 battery=unavailable

Fire Battery Level=21
#

i'd like to filter out the unavaiulable

#

oh i phrased my question badly there, didn't i

marble jackal
#

selectattr('state', 'is_number') should work in this case

#

more general selectattr('state', 'ne', ['unavailable', 'unknown'])

still plank
#

ah ok

#

thank you

viral sierra
#

HI,
every time my gate opens I make a notification on my phone. I would like to know how to make it show who opened on notification. (i know the name in log.) Someone can help me please ?

marble jackal
#

you need the context for that

viral sierra
#
service: notify.mobile_app_steven
data:
  message: Action portail {{id_user}}
  data:
    color: green
#

I just want to know who pressed the dashboard button and put it where there is id_usser

lucid bramble
#

I need some help on some template code. I'm pretty good at reading code and figuring out some of the changes that needs to be made but on this one I need some help on figuring out how to update a sensor which represents a file path.

As an example, I have a sensor
sensor.3d_printer_current_print with state = "subdirectory/filename.gcode"
but it could also be "filename.gcode" if the file hasn't been put into a subdirectory.

Each of these files produces a thumbnails but the api call always returns the thumbnails path relative to the filename and not relative to the main directory so whether the file is in at the main level or in a subdirectory the relative path of the thumbnails is always

3d_printer_object_thumbnails ".thumbs/filename.png"

What I would like to do is to modify the thumbnail relative with the subdirectory name available in the sensor.3d_printer_current_print if it exists.

is this possible.

I have no control on what the API returns when we do the call

mighty ledge
mighty ledge
lucid bramble
viral sierra
plain magnetBOT
#

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

mighty ledge
mighty ledge
marble jackal
#

grr you beat me to it

mighty ledge
#

lol

#

I use it in my own automations

marble jackal
#

slightly different approach

{% set user_id = context.user_id %}
{% set user = states.person|selectattr("attributes.user_id", "==", user_id)|map(attribute="attributes.friendly_name")|first if user_id else 'Home Assistant' %}
mighty ledge
#

don't have to test anything

marble jackal
#

I had to search for Rob's post on the forum 😛

mighty ledge
#

Ah

#

link to post?

#

I just copied my config

mighty ledge
#

ah

viral sierra
#

It doesn't work ...

#
service: notify.mobile_app_steven
data:
  message: >
    {% set user_id = context.user_id %} {% set person = states.person |
    selectattr('attributes.user_id', 'eq', user_id) | map(attribute='entity_id')
    | first | default %} {% if person %}
      Action portail {{ state_attr(person, 'friendly_name') }}
    {% else %}
      Action portail unknown
    {% endif %}
  data:
    color: green
marble jackal
#

ah this was for your cursing Alexa, I kinda remember that

viral sierra
#

i have unknown when i pressed it

lucid bramble
mighty ledge
viral sierra
#

UI of course ^^

mighty ledge
#

Then it should work But you can't just call the service, you have to perform the automation

#

calling the service does not pass context

#

has to be the automation

marble jackal
#

maybe try with a state trigger?

trigger:
  - platform: state
    entity_id: switch.portail
    to: "on"
viral sierra
#

i would like to show you the log ? Can i send somewhere ?

mighty ledge
#

Also, you can't use the 'test' button for the automation, as that doesn't pass the context either.

#

well it does, just not the user

#

so, let the automation run naturally, or add a separate testing trigger, just to test it

marble jackal
#

if you go automation trace, and then press changed variables what does that show?

#

specifically the context part under this (not the context in the trigger part)

mighty ledge
#

I'm 99% sure he's just testing it via the service caller or the test actions button

#

The only way it wouldn't work via the actual button in the UI, would be if he's using a custom card. But even then, it passes some context and it should have the user_id

viral sierra
#

i've this :

plain magnetBOT
#

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

marble jackal
#

hmm, there is a user_id on the trigger, but not on the automation itself

viral sierra
#

yes i just saw it

marble jackal
#

I don't use device triggers, and tested it with a state trigger. I can then see the user_id in the context of the automation

mighty ledge
#

just use the to_state then

viral sierra
#

where ?

mighty ledge
#
{% set user_id = trigger.to_state.context.user_id %}
#

It seems you have an automation that actually triggers it, not the UI

viral sierra
#
service: notify.mobile_app_steven
data:
  message: >
    {% set user_id = trigger.to_state.context.user_id %} {% set person =
    states.person | selectattr('attributes.user_id', 'eq', user_id) |
    map(attribute='entity_id') | first | default %} {% if person %}
      Action portail {{ state_attr(person, 'friendly_name') }}
    {% else %}
      Action portail unknown
    {% endif %}
mighty ledge
#

as parent_id shouldn't be populated unless it comes from a script or automation

#

yep

viral sierra
#

doesn't work ..

mighty ledge
#

how are you triggering it

marble jackal
mighty ledge
#

still shouldn't change the from/to state objects

marble jackal
#

no sure

#

the to_state had the user id, so I don't see a reason why the above wouldn't work if triggered correctly

mighty ledge
#

That's why I keep asking how he's triggering it

#

yet he hasn't replied

#

Context is heavily based on what triggers it

viral sierra
#

too fast for me..^^

#
show_name: true
show_icon: true
type: button
tap_action:
  action: toggle
entity: binary_sensor.ouverture_portail
mighty ledge
#

you can't toggle a binary sensor

#

so that doesn't make sense

viral sierra
#

sorry

#

type: entities
entities:

  • switch.portail
mighty ledge
#

Ok, so then it should be working with 1 of the 2 templates previously provided

#

or there will be an error in your logs

viral sierra
#

i don't have an error on my log .. and when i use this switch i'have '' action portail unknown "

mighty ledge
#

Post the trace again then

plain magnetBOT
#

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

mighty ledge
#

or use this


alias: SMS Portail
description: ""
trigger:
  - platform: device
    type: turned_on
    device_id: c21090ec6bd71c661d14
    entity_id: switch.portail
    domain: switch
variables:
  context_user: "{{ context.user_id }}"
  trigger_user: "{{ trigger.to_state.context.user_id }}"
  person: >
    {% set person = states.person | selectattr('attributes.user_id', 'eq', trigger_user) | map(attribute='name') | first | default %}
    {{ person or 'unknown' }}
condition: []
action:
  - service: notify.mobile_app_steven
    data:
      message: Action portail {{ person }}
      data:
        color: green
viral sierra
#

that's my user id : user_id: cae95d0942d04e8ebd2d665206bf6110

mighty ledge
#

yes, that's not the problem

#

the problem is that your template is failing to grab the person because we aren't looking at the correct context.

#

using the automation I just posted, triggering the automatin, then posting the trace variables here will show me what's going wrong.

plain magnetBOT
#

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

viral sierra
#

i have nothing anymore

mighty ledge
#

did you trigger it?

#

is there errors in the logs

#

I know I sound like a broken record, but this is automation testing 101

#

if the automation doesn't work, find errors in your logs

#

then post them

viral sierra
#

I have no log in changed variables

mighty ledge
#

my man, your home assistant logs

viral sierra
#

Stopped because of unknown reason "null" at 1 février 2023 à 16:55:58 (runtime: 0.00 seconds)

plain magnetBOT
#

Open your Home Assistant instance and show your Home Assistant logs

viral sierra
#

Template variable error: 'context' is undefined when rendering '{{ context.user_id }}'

#

Error rendering variables: UndefinedError: 'context' is undefined

mighty ledge
#

ok, delete this line from variables


  context_user: "{{ context.user_id }}"
#

then try to run it

viral sierra
#

i have : action portail unknown

mighty ledge
#

Yes, please show me the trace...........

#

I'm about to hit my frustration limit and walk away

plain magnetBOT
#

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

mighty ledge
#

is your person not attached to your user?

#

you can only know what people select things, not users

viral sierra
#

I'm not sure I understand but yes I would say

mighty ledge
#

I.e. your user needs to be attached to your user

#

Well it can't be

viral sierra
#

can i send you a picture ?

plain magnetBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

viral sierra
mighty ledge
#

ok, that doesn't help

#

go to developer tools -> template page and put this into the template editor

#
{% for p in states.person | selectattr('attributes.user_id', 'defined') %}
  {{ p.name }}: {{ p.attributes.user_id }}
{% endfor %}
viral sierra
mighty ledge
#

If your name doesn't show up, then you didn't create yourself properly

viral sierra
mighty ledge
#

However you are triggering it, it's not passing the correct context user_id

#

are you logged into Steven right now?

#

Do you have multiple steven users?

viral sierra
mighty ledge
#

Then it doesn't make sense how your user_id that's in the trace is not the user_id posted in your screenshot

#

and unfortuantely, I can't tell how you're actually triggering things

#

Click on Settings -> People -> Top of page, click users

#

Then click on each one and find the one that has an ID of cae95d0942d04e8ebd2d665206bf6110

viral sierra
#

ok, I recreated an other user and know it works

#

thanks a lot ..

sonic nimbus
#

Hello, how to add in my condition for time from my trigger:

- alias: "Hallway LED Light Effect Frontdoor"
  trigger:
      platform: state
      entity_id: binary_sensor.front_door
      #for: 00:00:02
  action:
    choose:
      - conditions:
          - condition: template
            value_template: "{{trigger.to_state.state == 'on' HERE I want to add timer 10seconds}}"
        sequence:

Is it possible?

mighty ledge
#

then your condition will be based on the trigger.id that you set on the trigger

still plank
#

i'm trying to get the device name from an entity state in a template. My device's original name was VA1453602560, and i have renamed it in the UI to be "Hall Radiator Actuator". My template expression:
device_attr(device_id(state.entity_id) ,'name')
is returning the original name, not the changed name. The documentation for device properties https://developers.home-assistant.io/docs/device_registry_index#device-properties implies that I should get the correct name here (and probably the original name in the default_name property.

inner mesa
#

I see the same. I recommend filing an issue

still plank
#

found in a forum thread theres a name_by_user attribute but it seems not documented elsewhere

inner mesa
#

then may be a doc update

#

I suspect that the integration doesn't even know about that

still plank
#

those properties are in the developer docs, i can't find anything about device properties in the user docs / template docs

#

anyway that provokes my next question- that attribute may be set, or None, it appears. How can i make an expression that defaults to the name attribute when the name_by_user is none? must i do it with if / iif or is there a clever filter type approach?

#

best i can do is:
{{ device_attr(device_id(state.entity_id) ,'name_by_user') | iif(device_attr(device_id(state.entity_id) ,'name_by_user'),device_attr(device_id(state.entity_id) ,'name'))}}
but it doesn't seem nice evaluating the name_by_user property twice

inner mesa
#

I think that's typically what "name" should do

#

as with "name" and "friendly_name" for entities

#

you could stick device_attr(device_id(state.entity_id) ,'name_by_user') in a variable to make it shorter

still plank
#

ok. thank you.

coral knot
#

Does someone know how to style / animate the **badge **of a custom Mushroom Template Card?
I would expect it to work with something like this:

style:
mushroom-badge-icon$: |
ha-icon {
--icon-animation: wobbling 0.1s ease-in-out infinite alternate;
}
@keyframes wobbling {
0% {
transform: rotate(-5deg);
}
100% {
transform: rotate(5deg);
}
}

marble jackal
coral knot
#

Ah sorry, thanks

marble jackal
#

please make sure to post it as code

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

half niche
#
sensor:
#  - platform: dnsip
#  - platform: dsmr
#    port: /dev/ttyUSB0
#    dsmr_version: 5
  - platform: template
    sensors:
      daily_power:
        friendly_name: Daily Power
        unit_of_measurement: kWh
#

If I understand correctly this the old way to create template sensors?

Can I just rewrite them in the new way and restart HA?

inner mesa
#

You have no template there 🙂

#

But yes, that's the legacy format and you can switch to the new format

half niche
sonic nimbus
#

why this template is returning false: {{is_state('sensor.stefan_iphone_ssid.state', 'ThePingInTheNorth')}} and this template returns correct ssid: {{states.sensor.stefan_iphone_ssid.state}}

lofty mason
#

I think remove .state from is_state?

sonic nimbus
sonic ember
#

This is probably easier than I'm making it in my head... I have an entity with an attribute that is an array of numbers (hourly energy prices). I can figure out how to store each hour into a separate entity using a for loop.
But what I want to do is rank them. So let's say 6am is the cheapest rate, I want [0] to be "6". Any tips on how to go about this?

torn nacelle
#

One message removed from a suspended account.

inner mesa
#

please don't crosspost

torn nacelle
#

One message removed from a suspended account.

fading patio
#

How do I create a template that matches the start of a context ID for the event trigger? My two doorbells use different ids so catching the event and checking which ID it came from ids how I determine which ids sending the event. I cannot match the entire ID though because it’s only the first approximately eight characters if I remember correctly of the 20+ character string that stay the same for each doorbell, the other digits change to numbers and letters that vary.

#
  id: 01GRAK5YSFF97Kxxxxxxxxxxxx
inner mesa
#

{{ '01GRAK5YSFF97K' in trigger.event.data.context.id }} or however you get to it

analog mulch
#

What should the template for a numeric sensor return when it is unavailable? I have a new error in 2023.2 from my SQL sensors (where I cannot set the availability property) that

Sensor sensor.climate_all_energy_l30d has device class None, state class None and unit kWh thus indicating it has a numeric value; however, it has the non-numeric value: unavailable (<class 'str'>);

This is generated by my attempt at catching the error in the value template of the SQL sensor

{% if states('sensor.climate_all_energy')|is_number and value|is_number %}  
{{((states('sensor.climate_all_energy')|float  - value|float)/30)|round(3)}}
{% else %}
unavailable
{% endif %}
fading patio
mighty ledge
#

or, make an availability template

#

{{ states('sensor.climate_all_energy')|is_number and value|is_number }}

#

if that's sql, it doesn't have availability so you have to return None

analog mulch
#

Yeah it’s sql. Thanks I’ll make them all none

mighty ledge
narrow surge
#

For automating the heating in the house better I would like to do the following:

When there is motion detected without a 5 minute pause between 2 detection points (so motion detected on 13:00 and 13:04 is within 5 minutes) turn heating on 19c

Will this only be possible with a template, if so what things should I use? And what should the trigger be in this case?

rose scroll
rose scroll
#

Then in an #automations-archived, use a numeric state trigger to turn on the heat if the state of the history_stats sensor crosses 2.

narrow surge
#

That could work, thanks @rose scroll !

fading patio
#

@mighty ledge and @rose scroll thanks for feedback. unfortunately and fortunately I found out that they aren’t actually unique in the beginning it’s just that they’re changing more slowly in the beginning similar to like a hexadecimal the right side is changing and the left is changing much more slowly. Fortunately, that made me go a little further and found that it looks like I can use a different event for the Amcrest doorbell press other than the one example on the integration web page. “AlarmLocal” triggers right before the button press example “CallNoAnswered” that their example showed. And that has the “camera: Front Doorbell” in it also so I don’t need the id anymore to try and identify the doorbell. Will try this after work today and see if it works.

verbal moth
#

Hello, I wanted to make a sensor for my light switch. I got told that I need to make a binary sensor. Since I am pretty new to home assistant I am not sure how to do this. The sensor should turn to on/1 if my switch is beeing hold (already existing event: long_pressed) and to 0 if the switch is beeing released (already existing event: long_pressed_released).
I tried to google it as well as to find something in the docs, but I could only find anything which doesn't helps me. I thought maybe somebody can help me.

dull burrow
#

is this for a remote like hue / ikea or a mains powered switch btw?

verbal moth
#

it is for the homeatic ip switch in combination with dimming

#

holding to dim or brighten

dull burrow
#

ok just making sure you didnt instead just need a blueprint to control the former

earnest sinew
#

Sorry, I am new here. Can somebody help me? I have a xiaomi robot vacuum and it has a sensor whitch shows when I should change filter. Unfortunately the unit of measurement is in second. How can I convert it to hours?

verbal moth
#

So the problem I have is how do I make it work if I have is to call an event with its specific data.

verbal moth
#

When I listen to the event "homematic.keypress" and holt the button long it will give me this:

  address: 00019F2991C492
  device_type: HMIP-WRC2
  interface_id: RaspberryMatic-HmIP-RF
  value: true
  device_id: b43efa02235fd76d3d123353150fd065
  name: Wandtaster Schlafzimmer
  type: press_long_release
  subtype: 2```
obtuse zephyr
#

You can have a template binary_sensor use a trigger which can listen for your events to set the state
Couple examples: https://www.home-assistant.io/integrations/template/#turning-an-event-into-a-trigger-based-binary-sensor and https://www.home-assistant.io/integrations/template/#state-based-binary-sensor---change-the-icon-when-a-state-changes

The event trigger itself can be specific to various event_data that you've got above https://www.home-assistant.io/docs/automation/trigger/#event-trigger

plain magnetBOT
#

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

verbal moth
#

Thank you NSX, I gave my best and since I am new I think I messed it up a bit or understood the logic wrong.
My sensors.yaml fails.

   event_type: "homematic.keypressed"
   event_data:
   address: 00019F29914C89
   device_type: HMIP-WRC2
   interface_id: RaspberryMatic-HmIP-RF
   value: true
   device_id: b43efa02235fd76d3d897353150fd065
   name: Wandtaster Schlafzimmer          
   type: press_long_release
   subtype: 2
   binary_sensor:
     - name: szdim
       auto_off: 1
       state: "off"```
#

May somebody can help me out with that mindblown

obtuse zephyr
#

It can be confounding at times, but with YAML, whitespace is critical, one wrong space and your whole script is messed up

inner mesa
#

and there are both too many and too few spaces in there 🙂

verbal moth
#

So basically it is right but some spaces are wrong? Since it says missing proberty "sensors". But I thought the binary_sensor line defines my sensor szdim so it is just a spacing problem?

plain magnetBOT
#

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

obtuse zephyr
#

I got botted

#

Also... state should probably start as on 🙂

#

Or... auto_off shouldn't be there

verbal moth
#

I turned it to auto_on: 1

#

So as I understand this it listens with this trigger to the event and if the event fires it will turn the binary_sensor (which it also creates there with the name szdim) to off

obtuse zephyr
#

I feel like you probably want 2 triggers, one for press and one for release? Where it's on after the press_long and then is off after the release event? Or is a time delay sufficient for turning it off

#

Currently, your trigger is just on the release event

verbal moth
#

yes i thought maybe the auto_on: 1 turns it back to on after a second. The automation should be at the end like: "decrease brightness until release event fires (so in this case until the sensor szdim turns to off)

#

Also I pastes the code to the configuration.yaml which is probably wrong

earnest sinew
#

so can I change unit of measurement on a sensor?

verbal moth
#

can I change a variable of a binary sensor trough a trigger?

inner mesa
#

a variable of a binary sensor

#

what do you mean?

verbal moth
#

I mean the state sorry. I want to change with two different trigger the state of one entity.

inner mesa
#

you can specify as many triggers as you want

plain magnetBOT
#

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

twilit narwhal
#

Hi! I am trying to make my IR light "smarter" using PiIR, light template and appdaemon. For some reason the min_color_temp_kelvin and max_color_temp_kelvin are constantly getting lost whenever brightness/colortemp changes. How can I set these variables permanently?

plain magnetBOT
#

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

twilit narwhal
#

My light template

#

Nevermind - sorted it out. Needed to set these variables under homeassistant - customize - light.relir

rose scroll
humble mortar
#

How do I properlyset this img line {% set img = states('sensor.printer_3d_file_metadata.attributes["thumbnails"][2]["relative_path"]') %}

     - name: 3d_printer_object_thumbnails
       unique_id: "IP59b37837-b751-4d31-98c2-516a52edf833"
       state: >
       {% set dir = states('sensor.3d_printer_current_print') %}
       {% set img = states('sensor.printer_3d_file_metadata.attributes["thumbnails"][2]["relative_path"]') %}
       {{ [dir.split('/')[:-1], img] | join('/') }}
#
       availability: >
         {% set items = ['sensor.printer_3d_file_metadata'] %}
         {{ expand(items)|rejectattr('state','in',['unknown','unavailable'])
           |list|count == items|count }}
       icon: mdi:image
       attributes:
         friendly_name: "Object Thumbnails"
#
Failed to restart Home Assistant
The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while scanning for the next token found character '%' that cannot start any token in "/config/packages/moonraker.yaml", line 331, column 8
#

line 331 is {% set dir = states('sensor.3d_printer_current_print') %}

inner mesa
#

Indent the lines under state: > by 2 spaces

humble mortar
#

Thank you

#

seems it puts a block before []/.thumbs/SpringNutxyz002-400x300.png

#

This code was supposed to remove the file name off dir ending (directory1/directory2/filename.gcode) then apply it to the resolution.png file start (directory1/directory2/resolution.png) but it's doing this when it doesn't have a directory to parse ie if the picture is in the root directory instead of subdirectories.

obtuse zephyr
#

In your expression, you've got an array in the first element (from split)

#

Sounds like that's probably empty and the /.thumbs.... is from img

humble mortar
#

How would I tell it to ignore the dir split if no subdirectories exist.

obtuse zephyr
#

If that's expected, you can try {{ (dir.split('/')[:-1] + [img]) | join('/') }}

humble mortar
#

Yes it expected that the user may or may not add a directory to their gcode upload 😄

obtuse zephyr
#

you sure you reloaded your templates?

humble mortar
#

I saved the yaml then restarted home assistant.

obtuse zephyr
#

Paste what you have now, and can you echo dir and img?

humble mortar
#
     - name: 3d_printer_object_thumbnails
       unique_id: "10.13.37.4859b37837-b751-4d31-98c2-516a52edf833"
       state: >
         {% set dir = states('sensor.3d_printer_current_print') %}
         {% set img = states.sensor.printer_3d_file_metadata.attributes["thumbnails"][2]["relative_path"] %}
         {{ (dir.split('/')[:-1], img) | join('/') }}
obtuse zephyr
#

That's not what I suggested?

humble mortar
#

Oh I missed the [img]

#

Now there is a box at the start and around the img

#

oh forgot the +

obtuse zephyr
#

and what's the YAML you have now

humble mortar
humble mortar
sinful bison
#

hi, is there a filter to escape special char to the standard one ?
I have an input select with word using Upercase and è or ë char.
I'm using it to match entity name, i put a | lower to standardize the uppercase, but i would like to convert a è to a e to

silent vector
#

How would I get to event_id with this output?

{'state': 'active noification', 'last_updated': datetime.datetime(2023, 2, 4, 16, 52, 59, 959377, tzinfo=datetime.timezone.utc), 'event_id': '1675529574.936298-0ln426', 'occupancy': 'off'}
#

I used this to get the output above

{{ state_attr('sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status','outdoor_2') }}
inner mesa
silent vector
#

It wasn't

#

I edited it to avoid confusion lol

#

But it gave me an error there was no attribute

#

UndefinedError: 'str object' has no attribute 'event_id'

sinful bison
#

oh

inner mesa
#

add |from_json

sinful bison
silent vector
#

Not sure if I did that right.

{{ state_attr('sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status','outdoor_2') ['event_id'] | from_json }}
inner mesa
#

you did not

silent vector
#

JSONDecodeError: Input must be bytes, bytearray, memoryview, or str: line 1 column 1 (char 0)

#

I wasn't sure where to put it lol

inner mesa
#

{{ (state_attr('sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status','outdoor_2') |from_json)['event_id'] }}

silent vector
#

JSONDecodeError: unexpected character: line 1 column 2 (char 1)

hollow hedge
#

Do custom binary sensors have to stay in the configuration.yaml now? I've been working on a Bed Occupancy Sensor with load cells and have created the working binary sensors in the configuration.yaml but would like to move it to the sensors.yaml file I have but can't seem to make it work in there. I also created a binary_sensors.yaml but of course it doesn't work either. This is the working code in the configuration.yaml:

  - binary_sensor:
    - name: Person 1 in Bed
      state: "{{ states('sensor.bed')|float >= 60 }}"
    - name: Person 2 in Bed
      state: "{{ states('sensor.bed')|float > 20
                and (states('sensor.bed')|float < 60
                  or states('sensor.bed')|float >= 90 )}}"```
#

Would the format change because it is in the sensors.yaml? I've tried several different variations but haven't had any luck.
Also, I've found that if I keep it in the legacy format, shown below, it will work correctly in the binary_sensors.yaml.

  sensors: 
    person_1_in_bed:
      friendly_name: "Person 1 in Bed"
      value_template: >
        {{ states('sensor.bed')|float >= 60 }}
    person_2_in_bed:
      friendly_name: "Person 2 in Bed"
      value_template: >
        {{ states('sensor.bed')|float > 20
          and (states('sensor.bed')|float < 60
            or states('sensor.bed')|float >= 90 )}}```
silent vector
inner mesa
#

not really

#

the problem is that that attribute has ' when JSON requires "

inner mesa
#

the point isn't which file it's in, but that it's under the right tag

silent vector
#

As in, the template sensor attr or the jinja

#
{{ (state_attr(''sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status'',''outdoor_2'') |from_json)[''event_id''] }}
#

TemplateSyntaxError: expected token ',', got 'sensor'

hollow hedge
ivory delta
hollow hedge
#

I know it's a simple formatting issue but just can't get it right.

silent vector
#

I was trying to understand what rob was telling me to try

ivory delta
#

The JSON decode error is closer to where you want to be. As it stands, you have something that HA can't even parse.

#

It sees a quote, expects to see a string, then sees another quote (the end of said string), and expects a comma before the next argument. Thus, you have too many quotes.

obtuse zephyr
silent vector
#

Is it line 20?

#

That's the template sensor being referenced in the Jinja..

obtuse zephyr
#

I have a feeling that non-serializable date is throwing things off

silent vector
#

What should I do to it

obtuse zephyr
#

Could as | as_timestamp ? Obviously less readable, but a number that you can convert back if needed

silent vector
#

How would I convert it back?

#

Now
JSONDecodeError: Input must be bytes, bytearray, memoryview, or str: line 1 column 1 (char 0)

hollow hedge
silent vector
#

Much better

Result type: dict
{
  "state": "active noification",
  "last_updated": 1675529579.959377,
  "event_id": "1675529574.936298-0ln426",
  "occupancy": "on"
}
#

Got it now

#
{{ state_attr('sensor.outdoor_2_outdoor_3_doorbell_notification_priority_status','outdoor_2')['event_id'] }}
#

How do I convert the time back?

obtuse zephyr
#

as_datetime

silent vector
#

Awesome.

hollow hedge
obtuse zephyr
#

If they are for the template platform

#

Then yes

#

You'll need to modify syntax to the new style accordingly

hollow hedge
obtuse zephyr
#

yep, you bet

torn nacelle
#

One message removed from a suspended account.

brittle jacinth
#

I’m trying to write some conditional icon color logic based on the light vs dark mode. How do I get the current value (to know if it’s light vs dark mode)

warm elbow
#

Oh the HA site is down

#

I want to create a template that controls the volume of one of my DLNA media devices. How do I do that?

#

Oh there it is again ^^

#

Template number I guess

gusty ledge
#

Is it possible to use a template which returns a list of entities in dashboards entities-card ( type: entities entities: {{template | list}} ) <- Documentation says: A list of entity IDs or entity objects or special row objects (see below).

inner mesa
#

Most cards don't support templates at all

amber tinsel
#

I'm new to HA and yaml and want to calculate the cost of my electricity by multiplying the energy used by the tariff. Can any one provide an example template to do this?

#

I think templates is the way to do this, but I'm not sure where to start ...

solemn frost
#

If you add it to the energy dashboard, it will calculate that itself

amber tinsel
#

I wanted to do this myself on my own dashboard

twin gull
#

I have a couple of smart plugs, I also have an integration that gives me the electricity price. Should I create one template that does the multiplication (current draw + current price) and then another reimann sum and then a utility meter or is there a better way to do it? (I'd like the data outside the energy dashboard. For instance I have a plug for the extension cord for my server and computer + peripherals. Or in my living room I have one "smart outlet" in the wall and then one just to the tv. So I want to calculate what the router/tvbox/lights around thge tv takes

humble mortar
# inner mesa try adding `|slugify`

What are these things called when you put them on the end is there a list of all the things you can do there? |urlescape, |timestamp_custom, |etc…

inner mesa
#

Filters. See the links in the channel topic

humble mortar
#

Thank you.

fossil venture
#

So I've been setting my sensors to unavailable when they are not available. core 2023.2 does not like that. What should I be setting them to now?

marble jackal
#

You mean by explicitly giving them the state unavailable or by use of an availability filter?

silent vector
#

Any idea why multiple_active_events wouldn't work? It doesn't become true when there's more than attribute state with active event/active notification https://dpaste.org/5LtJf

marble jackal
#

@silent vector What are the current attributes and their values of this sensor?

silent vector
marble jackal
#

I can't see the current values there

silent vector
#

Event id is a string

#

Occupancy is simply on off

#

Does that help?

marble jackal
#

Just go to developer tools > states and copy the current values

silent vector
#

That's what I figured you were looking for.

marble jackal
#

There's a typo there

#

active noification this is missing a t

silent vector
#

Oh my

#

🤦‍♂️

#

That's why I have been having issues ..

#

Lol

obtuse zephyr
#

The attribute values themselves of what you're interested in is still an object, not just a string, that's the state property

fossil venture
silent vector
obtuse zephyr
#

No... attributes is a dict

#

You still need to gather the attributes that are important and then interrogate that state property

marble jackal
#

You need to add | map(attribute='state')

silent vector
#

Before select right?

obtuse zephyr
#

Also.... I don't actually know in what order things would be evaluated within that template. I wonder if there may be an instance when those states first update, that the this.attributes reads the previous values

marble jackal
#

@silent vector | selectattr('state', 'defined') | map(attribute='state') before select

silent vector
#

That works.

#

Thank you.

obtuse zephyr
silent vector
#

Thank you for checking

#

For context on what I was doing with this, i'm creating an automation for frigate notifications. 3 cameras with a similar view will share a notification to avoid 3 separate notifications. I prioritize which will have the best view (that's the idea at least).

thorny snow
#

is there a neater way to deal with clamping an input_number between 2 values other than:

service: input_number.set_value
data_template:
  value: >-
    {{ [[(states('input_number.ch_accumulator') | float(default=0.0) + state_attr('sensor.boiler_cs_wdc', 'absolute_offset') | float(default=0.0)) | round (2), 5] | min, -5] | max }}
#

because the input_number does have a min and max set but if an automation then tries to set a value beyond that range it just fails

#

I'd love to have a way to force the number to be clamped between min and max

obtuse zephyr
#

How about {{ ([-5, (states('input_number.ch_accumulator') | float(default=0.0) + state_attr('sensor.boiler_cs_wdc', 'absolute_offset') | float(default=0.0)) | round(2), 5] | sort)[1] }}

thorny snow
#

certainly easier to read... please help me understand this though: this will always return the second item in the sorted list. So how does it sort?

obtuse zephyr
#

Three values in the list [min, your_val, max], If your_val > max, then max becomes index 1

#

Same situation for min

thorny snow
#

right

#

yes that makes absolute sense

#

thank you so much

#

this is way better

obtuse zephyr
#

yep, you bet

thorny snow
#

a very elegant solution too 🙂

floral karma
#

Hi folks - can anyone provide me some updated recommendations with the best way to display "Last Motion Triggered" from a group of binary sensors? Open to implementation, I have a bunch of motion sensors around the ingress parts of my house and want to have a single sensor that shows the name of the "last triggered" sensor

inner mesa
#

something like this:
{{ expand('group.downstairs_lights')|sort(attribute='last_changed', reverse=true)|map(attribute='entity_id')|first }}

marble jackal
#

Do note this doesn't work right after a restart, and it could display the last sensor which turned off, which could be different than the last one turned on

inner mesa
pine musk
#

so, I built some presence sensors for my couch.... I have an input boolean which is On if any sensor is activated, and off if all sensors are deactivated.

#

I want to create a template binary sensor that will reflect the input boolean, and show either mdi:sofa, or mdi:sofa-outline to indicate presence

inner mesa
#

where are you stuck?

pine musk
#

sucessfully stated problem, soldered up connectors, and tested sensors...

inner mesa
#

you just want a template that outputs a different string based on the state of an input_boolean?

pine musk
#

no, diffent icons and dif string

inner mesa
#

icons are just strings

#

it's the simplest possible template

#

{{ iif(is_state('input_boolean.whatever', 'on'), 'mdi:first_one', 'mdi_second_one') }}

pine musk
#

thanks.. was WAAAY overthinking it.

inner mesa
#

yeah

sinful bison
#

I was wondering, does something in the state object can tell me if it's a group ?
When looking it it raw, it display a list under entity_id
entity_id=['light.plafonnier_bureau', 'light.nanoleaf_bureau', 'light.glow_ecran_bureau', 'light.decoration_lumineuse_pinkie_pie', 'light.lampe_a_lave_bleu_bureau']
But obviously getting the entity id of it only return it's own and not that list

pine musk
#

so, this, RobC:

  - binary_sensor:
    - name: Couch
      icon: > 
        {{ iif(is_state('input_boolean.Couch_presence','on'), 'mdi:sofa','mdi:sofa-outline')}}
      state: >
        {{ iif(is_state('input_boolean.Couch_presence','on'),'Seated','Empty')}}
#

it works!

sinful bison
inner mesa
neon bolt
#

hi, is there any way to compare 2 calendar entries in a template as a condition ?

sinful bison
neon bolt
#

I mean :

#

if the content of

#

platform: state
entity_id:

    calendar.https_fr_airbnb_ca_calendar_ical_4469997_ics_s_e6256b885a96633ce257165cea4d909a
    attribute: description
#

yesteday is different from the one of today

#

so I can assume the renter changed

young jacinth
#

hey, i got another template thing i cant get inside of my head

i want to print out a string that seperates the states and the unit of measurement of all entitys that are inside a list. i tried something like this, but i cant access the variable of the for loop

https://pastebin.com/1SxNijda

#

can somebody help me here?

#

oh wow

#

searching and trying for 1 hour and coming to a solution myself 5 min after asking

neon bolt
fierce hornet
#

I want to display the last time an entity has changed in an easy to read format. I've found
{{ relative_time(states.switch.licht_bureau.last_changed) }} but that displays in English. Native language (Dutch) would be quite nice. Is there a way to accomplish this?

#

Also tried {{ (as_timestamp(now()) - as_timestamp(states.switch.licht_bureau.last_changed)) | timestamp_custom("%H", false) }} but that doesn't round up. so 3:55 hours ago is still displayed as 3 hours

pine musk
#

I find that the support around here is very good, when approached from the angle that this is volunteers, offering up their free time, and expertise

#

this support, you pay for with well asked questions.

haughty breach
haughty breach
mint viper
#

is there a way to get the systems set units (metric or imperial) in a template so i can change a conversion factor depending on the units?

mint viper
#

nvm, worked out i can get it from the temp state atributes

pine musk
#

trying to create a template sensor with associated attributes... its saying this is wrong:

  - sensor:
      name: docker_code_server
      unit_of_measurement: 'MB'
      state: '{{ state_attr("sensor.docker_code_server_memory","friendly_name") }}'
      state_class: measurement
      attributes:
        - dmemory: "{{ states('sensor.docker_code_server_memory') }}"
        - dstate: "{{ states('sensor.docker_code_server_state') }}"
        - dstatus: "{{ states('sensor.docker_code_server_status') }}"
obtuse zephyr
#

sensor is a list, not a map and attributes are a map, not a list

- sensor:
    - name: docker_code_server
      unit_of_measurement: 'MB'
      state: "{{ state_attr('sensor.docker_code_server_memory','friendly_name') }}"
      state_class: measurement
      attributes:
        dmemory: "{{ states('sensor.docker_code_server_memory') }}"
        dstate: "{{ states('sensor.docker_code_server_state') }}"
        dstatus: "{{ states('sensor.docker_code_server_status') }}"
pine musk
#

thanks. that looks like it will work.

mighty ledge
#

outside vs inside quotes don't matter so both should work

#

unless you're using something else to 'check'

pine musk
#

vs-code was indicating an error by marking it all with red underlines

#

when I made NSX's chasnge it cleared up

mighty ledge
#

yes, well you can ignore vs-code then

#

because it's valid yaml either way

inner mesa
#

It looks at schemas, not just valid YAML

#

the HA extension, that is

mighty ledge
#

Yes, well the point being is that it's incorrect about ' "" ' being invalid

obtuse zephyr
#

It wasn't complaining about that though, attributes in the initial was a list and sensor was a map.

#

I swapped it in my response because I like consistency 🙂

mighty ledge
#

ah, completely missed that!

thorny snow
#

I have this template binary sensor - which worked. I dont think I have changed it, but it continually now says "Unavailable" in the dashboard.
- name: Free Electric state: "{{ states('sensor.octopus_energy_electricity_current_rate') | float < 0 }}"
what might be causing this?

inner mesa
#

what is the state of sensor.octopus_energy_electricity_current_rate?

#

my guess is that it's not a number, and you provided no default, so it's not rendering the template and you have an error in your log about it

inner mesa
#

put the template in devtools -> Templates and debug from there

#

your indentation is also wrong above. state: should line up with name:

thorny snow
thorny snow
inner mesa
#

and it's really a binary_sensor and not just a sensor?

thorny snow
#

yes, it only needs to tell me if the unit rate is below 0 or not

inner mesa
#

I'm not questioning the reasoning, but the execution

#

and your indentation still looks wrong, so...

thorny snow
#

no i get it - trying to make sure it all lines up - appreciate it
I just dont get how its gone from working fine - to unavailable.
I removed the integration that feeds it the data a few weeks back, but added it again, ive double checked the entityID

thorny snow
inner mesa
#

usually that means that it added a xxx_2 entity_id

thorny snow
thorny snow
#

developer tools > states : shows only a single entity called Free Electric and the same for the energy sensor it reads

gusty ledge
#

I have an input_text.history which has the the latest states "fork,knife,spoon,...." Is it possible to test input_text.history has state knife within the last 60 minutes?

inner mesa
#

you can create a template sensor that tests for that, and then use the last_changed property of that entity

gusty ledge
lethal bison
#

Is it possible to template a - service: call? I'm attempting to call multiple entities with the same variables. I've attempted to pass a list of names to the service call with ```yaml
action:

  • service: >
    {{ expand( 'light.group_diningroom' ) | map(attribute='entity_id') | list
    | regex_replace(find="/?\d+", replace='variable_brightness') |
    regex_replace(find="light./?", replace='') }}```
    but the automation says "Stopped because of unknown reason "null""
inner mesa
#

Yes, you can template a service

#

If the template is working, replace > with >- and make sure the template is indented. I can't tell from my phone

lethal bison
#

okay, I"ll try that

lethal bison
#

Still no go. It does appear my regex sucks, as it's replacing everything after the first underscore, instead of appending the string "_variable_brightness" to the end of each result. I'm still testing

hexed galleon
#

How would I get a list of all binary_sensor entities that have a device_class of "door" without using a for loop?

inner mesa
#

{{ states.binary_sensor|selectattr('attributes.device_class', 'defined')|selectattr('attributes.device_class', 'eq', 'door')|map(attribute='entity_id')|list }}

hexed galleon
#

Fantastic, thank you! I was so close 🙂 Is there an "in" clause for selectattr? Or would I need to somehow do an "or" if I also wanted to include say "window" device_class?

plain magnetBOT
#

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

elfin nymph
#

nvm, i got that but i got a totally different problem... but first i got to sleep

hexed galleon
#

Jinja is so handy! Thanks for your help.

analog mulch
#

When not available, my templated SQL sensors are reporting the following error:

Sensor sensor.lights_all_energy_l90d has device class None, state class None and unit kWh thus indicating it has a numeric value; however, it has the non-numeric value: None (<class 'str'>); 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+sql%22

What am I supposed to output to the sensor so that it doesn't complain? Is there a None which is not treated as a string? The error is being generated by the following template in the SQL sensor:

    {% if states('sensor.all_light_energy')|is_number and value|is_number %}  
    {{((states('sensor.all_light_energy')|float  - value|float)/90)|round(3)}}
    {% else %}
    None
    {% endif %}
marble jackal
#

0 maybe? Depends on how you are using the result of this sensor

analog mulch
#

Ok for this onereturning zero is ok, but I have others where I want it to just be unavailable or something like that.

But this seems to be a generic problem with 2023.2 -- the sql integration now generates a whole bunch of such errors in the logs when HA is starting up -- something isn't ready yet and I think these type of errors were suppressed before.

marble jackal
#

not sure here, but maybe you can return unavailable instead in of none

analog mulch
#

that's how I started. Then I get the complaint that unavailable is a string

marble jackal
#

or actually provide none instead of the string "None"

analog mulch
#

prove none?

#

it's just a question of the case, or it's somethign special?

marble jackal
#

provide.. typ0

    {% if states('sensor.all_light_energy')|is_number and value|is_number %}  
      {{((states('sensor.all_light_energy')|float  - value|float)/90)|round(3)}}
    {% else %}
      {{ none  }}
    {% endif %}
analog mulch
#

aha interesting let me try

marble jackal
#

or simply remove the else

#
    {% if states('sensor.all_light_energy')|is_number and value|is_number %}  
      {{((states('sensor.all_light_energy')|float  - value|float)/90)|round(3)}}
    {% endif %}
#

or: {{ ((states('sensor.all_light_energy')|float - value|float)/90)|round(3) if states('sensor.all_light_energy')|is_number and value|is_number }}

analog mulch
#

Alas, if I don't return anything it complains it has an empty string:

Sensor sensor.kitchen_microwave_energy_l90d has device class None, state class None and unit kWh thus indicating it has a numeric value; however, it has the non-numeric value: (<class 'str'>); 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+sql%22
marble jackal
#

It seems to be the same erorr as before

#

Except it doesn't mention the state (as it is none now and not "None")

analog mulch
#

yes exactly -- it really needs a numerical value (because of the history, and correctly so), but if there is some unavailability it fails and nothing will satisfy it. For template sensors I set the availability key, but here I am not sure what to do otherwise.

elder mural
#

Hi Guys I'm really new to this and have tried finding examples to learn but have not been able to find any written example for me to understand how to actualy pull this off.

I'm trying to use a counter helper value as a trigger.

As an Example

mdi:fan
{% else %}
mdi:power
{%endif %}```

If theres any resources that i should first read up with examples other than the documentation on Home Assistant I would very much appreciate it as well!
marble jackal
#

{% if states('counter.fan_speed_state') | float(0) > 0 %}

#

Or, in a one line template:
{{ 'mdi:fan' if states('counter.fan_speed_state') | float(0) > 0 else 'mdi:power' }}

rose scroll
#

Actually...any particular reason you are using a counter to record your fan's speed?

marble jackal
#

And that 🙂

elder mural
# rose scroll Actually...any particular reason you are using a `counter` to record your fan's ...

its an RF Fan. I originally had an input boolean for the on/off state but was wondering if i could just use the counter count of 0 to indicate it as being turned off, and the other values to correspond to their speed values.

being new to this i wasn't really sure what other helper i should be using but when i saw counter, my monkey brain thought it made sense. is there perhaps a better way to do so?

elder mural
rose scroll
#

Check out input_select or input_number, aka Drop-down and Number in the Helpers menu.

elder mural
elder mural
#

Thanks @rose scroll and @marble jackal for the guidance!

neon bolt
#

hi, is there any way to track if a thermostat value was changed either by a human on the thermostat himself vs by an automation ?

mighty ledge
#

Yes, using a template condition that looks at the context object

neon bolt
#

do you have an exemple ?

mighty ledge
#

examples most likely won't help as the context object differs for what you intend to use it for

#

you need to reverse engineer what context you care about

neon bolt
#

can I explain what i want to achieve ?

#

maybe there's a better way 🙂

mighty ledge
#

context.user_id
context.id
context.parent_id

#

no there isn't a better way

#

you have to find out which id matches a context objects id

#

users have ids, it's an attribute of a person. So if your person does not have a user attached, you won't get context

#

automations, scripts, scenes, etc have an id, it's context.id

#

and you have to figure out which id matches the context object in your current automation.

#

the object in your current automation will come from your trigger

#

e.g. trigger.to_state.context

neon bolt
#

thanks, I will try to figure out how to implement that

azure tinsel
inner mesa
#

With what? What is wrong?

azure tinsel
#

hm.. i can create second sensor to switch peak/offpeak and use it as trigger maybe

#

it does not set variable tariff properly

marble jackal
#

why use a time pattern trigger

#

just use a time trigger on all relevant times

#
trigger:
  - platform: time
    at:
      - "06:00"
      - "07:00"
      - "22:00"
      - "23:00"
#

and your template has a double quote at the end which should not be there

azure tinsel
#

yep, that will trigger only 4 times a day, not 24, with both hours for winter and summer

#

doh

#

i think the double quote is problem, let me try

marble jackal
#

you might want to add a home assisntant start event as trigger though, for when your HA is not available when it should trigger

azure tinsel
#

yeah, cool, it is working 🙂 double quote was the problem, now i will optimise it with better triggers

#

thank you very much

marble jackal
#
      tariff: >
        {% set winter = [1, 2, 3, 11, 12] %}
        {% set start = today_at("07:00") if now().month in winter else today_at("06:00") %}
        {% set end = today_at("22:00") if now().month in winter else today_at("23:00") %}
        {{ 'peak' if start < now() < end else 'offpeak'}}
#

@azure tinsel you could also use that for your template

azure tinsel
#

lol.. looks much better

marble jackal
#

small copy paste error 🙂

azure tinsel
#

@marble jackal yep, thank you very much, everything working now, and looks a lot better 🙂

mighty ledge
#

@quasi widget do you know where the template tester is?

quasi widget
#

I know where templates under development tools is ^^

mighty ledge
#

yes

#

that

#

so, do you know the integration that created your TV?

quasi widget
#

lg webos integration

wild magnet
#

Hi, i want to create a binary sensor from a sensor with attribute someone can help me

quasi widget
#

before we proceed ... in my mind I'd need a script that basically alternates between the screen on and screen off actions each time it's run

mighty ledge
#

Ok, @quasi widget put this in your tempalte and paste the response here

{%- for e in expand(integration_entities('webostv')) %}
{{ e.entity_id }}:
 {%- for key, value in e.attributes.items() %}
   {{ key }} -> {{ value }}
 {%- endfor %}
{%- endfor %}
mighty ledge
#

or at least track something in the background

quasi widget
#

Right, can't know the state, so basically know what the previous action was and run the other

mighty ledge
#

well, can you just put code I wrote into the template editor?

#

then paste the results here

quasi widget
#

yes, gimme a sec

#

media_player.lg_c2_webos_smart_tv:
source_list -> ['Apps', 'HDMI 2', 'HDMI 3', 'HDMI 4', 'Live TV', 'Media Player', 'PC', 'Web Browser']
volume_level -> 0.12
is_volume_muted -> False
source -> PC
sound_output -> tv_external_speaker
assumed_state -> True
device_class -> tv
friendly_name -> LG C2 42"
supported_features -> MediaPlayerEntityFeature.PLAY|STOP|SELECT_SOURCE|VOLUME_STEP|PLAY_MEDIA|TURN_OFF|NEXT_TRACK|PREVIOUS_TRACK|VOLUME_MUTE|VOLUME_SET|PAUSE

mighty ledge
#

ok

#

so, only 1 entity

#

and it's already assuming the state of the TV it looks like

#

so, make an input_boolean, name it lg_screen or something

quasi widget
#

ah yes, I thought we might come to input_boolean

#

you're assuming I know how to do that, haha 🙂

mighty ledge
#

then, make a template switch (place this into configuration.yaml)

switch:
- platform: template
  switches:
    lg_screen:
      name: LG TV Screen
      value_template: "{{ states('input_boolean.lg_screen') }}"
      turn_on:
      - service: homeassistant.turn_on
        target:
          entity_id: input_boolean.lg_screen
      - service: script.turn_on_lg_screen_script
      turn_off:
      - service: homeassistant.turn_off
        target:
          entity_id: input_boolean.lg_screen
      - service: script.turn_off_lg_screen_script
quasi widget
#

input_boolean:
lg_screen:
name: Turn TV screen on and off
icon: mdi:whatever

#

would making an input_boolean look something like this?

mighty ledge
#

create one in the UI

#

it's in helpers

quasi widget
#

what kind of helper do I choose, toggle, switch as x ... ?

#

(sorry about these basic questions, but I've only a very vague grasp on things, haha)

mighty ledge
#

toggle

quasi widget
#

yep, did that

#

alright, I put the above code in configuration.yaml, put in the right script names

#

in the name: line it say Property name is not allowed

mighty ledge
#

it's probably friendly_name: instead of name:

quasi widget
#

indeed, that did it

#

where do I go from here?

quasi widget
#

I did that, yes, put in the names of my own screen on and off scripts

#

Screen On / Off Toggle Switch

switch:

  • platform: template
    switches:
    lg_screen:
    friendly_name: LG C2 Screen On / Off
    value_template: "{{ states('input_boolean.lg_screen') }}"
    turn_on:
    - service: homeassistant.turn_on
    target:
    entity_id: input_boolean.lg_screen
    - service: script.tv_screen_on
    turn_off:
    - service: homeassistant.turn_off
    target:
    entity_id: input_boolean.lg_screen
    - service: script.tv_screen_off
mighty ledge
#

ok

#

after you restart you'll have a switch named switch.lg_screen

quasi widget
#

Ah, indeed, got it.

mighty ledge
#

if you want to manage that from the UI, add unique_id: lg_tv_switch between friendly_name and value_template

#

at the same indendation

#

then you'll have a switch you can manage in the UI, i.e. you can put it in an area

quasi widget
#

damn, it works!

mighty ledge
#

just keep in mind that it will get out of sync when you change it via the remote

#

but if you use switch.toggle as a service, it won't matter

quasi widget
#

well, the point of this whole thing is to never use the remote 😛

#

I'm using my C2 as a monitor

mighty ledge
#

yes

#

I only use my remote now to fix things

#

other than that, my wife and I use HA in our phones

quasi widget
#

nice

#

that's a project for another day, for now I'd like to make a macro pad that controls my C2, mostly screen on/and off and power on/off

#

since I have your attention, as I understand it the most practical way to go about it is via mqtt, right?

mighty ledge
#

🤷‍♂️

#

it's whatever you can dream up

quasi widget
#

macropad sends hotkey to pc -> an mqtt enabled app catches it -> forwards it to HA -> runs appropriate script

mighty ledge
#

can your macropad write directly to an MQTT topic?

#

if yes, then that's what I would do

#

otherwise your other option is to use webhooks if it can do webhooks

quasi widget
#

that would be the direct way, yeah, but no, it's a dumb wireless USB pad

mighty ledge
#

if your macropad can do webhooks, then all you'd need is
macropad sends hokey to ha

#

you can even create webhook events

#

then an automation that runs a script based on the event

#

you have plenty of options

#

webhooks aren't easy but TBH, you didn't screw up the configuration.yaml portion that I posted, so you seem like you can do difficultt hings with directions

#

which oddly enough, following directions is a skill many people don't have.

quasi widget
#

right, but since the only thing this macropad can do is send HID inputs to the PC, I was thinking of using an application called HASS.Agent

#

thanks, I guess, hehe

#

I'm still in high water with all this stuff, but I'll get there

mighty ledge
#

I use hass.agent

#

it's simple

#

I use it w/ mqtt too

#

because I was too lazy to set up the webhook stuff

#

if you already have MQTT broker on your network, it's always a goto for use IMO

#

if you don't, then invest in webhooks

#

either way, the option for both is yours

quasi widget
#

I did set up Mosquitto in anticipation, definitely plan to play around with mqtt

#

well petro, I'm gonna stop bothering you for now, you've been extremely kind and patient, thank you very much

mighty ledge
#

np

quasi widget
#

I'm sure I'll be back at some point, heh, hopefully with higher level stuff 😛

#

have a good one

mighty ledge
#

You too

sonic ember
#

Jumping over here from #automations-archived ... I'm trying to create a simple template for a message to publish over MQTT. But even my small test won't work out. Can't figure out what I'm doing wrong. Whatever I fill into "Payload template" comes back to "[object Object]": null once I save the automation.

mighty ledge
#

json accepts: string, boolean, integer, double, null, list, or dictionary.

#

anything outside those types won't appear correctly

sonic ember
#

Hmm but shouldn't this return a string: {{ states('device_tracker.myphone') }}

#

It does in the template tester

mighty ledge
#

it should, but you're doing that in Node red right?

sonic ember
#

No, this is in Automations

mighty ledge
#

ok, post the full service you're using in yaml

sonic ember
#

I'm using visual editor, but this is what it creates:

service: mqtt.publish
data:
  qos: "1"
  retain: false
  topic: /test/topic
  payload_template:
    {{ states('device_tracker.myphone') }}
mighty ledge
#

you're missing >

#

if you plan to use multiple lines for your template, you need to use the multi-line yaml notation

sonic ember
#

Yeah I wasn't planning to, I wanted to do it in the Visual Editor

mighty ledge
#
  payload_template: >
sonic ember
#

Now it works if I manually create it in yaml

#

Damn, so the visual editor was the problem, now it works fine.

#

Thanks!

mighty ledge
#

np

snow folio
#

Guys I've made this automation but the remaining time on my timer is not updating, is there a way to calculate this based on "finishes_at" and give a response in "x hours" and "y minutes"?

https://pastebin.com/b0FytfyC

obtuse zephyr
#
  {% set remaining = state_attr('timer.a_timer','finishes_at') | as_datetime - now() %}
  {{ remaining.seconds // 3600 }} hours and {{ (remaining.seconds // 60) % 60 }} minutes
sonic ember
snow folio
obtuse zephyr
#

as in it's speaking the template instead of substituting the values?

#

Share what you have now

snow folio
#

it works on templates but echo still saying the value of .remaining

obtuse zephyr
#

I don't completely understand what you're saying it's doing.... however, did you reload the automations if you're doing this outside of the UI ?

snow folio
#

I was bashing my head in here, I suck at programming :/

plain magnetBOT
#

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

faint marsh
#

hi, I have a waste_collection sensor with the following attributes:
`types: Papier, Problemabfall, Gelber Sack, Restmüll
upcoming:

  • date: '2023-02-09'
    icon: mdi:trash-can
    picture: null
    type: Restmüll
  • date: '2023-02-13'
    icon: mdi:recycle
    picture: null
    type: Gelber Sack`
    How can I access the icon in the upcoming events array to use it in a template-card?
marble jackal
#

state_attr('sensor.your_waste_sensor', 'upcoming')[0].icon

faint marsh
#

that results in: UndefinedError: None has no element 0

#

At least in the template editor

#

Does that make a difference?

marble jackal
#

did you replace the sensor in my template with yours?

faint marsh
#

yes

marble jackal
#

{{ state_attr('sensor.your_waste_sensor', 'upcoming') }} this should return the array

faint marsh
#

Now it is working! I had to reset the Template Editor to Demo Template

#

Thank you very much

unique gyro
#

Hey there! 🙂 After searching for a little while I came empty handed. Maybe my search was not accurate for what I’m looking to accomplish. I have a Valetudo based vacuum and I want to create an entity that would allow me to see and change the current fan speed of the robot. Basically, the dropping list that let you choose the fan speed when you open the vacuum entity but as it’s own entity to integrate it into a dashboard. Is this possible? Thank you for your help.

lethal bison
#

Sounds like a select component. Open up the details for the entity, you can verify there

unique gyro
#

If I look at the entity I get : fan_speed_list:

  • low
  • medium
  • high
  • max
    battery_level: 100
    battery_icon: mdi:battery-charging-100
    fan_speed: high
    icon: mdi:robot-vacuum-variant
    friendly_name: Dreame W10 appartement
    supported_features: 8956
#

The vacuum entity seems to wrap it as a selector indeed. Thing is, I’m not sure how to only access the selector.

lethal bison
#

Not sure, in Settings > Devices > Entities tab, search for 'select', see if your vacuum is listed

sacred sparrow
#

Hi, I am a little confused as this template shows as "Unknown" instead of "off" when the upload/download sensors are "unavailable":

    - name: "NAS Data Transfer"
      icon: mdi:swap-horizontal
      availability: "{{ not is_state('binary_sensor.nas_status', 'unavailable') }}"
      state: "{{ states('sensor.nas_throughput_upload')|float > 50 or states('sensor.nas_throughput_download')|float > 50 }}"```
#

I am confused because I have another template that shows as 'off' when the volume status sensors are unavailable:

    - name: "NAS Status"
      icon: phu:nas-v2
      state: "{{ is_state('sensor.volume_1_status', 'normal') or is_state('sensor.volume_2_status', 'normal') }}"```
#

how can I get my first template to show as "off" instead of "unknown"?

obtuse zephyr
#

is binary_sensor.nas_status unavailable at that time? You'll want to add a default to your |float a la |float(0) otherwise you'll get a failed template execution (which is what unknown is telling you)

sacred sparrow
#

binary_sensor.nas_status is 'off'

#

hence why I am confused haha

obtuse zephyr
#

Right... so your Data Transfer sensor is still available

#

but if your upload/download sensors are unavailable

#

they can't be parsed to a float

#

So that'll blow up

#

So if unavailable == 0, then just add a default and you'll be good

sacred sparrow
#

sorry I am not sure what you mean by that - how do I add a default?

obtuse zephyr
#

"{{ states('sensor.nas_throughput_upload')|float(0) > 50 or states('sensor.nas_throughput_download')|float(0) > 50 }}"

sacred sparrow
#

oh perfect! Thank you 🙂

obtuse zephyr
#

Yep, you're welcome

lethal bison
# unique gyro It is not. 😦

From what I've seen on the Valetudo integration, you're probably using MQTT for this vacuum. I don't know anything about MQTT, but there should be a way

unique gyro
unique gyro
#

Yay I succeded with MQTT select entity.

#

Created an entity specifically on the FanSpeedControl.. topic.

full nacelle
#

hi I was creating an automation for morning call. It seems to end up in an error

#

Good Morning. {{ [ "I just provided a morning briefing including weather, and traffic conditions, and other things that ensure the residents of Anchorage House know what to expect today.", "Time for the daily update. It was like that scene in Ironman where JARVIS gives the daily briefing but no one was listening. ", "I have prepared a safety briefing to present to my residents but they would just ignore it.", "Do you like to be prepared for the day? So do my residents. So I provided them with an update on whats happening today.", "Sometimes I just like to be snarky, but this morning I decided to just tell everyone what is going on in the world.", "Homeassistant gives me the ability to make daily announcements like the one I just did using #Amazon Polly.", "Each day at this time I provide the residents of this house an update that includes everything they need to know about the upcoming day. But with more snark." ] | random }} {{ [ "The temperature today seems to be", "It seems like the temperature outside is", "The temperature <break time="1s"/>" ] | random }} {{ state_attr("weather.forecast_home","temperature")}}°Celsius, it is {{states("weather.forecast_home")}} outside. The date today is {{states("input_datetime.only_date")}}.

#

the error:

#

Message malformed: template value should be a string for dictionary value @ data['action'][1]['data']

slow vine
#

I have a template like this: {{ states('sensor.caller_id') in ['1111111111', '2222222222', '3333333333'] }} which matches sensor.caller_id to that list. The problem is the state is not just a number, rather its also a name and the name contains a' so it makes it difficult. basically like this: John Doe' 123456789 how can I make a partial match to a list?

full nacelle
slow vine
#

the information I need is in the state. There is not any useful (for this) data in the atribute.

normal rapids
#

Hello.. can I make a (sensor) template that uses another sensor template?

obtuse zephyr
obtuse zephyr
sinful grove
#

I created a template sensor that gives me the daily total cost of my energy.

- name: "Total daily Energy Cost" state: "{{ ((float(states.sensor.octopus_energy_electricity_17p2225658_1200025442284_current_rate.state) * float(states.sensor.octopus_energy_electricity_17p2225658_1200025442284_previous_accumulative_consumption.state)) + (float(states.sensor.octopus_energy_electricity_17p2225658_1200025442284_current_standing_charge.state))) | round(2) }}" unit_of_measurement: "GBP" icon: mdi:currency-gbp unique_id: "sensor.total_energy_daily_cost" device_class: monetary state_class: total

I use also a hacs integration (octopus) which provides a sensor with my total consumption in kWh for electricity and m3 for gas in 1 hour intervals.

Can someone help me understand how I need to set up my energy dashboard to track cost using this sensor?

My energy dashboard shows energy consumption just fine, but I’m struggling to link my daily cost to the dashboard.

marble jackal
#

You don't need to calculate the daily cost yourself. Just provide (a entity for) the price in the settings for the dashboard

sinful grove
marble jackal
#

In Settings > Dashboards > Energy you can provide a price for your energy. The dashboard will then calculate the costs for you

sinful grove
marble jackal
#

No, that's not possible

sinful grove
# marble jackal No, that's not possible

Thanks! Can I ask why not? I’d like to understand limitations here so I can take them into account in the future.

I thought that “Use an entity tracking the total costs” option expects a daily cost value in your currency. What data I would need to provide with this option otherwise?

#

Or if you can point me to any documentation where I can learn more about how to configure energy dashboard, that would help too. Thanks

sacred sparrow
#

Is there a way to repeat until a 4 minute timeout? I tried 'repeat.index == 24' but it didnt work:

  until:
    - condition: template
      value_template: "{{ is_state('binary_sensor.nas_status', 'on') or repeat.index == 24 }}"
  sequence:
    - service: homeassistant.update_entity
      data: {}
      target:
        entity_id:
          - sensor.volume_1_status
    - wait_template: "{{ is_state('binary_sensor.nas_status', 'on') }}"
      continue_on_timeout: true
      timeout: "00:00:10"```
marble jackal
sonic ember
#

Does anyone have a link to documentation on how to use templates in a dashboard card? I am using apexcharts and for one of the properties want to use an entity but the normal templating syntax doesn't seem to work.

marble jackal
sonic ember
#

Thanks!

haughty marsh
#

I'm learning the very basics of templating and I have a syntax question. How do I give an automation one action for each light in a group? I don't want a single action that operates on the group itself, but a distinct action for each group member. I don't understand where to put the {% for light in stuff, and I'm having trouble finding this online

frigid grail
marble jackal
#

That's what I would do

frigid grail
#

And speaking of templates, I’ve ran in an issue with an automation which is leading me to templates: I’ve got an Mqtt select that gets filled with the friendly names of my hue scenes (waf) so the spouse can select which scenes should run at a specific time of day. However I noticed (she complained;)) that some scenes didn’t work. So I noticed that for some scenes the friendly name and the entity Id didn’t match. Since I do a recall scene with a template that combines the friendly name with the room this triggers the error. So I’m in the templates test environment trying to figure out how I can get the entityid based on the friendly name. I’ve got a template that will select the correct one but I can’t get the entity I’d from it

#

{{ states.scene | selectattr('attributes.friendly_name', 'match','Living Room ' + states.select.evening_scene.state)|list}}

#

I tried with map(attribute='state') but I only got an date back not the entityid

hushed nacelle
#

I thought I was being clever by making a template to map a component's config values to dynamic inputs, like this: disable_brightness_adjust: {{ is_state('input_boolean.brightness_light_control_enabled', 'off') }}
(accepts true or false)

except that doesn't work?

Error loading /config/configuration.yaml: while parsing a flow mapping in "/config/configuration.yaml", line 243, column 33 expected ',' or '}', but got '<scalar>' in "/config/configuration.yaml", line 243, column 99

Does that mean I can't just use templates for values that don't accept templates? Is there a way to do this? I just wanted to not have to restart HA every single time I want to change these values

tepid onyx
hushed nacelle
#

I see, I know how to do that, can I just pass sensors to config values?

#

like those that accepts booleans or integers

tepid onyx
#

try it and see 😉

hushed nacelle
#

I'll try

marble jackal
hushed nacelle
#

I see, that indeed seemed to be accepted for the boolean but not for the ints

marble jackal
#

Not sure what you are referring to now

marble jackal
hushed nacelle
#

Tried this template sensor now:
adaptive_light_min_brigthness: friendly_name: "Adaptive light Min Brightness" unique_id: "AdaptiveLightMinBrightness" value_template: > {{ states('input_number.circadian_light_minimum_brightness') | int }}

and min_brightness: AdaptiveLightMinBrightness

but still:

Invalid config for [adaptive_lighting]: expected int for dictionary value @ data['adaptive_lighting'][0]['min_brightness']. Got None. (See /config/configuration.yaml, line 244).

#

so I'm trying to figure if it's the integration that just doesn't like using values from templates or if I don't know the syntax, that config value isn't a template value but I don't know if I'm trying to do something that can be done

marble jackal
#

You need to refer to the entity_id of your template sensor

hushed nacelle
#

oh right I forgot the "sensor." part

marble jackal
#

{{ states('sensor.adaptive_light_min_brigthness') | int }}

#

But you can also refer to the input number

#

The sensor is of no added use here

hushed nacelle
#

just tried doing min_brightness: {{ states('input_number.circadian_light_minimum_brightness') | int }} but it's still complaining about Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('input_number.circadian_light_minimum_brightness') | int", None)])" in "/config/configuration.yaml", line 245, column 0

marble jackal
#

Again the quotes around the template

hushed nacelle
#

right I forgot

#

Invalid config for [adaptive_lighting]: expected int for dictionary value @ data['adaptive_lighting'][0]['min_brightness']. Got None. (See /config/configuration.yaml, line 244).

marble jackal
#

Okay, then it doesn't accept templates there

hushed nacelle
#

yeah, so does that mean it just can't be configured through templates at all? no workarounds?

analog mulch
#

Maybe I am abusing jinja2 a bit, but I get a string of comma-separated temperatures from scrape, eg:

'-1 °C,0 °C,0 °C'

I would like to write a template to return this as a list with the units stripped:

['-1','0','0']

I can do a .split(',') to get a list and then a for loop to split each one and pick the leading part, but how do I get this back into a single list to then process later? Or mayeb there is a smarter way to do this using map?

marble jackal
analog mulch
thorny snow
#

I've been getting lost for some time now. I have a string value of time as %H:%M (unit_of_measurement: h; device_class: duration) that I want to add to the current time. Whatever I try, I keep getting error's that I can not do this. I have tried a couple of things with as_timestamp, which according to the docs should work, but that gives me the following error: ValueError: Template error: as_timestamp got invalid input '0.75' when rendering

How can I do this?

#

The value reports itself as H.M but due to duration it shows up in lovelace as HH:MM.

#

Same for strptime btw

#

Got it. timedelta with the state set to float.

#

Well, almost. It gives me the time in 6 decimals of milliseconds. How can I just have it show %H:%M? I now have this:

grand quarry
analog mulch
#

Another inappropriate jinja use -- I have a list of times of the format 17:00 over the next 24 hours. I would like to convert it to a list of isoformat dates, assuming that they are today if before midnight, or tomorrow if after. Because of the change of date I don't think I can use the today_at filter. I can easily do an if statement to figure out the correct date, but I don't know how to map this onto the list. I wanted to use a namespace and append to a list, but this returns unsafe. So I use a string namespace variable, append the times to a string and then split that. Is that the best way?

{% set times = [14,15,16,0]%}
{% set ns = namespace(datestring='') -%}
{% for time in times-%}
{% set bla = (today_at(time~':00').isoformat() if time|int>hour else (today_at(time~':00') + timedelta(days=1)).isoformat()) -%}
{% set ns.datestring = ns.datestring+bla-%}
{%if not loop.last-%}
{%set ns.datestring = ns.datestring+','-%}
{%endif-%}
{%endfor-%}
{{ns.datestring.split(',')|list}}
obtuse zephyr
#

You can't use append, but if you kept it an array, you can add two arrays together to have the same effect. ex. [1,2,3] + [4] = [1,2,3,4]

marble jackal
#
{% set times = [14,15,16,0] %}
{% set ns = namespace(datelist=[]) %}
{% for time in times %}
  {% set t = today_at(time~':00') %}
  {% set t = t + timedelta(days=1) if t < now() else t %}
  {% set ns.datelist = ns.datelist + [t.isoformat()] %}
{% endfor %}
{{ ns.datelist | sort }}
#

@analog mulch this

analog mulch
#

aha makes sense. Thanks

twilit narwhal
#

I want to hardcode the effect list for template light, but cant get my light effect list template to work properly:
effect_list_template: "{{ ['random'] | list }}"
What am I missing?

analog mulch
marble jackal
#

well, as 14 and 0 resulted in future datetimes it bade sense to sort it

#

well all are future, but those are the next day

analog mulch
#

ok, got worried that loops migth be non-deterministic or somethign

marble jackal
#

it was just to have them in a logical order

#

otherwise it would be 14:00 tomorrow, 15:00 today, 16:00 today, 00:00 tomorrow

marble jackal
#

not sure what you are trying to achieve here

twilit narwhal
#

I want to define a "list" of effects for my IR lights. They have only one effect and that's a random loop. As far as I understand, to define supported effects I set effect_list_template, but no matter what I try nothing works :(

#

I get this when I try to load config: Invalid config for [light.template]: some but not all values in the same group of inclusion 'effect' @ data['lights']['relir'][<effect>]. Got None. (See ?, line ?).

marble jackal
#

I have no clue to which integration you are referring now

#

oh, a template light

#

what is your complete config for this template light

plain magnetBOT
#

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

twilit narwhal
#

I control it through appdaemon script that issues commands to MQTT IR blaster

marble jackal
#

BTW you should make your unique_id's more unique.. bedroomlight is something you might reuse

twilit narwhal
#

good point

marble jackal
#

not sure what causes the error though, you're effect list template is a list

twilit narwhal
thorny snow
marble jackal
marble jackal
thorny snow
marble jackal
#

Wait, what is your goal here

#

You should be using strftime, not strptime

#

strptime is used to convert a string to a datetime, you already have a datetime

#

strftime is used to convert a datetime to a string

thorny snow
#

I have a sensor (sensor_tesla_time_to_full_charge) which reports the time till a full charge as H.MM (for example 1 hour 30 minutes is 1.50). I would like to know not how much time is left, but at what time it is fully charged.

inner mesa
#

Sounds like it's the number of hours

#

{{ now() + timedelta(hours=states('sensor.name'))|float }}

marble jackal
#

It doesn't show the time as H.MM. it just shows the time in hours

#

And what Rob posts should indeed work, maybe in combination with strftime

quasi widget
#

hello good people, I was wondering if someone could help me troubleshoot this weird issue I'm having trying to get my LG C2 TV to turn on (and off) with a script.

#

woops, wrong channel

plain magnetBOT
#

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

full nacelle
#

Why is this showing an error "Invalid config for [media_player.universal]: [entity id] is an invalid option for [media_player.universal]. Check: media_player.universal->commands->turn_on->entity id. (See ?, line ?)."

quasi widget
#

oh hey petro, it's me again 🙂

plain magnetBOT
#

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

quasi widget
#

this is the script

#

it works fine if I start executing it while the TV is turned on, I can get it to turn on and off repeatedly, no problem

mighty ledge
quasi widget
#

however if I turn it off and walk away, come back to it a couple of hours later, it won't turn on again

mighty ledge
#

@full nacelle look at your turn off service... it's correct. Then look at your turn on service

#

note the differences

full nacelle
full nacelle
mighty ledge
#

when it's in a deep sleep

quasi widget
#

that's what I'm thinking, but I'm pretty sure I have all the right options enabled in the TV's settings

mighty ledge
quasi widget
#

guess I'll look into it further, I just want to make sure the script is set up right ... which since it works in the moment, it should be

mighty ledge
full nacelle
#

I do understand how they work

mighty ledge
#

ok, so do you understand why turn_on is incorrect and why turn_off is correct?

full nacelle
#

I made a wol for it

#

but it seems cant call it

mighty ledge
#

I still have no idea if you understand what I'm talking about

#

You pasted a snippitof your code

full nacelle
#

I edited the temp from website

mighty ledge
#

This command in your configuration is wrong

    turn_on:
      entity id: switch.lg_tv

This command is correct


    turn_off:
      service: media_player.turn_off
      target:
        entity_id: media_player.arun_s_webos_tv

Can you see what the differences are to know enough to make a change to the turn_on command?

full nacelle
#

turn_on: service: media_player.turn_on target: entity_id: media_player.arun_s_webos_tv

#

this doesnt work for me, i tried it out

#

was experimenting with the button