#templates-archived

1 messages Β· Page 46 of 1

spring thicket
#

I checked there and non of my lights have the entity_id value for some reason

inner mesa
#

If it's on, last_changed is when it was turned on

spring thicket
#

Is there a option i need to select for them to show?

inner mesa
#

You asked about groups

#

Not lights

#

That is how you tell them apart

spring thicket
#

Huh, while thank you :))

#

Also last question for the last_changed how would i measure in a if command if its been on for longer then 10 minutes?

marble jackal
#

selectattr('last_changed', '<', now()- timedelta(minutes=10))

floral shuttle
#

really love that notation/syntax, makes it so clear and fault tolerant. yet cant find the correct syntax using that in an automation condition replacing smthng like: {{(now() - trigger.from_state.last_changed).total_seconds() > states('input_number.presence_timer')|int(default=60)}}. the timedelta can be used like timedelta(seconds=states('input_number.presence_timer')|int(default=60)) but how to get that condition working..

floral shuttle
#

this might be valid:```
{% set period = states('input_number.presence_timer')|int(default=60) %}
{{now() - timedelta(seconds=period) > trigger.from_state.last_changed}}

testing..
spring thicket
#

Does the "last triggered" attributes still work?

floral shuttle
#

why wouldnt it?

spring thicket
#

Cause im having trouble with it xD

#

I was wondering if anyone else was

floral shuttle
#

what are you trying to do?

spring thicket
#

Im trying to turn off lights that have been on longer then 5 minutes

#
service: light.turn_off
data_template:
  entity_id: |
    {% for entity_id in states.light -%}
      {%- if states.light[entity_id].state == "on" and states.light[entity_id].attributes.last_triggered is defined -%}
        {%- set last_triggered = as_timestamp(states.light[entity_id].attributes.last_triggered) -%}
        {%- if (now().timestamp() - last_triggered) > 300 -%}
          {{ entity_id }},
        {%- endif -%}
      {%- endif -%}
    {%- endfor %}
#

This is my code

#

But for some dumb reason non of the lights are turning off and its not working😭

#

Any idea?

#

On why its not working?

#

Im thinking of just switching over to python/appdaemon but i still wanna learn templating so that's why im doing it on that

marble jackal
#

last_triggered is not an attribute of a light entity

spring thicket
#

😐

marble jackal
#

Your looking for last_changed

spring thicket
#

Ah

#

XD

#

Thank youuu

marble jackal
#

And I already gave you the filter you should add to your template

#

Still no need for a loop

spring thicket
#

I did

#

I now get TemplateError: Invalid entity ID 'light.light.genio_led_strip_light'

marble jackal
#

That's because you are adding light. to your entity_id which it already has

#

But you are not listening to what I'm saying

spring thicket
#

Hmm?

marble jackal
#

{{ states.light | selectattr('state', 'eq', 'on') | selectattr('last_changed', '<', now()- timedelta(minutes=10)) | map(attribute='entity_id')|list }}

#

No need for a complicated for loop

spring thicket
#

The point for the loop is so i can put it in a automation as in

#

Instead of making a new script yk

marble jackal
#

You can just put the output of my template in a service call

#

And data_template has been depreciated for over 3 years, just use data

spring thicket
#

Wait so

#

Well

#

Im dumb xD

#

Wait so I didn't need to cycle through every light because entity_id accepts lists as well ;-;

#

oh wait fuck i just realised

#

i can't do that especially when i need the rooms they

#

are all in too lmao or what rooms the alexa is in with them

lyric comet
#

You can add a filter by area to TheFes' template. I hope you have a lot of conditions on that automation or people sitting in the rooms with lights are going to be unhappy. I have an automation for each room which is conditioned on occupation of the room and the light levels.

#

Ok course you could simply use the area directly in light.turn_off if any of the lights in that room are on.

floral shuttle
#

yeah, and you dont even need to check if they are on....

spring thicket
#

okay okay so BASICALLY why i choose this option instead is because i want it to send a alexa actionable notification to the room that the light is on in asking the person if alexa can turn OFF the light and if it does then it turns it off if not keeps it on

spring thicket
floral shuttle
#

Ofc you have your goals I might not grasp. What I meant was that for turning off lights in a particular room, you don’t need to check if they’re on. Simply issue the turn_off command to that room will turn them all off. It will only affect the light that was on, and if no light is on it won’t hurt either

spring thicket
#

true true fair point

floral shuttle
#

can even add the area to the service: service: light.toggle target: area_id: library πŸ˜‰ and compare that to the data template we had to use before the area coudnt be set as a target (long time ago....) {{expand(area_entities('library'))|selectattr('domain','eq','light') |map(attribute='entity_id')|list}}

spring thicket
#

I am trying to avoid asking other people and trying to figure it all out myself but i continously get stuck and run into errors and then spend hours on trynna figure it out and then get no where in the end

floral shuttle
#

sure, but you need to start with answering #templates-archived message . you've come to the right place, and no issue at all asking. just help us help you

spring thicket
#

mmm thank you :)) and i will indeed try to help out in the community more :>

#

also if i may ask how do you check what attributes a entity has? i checked the states but it doesn't appear to be showing them all i was wondering if there was a way to get a list through the template editor?

floral shuttle
#

? that is not what I meant.... I meant saying you need to start with explaining what you want to achieve. And not start with some technical solution that might not be the best solution for your requirement at all.

floral shuttle
spring thicket
#

Right now i'm currently trying to figure out a way to try figure out what room a light is currently in

#

i tried attribute.room or area but it doesn't appear to be a attribute lmao

floral shuttle
#

but you cant just try things. you need to follow the HA architecture πŸ˜‰ all explained in the docs....

#

btw, and this is an example of we needing to understand what you want: if all you want to do is show the 'on' lights in an area in your Dashboard view, you wouldnt need a template at all. You could simply use an auto-entities card in the dashboard and have that do the work for you...

#

just saying

spring thicket
#

okay okay so, what i am trying to get from the template is a list of alexa devices entity_id which are in rooms that have a light on in so i can use the alexa's entity id to activate a actionable notification.

floral shuttle
#
  - type: custom:auto-entities
    card:
      type: entities
      title: Lights 'on' in Library
    show_empty: false
    filter:
      include:
        - domain: light
          state: 'on'
          area: Library
spring thicket
#

i decided to refer back to the for loop again xD

{% for light_entity in states.light %}
  {% set light_room = states(light_entity.entity_id, 'attributes.room') %}
  {% for alexa_entity in states.media_player %}
    {% if states(alexa_entity.entity_id, 'attributes.area') == light_room %}
      Light Entity: {{ light_entity.entity_id }}

      Light Room: {{ light_room}}
      
      Alexa Entity: {{ alexa_entity.entity_id }}
    {% endif %}
  {% endfor %}
{% endfor %}
#

but what i find i get with this is it loops back to me all the lights whom have the state "Unavailable " in it

#

the end goal of this entire automation is to hopefully be able to check which lights are on and if they've been on for longer then 15 minutes if so it sends an actionable notification to the local alexa relevant to that light that is on asking the people in that room if they want to turn the light off. If no response is heard or a yes response is heard then turn it off else if a no response is heard then leave it on

marble jackal
#

A light doesn't have a room attribute

spring thicket
marble jackal
#

Check in developer tools > states

spring thicket
#

is there any of way of detecting which room a light is in?

marble jackal
#

You need to use area_entities()

#

Or area_name()

#

In this case

spring thicket
#

may i ask what exactly is that?

#

is it a attribute?

marble jackal
#

It's a function

#

area_name('light.some_light') will give you the area name of that entity

spring thicket
#

where's the documentation for that?

marble jackal
#

In the templating docs

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

marble jackal
#

2nd link

spring thicket
#

that explains alot thank you xD

#

wait nvm

spring thicket
#

does anyone happen to know how you could possibly detect who send event as a condition?

spring thicket
#

thank youuu

plain magnetBOT
#

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

marble jackal
#
  - condition: template
    value_template: >-
      {{ trigger.event.context.user_id ==
      states("media_player.brandon_s_bedroom_alexa")}}

This will never be true, the user id will never match the state of your Alexa entity.
Check the automation trace to see how a user_id in the context variable looks like

spring thicket
#

oh yeah i seen it lmao

#

would you happen to know anyway to check what device triggered the event?

marble jackal
#

Unless it's sent a part of the event (in the event data) I don't think you can

spring thicket
#

ahh damn thank youuu

lyric comet
#

If you have alexa media player installed you can use the sample there to get the last used player. This should normally be the one which triggered the automation. I use it to send tts to when something is called from them. I use different script data parameters so I know if the call came from Assist or Alexa or the dashboard

spiral imp
#

What do I have wrong with this? I am trying to use it in a markdown card.
{{ iif(is_state('sun.sun', 'above_horizon'), "Sunset is at" 'as_timestamp(states('sensor.sun_next_setting')) | timestamp_custom('%-I:%M %p')', "Sunrise is at" {{ as_timestamp(states('sensor.sun_next_rising')) | timestamp_custom('%-I:%M %p') }}.

mighty ledge
#

your quoting is all sorts of wrong

#

you have random quotes everywhere

spiral imp
mighty ledge
#

don't try to do it in one line

#

separate, then ~ them together

spiral imp
#

I have it working in multiple lines

#

It is part of a longer weather forecast string in a markdown card

#

This works, in the template editor:

#

{% if is_state('sun.sun', 'above_horizon') %} Sunset is at {{ as_timestamp(states('sensor.sun_next_setting')) | timestamp_custom('%-I:%M %p') }} {% else %} Sunrise is at {{ as_timestamp(states('sensor.sun_next_rising')) | timestamp_custom('%-I:%M %p') }}. {% endif %}

mighty ledge
#

Then use that

#

No reason to use iif

#

especially if you don't understand string concatenation

spiral imp
#

Ok, thanks

fallen bridge
#

hello, i'm writing automation that will do watchdog on several entities i.e triggered by state change from off to on for X munutes and turn it off. I cannot find syntax that will do action in a single line : instead of entity_id: switch.heater_kids_bathroom i want entity_id: {{ entity id that triggered me}}. I hope it's possible πŸ™‚

fallen bridge
#

so entity_id: {{ trigger.entity_id}} should do that ?

#

nope it's does not work.

inner mesa
#

You need to surround the template in quotes. And it needs to be under data:

#

Or target:

#

There's example on that page

fallen bridge
#

thanks a lot, my bad i missed the sample

#

got it working

limber haven
#

Hm.. so I've got an addon that gives the state of my dishwasher and I want to pull some of the states out to display in a template but Im kind of confused about something..

#

There is a state sensor.011090527032007221_active_program That in ha's Device and services shows the result as 'Eco50', but if I pull the state out via a template by calling that state, it shows up as Dishcare.Dishwasher.Program.Eco50

#

How the heck do I just get the "eco50" without the rest of the string? πŸ˜„ (HA seems to doing this itself on the ui just fine)

mighty ledge
#

It’s an enum sensor

#

Check against that full string. It’s used for translations

#

@limber haven ^

limber haven
#

Ah, Im not sure what oyu mean by that

mighty ledge
#

You have to use the whole value

limber haven
#

Well, I'm not checking this against something for an automation, I just want it to display in the output as "Program Running : Eco50" not.. "Program Running: Dishcare.Dishwasher....."

#

Appologies if Im not understanding, Im very much struggling with templating πŸ™‚

mighty ledge
#

The frontend should already translate it for you.

#

What does it show when you look at it in an entities card?

limber haven
#

It looks correct in a Entities card, shows up as 'Eco50c' which is the result I want which is why Im quite confused πŸ™‚

mighty ledge
#

Ok, so then you don’t need to template anything

#

Because it’s being translated for the front end

limber haven
#

Well, I want this to be part of a title card is the thing, not an entitiy card so it wants it in a {{ .... }} format..

#

which is what is giving me the 'non-translation' string result rather than then actual translated result?

#

So {{ states('sensor.011090527032007221_active_program'}} returns the value Dishcare.Dishwasher....

mighty ledge
#

Split the state on the . And grab the last item with [-1]

limber haven
#

πŸ™‚ Dishwasher Running - {{ states("sensor.011090527032007221_active_program").split(".")[-1] }} seems to work, thank you

#

Still confused why that was needed at all but... got there πŸ™‚

thorny snow
#

helo, i am running into an issue, i have some data that i send to home assistant via a webhook. and i want to filter out a perticular value. i want to filter out the 1st value of the orientaton array so i can compare this in an automation. can someone help me on how to do this. This is my template so far: message: "{{ (trigger.data.json | from_json).data.results[0].orientation }}"

#

this is the recieved code via webhook: json: {"hook": {"target": "https://webhook.site/5d76c3fd-0f55-4944-a338-0e326afc946e", "id": "camera-1", "event": "recognition", "filename": "camera-1_screenshots/23-05-08/14-23-40.241128.jpg"}, "data": {"camera_id": "camera-1", "filename": "camera-1_screenshots/23-05-08/14-23-40.241128.jpg", "timestamp": "2023-05-08T14:23:40.241128Z", "timestamp_local": "2023-05-08 14:23:40.241128+00:00", "results": [{"box": {"xmin": 317, "ymin": 247, "xmax": 362, "ymax": 261}, "plate": "p534sn", "region": {"code": "nl", "score": 0.519}, "score": 0.902, "candidates": [{"plate": "p523sn"}, {"plate": "p523sn"}, {"plate": "p523sn"}, {"plate": "vcg567"}], "dscore": 0.915, "vehicle": {"score": 0.769, "type": "Sedan", "box": {"xmin": 171, "ymin": 166, "xmax": 394, "ymax": 302}}, "model_make": [{"make": "Trabant", "model": "601", "score": 0.825}, {"make": "Trabant", "model": "P 601", "score": 0.1}, {"make": "Trabant", "model": "1.1", "score": 0.069}], "color": [{"color": "yellow", "score": 0.93}, {"color": "blue", "score": 0.01}, {"color": "brown", "score": 0.01}], "orientation": [{"orientation": "Rear", "score": 0.936}, {"orientation": "Unknown", "score": 0.032}, {"orientation": "Front", "score": 0.032}], "direction": 165, "source_url": "rtsp://gategate1:gategate1@192.168.178.102:554/stream2", "position_sec": 6577.5802705, "user_data": ""}]}}

marble jackal
#

The first score value?

thorny snow
#

No just the first orientation value. So in this case Rear

#

This software always places the correct value first in the array. So i want to collect this.

lyric comet
#

I always find using the Dev Tools a great help. Try

{% set json = json_str | from_json %}
{{json.data.results[0].orientation[0].orientation}}
#

My trick was to copy your json and set it to a variable json_str. That way you can drill down in the dev tool to find the right field and see what is going on as you do.

#

Also you might be able trigger.json directly as this should already be a mapped json string. So just

{{trigger.json.data.results[0].orientation[0].orientation}}
thorny snow
#

i have made it work with {{ (trigger.data.json | from_json).data.results[0].orientation[0].orientation in ['Front'] }} thanks for helping!

queen perch
#

im having issues.. since this last update.. my esphomes dont work right works when HA loads up and then esphomes stop working for temperature.. but also my automations arent working when i use the imap... but here is the time errors.. i dunno whats wrong but its broke some of my stuff how do i fix it? TemplateError('ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%A %B %-d, %I:%M %p') }}' but no default was specified') while processing template 'Template<template=({{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%A %B %-d, %I:%M %p') }}) renders=34>' for attribute '_attr_native_value' in entity 'sensor.date_and_time' TemplateError('ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%I:%M %p') }}' but no default was specified') while processing template 'Template<template=({{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%I:%M %p') }}) renders=34>' for attribute '_attr_native_value' in entity 'sensor.display_time' TemplateError('ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%I') }}' but no default was specified') while processing template 'Template<template=({{ as_timestamp(states('sensor.date_time_iso')) | timestamp_custom('%I') }}) renders=34>' for attribute '_attr_native_value' in entity 'sensor.display_hour'

#

there are some more i just wasnt able to paste more

marble jackal
#

looks like sensor.date_time_iso isn't giving a valid state

#

But you could simply replace that with now().strftime('%A %B %-d, %I:%M %p') for example

queen perch
#

how do fix that?.. i find this latest update.. is a bit flaky where automation may run but it does nothing... or my lights are reacking slow

#

so remove the timestamp custom then

marble jackal
#

Does sensor.date_time_iso give the current time?

queen perch
#

ya 2023-07-09T10:33:00

marble jackal
#

I guess it's provided by this integration

plain magnetBOT
queen perch
#

i guess thats just what i using

marble jackal
#

I don't see any use for such sensors in templates, as you can use now() instead, like I've shown above

queen perch
#

oh

#

ill give it a try in my stuff least my automation to see if its working

mighty ledge
marble jackal
#

Ah, right, I think I remember that change.

mighty ledge
azure ridge
#

Quick and simple but stupid question: I have a sensor called "sensor.peach" and would like to create a template that gives me it's name. Cant figure this out for the life of me....

marsh cairn
#

{{ state_attr('sensor.peach','friendly_name') }} - if it has the attribute friendly_name

inner mesa
#

{{ states.sensor.aarlo_battery_level_family_room.name }}

#

that will fall back to friendly_name if it exists

meager forum
#

Hey guys. I'm pretty new to this Home assistant stuff. I'm following a youtube video about how to install UI minimalist. But I have a problem for some reason is there anyone who is willing to help me?

#

<@&330946878646517761> can you guys help a rookie?

inner mesa
#

Do not do that

severe grove
#

now a very wise guy huh

#

also why do you assume we're all guys

meager forum
#

Thought if the ping function is not disabled for us we can use it lol

meager forum
grand quarry
#

Pinging a whole group and not even asking a real question is kind of rude, no?

meager forum
grand quarry
#

It was not a real question: https://dontasktoask.com/
It can't really be answered because you didn't specify what you need help with.

meager forum
#

I have an error saying that the Button-card template 'card_esh_welcome' is missing. BUT I believe I did everything right since I'm following a youtube video on it. What should I do?

#

Installed the button-card through HACS and added as a resource to the dashboard. Previously it showcased in the dashboard but after I started to config it not anymore

grand quarry
meager forum
floral steeple
#

Hi, I created an image entity here that points a jpg snapstop/thumbnail from a camera:

#### Images
- image:
    name: Bird Feeder Screenshot
    url: http://homeassistant.local:8123/local/bird_feeder/blink_camera_still_image.jpg

despite the jpg file updating, the entity itself as above, does not update when the jpg updates. Do I have to add a refresh or reporting interval for this new entity?

meager forum
inner mesa
#

it even has an example of watching for an image update

orchid oxide
#

is it possible to convert the state values in the following template from string to float without "dissecting" it (ie using filters or something and without using a loop etc.)
{{states.sensor|selectattr('entity_id','contains','battery')|selectattr('state','match','^[0-9.,]*$')|list}}

inner mesa
#

like |map('float')?

#

those aren't actually state values, either

#

so |map(attribute='state')|map('float')

orchid oxide
#

yeah that converts it to a number, but i want it to retreive the entity id for the given states. so i have
{{states.sensor|selectattr('entity_id','contains','battery')|selectattr('state','match','^[0-9.,]*$')|map(attribute='state')|map('float')|select('lessthan', 25)|list}} which returns [21.0, 0.0, 22.0] but i want to return the entity ids, associated with those value

inner mesa
#

You need a loop for that

orchid oxide
#

bleh, okay. ty

pastel moon
#

Hi, from this Sensors: {{ expand(area_entities('Bathroom')) | selectattr('domain', 'eq', 'sensor') | map(attribute='entity_id') | list }} Can I single out only humidity sensors for example?

#

it returns a list of sensor-entity_ids in the bathroom

#

I tend to change the name more often than I really want, so would be good to have automations/scripts read this runtime

#

Got it! Humidity_sensor: {{ expand(area_entities('Bathroom')) | selectattr('entity_id', 'search', 'humidity') | map(attribute='entity_id') | list }}

#

but.... when I now have the entity I need in a variable, how can I get the state using it? states(hum) didn't do it...

lofty mason
#

states takes a string, not an entity. maybe try either hum.state, or states(hum.entity_id)

inner mesa
#

What is 'hum' in that case?

#

The above gives you a list of entity_ids

pastel moon
#

hum is a variable holding the resulting list

inner mesa
#

There isn't just one state

#

What exactly did you want?

pastel moon
#

From a list of all sensors in the room, single out only humidity sensors and read their values

inner mesa
#

So a list of states?

pastel moon
#

I suppose that would be it, yes

inner mesa
#

Replace the last entity_id with state

pastel moon
#

Nice! I wish this wasn't so cryptic... That worked nicely, thanks!

#

So how would this work if I add another humidity sensor in there? It won't show a mean value, I get that, but...?

inner mesa
#

?

#

A list with two values

#

Think about what it's doing

pastel moon
#

lol, sorry! As I only have one, I never had to explicitly select one...

pastel moon
#

Ok. I have thought some more and think it would be useful if the above returned a named array, such as "{{{'humidity sensor 1': 55, 'humidity sensor 2': 76}}}". That way I could then look up the values where needed, making the script more adaptive. Would it be possible to do?

marble jackal
#

yes, in a for loop using a namespace

pastel moon
#

Something like this? {% set areas = ["Hallway", "Closet"] %} {% set ns = namespace(l = []) %} {% for area in areas -%} {% set ns.l = ns.l + expand(area_entities(area)) | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list %} {%- endfor %} {{ ns.l }}

#

But where (how) do I build the array?

marble jackal
#

not like this

pastel moon
#

Ok, please guide me then πŸ™‚

marble jackal
#

you need to build it in the for loop

#

but in your example you have a dict (mapping) not a list (array)

pastel moon
#

oh. I'll have to figure where I go wrong then...

marble jackal
#

what do you want as result

{
  "Humidity Sensor 1": 45,
  "Humidity SEnsor 2: 50
}
#

or

[ 
  {
    "name": "Humidity Sensor 1"
    "state": 45
  }.
  {
    "name": "Humidity Sensor 2"
    "state": 50
  }
]
pastel moon
#

I'd like a list like this: "{{{'humidity sensor 1': 55, 'humidity sensor 2': 76}}}"

marble jackal
#

that's not a list

#

but that is the first verstion

pastel moon
#

Then I can look-up a value for a specific entity with "humidity[entity_name]"

marble jackal
#

the second one is easeier to work with

#

oh, and you want entity_ids

#

your not providing entity id's in your example

pastel moon
#

the example was merely to see if I had grasped the idea, and apparently I hadn't...

marble jackal
#
{% set areas = ["Badkamer", "Woonkamer"] %}                  
{% set ns = namespace(l = {}) %}                                             
{% for i in (areas | map('area_entities') | sum(start=[]))
              | select('search', '^sensor.')
              | select('is_state_attr', 'device_class', 'humidity')
%}
  {% if states(i) | is_number %}
    {% set ns.l = dict(ns.l, **{i: states(i) | float}) %}
  {% endif %}
{%- endfor %}                                         
{{ ns.l }}
#

replace the areas wiht areas you have

pastel moon
#

That is excellent... I so wish I understood the mechanics of this better! Thank you so much!

pastel moon
#

This was harder than I thought... Trying to lookup the value like this {{ humidity_sensor_values[humidity_sensor_entity_id] }} yields an error "UndefinedError: dict object has no element ['sensor.bathroom_weather_1_humidity']"... What am I doing wrong please?

marble jackal
#

@pastel moon you're inputting a list, but the key is a single item

#

humidity_sensor_entity_id does not contain a single entity_id, but a list with one item

#

{{ humidity_sensor_values[humidity_sensor_entity_id | first] }} will probably work

pastel moon
#

I was trying to simplify for me to understand, this is how I'd like to use the template, if it makes sense: {% set sensor = 'sensor.humidity_2' %} {% set humidity_data = {'sensor.humidity_1': 115, 'sensor.humidity_2': 204} %} {{ humidity_data[sensor] }}

pastel moon
marble jackal
#

so the variable you were checking on was a list

topaz silo
#

so im having some issues with a template that used to work, but now does not seem to give the correct 'answer'

#

so even though 'sensor.goodwe_battery_mode' is '2', it is returning 'Unknown'

pastel moon
marble jackal
mighty ledge
#

I'd wager that the sensor was changed to an enum sensor

topaz silo
#

'unknown'

mighty ledge
#

that means it's the |float

#

provide a default for it |float(0)

#

actually, it's also missing )

#

which means it would have never worked

#

are you sure this worked in the past or did you just have this convo with chatgpt today?

topaz silo
#

maybe i typod it just then, but it used to work

#

and i just had this chat just now

#

so change the | float < 50 to | float(0) < 50 ?

mighty ledge
#

just add (0) to float

#

I purposely left out the rest to not confuse you

#

before you had |float but you need |float(0)

topaz silo
#

hmm, not working as yet.. let me check

mighty ledge
#

well, you're still missing the )

topaz silo
#

its working in the template thing in developer tools

#

i must have stuffed something else up in the view

mighty ledge
#

post your configuration

topaz silo
#

hmm, so now im really confused.. if i put the template in the developer tools, it shows the right output

#

but, when i check the state of that sensor in my card on the dashboard, it shows 'unknown'

#

hold on a sec

#

so in my yaml, i have this...

goodwe_battery_mode_desc:
      value_template: >
        {% if is_state('sensor.goodwe_battery_mode', '1') or (is_state('sensor.goodwe_battery_mode', '2') and states('sensor.goodwe_pbattery1')|float(0) < 50) %} 
          Idle      
        {% elif is_state('sensor.goodwe_battery_mode', '2') %}
          Discharging
        {% elif is_state('sensor.goodwe_battery_mode', '3') %}
          Charging
        {% else %}
          Unknown
        {% endif %}
      unit_of_measurement: ''
      friendly_name: "Battery Mode Description"
mighty ledge
#

I'd wager you placed it in your configuration incorrectly. That's why I asked you to post your configuration

#

can you paste your entire configuration in that file

topaz silo
#

you want the entire yaml?

plain magnetBOT
#

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

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

mighty ledge
#

use dpaste

#

top link

topaz silo
#

you want the entire sensors.yaml?

#

as i said, this used to work.. but i havent checked it in a loooong time

#

so i assume some changes in HA broke it?

marble jackal
#

The template is fine now

mighty ledge
#

Nothing in HA broke anything

marble jackal
#

did you reload template entities after your last change?

mighty ledge
#

legacy templates are frozen in time essentially

marble jackal
#

they will never be removed?

mighty ledge
#

seeing that he doesn't have a unique_id, reloading would make the first one unknown, and it would create a second sensor.goodwe_battery_mode_desc_2

topaz silo
#

well, as you said, i had to change float to float(0).. so something changed

mighty ledge
#

yes, that was required about a year ago

#

so, that did change but, not anytime recently

#

so if it hasn't been working for a year, then that would be why.

topaz silo
#

just restarted HA, nothing changed.. still 'unknown'

mighty ledge
#

for the love of god, can you please post your full configuration

#

whatever file it's in. Also post configuration.yaml showing the includes

topaz silo
#

thats sensors.yaml

marble jackal
#

it would have been a lot better if you pasted it as YAML, as the bot message mentioned

mighty ledge
#

@marble jackal just click 'veiw raw'

topaz silo
#

hmm i didnt see that option

marble jackal
#

ah, that helps

#

no nice colors though

topaz silo
#

there

marble jackal
#

oooh, colors

mighty ledge
#

ah, the problem is unit_of_measurement

#

remove that

marble jackal
#

and that is indeed a quite recent change

mighty ledge
#

remove all unit_of_measurement: ''

#

yes, but it's for all sensors, not just template

#

let me rephrase, remove unit_of_measurement: '' for all non-numerical sensors

#

So anything that returns a word, remove that

topaz silo
#

ok

#

so that used to be required, and now its not?

marble jackal
#

It was never required

mighty ledge
#

it was never required

topaz silo
#

ok

mighty ledge
#

ditto

topaz silo
#

i wonder how i ended up with it in there then.. oh well

mighty ledge
#

probably chatgpt if you used it

#

it lies alot

topaz silo
#

no, i didnt

#

that 'chat' above was about the 2nd time ive ever used it

mighty ledge
#

maybe you added it for badges?

#

some people would make the unit_of_measurement: '' so that it had a specific badge display in the frontend if you used badges

#

those little round things at the top of views

topaz silo
#

the power monitoring thing in my config has been broken for a long time

#

and it wasnt really important, as my solar was also pretty much broken

#

but its fixed now, so im looking at the config for it etc again

mighty ledge
#

well, you have alot of |float

#

without defaults

topaz silo
#

so they all need to change right?

mighty ledge
#

if they are converting a sensor, there is a chance at startup that the value is non-numerical, which will cause the float conversion to fail, and subsequently cause the template to fail

topaz silo
#

as in i have to specify a default precision for each

mighty ledge
#

that's not a precision

topaz silo
#

oh, default value

mighty ledge
#

that's the value when it can't convert the state to a number

topaz silo
#

yeah, got it

#

ok, so its not 'unavailable' during startup etc

mighty ledge
#

yeah, it's a rather annoying thing

#

you can also just add an availabilty template too

marble jackal
#

and backspacing

#

was just about to mention that.. Well let me add then that the new format also supports state_class

topaz silo
#

ok, that config is updated.. i guess ill check all others now too

#

thanks for the help

frank harness
#

I wonder if someone can help me, i am pulling my hair out on this and having very long and repetitive conversations with chatGPT :P. I am sure i am just missing something really silly!

#

I have created a utility meter help (sensor.hall_lights_cost). This seems to be doing the job i expect, and is currently reporting 29 Wh
i have a sensor that monitors my per unit cost (1kWh) (sensor.octopus_energy_electricity_xxx_xxx_current_rate). This is working as expected and is reporting 0.3863265 GBP/kWh

I have created the following custom sensor

    hall_lights_daily_rolling_cost:
      friendly_name: "Hall Lights Daily Rolling Cost"
      unique_id: "hall_lights_daily_live_cost"
      device_class: monetary
      unit_of_measurement: 'GBP'
      value_template: '{{ "%.5f" | format (float(((states.hall_lights_cost.state|float(0)) / 1000) * (states.sensor.octopus_energy_electricity_xxx_xxx_current_rate.state|float)) | round(5))}}'
neat prairie
#

chatgpt isn't good for HA. it's quite out of date, and will freely lie to you

frank harness
#

however, that sensor is always reporting Β£0.000000

#

the maths all add up as when i do the maths manually, i get what i expect the value of the sensor to show

neat prairie
#

I'd suggest trying each bit of that in the developer tools template editor. see what it looks like

frank harness
#

IE
29/1000 = 0.029 * 0.38632 = 0.01120

neat prairie
#

like make sure that float(((states.hall_lights_cost.state|float(0)) / 1000) has the value you think it does

frank harness
#

not really sure how i test that in developer tools

neat prairie
#

Go to developer tools. Go the the template tab. try {{ float(((states.hall_lights_cost.state|float(0)) / 1000) }}

frank harness
#

Result Type: string
float(((states.hall_lights_cost.state|float(0)) / 1000)

neat prairie
#

actually, take off the float( at the front.

#

miscounted

frank harness
#

(((states.hall_lights_cost.state|float(0)) / 1000)

#

same results in the results area just without float there

neat prairie
#

you're putting the {{ }} round it?

frank harness
#

Sorry just on a work call give me a second

fickle sand
#

(((states.hall_lights_cost.state|float(0)) / 1000)
That's missing the domain of the entity (sensor), an even better and more robust approach is to change that line to something like this:

states('sensor.hall_lights_cost') | float(0) / 1000
frank harness
#

ok so

(((states.hall_lights_cost.state|float(0)) / 1000) = Does not work (TemplateSyntaxError: unexpected '}', expected ')')

states('sensor.hall_lights_cost') | float(0) / 1000 = Does work, and shows 0.029

frank harness
#

in fact, would you mind showing me what the whole line would be? Still a little confused

#

currently its:

'{{ "%.5f" | format (float(((states.hall_lights_cost.state|float(0)) / 1000) * (states.sensor.octopus_energy_electricity_19l3741410_1013022116772_current_rate.state|float)) | round(5))}}'
fickle sand
#

Than your code should like this

'{{ "%.5f" | format(states('sensor.hall_lights_cost') |float(0) / 1000 * states('sensor.octopus_energy_electricity_19l3741410_1013022116772_current_rate')|float(0) | round(5))}}'
frank harness
#

I just added the missing domain in and actually that did work! But you clearly know better so i will use yours πŸ™‚

#

hmmm

#

i actually got an error using yours in the config checker

#

Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 60, column 7
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 64, column 52

neat prairie
#

Basically, when you have a problem with a template, build it up from elements πŸ™‚ helps work out where the problem is.

fickle sand
#

It could be that some ( or ) is misplaced. Didn't check it, only adjusted the syntax to the correct format

#

the difference between both approaches of accessing the entity states is:

Avoid using states.sensor.temperature.state, instead use states('sensor.temperature'). It is strongly advised to use the states(), is_state() state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).

frank harness
#

'{{ "%.5f" | format((states("sensor.hall_lights_cost") | float(0) / 1000) * (states("sensor.octopus_energy_electricity_19l3741410_1013022116772_current_rate") | float | round(5))) }}'

#

think it was the single speech marks

#

this worked

#

thank you

topaz silo
#

hmm, so now i am looking at my energy dashboard stuff.. it seems some 'sensors' that i used to use, are now missing

#

namely the _accumulated ones

frank harness
#

Its a bit annoying the energy dashboard does not include the cost of the individual devices. Can';t work out why they didnt add that?

frank harness
#

is it

format((states("sensor.electricity_daily_cost") | float))

Just not sure what i should do with that first float that i have missed off

mighty ledge
#

why are you using format

#

the frontend can change the number of sigfigs

frank harness
#

good question πŸ™‚ I dont fully understand it. im just re using someone elses

mental violet
#

Hello,I know this is a big question.
I have a sensor that should contain 12 lists of triples (spending date, spending name, spending value) as attributes (for each month). Based on 6 triggers the list should be changed (It is a new year, it is a new month, adding new entry, remove last entry (of this month), monthly cost should be added).
I have created that sensor, but every time I restart home assistant the sensor attributes are emptied. So they only contain an empty list. Here is my code (of the first 2 months 3-12 are the same as 2).
Any help would be awesome thank you ❀️
https://dpaste.org/xJMPw

lyric comet
#

Are you using 2023.7? It does say it should store trigger sensors, one thing I would be tempted to try is changing the state (eg put a timestamp in it). to ensure the save is triggered

mental violet
mental violet
#

Why does this, if the sensor is unavailable/ unknown not equals to [] ?:

{% set previous = state_attr('sensor.legro_finance_list','monthly_tally_'~month_number) | default('[]',true) %}```
inner mesa
#

