#templates-archived

1 messages Β· Page 121 of 1

dreamy sinew
#
{%- set map = {'cooling': 'blue', 'heating': 'orange', 'idle': 'green'} -%}
{{ map.get(state_attr('climate.ecobee_lite3', 'hvac_action'), 'red') }}
#

@true otter

wet lodge
#

Hi folks. I'm trying to extract the name of my next timer (timerLabel) from the Alexa Media Player. The sensor.kitchen_next_timer sensor has a sorted_active attribute with the following output:
https://paste.ubuntu.com/p/PPGFZh8WRQ/

Could someone please help me with the template to extract the timerLabel for the first active timer? The example I provided has two timers.

dreamy sinew
#

Can you toss that through a json formatter please? Hard to read on mobile

wet lodge
shut silo
#

any chance to set a condition and check if numeric_state of a sensor decreses by one?
or a wait template
but i don't know how to get the previous value

dreamy sinew
#

@shut silo you can compare the to and from states

shut silo
#

can you explain a bit more? i have an automation and want to continue the actions only if a sensor decreased by one

#

i know "from" and "to" only in triggers

dreamy sinew
#

@wet lodge that structure is kinda odd. A mix of those string IDs and dicts

wet lodge
#

Maybe that was why I was struggling so much.

dreamy sinew
#

I would need to do some testing but I'm not at a computer

wet lodge
#

I can wait.... Appreciate any help I can get, whenever I can get it.

dreamy sinew
#

@shut silo template docs should cover the answers there

shut silo
#

I read them, but didn't find the answer

#

any keyword i should look for?

dreamy sinew
#

@wet lodge {{ value_json[0]|select('mapping')|map(attribute='timerLabel')|first }}

#

something like {{ (trigger.to_state.state|float - trigger.from_state.state|float) > 1 }}

wet lodge
#

And, forgive me, but that output is from an attribute of a sensor... How do I combine that statement with the template that extracts the attribute?

true otter
#

hey phnx what does set map stand for? Can I use it with other strings where I need to set a color based on the state or state attribute of an entity?

dreamy sinew
#

@wet lodge just replace value_json with your states() call

#

@true otter set creates a variable. map is an arbitrary name I gave the variable

wet lodge
#

Hmmmm.... I've tried each of the following with no luck:

{{ state_attr('sensor.kitchen_next_timer', 'sorted_active')[0]|select('mapping')|map(attribute='timerLabel')|first }}

{{ states.sensor.kitchen_next_timer.attributes.sorted_active[0]|select('mapping')|map(attribute='timerLabel')|first }}

Any suggestions?

true otter
#

for my awareness: so you use the "random".get to pull the state attribute information , but you close it out with 'red' }}. Why is that?. I am just yrying to understand how templates work.

dreamy sinew
#

'red' is a default value if the lookup fails

#

@wet lodge what is the raw output of the state_attr() call?

waxen rune
#

I'd like to create a sensor that shows 98 from this:
{{ state_attr('sensor.garage', 'parameters') }} gives me {'type': 'Buffer', 'data': [98]}

It seemed simple, but I am stuck. I've been trying several variants of from_json but I have realised I need push in a better direction or an example to steal from.

dreamy sinew
#

state_attr(...).data[0]

waxen rune
#

That is just brilliant. Thanks.

spiral flax
#

hi, is there a way to send different key-value in the data attribute when I calling a service in an automation action? like:

service: light.turn_on
data:
  {% if trigger.to_state.attributes.bulb_mode == 'color' %}
    brightness: {{ trigger.to_state.state|int }}
  {% else %}
    white_value: {{ trigger.to_state.state|int }}
  {% elif %}

or I need to create separate automation for these two cases?

wet lodge
spiral flax
#

what's the problem with the {{ state_attr('sensor.kitchen_next_timer', 'sorted_active')[0]|select('mapping')|map(attribute='timerLabel')|first }} ?

wet lodge
#

It doesn't return anything.

dreamy sinew
#

Ugg that structure is so weird

#

Need to add [0] before the |select

#

You dropped that from my example

spiral flax
#

For me it works, see the image, that I've sent in private

spiral flax
#

he's state_attr('sensor.kitchen_next_timer', 'sorted_active') stores a string value instead of an object

#

@dreamy sinew is there a way to convert it to an object/array?

dreamy sinew
#

Seems like it's already stored as an object

#

Attributes aren't always converted

spiral flax
#

? {{ state_attr('sensor.kitchen_next_timer', 'sorted_active') is string }} returns true for him

true otter
#

hey phnx I just tried to replicate what you shared , but my icon is going to the default only color. Which by the way was an awesome idea. {%- set motion = {'off': 'green', 'on': 'red', 'true': 'green', 'false': 'red'} -%} {{ motion.get(state_attr ('binary_sensor.motion_sensor_119', 'device_tripped'), 'orange') }} Could I use this same template if I want only to consider the state of the device. Would it maybe look like this ```{{ motion.get(state ('binary_sensor.motion_sensor_119', 'device_tripped'), 'orange') }}?

silk smelt
#

Can someone tell me what is wrong with the following? I get "input_number" undefined.. ``` action:
- service: input_number.set_value
data_template:
entity_id: input_number.running_cost_varmekabler_bad_1etg
value: "{{ (state_attr('sensor.cost_varmekabler_bad_1etg', 'this_day')) | float + states(input_number.running_cost_varmekabler_bad_1etg) | float }}"

silk smelt
#

i gues its some kind of formatting error

#

argghhhh

dreamy sinew
#

@true otter as long as the states you pull match the keys in your dict you can do it

ivory pawn
#

