#templates-archived

1 messages · Page 61 of 1

neon lodge
#

thank you. i will try to figure it out 🙂

leaden hatch
#

calendar get_events migration and understanding what i'm doing

analog leaf
#

Can someone point me to where I can find all available functions in templates and what each does in hass?

marble jackal
#

The are links in je topic description

analog leaf
#

Oh, I hoped there where more organised and cleaner docs on that somewhere. But I guess those will do too.

onyx quest
#

I'm setting up a state-switch card that uses a template. I have confirmed that the media player's source is currently HEOS 3 - Aux In, but it's returning Other. What am I missing? {% set source = state_attr('media_player.kitchen.heos', 'source') %} {% if source == 'HEOS3 - Aux In' or source == 'Kitchen Aux In' %} Aux {% else %} Other {% endif %}

inner mesa
#

this is not a valid entity_id: media_player.kitchen.heos

#

The HA logs probably mentioned that

onyx quest
#

Yeah stupid typo on my part

plain magnetBOT
#

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

wanton girder
#

Can someone show how to exclude every but the last 5 symbols - eg 11:11

storm abyss
#

Hi all... I'm using decluttering card. I want to pass either a temperature sensor or a message to a card. How do I check in the template whether the passed variable has a value?

#

Something like this (but this doesn't work)

{% if [[temperature_sensor]] != null %}
  Temperature
{% else %}
  Message
{% endif %}
haughty breach
wanton girder
#

I'm using scrape an get a text and timestamp- I only want the timestamp

#

Think I need something along these lines

wanton girder
#

Anyone ?

lucid thicket
#

Why isn’t didgeridrew’s suggestion working for you?

#

You can enter
{{ value[-5:] }} in the 'Value Template' section in the sensor in the UI

lucid thicket
thorny cargo
#

Hello, how would a template light look like that is a pure dummy, does nothing but supports everything. It will be used in automations.

crimson wadi
#

How would I go about creating a sensor that allows me to switch between N other sensors? For instance, I have 4 temperature sensors from ESPHome devices and I want to be able to choose one of those to "be" this sensor (so I can use it as the sensor target for the ESPHome Thermostat)

mighty ledge
#

You’ll get every domain, as a fake entity

thorny cargo
#

But i need several lights, not just one.

#

Is that possible with the demo integration?

median citrus
#

can someone give me a hint on how i need to write a template to get from
"{'weather.mycity': {'forecast': [{'datetime': '2023-12-10T00:00:00Z'}]}}
to
"{'forecast': [{'datetime': '2023-12-10T00:00:00Z'}]}"

marble jackal
#

I guess you are referring to the service response change for weather forecasts?

median citrus
#

yep

#

drives me crazy and broke a few things for me

marble jackal
#

Instead of response.forecast it's now response['weather.your_weather'].forecast

median citrus
#

ok but how do i strip the ['weather.your_weather']

#

i have some other things that rely on the prevoiuse format

inner mesa
#

Depends on what those other things are

marble jackal
#

We can help you better if you share your code

median citrus
#

originally i was using the forecast entity, when that went away i created a template sensor which was updated hourly, and used that in turn to again create the string

#

my assumption was that it would be easiest to manipulate the template sensor using forecastS in a way that is has the same format as the previous version which was using forecast (singular)

rigid valley
#

Hi folks, was hoping some one could help me with this. I want a template binary sensor that is on if numeric value (of another sensor) is below x and off if above y. notice that is 2 seperate numerical values it needs to evaluate against. If it is between those 2 values it should keep its existing state. Any help would be greatly appreciated.

dim lodge
#

Hi there. I'm running HA Container on Podman, and today I updated from 2023.8.x all the way to 2023.12.1. It looks like there was a behavior change (or I'm just not remembering right); the built-in YAML editor has started expanding shorthand template conditions to full on condition: template / value_template clauses. This just makes my stuff harder to read. But I like using the built-in editor. Is there a way I can make it stop doing that?

lofty mason
dim lodge
#

What's the rationale for this change? It's just making all my scripts more unwieldy.

lofty mason
#

There were bugs in how the visual editor processed the shorthand templates, it was difficult to handle them, so it is converted to a standardized format.

dim lodge
#

Hmm. That's interesting. At least it seems to only do the conversion when I load up a script in the visual editor. If I change them back to shorthands, it won't re-expand them when I hit save.

lofty mason
#

yes the expansion would occur as part of loading in visual mode.

dim lodge
#

Is it possible to have the default view for scripts be the YAML view? Would that sidestep this behavior?

lofty mason
#

No it's not possible, but I suppose it would work if that was possible.

dim lodge
#

That's a bummer. Okay, thank you.

marble jackal
#

Do you only use the forecast for this sensor? Because you can als create this sensor with the response without the need to store it in an attribute

median citrus
#

so basically. the template sensor was featuring the forecast for the next days and the other template sensor was creating the string wich I was using vor visualization on the epaper display

marble jackal
#

Yeah, but you can do that in one sensor, without the need to store the entire forecast

marble jackal
median citrus
#

I know i just redacted the actual city 🙂

marble jackal
#

Okay

#

You just need to change the last line to
forecast: "{{ MYCITY_forecast_waveshare['weather.MYCITY'].forecast }}"

median citrus
#

OH GREAT, sorry i did't get ist where to change in the first place!

#

that helped, thanks a LOT!

marble jackal
median citrus
#

thanks!

marble jackal
median citrus
#

oh thats nice, helps to clean up my configuration.yaml !

#

much apprechiated!

storm abyss
#

what's the easiest way to check if a calendar event happened yesterday in a templated sensor?

marble jackal
#

You can only access that by using a service call:

service: calendar.get_events
data:
  start_date_time: "{{ today_at() - timedelta(days=1) }}"
  duration:
    hours: 24
    minutes: 0
    seconds: 0
target:
  entity_id: calendar.your calendar
response_variable: yesterday
#

if you use that in a trigger based template sensor, you access it in your template

distant plover
#

How can I make a condition that checks for an entity not existing? 🙂

marble jackal
#

{{ states.sensor.foo is none }}

wise sluice
#

having trouble with a template in a service call. in dev tools this works fine:
service: climate.set_temperature data: temperature: "{{ state_attr('climate.aircon_test' , 'temperature')|float | round(0) + 1 }}" target: entity_id: climate.aircon_test

but when i call climate.set_temperature from a chip card tap action it says expected float for dictionary value @ data temperature

#

service call is written as
tap_action: action: call-service service: climate.set_temperature data: temperature: "{{ state_attr('climate.aircon_test' , 'temperature')|float | round(0) + 1 }}" target: entity_id: climate.aircon_test

inner mesa
#

You can't use templates in calls like that. Make a script that does that and call the script instead

wise sluice
#

got it thanks. didn't realize we couldnt template in a front end call. thought my template was problematic

floral shuttle
#

how do we guard a value to be in the index of a list? eg {% set bft = 16 %} {% set colors = ['lightblue','paleturquoise','aquamarine','greenyellow','lime', 'mediumspringgreen','yellowgreen','navy','gold','orange', 'tomato','orangered','maroon'] %} {{colors[bft] }};

#

using that with an actual entity ofc, with possible values 0-12. so the list is length 13.

#

I did try this {{colors[bft] if bft <= colors|length else 'grey'}} but still get

list object has no element 13

#

which is correct, but it doesnt move to the else on 13, if I go beynd that the else does kick in.

#

aarrgh.. typo.. <= {{colors[bft] if bft < colors|length else 'grey'}} works ok.. never mind me, sorry

mighty ledge
#

Ya, when checking indexes, < is correct

marble jackal
#

is there a function/filter for median?

#

or do I need to do something like:

{% set list = [2.3, 2.5, 2.1] %}
{{ (list | sort)[(list | count / 2) | round(0, 'floor') | int] }}
thorny cargo
#

I´d still be looking for a template light, that is just a dummy light and does nothing, so I can put automations between it and my physical light.

marble jackal
#

can't you just use an input boolean?

mighty ledge
#

which is why I suggest using the demo platform.

#

Not to mention, it will be a very hard and large template entity

marble jackal
#

okay, I'll settle for this for median then

{% set list = [2.3, 2.5, 2.1, 2.4] %}
{% if list | count is odd %}
  {{ (list | sort)[(list | count / 2) | round(0, 'floor') | int] }}
{% else %}
  {% set mid = (list | count / 2) | int %}
  {{ (list | sort)[mid-1:mid+1] | average | round(2) }}
{% endif %}
mighty ledge
#

Just make a macro

#

I don't see a median filter

#

should be easy enough tho

#

should be a filter & func

marble jackal
#

I think it's better to use median for my combined template weather instead of the average

#

so that's why I was looking for it

mighty ledge
#

Ya, sure

#

we shouold have mean, median, and mode

#

we have mean

marble jackal
#

But I wanted to share it on the forums as a package, so I don't want to make it more complicated with an additional custom template.

thorny cargo
mighty ledge
#

Because the function needs to work in order for it to have the function

thorny cargo
#

I tried the demo platfrom but couldnt find out how to control the number of lights.

marble jackal
#

what do you want it to support? only on and off, or also brightness, color_temp, color etc?

mighty ledge
#

i.e. if you want to have brightness, you need an input_boolean that represents your brightness

#

if you want effect list, you need an input_select that reflects your effects

thorny cargo
#

Thank you. That´s too much work then for my dozens of lights i need.

mighty ledge
#

if you want color, you need 3 input numbers that reflect RGB

#

if you want white color, you need an input number that reflects your white value

thorny cargo
#

Yeah, got it.

mighty ledge
#

hopefully now, you can see why no one wants to help 😉

marble jackal
#

and all of that for each light (if you want to be able to set them different from each other)

#

only on/off is simple 🙂

thorny cargo
#

Do you know how I can config the demo platform? Doesnt seem to be possible, is it?

mighty ledge
#

and even then, you need an input_boolean for the on/off

marble jackal
#

yes sure 🙂

mighty ledge
#

you can't, w/ the demo integration you just get a few demo lights & entities

thorny cargo
#

Can the template light not store information on its own?

mighty ledge
#

No

thorny cargo
#

light when i define turn_on:
self.turn_on or something like that

mighty ledge
#

no

thorny cargo
#

There must be a solution to my flashing problem.

mighty ledge
#

well, you never asked that question, you asked about template lights

#

that's why we have a macro

plain magnetBOT
#

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

thorny cargo
#

What´s a macro?

mighty ledge
#

what I used above

#

the xy problem