because that's a string

lyric comet
#

Probably because you have the default set to '[]' and you are not testing if it is defined.

inner mesa
#

"unavailable" and "unknown" are perfectly acceptable strings

#

does that attribute exist when the sensor is unavailable?

mental violet
#

thisa does not work either :/

#
``` does this cover all possible errors that could happen to the sensor?
wary yew
#

I got into the world of templates today and I have a couple very basic questions.

  • I have a motion sensor in a mushroom card, and it's reporting the State "Clear" (this is by default, I did nothing). But when I call the state of the binary_sensor in a template, the State is "off" instead. Why? How can I use the nice name?
  • How can I call the last-change of a sensor in a template?
mental violet
#

to your first question, this is changed only in the front end. The sensor is 'off' or 'on'. In frontned it is interpreted as clear, etc.

wary yew
mental violet
#

I changed now the sensor to this:
https://dpaste.org/mhN6O
now the attributes dont disapear after a restart, but the data in all the attributes is lost.
I would even pay with paypal if someone could create or change this sensor so it works.
like 10 bucks or so? I am really sad and I dont know what else to do.
(I hope this is ok, to ask for a payment here, it is not my attention to discriminate the server rules)

mighty ledge
mighty ledge
#

keep in mind, it's a datetime object

#

my second reply was to chaos

mental violet
#

First of all thank you for the help

wary yew
marble jackal
#

It's rendered at the start of every minute

#

Or on a state change of the sensor

wary yew
#

the mushroom card does every second 😦 Is there no way to achieve the same behaviour?

mighty ledge
#

it does not, it just appears as if it is

#

the value doesn't change, the display changes based on it's distance from it

#

i.e. no calculation is occuring

#

when you're using a template, it's running a calculation, so it's throttled based on the calculation

#

relative_time will update on the minute

wary yew
#

I get that. I cannot simulate that display change right?

mighty ledge
#

nope, not without JS

wary yew
#

got it. Not the end of the world

inner mesa
#

many cards just start their own timer

lyric comet
#

The mushroom card probably has the end time and uses javascript on the browser to count down.

wary yew
#

yeah, I understand.

mental violet
mighty ledge
#

There's probably an error somewhere, sadly, its so overly complicated that it'll take a while for someone to debug

#

When I need persisting values, I use MQTT

mental violet
#

I am more than willing to reward you or someone else for the efforts via PayPal. Because I know how much time this is gonna take.

rare furnace
#

What is wrong with this statement?

{% if is_state('light.tv', 'on') %}
{{ "#%02x%02x%02x" % state_attr('light.tv','rgb_color') }}
{% else if is_state('light.living_room_lights', 'on') %}
amber
{% else %}
grey
{% endif %}

I added else if and now it doesn't work

inner mesa
#

Use elif rather than else if

rare furnace
#

Ah right

#

thought elif was python

lyric comet
# mental violet First of all thank you for the help

I suspect part of the problem is some of your triggers have empty to values which means they will be triggered on a reload and could be triggered before the value of the sensor is set. I don't have time to look further in your code, I am afraid, I do know that my template sensors with triggers attributes are restored so that would seem to be the most likely reason.

#

You do not check to see if any of the sensors you need are unavailable in or unknown, so you potentially have updates before read.

marble jackal
#

What Jane explains is likely to occur when one of the trigger entities is also a template sensor

mental violet
#

So you are saying that when my trigger sensors are initiated they maybe trigger my finance sensor.
Which is not setup at that moment, so the "or []" part comes in an "resets"/ overwrite my attributes.
Do you know a way how I can overcome this problem?
Maybe I can create an availabe_template in the trigger sensors, that they only are available when my finance sensor is initiated?

marble jackal
#

Is the last trigger another template sensor?

#

It might already help if you add not_from: unavailable

analog mulch
#

I have three devices (climate.ac_<room> with <room> some room names). I would like a template which would be true if any of the devices are in any of the list of states ['off', 'fan_only']

#

Something like states('climate.ac_kids') in ['off','fan_only'] for three devices

marble jackal
#

You can use is_state as a test in the select() filter

analog mulch
#

aha, is_state can take a list of states! thanks

quiet kite
#

value_template: "{{ value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first }}"
This return me:
{'type': 5, 'name': 'ltr578 Ambient Light Sensor Non-wakeup', 'vendor': 'Lite-On', 'version': 256, 'accuracy': 3, 'values': [38.36375], 'lastValuesTime': 1689072491531, 'lastAccuracyTime': 1689056526374}
How to get values[0] from this?

mighty ledge
#

wrap it in parenthesis and get the valeus: (...).values[0]

marble jackal
#

or create a variable if you also want extract more values

{% set data = value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first %}
{{ data.values[0] }}
quiet kite
#

with: "{{ (value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup')).values[0] }}" I have unknown 😦
without [0] i have empty

mighty ledge
#

you wrote:

value_template: "{{ value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first }}"
I said:
wrap it in parenthesis and get the valeus: (...).values[0]
then you decided to remove |list | first

quiet kite
#

no, i found issue, values is build-method

#

is possibel to execute quick rleoad from ha cli?

#
value_template: "{{ (value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first)['values'][0] }}" # good
# value_template: "{{ (value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first).values }}" # bad
mighty ledge
#

that access method is identical

#

['values'] and .values is the same

#

unless it's a dictionary item

#

then it's a function and .values won't work

fringe sail
#

Hey guys. I'm controlling a ceiling fan's speeds. I control it by turning on 3 switches in a particular group for each speed. Switch 1 and 2 on is low. Switch 2 and 3 on is medium and all 3 on is high. I need to set a trigger for 1 and 2 on and each of the groups described above to act as triggers in an automation. I was told that I'd probably need a template for this, but I don't know how that template would look. Can anyone give me and example of a template that would group multiple entities in a particular state, to act as a trigger?

neat prairie
#

So what states do you want to trigger?

fringe sail
#

I have everything working on the fan speeds. My problem is that I have icons in my front end that don't correctly reflect the state when the speed is set by turning on the switches independently. If I turn on a speed by turning on a group of the switches, the icon shows correctly, but if I turn on the switches independently, then the icon doesn't show the state. I hope I'm explaining this where it makes sense.

mighty ledge
#

what are the 3 entities?

fringe sail
#

If I could just make multiple switches together act as a trigger, I think that I could make it right.

neat prairie
#

to write the template, you have to be able to define what goes into making the final value. like is it the highest of the three? the lowest? the average? a sum?

fringe sail
#

fan speed 1, 2 and 3

mighty ledge
#

can you write the entity_id's out please

fringe sail
#

fan.fan_speed_1, fan.fan_speed_2 and fan.fan_speed_3

mighty ledge
#

such an odd way to do that

#

so what behavior do you want when you turn the fan on?

#

or do you just want a UI item to set high medium low, off

fringe sail
#

I want no matter how the switches get turned on or off, that whenever the correct set of switches is on or off, the icon will show the correct state.

mighty ledge
#

what icon

fringe sail
#

Let me get a picture of my setup

plain magnetBOT
#

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

fringe sail
#

Ok, will do

#

Here's an image to help me explain https://imgur.com/a/7FJJKhN

mighty ledge
#

that seems so over complicated

#

why do you have the switches at the bottom??

fringe sail
#

Everything works correctly, except when I turn the switches on independently. If I could set multiple switches as a single trigger, I'd have no problem. I just don'y know how to do that.

#

I just want to be able to see what the switches are doing independently. They aren't needed to make anything work.

mighty ledge
#

what's making these

#

are they separate buttons?

fringe sail
#

Some rare times the device in the fan housing don't turn on every switch as it should and I can see exactly what isn't on with the independent switches.

mighty ledge
#

that's not answering my question, what's making those buttons at the top

fringe sail
#

Each of those is an input boolean and I have an automation that turns on the correct set of switches for each speed.

mighty ledge
#

Ok, that's what I was looking for

#

instead of input booleans, make template switches

inner mesa
#

seems like you really want an input_select

mighty ledge
#

you could aslo do taht or template selects

#

either way, you need something that responds to the value of the 3 switches

#

If I were in your shoes, I'd make a template select. Remove all the automations and input_booleans

#

you'd have 1 template select for each room.

fringe sail
#

I'm sure that you're right, but I'm not that good at templates. That's why I went the way that I did.

#

Can you give an example of what you're saying?

mighty ledge
#

Yes, but are you willing to change your UI?

#

I'm tring to figure out what you want

#

if you want the same UI, then you need to make a bunch of template switches

#

if you don't care about the current UI that you have, then you can go another route

fringe sail
#

Can you show an example of a template select?

mighty ledge
#

it's a dropdown

#

it'll have a menu that pops open and has 4 options: off, low, medium, high

inner mesa
#

you can also keep your buttons and just have each button choose a differnet option

mighty ledge
#

but that won't feed back to his buttons, which is his problem

fringe sail
#

I guess that I need an example of a template switch

mighty ledge
#

Ok, so you want to go the template switch route

fringe sail
#

I guess...lol. Before I do that though, is there a way to make multiple switches together as a trigger?

mighty ledge
#

another question: If you turn on just fan switch 2, is the fan still at low speed or does it not have a speed?

mighty ledge
fringe sail
#

no 1 fan speed does anything. It must be at least 2 speeds to do anything

mighty ledge
#

so please, lets focus on the solution, not what you want the solution to be

mighty ledge
fringe sail
#

Correct

mighty ledge
#

ok, that makes this more complicated, but it can be worked through

#
switch:
- platform: template
  switches:
    fan_low:
      value_template: "{{ is_state('fan.fan_speed_1', 'on') }}"
      turn_on:
      - service: fan.turn_on
        entity_id: fan.fan_speed_1
      turn_off:
      - service: fan.turn_off
        entity_id: fan.fan_speed_1
#

that replaces your low input boolean and the automation that pairs with it

#

it will be a switch entity.

#

when you turn it on, it runs the turn_on actions

#

when you turn it off, it runs the turn_off actions

#

the value_template determines the state of that switch

#

so no automations are needed, it just knows

#

if fan.fan_speed_1 is on, that switch will be on

#

now, for medium...

#
- platform: template
  switches:
    fan_medium:
      value_template: "{{ is_state('fan.fan_speed_1', 'on') and is_state('fan.fan_speed_2', 'on') }}"
      turn_on:
      - service: fan.turn_on
        entity_id:
        - fan.fan_speed_1
        - fan.fan_speed_2
      turn_off:
      - service: fan.turn_off
        entity_id:
        - fan.fan_speed_1
        - fan.fan_speed_2
#

high...

#
- platform: template
  switches:
    fan_high:
      value_template: "{{ is_state('fan.fan_speed_1', 'on') and is_state('fan.fan_speed_2', 'on') and is_state('fan.fan_speed_3', 'on') }}"
      turn_on:
      - service: fan.turn_on
        entity_id:
        - fan.fan_speed_1
        - fan.fan_speed_2
        - fan.fan_speed_3
      turn_off:
      - service: fan.turn_off
        entity_id:
        - fan.fan_speed_1
        - fan.fan_speed_2
        - fan.fan_speed_3
#

if you need a delay between the fan.turn_on for each fan... use this instead for turn on/ turn off

#
turn_on:
- service: fan.turn_on
  entity_id: fan.fan_speed_1
- delay: "00:00:01"
- service: fan.turn_on
  entity_id: fan.fan_speed_2
inner mesa
#

so...weird

mighty ledge
#

it really is

fringe sail
#

Maybe I'm wrong, but it seems that low speed should be like this, because fan speed 1 and 2 need to be on for low speed. Is this correct?

switch:
- platform: template
  switches:
    fan_low:
      value_template: "{{ is_state('fan.fan_speed_1', 'on') }}"
      turn_on:
      - service: fan.turn_on
        entity_id: fan.fan_speed_1
        entity_id: fan.fan_speed_2
      turn_off:
      - service: fan.turn_off
        entity_id: fan.fan_speed_1
        entity_id: fan.fan_speed_2
mighty ledge
#

Sure, if that's what's needed for low

#

but, your'e listing it wrong

#
      - service: fan.turn_on
        entity_id:
        - fan.fan_speed_1
        - fan.fan_speed_2
fringe sail
#

Ok I've got it. I really appreciate this @mighty ledge !

mighty ledge
#

you also need to change the value_template

#
      value_template: "{{ is_state('fan.fan_speed_1', 'on') and is_state('fan.fan_speed_2', 'on') }}"
#

because the state of the switch will show as "on", when speed1 and speed2 are on

#

value_template derrives what the state of the switch will be, through a template

fringe sail
#

Yeah, I just saw that from your other examples. I would've never figured this out myself.

#

I'm gonna go try all of this out, much appreciation again.

mighty ledge
#

just keep in mind that you'll need to change things for each switch

fringe sail
#

Absolutely, will do

mighty ledge
#

also, when adding this to configuration.yaml, make sure you only have 1 switch section

#

e.g.

switch:
- platform: template
  switches:
    ....

- platform: template
  switches:
    ....

not

switch:
- platform: template
  switches:
    ....
switch:
- platform: template
  switches:
    ....
fringe sail
#

OK, so it goes in the switches.yaml and not the templates.yaml?

mighty ledge
#

Yes

inner mesa
#

or just put them all under switches:

fringe sail
#

Ok, good deal

frank harness
#

Could someone show me how i could regex this please?

{{ "%.2f" | format((states("sensor.daily_rolling_cost_pool_pump") | float(0) ) + (states("sensor.daily_rolling_cost_front_lights") | float ) + (states("sensor.daily_rolling_cost_porch_lights") | float) + (states("sensor.daily_rolling_cost_cinema_room_speakers") | float) + (states("sensor.daily_rolling_cost_cinema_room_lamp") | float) | round(5)) }}'

I have more sensors to add, and they all begin with "sensor.daily_rolling"

inner mesa
#

did you read the links?

#

please do

frank harness
#

sorry i am not sure which links? The ones in the pinned posts?

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

inner mesa
#

the second one, in particular

#

anyway, here:
{{ "%.2f" | format(states.sensor|selectattr('object_id', 'match', 'daily_rolling')|map(attribute='state')|map('float')|sum|round(5)) }}

frank harness
#

Will that add the value of the "state" up?

inner mesa
#

yes. that's this part: map(attribute='state')|map('float')|sum

frank harness
#

You are a HERO sir.

#

if i wanted to exclude one from it can i do that?

inner mesa
#

yes, with rejectattr()

frank harness
#

actually just checking. not sure i need to.

#

one second

#

Aamzing

#

it works

#

thank you so dam match!

#

Really appreciate that Rob.

#

hmmm

#

It worked in template developer tools

#

but in my yaml im getting

#

Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/configuration.yaml", line 152, column 7
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 156, column 69

#
total_rolling_cost:
      friendly_name: "Daily Rolling Cost Total"
      unique_id: "daily_rolling_cost_total"
      device_class: monetary
      unit_of_measurement: 'GBP'
      value_template: '{{ "%.2f" | format(states.sensor|selectattr('object_id', 'match', 'daily_rolling')|map(attribute='state')|map('float')|sum|round(5)) }}'
#

Think my quotes are wrong, so swapped them

"{{ '%.2f' | format(states.sensor|selectattr('object_id', 'match', 'daily_rolling')|map(attribute='state')|map('float')|sum|round(5)) }}"
inner mesa
#

yes, and you should fix your indentation. 2 spaces per level

frank harness
#

they are, that was just a bad copy and paste

#

here is a question for.....

#

lets say i name that sensor above "sensor.daily_rolling_total"

#

whats that going to do?

#

on the basis the regex is looking for that

mighty ledge
#

it's not going to work

#

use search if you want partial word searching

#

not match

frank harness
#

ill keep it simple and just not name it that

mighty ledge
#

well, it's only going to find 1 entity

#

so...

frank harness
#

well it didnt?

inner mesa
#

match just starts at the beginning

mighty ledge
#

ah, so it's not really match

inner mesa
#

that's "eq"

frank harness
inner mesa
#

"search" searches anywhere (substring)

mighty ledge
#

right, but it's not really regex's match function

inner mesa
#

search with "^xxxx" is probably the same as match

mighty ledge
frank harness
#

lol πŸ™‚

#

thanks gents!

#

you both helped finally get my energy dashboard V2 done

inner mesa
#
{{ "foobar" is match("foo") }}
{{ "foobar" is search("foo") }}
{{ "foobar" is match("bar") }}
{{ "foobar" is search("bar") }}
{{ "foobar" is search("^bar") }}
->
True
True
False
True
False
mighty ledge
#

yeah it just doesn't do what re.match() does

#

which returns a list of things that match your regex exactly

inner mesa
#

<time to go to the code>

mighty ledge
#

I didn't implement match, but I do reemmber talking with someone when they implemented regex_findall

#

which is close to match

frank harness
#

im really upset no one told me how great my energy dashboard looked πŸ˜›

mighty ledge
#

Lol, missed the link. It looks great

frank harness
#

lol thanks πŸ™‚

fringe sail
#

Does anyone see anything wrong with this? I've put this in my switches.yaml file, but I can't find any of these switches after saving the switches.yaml file.

- platform: template
  switches:
    dining_room_fan_low:
      value_template: "{{ is_state('fan.dining_room_fan_speed_1', 'on') and is_state('fan.dining_room_fan_speed_2', 'on') }}"
      turn_on:
      - service: fan.turn_on
        entity_id:
        - fan.dining_room_fan_speed_1
        - fan.dining_room_fan_speed_2
      turn_off:
      - service: fan.turn_off
        entity_id:
        - fan.dining_room_fan_speed_1
        - fan.dining_room_fan_speed_2
lyric comet
#

How/where have you included it in to your config file?

fringe sail
#

In my switches.yaml file inside my config folder.

lyric comet
#

The most likely cause is the indentation of the include or the level.

mighty ledge
#

make sure switches.yaml is included in configuration.yaml

#

other than that, the code looks good

fringe sail
#

They don't appear in the developer tool states page either

mighty ledge
#

did you restart after adding them and is switches.yaml included in configuration.yaml?

fringe sail
#

All of the other template sensors I've made appeared after I saved the yaml file, but not these switches.

#

Yeah, I restarted HA too

mighty ledge
#

can you post how you're including them in configuraiton.yaml?

fringe sail
#

yes, just a moment

mighty ledge
fringe sail
mighty ledge
dull tendon
#

hey guys i have an issue with the variable section of my Automation YAML that why i came to the template channel:
description:
designed to control the temperature of an air conditioning system in an intelligent manner. It takes into account various parameters such as the outside temperature, humidity, inside temperature, and desired temperature. The goal is to dynamically adjust the AC temperature to achieve and maintain the desired temperature while considering the current environmental conditions.

Code: https://dpaste.org/WBrVq (YAML) or https://dpaste.org/yACAr (Python Format, looks cleaner for comments)

issue: wrong temp output

mighty ledge
#

what's the right output

dull tendon
#

If the room temperature is typically hot due to the outside temperature where I live, I should set the AC to a lower degree than my desired temperature. This will help the AC reach my desired temperature faster. As it gradually gets closer to my desired temperature, I can adjust the AC's temperature to be increasingly closer to my desired temperature.

mighty ledge
#

right I get that, but I have no idea what it's outputting now and I have no idea what it should be outputting, and I have no idea what your inputs are

#

so.. how tf can anyone debug it without that info

dull tendon
#

right now its 34c outside and room is 29c when i got here my desired temp for the room 'inside' would be 25

mighty ledge
#

well, not based on your code

#

inside - outside would be -6

#

you then make it positive

dull tendon
#

i would normally set the temp to be 20 or 19 to get the room down to 25 faster but if i leave the temp at 19 the room can get too cold which is not what i want and also not energy efficient

mighty ledge
#

and then you say "if it's greater than or equal to 1, just set it to the desired"

#

so

#

so right now, you're just setting it to the desired temp

fringe sail
mighty ledge
#

so what you have should work now πŸ™‚

fringe sail
#

Exactly

dull tendon
#

i am worreid i might have over engineered this thing

mighty ledge
#

that's your current code path

#

so it's doing exactly what you asked

fringe sail
#

Can I make a unique ID for these switches in the switches.yaml? Otherwise I can't manage them from the UI.

mighty ledge
#

if the temperature is wrong, then the issue is just in adjusted_desired_temp

mighty ledge
fringe sail
dull tendon
#

so i had my presistant notification output the following:

outside_temp = 35.8
desired_temp = 23
adjusted_desired_temp = 23```
mighty ledge
#