hey there, How can I access the get result from the rest command service in the second service? Thanks

  sequence:
    - service: rest_command.test_get
    - service: input_select.set_options
      target:
        entity_id: input_select.test
      data:
        options: >
           {% ..do some calculations on rest_command.test.get value %}
           {{ list }}```
```rest_command:
  test_device:
    url: "http://xxx.xxx.xxx.xxx/test.json"```
true otter
#

When I removed the attribute part behind state I got an error message

dreamy sinew
#

state_attr() requires an attribute

ivory pawn
#

I dont really want to have a restful sensor as a go between. Is there a way to make a get request in the sequence without using the rest command service, and then also be able to access the get result?

floral lichen
#

How can I edit this to count the day as 9am to 9am instead of midnight to midnight??

    start: '{{ as_timestamp( now().replace(hour=0).replace(minute=0).replace(second=0) ) + (1 - now().weekday()) * 86400 }}'
    duration: '24:00'
thin vine
#

this works:

    start: '{{ as_timestamp( now().replace(hour=9).replace(minute=0).replace(second=0) ) + (1 - now().weekday()) * 86400 }}'
    duration: '24:00'
#

you can check in devtools -> template with:

{{ (as_timestamp( now().replace(hour=9).replace(minute=0).replace(second=0) ) + (1 - now().weekday()) * 86400) |timestamp_local}}
glad geode
#

Is there a square root filter?

#

Or function

proud rain
#

Hi, I'm trying to write a template which includes "e raised to the power of", or EXP(x) in Excel. I've tried exp(x) and math.exp(x) in my template, but am getting the result "Unavailable". Returning (x) by itself works in my code. Is there an equivalent?

glad geode
proud rain
#

@mighty ledge Thanks, shows how much of a newbie programmer I am (didn't know ** meant raise to the power of).

#

Here's my little bit of code - It takes current indoor temperature and humidity and provides a "Feels Like" temperature - based on the Australian Bureau of Meteorology method ```sensor:

  • platform: template
    sensors:
    citypad_feels_like:
    value_template: >-
    {% set t = states('sensor.citylink_temperature') | float %}
    {% set rh = states('sensor.citylink_humidity') | float %}
    {{(t+rh/100e**(17.27t/(237.7+t)))}}```
glossy viper
#

real feel is very triky to find out

proud rain
#

BOM has a good writeup here: http://www.bom.gov.au/info/thermal_stress/?cid=003bl08&fbclid=IwAR2ycHTHeuK5eD2uFqoBMjHmbNX9GEwpDa3Owjhxy9arcOOmB4L5KjwdfQM

glossy viper
loud otter
#

Hi all, can someone please explain me how set_white_value works ? looking at docs I read this : Integer between 0 and 255 for how bright a dedicated white LED should be. but then i logs i see an error message looking for hue values.

mighty ledge
burnt solstice
#

can someone help me with my template

#
  • platform: template
    sensors:
    front_door:
    friendly_name: "Front Door State"
    value_template: >-
    {% if is_state('light.front_door', 'Unavailable' ) %}
    Off
    {% elif state_attr('slight.front_door', 'Off') %}
    Off
    {% else %}
    on
    {% endif %}
glossy viper
#

what is slight.front_door ?

burnt solstice
#

Oh man

#

Typo

#

I am guessing thats the problem. I want to have it so if my front door light is off or manuelly turned off by the light switch, i want it to say off and not unavaliable

glossy viper
#

πŸ™‚

#

also try to see if in developer tools if state is Off or off πŸ˜›

burnt solstice
#

ok, sounds good

#

But Adrian if i update those things, would that work ?

glossy viper
#

u verified?

#

restarted?

burnt solstice
#

it work

teal umbra
#

which channel to ask for help with a binary sensor / mqtt reading a topic?

floral lichen
#

Anyone have some premade templates for displaying history stats from last week / month etc. ones with a drop down or date selector would be super nice πŸ™‚

proud rain
#

Newbie programming question: {{t+rh/100*e**(17.27*t/(237.7+t)) | round(2)}} The first part of this is producing a float, I was hoping to round that to 2 decimal places with the second command. But I am still getting lots of decimal places. What am I doing wrong?

proud rain
#

Thanks rawframe. In the end this worked: {% set t = states('sensor.citylink_temperature') | float %} {% set rh = states('sensor.citylink_humidity') | float %} {% set rf = t+rh/100*e**(17.27*t/(237.7+t)) %} {{rf | round(2)}}

turbid orbit
#

Howdy folks. Running into some issues with templates. I copied this verbatim from the input_datetime integration page but am getting an error that I can't seem to figure out. Beta channel btw.

service: input_datetime.set_datetime
target:
  entity_id: input_datetime.XXX
data:
  timestamp: "{{ now().timestamp() }}"

Error:

Failed to call service input_datetime/set_datetime. expected float for dictionary value @ data['timestamp']
turbid orbit
#

I'm just trying to set this input helper to "ten minutes from now"

thin vine
#
  service: input_datetime.set_datetime
  entity_id: input_datetime.XXX
  data:
    timestamp: "{{ now().timestamp() }}"
turbid orbit
#

Turns out it's not working in Developer Tools > Services but does work in a script 🀷

thorny snow
#

I'm trying to set up a toggle button that looks at the colour state of the bulb and and if its red, change to blue, if blue to red. I came across someone else talking about it,

entity_id: light.the_study_lamp

color_name:  >
 {% if is_state_attr('light.the_study_lamp','rgb_color',(255,0,0)) %} blue
#

Im a bit confused

mighty ledge
cinder gale
#

I'm using a template variables in an automation and it's not working for me, is this the right place for this?

#

I'm using variables in an automation but when I reload the automation I get not a valid value for dictionary value @ data['action'][1]['target']['entity_id']. Got None.

dreamy sinew
#

what are you using there?

cinder gale
dreamy sinew
#

share what you actually have

cinder gale
#
- id: handle_tag_scan
  alias: "Handle Tag Scan"
  mode: single
  # Hide warnings when triggered while in delay.
  max_exceeded: silent
  variables:
    # Map scanner device ID to media player entity ID
    media_players:
      3ac9a05c3c08687bf11ee545ba78aabb: media_player.a_room
    # Map tag ID to content
    tags:
      F9-FB-3C-B2:
        media_content_id: "https://www.youtube.com/watch?v=rLdpprJ3jeE"
        media_content_type: music
  trigger:
    platform: event
    event_type: tag_scanned
  condition:
    # Test that we support this device and tag
    - "{{ trigger.event.data.tag_id in tags }}"
    - "{{ trigger.event.data.device_id in media_players }}"
  action:
    - variables:
        media_player_entity_id: "{{ media_players[trigger.event.data.device_id] }}"
        media_content_id: "{{ tags[trigger.event.data.tag_id].media_content_id }}"
        media_content_type: "{{ tags[trigger.event.data.tag_id].media_content_type }}"
    - service: media_extractor.play_media
      target:
        entity_id: "{{ media_player_entity_id }}"
      data:
        media_content_id: "{{ media_content_id }}"
        media_content_type: "{{ media_content_type }}"
    - delay: 2 # timeout before we allow processing next scan
#

if there's a better place to share lmk

#

if I hard code the target line with entity_id: media_player.a_room everything works

#

this error occurs at automation reload time, not event fire time, so there isn't actually a trigger.event.data at that time (I think?)

dreamy sinew
#

i have never used that so i don't know

cinder gale
#

so this has two layers of variables it would seem the even data provides trigger.event.data.device_id but I need to use that value to then look up the media_player.a_room

#

but that data isn't available until "event time", but the action.target.entity_id is parsed and required at automation load time

cinder gale
#

I've tried to put maaaany things in the place of action[1].target.entity_id and it always says it evaluates to None

#

even things that hass guarantees to give me, e.g. "{{ trigger.event.event_type }}" or "{{ trigger.platform }}"

#

why won't it accept any variable there?

#

I've stripped this down to be a lot simpler now it's

#
- id: handle_tag_scan
  variables:
    # Map scanner device ID to media player entity ID
    media_players:
      3ac9a05c3c08687bf11ee545ba78aacc: media_player.a_room
    avar: media_player.a_room
  trigger:
    platform: event
    event_type: tag_scanned
  action:
    - service: media_extractor.play_media
      target:
        entity_id: "{{ avar }}"
      data:
        media_content_id: "https://www.youtube.com/watch?v=rLdpprJ3jeE"
        media_content_type: music
dreamy sinew
#

looks like variables are not a part of automation directly? seems like they're a script thing so they'd only be valid in the action block

#

nope, that's wrong

#

i don't know how those work though

mighty ledge
#

I'm pretty sure the target is not templatable until the release

mighty ledge
#

remove target

#

if you're in release of HA, target cannot be templated. If you're in the beta, you need to have the beta release that has the PR for templating in target.

teal umbra
#

where to ask question / help with a custom binary sensor / mqtt

#

trying to make custom sensor on which person is at home
Mqtt topic is

Message 2 received on ai/Living_hd/motion at 8:47 PM:
Person [MyName] (56%)

Message 3 received on ai/Living_hd/motion at 8:55 PM:
Person [MyGirlfriendsName] (88%)

How do i read the name only?

cinder gale
#

@mighty ledge thanks, yes I also learned that it's not yet supported but in the next release it will be and that is excellent!

#

@mighty ledge and @dreamy sinew ty both!

autumn pasture
#

Hello! I have a question: How can I assign a latitude and longitude value to a non-tracking sensor so it shows on my map in the dashboard?

glossy viper
#

@autumn pasture based on what?

autumn pasture
#

i have a sensor and i want it to show on map

#

it is a sensor that gets its value from mqtt

glossy viper
#

make a zone for it

autumn pasture
#

oh!

#

nice

#

ok let me show you something

#

sensor tempcamp:
platform: mqtt
state_topic: '/devices/192.168.1.125/ai/1'
name: 'Temperature Camp'
#device_class: "temperature"
#qos: 0
#latitude: 47.6438

longitude: 67.3432

unit_of_measurement: 'Β°C'
value_template: '{{ (((value_json * 120)/10000) - 40) | round(2) }}'

#

you see where a entered the latitude and longitude ...

#

i doest not work liket that . where do i had the zone for that

glossy viper
#

in map - add zone

#

and u put lat/long for that zone

autumn pasture
#

i have created the zone ! yes i works ! i have it on the map now

#

how to connect my sensor to that zone now?

glossy viper
#

define template as {{ state_attr('zone.xxx','latitude') }}

autumn pasture
#

Thanks man!

echo siren
#

Im trying to get one of my templates to work where I use a utility_meter to calculate daily and monthly energy usage. I have several MQTT kwh meters. I have one for the total usage and that works. I have other that are connected to spa bath and heating. I wish to use the total – spa - heating to calculate the home household energy usage. I just cant get it to work, its always the same as the total house even tough that I tried different ways to calculate it:
huhallsel_total_kwh:
unit_of_measurement: 'KWh'
value_template: >-
{% set vattenfallkwh = states('sensor.vattenfall_total_kwh') | float %}
{% set ivtkwh = states('sensor.ivt_total_kwh') | float %}
{% set daikinkwh = states('sensor.daikin_total_Kwh') | float %}
{% set qlimakwh = states('sensor.qlima_vp_Total_Kwh') | float %}
{% set spakwh = states('sensor.spabad_total_kwh') | float %}
{% set value = ( vattenfallkwh - ivtkwh - daikinkwh - qlimakwh - spakwh ) | round(1) %}
{{ '{:.1f}'.format(value) }}

Each sensor has a correct value but the total is always the same as vattenfallkwh for the utility_meter

inland hazel
#

@echo siren What is the output of {{ value }}? (You can use the Template under Developer Tools to test your templates.)

echo siren
inland hazel
#

@echo siren What is the output of the following template:

vattenfallkwh: {{ states('sensor.vattenfall_total_kwh')|float }}
ivtkwh: {{ states('sensor.ivt_total_kwh')|float }}
daikinkwh: {{ states('sensor.daikin_total_kwh')|float }}
qlimakwh: {{ states('sensor.qlima_vp_total_kwh')|float }}
spakwh: {{ states('sensor.spabad_total_kwh')|float }}
echo siren
inland hazel
#

Try taking out ivtkwh and see what value returns.

echo siren
echo siren
inland hazel
#

8020.6 is what I calculate based on the values you gave above.

#

What is vattenfall_total_kwh compare to huhallsel_total_kwh?

inland hazel
echo siren
slate tundra
#

how do i make this update every minute instead of seconds and give a result in minutes instead of secons
{{ (as_timestamp(strptime(states('sensor.cert_expiry_timestamp_domain_name'), "")) - as_timestamp(now()))|round(0) }}

#

or hours

#

even better

lethal dawn
#

anyone got any secret way to convert color_xy into color_hsl for a template?

undone jungle
#

Dear all, I am seriously struggling with getting my cover (i.e. garage door). I've gone over documentation, examples, threads and the darn garage door won't budge.

#

My current cover config above - the doors are operating a Satel alarm integration to initiate movement of the gate.

#

There is a single binary sensor detecting the state. No position detection

autumn pasture
# glossy viper define template as {{ state_attr('zone.xxx','latitude') }}

Hey .. we have added ' attribute template' ... and it worked for sensor that are declared under platform template but it doesnt work for sensor under platform_mqtt... here is the code we created for platform template sensor: sensor:

  • platform: template
    sensors:
    analog_input_5:
    friendly_name: "Analog Input 5"
    value_template: '{{ states.sensor.hidden_current_state.attributes["CurrentState"]["AnalogInput"][4]["Measure"].split(" ")[0] }}'
    unit_of_measurement: "Β°C"
    attribute_templates:
    latitude: '47.649328'
    longitude: '-67.412194'
undone jungle
#

The doors are operating just fine from the alarm level and when operated from external buttons and/or apps, the position detection in HA is updated correctly

#

The Satel integration also properly detects motion in the house, as well as all the binary door sensors, so I am fairly confident it's working correctly.

autumn pasture
#

but for sensor under platform_mqtt i can find the formulation to add the longitude and latitude attribute : sensor temptrailer:
platform: mqtt
state_topic: '/devices/192.168.1.120/ai/0'
name: 'Temperature Trailer'

attribute_templates:

longitude: '47.613777'

latitude: '-67.417687'

unit_of_measurement: 'Β°C'
value_template: '{{ ((value_json * 50)/10000) | round(2) }}'

mighty ledge
#

@vestal idol use #frontend-archived, that's not a templating question. Also please don't post codewalls.

vestal idol
undone jungle
#

Any help would be greatly appreciated! πŸ™

strange agate
undone jungle
#

Pressing either if the buttons for this cover results in no action from the garage doors

#

Can you confirm my syntax is correct?

strange agate
#

so your switch.garage_door actuates your garage door? is it momentary, or does it turn on when open and off when closed?

undone jungle
#

It's supposed to be momentary, but it's a class switch

#

I currently have it as

entities:

  • entity: cover.garage_door
    show_header_toggle: false
    type: entities
    title: Garage
    state_color: true

In Lovelace and the icon properly follows the state of the door but the card doesn't actuate it.

strange agate
#

although I suppose you could change to type: button if you want it to pop up the cover dialog

#

then when you click on it, the cover details should pop up, and you can open/close/stop

undone jungle
#

I'll try playing with action types and button, but not sure if it will work.

#

Thank for the help so far!

timber locust
#

Hey guys! Is the command for a command line switch templateable? I'd like to make a timelapse from camera snapshots using this template but I'm getting an error.

  create_timelapse_from_jpgs: 
    command_on: >-
      ssh -i /config/.ssh/id_rsa -o StrictHostKeyChecking=no -q
      root@192.168.1.252
      find /usr/share/hassio/homeassistant/www/snapshots/{{ (as_timestamp(now()) - (24*3600)) | timestamp_custom('%Y-%m-%d', True) }} -empty -type f -delete &&
      ffmpeg -framerate 60 -pattern_type glob -i "/usr/share/hassio/homeassistant/snapshots/{{ (as_timestamp(now()) - (24*3600)) | timestamp_custom('%Y-%m-%d', True) }}*.jpg" -c:v libx264 -crf 24 -pix_fmt yuv420p /usr/share/hassio/media/timelapse_{{ (as_timestamp(now()) - (24*3600)) | timestamp_custom('%Y-%m-%d', True) }}.mp4
#

Basically I want to run ffmpeg on all the snapshots created yesterday. These are located in /snapshots/2021-03-01. But that changes every day of course.

undone jungle
#

@strange agate I've made great progress, since both the garage door and main gate open - the issue was a combination of inconsistent documentation for the integration and setting up switches appropriately.

#

One last thing that doesn't work is the cover implementation in Lovelace

#

The up botton works just fine

#

So does the middle one, for both stopping, opening and closing

#

But then the gate is open the down button doesn't work

strange agate
#

if your switch is a momentary, you may need to change the entity to switch.turn_on for the close_cover

#

assuming it just turns the switch on every time the garage is actuated

undone jungle
#

Correct, it's just a 2 second momentary MONO on the alarm side.

strange agate
#

right, so it would be a "on" then instead of an "off" like in your code you posted

undone jungle
#

Right, I didn't spot that

#

Absolutely makes sense!!

#

Thank you so very much for the input.

#

I am so loving HA and the community. Learning so much every day.

#

It's 2 am and I am still excited playing around with the code #crazy!

strange agate
#

yup, same πŸ˜„ it's a blast haha

undone jungle
#

Last thing - is there an option to set up a 'universal' button icon, since all my 3 are actually the same thing

#

I could forgo the stop for sure, by deleting it from the config

#

I wonder about switching to just stop or if another one exists for a universal 'click' in the cover template

strange agate
deep yoke
#

has anyone written a sensor or template to display whether there are updates (to the images) of the containers used by HA (including HA itself) ?
I'd like to see when there's an update for my containers (HA, nodered, etc.) , and then read to make sure no breaking change and then update

wicked ferry
#

I’ve spent hours reading up on how to do this and I cannot figure it out. I’ve only been using HA for about two weeks. Here is what I’m wanting:
A switch that flips when any of the sensors on my litter bots read above 95 full. I’ve tried virtual sensors, virtual switches, IF then conditions and I cannot get it to work. I would paste my code in here but I think with my frustration it’s turned into gibberish. Where should I start please? (Also first time HA discord) thanks in advance!

alpine pelican
#

That's how you can get the value of the latest version if the project in question releases versions... Some don't.

#

For HA itself, there is already a sensor for that: updater.

deep yoke
#

thank u this is golden! now i need to figure out how to pull the container version (for instance mosquitto or nodered), is a shell command the only way to bubble this back up?

alpine pelican
#

that one's tough. I ended up going with running a script that I wrote on the host system that runs this (/usr/bin/docker logs vscode 2>&1 | awk '/] info code-server [0-9]/{print "{ \"version\": \"" $4 "\" }"; exit}' to store that in a variable that gets published to mqtt. Then I have a sensor in HA that monitors that topic in mqtt (software_versions/vscode is the topic).

#

The script loops through a bunch of the software I run and publishes the versions of each of the packages to mqtt. So I have "PACKAGE_version" and "PACKAGE_latest_version" and if they're not the same, I get notified.

deep yoke
#

ah thats a smart solution, verbose but def does the job

#

so u have the script running on a regular cron job i imagine?

alpine pelican
#

yeah... like every hour or something.

#

or every 15 minutes, actually.

deep yoke
wind peak
#

When using this: wait_template: "{{ is_state('media_player.floor', 'stop') }}"
How could I modify that template to to make sure the state is stop for at least 10 seconds?
(I want the automation to wait until a certain state changes for at least 10 seconds as an example)

dreamy sinew
#

probably a separate automation that flips a input bool to true when the media player goes to stop for 10s

wind peak
#

Mhm, okay.

dreamy sinew
#

would need to have something to reset it though

inland moat
#

Hello there! I have some weird error with the developer-tools -> Template function... somehow the preview on the right side is not working anymore. Top right loading animation spins forever. What could be wrong here?

#

oh no... nevermind... cache problem 😦

rich oar
#

Hello, let's say I have defined a template sensor, collecting room temperature once every second.

Then I change the name of the said sensor in my config file. What happens to the data collected with the old name? Does that remain in the database somewhere as a piece of junk, or is the corresponding data deleted with my sensor name change?

glossy viper
#

will remain in database

#

untill purge_days of your recorder reach target

rich oar
glossy viper
#

depending on what database u rely on

#

influx, maria, sql...etc

rich oar
#

Hmm I'm not sure. Is there a default? I don't think I've specified it anywhere...

glossy viper
#

default is... documentation

rich oar
#

Point taken! πŸ™‚ Thank you

wicked ferry
#

I have spent hours and hours. I cannot figure this out. I have three sensors: sensor.hallbot_waste_drawer
sensor.bar_bot_waste_drawer
sensor.catroom_bot_waste_drawer

If anyone of them is about 95 in value I want the virtual switch anylitterfullswitch to be turned on. If none of them are above 95 I want it off. Here is what I have. I thought I was so close but I get this error when I check it's status as "unavailable."

Here is my code (PLEASE help me):
switch:

  • platform: template
    switches:
    anylitterfullswitch:
    value_template: "{{ (states('sensor.hallbot_waste_drawer')|int > 90),
    or (states('sensor.bar_bot_waste_drawer')|int > 90),
    or (states('sensor.catroom_bot_waste_drawer')|int > 90)}}"
    turn_on:
    service: switch.turn_on
    target:
    entity_id: switch.anylitterfullswitch
    turn_off:
    service: switch.turn_off
    target:
    entity_id: switch.anylitterfullswitch
unreal merlin
#

Greetings πŸ™‚

#

Can I regex_match a variable in templates?

#

for example: {% if rooms_to_clean|regex_match("^"myvar"$|,") == true %}yes{% endif -%}

dreamy sinew
#

maybe?

#

try it out in the template tester

#

there are some regex methods exposed which can be found in the docs

unreal merlin
#

trying but can't really find a way around that string and variable concatenation

dreamy sinew
#

oh

#

'*{}$|,'.format(myvar)

ornate storm
#

I am trying to implement a test sensor with the following value template
value_template: '{{ value_json.24hreward }}'
but that doesnt work because there are number in that
This would work but its not what I need
value_template: '{{ value_json.reward }}'
can somebody tell me what syntax I need to use to get numbers to work here?

strange agate
#

@wicked ferry do you have a switch.anylitterfullswitch entity? from what I understand, you want to create something along the lines of input_boolean helper and then use your switch to reference it.
(or binary sensor in this case might be more helpful since you won't plan on toggling it manually)

ornate storm
dreamy sinew
#

eh, type of quotes isn't important

#

"{{ value_json['24hreward'] }}" is equivalent

#

value_json.get('24hreward') would also work with the added benefit of not throwing a value-error on miss

ornate storm
#

yes my bad but you need quotes inside the brackets

#

thats what I wanted to say :)

gaunt vector
#

{{ states['media_player.spotify_jon_graft'].state }} returns playing. How do I return the track name & artist that is actively playing?

gaunt vector
teal umbra
#

i would like to make a binary sensor to see who is at home
Therefore I've configured my camera's with face detection which sends mqtt messages

The topic contains ai/Default/motion Person [Eric] (91%),Person [Nick] (84%),Person [Finn] (78%),Person [Luke] (87%),Potted plant (79%) "

What is my best way to strip these names? I don't need to know if the potted plant is at home πŸ™‚

#

Dont know really where to look since all tutorials i find about mqtt is how to send messages

wicked ferry
#

@strange agate thanks so much for help! I’ve tried adding a virtual switch and also tried adding a helper. Still cannot get it to give me anything beyond unavailable.l for switch state. Any other ideas? Thank again!

devout badge
#

So I'm going a bit crazy with the template engine. I'm not entirely sure what it is, it seems specific to the MQTT climate module - that appears to, as best I can tell from the source, use the "async_render_with_possible_json_value" method to render the template for the temperature command, which strikes me as weird as that seems more designed to process input, not render a command. More importantly, it's kind of broken - after I'd finally figured out they used this and the target temperature was therefore "value_json" and not a more helpful name, I tried to make it work to render a very simple JSON to push out to MQTT - namely, "{"action":"set","value": {{value_json|float}} }". When I leave it without that template section it correctly sends out the JSON, obviously without anything filled in, but as soon as I add the value_json|float it only throws the number to MQTT, dropping the entire rest of the template. I'm kind of running out of ideas and sanity here, am I doing something stupidly wrong?

#

I've gone so far as even trying to have the {{}} at the top level and use Jinja string concatenations but somehow even that works exactly until I cast value_json to a float - if I leave that out or don't convert it (resulting in a null as far as I can tell) the entire thing renders fine but as soon as the number comes in everything else disappears.

#

Okay, so now I have even more questions. I dug further into the code that Home Assistant actually uses to parse these templates, and apparently it also exposes a "value", in addition to "value_json". And guess what, when you use value instead of value_json|float it suddenly renders properly! I have no idea why that even makes a difference, and I really don't know why the climate module uses this version of the template renderer in the first place instead of one with named variables, but honestly I'm mostly hoping somebody can add this to the documentation page for the Climate/MQTT module so other people know to use "value" and not lose an hour of their life thinking they're going crazy like me.

mighty ledge
#

@devout badge All templates render objects as real values after the template is complete. Most likely your resulting type was wrong or malformed

#

Use the template editor next time and make a value_json variable that represents the json that would have been passed and you can see how the template will be rendered

#

Also, all value_template fields in configurations have 2 variables: value and value_json. This has been this way for a very long time.

#

Usually the examples cover this. Otherwise you’re welcome to make changes to the documentation yourself

devout badge
mighty ledge
#

Yes you can’t return a dict

devout badge
mighty ledge
#

You have to return json

#

|tojson

#

That’s an mqtt thing

devout badge
#

Weirdly enough I'm still not doing that.

#

And it works now

mighty ledge
#

No but keeping it value keeps the object in tact

devout badge
#

The only thing I changed was now I use value instead of value_json|float

#

Oh.

#

Okay, so that still leaves two things that confuse me: a) it seems most other modules use named variables in their command templates, not the generic "value", and b) the fact that the Climate module seems to have so little documentation confirmed to everything else. There is literally not a single command template example other than a single one for reading mode_state that is literally just "{{ value_json }}".

#

How would one go about writing more examples? How is this doc generated/edited?

devout badge
# mighty ledge |tojson

Also now that I think about it, why/how does that dict turn into a single number? That seems like a very weird failure mode.

mighty ledge
#

Yes named variables are everywhere

devout badge
mighty ledge
#

Which template field are you talking about

devout badge
#

temperature_command_template

mighty ledge
#

Probably an oversite

devout badge
#

Anyway, the lack of documentation and examples around that made it kind of hard to even figure out what variable to use, and when I thought I'd figured that out obviously I ran into that issue with it becoming a dict.

mighty ledge
#

You’re welcome to make edits to the page

mighty ledge
#

There’s a β€œedit” at the bottom of the docs page

devout badge
#

Nevermind I just realised

#

I didn't see that because I wasn't scrolled all the way down

mighty ledge
#

You can also just provide feedback

devout badge
#

Guess I'll suggest better examples now, specifically around these templates, and maybe I'll come back later and write some myself if I have the time

strange agate
deep yoke
#

hi

worldly rampart
#

Hi. I know this is probably pretty basic so please forgive me (I'm new to HASS and still getting my head around the nomenclature).

I have 20-odd CCTV cameras which publish to an MQTT topic when they detect motion. cctv/+/motion (where the wildcard is the name of the camera). Payload is a JSON string containing some info about the detection.

Is there a way I can have HASS auto-generate entities & sensors for all these cameras automatically when they publish vs setting up entities & sensors manually for each?
Not a big deal if it can't but figured it'd be something that would be possible.

....Is templating how I'd accomplish this or am I completely barking up the wrong tree.

#

NB. I'm aware of MQTT Discovery, but not sure whether that would be useful in this context.

sonic nimbus
#

Hello, why Im getting an error 'UndefinedError: 'device_tracker' is undefined' when I add this to my template sketch: {{ states.device_tracker.stefans_iphone.last_chaged }}

#

even if I add only {{ device_tracker.stefans_iphone }} it has the same error

mighty ledge
mighty ledge
sonic nimbus
#

oh I see..thanks!

#

and how to set two random entities for covers

#

here is random entitiy for one

#
      data:
        position: >
          {{ range(20,100)|random }}
        entity_id: >
          cover.{{ ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] | random }}
#

so if I wrote something like this ```
- service: cover.set_cover_position
data:
position: >
{{ range(20,100)|random }}
entity_id: >
- cover.{{ ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] | random }}
- cover.{{ ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] | random }}