#

it's so common that we have a bot message for it

#

it's when users don't explain the real problem, they ask some random ass question that has nothign to do with the real issue, when they could have asked about the real issue instead

thorny cargo
#

I did ask the real question in general yesterday.

mighty ledge
#

🤷‍♂️

#

post a link to it

thorny cargo
marble jackal
#

you can use template lights for that, but use the values from the actual light

mighty ledge
#

Template lights wont' solve that problem

#

if you're saying alexa turn on lights to 1% and the lights flash 100% then 1%, that will always happen

marble jackal
#

yes

mighty ledge
#

as the hardware is doing that.

marble jackal
#

that depends on the hardware

#

🐌

mighty ledge
#

let me guess TUYA devices?

thorny cargo
#

we had that discussion yesterday

#

It´s not about the hardware

#

It´s hue devices.

#

Let me explain further.

mighty ledge
#

I have hue devices and they don't do that, so...

thorny cargo
#

I have an automation that turns on a light to the desired brightness (and other things) whenever it is turned on. So the light will always receive two light.turn_on. First without payload, second with payload.

mighty ledge
#

why...

#

change that automation

thorny cargo
#

After a certain time I want my lights to turn on at 1% brightness for example.

#

So if I say to Alexa. Turn on light.

mighty ledge
#

you can template the entire data field to include or not include brightness in the first light.turn_on

thorny cargo
#

It should turn on at 1%.

mighty ledge
#

you don't need 2 light.turn ons

thorny cargo
#

How do I avoid the first one, when it is done via Alexa or UI button?

mighty ledge
#

alexa only sends 1 light.turn_on call

#

your automation is doing 2

#

unless you set up some janky solution in alexa

thorny cargo
#

Yes, but I would need to modify that light.turn_on call from alexa which i cant?

#

So my automation is waiting for the light.turn_on without payload and then sends another one with the right brightness.

mighty ledge
#

.... why

thorny cargo
#

What would you suggest to solve it?

#

Can I modify the light.turn_on from alexa or UI?

#

I mean, if it is a physical button, it´s easy. I directly call my automation instead of turning on the light. So only one light.turn_on with brightness is issued.

mighty ledge
#

Please explain why you're intercepting a light.turn_on service

thorny cargo
#

To turn on the light to a brightness when no brightness was specificied.

mighty ledge
#

but why, please explain why you are doing this

marsh cairn
#

Specify a brightness

thorny cargo
#

For example to turn it on at 1% brightness when the user just turned it on.

mighty ledge
#

"I'm doing this because I want the birghtness at 4am to be xyz"

thorny cargo
#

Different brightnesses at different times.

#

Amongst other things.

#

And when the prior brightness was larger than the new one, the light will flash.

mighty ledge
#

That would be a template light that you expose to alexa

#

if you want light settings per time of day

thorny cargo
#

There we go with template lights again for every light.

mighty ledge
#

keep in mind, that will still not work for physical button clicks

marble jackal
#

but not a dummy light, you need to base it on the actual light

mighty ledge
#

there'sn o way to intercept that

thorny cargo
#

Yeah, then my template light idea was not too off.

marble jackal
#

unless you have smart buttons (like a shelly in detached mode). You can then use the button press to toggle the template light as well

thorny cargo
#

I only have smart buttons. I dont use light switches that cut electricity anymore.

#

And for buttons there is no problem already.

#

But instead of programming template lights for every physical light, i´d rather write my own addon or integraton that automatically creates template lights for the real one and links them already.

marble jackal
#

you can create one, and use anchors for the others

thorny cargo
#

Anchors?

marble jackal
#

those are my template lights based on actual lights

#

behind smart buttons

thorny cargo
#

"{{ this.entity_id }}" since when is this possible?

marble jackal
#

dunno, a year maybe?

thorny cargo
#

Still seems like a lot of work.

#

How do others solve my problem?

marsh cairn
#

I suppose they try to set the brightness with a single light.turn_on call in an automation, write template lights or live with it

thorny cargo
#

But there is absolutely no way to stop/manipulate the first light.turn_on call?

fickle sand
#

I use adaptive lighting to intercept those calls and let that decide the brightness needed

marsh cairn
#

Or the Flux integration

thorny cargo
#

My scheme is the following right now. I have 3 automations for every light. One auto on which handles stuff that turns on a light automatically light motion, doors, etc. This one calls the on automation which turns on a light to the desired settings like brightness, etc. Then i have an auto off automation which turns off a light based on motion, time, etc. That´s how it´s done?

#

Ok, I have some questions about adaptive lightning and flux:

  • Can they set the brightness and temperature of lights to desired values at certain times?
  • Can they put lights which are already on to the desired values with custom transition time like 10 seconds?
  • When lights should not be changed under certain circumstance (e.g. they are currently red to notify me of something), can I specify they shouln´t be modified in those circumstances?
  • How do those integrations intercept the turn_on call?
#

I have very precise requirements for different lights to what values they should be set at different times.

mighty ledge
#

None of what you described requires intercepting the service call

#

the only time you'd need to intercept the service call is from a physical switch

#

all the other times, you program it to handle the light

thorny cargo
#

What about Alexa and UI turning the light on at 8:05 pm when the brightness from 8 pm onwards should be at 1%?

mighty ledge
#

you can make a script that gets a brightness from a look up table. Make the script accept any light entity. Have all your automations call that script

mighty ledge
#

HA is for automations

#

alexa is for voice control

thorny cargo
#

I mean voice control via Alexa.

mighty ledge
#

that's the only circumstance that you'd need a template light

#

literally

#

all the other ones, you program into your automations

thorny cargo
#

And buttons in the HA UI?

mighty ledge
#

automation

thorny cargo
#

But how? The buttons directly issuse the turn_on command

mighty ledge
#

no, you can make a script and have the button call the script

#

that's what tap_action is for

thorny cargo
#

So I wouldnt have my real lights in the UI anymore but instead buttons that start my automation?

mighty ledge
#

no... you change the tap action

#

from toggle, to call-service

#

and instead call a script that turns on or off the light w/ the desired intensity

#

there's about 800 ways to do this without intercepting the turn_on action

thorny cargo
#

Where/how can I do that?

mighty ledge
#

have you ever built a script?

marsh cairn
#

See above

fickle sand
#

No, you have a script.

  • in the UI you assign that script to the tap_action
  • with outside control you will control a template light in alexa that in turn triggers an automation in HA with the same script to control the real lights
thorny cargo
#

I have built scripts before, but I still dont get how i would link the buttons in UI for my lights? What is the difference between a script and an automation that just has actions?

mighty ledge
#

the action section of an automation is just a script

#

please take 5 minutes to read about tap_action

thorny cargo
#

So i can always use automations instead of scripts?

mighty ledge
#

there's nothing to understand if you read about tap_action

thorny cargo
mighty ledge
#

I feellike you're overloading your brain

#

because now you're completely mixing things up

#

we stated multiple times that you don't need the helpers w/ the template light for what you want to do, after you explained what you wanted to do

thorny cargo
#

Oh I think I get it.

#

I have a template light which always controls the real light directly except for a turn on command without payload?

mighty ledge
#

right

thorny cargo
#

And in the UI and Alexa I put my template lights instead of my real ones?

mighty ledge
#

sure if that's what you want

thorny cargo
#

Then i dont even need tap actions do I?

mighty ledge
#

nope

thorny cargo
#

Nice

#

and for not having to do it for every light I can use anchors?

#

I dont even need to check if the payload is empty. I could just always call my on automation for the real light when the turn_on for the template light is issued.

mighty ledge
#

you can use anchors to cut down the yaml, yes

thorny cargo
#

Where can I find the doc for those anchors?

mighty ledge
#

yaml anchors are documented all across the internet

#

theya re not an HA thing

#

they are a yaml thing

thorny cargo
#

ok

#

thx

#

Still a lot of work for a little flash

#

Is there a way to determine whether it was alexa who issued the turn_on?

mighty ledge
#

If you give alexa a unique user, you can use the context object to figure out if it was her or not.

#

otherwise, no

thorny cargo
#

perfect thx

#

is it also possible to determine which alexa user used it?

mighty ledge
#

probably not

marble jackal
#

cleaning up my log, I have this warning on startup.
Error in 'choose[0]' evaluation: In 'template' condition: TypeError: argument of type 'NoneType' is not iterable

Most of my choose templates are like trigger.id == 'foo' which would cause this right? This would be something like 'bla' in variable

mighty ledge
#

yeah blah in variable

#

or a generator

#

| selectattr etc

marble jackal
#

and the error points to the first item in the choose action

#

I can't find it 🙂

mighty ledge
#

what about a template entity?

marble jackal
#

it needs to be a trigger based template entity with an action section then, as otherwise it can't use choose

#

but I searched on choose in VSCode in my whole config

#

I'll try again..

#

regarding the median function/filter.. I'm looking in core/homeassistant/helpers/template.py
would it be as simple as:

def median(value):
    """Take the median value"""
    return statistics.median(value)

statistics is already imported.
Oh, and add
self.filters["median"] = median

#

oh and self.globals["median"] = median

mighty ledge
#

Yes

#

well, you'd need to annotate it

#

and build tests

marble jackal
#

yes, I already understood the tests are the tricky part in HA PR's 😛

fickle sand
#

Jup that was the easy part haha, tests can be awful 😛

thorny cargo
#

Why does this:
"{{states.light.flur.state}}" work, but this:
"{{states.light.flur.brightness}}" doesnt?

mighty ledge
#

because brightness is an attribute

#

states.light.flur.attributes.brightness

#

or use the states method

#

state_attr('light.flur', 'brightness')

thorny cargo
#

but no the brightness

mighty ledge
#

typo

thorny cargo
#

whats preferable? state_attr or states?

mighty ledge
#

states gets the state

#

state_attr gets state attributes

thorny cargo
#

states.light.flur.attributes.brightness
and
state_attr('light.flur', 'brightness')
is the same, isnt it?

mighty ledge
#

one uses the state object, one accesses the attribute from the state object safely

thorny cargo
#

so which should i use?

mighty ledge
#

always use the states method or state_attr method

#

avoid state objects unless you know how to code

thorny cargo
#

states.light.flur.attributes.brightness is preferable then?

inner mesa
#

No

#

always use the states method or state_attr method

#

This is covered in the docs