why don't you just test this in the template editor

#

with 1 template

#

instead of these 839489283492384 broken apart templates

dull tendon
#

lmao

#

this is my first time using HA lol i just now knew there was a template editor

mighty ledge
#

well, if that's the case you should be able to pound this out pretty quick

#

with the template editor

dull tendon
#

so i set everything under one variable in the Template tab in developer tools?

mighty ledge
#

Yep

#

so...

#

outside_temp: "{{ state_attr('weather.forecast_home', 'temperature') | float }}"

#

becomes

#

{% set outside_temp = state_attr('weather.forecast_home', 'temperature') | float %}

#

you can even just use fake numbers for testing

#

each template

#

e.g.

{% set var1 = 5 %}
{% set var2 = 6 %}

Then the template you're going to use would be something like

{{ var1 + var2 }}
#

and when you put it into your automation, you'd use...

var1: "{{ states(...) }}"
var2: "{{ states(...) }}"
var3: "{{ var1 + var2 }}"
dull tendon
#

damn couldn't they just use the same syntax

mighty ledge
#

1 is yaml

#

the other is pure jinja

#

automations are yaml that allow jinja

#

regardless, your automation only needs 1 result so you can just do 1 huge template that outputs to ac_temp

#

there's no reason for you to separate it all

dull tendon
#