#

How to be sure that HA wont pick two same entities?

mighty ledge
#

I’m not at a computer so maybe someone else can type it out

#

But you need to return a list.

#

First make the list, then select a random one, then filter the selected one out of the list and select a second random one

#

set first = Mylist | random
set second = Mylist | reject(first) | random

#

{{ [ first, second ] }}

wicked ferry
#

I want to measure the time since status change on a door contact sensor. I have it working but everytime I reboot HA server it sets it back to zero. What's the best way to have the time since sensor change hold through a restart of HA server? Thanks in advance!

mighty ledge
thorny snow
#

Hey all. During the release party live stream I noticed this on the release notes: Templates can now be used to create weather entities. So far I haven't been able to find any docs on what the weather entity should look like, and how to template it. Does anyone have any idea?

wise arrow
#

I seem to have soiled myself

mighty ledge
sonic nimbus
#

thanks petro, I will try

#
{% set covers = ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] %}
{% set first = covers | random %}
{% set second = covers | reject(first) | random %}```
#

Im getting an error TypeError: object of type 'generator' has no len()

#

If i remove last row, and just print {{first}} it gives me ok result, so I guess there is some error in the last row?

sonic nimbus
#

I think I found solution {% set covers = ['ds_l', 'ds_s', 'ds_d', 'ss_l', 'ss_d', 'rs_l', 'rs_d'] %} {% set first = covers | random %} {% set second = covers | reject('==',first) | list | random%} πŸ™‚

young shadow
#

Hi guys, is it possible to use the jinja abs() to get the absolute value from a number? Template editor threw an error to this:
{{ abs((states('sensor.daily_covid_cases') | int) - (states('sensor.daily_covid_cases_yesterday') | int)) }}

Update: Figured it out
{{ ((states('sensor.daily_covid_cases') | int) - (states('sensor.daily_covid_cases_yesterday') | int))|abs }}

frank gale
#

hey there! Am I the only one who gets messed up Automations and Script because of the GUI introduced on 2021.3.0? It seems that it wipes out the templates that doesn't recognise and if you want to change something in the Automation or Script and then save, you got a messed up one...

hard swallow
#

Hi Im on 2021.3.2 and cant do backups either manually or automated. Always say system is in freeze state

glad geode
#

Hey, is there a way I can get the length of time an entity has been in its latest state from a template? I suppose other than having an sql sensor to get the time between the last 2 entries of said entity in the states table

plain trellis
#

One way would be to have an automation trigger on the state change and save the current time, so later you can do some math to get the duration. (I have not tried this. but I thing it should work)

mighty ledge
#

Also, on a standard entities card, you can display secondary info, and one of the pieces of info is the last time the state changed

#

And you can expose last_changed in a template sensor with device class timestamp and the front end will properly calculate the relative time on most cards

mighty ledge
glad geode
mighty ledge
#

It’s on the state object itself

glad geode
#

Ah, ok. So how would I pull that out? states('entity').last_changed? or would it have to be states.domain.entity.last_changed?

mighty ledge
#

states.domain.object_id.last_changed

arctic sierra
#
notify:
  - name: gmail
    platform: smtp
    server: smtp.gmail.com
    port: 587
    timeout: 15
    sender: email@gmail.com
    encryption: starttls
    username: email@gmail.com
    password: password
    recipient:
      - email@gmail.com
    sender_name: My Home Assistant
#

Setting up email notifications and I'm getting the error "component not found: notify." anyone know how to fix this?

thorny snow
#

Hi! How do you guys debug your templates? I have a template which looks fine in Developer Tools/Template, but can not be used as-is within the weather template I'm trying to build - I think due to escape issues which I think I have fixed, but how can I e.g. see the result of instantiating my template? I could post more info on my particular problem, but I am more interested in how problems like this are to be debugged in general...

sterile storm
#

How could I get the sun's next_rising and the next_setting in relative time?
I've tried The sun will set in about {{ relative_time(state_attr("sun.sun", "next_rising")) }} πŸŒ…

#

But that shows 2021-03-08T06:11:24+00:00

wicked ferry
#

So, I think after hours I got my mqtt up and running. I'm trying to show on a card the time since last sensor change. I got it to work but its returning a value that's not user friendly. How do I convert this:
2021-03-07 18:55:59.269596-06:00
Into something useful?

sleek rain
#

Since you don't say the exact desired format, start with this: {{ as_timestamp(mytime) | timestamp_custom('%D %-I:%M %P') }}

wicked ferry
#

Thanks so much. How might I change it to time days hours minutes since that time stamp above? That's actually what I really need.

#

Do I put that in the configuration file under this?

#

sensor:

  • platform: mqtt
    state_topic: "events/clarkmeowspace/on"
    name: "MQTT ClarkMeowSpace"
inner mesa
#

you create a template sensor

wicked ferry
#

Is that wrong? Sorry. I'm new to this and I spent hours to get this to work.

#

I'm trying to preserve time since sensor change and make it last a HA reboot.

sleek rain
#

Put it into sensors value_template field

wicked ferry
#

That's something new fo rm.e

inner mesa
#

your mqtt sensor is fine. if you want to use a template to further manipulate that value to represent something else, you would just a template sensor

wicked ferry
#

Thanks

#

Awesome.

#

Thanks so muchQ!

#

much!!!

wicked ferry
#

Thank you!

wicked ferry
#

this seems to work in the developer tools template but cannot get it to work in the config. Any help?
clark_meowspace_last_changed:
value_template: "{{relative_time(states.sensor.mqtt_clarkmeowspace.last_changed)}}"

Tools Template Result:
clark_meowspace_last_changed:
friendly_name: 'Clark Last In MeowSpace'
icon_template: mdi:clock-outline
value_template: "18 minutes"

When I check the config file I get this error:
Error loading /config/configuration.yaml: while scanning for the next token
found character '\t' that cannot start any token
in "/config/configuration.yaml", line 63, column 1

inner mesa
#

Get rid of your tab

#

That’s what \t is. Only spaces

wicked ferry
#

Wow...crap. Thanks

#

Really appreciate the help

brisk nebula
#

Hi everyone, I have a template sensor that infers value based on relative last_updated attributes of two other sensors. Is there a way to preserve its value between restart of HA?

unreal merlin
#

Howdy πŸ™‚ I'd like to build a template sensor that shows some data about the access point a mobile device is connected to. To achieve this, I need to hardcode a hash map of some sort with data like: aa:bb:cc:dd:ee:ff: Living Room 5GHz AP (mac_address: ap_info).

#

What's the best way to store config data like this? Input_text is not an option as that's limited to 255 chars and I've got ~300. So I was thinking building a template sensor, using the mac addresses as attributes, and "attribute values for "ap_info" - but that seems to be returning "None".

#

likely the simplest thing to do would be to build a template sensor with a state that's JSON, serialize it and use as is - but before I jump into that rabbit hole: is there a better way of doing this I wonder?

coarse tiger
#

@unreal merlin

unreal merlin
#

great, thanks

wicked ferry
wicked ferry
#

I have a sensor that is giving me the time that an event happened:
2021-03-08 05:57:30.267209-06:00

How do I turn this into hours minutes from current time? If the time stamp was for 10 minutes ago, I want the output to say 10 minutes ago or something similar. I'm flexible I just need this time since that timestamp and have it update when I use on a card. I've spend so much time figuring this out using mqtt. I just cannot take it home. Thanks in advance!

fossil totem
#

pulling what's left of my hair out trying to catch a trigger event from mqtt which has a json-formatted payload but for reasons i don't want to parse it out as JSON

#

in my automation, for debug purposes i have the following:

#
trigger.payload: {{trigger.payload}} - buttonjsonpayload: {{buttonjsonpayload}} - trigger.payload == buttonjsonpayload: {{trigger.payload == buttonjsonpayload}}
#

spitting that out to MQTT i see the following:

#

trigger.payload: {"event_type":"button_short_release","event":"p[1].b[5]","value":"OFF"} - buttonjsonpayload: {"event_type":"button_short_release","event":"p[1].b[5]","value":"OFF"} - trigger.payload == buttonjsonpayload: False

#

so, i have two values trigger.payload and buttonjsonpayload. this is in the context of a blueprint, buttonjsonpayload is created in the variables: section. When sent to MQTT, both value render to matching strings. when compared, they don't.

#

casting both to string (like {{trigger.payload|string == buttonjsonpayload|string}}) doesn't change the outcome

chilly quartz
#

Hello all, is there a rule somewhere that states an entity ID cant start with a number? or am I doing something wrong?

#

{{ states.sensor.5in1_temperature.state }} and inside set temp is {{ states.input_number.climate_set_temp.state }}

#

returns TemplateSyntaxError: expected token 'end of print statement', got 'in1_temperature'

dreamy sinew
#

dot walking doesn't work with vars that start with a number

#

states.sensor['5in1_temperature'].state would work

#

or states('sensor.5in1_temperature')

spiral imp
#

How can I combine this into one?

  - platform: template
    sensors:
      smoke_detected:
        friendly_name: Smoke Detected
        value_template: >-
          {{ is_state('sensor.smoke_detector_main_alarmlevel','1') 
            or  is_state('sensor.smoke_detector_main_alarmlevel','2') }}
dreamy sinew
#

{{ states('sensor.smoke_detector_main_alarmlevel') in ['1', '2'] }}

spiral imp
#

i figured it was simple, thanks

buoyant minnow
#

Hi! Is it possible to get the current icon of an entity? I cannot find it as an attribute.

pseudo ember
#

i have problems with json api tat returns numbers as string eg. "1.17" its a list i want to use the list | sum for mothly statistics

[{ "id": 301, "day": "2021-01-02", "electricity1_cost": "1.17" }, { "id": 302, "day": "2021-01-03", "electricity1_cost": "0.90" }]

#

what would be the easy way to convert the numbers to float ?

dreamy sinew
#

|map(attribute='electricity1_cost')|map('float')|sum

#

could try dropping the float map and see what happens though

pseudo ember
#

awsome πŸ˜„

#

its working flawless, thanks @dreamy sinew

carmine aspen
#

Hey all, trying to work in a value template into a numeric condition for above but it doesn't seem to take it. Anyone have any ideas? https://hatebin.com/agukapwrap

inner mesa
#

you have a typo in your URL, and fixing it leads to a blank page

pseudo ember
#

is there a simple way to add or subtract x months from {{ now() - 6months }} {{ now() + 3months }}

dreamy sinew
#

timedelta()

#

you can offset by days or weeks

trail estuary
#

Is it possible use templating to catch all sensor states of a certain measurement unit? Say i want to sum all consumption values where the unit is kWH?

marble jackal
marble jackal
earnest cosmos
#

Is there a way to set a state for a binary_sensor if conditions are met, say for 60 seconds or more? This for my illuminance sensor telling if it is dark outside (to turn on lights)

#
binary_sensor:
  - platform: template
    sensors:
      dark_inside:
        friendly_name: MΓΈrkt innendΓΈrs
        value_template: "{{ states('sensor.pir_ute_paviljong_illuminance')|float < 700 }}"
glossy viper
#

sun elevation could be better

earnest cosmos
#

Sun elevation do not take into account how much light is emittet all through the year.

#

Especially will this come to play at 60 degrees north where I live. Where the sun sets at 22:00 and rises at 03:30 in the summer, and in winter.... πŸ™‚

#

So after testing over some years I find illuminance to be the most accurate method

glossy viper
#

so take straight measurement from sensor

earnest cosmos
#

I do, but when there is a glitch form the sensor, eg. reporting wrong value the light automation will fire. So I will have to work around this, and was hoping the sensor state could be set somehow after the state was below the trheshold for some time.

glossy viper
#

in automation u can put a time condition if luminance drops under your threshold

trail estuary
#

Can a template sensor generate new sensors? Say from a list?

undone knoll
#

Hi All. Could some template guru please help me change the state text in an entities card. I have been puzzling over this for hours. I'm afraid the entry bar is still too steep for me at the moment... https://paste.ubuntu.com/p/VH7kngM3Pt/ mindblown

trail estuary
#

So, if I have 25 sensors I want to do calculations on, there is no way around templating every single one of them?

trail estuary
#

#feature-idea 🀣

mighty ledge
#

You can use the template editor to write the code for you

trail estuary
#

Really?

mighty ledge
#

Yep

trail estuary
#

Link to learn how?

mighty ledge
#

That’s going to change depending on what you’re trying to do

#

There’s no real learning page

silk smelt
#

Hi all! I am looking for some help with utility meters. I have some floor thermostats that sometimes report crazy kwh usage that messes up my history graphs so I need to "wash" them. Is there a way I can do this with templates? pass the kwh sensor through a template which removes crazy peaks?

stoic otter
#

Hello all... been reading on the templating page and also the jinja docs, and i'm having trouble figuring out how to do something that I thought would be relatively simple. I've got an incoming MQTT message that is just text (not JSON), and i'd like to extract a portion out of it as a sensor. For example, if the message on the topic is just a string like "The battery voltage for 21231 is 3.02V", i'd like to have a value template that just extracts out the 3.02V from that message. But even with the regex filter I'm not really sure how to do that. Can anyone give me an example on how to parse out a value from a text string?

#

ok, i think i'm closer... i was able to do "{{ value.split(' ')[-1] }}" and that gets me 3.02V, but it also requires the string i'm looking for to be at the end, so I suppose if the message is sometimes "The battery voltage for 21231 is 3.02V (low)" then it won't get the right string. I guess i just want to search the string for \d.\d*V

dreamy sinew
#

It's hard to parse arbitrary data

wicked ferry
#

History Stats - is it possible to use this to report time since a sensor was state "on?" And will it survive a server reboot? I tried using mqtt but gave up after about 20 hours of not being able to get the time to format in a usable manner. Any help would be super apprecaited.

analog belfry
#

Does anyone know if it's possible to call a script for each item in a JSON list? I'm receiving the JSON object through webhook trigger in an automation. I've been trying to find a way to template a for loop either in the script sequence or the automation action but I fear what I want might not be possible. Any help would be great!

small hatch
#

can anyone help me with a rest sensor? I cant get it to populate with info

charred crow
#

Hey all! I'm looking for example of template fan. In the latest version I can there was percentage added to control the fan. I have sonoff dual which controls 2 speeds of a fan (0,1,2). I'm looking for working example so I could understand how it works now and I could copy it to my HA. Thanks!

unreal merlin
#

hmm is there a way to stop processing templates, e.g. like a "{% set this=that %} {% return %}"?

#

like returning from a function for lacking a better term

rose marlin
#

I saw in the release notes for 2021.3 that "Templates can now be used to create weather entities". Is there an example or instructions on how to do this? I am getting a weather station shortly and would like the temp, humidity, wind, etc. to be pulled from the local weather station, but the forecast information to be pulled from my AccuWeather integration. Any help you can give is greatly appreciated. Thanks.

mighty ledge
#

You can make a nested if statement and as long as your logic is correct, it will return on whatever if/then branch you’re on

dreamy sinew
#

functions are a thing in jinja. they're called macro

#

but if you find yourself looking to one of those you probably need to re-evaluate your logic

lethal galleon
#

in the following example, will cl match now()? I'm asking because cl doesnt seem to include microseconds and now() dose

{% set cl = strptime(states('SOME_SENSOR'), '%Y-%m-%d %H:%M:%S%z') + timedelta(hours=-2) %} {{ cl == utcnow()}}

mighty ledge
elder moon
#

i want to sync a input_select in HA with MQTT topic. Unfortunately one of the possible states of MQTT topic is "none" and HA doesnt allow templates with "none" in them

marsh lynx
#

I just updated my HA to 2021.3.3 because apparently that has the latest plexapi in it. But due to the change in the services, I am struggling to construct the code to call the service as a test.

Previously I went to "Developer Tools" > "Services". Selected the media_player.play_media service, and then put the following in for the service data:

media_content_type: EPISODE
media_content_id: '{ "library_name": "TV Shows", "show_name": "Spycraft", "shuffle": "1" }'```