marsh cairn
#
{{ state_attr('light.example', 'attribute') }} for an attribute```
marble jackal
#

whoops, I meant

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

thorny cargo
marble jackal
#

because states('your.entity') will never error

thorny cargo
#

Ah ok

#

Thank you

marble jackal
#

and states.your.entity.state can

#

if your entity does not exist

thorny cargo
#

This looks more like what i´m used from programming tho.

#

*used to

#

Since it avoids using strings.

#

Do i have to restart HA for every template light change?

plain magnetBOT
#

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

mighty ledge
#

if you just added the light for the first time, you have to restart

#

if you make changes to an existing light template, you can reload template entities

thorny cargo
#

Why is that?

mighty ledge
#

you need effect_template most likely

#

you have a template for the list, a action for the effect, but you don't have what the current effect is

thorny cargo
#

Nice, works like a charm

#

Have I got everything then in my template?

#

The bar for my color temperature doesnt work. It sets the temperature but no controller is shown

#

Why does my dummy not get the temperature of my real light?

#

temperature_template: "{{state_attr('light.flur', 'color_temp')}}"

#

Should be fine, shouldnt it?

mighty ledge
#

Yep

thorny cargo
#

The controller bar for temperature of my dummy is still missing even though i addes min and max mireds to my template light.

#

Seems like the dummy cant get the temperatue of my real light.

marsh cairn
#

You are just "pulling" the temperature as current state. You likely haven't the set_temperature service call.

thorny cargo
#

Setting temperature works.

#

What doesnt work is that the dummy shows the current temperature.

marsh cairn
#

Have you looked into the Dev tools, if your template shows the expected output?

thorny cargo
#

{{state_attr('light.dummy_flur', 'color_temp')}} is null

#

but why?

inner mesa
#

Light is probably off 🤷

thorny cargo
#

No, it´s on

marsh cairn
#

What do the states in the Dev tools say?

thorny cargo
#

<template TemplateState(<state light.dummy_flur=on; min_color_temp_kelvin=2000, max_color_temp_kelvin=6535, min_mireds=153, max_mireds=500, effect_list=['blink', 'breathe', 'okay', 'channel_change', 'candle', 'fireplace', 'colorloop', 'finish_effect', 'stop_effect', 'stop_hue_effect'], supported_color_modes=[<ColorMode.COLOR_TEMP: 'color_temp'>, <ColorMode.HS: 'hs'>], color_mode=hs, brightness=255, color_temp_kelvin=None, color_temp=None, hs_color=(28.391, 65.659), rgb_color=(255, 166, 87), xy_color=(0.526, 0.387), effect=None, friendly_name=Dummy Flur, supported_features=36 @ 2023-12-11T16:45:09.538803+01:00>)>

#

and that are those of the real one:

#

<template TemplateState(<state light.flur=on; min_color_temp_kelvin=2000, max_color_temp_kelvin=6535, min_mireds=153, max_mireds=500, effect_list=['blink', 'breathe', 'okay', 'channel_change', 'candle', 'fireplace', 'colorloop', 'finish_effect', 'stop_effect', 'stop_hue_effect'], supported_color_modes=['color_temp', 'xy'], color_mode=color_temp, brightness=255, color_temp_kelvin=4291, color_temp=233, hs_color=(26.727, 29.841), rgb_color=(255, 212, 178), xy_color=(0.405, 0.36), effect=None, friendly_name=Flur, supported_features=44 @ 2023-12-11T16:45:09.537201+01:00>)>

marsh cairn
#

And why are you using another template now? We have been talking about {{state_attr('light.flur', 'color_temp')}}

thorny cargo
#

?

#

Seems like I discovered a HA bug/missing feature.

marsh cairn
#

It depends on the color mode your light is in. Color mode hs doesn't provide color_temp,

thorny cargo
#

Regardless of the mode my light is in, the dummy cant show a temperature since it cant switch to temperature mode.

#

How would I use anchors to use my code for a list of light names?

marsh cairn
#

Color temperature doesn't exist in Hue/Saturation

thorny cargo
#

Yeah and the template light cannot switch to temperature mode, thus never has a temperature.

#

But it can still set it.

marsh cairn
#

To get the state a workaround might be to use hs_template instead of temperature_template

thorny cargo
#

I already got hs_template. Removing temperature_template doesnt change anything.

#

Can I use my template light code for mulitple lights?

slender adder
#

Question does some1 have a template to set a state of a entity to sleeping?

#

in this case my entity 🙂

torpid crag
#

Hi All… any idea how to go about sorting this error in my logs?

2023-12-12 12:17:27.913 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'motionDetectorStatus' when rendering '{{ value_json.motionDetectorStatus }}'

mighty ledge
mighty ledge
torpid crag
#

I dont think so… nothing in the config.yaml file anyway.

#

Plus all my “helper” based motion groups seem to be OK as well. I literally dont know where the error is coming from. 🙂

scenic verge
#

I currently have a simple binary sensor template helper made:
{{ states('sensor.living_room_cube_sensor_angle_x')|float > 85 }}
How do i add more entity's to this? So the binary sensor only turns on during multiple entity values being correct? And is it possible to make this between two values instead of currently >85?
Or would something like this work?

{{ states('sensor.living_room_cube_sensor_angle_x')|float < 90 }}
{{ states('sensor.living_room_cube_sensor_angle_y')|float > 80 }}
{{ states('sensor.living_room_cube_sensor_angle_y')|float > 90 }}
{{ states('sensor.living_room_cube_sensor_angle_z')|float > 80 }}
{{ states('sensor.living_room_cube_sensor_angle_z')|float > 90 }}```

thanks!
marble jackal
#

I would do it like this:

{% set x = states('sensor.living_room_cube_sensor_angle_x') | float(0) %}
{% set y = states('sensor.living_room_cube_sensor_angle_y') | float(0) %}
{% set z = states('sensor.living_room_cube_sensor_angle_z') | float(0) %}
{{ [x, y, z] | select('>', 80) | select('<', 90) | list | count == 3 }}
#

you need one true or false. Not 6 true or false

#

I assume they all need to be true (so x, y and z should be between 80 and 90)

ember saffron
#

Hi, I have a MQTT sensor and the integrated MQTT broker. I now implemented the sensor. which works. I also would like to use the availablity, because after a HA start the sensor is still unavilale. but I have a block here where Im stuck. Can someone enlighten me? http://pastie.org/p/5XcCy8BjGEam9cN2d3yafk

scenic verge
marble jackal
#

that's becasue I used your example

scenic verge
#

so x, y and z need to be between different values in order to activate the binary sensor.

#

ah i see, my bad then.

marble jackal
#

in that case:

{% set x = states('sensor.living_room_cube_sensor_angle_x') | float(0) %}
{% set y = states('sensor.living_room_cube_sensor_angle_y') | float(0) %}
{% set z = states('sensor.living_room_cube_sensor_angle_z') | float(0) %}
{{ 80 < x < 90 and 60 < y < 70 and 50 < z < 95 }}
scenic verge
#

looks weird, that it starts with a value, then x, then the secondary value. thanks a lot though! don't understand how it works but as long as it does^^

#

works perfect, just tested^^ gonna make some nice HA-p0rn from this 😄

marble jackal
#

it basically states that x should be between the 2 values

#

you could also do it in 6 seperate steps if that's more readable for you:
{{ x > 80 and x < 90 and y > 60 and y < 70 and z > 50 and z <95 }}

scenic verge
mighty ledge
#

no

#

if you want it to work with minuses, add | abs to each value

#

As a sidebar, i'm 99.999999% sure a blueprint for this device already exists

marble jackal
#

is it the xiaomi magic cube? In that case, yes

mighty ledge
#

It's gotta be

#

I don't know any other device that has cube in the name that reports angles

scenic verge
scenic verge
#

whoops, already see why pasting it here.

#

🏗️

marble jackal
#

-85 < z < -95

inner mesa
#

You'll never get negative values anymore

scenic verge
#

what do you mean?

scenic verge
marble jackal
#

if you add abs your values will always be positive

#

70 will remain 70, but -70 will become 70 as well

#

and even when you would still get negative values, -85 < z < -95 will never be true. A value can not be above -85 and below -95 at the same time

mighty ledge
#

if you use abs, remove all the negative signs in your last line

#

abs is absolute value

#

i.e. always postive number

scenic verge
#

but that makes it not work at all.

mighty ledge
#

because your last line has negatives

#

remove the negatives

scenic verge
#

it should, the value is negative in order to make the binary sensor work.

mighty ledge
#

dude

scenic verge
#

z2m reports the current z-axis is -90.

mighty ledge
#

if your values are always positive because use ABS, then how will x ever be -?

marble jackal
#

yes, and you converted that to 90 because you used the abs filter

mighty ledge
#

this is math 101, learned in like 3rd grade

scenic verge
#

so it can't work with minuses? it didn't work before i added abs, and now neither, because of abs then, as i understand it.

#

and yeah, not great at math and code.

marble jackal
#

you added abs where you declare x, y and z

#

that will mean you will not have negative values anymore

mighty ledge
#
{% set x = (states('sensor.living_room_cube_sensor_angle_x') | float | abs) %}
{% set x = (states('sensor.living_room_cube_sensor_angle_y') | float | abs) %}
{% set x = (states('sensor.living_room_cube_sensor_angle_z') | float | abs) %}
{{ 0 < x < 5 and 0 < y < 5 and 85 < z < 95 }}
marble jackal
#

-80 will be considered the same as 80

mighty ledge
#

that will work with both postive and negative numbers

scenic verge
scenic verge
#

or?

marble jackal
#

that template will work, because -90 will be converted to 90 by the abs filter, and 90 is between 85 and 95

scenic verge
#

But that's not good. Because the sensor can report between 85-95 when its facing up. It reports -85 till -95 when facing downwards ^^

#

If i would then use the template and understanding correctly, both binary sensors would turn on.

#

Both the binary helper set for upwards facing, as the one for facing downwards with negative z value.

marble jackal
#

we don't know of any binary sensors, we only know of this particular template you are asking questions about. We don't know what you are trying to achieve

plain magnetBOT
#

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

marble jackal
#

so, it might be helpful if you would describe your problem, and what you are trying to achieve

scenic verge
#

the device/sensor reports x y z values on different entity's. when its facing down, its z sensor is reporting 90 degrees. so the value 90. when its facing down, its reporting -90 on the same z axis. on both situations i want to make a action for it.

mighty ledge
#

as stated before, you should look into the blueprint

#

it's an automation thats already set up for you, you just fill out the fields

marble jackal
scenic verge
#

thanks you too! ❤️

mighty ledge
#

pretty sure you didn't understand his repsonse