@mighty ledge thank you this chat has been very educational i'll go test things out and come back here to bother you again if needed

mighty ledge
#

πŸ‘

fringe sail
#

I'm not sure if this should be asked here, but I've got the 3 template switches working from earlier. I then set the 3 buttons in the front end to be the 3 template switches. When I turn on the low template switch, the low button turns on. When I turn on the medium template switch, the medium button turns on, but when I turn on the high template switch, all 3 of the buttons turn on. How can I stop this?

snow folio
#

Hello guys, I'm looking for the template to scan a specific unifi wifi network in order to check if they're guests or no, but can't find it

inner mesa
#

is that information available in an entity somewhere?

snow folio
#

I don't think so, I just got my unifi u6 lite for this purpose and installed the integration, although, the integration asks me which SSID I want to monitor the entities that appear are the individual devices

#

even if they're not in the network

inner mesa
#

they aren't magic, and they don't really do anything on their own

snow folio
inner mesa
#

doesn't that do what you want?

#

it's not "scanning", it's just finding all device_tracker entities that are home and have a specific essid in their attributes

snow folio
#

I missed the attributes.essid part, I think is working now

quiet kite
#

What i doint wrong: 'sensor' is undefined:

description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.fully_kiosk_device_info_sensor_info_ambient_light
condition: []
action:
  - service: number.set_value
    data:
      value: >-
        {{ states(sensor.fully_kiosk_device_info_sensor_info_ambient_light)|int +1 }}
    target:
      entity_id: number.lenovo_tab_p11_screen_brightness