Which doesn't appear to work now, so now I'm trying to use the new service.  I have went to "YAML Mode" and have been trying the follow, but to no avail.  Has anyont got any ideas?:
```service: media_player.play_media
target:
  entity_id: media_player.plex_plex_for_samsung_tv_2019
data:
  media_content_id: '{ "library_name": "TV Shows", "show_name": "Spycraft" }'
  media_content_type: EPISODE```

cc: @marble needle
trail estuary
#

Can template entities be placed in an Area?

lethal galleon
#

Do you mean like this {{ cl == utcnow().strftime('%Y-%m-%d %H:%M:%S+00:00') }}?

mighty ledge
lethal galleon
#

oh, duh. Thanks!

dreamy sinew
#

none as the key is fine, it doesn't like None as the value

elder moon
#

oh is it?

#

let me try

frosty wave
#

noob question:
i have 1 sensor and want to create a template sensor with sensor * 1,5 -> how would be the correct syntax?
value_template: "{{ states('sensor.nice_sensor') |float *'1,5' }}" < like this?

dreamy sinew
#

need to use proper numbers

#

...|float * 1.5

frosty wave
#

thank you, gonna try it

frosty wave
#

what to do to cut the result to x.xx ?
"{{ states('sensor.waschmaschine_monat') |float * 0.246 | round(2) }}"
Result is: "0.10500000000000001"
sensor is: 0,07