marble jackal
#

Still trying to help here

scenic verge
#

i got it figured out by removing the abs, and swapping the minus and positive numbers in Z (and the x and y sensors)

marble jackal
#

yes, that was what i was trying to suggest 🙂

scenic verge
#

sorry for being stopid quite some times.

plain magnetBOT
#

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

jolly cradle
#

I've written a message and I got a reply that it got converted to a file. is anyone able to see the file/message?

#

it was over 15 lines long.

plain magnetBOT
#

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

plain magnetBOT
#

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

marble jackal
#

@limpid stratus remove - sensor: above the 2nd sensor. It isn't placed under the trigger now, so it can't access the variable with the forecast

ember saffron
#

Hi, I have a MQTT sensor with the integrated MQTT broker. I now implemented the sensor. which works. But after HA start it is (of course) unavailable. I would like to change that, I have a block here where Im stuck. Can someone enlighten me? http://pastie.org/p/55cyGv924LRsiyeCFV0Hms Thanks 🙂

trail estuary
#

Is there some way I can rate limit this template so that it doesn't change its state more often than a given interval?

        {% if now().minute >= 40 and (((states('sensor.amsleser_houruse') | float / (now().minute)) * 60) | round(2)) > 4 %}
          {{ True }}
        {% else %}
          {{ False }}
        {% endif %}
icy jay
#

Hi,

ive been using a automation to list calendar events and turn a input boolean on or off if there are events or not. This work until the service changed from „list events“ to „get events“

plain magnetBOT
#

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

icy jay
#
   - service: calendar.get_events
    data:
      duration:
        hours: 120
        minutes: 0
        seconds: 0
    response_variable: response3
    target:
      entity_id: calendar.db
#
        conditions:
          - condition: template
            value_template: "{{ response1.events | count > 0 }}"
          - condition: template
            value_template: "{{ response2.events | count > 0 }}"
          - condition: template
            value_template: "{{ response3.events | count > 0 }}"
    then:
      - service: input_boolean.turn_on
        target:
          entity_id: input_boolean.kalenderanzeige
        data: {}
#

Any ideas why this wont work anymore?

#

Thats what the 2023.12 change says:

The output of this newer service changed slightly, as it now returns a mapping of entity IDs to lists of events instead of a list of events.

icy jay
#

That solved it:

{{ response2['calendar.ics'].events | count > 0 }}

spark vortex
#

I have a bunch of template sensors in my template.yaml file, and I need to create a float variable to be used in each sensor to calculate energy cost, how can I define this variable?

#

this is an example of sensor that I have:
- sensor: - name: Frigo yearly cost unit_of_measurement: "€" state: "{{ (float(states('sensor.frigo_consumi_yearly')) * float(0.35)) | round(2) }}"

I want to replace 0.35 with a variable so I can just change it instead of changing the value in each sensor every time

analog mulch
#

hi! is |has_value supposed to work on binary_sensors? If not what's the proper thing to do? I want to set up an availability template based on some binary_sensors having a known state

marble jackal
analog mulch
# marble jackal Yes, that should work

BUt this is what I get in 2023.12.1, in the template devtool:

{{states('binary_sensor.sealed_salon' )}}
{{states('binary_sensor.sealed_salon')|has_value}}

output:

off
False
marble jackal
#

You know you have two different entity ids there right?

analog mulch
#

yeah that was a stupi typo/ it's the same

marble jackal
#

You need to use it on the entity id

#

Not on the state

#

{{ 'binary_sensor.sealed_salon' | has_value }}

analog mulch
#

oh i see -- that's a bit funny. Ok indeed it works

spark vortex
marble jackal
marble jackal
#

You need to use it in the same way as your sensor value, so het the state and convert it to a float

spark vortex
spark vortex
marble jackal
#

Why do you want to set an initial value?

spark vortex
#

I need a variable that I can update manually on needs

#

it is not a calculated value in HA itself

marble jackal
#

I understand that, but I don't think you understand what the initial setting does.

#

That will set it back to 0.35 on every restart of HA

#

While otherwise it will just restore the previous state

spark vortex
#

yeah, I will change the initial value if I need to change the cost per kwh, or there is a better way to do it?

#

min/max is something that I dont need

marble jackal
#

Just change the value of the input number in the GUI

#

That's where is built for

spark vortex
#

I am doing like this now:
price_per_kwh: name: price per kW/h initial: 0.35 min: 0 max: 10 unit_of_measurement: "€/kWh"

- sensor: - name: Totale total cost unit_of_measurement: "€" state: "{{ (float(states('sensor.totale_consumi')) * float(states('input_number.price_per_kwh')) | round(2) }}"

#

but I think something is wrong

marble jackal
#

You don't need the initial value, you can just change the value on your dashbord or in the entity settings

spark vortex
#

ok, so you suggest to create it with "number" helper? but I only see max and min, where exactly I can set the value?

marble jackal
#

In the entity settings

spark vortex
#

ah ok, after the creation and using steps of 0.01

marble jackal
#

Yes

spark vortex
#

ok, so now if I try to use it I get Invalid config for 'template' at templates.yaml, line 135: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value 'sensor->0->state', got "{{ (float(states('sensor.totale_consumi')) * (states('input_number.price_per_kwh')) | round(2) }}"
- sensor: - name: Totale total cost unit_of_measurement: "€" state: "{{ (float(states('sensor.totale_consumi')) * float(states('input_number.price_per_kwh')) | round(2) }}"

#

oh, missing )

mighty ledge
#

that's why you should avoid overly using them

#

or use an IDE that adds them for you

spark vortex
#

weird that the HA config checker did not discovered it

mighty ledge
#

e.g. of using float and round properly:

{{ (states('sensor.totale_consumi') | float * states('input_number.price_per_kwh') | float) | round(2) }}
mighty ledge
spark vortex
#

ah

mighty ledge
#

it does not look at anything in the yaml fields

spark vortex
mighty ledge
#

that's the intended way to use jinja

#

you can even do...

{{ states('sensor.totale_consumi') | multiply(states('input_number.price_per_kwh') | float) | round(2) }}
fierce hawk
#

Hi there!
I would like to change the color of a light based on some sensor state;
Short story is we are having multiple tarriff for electricity and I would like to change color of a light based on the current tarriff.

The sensor I have is: sensor.current_price with those states: "Bleu, Blanc, Rouge, inconnu"
I'd like the light to be blue when state is bleu, white when state is blanc etc...

What would be the best implementation?

mighty ledge
#

an automation, not using templates, using the choose action/sequence with state conditions that lead to light.turn_on actions using the accompanied color

#

if you aren't afraid of templates, there are template solutions to this problem

#

@fierce hawk ^

plain magnetBOT
#

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

honest wing
#

wrong channel, sorry

mighty ledge
honest wing
slender adder
#

Question is it possible with a template to change a state from person. to another state ?

#

i can do it with the developer tools

mighty ledge
#

No, templates do not offer a way to set states

slender adder
inner mesa
#

You should focus on the device_trackers that are assigned to the person

slender adder
#

its my phone + Smartwatch

#

instead of home

#

and when my automations detect that some stuff will trigger, like my curtains who close

#

and some devices cant trigger stuff anymore

#

ha didnt knew the HASS app also tracked battery state

inner mesa
#

Seems like you really want a template sensor or input_text

tribal cedar
#

Is it possible to use a template to reuse the options from an input_select helper, as the valid options for a scripts field.

I'm trying to do this but I'm surely missing something as this isn't working as the definition for the script field.

option: selector: select: options: "{{ state_attr('input_select.sitting_room_activity', 'options') }}" name: option required: true

slender adder
sage aurora
#

Anyone know a good way to strip the leading zero off a sunrise time? {{ (states('sensor.sun_next_rising') | as_timestamp | timestamp_local | string)[11:16] }} will give me 07:30

forest ferry
#
  - name: 'HOME power total'
    unique_id: home_power_total
    device:
      identifiers: energymon3
      name: "ENERGYMON3"
      model: "Sonoff Basic"
      manufacturer: "Tasmota"     
    device_class: power
    state_class: measurement
    suggested_display_precision: 0
    unit_of_measurement: "W"
    state_topic: tele/ENERGYMON3/SENSOR
    force_update: true      
    value_template: "{{ value_json.ENERGY.Power[0] }}"
#

based on the above template, I would expect that changing "W" to "kW" would divide the value by 1000 and show "kW" as a suffix; but It multiplies by 1000 and stays in watts... what am I missing?

inner mesa
sage aurora
inner mesa
sage aurora
#

Sweet 🙂

forest ferry
timber cliff
#

I'm looping thru an array in the attributes. I'd like to use a filter for the time comparison but comparing a str to date is bad. Is this unpossible with a filter? Can I change the component to define types on the attributes?
example:

{% for ass in state_attr('sensor.infinite_campus_assignments', 'assignment') | selectattr('missing', 'equalto', true)| sort(attribute='duedate') -%}
  {% if as_datetime(ass.duedate)> now() - timedelta(days=14 ) %}
    {{ ass.assignmentname }}
    due date: {{ ass.duedate }}
  {% endif %}
{%- endfor %}
timber cliff
#

if the property in the component was date time I assume this would work..selectattr('duedate', 'lt', two_weeks_ago)

marble jackal
#

@timber cliff How is the datetime string formatted? If it's an isoformat datetime string in either UTC or your local time, you can easily create a string to compare with

distant plover
#

Can I shorten this somehow? {% set precipitation = state_attr('sensor.weatherman_data_tag','wm_precipitation_0') %} {% set precipitation_unit = state_attr('weather.forecast_home','precipitation_unit') %} {% if precipitation == 0 %} '' {% elif precipitation > 1 %} {{ precipitation | round | string + ' ' + precipitation_unit}} {% else %} {{ precipitation | string + ' ' + precipitation_unit}} {% endif %}

marble jackal
#
{% if precipitation > 0 %}
{{ precipitation | round(0 if precipitation > 1 else 2) ~ ' ' ~ precipitation_unit}}
{% endif %}  
#

no need for the string filter if you use ~ to join the parts

#

or use

{% if precipitation > 0 %}
{{ [precipitation | round(0 if precipitation > 1 else 2), precipitation_unit] | join(' ') }}
{% endif %}  
fossil venture
marble jackal
#

has_value needs to be applied on an entity_id, not an a state

#

so has_value(this.state) will always be false