mode: single
#

i want set number.lenovo_tab_p11_screen_brightness to sensor.fully_kiosk_device_info_sensor_info_ambient_light when sensor.fully_kiosk_device_info_sensor_info_ambient_light was changed

marsh cairn
#

Put quotes (') around your sensor entity

snow folio
marsh cairn
#

Sometimes integrations don't update the online status instantly

snow folio
#

just notices there's a bug on unifi but the strange thing is I even restarted HA and the counter still at 0

inner mesa
#

You should look at the attribute in the entities

#

Look at the actual data. The template is just reading it

snow folio
#

yes, the ssid appears on the device's attribute but the counter still at 0

inner mesa
#

Debug the template then

#

What it's doing is straightforward

#

There's only like 3 things it's looking for

snow folio
#

for some reason the template just reads my IOT network I have 3 devices on it and it works well but when I move to another ssid it reads 0

inner mesa
#

Debug

#

devtools -> Templates

#

There really isn't much to it

mighty ledge
#

Templates can do ANYthing

snow folio
fringe sail
#

@mighty ledge , those switches did work, however I had to fall back to my automations. Maybe I'm doing something wrong, but I set the 3 buttons in the front end to be the 3 template switches. When I turn on the low template switch, the low button turns on. When I turn on the medium template switch, the medium button turns on, but when I turn on the high template switch, all 3 of the buttons turn on. I couldn't figure out how to stop that. The automations are way too complicated, but now that they're set up, they work 99% for what I want.

heavy island
#

I have a WLED controller for an RGB+WW LED strip, and have been trying to get it to work properly with the Adaptive Lighting integration. Unfortunately the color temp of the strip I have is much warmer than whatever WLED or Adaptive Lighting is expecting, so it looks like garbage. I found a blueprint for using an RGBW light as a CT Light, which installs an automation to set the specified light based on color temp specified in an input_number.

I thought a template light might be the solution -- let Adaptive Lighting adjust that template light color, then feed the result of that into the input_number for that color correction automation. Does anyone know of an example doing something similar I could look at?

mighty ledge
#

Just add them to the turn_on / turn_off sequences

fringe sail
#

I figured that too, but I couldn't figure out how to do it...lol

mighty ledge
#

The turn on section is like an action section of an automation

fringe sail
#

I'll try that and let you know how it works out.

mighty ledge
#

Same with the turn off section

fringe sail
#

I thought that if I turned off one of the other switches, then it wouldn't be on high anymore. It seems that I need the buttons to be just a representation of the switch states and not the actual switches.

mighty ledge
#

That’s exactly what the value_template is

#

It does not cause the turn on / off actions

#

It just represents the state of the switch

#

The turn on / off actions are performed when you or a service call turns on or off the switch

#

That’s why high turns on when you turn in medium

#

Because all 3 switches are on, and all 3 being on means high is on

fringe sail
#

Since the buttons are the switches though, when high is turned on, it automatically turns on the other 2 buttons.

#

Yes that's right, but I don't see a way to stop that if the buttons are the switches themselves.

mighty ledge
inner mesa
#

I feel like this is similar to launching a nuclear weapon

fringe sail
#

Can the buttons be the value templates instead? would that make a difference?

mighty ledge
#

That’s what we are doing

#

It’s no different, it just has a turn off sequence

#

Which you do want

inner mesa
#

Whatever you do, do NOT press the red button

marsh cairn
mighty ledge
#

Anyways, the value template should check is_state(…, "off") for the 3rd switch in each case

#

Because as I said before (unlike what rob thinks) templates can do anything

torpid crag
#

Hi There, is this the correct place to ask for help for an imap_content template? Im trying a very simple thing with the imap integration, adding the following into the "Template to create custom event data" field in the integration... but geting errors:

#

template:

  • trigger:
    • platform: event
      event_type: "imap_content"
      id: "custom_event"
      sensor:
    • name: imap_content
      state: "{{ trigger.event.data['subject'] }}"
#

This the debug log:

#

2023-07-12 10:48:24.085 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'trigger' is undefined when rendering 'template:

  • trigger:
    • platform: event
      event_type: "imap_content"
      id: "custom_event"
      sensor:
    • name: imap_content
      state: "{{ trigger.event.data['subject'] }}"'
      2023-07-12 10:48:24.088 ERROR (MainThread) [homeassistant.components.imap.coordinator] Error rendering imap custom template (Template<template=(template:
  • trigger:
    • platform: event
      event_type: "imap_content"
      id: "custom_event"
      sensor:
    • name: imap_content
      state: "{{ trigger.event.data['subject'] }}") renders=1>) for msgid 6 failed with message: UndefinedError: 'trigger' is undefined
haughty breach
torpid crag
haughty breach
#

The IMAP Search field is for filtering things like Sender. My understanding of the template field is that it can be used to produce custom data inside the imap_event so it can be accessed by a content sensor... I think this is mainly for use pre-processing the body of emails, since there is a length limit to how much of the body will be passed in the event data.

torpid crag
#

OK got it. Thank you!

torpid crag
#

OK so getting there! Question: I have this line of text in an email "Quantity delivered -- 1 - TFTC". The email content both has a text and html version, so i only want to get the first text version. Im stuggling with initial understanding: {{ trigger.event.data["text"] | regex_findall_index("*Quantity delivered -- *([0-9]+) - TFTC") }} - can someone point me in the right direction?

#

(Ive got everything else working as expected FYI)

rain cove
#

Where can I find the correct yaml format for template sensors, when including a yaml file in configuration.yaml like sensor: !include sensors.yaml

#

the template documentation page isnt clear which format im supposed to be using with this include, and the forums seem to be out of date, at least with what google is pulling up

mighty ledge
#

The merge dir list one

#

FYI the documents are clear. If the field you want to include on says list, it’s merge dir list. If the field says mapping, you use merge dir named

rain cove
#

Not sure what you are referring to, I am using the default auto generated configuration.yaml and sensors.yaml

#

Hence !include

mighty ledge
#

You’re asking how to include the template section.. right?

rain cove
#

sensor section, but yes

mighty ledge
#

I’m sorry, I’m not understanding your question.

#

You already have the include for sensor, you just said it

rain cove
#

configuration.yaml:

sensor: !include sensors.yaml

sensors.yaml:

  - platform: template
    sensors:
      outside_temperature:
        name: "Outside Temperature"
        unique_id: "outside_temperature"
        unit_of_measurement: "{{ state_attr('weather.ecobee', 'temperature_unit')  }}"
        value_template: "{{ state_attr('weather.ecobee', 'temperature')  }}"
mighty ledge
#

Yes that’s all correct

rain cove
#

The format of sensors.yaml is wrong, as I get an error when restarting HA. I am trying to figure out what the correct format is, and I couldnt find the correct page for it

mighty ledge
#

That format is correct

#

You must have incorrect spacing somewhere in your file

#

But what you posted without showing relation to other sensors, is correct

#

So that means your spacing is not correct in relation to other sensors in the file

rain cove
#

Im getting an error related to name being an invalid value:

The system cannot restart because the configuration is not valid: Invalid config for [sensor.template]: [name] is an invalid option for [sensor.template]. Check: sensor.template->sensors->outside_temperature->name. (See ?, line ?).

#

Im pretty sure name is correct, but i also did friendly_name and it didnt like that either

mighty ledge
#

Legacy docs say friendly_name

#

That probably will go to the wrong sensor section, scroll to bottom

#

This link

rain cove
#

Hmm, another change I made in combination to friendly_name fixed it. Not sure why I need to use the legacy though

mighty ledge
#

that’s the route you decided to go

#

template: is the new method

#

Hence why your question was confusing

#

Legacy template sensors go in the sensor section

#

New template sensors go in the template section

rain cove
#

Oh, I had no idea

#

Ty for your help, and that info on legacy template sensors. I got it working with the legacy way, but ill play around with the new way to do things

haughty sphinx
#

I have a simple question ( i think!?) I need to add two attribute values together from 2 different sensors to get one single value. ( sensor.fubar1.attribute1 + sensor.fubar2.attribute2 = SomeFubarValue)
I cant seem to do this with the input helper GUI. So I guess i have to make a template for each sensor attribute and then try to sum them with the input helpers. Is this the correct way to do this... it seems a bit over complicated to me.

compact rune
#

You could probably just make a sensor that adds it together for you. Something like {{ state_attr('sensor.fubar1', 'attribute1') | float(0) + state_attr('sensor.fubar2', 'attribute2') | float(0) }} might do nicely

haughty sphinx
#

Of course! πŸ˜„ thx mian! ill try that

quiet kite
#
value_template: "{{ (value_json.sensorInfo | selectattr('name','eq','ltr578 Ambient Light Sensor Non-wakeup') | list | first)['values'][0] }}"

I have problem with this, sometimes this yaml key values don't exists, then I want to show last value. How can I do this?

hexed galleon
#

How would you get a count of the distinct areas for entities that match a specific state? Basically trying to get a count of occupied rooms, with each room having multiple potential occupancy sensors. Have this so far: {{ states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'occupancy') | map(attribute='entity_id') | select('is_state', 'on') | list | count }}