marble jackal
#

You are rounding 0.246 to two digits now

#

Use brackets to make sure the calculated value is rounded instead

frosty wave
#

yea got it, thank you

#

"{{ (states('sensor.waschmaschine_monat') |float * 0.246) | round(2) }}" -> works πŸ˜‰

rose marlin
wary tide
#

Hi guys, I cant seem to get my template sensors with data from my car working. I use Bluelinky for Node RED and send an MQTT message to my broker

#

Unfortunately my value_template doesnΒ΄t work. It will always say "Offen" Even when the raw data I configured in a different sensor says False. Thats the config I created:

#
  • platform: mqtt
    name: "Kona Kofferraum"
    state_topic: "kona/status"
    value_template: "{{ 'Geschlossen' if value_json.status.trunkOpen == 'False' else 'Offen' }}"
    unique_id: sensor.kona_kofferraum
#

Any idea why thats not working?

mighty ledge
#

If it’s json, false is not a string

wary tide
#

Yes, itΒ΄s json. So what would I need to change that to?

#

Just False without the ´´ right?

brisk nebula
wary tide
sonic nimbus
#

Hello I need a little help regarding my script with syncing tvo volume attributes on two entites

#

I just want to be observable one automation, it has two media_players as triggers

#

and I dont know how to pass for last row in my automation based on which trigger is called, to set another one?

sonic nimbus
mighty ledge
sonic nimbus
#

Yeah, I assumed that. Although both my media_players are wired..

restive parrot
#

Is there a way to get the current theme? I want to use different colors in a card, depending on the current theme, so I would like something like this:

{% if is_state('homeassistant-theme', 'dark') %}
'#ffffff
{% elif is_state('homeassistant-theme', 'light')  %}
'#000000'
{% else %}
'#000000'
tough ice
#

I am trying to use a template to create a dynamic list of entities to add to a group. I saw an example somewhere of how to create a list, but I am just not getting the syntax correct, and I can no longer find the example. This is the code I use: https://paste.ubuntu.com/p/RKB22DSWNz/
The result an empty list. The actual list should be what is printed out, but the result is ['empty'].
sensor.basement_heating
sensor.dining_room_heating
sensor.guest_room_heating
sensor.kitchen_heating
sensor.living_room_heating
sensor.master_bedroom_heating
sensor.office_heating
['empty']

lethal galleon
#

Given:
{% set cl = strptime(states('sensor.jewish_calendar_upcoming_candle_lighting'), '%Y-%m-%d %H:%M:%S%z') %} {{ cl + timedelta(hours=-1, minutes=-34) }} {{ utcnow().replace(second=0, microsecond=0) }} {{ cl == utcnow().replace(second=0, microsecond=0) }}
Which shows in dev tools as
2021-03-12 13:29:00+00:00 2021-03-12 13:29:00+00:00 False
Why is the condition false? Aren't the times equal??

deft timber
#

I bet it has to do with timezone. What gives the following ?

{{ as_timestamp(cl + timedelta(hours=-1, minutes=-34)) }}```
lethal galleon
#

1615556940.0 1615555740.0

#

Both times should be utc

deft timber
#

Or just use this {{ states | selectattr('name', '==', 'Thermostat heating') | map(attribute='entity_id') | list }}

lethal galleon
#

@deft timber fwiw, {{ cl.tzname() == utcnow().tzname() }} is true

mighty ledge
tough ice
modest sparrow
#

I have a question about changing the update frequency on a sensor, which channel should I go? I have a MQTT sensor which updates too fast and fills the database, want to reduce the frequency

modest sparrow
#

Great, thanks πŸ™‚

white ruin
#

Hey all, apologies if this has been asked but I can't seem to find it. I'm setting up a chores tracker with NFC tags and input_datetime entities. I'm trying to build sensors off of the input_datetimes that are some amount of time in the future (like 90 days for an air filter) but having trouble templating because everything is different variable types. I'd like to just do something like {{ states('input_datetime.last_air_filter') + timedelta(days=90) }} but obviously states is returning a string and timedelta a datetime object. I can convert everything to timestamps with the filter, but it seems silly to convert both to a timestamp rather than just finding some common type I can pull directly. Any thoughts on how to better accomplish this?

#

Ah I see my problem. states('etc') returns a string. states.etc.state returns the object. Of course docs recommmend not using states.etc.state, but seems way better for this use case

#

Well, no, states.etc.state still returns a string. So that doesn't fix it. I'm now trying to use strptime except even when I use that I get a concatenation error

mighty ledge
white ruin
dreamy sinew
#

States are always strings

mighty ledge
#

As phnx said, all states are strings

dreamy sinew
#

state attrs can be anything but the state itself is always a string

slate sparrow
#

hi, I'm trying to create a 'cooking' sensor. there's a temperature sensor above the stove and one in the living room. I'd like a binary_sensor (cooking) to turn on if the sensor above the stove is 3 degrees higher than the one in the living room. I use a similar sensor in summer to tell me when to open/close the windows that I think I can use as a start but I need help to change the +3 degree difference. here's what I have:

#
  • platform: template
    sensors:
    cooking:
    friendly_name: "Cooking"
    value_template: "{{states.sensor.temp_inside_upstairs.state < states.sensor.kitchen_temp.state}}"
formal ember
#

anyone able to help me with a switch template? just not sure how I would create one for an aicon unit, require it to use with the generic_thermostat integration. managed to write the sensor template fine, but stuck on switch...

thorny snow
#

Hey ALl, iam new here and from germany, i have some issues with modbus sma inverter integration can anyone help?

configuration yaml.
sensor: !include sensor.yaml

#sma#
modbus:
type: tcp
host: xxx.xx.x.xxx
port: 502
delay: 3

thorny snow
#

yes thank you πŸ™‚ i used wrong channel my bad first time used Discord with over30 its New Land for me πŸ˜„

mighty ledge
mighty ledge
silent barnBOT
#

Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.

mighty ledge
#

that should work as is, but it won't be a toggle. Just an on and off lightning bolt

#

Is that what you want?

formal ember
#

ah yes, reading the generic_thermostat docs and it says it must be a toggle device

mighty ledge
#

so what do you want to use to determine that the switch is on?

formal ember
#

i don't think it requires it, because the sensor in the thermostat will let the thermostat know whether to toggle the switch, no?

mighty ledge
#

the only way for it to be a toggle is for the switch to know it's state

#

so your 2 statements conflict. It's either "generic_thermostat docs and it says it must be a toggle device" or "i don't think it requires it". Not both

formal ember
#

the first then, says must be a toggle

mighty ledge
#

So back to my original question, what do you want to use to show that the switch is on?

#

It's ok to say "I don't know"

formal ember
#

Hmmm... Say the AC unit is running, then the switch should show as on....

#

give me 2 i will try write it out

#

i think i am following now

mighty ledge
#

ok, so if that's the case, what's the AC unit's possible states?

formal ember
#

off or cool

mighty ledge
#

So basically, template switches use the state of itself to know which service to call... turn_on or turn_off

formal ember
#

ah, because its a toggle, and has to know what to toggle to?

mighty ledge
#

yes

formal ember
#

starting to get it

mighty ledge
#

that's done through the value_template field

#

so your states are 'off' or 'cool'

#

first, go to the devtools -> states page

#

verify that those are infact the spellings of your states. What you see in the UI is translated.

formal ember
#
  switches:
    bedroom_aircon:
      value_template: "{{ is_state_attr('climate.master_bedroom_aircon', 'hvac_modes', 'cool') }}"
      turn_on:
        service: switch.toggle
        target:
          entity_id: script.bedroom_ac_night
      turn_off:
        service: climate.turn_off
        target:
          entity_id: climate.master_bedroom_aircon```
#

i think this may just do it

#

wait

#

turn_off to be replaced

#

with toggle

mighty ledge
#

I don't use climate devices, it might be a different service

#

whatever you use to turn it off through services is what you want to use

#

and your turn on looks incorrectd

#

your turn on should just call the script

formal ember
#

yeah climate.turn_off is the one out of services

mighty ledge
#
turn_on:
  service: script.bedroom_ac_night
formal ember
#

ahhh

#
  switches:
    bedroom_aircon:
      value_template: "{{ is_state_attr('climate.master_bedroom_aircon', 'hvac_modes', 'cool') }}"
      turn_on:
        service: script.bedroom_ac_night
      turn_off:
        service: climate.toggle
        target:
          entity_id: climate.master_bedroom_aircon```
mighty ledge
#

personally, I wouldn't use climate.toggle

#

you want the turn off to turn off, not potentially turn on

formal ember
#

oh yeah, its turn off

#

sorry

#

from services. there was no toggle.

#

cheering, hopefully this works

mighty ledge
#

It should work for you

#

if you go to the services tab and execute template.reload you shouldn't need to restart

formal ember
#

perfect, cheers

formal ember
#

Thanks for helping me wrap my head around what is so foreign to me

weary drift
#

Hi!

I have a value i get from SNMP. The value i get is "MemFree: 302579712"
I want to strip "MemFree: " and then divide it by a number.
This works for stripping the text in the devtools template. But how should i write it as a value_template?

{{ mydata | regex_replace(",\d+|[ MemFree:]", "") }}```
Isn't ```value_template: '{{ regex_replace(",\d+|[ MemFree:]", "") }}'``` enough, i get 
 unknown as value with that?
marble valley
#

hi,need some help...
trying to make a sensor that triggers (xx) minutes before wake up time to start the bathroom heating.

using an input_datetime storing the wake up time and a input_number holding the minutes before wake up.

i am able to create a new time from the now() time, but that's not what i need...

{{ (now().strftime("%s") | int - ( states('input_number.badkamer_tijd_voor') | int * 60)) | timestamp_custom("%H:%M", false) }}

i need a new time from input_datetime - input_number

{{ states('input_datetime.klok_1') | int - states('input_number.badkamer_tijd_voor') | int }}

thanks.

weary drift
#

I managed to get it to work with a template sensor.
value_template: '{{ ((states.sensor.snmpunraidmemfree.state)|regex_replace(",\d+|[MemAvailable:]","") | float / 1048576) | round(0) }}'
But i want it in the sensor that gets the data instead.