#
template:
  - trigger:
      - platform: state
        entity_id: binary_sensor.your_sensor_here
        to: 'on'
    sensor:
      - name: Sensor Daily First On Time
        state: >
          {% set opened = states[trigger.entity_id].last_changed %}
          {% if as_datetime(this.state) is not none and as_datetime(this.state).date() != opened.date() %}
            {{ opened }}
          {% else %}
            {{ this.state }}
          {% endif %}
        device_class: timestamp
#

that should work I think

fossil venture
#

Thanks buddy.

#

Oh hang on. They only want the first time it was opened each day.

marble jackal
#

yes, that is done by the date comparison

fossil venture
#

Yep I see that now. Thanks.

marble jackal
#

if the date of the current state is the same as the date of opened, it will return the current state

fossil venture
#

Yeah. This bit: as_datetime(this.state).date() != opened.date() I just saw my attempt using .day was missing and jumped to the wrong conclusion.

#

Counting down until they ask me to format the datetime as they want...

marble jackal
#

incoming in 3... 2...

marble jackal
#

0.5...

mighty ledge
#

what are we waiting for

marble jackal
#

the person who requested this last time the door was opened sensor to request for a different format for the datetime

mighty ledge
#

I have an automation that does that

#

makes a mqtt device and plops in door information

#

who opened the door, when it opened, when it closed, etc

#

I should probably turn that into a blueprint

marble jackal
#

how do you know who opened it?

mighty ledge
#

you can infer that information, or you can pull it from the context (if they used the UI)

#

e.g. the sensor displays "Mike or Lindsay", if my wife or I are home

#

so, one of use must have opened the door

marble jackal
#

ah sure

#

That stops working if you also have a kids without device trackers 😉

#

TheFes, 4yo or 2yo opened the door

mighty ledge
#

just cut off thier hands

#

jk

#

but yes, we don't have kids, so it's pretty easy for us

#

I use a template to detect if guests are home via devices connected to my guest vlan

#

on a more serious note about stopping your 2 and 4 year old from opening the door, you can get those spinning plastic things that don't allow them to spin the door knob

plain magnetBOT
#

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

radiant vine
#

That went well... anyway if somebody could help i would be glad 🙂

#

Probably had some strange indentation problem there.

mighty ledge
#

indent icon_template 2 spaces (and it's template)

#

@radiant vine ^

radiant vine
wintry bay
#

Hello! I could need some help with a template.

speech_engine:
  mode: queued
  sequence:
  - variables:
      media_player: !include players.yaml
[ truncated ]
  - service: input_number.set_value
    target:
      entity_id: input_number.media_player_volume
    data:
      value: "{{ state_attr(media_player, 'volume_level') }}"
#

The set_value does not set the value. But in dev-tools-->templates (and the template below is the above players.yaml):

  {% if player == 'office' %}
    {% set media_player = 'media_player.office' %}
[ truncated ]
  {% endif %}
  {{ media_player }}
{{ state_attr(media_player, 'volume_level') }}

returns:
media_player.office
0.37

#

it's since I used this that it doesn't work. Before, while testing, I hardcoded "media_player.office" instead of the variable media_player

data:
      value: "{{ state_attr(media_player, 'volume_level') }}"
mighty ledge
#

what's in !include players.yaml

#

post the full file contents here

wintry bay
#

roughly 40 lines of IFs. But this has been working for 4 years and still does. I recently implemented the volume control

plain magnetBOT
#

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

mighty ledge
#

looks like it returns a list or a string

#

depending on the path it takes

wintry bay
#

only a string, no lists

#

but yes

mighty ledge
#

if it's a list, state_attr(media_player, 'volume_level') won't work

mighty ledge
#

that will be resolved as a list

wintry bay
#

true! but that currenty is not active because the IFs falls in another case

#
returns: 
media_player.office
0.37
mighty ledge
#

it returns both the media player and the level?

#

I don't see that include showing a number anywhere

wintry bay
#

the long code returns the media player. The numebr comes from "{{ state_attr(media_player, 'volume_level') }}"
I copied both of them in Dev tools -> templates

mighty ledge
#

is there an error in your logs?

wintry bay
#

not about this :/

mighty ledge
#

Then it should be working

wintry bay
#

i can also copy the script

mighty ledge
#

You're most likely looking in the wrong spot or the path the script is taking isn't what you expect

wintry bay
#

yeah, it should :/ but doesn't, and I thought it's my eyes failing somewhere

mighty ledge
#

view the trace

wintry bay
#

the logbook doesn't save any trace for this script. There is an input boolean that I use for testing, this triggers a test message. It helps me while writing the templates and the scripts used - but the whole speech system doesn't leave any trace if you mean the tree-like tool that shows the debug trace of anything

mighty ledge
#

trace is a function on the script itself

wintry bay
#

F*** im dumb. I activated the wrong input_boolean

#

it does work

mighty ledge
#

so it's the boolean that produces the list?

wintry bay
#

ok this is awesome!

mighty ledge
#

cause that would make your states() fail

#

or was it adjusting another media player?

wintry bay
#

no, the boolean that i was toggling was running a different speech pipeline. The "testing" one uses another which is the one I'm working on

#

the templates and all is correct - i was just calling the wrong script that started the speech engine

#

about the list: that is a condition that 100% won't work, but it's also on IF that is never triggered. It is a residue from when I was using Alexa as media player

#

but thanks! really!

tribal cedar
#

Does anyone know if theres a way to use area_entities in a template sensor, so that when entities are added or removed to a given area, the template sensor itself dynamically picks up on the change?

Today I added various power entities into my living room and expected my template sensor that iterates through them and totals their power together, to reflect the new entities but it seems that the area_entities doesn't listen for changes in the entities in the area.

Rebooting HA of course made it then pick up the changes.

inner mesa
#

Interesting, I hadn't thought about that. It's not based on entities, so there's no tie-in to the state machine

tribal cedar
#

Yeah I had been trying to optimize all of my custom template sensors and had previously being recommended to use the area_entities, which did work great, but yeah it seem to have this slight downside. Whether its by design or not I guess is the question. Its not a big deal but I guess it might surprise people when it doesn't pick up on changes to the area of some entities.

#

Would it require some sort of like 'area entities changed' event.

inner mesa
#

Right, just "entity added" isn't enough. And it's not in the state machine, so isn't represented in a state_changed event

tribal cedar
#

Ahhh ok, got it.

limber haven
#

you know.. as much as I hate large language models.. Bing is actually 'okay' at writing template code...

#

Or at least, writing it enough so you can kinda bodge it

#

.. generally

worthy granite
#

Hi

#

some help please with a sensor template.

#

I want to swop the sign of a energy value that is coming in from my inverter > states('sensor.sunsynk_battery_power'))

#

it comes in as a negative when charging the battery and as a positive when its depleting the power.

#

{{ (states('sensor.sunsynk_battery_power') | float | abs) }} - This would just make it always positive.. but not when its positive .. to negative.

marble jackal
#

multiply with -1

limber haven
#

Yeah I was just thinking that 😄

marble jackal
#

{{ states('sensor.sunsynk_battery_power') | float * -1 }}

limber haven
#

gets flashbacks of square roots, imaginary numbers..

#

I could use a hand actually with some template code that I cant seem to make work. I need to read the value from an array and return that that time -2 hours. (which I have working) BUT it needs a second check that if the event start time is after 4pm then the resulting time should be 2 hours before 4pm. {% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %} {% set timestamp = as_timestamp(event) %} {% set two_hours_prior = timestamp - 2*60*60 %} {{ two_hours_prior | timestamp_custom('%H:%M', true) }} {{ 'true' if now().strftime('%H:%M') == two_hours_ago else 'false' }}

marble jackal
#

do you really need the string true and false? Is this for a binary sensor?

limber haven
#

Its for a trigger template so I think it does? (It needs to return true/false was my understanding)

marble jackal
#

it will retrun true or false if you just do
{{ now().strftime('%H:%M') == two_hours_ago }}

#

it will actually retrun a boolean value then, not a string

#

and you our returning both a time string and true or false

#

I think you intended to do this:

{% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %}
{% set timestamp = as_timestamp(event) %}
{% set two_hours_prior = timestamp - 2*60*60 %}
{% set two_hours_ago = two_hours_prior | timestamp_custom('%H:%M', true) %}
{{ 'true' if now().strftime('%H:%M') == two_hours_ago else 'false' }}
#

you never defined the variable two_hours_age, you just outputted what it should be

#

I would do it like this though:

{% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %}
{% set two_hours_ago = (event | as_datetime | as_local).strftime('%H:%M') %}
{{ now().strftime('%H:%M') == two_hours_ago }}
#

test that in devtools > templates first, it could be that the value is already a datetime, and then it will retrun an error

worthy granite
marble jackal
#

no, multiplying with -1 will turn positive values negative, and negative values positive

#

you can easily try for yourself using a calculator

limber haven
#

Ahh right right I see

#

Yeah it complains that the value is already a datetime and not a float 🙂

marble jackal
#

remove the as_datetime filter then

#
{% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %}
{% set two_hours_ago = ((event | as_local) - timedelta(hours=2)).strftime('%H:%M') %}
{{ now().strftime('%H:%M') == two_hours_ago }}
limber haven
#

Yeah that produces a 'false' result which should be correct 🙂

#

Just as well, I thought that was working when it clearly wasnt haha. Now for the next bit to check if its before 4pm and do something different if it is 😄

worthy granite
marble jackal
#

yes, but make sure not to round only -1

worthy granite
#

{{ states('sensor.sunsynk_battery_power') | float * -1 }} round(0)

marble jackal
#

no, the round filter needs to be inlcuded in your template, so within the curly brackets

worthy granite
#

{{ states('sensor.sunsynk_battery_power') | float * -1 round(0) }}

marble jackal
#

no.. you have to declare a filter by using the pipe | character, just like you do for the float filter

worthy granite
#

oh that would round the -1

marble jackal
#

and that

worthy granite
limber haven
marble jackal
#

sorry, yes, I forgot that part

#

added it in the last version

limber haven
#

🙂

dry narwhal
#

Hi everyone,
trying to extract the first two letters of the first word and first two of the second word of the area_name. But I am guessing that I have to write my idea differently:

plain magnetBOT
#

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

limber haven
#

was doing like 10 other things, but I .. think this code does what I want? (its hard to tell) ```TEST:
{% set event = state_attr('event.octopus_energy_octoplus_saving_session_events', 'joined_events')[-1]['start'] %}
{% set two_hours_ago = ((event | as_local) - timedelta(hours=2)).strftime('%H:%M') %}
{% set cutoff = (today_at('14:00') | as_local).strftime('%H:%M') %}

{% if two_hours_ago >= cutoff %}
Window is after the Cutoff
{{ now().strftime('%H:%M') == cutoff }}
{% else %}
Window is before the Cutoff
{{ now().strftime('%H:%M') == two_hours_ago }}
{% endif %}```