marble jackal
marble jackal
quiet kite
nova star
#

Hello
I am making an automation to enter an order and send it on telegram via the bot.
I can send the quantities of products but I can't find how to display the unit of measure defined when creating the entity on home assistant.

This is my code now (it is working):
`service: notify.panda
data:
title: Commande MarchΓ©

message: >-
{{ states('input_number.courgette') | int }} courgettes
{{ states('input_number.tomates') | int }} tomates
{{ states('input_number.persil_plat') | int }} persil`

How can I display the unit of measure of each entities ?

rocky crypt
#

Ok... I'm pulling my hair out over here!
My lights have a dimming function. And I'm using an if statement to see if brightness is a specific number. This works IF the light is on... If the light is off, attributes.brightness doesn't exist! So, the code errors and won't continue.
So then I got the brilliant idea to "test" if light is on FIRST before it checks brightness level... However, it still doesn't work because it still somehow hits the attributes.brightness even with the light off 😦

#
          {% if states.light.in_wall_paddle_dimmer_500s_5.state == "on" %}
            {% if states.light.in_wall_paddle_dimmer_500s_5.attributes.brightness == 51 %}
              {% set a = a + ['light.in_wall_paddle_dimmer_500s_5'] %}
            {% endif %}
          {% endif %}
#

How would I fix this?