So states.sensor.snmpunraidmemfree.state should be like... "current value" or something. What am i missing?

weary drift
#

Solved πŸ™‚
value_template: '{{ ((value.split(" ")[1]) | float / 1048576) | round(0) }}'

daring yew
#

I have a question on the population of values to templates, I have a sensor that spikes sometimes to -40, i do not want these spikes in the database or in the graph, I have now displayed both values but the output of the template is populated once every few minutes(not a fixed period) the input is populated every few seconds, anyone have an idea what might happen here ?

#

{% if states('sensor.wp_buitentemp') | float > -30 %}
{{ ((states('sensor.new_wp_buitentemp')|float (states('sensor.wp_buitentemp')|float))) }}
{% endif %}

thorn basin
#

Is it possible to perform an action whenever an entity is clicked using automations? Ive had my eye on trigger event_type: click, but no luck getting it to work - anyone know what its for

inner mesa
#

When you say β€˜entity is clicked’, I don’t know whether you’re talking about something in a Lovelace card (in which case you should look at the card docs and tap_action) or some physical device

gaunt vector
#

How do I add all of these together? I've tried a couple of combinations and haven't had any success yet.

{{ states.sensor.coinbase_btc_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_comp_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_cgld_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_grt_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_nu_wallet.attributes["Balance in native currency"] }}
{{ states.sensor.coinbase_ltc_wallet.attributes["Balance in native currency"] }}

These return values such as:
1234.56 USD

inner mesa
#

you can convert each to a float with this: "1234.56 USD"[0:-4]|float

#

basically, chop off the last 4 characters and convert to float. then just add

gaunt vector
#
{{ states.sensor.coinbase_btc_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_ltc_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_comp_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_cgld_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_grt_wallet.attributes["Balance in native currency"] [0:-4] | float + states.sensor.coinbase_nu_wallet.attributes["Balance in native currency"] [0:-4] | float }}

Awesome, thank you @inner mesa !

inner mesa
#

I’m sure there’s a more clever way to approach that by iterating through a filtered list of states (they all contain β€˜coinbase’ and require the same massaging), but if ha e to play with it in the dev tools

tall otter
#

if i make change to my config.yaml i can't reload it without restarting HA right? if i want to do that i have to make a separate yaml and !include it

#

then i can apply those changes without reloading the whole thing

#

but not my main config.yaml itself?

inner mesa
#

It has nothing to do with separate files - everything starts with a reference in configuration.yaml. Look at configuration -> Server Controls to see what can be dynamically reloaded

#

It could be sitting right in configuration.yaml or in some included file

crystal nest
#

Folks I think I'm being dumb again. I have an ESPHome sonoff ifan03 which has state of on/off and then speed of low/medium/high. I created a binary sensor which correctly shows just off/low/medium/high as well as the corresponding icon fan-off/fan-speed-1/fan-speed-2/fan-speed-3 but I can't get it to show the "on" state colour (grey = off, yellow = on) - it just stays at grey even when the fan is on. Can anyone point me in the right direction?

inner mesa
#

A binary_sensor can only be on or off, so I’m not sure what you created

crystal nest
#

Good point. I started off with a sensor to show the state, then when I hit the problem of it not showing a button or entity as "on", I moved to binary_sensor with a value_template: of {{ state('fan.ifan03_fan', 'on') }}

#

Functionality is exactly what I want, my GUI updates as does the fan setting, just the icon doesn't change to it's yellow "on" state

inner mesa
#

That may just be for switches/lights

#

I use the custom button card to have more control over icon colors

crystal nest
#

Hmmm just feels incomplete without it. Think I can hack the style somehow based on the state?

#

I did look at that but it seemed a learning curve

inner mesa
#

You can use card-mod

#

Not really. It can be pretty simple

#

It’s trivial to set the color based on state

crystal nest
#

I'll have another read, tbh I was reading it while trying to work so it wasn't getting my full attention

inner mesa
#

That card does nearly everything, so it can be overwhelming. But it’s not that bad if you just focus on what you want to do

crystal nest
#

Yeah the doc page did look a little large lol

inner mesa
crystal nest
#

Oh sorry. Every time I get the wrong room

inner mesa
#

just look at the topics

#

you can ignore the template: part

crystal nest
#

Ah okay, that looks straightforward enough thx

toxic dome
inner mesa
#

that, too πŸ™‚

crystal nest
#

Oh bother πŸ˜›

#

That fixed it ty - so a binary_sensor (correctly configured!) does indeed show the yellow "on" state as a regular entity. Perfect

inner mesa
#

sorry about that, was scanning on my phone and missed that. I do heartily endorse the custom button card, though. Tons more control

crystal nest
#

Looking exactly as I'd imagined it. Yeah I'll certainly have a good read of the custom button card docs, does look like I can really customise stuff

mint drift
#

Hi Guys, Is what I am looking for a template? - I want a glance card where I put some motion sensors up that show the ''last seen'' status so basically the last time there was a ''detected'' presence so just the time of last one

inner mesa
#

a template sensor would be the straightforward way to do it in a standard glance card

formal ember
#

I haven't got this coming up in my sensors, can anyone take a look and tell me if I have written this wrong?

#
      value_template: >-
        {{ is_state('device_tracker.damien_owntracks_2', 'home')
            or is_state('device_tracker.damien_ios', 'home')
            or is_state('device_tracker.damien_phone', 'home') 
            or is_state('device_tracker.olia_owntracks', 'home')
            or is_state('device_tracker.olia_ios', 'home')
            or is_state('device_tracker.olias_iphone_2', 'home') 
            or is_state('sensor.family_status', 'Home') }}```
#

config validation says its ok

inner mesa
#

what's wrong?

#

is that a binary_sensor?

#

did you reload template entities or restart HA?

#

Did you try putting that in devtools -> Templates?

formal ember
#

just a sensor template

formal ember
#

and came back as - platform: template sensors: family_home: value_template: >- False

#

because no one is home...

#

oh so strange, now it is appearing in devtools > states

#

disregard!

#

also if I used the template

      friendly_name: "Door Open/Closed"
      value_template: >-
        {% if is_state('binary_sensor.front_door_sensor_contact', 'open') %}
          Door Open
        {% else %}
          Door Closed
        {% endif %}
      icon_template: >-
        {% if is_state('binary_sensor.front_door_sensor_contact', 'open') %}
          mdi:door-open
        {% else %}
          mdi:door-closed
        {% endif %}```
#

would it change the icon on my entity panel from open to closed depending on the door's state?

inner mesa
#

binary_sensor is on or off

#

but yes, it should

formal ember
#

beauty

formal ember
#

Hmm with the following, would the state of the sensor be home if any of those states are true? and what would the state be if false?

  sensors:
    family_home:
      value_template: >-
        {{ is_state('device_tracker.damien_owntracks_2', 'home')
            or is_state('device_tracker.damien_ios', 'home')
            or is_state('device_tracker.damien_phone', 'home') 
            or is_state('device_tracker.olia_owntracks', 'home')
            or is_state('device_tracker.olia_ios', 'home')
            or is_state('device_tracker.olias_iphone_2', 'home') 
            or is_state('sensor.family_status', 'home') }}```
inner mesa
#

no, it would return a boolean

#

you can add if/else logic to have it return something else

#

you can test this

formal ember
#

ok, i get the if/else logic, but if it returns a boolean, where does that go?

inner mesa
#

it will be the state of the sensor

#

you can try this

#

just change the state of one of the entities to whatever you want

formal ember
#

now I am really lost... this is what I get for trying to copy someone elses config for presence detection....

inner mesa
#

lost how?

formal ember
#

Ok so my logic is this....

Automation to detect group.family or person.x/y at home. This automation turns on an input boolean. input_boolean.family_is_home

Another automation that detects input_boolean.family_is_home turning on, runs script.welcome_home only if the boolean is off and no one is home already (thinking I need to put a guest mode in around here somewhere)

#

maybe I just need to drop the sensor.family_home above

#

am I over complicating it?

inner mesa
#

it seems like you only need the "family is home" sensor

#

a template binary sensor would be enough

#

or just put them all in a group

dreamy sinew
#
{{ states.device_tracker|selectattr('state', 'eq', 'home')|list|length > 0 or is_state('sensor.family_status', 'home') }}
#

any device tracker entity has a state of home or that sensor

inner mesa
#

even that seems more complicated than necessary for those requirements

dreamy sinew
#

haha probably

#

group would probably do it

inner mesa
#

the requirement I see is to run some "welcome home" automation when a sensor goes from "not home" to "home", indicating that somebody arrived home

#

so a group of device trackers would do that

dreamy sinew
#

true

#

or associate all of those with people and have a group of persons

formal ember
#

i have a binary sensor group.family created

inner mesa
#

a binary_sensor and group are two different things

formal ember
#

ah sorry, yep....

  - person.damien
  - person.olia```
#

in the group.yaml

inner mesa
#

right

formal ember
#

and a bayesian binary sensor for each person with their device trackers

inner mesa
#

as long as you have device_tracker entities assigned to those person entities

#

sure

formal ember
#

I have double tapped it haven't I haha

#

Am thinking I could do away with the bayesian sensor altogether

dreamy sinew
#

i think the person entity does that for you

formal ember
silent barnBOT
#

@formal ember Discord isn't like IRC, you don't have to tag people on every response. Keep in mind that every time you tag somebody, they get a notification ping. That can very quickly become annoying and people may block you.

When using Discord's new Reply feature it defaults to pinging the person you reply to, click @ ON to @ OFF to stop this - on the right side of the compose bar.

dreamy sinew
#

for the quote reply πŸ˜‰

formal ember
#

πŸ˜„

dreamy sinew
#

no need for ping on active conversations

formal ember
#

sorry mate

dreamy sinew
#

all good

#

gotta learn ya now before you do it to someone crankier

formal ember
#

I do it to Tinkerer all the time πŸ˜‰

#

he LOVES it

dreamy sinew
#

lol

formal ember
#

Ok so back to my setup:

Automation to detect group.family or person.x/y at home. This automation toggles, sensor.family_status to on or home.

Second automation to detect sensor.family_status as being on or home. This then runs script.welcome_home

Leaving home would be an automation that detects group.family or person.x/y away. This automation toggles sensor.family_status to off or away.

Another automation to detect sensor.family_status is off or away. This runs script.leaving_home

#

If I keep it simple, am I going to miss out on anything?

inner mesa
#

again, seems too complicated

#

just use the sensor and have a single automation that runs an "away" or "home" automation

dreamy sinew
#

you don't need an automation for a toggle when you can just create the sensor using the same template

#

1 entity instead of 2

formal ember
#

ok then...