dry narwhal
limber haven
#

So it should read the avlue of the saving session, and check what the time is 2 hours before that point, if the resulting time after 2pm, it should return 'true' if the time is actually just 2pm. If the result is BEFORE 2pm it should return true at.. whatever time is 2 hours before... ... if that makes sense

#

(i.e. if the trigger time in 'event' was 6pm, it should return true if the actual time is 2pm, If the 'event' was at 3pm, it should return true at 1pm)

#

My head hurts haha.

dry narwhal
#

My fixed code is:

plain magnetBOT
#

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

dry narwhal
#

(Just if someone is looking for something similar 🙂 )

marble jackal
#

@dry narwhal why are you using that first for loop

#

you can just do:

   {% for item in states.climate | selectattr('entity_id', 'search', 'eq3', ignorecase=True) -%}
   {% set a_name = area_name(item.entity_id) %}
   {% set name_split = a_name.split() %}
   {{
    {
     "type": "thermostat",
     "entity": item.entity_id,
     "name": name_split[0][:2] + name_split[1][:2] if name_split | length > 1 else a_name[:4]
    }
   }},
   {%- endfor %}
coarse tiger
#

Why doesn't this work anymore? 🤔

{%- set seendevices = namespace(entities=[]) -%}
{%- for device in states.device_tracker -%}
  {%- if(device.attributes | length) == 2 and device.state == "home" -%}
    {%- set seendevices.entities = seendevices.entities + [device.entity_id] -%}
  {% endif %}
{%- endfor -%}
mighty ledge
#

that will work

#

explain whats not working 😉

coarse tiger
#

i have ping device trackers which i need to count

#

i see ping devices, with 2 attributes and state "home" in my entities list

#

seendevices.entities however is empty

mighty ledge
#

there's most likely more or less attributes

#

you should be using integration_entities('ping') anyways

marble jackal
#

🐌

mighty ledge
#

@arctic sorrel please put the sonic run emoji on the previous snail emoji. Thanks.

marble jackal
#

my ping entities have 6 attributes

mighty ledge
#

Yes, now that they moved to the UI, the number of attributes most likely changed

marble jackal
#
round_trip_time_avg: 1.058
round_trip_time_max: 1.698
round_trip_time_mdev: ""
round_trip_time_min: 0.418
device_class: connectivity
friendly_name: Server
coarse tiger
#

integration_entities('ping') wasn't a thing also when I did this afaik
thanks, got it to work with that

mighty ledge
#

I'm still waiting for tinkerer to put the sonic emoji on the snail emoji

coarse tiger
#

device.state is empty though

mighty ledge
#

well it's an entity_id

#

not a state object

coarse tiger
#

this worked before

mighty ledge
#
{{ integration_entities('ping') | select('is_state', 'home') | list }}
mighty ledge
#

saying things like "this worked before" when you aren't understanding why it worked before doesn't help the convo

mighty ledge
coarse tiger
#

I'm just baffled

mighty ledge
#

it's not baffeling, you used a really odd way to figure out the state objects were from the ping integration

coarse tiger
#

where is my breaking change announcement about device.state 😡 🤬

mighty ledge
#

there is no breaking change

#

you made a bad template

coarse tiger
#

true

mighty ledge
#

the number of attributes changed

#

which broke your bad template

#

ping was listed as a breaking change

#

anyways, use the template above, it's easier now

coarse tiger
#

my ui still only shows source and ipattributes

#

entity list shows friendly_name being added

mighty ledge
#

clear your cache and refresh the page, those are most likely the old unused yaml entities

#

ping was moved from yaml to the UI

#

and the dev tools -> states page and entity lists use caching for speed, which sometimes missleads users

coarse tiger
#

can confirm

marble jackal
#

device.state is not why no entities were found

#

it's the check on 2 attributes

#

the ping entities which are moved to the GUI have more attributes

heady sonnet
#

I am working on an automation that notifys me when a door is opened. I am sure i can do this with templating but not sure how to get the variable for it. I want to have the notification tell me which binary sensor was triggered in the message i.e "your {{ back_door }} was just opened" while there being several different triggers.

marble jackal
heady sonnet
#

outstanding thank you very much @marble jackal .

chrome ether
#
          ok
        {% elif state_attr('climate.fancoil_studio', 'current_temperature') | float > state_attr('climate.fancoil_studio', 'temperature') | float + 0.2 %}
          warm
        {% elif state_attr('climate.fancoil_studio', 'current_temperature') | float < state_attr('climate.fancoil_studio', 'temperature') | float - 0.2 %}
          cold
        {% endif %}```

mm i'm trying to figure out how to make a template that compares 2 values and i'm at the point where the first if is es: 22.5 it returns ok, if 22.2 returns cold and 22.8 warm.. how can i make so that between 22.3 and 22.7 is still resulting ok in the first if?
marble jackal
#
{% set current = state_attr('climate.fancoil_studio', 'current_temperature') %}
{% set set_temp = state_attr('climate.fancoil_studio', 'temperature') %}
{% set cold = set_temp - 0.5 %}
{% set warm = set_temp + 0.5 %}
{% if current > warm %}
  warm
{% elif current < cold %}
  cold
{% else $}
  ok
{% endif %}
chrome ether
#

had to fix the typo in else part

celest brook
#

Okay, I'm presumably getting something easy wrong, but I'm blanking. I'm trying to make a template binary sensor just blindly follow the state of a binary helper variable, and it's just not showing up as an entity, and I don't seem to get an error log.

#

`

  • binary_sensor:
    • name: "Wasmachine loopt"
      unique_id: "SensorWasherRunning"
      device_class: power
      state: >
      {{ states('input_boolean.washer_running') }}`
#

The code in the {{}} successfully returns on or off in the devtools template page.

#

(and the template binary sensor right above, in the same file, with the same indentation, does show up and has done so for many months.)

#

ooooh. Bloody hell. It appears to be a naming conflict.

marble jackal
mighty ledge
#

It should be fine as long as you don't create a second sensorwasherrunning in the template integration

celest brook
#

I dislike UUIDs, but it certainly seems like it would work better.

mighty ledge
#

I don't like uuids either

#

unique_id's only need to be unique per integration

celest brook
#

Yeah, I’m still not sure what exactly is going on, but it seems like starting it with template or sensor is a no-no.

mighty ledge
#

well, under the hood that unique_id is already prepended w/ template

celest brook
#

“template.”, right?

#

Yeah, I don’t really understand why it wouldn’t like that. But in the interests of making my life easier I might just move on to UUIDs because I don’t really care what it is.

mighty ledge
#

not sure, it doesn't really matter. It's only to make it unique under the hood in the system

marble jackal
#

In the visual code studio add on you can generate them with a right click of your mouse

celest brook
#

I did also notice that in the unique ID to entity name transition it seems to translate my CamelCase into camel_case, so it’s doing weird stuff.

mighty ledge
celest brook
marble jackal
mighty ledge
#

what's the shortcut combo?

slender adder
#

Just a input text and let the automation set the text sleeping in it or awake and trigger stuff from it

topaz walrus
#

Think this would be a template question?

I have a Aquara Dual Relay Zigbee device. I have it paired to Home assistant with a third party zigbee controller. If I had it paired using one of aquara's zigbee hubs, there would be an option to change the relay to a "pulse" mode vs a hard on/off relay. Since I dont own an aquara hub I am not able to change this...

I currently have it wired into my garage door and it works, but I have to toggle the switch twice in home assistant to make it operate. (Switching to pulse mode, would normally fix this)

Is there a way I can change the type of device in home assistant to a button vs a switch, or essentially make it open and close with press in home assistant. Basically using software, make it "pulse"

Please DO reply to this and or mention me if your able to help. 🙂

tribal cedar
fossil venture
# topaz walrus Think this would be a template question? I have a Aquara Dual Relay Zigbee devi...

Template button integration would be a good fit for this. Confusingly it is not a template question, as no templates are actually required. So #integrations-archived would have been a better fit, ```
template:

  • button:
    • unique_id: "garage_door_button"
      name: "Garage Door"
      icon: "mdi:garage"
      press:
      • service: switch.turn_on
        target:
        entity_id: switch.your_switch_here
      • delay: 1
      • service: switch.turn_off
        target:
        entity_id: switch.your_switch_here
tribal cedar
#

OK cheers. Is that something a layman like myself should log, or should it come from someone with a bit more knowledge and power 🙂

inner mesa
#

Nobody else will do it

plain magnetBOT
#

If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.

inner mesa
#

Just post on the forum

willow belfry
#

Can anyone help me modify the template below? I'd like to adjust the template so that it only picks from four specific colors rather than the entire RGB spectrum.

data:
  rgb_color:
    - "{{ range(255)|random }}"
    - "{{ range(255)|random }}"
    - "{{ range(255)|random }}"
target:
  device_id:
    - 472d84c9d68d751c9b5f51ae2ad7036b
    - f823e6ed66629c44c7ba41a6f622c1e0```
#

I considered swapping rgb_color: with color_name: but wasn't able to discern the proper syntax for a list of colors (red, green, blue, orange).

lucid thicket
#

Also as a side note, get in the habit of never using device id’s whenever you can avoid it

willow belfry
#

Funny you should mention the device id. That’s actually the way HA converted the initial UI action into yaml.

fossil venture
#

Yeah it does that now to make device replacement easier. Unfortunately it completely obscures the entity id.

willow belfry
#

I did manage to cobble together this template color_name: "{{ ('blue','green','red','white')|random }}" which is pretty close and working. I'm going to keep playing with the RGB angle since it would be nice to have the full flexibility of RGB.

willow belfry
#

Ha! This ultimately works. No idea why. rgb_color: "{{ [[255, 0, 0], [0, 255, 0], [0, 0, 255]] | random }}"

marble jackal
lunar osprey
#

Hello, I have a JSON from a REST API (grocy api in particular, with list of all products in my stock)

#

I'd like to create a sensor that has, in its attributes, the list of all the products

#

the JSON is in the form of

#

[{"name":...},{"name":...},{"name":...},{"name":...}]

#

it's an array

#

how can I add all the products as attributes of the sensor?

#

with value_template: "{{ value_json | length }}" I get the count of them properly

#

I would need something like

#

json_attributes_path: "$"
json_attributes:
- amount

#
  • name
#
  • expiry
#

etc...

lunar osprey
#

json_attributes: >-
{% for x in (value_json|from_json) %}
{{ x.amount }}
{% endfor %}

#

This doesn't seem to work

marble jackal
#

You can't

#

Only by putting the names in yourself, you can't use a template for that

heavy crown
#

json_attributes: >-

lunar osprey
#

what you mena jq?

marble jackal
#

The attributes in a rest sensor can't be templates

#

The only thing you can determine is the dictionary which contains the attributes

full knot
#

Hi! i would like to trigger an automation 30 minutes before my phone alarm goes off. I have tried this:

  - platform: template
    value_template "{{ states('sensor.time') == (state_attr('sensor.sm_a546b_next_alarm', 'timestamp') - 30*60)|timestamp_custom('%H:%M', false) }}"```