#

Well, N/M. It is working as expected. πŸ™‚

#

Apparently, I'm using Variables wrong 😦 But I don't know how it's wrong... 😦

plain magnetBOT
#

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

marble jackal
marble jackal
#

{{ ['light.light_1', 'light.light_2'] | select('is_state_attr', 'brightness', 51) | list }}

#

Btw, if you would have used is_state_attr() or state_attr() instead of states.some.entity.attributes.brightness in the first place (as strongly adviced in the docs) you wouldn't have had these errors

nova star
mighty ledge
#

use set a = namespace(a=[]) and set a.a = a.a + [ ... ]

#

or do what thefes said

#

which doesn't need namespace

rocky crypt
#

@TheFes On this one yes. But I have another one that is going to do two different actions... This is why I need the variable.

mighty ledge
#

I think you miss understood his comment

rocky crypt
#

Can't adjust lists outside of namespace... I don't quite understand that statement... 😦

nova star
mighty ledge
#

See my example

rocky crypt
#

I guess I'm very confused now 😦 My whole set a and if statements appear to work in other automations. Just for the variable, section it's not working 😦 Maybe I'm not explainging myself correctly...

marble jackal
#

And that whole template can be replaced with that single line I posted

rocky crypt
#

Oh!

#

Ok... For the variable section though?

marble jackal
#

Yes

#

But you'll still get an error on the service call if it returns an empty list

rocky crypt
#

I'm OK with that because if the list is empty, it won't do anything anyways πŸ™‚

mighty ledge
#

it will turn off the automation

rocky crypt
#

Oh.

#

I'm not OK with that! ROFL

mighty ledge
#

put a condition

#

"{{ entity | count > 0 }}"

marble jackal
#

Btw these actions will be performed microseconds after each other, so these lights won't be on for long

rocky crypt
#

That makes sense!

#

Well, there is a trigger...

mighty ledge
#

I still find it odd that you're only looking at 51 brightness

marble jackal
#

And brightness: 255 is not 20%

rocky crypt
#

Oh. Yes.. I know.. Sorry.. Let me explain.. If the light is at 20%... before it turns them off, I want it to put them back to 100% then turn them off. This way if someone comes into the room and turns on the light, it'll be 100%

#

If I JUST turn them off, when someone comes back into the room to turn the light on, it'll still be at 20% πŸ™‚

mighty ledge
#

what happens if it's at 19%?

rocky crypt
#

Then it'll leave the light alone.

#

πŸ™‚ I have another script that ran that made the lights 20% πŸ™‚

mighty ledge
#

ok, seems odd

#

Seems like you're not using scene.create and scene.apply when you should be

rocky crypt
#

It's for the Roomba. Per manual, it states it works best with light... So, when the vacuum starrts, I want it to turn the lights on, but only at 20%. When it's done, I want it to turn the lights off that it turned on.

mighty ledge
#

yeah, scene.create and apply is what you really want to use

#

before the roomba runs, capture the scene, or turn the lights on and capture the scene. Then run the roomba with the lights at 20%, then when the roomba is done, apply the captured sceen and turn the lights off.

#

no need to even think about the actual percentages

rocky crypt
#

But if someone comes into a room where roomba is, I want them to be able to turn the light to 100%.. Then I don't want roomba to turn that light back off because someone is in there...

mighty ledge
#

ok, you can cancel events

#

all you need to know is if the vacuum is running and someone changes the light %

#

then you can cancel the scene.apply & turn off at the end

#

but what happens if they enter the room, turn on a light, then leave after turning off the light

#

you've got alot of problems you're going to run into regardless what route you go

#

Personally, I just run my roomba in the daytime when no one is home

rocky crypt
#

That's true. That can happen.... And that is something that I am willing to "live" with.

#

For now, I think I'll stick with the variable way. I don't know much about scenes. So, I'll have to look into that another time... I appreciate the idea and thought for sure!

mighty ledge
#

there's not much to know

#

you'd turn both lights on, use scene.create with the entities in question and a unique name. Then when you want to return to said state before turning off, you call scene.apply using that unique name

#

it stores all attributes of the entities when scene.create was called.

#

no templates needed.

rocky crypt
#

And do you specify what items to capture?

marble jackal
#

Yes, it's all in the docs

rocky crypt
#

Ok. I'll look into that. Because I'm still unable to get it to run even with the one liner variable... 😦 So, I have to be doing something wrong still...

mighty ledge
#

it's very simple

rocky crypt
#

I still wish I knew what I was missing though...

mighty ledge
#

(with scene.create)

rocky crypt
#

I'll look at scene.create. But, if someone could do me a favor an check out https://dpaste.org/uUEh6 What did I do wrong? light.turn_on is just reporting back as '{{ entity }}'

mighty ledge
#

use multiline notation or wrap your template in quotes

rocky crypt
#

Under variables?

mighty ledge
#

look at where you're using {{ entities }}

#

and look at where you're using the longer template

#

notice the differences in the YAML

rocky crypt
#

entity_id: has multiline notation... >- Correct?

mighty ledge
#

yes

rocky crypt
#