#
  sensors:
    family_home:
      value_template: >-
        {{ if is_state('device_tracker.damien_owntracks_2', 'home')
           or is_state('device_tracker.damien_ios', 'home')
           or is_state('device_tracker.damien_phone', 'home') 
           or is_state('device_tracker.olia_owntracks', 'home')
           or is_state('device_tracker.olia_ios', 'home')
           or is_state('device_tracker.olias_iphone_2', 'home') 
           or is_state('sensor.family_status', 'home') }
           home
          {% else %}
            away
          {% endif %}```
#

comes back with TemplateSyntaxError: expected token 'end of print statement', got 'is_state'

#

cannot find something so complicated in the documentation

inner mesa
#

right, that's wrong πŸ™‚

formal ember
#

gotcha

#

can i make it right? πŸ™‚

inner mesa
#

you already posted a proper if/else/end example above

formal ember
#

oh, yes...

#

ok, how do I add or's to that then?

inner mesa
#
        {% if is_state('device_tracker.damien_owntracks_2', 'home')
           or is_state('device_tracker.damien_ios', 'home')
           or is_state('device_tracker.damien_phone', 'home') 
           or is_state('device_tracker.olia_owntracks', 'home')
           or is_state('device_tracker.olia_ios', 'home')
           or is_state('device_tracker.olias_iphone_2', 'home') 
           or is_state('sensor.family_status', 'home') %}
           home
          {% else %}
            away
          {% endif %}
formal ember
#

ah... yeah i would have never got that

#

thank you

inner mesa
#

it's still too complicated

formal ember
#

πŸ˜„

inner mesa
#

you keep repeating that monster

#

just group all device_tracker entities and use that one group for everything

#

or...just continue doing what you're doing, I guess

formal ember
#

right, like a group.family_device_tracker

inner mesa
#

sure

formal ember
#

that simplifies things

inner mesa
#

and...that's it

formal ember
#

wowee

#

🍻

inner mesa
#

and you can test it by manually modifying states of individual trackers to make sure you get the right result

formal ember
#

I am guessing you could do away with sensor.home too?

#

sensor.family_home rather

inner mesa
#

right. the group replaces that

#

the group is all

formal ember
#

I think I have just realised I could use my group ```Family:

  • person.damien
  • person.olia``` instead of an even larger one as those trackers are already assigned to the person.
#

thats the new automation

#

for coming home

#

I am thinking its even easier if I just go 'if family comes home, run script'.... but now I am in #automations-archived land

inner mesa
#

Yes, that’s the point of the group πŸ™‚

formal ember
#

Thanks for putting up with my time here

inner mesa
#

Np, it’s a process. But a rewarding one, IMO

dawn relic
#

Could anyone help me with this problem? Im trying to multiply my sensor value by the number 1127, but my sensor read out gives me 0

#
  • platform: scrape
    name: vechainvalue
    resource: "https://www.coingecko.com/en/coins/vechain/eur"
    select: ".no-wrap"
    scan_interval: 1

    • platform: template
      sensors:
      vechain_waarde:
      friendly_name: 'VeChain Waarde'
      value_template: "{{ (states('sensor.vechainvalue') | float * 1127) | round(0) }}"
      unit_of_measurement: '€'
#

This is the code I wrote in the configuration file, does anyone see the problem?

inner mesa
#

Do you get the same if you put the template in devtools -> Templates?

#

The sensor may report β€˜unavailable’ or something that cannot be converted to a float

#

Perhaps during startup

dawn relic
#

My template read out also says 0, when I change round(0) to round(1) it gives me 0.0

#

So the code seems fine, but I think it has something to do with the scrape sensor which the value from the scrape cant be converted nor multiplied by the number 1127

#
  • platform: template
    sensors:
    vechain_waarde:
    friendly_name: 'VeChain Waarde'
    value_template: "{{ ((states('sensor.vechainvalue') | string) * 2) | round(1) }}"
#

When i change float to string it gives me:- platform: template
sensors:
vechain_waarde:
friendly_name: 'VeChain Waarde'
value_template: "€0.06409742€0.06409742"

#

Now I do be getting some values, but it's just the same value put next to each other twice

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.

inner mesa
#

Well, there’s your problem. The first character is messing up the conversion.

#
- platform: template
    sensors:
      vechain_waarde:
        friendly_name: 'VeChain Waarde'
        value_template: "{{ ((states('sensor.vechainvalue')[1:] | float) * 2) | round(1) }}"
timid cape
#

in the example above, is it possible to store the value to a different attribute.

#

I believe the default value is the state attribute

dawn relic
#

Thanks @inner mesa!

inner mesa
#

State isn’t an attribute

timid cape
#

got it. Let me rephrase

#

n the example above, is it possible to store the state value to a different attribute.

inner mesa
#

But yes, you can add attributes to template sensors

timid cape
#

how would I do that RobC. Is it possible to do that with the sql sensor?

inner mesa
#

Recommend consulting the docs on that

timid cape
#

thanks. I don't that option is available for sql sensors. thank you.

inner mesa
#

You can just create a template sensor based on the output of your sql sensor

timid cape
#

the problem is the sql response is larger than 255 characters. because the state column is limited to 255 chars

#

I was hoping to store the result in the attributes collumn

inner mesa
#

You could with your own custom component

timid cape
#

Do I need to make a new front end component or a new entity?

inner mesa
#

An integration

timid cape
#

thanks. Sorry to bother you again... Do you have a link to an example

dawn relic
#

Am trying to convert to a float the following output value:

  - platform: scrape
    name: Exodus ETH Wallet ETH BAL
    resource: "https://etherscan.io/address/0x82fbEd465c16679C6dC8E4d8c2dfEcd097175fb8"
    select: ".col-md-8"
    scan_interval: 1

The value I get is 0.0159... Ether
How do I get rid of 'Ether'?

wheat tendon
#

how do i make the last boot sensor human readable? (for some reason when i preview a multiple entities card, it will show it as 16 hours but when i try it in the singular entity card it shows the garbled timestamp.)

inner mesa
mighty ledge
wheat tendon
mighty ledge
#

for what

#

I said 'or' and both go in different places...

wheat tendon
mighty ledge
#

just put it in the entities card like any other entity

#

entities card != entity card

#

entites card it works and will display a relative time. entity card will not work and it'll display the timestamp

snow lintel
#

Hey Guys - I'm trying to fix my fans that broke with the latest update (fixed speeds -> percentage speeds) ... is this the best channel to get help?
I have tried a few options wrt changing the speeds to percentage as opposed to low, med, high etc ... but my fans arent even loading to begin with now.
They were working perfectly until now ... not even the default on the latest setup doc is working - maybe I'm over thinking it πŸ˜‚
https://paste.ubuntu.com/p/fjCXmp8CBy/ This is my original config - maybe better to start there and see what needs to change?

wheat tendon
inner mesa
#

You can build a template sensor using the link I posted earlier to convert to a format you like better

low blaze
#

Can anyone tell me if I have an array, can I get HA to return the # of items in the array

#

example, have an array of values but need to know how many values there are is there a count function?

inner mesa
#

In a template, yes

#

Where is the list coming from?

low blaze
#

attribute of an entity (sonos list of favorites)

inner mesa
#

And where do you want to use the count?

#

It’s as simple as doing β€˜|count’ to count the items

low blaze
#

need to assign it to a variable

silent barnBOT
inner mesa
#

Lots of jinja docs out there

dreamy sinew
#

probably |length

low blaze
#

can you give me an example of the line that would have that in it?

#

(I have the rest working fine)

#

state_attr(entity_id, "source_list")

#

where would |length go

dreamy sinew
#

well since state_attr() is a complete expression, outside

low blaze
#

so right after it

inner mesa
formal ember
#

Hi Template Guru's

        {% if is_state('binary_sensor.office_door_sensor_contact', 'on') %}
          mdi:door-open
        {% else %}
          mdi:door-closed
        {% endif %}```

If I wanted to add a colour change to this one, would it be as simple as adding the line under the else line if I wanted door-closed to be Red?
inner mesa
#

No

#

That’s just for the icon

formal ember
#

do I have to create a different template to do colour?

#

or would I be better off using something like card-mod?

inner mesa
#

The template isn’t the problem or solution

#

You could, or use something like custom button card

formal ember
#

Down the rabbit hole I go again

boreal fiber
#

is it possible to make a template for a condition that looks for the following: "has value been above 100 in the last hour" then template is true or false for condition?

#

want to see if the sump pump has ran in the last hour measuring watts basically

#

i see that option in the UI for triggers but not conditions but i guess ill use it as my trigger

dreamy sinew
#

sounds like something better served as a trigger, yes

low blaze
#

I have a value example: {{states.climate.downstairs_thermostat.attributes.current_temperature}}

#

can I add that directly into a lovelace card at the top as a badge?

#

or do I need to define a sensor with it and put the sensor as a badge?

#

I found state-label in the badge documentation but wasn't sure how to use it directly as a badge

mighty ledge
low blaze
#

k thanks

#

separate question, I know i can break out smaller yaml's using the !include

#

and it seems from the documentation that i can break out multiple if i want, but they need different names

#

is the non-indented label irrelevant?

#

sensor: could contain some sensors in the base configuration.yaml

#

and then sensors2: !include sensors2.yaml could have other sensors whiel sensors3: !include sensors3.yaml could have yet others?

mighty ledge
#

but you can split it up like this:

#
sensor: ...
sensor foo: ...
sensor bar: ...
#

you need the space

low blaze
#

oh ok

#

sensor badges: !include sensors-badges.yaml etc

#

then i can just have a separate yaml for badge templating and such

mighty ledge
#

yep

low blaze
#

cool πŸ™‚

mighty ledge
#

just need a space

low blaze
#

thank you

mighty ledge
#

np

low blaze
#

I new it had to matter and not at the same time

mighty ledge
#

keep in mind, that your errors will not point to the correct location

low blaze
#

?

#

oh

#

on the checks

#

yes it is going to imagine its just part of the base file

#

i read that

mighty ledge
#

like if you have an error in a sensor, it'll point to some random ass location

#

the error contents will be correct, just not the line pointer

hard pagoda
#

I highly doubt I'm doing this even remotely right, so maybe someone can help me. I have several Inovelli fan/light switches, and the fan is showing up as a "light" that the "brightness" can be adjusted. I'm trying to create a template to turn them into fans and will hide the light entity. This is what I've got in the configuration right now, and the fan comes on, but I'm not able to get the slider adjustment to work right. Since my fans don't really do any speed different than low, medium, and high, I was going to set the slider to 33%, 66% and 100%. Anyone help me out on this?

silent barnBOT
hard pagoda
#

Ok, so I'm not figuring out how to do the code wall. lol sorry.

plain zinc
#

I'm trying to find it in the docs, but is there any way when creating a binary sensor template to do something with a time period component like a condition where you stipulate: for: seconds: 10

blazing burrow
#

so I have this template:

sensor:
  - platform: template
    sensors:
      coinbase_total_balance:
        friendly_name: Coinbase Total Balance
        unit_of_measurement: USD
        value_template: >
          {{ (float(state_attr('sensor.coinbase_mana_wallet', 'Balance in native currency').split(' ')[0]) 
             + float(state_attr('sensor.coinbase_my_wallet', 'Balance in native currency').split(' ')[0]) 
             + float(state_attr('sensor.coinbase_eth_wallet', 'Balance in native currency').split(' ')[0]))
             | round(2) }}
        icon_template: mdi:currency-usd

is there a good way I can use this more generically, like a wildcard or maybe selectattr? I don't really get how selectattr works... but basically I'd like to account for the situation where I may have many more wallets, and not have to add that any more lines

plain zinc
#

oh I think I found it... it's just named differently with delay_on

blazing burrow
#

I'm tempted to develop a PR to the coinbase integration to add this as a sensor entity, but would like to get something more general working in the meantime

raven zenith
#

Is there a way to make a safe_alarm_panel use a button for disarming instead of requiring a code input?

#

Oooh, that worked... just added disarm as a state and set the code in the template .yaml.. is there a way to get rid of the keypad now?

#

(I guess maybe there's an easier template to use if I don't care about the keypad?)

raven zenith
#

right now I'm calling a service for each template state... maybe I can conditionally check the {{code}} value and if it's present call one service and if it isn't call another?

hard pagoda
#

Using that configuration, I'm able to get it to turn on, but not adjust the speed of the fan.

formal ember
#

Hello everyone, wondering if anyone knows a quick fix to pull data from or push data from a temperature sensor more often. The sensor is based off an attribute on my HVAC system, it is a template. Could I run an automation to actively ask the device what the temperature is, instead of waiting for it to broadcast the temp?

deft timber
formal ember
#

Ah yes, I threw it up there too but no response. I’ll try again πŸ˜ƒ

hard pagoda
#

Ok, so I've tried this and it's still not adjusting the speed of the fan. Can anyone help me out here? https://paste.ubuntu.com/p/rhkxC9Dqbp/
Using that configuration, I'm able to get it to turn on, but not adjust the speed of the fan.

mighty ledge
hard pagoda
mighty ledge
#

The docs have an example

hard pagoda
#

So for these lines value_template: "{{ states('input_boolean.state') }}"
percentage_template: "{{ states('input_number.percentage') }}"

#

The input_xxxxxxx would be the entity of the light. that is suppose to be a fan?

mighty ledge
#

The value_templates are what render the current state of your fan for that specific field

hard pagoda
#

so it would be value_template: "{{ states('light.living_room_fan_hallway') }}" ?

mighty ledge
#

Please read the docs

#

It describes what each field template means

dreamy sinew
#

note that jinja2 is not a HA specific concept

grim obsidian
#

Is it not possible to use a variable as part of another variable? i.e.:
{% set last_triggered = states.{{ trigger.event.data.entity_id }}.attributes.last_triggered %}

mighty ledge
#

treat it like any other object in your code

#
{% set last_triggered = states[trigger.event.entity_id].attributes.last_triggered %}
grim obsidian
dreamy sinew
#

{% %} logic statements
{{ }} print statements

#

states.automation.get('lights_on_{}'.format(light_source)).attributes.last_triggered

grim obsidian
dreamy sinew
#

what is the entity id of the automation you're trying to pull?

grim obsidian
#

automation.lights_on_bedroom

mighty ledge
#

the error is later on in your template

dreamy sinew
#

its coming from states.automation.get()

#

something isn't working quite right

mighty ledge
#

is automation nolonger a dict?

dreamy sinew
#

no its an object

mighty ledge
#

well, object with a .get

#

'collection'

dreamy sinew
#

apparently missing the .get

grim obsidian
#

{{ states.automation.get('lights_on_{}'.format(light_source)).attributes.last_triggered }}```
This is the entire template right now.
mighty ledge
#

huh, they must have changed it from a collection then

dreamy sinew
#

states.automation|selectattr('entity_id', 'eq', 'automation.lights_on_{}.format(light_source)')[0].attributes.last_triggered maybe

#

oh no

mighty ledge
#

well either way, this would work

{{ (expand('automation.lights_on_' ~ light_source) | first).attributes.last_triggered }}
grim obsidian
#

YES!

mighty ledge
#

@dreamy sinew that would work if you used |first instead of the getitem

#

[0] or whatever it's called

#

I think

dreamy sinew
#

i've had weirdness with that but i think you solved it by wrapping in paren

mighty ledge
#

really should just have a template editor up at our disposal at all times

dreamy sinew
#

meh, i'm cool with using the one on my system

mighty ledge
#

with a bunch of canned crap

dreamy sinew
#

i can usually get close to whatever the question is

mighty ledge
#

I'm at work... no access πŸ˜•

dreamy sinew
#

ah lame

#

there are a few generic ones out there

mighty ledge
#

I put a dev version of HA in docker on it in wsl2

dreamy sinew
#

maybe a FR to get it exposed out on the demo system

mighty ledge
#

but it's not running

grim obsidian
#

Thank you very much for the help, guys

#

Another question - Would this work?

    - event: lights_off_override_enable
      event_data_template:
        light_source: "{{ (trigger.entity_id.split("switch.light_")[1]) }}"```
#

(Doesn't seem to)

dreamy sinew
#

you're chopping your template with " inside

#

need to use ' inside

grim obsidian
#

Ah of course.. Rookie mistake!

silent barnBOT
thorny snow
#

What variables are supposed to be accessible in the template?

brisk temple
#
value_template: '{{"WARNING" in state_attr("sensor.pixel_4_last_notification", "android.text"}}'
#

it doesn't know what android.text is, you could do a trigger attribute, value_template: '{{ "WARNING" in trigger.to_state.attributes.android.text'

#

if you wanted to expand your trigger to multiple entities

grim obsidian
#

I'm trying to do an if statement in my action, so instead of this:

    - event: lights_on_override_enable ```
I do this:
```  action:
    - event: >
        {% if (is_state("trigger.event.data.new_state", 'on')) -%}
        event.lights_off_override_enable
        {%- else -%}
        event.lights_on_override_enable
        {%- endif %}```
Is this possible? What am I missing?
inner mesa
#

no, that's not possible like that

#

you can use templates inside of data:, but I don't know if that'll work for firing events

grim obsidian
#

Okay, thanks!

inner mesa
#

I would just use a generic event and add custom data (which can be templated)

dull stump
#

I have an MQTT sensor to which an application is sending 8-bit RGB values as a simple string of nine digits. How would I go about separating this sensor into sub-entities for each color value such as sensorname.red?

    name:  wallpaper-color
    state_topic: "wallpaper-color"```
#

I intend to use this sensor to drive the color of various lights in an automation.

dull stump
#

Thus far, I have tried this approach but the resulting channel sensors don't contain any values. Perhaps I have made a mess of something.

  - platform: template
    sensors:
      wallpaper_red:
        friendly_name: Wallpaper Red Channel
        value_template: "{{ states('sensor.wallpaper-color').split()[1] }}"
      wallpaper_green:
        friendly_name: Wallpaper Green Channel
        value_template: "{{ states('sensor.wallpaper-color').split()[2] }}"
      wallpaper_blue:
        friendly_name: Wallpaper Blue Channel
        value_template: "{{ states('sensor.wallpaper-color').split()[3] }}"
deft timber
#

FYI the index should be 0 -> 2 and not 1 -> 3

#

and if your sensor.wallpaper-color contains comma separated values you should use {{states('sensor.wallpaper-color').split(',')}}

flint crown
#

Will a template binary_sensor be updated, when a entity in the attributes_templates changed ?

grim flicker
#

I would like to write this {"humidity": 39} to a .json file. How should the template look like?
i have this - service: notify.tekstbestand data: message: > "{{ {'humidity': states('sensor.mancave_multi_sensor_vochtigheid')} }}"
but this isnt getting the right format in the file

charred dagger
#

What DO you get?

#

Try message: "{ 'humidity': {{states(...)}} }"

dull stump
# deft timber and if your `sensor.wallpaper-color` contains comma separated values you should ...

I did eventually figure it out but thank you for the advice. Integrating it as an automation with a data_template as seen below worked perfectly.

  alias: New Automation
  description: ''
  trigger:
  - entity_id: sensor.wallpaper_color
    platform: state
  action:
  - service: light.turn_on
    data_template:
      rgb_color:
        - "{{ states('sensor.wallpaper_color').split(';')[0] }}"
        - "{{ states('sensor.wallpaper_color').split(';')[1] }}"
        - "{{ states('sensor.wallpaper_color').split(';')[2] }}"
      entity_id: light.light_1
dreamy sinew
#

overkill

#
``` should do it
royal rampart
#

ugh, after 3 days I get fans working, and now they don't work....

dull stump
dreamy sinew
#

notice the stealth edit

dull stump
# dreamy sinew notice the stealth edit

There is no longer an error but it doesn't work.

  alias: Light Color Follows Wallpaper
  description: ''
  trigger:
  - entity_id: sensor.wallpaper_color
    platform: state
  action:
  - service: light.turn_on
    data_template:
      rgb_color: "{{ ('sensor.wallpaper_color').split(';') }}"
      entity_id: light.light_1
#

Doesn't it need to be split three times for three values?

dreamy sinew
#

that's what the .split() does. it becomes a list of 3 values

dull stump
#

The raw sensor data is 000;000;000;.

dreamy sinew
#

ah so you get 4

deft timber
#

rgb_color: "{{ states('sensor.wallpaper_color').split(';') }}"

dull stump
#

Ah, so it is.

dreamy sinew
#

{{ "000;002;003;".split(';')[:-1]}}

dull stump
#

I'll remove the final ; from the sensor side.

dreamy sinew
#

that will also work

dull stump
#

Still doesn't work, I'm afraid.

  alias: Light Color Follows Wallpaper
  description: ''
  trigger:
  - entity_id: sensor.wallpaper_color
    platform: state
  action:
  - service: light.turn_on
    data_template:
      rgb_color: "{{ states('sensor.wallpaper_color').split(';') }}"
      entity_id: light.light_1
royal rampart
#

ok, so I add a percentage_template to my fans template and vscode tells me percentage_template is not allowed

dull stump
#

Raw sensor data is now 000;000;000.

#

Pasting "{{ states('sensor.wallpaper_color').split(';') }}" into Developer Tools produces "['000', '090', '185']".

#

Pasting my original "{{ states('sensor.wallpaper_color').split(';')[0] }}" produces a single value for red in quotes without brackets.

deft timber
#

doesn't rgb_color expect a list of int instead of a list of string ? You can try {{ states('sensor.wallpaper_color').split(';') | map("int") | list}}

#

to cast each string in int

dull stump
#

This gives me an 'expected block end but found scalar" error.

  alias: Light Color Follows Wallpaper
  description: ''
  trigger:
  - entity_id: sensor.wallpaper_color
    platform: state
  action:
  - service: light.turn_on
    data_template:
      rgb_color: "{{ states('sensor.wallpaper_color').split(';') | map("int") | list}}"
      entity_id: light.light_1
#

Beginning to think that my overkill solution might not have been such overkill. πŸ˜†

dreamy sinew
#

you mixed your quotes

dull stump
#

"{{ states('sensor.wallpaper_color').split(';') | map('int') | list}}"

#

Trying this.

#

It produces "[255, 70, 17]" and no errors but still doesn't work.

low blaze
#

In the past when I've had a "switch" (like a tasmota) that is really a lamp, I will make an entry under light: in my config.yaml so that it creates a light.entityname. Right now I added a door sensor that is a binary_sensor. I went into customize.yaml and set it's device_class to be door, and this worked great in lovelace for identity purposes but when I went to write automations, the states are being triggered in their original form (not the converted display of Open/Closed) is there a proper way to modify this so that I can use "Open/Closed" in my automations, maybe modify the template of the entity also? I was alternatively going to define a door (similar to how I define lights mentioned above) but that doesn't seem to work the same way. thanks for any guidance

true otter
#

Hey guys need a bit of help. I want to create a date template that outputs " Thursday, March 18 " I have started a bit with ```{% set months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %}
{% set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %}
{{ days[now().weekday()] + ' ' + months[now().month-1] + ' ' + now().day }}

#

but when I place the now().day into the piece I am getting an error. If I remoe it and just place it as {% set months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %} {% set days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] %} {{ days[now().weekday()]+ ', ' + months[now().month-1] + ' ' + 'day' }} i get everything but the day of the month.

#

I have racked my brain to sleep trying to solve this . Anyone willing to point me in the right direction? Please.

dim iron
#

hmm best way to decode an image sent over mqtt? data:image/jpeg;base64,/9j/4MOREDATAhere ? Ideally I would like to save it as a file or use it as a camera

mighty ledge
#
{{ as_timestamp(now()) | timestamp_custom('%A, %B %d') }}
mighty ledge
true otter
#

Thanks @mighty ledge .πŸ™‚

toxic radish
#

Hi all! I'm struggling with a script, trying to build what to send to my Sonos, or my google home mini's. Maybe someone can point me into the right direction.
Kitchen is a Sonos -> needs to recieve the property "source:"
Livingroom, Bedroom and Bathroom need to recieve the property "media_content_id:"

silent barnBOT
toxic radish
#

When i check this code in Developer Tools > Template it works just fine

#

but as a "script:" it doesn't work, logging says: Error executing script. Error for call_service at pos 3: Error rendering data template: UndefinedError: 'state' is undefined

mighty ledge
#

And it looks like your template spans across fields, which does not work

#

Use choose instead

toxic radish
#

aah i've read about choose, thank you i'll have a look

#

while parsing a block mapping in "/config/packages/radio.yaml", line 83, column 13 expected <block end>, but found '<scalar>' in "/config/packages/radio.yaml", line 83, column 40

#

this is line 83: conditions: "{% if states("input_select.radio_speaker") != "Keuken" %}"

keen echo
#

I have problems with some Yaml in my configuration, where to ask help for it?

toxic radish
mighty ledge
silent barnBOT
mighty ledge
#

Sorry, that's not a link to it

silent barnBOT
mighty ledge
#

That one

toxic radish
#

Thank you

#

I did saw that documentation

stone lintel
#

TemplateError('UndefinedError: 'mappingproxy object' has no attribute 'today_energy_kwh'') while processing template 'Template("{{ states.switch.hs110.attributes["today_energy_kwh"] | float }}")' for attribute '_state' in entity 'sensor.tumble_dryer_switch_today_kwh'
I'm having this error appear and I'm sure it's been working fine.
This is the template in question

      friendly_name_template: "{{ states.switch.tumble_dryer.name}} Today's Consumption"
      value_template: '{{ states.switch.hs110.attributes["today_energy_kwh"] | float }}'
      unit_of_measurement: "kWh"```
Could I get some help on this please? This is for an HS110 TP Link plug
glossy viper
#

hi. how can i add to logging the person who is home when doorbell rings. i added time for now

coarse tiger
#

you use that second one as template for a sensor and write out the value of the sensor to the message

glossy viper
#

oh... that's why some guys are purple ...they are smart πŸ™‚

#

thank you @coarse tiger

toxic radish
#

Anyone can help me out with my script?

#

Logging: Radio afspelen: Error executing script. Invalid data for call_service at pos 3: extra keys not allowed @ data['choose']

glossy viper
#

@toxic radish u saw beardedtinkerer's youtube video ?

deft timber
glossy viper
#

now i receive xxxyyyy

deft timber
#

btw you could significantly simplify your code @toxic radish. I suggest you create a dict variable radios containing the key/value, and then in the source or media_content_id, juste call {{radios[states("input_select.radio_station")] }}