I do not know anything about templates and found this on a forum. Im using the right sensor. But nothing triggers.

Could someone help me with this? \:)
inner mesa
#

what does {{ state_attr('sensor.sm_a546b_next_alarm', 'timestamp') }} return in devtools -> Templates?

honest elk
#

Does anyone have any idea why this is returning '93ABD9' when the input boolean is off?

{% if is_state ('input_boolean.stove_enabled', "on") + states ('sensor.flue_sensor_stove_flue_temp') |float <= 190 %} #93ABD9
{% elif is_state ('input_boolean.stove_enabled', "on") + states ('sensor.flue_sensor_stove_flue_temp') |float <= 375 %} #D47428
{% elif is_state ('input_boolean.stove_enabled', "on") + states ('sensor.flue_sensor_stove_flue_temp') |float <= 600 %} #EF0F0F
{% elif is_state ('input_boolean.stove_enabled', "off") -%} white
{% else %} white
{% endif %}
inner mesa
#

you're adding a boolean to a float?

#

this kinda thing makes no sense:
is_state ('input_boolean.stove_enabled', "on") + states ('sensor.flue_sensor_stove_flue_temp') |float <= 190

#

I guess you want and where you have +

honest elk
#

RobC thank you.. I have literally been pulling my hair out for two hours with this

inner mesa
#

ok, so there's no alarm, then

#

start there

full knot
#

in the states tab Sensor.sm_a546b_next_alarm has these attributes Local Time: Sun Dec 17 01:00:00 GMT+01:00 2023 Package: com.sec.android.app.clockpackage Time in Milliseconds: 1702771200000 device_class: timestamp icon: mdi:alarm friendly_name: SM-A546B Next alarm

#

oooh wait so timestamp is not there

inner mesa
#

feel free to debug that kind of stuff on your own 🙂

mystic juniper
#

Hey all! I just installed the LCARS theme / templates and I have a quetion -- I seem to have lost the 3 dot menu in the upper right corner, replaces with the text UNKNOWN. If I siwtch back to the default or other theme ( non lacrs ) it comes back

#

Any suggestions ?

marble jackal
#

Which comes with the add-on

fossil venture
hard venture
#

In devtools , {{ state_attr('sensor.arcadia_christian_church', 'stream') }} currently returns true.
How do I convert that to properly be used in a button card? This does not work - I always get grey

type: custom:button-card
entity: sensor.arcadia_christian_church
triggers_update: sensor.arcadia_christian_church.stream
state:
  - value: 'true'
    color: rgb(255,0,0)
  - value: 'false'
    color: rgb(55, 55, 55)
marble jackal
#

It's probably a boolean value, not a string. Remove the quotes around true and false

hard venture
#

I've tried that, still no dice.

marble jackal
#

Oh wait, you are checking on the entity state, not on that attribute value

hard venture
#

Yeah... How do I check the attribute value from the devtools template in the card?

#

Do I need to build some sort of helper sensor and make the comparison on that in the card?

#

If I add show_state: true to the card, it gives me the name of the current stream.

#

which makes sense that 'true' or true isn't ever going to match that...

marble jackal
hard venture
#

Created a template helper that looks at that state, Set the button-card to look at the helper state instead. Took a few more tries to realize that it was returning 'True', not true or 'true', but it's working now.

analog thicket
#

Hello everyone. I need help with a sensor and im prettry new to this homeassistant. 🙂

#
  • name: "Elpris ekskl elafgift"
    unique_id: elpris_ekskl_elafgift
    state: {% set elafgift = (0.86120) %}{% set elpris_ekskl_elafgift = (states('sensor.elpriser_inkl_afgifter')|float) - elafgift %}{{ elpris_ekskl_elafgift }}
    unit_of_measurement: DKK/kWh
hard venture
#

Thanks for letting me rubberduck, @marble jackal

analog thicket
#

here i try to substract 0.86120 from my sensor "sensor.elpriser_inkl_afgifter"

#

it works when im trying it in Developer tools -> Template

#

but not when im putting it in my template file

#

when i try to start homeassistant after adding it I ger the following error: "found character '%' that cannot start any token"

#

What am I doing wrong? 🙂

lofty mason
sage aurora
#

To avoid my template turning into a huge mess, is it possible to define a custom function myself with a return value?

I need to look at the weather conditions reported by my weather service, and map these to weather icons in HA. It will use substring matching since the local weather service has tons of variants, and I only need to use maybe 5 icons in HA.

inner mesa
#

Yes, it's called a macro

sage aurora
#

Also, I'm not clear on where exactly to do the from include in my automation yaml.

mighty ledge
#

you do the from every time you start new jinja

#

to reload macros, call the reload template macro service call

sage aurora
#

Hmm. Would this be correct?

...
- type: icon
          value: >- 
            {% from 'weather_icon.jinja' import weather_icon %}{{ weather_icon(state_attr('weather.gatineau_hourly_forecast', 'forecast')[0]['condition']) }}
          x: 160
...
mighty ledge
#

that's one way

plain magnetBOT
#

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

marble kestrel
sage aurora
#

Awesome, macros are working 🙂 thanks!

scenic verge
lunar crater
#

hello template masters! i am trying to make sense of my self build mqtt sensors by having them push their measurements over a shared topic instead of having the device id included there. This should result in something of a payload like this {"hw_id":"<emac>", "sn_ix":"<index>", "celsius":<measurement>, ...}
Based on the string supplied in hw_id id like it to reference a device and sn_ix a sensor entity displaying the measurement

#

could anyone help me figuring out what i need to setup to do this? I am already able to grab the measurement through a value template, but i cant seem to find what needs to be done to be selective about the data origin

scenic verge
mighty ledge
#
light:
scenic verge
mighty ledge
#

yes

#

it's just like sensor: or any other field/section in configuration.yaml

mighty ledge
scenic verge
#

thanks, that did the trick ❤️

lunar crater
#

the payload however includes fields to identify which esp and sensor it is from which i would like to use to assign the data to the correct sensor entity

paper hazel
#

When using numeric state as a trigger with sun.sun, can the below be a template? e.g.```
below: "{{ states('input_number.lights_sun_elevation') }}"

#

When reloading I get an error in the logs saying it expected a float. I have tried with this and get the same error:```
below: "{{ states('input_number.lights_sun_elevation') | float }}"

cerulean oyster
#

How can I format a value of an entity which is a datetime as string to a custom time format?
I've tried already with "|asdatetime" and then "timestap_custom("%-H:%M", default=0), but the default (empty) is shown.
Wiothout the default I get a hint, the input value is invalid.

lofty mason
cerulean oyster
#