So, I'm confused. 😦

mighty ledge
#

why

rocky crypt
#

Oh sorry. Yes. Under variables. I have >- as well. I changed that and forgot to change it on dpaste.org. That's why I was confused πŸ™‚

mighty ledge
#

read this

rocky crypt
#

So like this?

mighty ledge
#

yes that would work

#

but that will error when the list is empty

rocky crypt
#

Right. Forgot the condition...

#

But it's not working. So, I still have something wrong...

#

If I put this line:

{{ ['light.in_wall_paddle_dimmer_500s', 'light.in_wall_paddle_dimmer_500s_5'] | select('is_state_atrr', 'brightness', 51) | list }}

In template (Settings/Develop Tools/Template), it errors and says "TemplateRuntimeError: No test named 'is_state_atrr'."

#

I would expect it to return my light.in_wall_paddle_dimmer_500s_5 (As this is the light at 51 brightness.

#

Am I wrong?

marsh cairn
#

Typo: attr not atrr

rocky crypt
#

THANKS! Yep! That was it πŸ™‚

#

Wow! All that because double R instead of double T πŸ™‚ HAHA It's now working as expect...

#

@petro Thanks for the scene template idea. This will come in handy as well! I may end up switching it to this, but it drives me crazy when I think something should work and it doesn't. That was the main reason for me wanting to figure out the variable way..

marble jackal
#

Whoops, sorry for that. That's what you get from writing code on mobile

rocky crypt
#

NO WORRIES! I appreciate the help! I do have another quick question. Is there a way to automatically do the select query on all device_class Lights? Without specifying each light ID?

analog mulch
#

Why doesn't this work?

now()-as_datetime(states('input_datetime.last_vacuum'))

The template editor complains can't subtract offset-naive and offset-aware datetimes I would like to do something like this to return a timedelta.

mighty ledge
#

you'll have to force it to be local or UTC

#

now() - states('input_datetime.last_vacuum') | as_datetime | as_local

#

I assumed you wanted local

analog mulch
#

aha. Thanks!

rocky crypt
#

N/M my question. I figured it out πŸ™‚

marble jackal
#

Oh, should have scrolled to the bottom

cerulean cipher
sonic ember
#

After a small break, I'm back at working on my energy pricing templates. I notice I'm just missing experience with these... Hoping someone here can help me in the right direction.

#

I have a list of figures, and I'd like to shuffle through them, so that I can compare the current (index 1) PLUS the 5th from then (index 6), to the next pair, etc.

#

Currently I have a template that simply sorts the list, and gets the lowest number:

#
state: >
      {% set hour_threshold = states('input_number.dishwasher_hours_ahead') | int(0) - 5 %}
      {% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
      {% set items = state_attr('sensor.energyprices','raw_today') + state_attr('sensor.energyprices','raw_tomorrow') %}
      {% set lowest = items | selectattr('start', '>', now()) | selectattr('start', '<=', time_threshold) | sort(attribute='value') | first %}
      {% set lowest_price = lowest.value + states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
      {% set cheapest_time = lowest.start %}
      {{ cheapest_time }}
marble jackal
sonic ember
#

THat looks like it indeed... BUT, one small thing (let's see if that works)... I am only interested in hour 1 and hour 1+4. In my case it's for the dishwasher. And hours 2,3 and 4 use negligble energy, but 1 and 5 use a lot.

#

Let me read through your docs and see how I can use it. Thanks for making it either way!

#

Advanced data selection settings - πŸ™‡β€β™‚οΈ awesome!

#

πŸ˜• looks like enabling experimental mode for HACS crashed my server... Damn

mighty ledge
#

you can just install it manually

#

i.e. drag and drop

sonic ember
#

Yeah, that was my plan b. Trying to see if I can still get into HAOS, but seems I can't get in through terminal, hard reset needed... 😩

mighty ledge
#

what error are you getting?

sonic ember
#

No error, system just crashed. but it's back up

sonic ember
marble jackal
#

Let me check

#

But you should be able to do only hour 1 and 4, you can assign a weight of 0 to hours 2 and 3

sonic ember
#

I looked at my energy readings again, Seems this is what I need:
weight=[2,1,3,0,0]

#

That means 3rd hour weighs the most, first hour second most, and 2nd hour the 3rd most, with the last 2 being ignored, right?

marble jackal
#

Yes

#

Basically you could do only 3 hours then

sonic ember
#

And does it actually WEIGHT the prices? So for example if one hour usually uses twice as much power, should I actually make the number twice as high? Or is it simply a ranking

marble jackal
#

Yes

mighty ledge
#

3,2,4,1,1

marble jackal
#

It does

#

You can use the template sensor to have them calculated based on an energy sensor

#

You can even do shorter periods, so readings per 15 minutes

sonic ember
#

Yeah I didn't realise it did more than ranking so I thought I can just check my graph πŸ˜„

marble jackal
#

This is an example of the output of the sensor for my washing machine

  wasmachine_turbowash_60_1400:
    data:
      - 27
      - 45
      - 2
      - 2
      - 1
      - 1
      - 2
    no_weight_points: 4
    complete: true
sonic ember
#

Oops for the @

marble jackal
#

It ran today without issues for me

sonic ember
#

For the "example" lines it's asking for a string

#

Line 20: example: 120 Incorrect type. Expected "string".

marble jackal
#

Hmm, I noticed that as well now

#

I should correct that though to something more appropriate

#

120 is not much of a description

sonic ember
#

Funny.
Ok, so I assume this will only work once my dishwasher has run again now that I've set it all up right?

#

Or can it look back historically?

#

So if I understood correctly... I have now installed the script, and created the sensor (which exists empty, which I guess means it works). I just keep it as it is, and I read out the values once my machine has done a wash?

marble jackal
#

If you've set an automation to start and stop the script it should work

sonic ember
#

Ah so it needs to be turned on right before the dishwasher runs, and then turned off right afterwards?

#

And turning it off is of course just changing the service call to turn_off

marble jackal
#

No it's supposed to turn off automatically based on a state change of an entity

#

Eg a binary sensor based on a power sensor checking if the device is active

#

Or a sensor provided by the device itself

sonic ember
#

Ah, that's what the off part is for. I haven't been able to find a sensor on my dishwasher that does that, and the power is measured by a smart socket

marble jackal
#

My washing machine is a smart one, so I use the sensor provided by it.
But for my dishwasher I have a template binary sensor which turns on when it's using power, and turns off when it stops doing that

sonic ember
#

Cool!

marble jackal
sonic ember
#

And I actually think I did find a sensor that will work. Thanks!

#

Let's see what happens next time I run it.

#

Looking forward to trying this script.

marble jackal
#

Okay, let me know if it doesn't work, I don't know if anyone besides me actually uses it πŸ˜…

#

And to be honest, I don't even have dynamic rates

sonic ember
#

Haha well I've been playing with this stuff for a while, learnt a lot. But also good to know when using someone else's stuff is a better idea and use my energy elsewher.e

#

But I'll let you know

sonic ember
marble jackal
#

Haha, I still have fixed rates from 2 years ago, they can't be beaten by dynamic rates yet

#

Looking for a full year average of course, summer rates are a lot cheaper then what I pay

crimson lichen
#

Hi,
I have 8 motion sensor.
Now, i want to show list of sensor if state is unknown.
How to use template
Thanks

inner mesa
#

simple

#

{{ states.sensor|selectattr('state', 'eq, 'unknown')|map(attribute='entity_id')|list }}

#

did you try something?

crimson lichen
inner mesa
#

ok

uneven plinth
#

Hi, does anyone have experience of RGBW zigbee light bulbs being connected using a zigbee light switch, does it work?

haughty breach
hexed galleon
#

Anyone know if there's any way to get mdi icons inline with conditional template text?

hexed galleon
#

E.g. {{"mdi:lock" if is_state('lock.frontdoor','locked')}}

inner mesa
#

Not embedded in the text like an emoji, if that's what you mean

#

You can use actual emojis

hexed galleon
#

That's a bummer. Emojis aren't nearly as flexible/clean as MDI.

#

Seems like it's possible in the markdown card. Wonder if I could do some fiddling with mod-card to get it...

inner mesa
#

Oh, nice. I keep forgetting that you can insertt HTML

floral shuttle
#

working on details, wondering if I should use: - > {{trigger.entity != 'device_tracker.synology_diskstation' and now() > today_at('23:00')}} as a template condition, - > {{ not trigger.entity == 'device_tracker.synology_diskstation' and now() > today_at('23:00')}} is there an order of operations issue here?

#

goal: this needs to be false when the trigger is that device, and its after 23 (which is the scheduled turn_off time, so I dont need a notification ...)

marble jackal
#

If it should be false after 23:00, you should use <

#

In both cases

#

The not only applies to the part before and, unless you use parenthesis

marble jackal
#
{{ not false and true }} # True
{{ not (false and false) }} # True
{{ not (false and true) }} # True
{{ not false and not false }} # True
floral shuttle
#

thx, that was what I was looking for, I'll use

#
 {{not (trigger.entity == 'device_tracker.synology_diskstation' and
               now() > today_at('23:00')) }}``` which seems the most succinct translation of that sentence above
mighty ledge
#

statements always work left to right with and

#

not (x == y) is identical to x != y

#

as both apply the __equals__ method on the object under the hood.

marble jackal
#

In that case he needs < instead of >

mighty ledge
#

ah, i see the () was around the whole thing

#

yes

floral shuttle
#

thx!

floral shuttle
#

found another possible change. in the nex_alarm_timestamp sensor (remember Petro?) we use {% set days = timestamp|timestamp_custom('%d')|int - (now()+timedelta(days=1)).day +1 %} and this seems to be identical with the tiny bit clearer: {% set days = (timestamp|as_datetime()).day - (now()+timedelta(days=1)).day +1 %}. I like the fact they both use the .day . Would you agree on that?

mighty ledge
#

@floral shuttle I'd just do:

{% set days = (timestamp | as_datetime - now()).days + 2 %}
#

not sure why you're doing all the +1 day stuff

floral shuttle
#
          {% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %}
          {% if timestamp %}
            {% set days = timestamp|timestamp_custom('%d')|int
                 - (now()+timedelta(days=1)).day +1 %}
            {% set day_dict = {0:'Today,',1:'Tomorrow,',2:'The day after tomorrow,'} %}
            {% set date = timestamp|timestamp_custom(' %A, %-d %B') %}
            {% if days in day_dict %} {{day_dict[days] + date}}
            {% else %}{{'Next' + date}}
            {% endif %}
          {% else %} Not set
          {% endif %}```
mighty ledge
#

easy time does that