Input value is still invalid (I've did the timestamp converstion before)
ValueError: Template error: timestamp_custom got invalid input '1702854941.0' when rendering template

Got it, have to convert as_timestamp to float, then I can pass it to rimestamp_custom.

lucid thicket
mighty ledge
lunar crater
#

That seems rather smart!
I suppose this would effectively not trigger an update on the recorder for that entity?

mighty ledge
#

it shouldn't

#

but that's the route I'd take for the most part

#

not sure how good the code is, but it should work

mint hazel
#

Is there an easy way to replace only the last occurence of a character in a string? I've got a template that returns a list of entity friendly names separated by a comma. The last comma should be replaced with an " and".
Currently: A, B, C, D
Wanted: A, B, C and D

lofty mason
mint hazel
#

Oh, thats smart 😄 Thank you

#

I asked chatgpt in the meantime because I remembered that existed and it came up with this

| regex_replace(',([^,]+)$',' und\1')

I have no idea what's going on there. It works but I might change to your solution simply because I understand it 😄

lofty mason
#

yeah regex can get quite complicated.

limber haven
#

Hm, is there. a way to pull the array value for several different enties and check an array and return a count on how many are true?

#

I hvae several 'climate.wiser_roomname' and want to create ac ount of how many of those have the value 'is_heating:true'?

mighty ledge
#

{{ states.climate | selectattr('attributes.is_heating', 'eq', True) | list | count }}

limber haven
#

haha, your so good at this petro 😄

mint hazel
#

It's for an automation that notifies me on one of my Sonos speakers that at least one of the windows is still open when I open the door to leave my apartment. I tried it without the "and" and it just sounds super weird to me 😄

inner mesa
#

The 'and' is fine, it's the lack of that crucial comma 🙂

keen swan
#

Is there a way to check the state of an entity 3 seconds ago? this is my starting point

{{ (now() - states.binary_sensor.office_pmth_presence.state=='off') }}
inner mesa
#

No

keen swan
#

i was thingking something like this

{{ (now() - states.binary_sensor.office_pmth_presence.state=='off').total_seconds() < 3 }}

but that wont work

inner mesa
#

Templates have no access to historical state

keen swan
#

It works with last changed

#

this works as a true false

{{ (now() - states.binary_sensor.office_pmth_presence.last_changed).total_seconds() < 3 }}
velvet pilot
#

I have a temp sensor that becomes unavailable for exactly 10 minutes then it comes online again. How can I make something that it always shows the last known temperature

mighty ledge
velvet pilot
inner mesa
velvet pilot
inner mesa
#
template:
- sensor:
  - name: Holly Weight
    unique_id: holly_weight
    state: >-
      {% set weight = states('sensor.litter_robot_4_pet_weight')|float %}
      {{ weight if weight > 13 else this.state }}
#

now you have some knowledge

balmy terrace
#

afternoon guys!
I have a template sensor entity, but I'm having a hard time to list on attribute (one item per line)

{% set unavailable = expand(area_entities('Balcony'))
                    | selectattr('state', 'eq', 'unavailable')
                    | list
                    | map(attribute='name')
                    | join('\n') %}
{{unavailable}} 

It seems the linebreak is stripped out when rendering inside attributes , is there a workaround for this?
Thank you!

cerulean oyster
#

Hi, I'm willing to learn HA and reading a lot using Google, but all suggestions do not work for me. That's why I#m trying to get an answer here.
Having an entity card with several entities.
Now I want to change the icon color upon the value, i.e. battery is low. I've tried this what I found

type: entities
entities:
  - entity: sensor.working_room_battery
    name: Natterie
    icon: mdi:battery
    style: |
      :host {
        --paper-item-icon-color: red;
        color: red;
      }

But getting "Der Schlüssel „entities.3.style“ wird vom visuellen Editor nicht erwartet oder nicht unterstützt." which means, "style" is not supported.

mint hazel
inner mesa
#

The fight could lead to armed conflict

inner mesa
faint badge
daring mason
#

Does anyone know of a template method that can combine multiple climates as one? Or to create a single climate entity that will relay commands from itself to two others? I created a climate group which presents as a "group.climates_example" entity and isn't good for my needs.

My use case: I have two minisplits hooked up to the same heatpump, two broadlinks, one for each. Both broadlinks with their sensors are using smartIR (https://github.com/smartHomeHub/SmartIR) to give me two climate entities.

Because there's only a single heat pump, my minisplit modes need to be synced with one another. Again, the climate group is fine for issuing synced commands to both devices via automation, but since it's not a "climate.example" entity, I can't use it with my preferred Simple Thermostat (https://github.com/nervetattoo/simple-thermostat) card on the dashboard.

As an alternate solution, I was going to ditch the climate group altogether and control only one climate entity via both manual dashboard control and automation, then have a separate automation set Climate 2 to the same attributes as Climate 1 whenever it changes. The problem I ran into there is that I cannot use a float template as an input to set temperature. The automation rejects the following and won't save it.

service: climate.set_temperature
data:
  temperature: {{state_attr('climate.example_1', 'temperature') | float}}
target:
  entity_id: climate.example_2

Any Ideas?

lofty mason
#

quotes around the template?

daring mason
plain magnetBOT
#

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

neon lodge
#

Hi.
Im trying to create a template in the "new" helper menue, but i cant get it to react as i do in the dev-tool->template
{% if is_state("binary_sensor.frient_a_s_wiszb_138_binary_input", "on") -%}
Open
{%- else -%}
Closed
{%- endif %}

It does not update when status is changed to ON

or am i maby doing the whole thing wrong?

mighty ledge
#

why are you doing this when you already have a binary sensor

#

just change the device_class of the binary sensor to opening or door

#

or change the "display as"

#

and your states in the UI will be open/closed

neon lodge
#

oh lord..

#

because im stoopid apperantly hehe

lofty mason
#

If you were creating a binary template, it wanted the result to be on/off, not "Open" or "Closed".

neon lodge
#

Yeah... i figured it out, i over complicated a easy thing. thank you both

cursive geode
#

How do I write sensors that are in an extra .ymal in the config?

final axle
#

can someone please tell me, why a variable, that i set in a for loop, is again empty after the for loop?

mighty ledge
mighty ledge
mighty ledge
#

chances are, you don't even need a loop either

final axle
mighty ledge
#

can you post your code?

final axle
#

let me tiedy it up again

mighty ledge
#

No need

#

unless it has sensitive info

cursive geode
mighty ledge
cursive geode
#

duplicate key is displayed

mighty ledge
#

I see that, put your code into the file

#

sensor/notify.events/notify_events.yaml

#

that's where all your sensors should go

#

if you want them to be separate, you have to use a different method

plain magnetBOT
#

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

mighty ledge
#

ok, so

final axle
#

this should output the 'input_text.music_follow', a active tracker list, without the trackers of the user how press a button

mighty ledge
#
{% set ns = namespace(output=[]) %}
....
inside for loop
....
{% set ns.output = ns.output + [ item ] %}
#

then finally outside the loop

#
{{ ns.output }}
#

FYI, there's some other things you can change. e.g.

{% set matching_users = (states.person | selectattr('attributes.user_id','==', "81f3967ff55f4c94afe6e52400d538d1") | list) %}
{% if matching_users | length > 0 %}
{% set user = matching_users | first %}

can change to

{% set user = states.person | selectattr('attributes.user_id','==', "81f3967ff55f4c94afe6e52400d538d1") | list | first | default %}
#

which will default user to None if there is no element in the list

#

that's what default does

mighty ledge
#

or you can do this

#
{% set user = states.person | selectattr('attributes.user_id','==', "81f3967ff55f4c94afe6e52400d538d1") | list | first | default('system') %}
#

which also removes the {% set user = None %} and the {% set user = "system" %} without the if check

#

you can even default it to something that resembles a state object to make the rest of your code work

#

lastly, your whole for loop can be turned into a 1 liner

#
{{ state_attr(user.entity_id, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
#

@final axle ^

final axle
mighty ledge
#

Yes, that list gets them all

final axle
#

just for you to understand, in the automation, the user id is replaced by a variable

mighty ledge
#

Yes I understand that

#

state_attr(user.entity_id, 'device_trackers') returns a list of entity_ids

#

| select('is_state_attr', 'source_type', 'espresense')

#

filters the list of entity_ids

#

to only ones that are from espresense

final axle
#

i cant share the automation yaml here, let me upload it to pasebin

cursive geode
mighty ledge
#

the sensor section supports more than 1 integration

#

you just decided to put it all into 1 separate file

#

Trust me, put the sensor in that file, it will work

final axle
final axle
mighty ledge
#

Yes, I see that but the code doesn't need a loop is what I'm saying

final axle
#

if you want, you can revise it and re upload it

#

because i plan to make it public in the future when everything works

mighty ledge
#

all it looks like it's doing is putting a list of entity_id's into an input text

final axle
#

when done, this automation should implement a follow me function for music based on snapcast and espresence

final axle
mighty ledge
#

Ok, sit tight

final axle
#

i have two buttons, where a user can add its espresence device trackers or remove it

#

when they are in the list, the music will follow these trackers

mighty ledge
#

@final axle

trigger:
  - platform: event
    event_type: call_service
    event_data:
      domain: input_button
      service: press
      service_data:
        entity_id: input_button.folge_mir
    id: "1"
  - platform: event
    event_type: call_service
    event_data:
      domain: input_button
      service: press
      service_data:
        entity_id: input_button.folge_mir_nicht
    id: "2"
action:
- variables:
    triggering_entity: >
      {{ trigger.event.data.service_data.entity_id }}
    user_id: >
      {{ context.user_id }}
    user: >
      {{ states.person | selectattr('attributes.user_id','eq', user_id) | first | default }}
    entity_ids: >
      {{ state_attr(user.entity_id | default, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
condition: []
action:
  - service: input_text.set_value
    target:
      entity_id: input_text.music_follow
    data:
      value: "{{ entity_ids }}"
cursive geode
mighty ledge
#

You either have to change your !include, or add the sensor to your file

#

there's no in betweens.

final axle
mighty ledge
#

Oh, nevermind, see what I did

#

hold on

final axle
#

it dont let me save...

mighty ledge
#
alias: Musik folgen
description: ""
trigger:
  - platform: event
    event_type: call_service
    event_data:
      domain: input_button
      service: press
      service_data:
        entity_id: input_button.folge_mir
    id: "1"
  - platform: event
    event_type: call_service
    event_data:
      domain: input_button
      service: press
      service_data:
        entity_id: input_button.folge_mir_nicht
    id: "2"
condition: []
action:
  - variables:
      triggering_entity: >
        {{ trigger.event.data.service_data.entity_id }}
      user_id: >
        {{ context.user_id }}
      user: >
        {{ states.person | selectattr('attributes.user_id','eq', user_id) | first | default }}
      entity_ids: >
        {{ state_attr(user.entity_id | default, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
  
  - service: input_text.set_value
    target:
      entity_id: input_text.music_follow
    data:
      value: "{{ entity_ids or 'system' }}"
#

Had to edit it again, try copying it now

final axle
mighty ledge
#

is there a reason you're using an event for pressing the button?

final axle
mighty ledge
#

You can get it from the context object

#

in that case, use this instead...

final axle
# final axle it does nothing....

triggering_entity: input_button.folge_mir
user_id: 81f3967ff55f4c94afe6e52400d538d1
user: >-
<template TemplateState(<state person.lanea_lucy=home; editable=True,
id=lanea_lucy, latitude=52.107986, longitude=9.253258, gps_accuracy=100,
source=device_tracker.sm_f936b, user_id=81f3967ff55f4c94afe6e52400d538d1,
device_trackers=['device_tracker.sm_f936b', 'device_tracker.lanea_z_fold4'],
friendly_name=Lanea Lucy @ 2023-12-19T20:42:03.002445+01:00>)>
entity_ids: []

mighty ledge
#
alias: Musik folgen
description: ""
trigger:
  - platform: state
    entity_id:
    - input_button.folge_mir
    - input_button.folge_mir_nicht
condition: []
action:
  - variables:
      triggering_entity: >
        {{ trigger.entity_id }}
      user_id: >
        {{ context.user_id }}
      user: >
        {{ states.person | selectattr('attributes.user_id','eq', user_id) | first | default }}
      entity_ids: >
        {{ state_attr(user.entity_id | default, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
  
  - service: input_text.set_value
    target:
      entity_id: input_text.music_follow
    data:
      value: "{{ entity_ids or 'system' }}"
#

Ah, hold on, can't serialize the satates object.

#
alias: Musik folgen
description: ""
trigger:
  - platform: state
    entity_id:
    - input_button.folge_mir
    - input_button.folge_mir_nicht
condition: []
action:
  - variables:
      triggering_entity: >
        {{ trigger.entity_id }}
      user_id: >
        {{ context.user_id }}
      user: >
        {{ states.person | selectattr('attributes.user_id','eq', user_id) | map(attribute='entity_id') | first | default }}
      entity_ids: >
        {{ state_attr(user, 'device_trackers') | select('is_state_attr', 'source_type', 'espresense') | list }}
  
  - service: input_text.set_value
    target:
      entity_id: input_text.music_follow
    data:
      value: "{{ entity_ids or 'system' }}"
#

That should work

final axle
#

i dont need system, but one button (folge_mir) need to add the trackers and the other button (folge_mir_nicht) needs to remove the trackers again from the list

#

thats what i try to do

mighty ledge
#

so 1 button adds, the other removes?