#templates-archived

1 messages · Page 116 of 1

dreamy sinew
#

sorry, i hate dealing with datetimes so i'm not much help here

gloomy horizon
#

np; it's probably something pretty well known to the python coders out there. I'm just really bad with them as well lol

dreamy sinew
#

its limited to a subset of stuff and i hate dealing with it in python as it is

gloomy horizon
#

no question it's a headache.

dreamy sinew
#

is there a next game date property?

gloomy horizon
#

There is, but I can't seem to get it to work with strptime. If I could figure out how to add a new attribute to the custom sensor that I'm using I'd create an attribute that would work.

dreamy sinew
#

what are the attributes on the original sensor?

#

might be able to merge a few properties to get it to work

gloomy horizon
#

That'd be great. Here's my github where I forked it. I figured I'd do a PR on the original version because it might help the dev a bit.

#

I already fixed the time variable at line 92 so that I could get the space between the time and "PM" which made strptime work. But really if I could just expose dttm_local (at 91) as an attribute to HA I could probably work from there

dreamy sinew
#

looks like you have next_game_date and next_game_time that you could use

gloomy horizon
#

I do, but I've tried to merge next_game_date and next_game_time together in strptime and it doesn't accept them as a valid date/time string

#

e.g. {{ strptime(state_attr ('sensor.leafs_game', 'next_game_date') + ", " + state_attr('sensor.leafs_game','next_game_time'), '%I:%M %p') }} doesn't actually return a timestamp

dreamy sinew
#

could try this:

{{ strptime(next_game, '%B %-d, %Y %-I:%M %p') }}```
gloomy horizon
#

That returns the merged date, but as_timestamp on that final strptime returns "none". I'm pretty sure I need to go to as_timestamp to add 5 minutes

dreamy sinew
#

nah,
{{ strptime(next_game, '%B %-d, %Y %-I:%M %p') + timedelta(minutes=5) }}

gloomy horizon
#

TypeError: can only concatenate str (not "datetime.timedelta") to str

dreamy sinew
#

so strptime isn't parsing

#

'cuz this works {{ now() + timedelta(minutes=5) }}

gloomy horizon
#

Yeah. I think we're at what I said - I don't think that next_game is rendering in a format that strptime recognizes as a time/date format

dreamy sinew
#

while you're making changes, why not add the raw timestamp to the attributes

gloomy horizon
#

That's kind of what I was thinking. I'm going to have to follow the developers documentation - I don't know how to add the attribute. I assume that the change is made in the dict defined at 111 but I'm not quite there yet

dreamy sinew
#

i'd add it to the time dict at 92

#
time = {
    'next_game_time': dttm_local.strftime('%-I:%M %p'),
    'next_game_datetime': dttm_local
}
#

might need to define some sort of format

#

worth a test

gloomy horizon
#

Sweet. I will. I'll play around with it a bit more. Thanks phnx I really appreciate your help.

dreamy sinew
#

probably dttm_local.timestamp()

#

should work

#

or .isoformat()

gloomy horizon
#

I'll give it a shot. Have to go AFK for a few minutes but I'll let you know where I get when I get back.

glossy viper
subtle shore
#

how can i parse an rgb json value? cant get it to work...

{
  "state": "ON",
  "color": {
    "r": 255,
    "g": 118,
    "b": 72
  }
}

i KNOW there is one thread in the forum. but google dont like me today.

#
  action:
  - service_template: light.turn_{{ trigger.payload_json.state | lower }}
    data_template:
      entity_id: "{{ trigger.topic.split('/')[2] }}.{{ trigger.topic.split('/')[3]}}_{{ trigger.topic.split('/')[4] }}_{{ trigger.topic.split('/')[5] }}"
      color: "{{ trigger.payload_json.color }}"
#

something about a value template and then fetching the tree values from the payload....

charred dagger
#

{{trigger.payload_json.color.r}} and so on

#

Just like {{trigger.payload_json.state}} in your second line there.

dreamy sinew
#

needs to be a tuple or a list? i can't remember

subtle shore
#

then is maybe something above false. let me check.

i have tried color: [{{ trigger.payload_json.color.r }}, {{ trigger.payload_json.color.g }}, {{ trigger.payload_json.color.b }}]

dreamy sinew
#

{{ trigger.payload_json.color.values()|list }}

subtle shore
#

have it!

#

color rgb_color: [{{ trigger.payload_json.color.r }}, {{ trigger.payload_json.color.g }}, {{ trigger.payload_json.color.b }}]

charred dagger
subtle shore
dreamy sinew
#

wrap it in "

subtle shore
#

oh - it does.

#

i wrote it between []

dreamy sinew
#

yeah, that would make a list of a list

charred dagger
dreamy sinew
#

yeah, it returns a dict_values which gets dumped as a string unfortunately

#

not a native type

subtle shore
#

super nice here. 😄 u guys helped me alot.

from every light with all values as automation (6 per light) to just a single template per value (6 in total). 😛

#

and now i can add even more without writing more automations. 😛

dreamy sinew
#

😛

charred dagger
#

I'm all for reducing automation numbers.

dreamy sinew
#

and the native type outputs from template has been pretty huge for template complexity

charred dagger
#

Oh yes

#

With that and the recent changes to automations, automations are almost a programming language now.

#

I dropped appdemon a year ago, and just removed my last python_script in favor of an automation.

thin vine
#

hmm i need to check indeed if I still need the python_script

dreamy sinew
#

sometimes python_script is still easier

gloomy horizon
# dreamy sinew or `.isoformat()`

Wasn't necessary; {{ state_attr('sensor.leafs_game', 'next_game_datetime') - timedelta(minutes=5) }} now works. Thanks for helping me with that modification. Just to be clear, this template trigger should work, shouldn't it?

thin vine
#

I seem to remember I used it because of native types,I'll check tomorrow

dreamy sinew
#

re-share the full thing please? i don't remember what we were working with

gloomy horizon
#

Sure. We added an attribute
called next_game_datetime; that currently result in 2021-01-15 16:55:00-07:00. So, I should be able to use a template trigger of {{ now () == state_attr('sensor.leafs_game', 'next_game_datetime') - timedelta(minutes=5) }} right?

dreamy sinew
#

that should work

gloomy horizon
#

Oh no, wait a minute that won't does it? Because template triggers only define themselves at boot, not constantly checking, right?

dreamy sinew
#

that might have been changed? i don't remember now

#

worst case you can add a datetime sensor and compare with that

gloomy horizon
#

Oh ok. Cool - I hope it did. Thanks!

gloomy horizon
dreamy sinew
#

Hmm

gloomy horizon
#

Got it. compare timestamps. {{ as_timestamp(states('sensor.date_time_iso')) == as_timestamp(state_attr('sensor.leafs_game', 'next_game_datetime') - timedelta(minutes=85)) }}

dreamy sinew
#

That'll do it

gloomy horizon
#

Yep. Thanks a ton. I think I hate times as well now.

glossy viper
subtle shore
#

and i am happy about my lights... ^^

thin vine
unreal salmon
#

When building a template called x with a template attribute y, is there a way to refer to attribute y inside this template by saying something like self.attribute.y instead of using state_attr('sensor.x', 'y')

thin vine
#

yes. states.sensor.x.attributes.y

unreal salmon
#

I don't want to repeat sensor.x though

thin vine
#

but this might give errors if the sensor is unavailable, so it's better to use the state_attr() as that can deal with unavailable things

unreal salmon
#

I want it to be inferred. Is it possible?

#

Also, is it possible to create templates out of entities of an integration in a for loop of some sort? I don't want to repeat all the code for each entity when creating the template when the only thing different between each template is the entity being templated.

thin vine
thin vine
unreal salmon
thin vine
#

so, yeah you want to create template entities, for which I'm not sure if you can do that with templates. lets wait till the template gods come in 😉

bright quarry
#

https://pastebin.ubuntu.com/p/mSBgYFTskq/

anyone know what's wrong with these? trying to have sensors based on mqtt messages that take the "time:" field from the sensor and update it whenever "extradata: contact open" mqtt message occurs. i have a bunch of these, but only one updates (guessing it's like the first one triggered or something).

somber hamlet
#

If you want a rounded value of a sensor, is it always necessary to make a dummy sensor?

thin vine
#

depends... if you want to show it on a dashboard or graph, I believe you do, but as trigger or condition you could use a template trigger or condition where you react to the rounded value

somber hamlet
#

I just want to show it on my lovelace dashboard.

ivory delta
#

If you're using the default cards, you'll need to 'wrap' the original with a template sensor. Some custom cards may be able to treat the numbers for you.

somber hamlet
#

Thanks, I will look for one.

spring zenith
#

If i have a date in (input_datetime.gdate) helper.
And i would like the difference of this date with today in a other helper. (input_number.daysto)
what would be the solution for that?

thin vine
#

{{((as_timestamp(input_datetime.gdate) - as_timestamp(now()))/(3600*24))|round()}}

spring zenith
#

Thanks, Goy yo learn where to put this i think.

thin vine
#

probably an #automations-archived when the input_datetime.gdate changes with a service to set the input_number,daysto

spring zenith
#

I'll try right away 🙂

thin vine
quiet moth
#

Anyone know an effective way to strip the start time out of a calendar event so that I can use it in a notification? I want the notification to tell me the start time of the event for the event which is happening tomorrow. Without it including the entire date / time string that gets produced by the 'start_time' attribute.

#

The end goal is using it as a TTS broadcast at bed time to say "The tesco delivery is at (StartTime) tomorrow"

#

Found it 😄

thin vine
#

{{as_timestamp(states('input_datetime.pre_heat_time')) |timestamp_custom('%H:%M') }}

quiet moth
#

Thanks Magie 🙂

spring zenith
thin vine
#

try putting "" around the template

#

so data: "{{((as_timestamp(input_datetime.gdate) - as_timestamp(now()))/(3600*24))|round()}}"

#

and don't add 3 accolades { just 2

#

oh.... sigh

#

another edit 🙂

#

data: "{{((as_timestamp(states('input_datetime.gdate')) - as_timestamp(now()))/(3600*24))|round()}}"

#

you need the states ('') part too 😉

#

no sure why I missed that part in my first reply 😉

spring zenith
#

states part ... looking it up

thin vine
#

should be good.

#

I've tested it just with my own input, in the developer tool Template part

#

{{((as_timestamp(states('input_datetime.pre_heat_time')) - as_timestamp(now()))/(3600*24))|round()}}

#

that's also a good place to start if you're messing with templates, it gives feedback on what's wrong with your template 😉

spring zenith
#

indeed nice

#

it give back data: "113"

thin vine
#

so 113 days till holiday 🙂

spring zenith
#

yep :-)... should be . Thanks a lot (restarting now)

long nymph
#

Hello, this is my first discord post ever. I've done a lot of research trying to find a step-by-step tutorial on how to build templates but I'm having zero luck. Tons of examples but not much of the "why". I want to get the status of the lights in my garage (either from a smart plug, luminance sensor, or smart bulb) and have the smart switch control them. I'd like both the sensor and the switch to be one button in Lovelace.

thin vine
#

Hi, welcome @long nymph . Not sure why you would need a template for that, maybe I don't understand your question correctly. you can add sensors and buttons directly to lovelace. if you need help with that, #frontend-archived is a better place to ask. Or explain what the template is needed for

long nymph
#

Thanks @thin vine. I'd like to combine the output of the sensor/bulb (whether the lights are on or off) to appear on the switch button in Lovelace. The switch is a zigbee mechanical switch that physically toggle the three way switch. It's never synced up correctly!

sudden mango
#

I mean does a simple template switch not work for you?

long nymph
#

HI @sudden mango it might but I haven't been able to plug the right info in to make it work. I'm very new to this! To the point that I think all of this gets added to the YAML but I'm not sure...

sudden mango
#

Alright. Let's see your configuration 🙂

#

Have you restarted once your changes were made? Switches don't have a reload button besides restart.

long nymph
#

I tried to restart but the YAML stopped that!

silent barnBOT
spring zenith
#

The date is not changing.
The yaml code is edited in visual studio and there are red lines under thecode: data: "{{((as_timestamp(states('input_datetime.gdate')) - as_timestamp(now()))/(3600*24))|round()}}"

sudden mango
#

@long nymph made a few changes.

silent barnBOT
sudden mango
#

friendly_name has an underscore

#

and to turn on it wass missing service:

#

Are you using VS code home assistant addon?

spring zenith
#

yes. error => Incorrect type. Expected "object"

sudden mango
#

oh sorry not you i'm not sure on yours

long nymph
#

Thanks for the help, I'll give it a try! I was doing it in Developer Tools. I'll take a look at the VS Code addon. I really do want to learn more... is there a "For Dummies" tutorial you recommend?

spring zenith
#

thats ok 🙂

sudden mango
#

Honestly just the home assistant documentation websites. Their examples are the bee's knees

#

most of the time 🙂

#

does your switch have both turn on and turn off or is it a momentary switch?

long nymph
#

OK. I still feel like I missed a few days of class but I'll keep chipping away at it! I appreciate the help @sudden mango and @thin vine

#

The switch is a normal on and off but the zigbee part fits over the switch and physically moves it

thin vine
sudden mango
#

you might want the service to be switch.toggle for both or switch.turn_on and switch.turn_off

#

but the rest looks right to me

long nymph
#

it's a 3 way switch in the garage so there is no true on or off. So I went with toggle

thin vine
inner gulch
#
  {% if trigger.to_state.state | float = "on" %}
    light.turn_off
  {% else %}
    light.turn_on
  {% endif %}
thin vine
#

hmm better:

      service: input_number.set_value
      data:
        entity_id: input_number.target_temp
        value: "{{ trigger.payload }}"```
inner gulch
#

My guess is that this wont work

#

anyone can help me out

#

basiclly wanna do one automation for a motionsensor and either turn it off or on depending if the sensor "to" state was on or off 😛

spring zenith
#

testing 🙂

inner gulch
#

hmm maby float == "on" ?

thin vine
#

@inner gulch the current implementation includes a nice blueprint exactly for that

inner gulch
#

It does?

thin vine
#

so you don't need to come up with one yourself 🙂

#

"Motion-activated Light"

inner gulch
#

I have not updated HA in a while so might be missing somthing 😄

sudden mango
#

@long nymph For your icons you will also want to change their names to mdi:lightbulb-on-outline and mdi:lightbulb-off. But visual studio code should suggest that for you. If you're unsure of the value_template you should try it in the developer/templates screen

inner gulch
#

I got 0.114.3 😛

thin vine
#

well, you are encouraged to upgrade anyway becuase of security concerns..

inner gulch
#

Yeah, is just that i need to do alot of work to get it compliant with the newest version 😛

thin vine
#

fair enough

inner gulch
#

things that isnt components anymore but is now integrations

thin vine
#

let me dig through my old automations, you should be able to do stuff like you say

#
  trigger:
    - platform: state
      entity_id: sensor.0x00158d0002b4a1cf_click
      to: 'right'
  action:
    service_template: >
      {% if is_state('group.lampen', 'off') %}
        script.turn_on_light
      {% else %}
        script.turn_off_light
      {% endif %}```
#

is what I used to do

#

so you can adapt from that 🙂

inner gulch
#

hmm yeah ill see what i do

thin vine
#

trigger.to_state is sometimes a bitch to get working as you have no way to check it with the template editor.

#

I tend to debug that by sending it to notify.webbrowser so I can analyse the syntax of the exact output

spring zenith
#

getting strange .. Value has now the red lines underneed.
And (like before) i can not execute the annimations

#

Maybe... browser temp data?
Could it be the '' ... because it is a number ?

ivory pawn
#

Hello all , is it possible to take an mqtt light payload and apply it to an existing light which is not mqtt? for example brightness, color etc.
Currently im extracting and passing individual attributes as follows:

    entity_id: light.testlight
    service_template: >
      light.turn_{{ trigger.payload_json.state }}
    data_template:
      brightness: '{{ trigger.payload_json.brightness|int }}'
      color_temp: '{{ trigger.payload_json.saturation|int }}'
      etc... ```
Im basically trying to take an mqtt light remote and have it control a non mqtt light that already integrated with HA. (like a bridge)
thin vine
#

should be correct, I don't get errors in vs code

spring zenith
#

ok.. copy past and.. errors gone?
Looking for that stupid typo of me.
Found it.
Changed the 'Data:' for 'value:' . There was no Data in my code mindblown

thin vine
ivory pawn
#

@thin vine thanks. the trigger data is correct for light control but I dont know how to simplify the data_template (or not use template) to just pass all the json values to the light i want to control. Does anyone know how that might go code-wise? ... so that i dont have to enter brightness, color_temp etc.. all manually

thin vine
#

not sure @ivory pawn not to familiar with payload_json

spring zenith
#

No errors anymore.
But the number is not changing. I executed the automation

thin vine
#

@spring zenith currently it only changes on sunrise, that;s what the automation does

spring zenith
#

trigger: [] .... ofcourse 🙂

#

Can i check logs to see whats happening?

thin vine
#

i know

#

value: "{{((as_timestamp(states('input_datetime.gdate')) - as_timestamp(now()))/(3600*24))|round()}}"

#

missed the states again... sorry 🙂

#
    alias: 02_Input_Days2
    description: ""
    trigger:
      - platform: state
        entity_id: input_datetime.gdate
    condition: []
    action:
      - service: input_number.set_value
        data:
          value: "{{((as_timestamp(states('input_datetime.gdate')) - as_timestamp(now()))/(3600*24))|round()}}"
          entity_id: input_number.02_days_to_vacation
    mode: single```
#

and triggering on changing the input date 😉 not sunset

#

and yes, I've built it in my HA too, to troubleshoot 😉

spring zenith
#

Well... just wanted to post that. bacause i tested it in the template tester like you told me.
Im getting smarter after just 3 hours 😂

thin vine
#

hehehe

ivory pawn
#

How can i make it so that the data_template (in my example a few above) is ONLY executed if the trigger.payload_json.state == 'ON' ? I just keep getting errors. (I want this because if the state is off then the no data can be passed to a light_turn_off and an automation error is caused)

spring zenith
#

Done. its working !
I m trying this for 2 weeks in node red. only took me a few hours with your help @thin vine .🤩 Thank you 🙂
Of course not giving up on node red. The mix of it all makes HA perfect 🙂

thin vine
ivory pawn
#

@thin vine hi thanks. it is an automation, with a mqtt trigger, and action as shown. is this wrong?

livid island
#

hi all, i wanna ask i have a couple of automation using the if trigger.entity_id but is there also a trigger.state? so i can do different things depending on the state of the trigger entity?

dreamy sinew
#

trigger.to_state.state and trigger.from_state.state are things

livid island
#

ah dammit, i'm just gonna check directly on the state instead. thanks.

dreamy sinew
#

states(trigger.entity_id) can also be a thing

livid island
#

🤦‍♂️ okay i'm back at it's adding a lot of newlines when looking them developer tools, how can prevent that...

#

i had to do a one line that last automation i did...

dreamy sinew
#

{%- -%}

livid island
dreamy sinew
#

yep should strip the extra whitespaces

livid island
#

yeah that work phnx where you when i last had this problem 😉 thank you so much

dreamy sinew
#

haha

livid island
#

just have to find the other back again and fix it 😄

long nymph
#

Holy crap I got my garage light switch button working! Thanks for the help!

thin vine
#

nice brig

sonic nimbus
#

hello again 🙂

#

How can I split some variable that are going into my script

#

here is the start of that script

#
icon: "mdi:party-popper"
description: 'Set roller shutter to desire position'
fields:
  covers_positions:
    description: Set which covers are affected and what are positions
    example: 
      - cover.ds_l;60
      - cover.ds_s;40
      - cover.ds_d;20
      - cover.rs_l;0
      - cover.rs_d;0
      - cover.ss_l;100
      - cover.ss_d;100```
#

so, I want to have one script, which will be handling positions of my roller shutters (covers)..I want something like [key,value] pair

#

and then to call somehow foreach in action part

#

and foreach key,value pair to trigger service.set_cover_position

ivory delta
#

Uh... why not just use scripts the way they're intended and pass in multiple variables when you need to?

#

🤯

lime grove
#

I have a template which uses met.no to get temperature and humidity, I followed a guide to create it, if it wasn't for the guide how would I know what state_attr to use to get the required data?

jagged obsidian
#

Developer Tools - States

lime grove
#

Thank you

dreamy sinew
#

make a template sensor if it reads from existing values @low stream

charred dagger
#

Nah. You can do it!

lost rock
#

I am trying to figure out Home Assistant templates. I have a digital scale that I have hacked with a HX711 and D1 Mini so that I can get the weight of a tank of peroxide.
Thank you Hook UP video for making a propane sensor.
I have set up two helper entities in HA called input_number.peroxide_full and input_number.peroxide_empty. My goal is to use these along with the sensor value from the scale to create a number representing the amount of peroxide available. This will be used to control a meter on my dashboard.
I have been looking at the template docs and believe that is what I need to create. But I am having a hard time getting the concept of how to create one.
I have been experimenting with the template tool but cant figures out how to access the inputs.

Any help would be appreciated.
Thank you

thorny snow
#

What's the easist way to reject items from a list?

#

I guess, what's similar to " | random" in that way?

#

I've tried select and selectattr

#

I get a weird error "the <generator object select_or_reject at 0x7f90eb75d900>}} is 46 %,
"

#
{{ state.name | lower | rejectattr("name", "hasp") }} ```attempting with this
dreamy sinew
#

('name', 'eq', 'hasp')

silent barnBOT
dreamy sinew
#

Search that page for built-in tests

lost rock
#

can you return the value of a helper to a template?

dreamy sinew
#

Same way you return the value of a sensor

thorny snow
#

@lost rock {{(((states('input_number.scale_input') | int) - (states('input_number.low_value') | int) ) / (states('input_number.high_value')| int) *100) |round(0)}} returns a number between 0 - 100

thorny snow
#

There's probably a prettier way to do that

lost rock
#

I have been trying that but it returns error and basically it boils down to the input_number.peroxid_full returning unknown.

thorny snow
#

what did you set that value to?

#

I presumed you'd weigh the bottle empty, set the lowvalue manulally, them do the same with a full... scale will them give you a percentage.

#

I created the helpers in the UI and they work fine in that template.

#

Thank you @dreamy sinew

lost rock
#

Yes in the states tab of the developers tools it it shows a states of 28566.0

thorny snow
#

@dreamy sinew that didn't work 😄

#

in the default template editor, I changed weather to sensor and used this: {{ state.name | lower | rejectattr('name', 'eq', "hasp") }}

dreamy sinew
#

Hmm

thorny snow
#

do you see that crazy error?

#

@lost rock what do you have for the input_number.low_value and high_values?

#

you can insert numbers there

lost rock
#

Yes they are 0 and 30000

thorny snow
#

Ok, so you can create input_numbers helpers as I did and set their values to 0 and 30000 or hard code thiose in place if what I provided

#

don't use zero, it'll divide by zero probably.. use 1

lost rock
#

let me try that

#

doesn't make a difference. still unknown

thorny snow
#

ok, show me the template you are using

hexed galleon
#

Is the match test for selectattr not available in HA Jinja?

#

If not, how would you just return entities that have a certain attribute? Was going to use a regex MAC check.

dreamy sinew
#

match is a filter not a test so can't be used that way

lost rock
#

I have not created a template yest I am just testing in the developer tools

#

sorry yet

hexed galleon
#

Sorry, I don't understand. Why would this not work? {{ states.binary_sensor | selectattr('mac','match','^[0-9A-Fa-f]{8}$') | list }}?

dreamy sinew
#

That's not a built in test and HA hasn't implemented it

hexed galleon
#

OK, cool. So easiest to just make some separate groups then of different entities I want to check and expand them. All good 🙂

thorny snow
#

@lost rock I gave you the template

#

You just needed to modify it with your entities or values

hexed galleon
#

Just have to use different "low" values for my Wyze sensors than any other battery sensors. The implementation of the WyzeSense API misreports battery levels, so "80%" is actually 0%.

#

Was gonna identify them by MAC, but will just use separate groups.

sonic nimbus
ivory delta
#

wtf? No. Write one script that accepts an entity ID and a position.

#

Voila. Infinite combinations possible.

subtle shore
#

remember this?
i got it. just for something different - at first.
"{{ 'homeassistant/indoor/' + trigger.entity_id.replace( '.', '/' ) | reverse | replace( '_', '/', 1 ) | reverse + '/STATE' }}"

low flame
#

I'm trying to export the data that is displayed under "entities" in configuration. But I cannot find anywhere how to append the "integration" to my list. I'd like to get something like
name, entity_id, integration (kitchen counter light, light.kitchen, Tuya
This gets me the list:
{% for state in states %} {{ state.domain, state.entity_id, state.object_id, state.name, }} {%- endfor -%}

thin vine
#

it's just not in the data, so you can't extract it:

<template TemplateState(<state light.staande_lamp=off; min_mireds=153, max_mireds=500, effect_list=['colorloop', 'random'], friendly_name=Staande lamp, supported_features=63 @ 2021-01-17T13:08:56.966935+01:00>)>
low flame
#

This is was I suspected... 😦 It's very sad that the page itself under configuration is not selectable, printable or anything. There must be somewhere where that data is linked since you can filter by "deconz" for example.

mighty ledge
low flame
#

Any suggestion elsewhere?

ivory delta
#

You're trying to display which integration created something? That information is in the entity registry... it's internal only.

mighty ledge
#

you can attempt to backtrack the information in the entity_registry

#

there have been talks about using the expand method to access device entity_id's but that's about it and no one has stepped up to dev it

sonic nimbus
ivory delta
#

Stop tagging me.

mighty ledge
# low flame Any suggestion elsewhere?

if you know python, you can import json and read core.entity_registry and core.device_registry. Then each item in core.entity_registry.data.entities contains a device_id. Iterate the core.device_registry.data.devices grabbing the id and comparing it to the device_id.

silent barnBOT
mighty ledge
#

Actually, what I said isn't even needed. the entity_registry contains the platform.

low flame
#

Yes. That's what I just found

mighty ledge
#

so just iterate the core.entity_registry.data.entities and output entity_id and platform.

low flame
#

Thanks. Off to work on this 😉

mighty ledge
#

have fun

low flame
subtle shore
#

is there a way to get something like that
payload: "{{ states.TRIGGER.ENTITY_ID.attributes }}"
inside an automation? short version:

[...]
    entity_id:
    - media_player.livingroom_libreelec
    - media_player.bedroom_libreelec
    - media_player.guestroom_libreelec
    - media_player.XYZroom_libreelec
  condition: []
  action:
  - service: mqtt.publish
    data:
      topic: "{{ 'homeassistant/' + trigger.entity_id.replace( '.', '/' ) | reverse | replace( '_', '/', 1 ) | reverse + '/STATE' }}"
      payload: "{{ states.TRIGGER.ENTITY_ID.attributes }}"
#

atm i have that block with (for) every media_player (of course each media_player entity once)

#

i dont know how to insert the variable inside the states string

ivory delta
#

Did you check the docs?
trigger.to_state.attributes

subtle shore
#

i think i dont have understood the use of this correctly.
thank you. that helped.

pliant viper
#

Any tips on how to format an input number? This works {{ '{:02d}'.format(6) }} but this fails to evaluate {{ '{:02d}'.format(states('input_number.day_start_hours')) }}

ivory delta
#

States are strings. Try casting it to an int/float first.

#

{{ '{:02d}'.format(states('input_number.day_start_hours') | float) }}

pliant viper
#

ahh, well that would make sense

#

Thanks

#

Although I'm starting to think I'm doing this the hard way...

lost rock
thorny snow
#

set its minimm to 1

lost rock
#

Yes I did that. Min is 1 and Max is 30000

#

{{ states("input_numpger.peroxide_full") }} this should show the value in the result window of the developer tools templates window it doesn't it says that it is unknown. Until I can get that sorted out I am stuck. The formula you sent is correct although I need to account for the tear weight of the empty bottle. The math is not the problem it is getting the data into the formula. I hope that better explains.

thorny snow
#

{{ states('input_numpger.peroxide_full') }}

#

wrong quotes?

lost rock
#

I thought that also it makes no difference. same result either way.

thorny snow
#

you said state tab is correct?

#

you must be using the wrong name. this works for me: {{ states('input_number.low_value') }}

#

so, I hope that's a typo... "input_numpger"

lost rock
#

Yes it was

#

Now that is interesting I just got it to work. I went back to the helper and copied the entity id then pasted it into the test block and it is now showing the correct information. don't under stand that one at is is exactly the same. input_number.peroxide_full

#

thank you for your help I appreciate it.

#

is there any good documentation on creating the yaml sensor using templates?

thorny snow
#

but those are only true/false, etc.

#

easy to start with

lost rock
#

I did see that during my journey but could not remember where. thanks for the link I think that will help.

#

again I appreciate your help. hope I can return the favor sometime.

thorny snow
#

Those are the official docs, and they are mostly hard to beat, if a bit fragmented

lost rock
#

Some time knowing what doc you are looking for is the issue for me. 😄

thorny snow
#

LOL I can never find the right term to search for

lost rock
#

Yep!! any way here you gol

#

{% set full=states('input_number.peroxide_full') | float %}
{% set empty=states('input_number.peroxide_empty') | float %}
{% set raw=states('sensor.peroxidescale_hx711_weightraw') | float %}
{% set level = ((raw - empty)/(full - empty)) * 100 %}
{{level}}

#

works fine it is returning 74 at this time.

#

Now to create the sensor so it can be used in lovelace.

rain cove
#

Hey all, I am trying to show a history graph with humidity and heating/cooling actions from my thermostat. When I add "climate.thermostat" to my history card, it shows on the graph when it is heating/cooling. How can I do this myself? I tried making a template with the hvac_action attribute, and adding it to my history graph, but that does not seem to work as I want it to

mighty ledge
#

You can't do it yourself, it's only available on climate devices

rain cove
#

Darn, thanks for the info

ivory pawn
#

Hello, some help pls? - I do not want brightness to be allowed to be 0 but am struggling with the code in my automation

        data:
          # brightness: '{{ trigger.payload_json.brightness|int }}'
          brightness: >
            {% if '{{ trigger.payload_json.brightness|int }}' > 0 %}
              '{{ trigger.payload_json.brightness|int }}'
            {% else %}
              '1'
            {% endif %}
#

removing the quotes doesnt work either

timid osprey
#

why are you templating inside of your template

ivory pawn
#

What would be the better way? should i use data_template?

timid osprey
#

use the dev tools template editor

#

your template is quite wrong

ivory pawn
#

does the editor work when the payload is from mqtt (json payload) ?

timid osprey
#

I have never used the UI, I don't really know

#

{{ trigger.payload_json.brightness if trigger.payload_json.brightness > 0 else 1 }}

silent barnBOT
timid osprey
#
{% set trigger = {
  "payload_json": {
    "brightness": 2
   }
} %}
{{ trigger.payload_json.brightness if trigger.payload_json.brightness > 0 else 1 }}

Do stuff like this to test

ivory delta
#

You'll want to cast to a number type before performing comparisons.

#

And by the time you do that twice in Bu's original template, you end up with quite an unwieldy mess 🤣

timid osprey
#

the json is parsed as a number

ivory delta
#

Pfft. Maybe.

timid osprey
#

for suresey, lol

ivory delta
#

I still prefer mine 😉

timid osprey
#

I like mine 😛

ivory delta
#

Readability... 'pick the bigger of these two (or more) numbers'

timid osprey
#

you think yours is more readable?

#

you fucking crazy

lost rock
#

@thorny snow Just wanted to let you know the final sensor is working find. Thanks again. I tried to past in the final yaml clip but the Has Bot moved it and provided a link. Not sure what that was but it is working.

ivory pawn
#

thanks @lost rock and @timid osprey ill try it out all out and report back 🙂

ivory delta
#

I hate the 'x if a else y' syntax Jinja has going on. It's not very newbie friendly... you have to skip ahead to parse the middle section before you think about which direction to look for the outcomes.

timid osprey
#

mine literally reads left to right

ivory delta
#

You can read it in whichever order you want. That's not the order in which the logic is defined though.

#

Or rather, not the order in which it's performed.

timid osprey
#

you focus on how humans read it, not the machines

ivory delta
#

Eh... I don't 😄

timid osprey
#

💋

ivory delta
#

JavaScript's ternary operator is great. a ? x : y means the same as Jinja's weird-ass syntax but it reads in order.

#

'If a is true, do x, else y'. Way more logical.

charred dagger
#

"jinjas weird ass syntax" is actually python

timid osprey
#

NERD

#

❤️

ivory delta
#

Fine, I'll redirect my ire at Python 😄

#

I'll take the | max over ternary any day. It's more succinct and it's expansible for when you have more than 2 items to compare.

ivory pawn
timid osprey
#

cunt

#

with your purple name

#

and your two o's

#

and your m and your n

ivory delta
#

See... my option's better. It's official 🤣

timid osprey
#

lmao

ivory delta
#

1 out of 1 users would recommend.

timid osprey
#

copy/paste, EXCELLENT

#

| floating an int

#

EXCELLENT

#

just catching those string edge-cases, I see

ivory delta
#

Nah... there's so many ways you could achieve the same thing. If it works, it works. I just try to write things in a way that I know I'll understand when I see them again in 6 months and are easy to maintain.

#

Yeah, defensive coding. Assume it could be any type but force it into the type you want 😄

timid osprey
#

how many ways to skin a cat

ivory delta
#

{{ [trigger.to_state.state | float, 1] | max }}
Bingo

#

Do that with your version 😄

#

300 lines later...

timid osprey
#

wut

ivory delta
#

Kidding 🙂 Love you

timid osprey
#

I knew you were kidding but I couldn't figure out what .state was, lol

#

my HA configs are quite simple compared to everyone I seem to try to help, 😛

#

I rely on other peoples problems to learn more about HA

ivory delta
#

Nothing wrong with that. I spent my first few months on this server lurking and learning from other people's problems too.

#

There's still so much I don't know but I'm pretty confident with the bits I understand now.

dreamy sinew
#

the jinja well is deep

neat ermine
#

Hi , maybe someone could help me on getting a attribute value

#

I want to get the name of face detected in Image detection DLIB

#

by using the template : image_processing.dlib_face

#

in the template , i use - '{{ states.image_processing.dlib_face_dashboard }}'

#

and get a output of :

#

<template TemplateState(<state image_processing.dlib_face_dashboard=1; faces=[{'name': 'Mig', 'entity_id': 'image_processing.dlib_face_dashboard'}], total_faces=1, friendly_name=Dlib Face dashboard, device_class=face @ 2021-01-17T18:57:58.696476+00:00>)>

#

How can I get just the 'name' ?

#

in this case = Mig

ivory delta
#

Did you check the documentation?

state_attr('device_tracker.paulus', 'battery') will return the value of the attribute or None if it doesn’t exist.

neat ermine
#

state_attr('image_processing.dlib_face_dashboard', 'name')

#

like this ?

#

Iscrmbling arround this and read the isntructions but I'm not able to get it

pliant viper
#

Is it possible to have a Template Sensor that doesn't convert to text, having to do something like this, makes me think I missed something in the docs {{ ((strptime(states('sensor.calculated_system_start_time'), '%H:%M:%S')) - timedelta(minutes=15)).time()}}

ivory delta
#

That doesn't convert to text? All states are strings, if that's what you're hoping to avoid.

pliant viper
#

Was afraid of that

ivory delta
#

If you're depending on using it as another data type, deal with the types after you read from the state.

#

Worth noting that a lot of (but certainly not all) integrations can auto-cast data types as needed.

pliant viper
#

Was trying to save time, sensor.calculated_system_start_time is a template sensor

#

where I do some datetime math and then output it as a datetime.time

#

so just seemed like a pain to have to convert back to datetime then to string to use in an automation

#

Thanks for the clarification

neat ermine
#

@ivory delta it doesnt display the name

#

{{state_attr('image_processing.dlib_face_dashboard', 'faces')}}

#

displays :

#

[
{
"name": "Mig",
"entity_id": "image_processing.dlib_face_dashboard"
}
]

dreamy sinew
#

is it always one item or could there be multiple?

#

if there are multiple do you want all of them or just the first one?

neat ermine
#

it could be nmore than 1

#

how would get all ?

#

or , get all but able to distingsh

dreamy sinew
#
{{ ', '.join(state_attr('image_processing.dlib_face_dashboard', 'faces')|map(attribute='name')|list) }}
#

or remove the join bit if you just want the raw list

neat ermine
#

... this is a face detection , I want to have a wall tablet display a diferent lovelace view for diferent users

dreamy sinew
#

above would output "name1, name2" vs ["name1", "name2"]

neat ermine
#

i will add this to a automation, so when someone is in front of the tablet, it will show his lovelace view

#

so i will probably use without join and work the automation for the result of template

#

we are just 4 persons here , and maybe any other unknown face (guests)

dreamy sinew
#

just this then:

{{ state_attr('image_processing.dlib_face_dashboard', 'faces')|map(attribute='name')|list }}
neat ermine
#

result is :

#

[
"Mig"
]

dreamy sinew
#

which is expected

neat ermine
#

yes , but woudnt just the name Mig , be more easy for the autmoations ?

dreamy sinew
#

you said you want to handle multiples

neat ermine
#

yes

dreamy sinew
#

if multiples are an option you need to have your response be consistent

neat ermine
#

but just one at a time

dreamy sinew
#

that's not how this works

neat ermine
#

? there will be just one person facing the tablet ..

#

else will take care of non positive identifications

dreamy sinew
#

you misunderstood the question i was asking earlier

#

{{ state_attr('image_processing.dlib_face_dashboard', 'faces')|map(attribute='name')|first }} will get you there

#

but if the camera ever pulls up more than one person at once you'll only ever get the first one in the list

neat ermine
#

it worked

#

I now get the point on your question

#

.. yes .. if more than 1 person , it will just display First

#

.. and yes , I will need to think on how to display for when more than one identifiaction is detected

#

.. thank you so much @dreamy sinew - will get to work with this lovelace touchless panel 😉

glossy viper
#

hi. i'm trying to put personal values from sensors of humidity and temp intto this template, but seems i cannot find correct syntax. help needed 🙂

young jacinth
#

hi, is something like this not possible?

{% set entity_id = 'sz_light' %}
{% set lights = ['group.{{entity_id}} '] %}
{{ lights }}

i want to get group.sz_light as output

deft timber
#

you should not write {{ }}in {% %}

deft timber
young jacinth
#

how do i have to do this in a state check?
{% if is_state('input_boolean.lighting_"~entity_id', 'on') %}

#

{{ states('input_boolean.lighting_"~entity_id') }}
wont work too i get unknown as output here.

dreamy sinew
#

What are you trying to accomplish?

young jacinth
#

this is the whole template

entity_id: |
  {% set lights = ['group."~trigger.entity_id'] %}
  {% if is_state('input_boolean.lighting_"~trigger.entity_id', 'on') %}
    {{ expand(lights)|selectattr('state','eq','on')|map(attribute='entity_id')|join(',') }}
  {% else %}
  {% endif %}
dreamy sinew
#

i've never seen ~trigger before

young jacinth
#

this is part of an automation

#

i want to use trigger.entity id
nontheless it wont work if i just use entity_id in the template editor without trigger

#

this here wont work:

{% set entity_id = 'sz_light' %}
{% if is_state('input_boolean.lighting_"~entity_id', 'on') %}
 {{ entity_id }}
{% else %}
{% endif %}
#

input_boolean.lighting_sz_light is configured and is state on off course

dreamy sinew
#

I have never seen ~ used in a template

young jacinth
#

mh okay, is there a another way to accomplish this?

young jacinth
#

as ~ only works in expressions?

ivory delta
#

The snippet slashback shared appears to work just fine.

#

If yours doesn't work, you're doing something wrong.

#

The random double quote you've added won't help, nor will the fact you're trying to use an expression inside quotes.

lethal dawn
#

I'm trying to extract the counter attribute from the trigger payload for my hue dimmer switch via MQTT integration

I've managed to find that the counter is included in the variable {{ trigger.to_state }} but the value of that looks like this:

<state sensor.lounge_dimmer_action=up-press; action=up-press, brightness=255, counter=1, duration=0, linkquality=78, update=state=idle, update_available=False, friendly_name=Lounge Dimmer action, icon=mdi:gesture-double-tap @ 2021-01-18T03:12:05.004430+00:00>

Is there inbuilt templating to work with that format, or am I going to have to figure something else out?

nocturne chasm
#

Copy this to the template editor and see if it will change with different button presses {{ state_attr('sensor.lounge_dimmer_action', 'action') }}

#

Or maybe just just the state of the sensor

lethal dawn
#

just found it actually - trigger.to_state.attributes.counter

#

Working Automation

- alias: Dimmer - Bedroom (up-press)
  trigger:
  - platform: state
    entity_id: sensor.bedroom_dimmer_action
    to: up-press
  action:
  - service: light.turn_on
    data:
      brightness: '{{ (states.light.bedroom_light.attributes.brightness + trigger.to_state.attributes.counter * 255 / 10) | int }}'
    entity_id: light.bedroom_light
#

only got my zigbee2mqtt running this weekend, so only just getting to learn all the pieces that make things move - prior to that I was just integrating with hue bridge which was 🚮

#

just found the template editor - that got me over the last hurdle

#

is there any reason lots of ppl here use state_attr instead of dot notation?

nocturne chasm
#

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

lethal dawn
#

yup - just found that in your link, thanks

dreamy sinew
#

ehh trigger.<to/from>_state.attributes is fine enough

#

assuming you don't completely fubar your trigger

nocturne chasm
#

Just a guess but seems like the action attribute would actually provide the correct state

lethal dawn
#

technically I'm also loading the light state

#

coming from a heavy .net background - dot notation feels far more natural - I'll keep an eye on the error log and see if it becomes a problem

dreamy sinew
#

oh, yeah might as well play it safe for that one

#

using the object notation will raise exceptions if the thing you're looking for doesn't exist

lethal dawn
#

I mean, if the light hasn't loaded/initialized yet - then the automation isn't going to work anyways - so having a log of why it failed could come in useful

dreamy sinew
#

it doesn't give you the why, just a big nasty exception

lethal dawn
#

yup - but silent failure is worse 😂

nocturne chasm
#

Where as the other way you get a none doesn’t exist type error I think

lethal dawn
#

ah - may be more useful then

dreamy sinew
#

vs state_attr() which handles the problem and you can handle the return with defaults

spring zenith
#

With the help of some fine people i got something working.
And today... it does not work any more?
made automations.yaml file empty. Pasted the previously working code in . so now i have only 1 automation.
An its not working anymore? 😖

deft timber
young jacinth
deft timber
#

Same issue with your previous code. Try fixing the quotes

#

What I don't understand is this is_state('input_boolean.lighting_'~trigger.entity_id, 'on') --> trigger.entity_idwill be something like domain.entity, so input_boolean.lighting_domain.entity will not be a valid entity id

#

I guess what you want is to remove the domain part before concatenation. Like so:
is_state('input_boolean.lighting_'~trigger.entity_id.split('.')[1], 'on')

mint viper
#

how would i write a template so that a "wait for trigger" action goes off 30 mins before the time in a time input helper?

#

i have never used templates before

deft timber
#

not sure this is the most efficient way but this should work : {{as_timestamp(now()) + 30*60 >= as_timestamp(states('input_datetime.your_entity')) }}

mint viper
#

thanks

glossy viper
deft timber
#

this is not valid % set t = 7.5*{{state '(sensor.immax_temperature)'}}/(237.7+{{state '(sensor.immax_temperature)'}}) %}

#

You should not write {{}} within {% %}

#

and the quotes are wrong

#

{% set t = 7.5* (states('sensor.immax_temperature') | float)/(237.7+(states('sensor.immax_temperature')| float)) %}

glossy viper
#

ty

deft timber
#

& {% set e= 6.112 * et * ({{state '(sensor.immax_humidity)'}}/100) %} should be {% set e= 6.112 * et * ((states('sensor.immax_humidity')|float)/100) %}

glossy viper
#

is working. now i can integrate in a template sensor with macro as value ?

deft timber
#

yes, you put your macro in the value_template of your sensor

#

though why are you using a macro here?

#

why don't just put

value_template: >
  {% set T = 2 %}
  {% set H = 45 %}
  {% set t = 7.5* (states('sensor.immax_temperature') | float)/(237.7+(states('sensor.immax_temperature')| float)) %}
  {% set et = 10**t %}
  {% set e= 6.112 * et * ((states('sensor.immax_humidity')|float)/100) %}
  {% set humidex = T+(5/9)*(e-10) %}
  {% if humidex < T %}
    {% set humidex = T %}
  {% endif %}
  {{humidex}}
glossy viper
#

because i am dumb? :))

deft timber
#

lol

#

is it just me or you are not using H ?

glossy viper
#

h = humidity?

deft timber
#

since you get if from the sensor now, you don't use it in your macro, nor it is needed to define it as avariable

glossy viper
#

i see. indeed i have this smart guy called immax that has temp humidity and lux measurements

#

i guess I can eliminate T and H

deft timber
#

You can make it clearer

value_template: >
  {% set temp = states('sensor.immax_temperature') | float %}
  {% set humid = states('sensor.immax_humidity') | float %}
  {% set t = 7.5*temp/(237.7+temp) %}
  {% set et = 10**t %}
  {% set e = 6.112 * et * humid / 100 %}
  {% set humidex = temp +(5/9)*(e-10) %}
  {% if humidex < temp %}
    {% set humidex = temp %}
  {% endif %}
  {{humidex}}
#

Or

value_template: >
  {% set temp = states('sensor.immax_temperature') | float %}
  {% set humid = states('sensor.immax_humidity') | float %}
  {% set t = 7.5*temp/(237.7+temp) %}
  {% set et = 10**t %}
  {% set e= 6.112 * et * humid / 100 %}
  {% set humidex = temp +(5/9)*(e-10) %}
  {{ [humidex, temp] | max }}
glossy viper
#

even nicer

#

when u know syntax...things are so simple

#

to have only digit number i put {{ [humidex, temp] | max | float }} ?

#

uh..doesn't work

deft timber
#

you mean to round it ?

glossy viper
#

yup. now i have 23.66250298780825

deft timber
#

| round

glossy viper
#

pf..told u i am du... :))

deft timber
#

🙂

glossy viper
#

maybe too old for this 😦

#

and | round (2) will be 2 decimals ?

deft timber
#

yep

#

and | int if you just want a floor. (not a rounding then)

lime grove
#

when defining sensors in the configuration.yaml it starts with these 3 lines

#

sensor:

  • platform: template
    sensors:
#

does sensor: have to be a unique name to each sensor?

#

as im running in to issues when adding a second template which is killing the one before it

glossy viper
#

sure

#

otherwise u cannot differentiate them

#

but put them in separate files

deft night
#

where can you find the template code used to build the states card? I want to make a markdown template showing the attributes for a specific sensor in a similiar way

mighty ledge
# lime grove sensor: - platform: template sensors:

There's multiple ways you can add more template sensors:

sensor:
  - platform: template
    sensors:
      a:
        ...
  - platform: template
    sensors:
      b:
        ...

or

sensor:
  - platform: template
    sensors:
      a:
        ...
      b:
        ...

or

sensor:
  - platform: template
    sensors:
      a:
        ...
sensor b:
  - platform: template
    sensors:
      b:
        ...
mighty ledge
#

i.e. maybe supply a picture of what you're talking about

deft night
#

just print out the contents in yaml

#

dont want to bother with formatting, a nice indented list will do

mighty ledge
#

Yeah, that's not a simple template. You'd need to show the object you intend to format with yaml. The template would most likely be one of the harder templates to come up with as it would require recursion with a macro.

deft night
#

hehe, yeah I was hoping to steal it from the github source 🙂

mighty ledge
#

it's written in python, so its not transferable

deft night
#

aah, I see. i thought it uses templating internally aswell

mighty ledge
#

no

#

you're semi in luck

#

because I wrote something like this a year ago

deft night
#

yeah, ideally this could be a custom card for everyone to use

mighty ledge
#

so who's going to develop it?

deft night
#

just drop it in a view for those couple sensors you use for housekeeping or other interesting stuff 🙂

#

my knowledge of python is rudimentary, but if there is interest why not

#

so far I've written a couple of small tools for MQTT stuff mostly

mighty ledge
#

well cards are written in JS or TS

#

the whole frontend is JS/TS

deft night
#

but I imagine they have access to those elements that render the entity in developer tools

mighty ledge
#

that depends if it was made generic or not

subtle shore
#

how do i print attributes as json for my payload?
payload: "{ \"state\": \"{{ trigger.to_state.state }}\", \"attributes\": {{ trigger.to_state.attributes }} }"
results in

{ "state": "idle", "attributes": {'friendly_name': 'LibreELEC Livingroom', 'supported_features': 186303} }
#

but should look like this:
{ "state": "idle", "attributes": { "friendly_name": "LibreELEC Livingroom", "supported_features": "186303" } }
e.g.

{
"state": "idle", 
"attributes": {
  "friendly_name": "LibreELEC Livingroom",
  "supported_features": 186303
  }
}

i tryed the to_json - ( {{ trigger.to_state.attributes | to_json }} ) which does not work at all Object of type mappingproxy is not JSON serializable

#

i think this belong here. not to automation.
posted that accidentally in the wrong channel

#

i have tried

      payload_template: >
       {% set payload_data = "{{ trigger.to_state.attributes | to_json }}" %}
#       stringified object: {{ payload }}
#       object|to_json: {{ payload |to_json }}
      payload: "{{ payload_data }}"
#

the error was two or more values in the same group of exclusion 'payload' @ data[<payload>]

brisk temple
#

int in json usually aren't wrapped in ""

#

you want it to be a string?

deft timber
#

If I understand the message, it says you can't set a payload && payload_template at the same time, you have to return payload_data in payload_template

subtle shore
subtle shore
#
      payload_template: >
       {% set payload = "{{ trigger.to_state.attributes | to_json }}" %}

will set an empty payload

deft timber
#

you have to return something

#

you shoud write payload_template: "{{ trigger.to_state.attributes | to_json }}"

subtle shore
#

i also tried an {{ trigger.to_state.attributes | replace( '\'', '\"' ) }} with no success. Error loading /etc/homeassistant/configuration.yaml: while scanning a double-quoted scalar

subtle shore
#

Object of type mappingproxy is not JSON serializable

#

GOT IT!

#

ATM i donno why

       payload: >
        { "state": "{{ trigger.to_state.state }}", "attributes": {{ trigger.to_state.attributes | replace( '\'', '"' ) }} }
{
  "state": "off",
  "attributes": {
    "friendly_name": "LibreELEC Livingroom",
    "supported_features": 186303
  }
}
#

kind of...
that media_position_updated_at and the is_volume_muted crashes my json.
{ "state": "playing", "attributes": {"volume_level": 0.66, "is_volume_muted": False, "media_content_type": "video", "media_duration": 3523, "media_position": 1169, "media_position_updated_at": datetime.datetime(2021, 1, 18, 15, 36, 13, 727521, tzinfo=datetime.timezone.utc), "media_title": "Test Video", "media_album_name": "", "media_series_title": "", "media_season": -1, "media_episode": -1, "friendly_name": "LibreELEC Livingroom", "entity_picture": "/api/media_player_proxy/media_player.livingroom_libreelec?token=XX&cache=XX", "supported_features": 186303} }

i need a different approach

silent barnBOT
subtle shore
#

yeah. i thought the same...
is there no better way?

sage aurora
#

I need to divide a value by 3600 to get the proper sensor value. Any ideas? I found some reference to multiplying instead {{ value | multiply(1/3600) | float(2) }}

#

I guess that's the best way?

#

Err sorry, opposite : 3600 / value is what I need to do. In any case, that gave an error as value is maybe a string?

subtle shore
#

100*(1/3600)= 0.02778
100/3600= 0.02778

so, it will be the same

#

oh. nvm

sage aurora
#

Maybe I can cast it to float first to keep it more readable.. eg value_template: "{{ ((3600 / (value | float)) | float(2) }}"

#

Invalid config for [sensor.mqtt]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['value_template']. Got '{{ ((3600 / (value | float)) | float(2) }}'. (See ?, line ?).

#

Too many brackets 🙂

subtle shore
#

value_template: "( ((3600 / ( {{ value }} | float ) | float(2) )"
should it not look like this?

deft timber
#

?

subtle shore
#

sry. i just startet with templating.

regal seal
#

When configuring a value_template and the json output has a weird character in it, what's the proper way to escape the template so it will parse properly? Example:

- platform: mqtt
    name: "Roxy - Position Event"
    state_topic: "AutoPi/event.vehicle.position"
    value_template: "{{ value_json.@tag }}"
subtle shore
sage aurora
#

Here's what did it : value_template: "{{ '%.2f'%(3600 / (value | float)) | float }}"

subtle shore
regal seal
#

Have not tried that yet. Worth a shot I suppose

regal seal
#

that is an output string literal as opposed to part of a variable name, but also worth a try, yeah.

subtle shore
regal seal
#

yep. Just tried that -- configuration checker is not happy with that.

#

nor does it like %40

deft timber
subtle shore
dreamy sinew
#

Try |urlencode at the end

subtle shore
#
- platform: mqtt
    name: "Roxy - Position Event"
    state_topic: "AutoPi/event.vehicle.position"
    value_template: >
    {{ value_json.'\x40'tag }}
regal seal
#

Invalid config for [sensor.mqtt]: invalid template (TemplateSyntaxError: unexpected char '@' at 14) for dictionary value @ data['value_template']. Got '{{ value_json.@tag | urlencode }}'. (See ?, line ?).

dreamy sinew
#

Ahh ok I see the problem

regal seal
#

it has to do with the python variable name

dreamy sinew
#

value_json.get('@tag')

regal seal
#

That sounds promising, let me try that. Thanks.

#

configuration valid, reloading, 🤞

subtle shore
#
found character '%' that cannot start any token```
subtle shore
deft timber
#

in payload

subtle shore
#

still the same.

deft timber
#
payload: >
 {% set str = '{ "state": "'~trigger.to_state.state~'", "attributes": {' %}
 ...
#

strange...

subtle shore
#

damn. missed that > -.-"

#

{'state': 'paused', 'attributes': {'volume_level': '0.66', 'is_volume_muted': 'False', 'media_content_type': 'video', 'media_duration': '3523', 'media_position': '1308', 'media_position_updated_at': '2021-01-18 16:35:28.771510+00:00', 'media_title': Test Video': '', 'media_series_title': '', 'media_season': '-1', 'media_episode': '-1', 'friendly_name': 'LibreELEC Livingroom', 'entity_picture': '/api/media_player_proxy/media_player.livingroom_libreelec?token=XXX&cache=XXX', 'supported_features': '186303'}}

regal seal
#

@dreamy sinew thanks, get('@tag') worked!

subtle shore
#

i think im happy with my solution.
it will work for me.
thank you very much.
its not pretty but its mine. 😛

should the attributes not already be in json foram?
if not:
maybe there will be a simpler way in the future.
something like trigger.to_state_json.attributes or something?
as feature request maybe?

fossil totem
#

i'm looking for some dealing with filtering items out of a list. based on some forum comments, there currently aren't filters defined which will make this easy but... well who knows.

#

So, here's a list of lights by entity name: {% set lights = states.light | map(attribute='entity_id') | list %}

#

and when i do a {{lights}}, cool there's my list

#

what i'd like to do is to remove items from that list matching a certain string

queen meteor
#

use | exclude

dreamy sinew
#

Ah, is that a HA addition?

subtle shore
fossil totem
#

trying to find docs on that...

#

TemplateAssertionError: no filter named 'exclude'

#

not coming up with much - any idea where i can find docs on how to use exclude? even an example would do

queen meteor
#

It is actually reject, not exclude... my bad. too many programming languages, everybody does things differenty. ```
{% set lights = states.light | map(attribute='entity_id') | list |reject("equalto", "light.family_room_lights")|list %}
{{ lights }}

#

if you want to use wild cards, you may have to use regex...

dreamy sinew
#

Which I don't think you can use in reject iirc

fossil totem
#

i will for sure have to use some sort of wildcard/regex, as i will not know ahead of time the full name of the element(s) in the list i want to remove

#

is there a list of supported filters and tests?

dreamy sinew
#

The default set from jinja2 plus any the HA template docs talk about

silent barnBOT
dreamy sinew
#

Search "built-in filters"

fossil totem
#

roger that. so i see reject there, i think my problem is the there are no built-in tests that can do substring or regex

dreamy sinew
#

Yep that's the main issue. The regex stuff that was added in HA are filters and not tests so you can't combine that way

#

But they might work on their own

fossil totem
#

not getting anywhere there. thinking a for loop might be my solution.

dreamy sinew
#

Might be unfortunately

fossil totem
#

which i guess brings me to my next problem - can i concatenate a list?

#

goal - create an empty list foo, iterate through my list of lights in a for loop, run my regex test on each element, if it matches, add it to foo

dreamy sinew
#

Yes but no

fossil totem
#

maybe make a big string, with comma separation and do a join afterwards?

thorny snow
#

isn't that all a list is anyway, with [] on the outside?

fossil totem
#

hey @thorny snow long time my friend!

thorny snow
#

hey 🙂

dreamy sinew
#
{% set ns = namespace(l1=[]) %}
{% for item in list if 'foo' in item %}
{% set ns.l1 = ns.l1 + [item] %}
{% endfor %}
{{ ns.l1 }}
#

something like that works @fossil totem

#

but you have to use a namespace and you have to recreate the list each time like that

fossil totem
#
{% set filtered_lights = "" %}
{%- for light_entity in states.light | map(attribute='entity_id') | list -%}
 {% if light_entity | regex_search("light.hasp_.*selected_.*ground_color") %}
 {%- else -%}
 caught {{light_entity}}
 {% set filtered_lights = filtered_lights + "," + light_entity -%}
 {%- endif -%}
{%- endfor -%}
dreamy sinew
#

that will fail for namespacing reasons

fossil totem
#

ok i gotcha. the code above doesn't work

#

and i'll try yours, thanks!

dreamy sinew
#

things inside the for loop can't touch things outside the loop

fossil totem
#

ahhhh that's why i'm not able to concatenate. mystery solved scoob!

dreamy sinew
#

yup. hence my un-helpful "yes but no" answer

#

i just had to switch to my laptop because i wasn't going to show my example typed out on mobile

thorny snow
#

LOL I think I was the one looking for the exclude filter and HASPs

dreamy sinew
#

namespacing is a good hack to get you around a few things but its definitely cumbersome

deft night
#

I guess I use it wrong?

timid osprey
#

Did you pipe a date time object?

deft night
#

how do I verify that before? as_timestamp work on it fine

#

{{ check.last_ping|as_timestamp }} =1610991122.0

#

{{ check.last_ping|relative_time }} = TemplateAssertionError: no filter named 'relative_time'

dreamy sinew
#

i don't think its a filter, its probably a global

#

try relative_time(check.last_ping)

deft night
#

yeah already did, it just returns the datetime obj

#

maybe if I format that one to a timestamp before...

#

hmm, then it retuns the timestamp

fossil totem
#
{%- set lights = namespace(light=[]) -%}
{%- for light in states.light | map(attribute='entity_id') | list -%}
 {%- if light | regex_search("light.hasp_.*selected_.*ground_color") -%}
 {%- else -%}
   {%- set lights.light = lights.light + [light] -%}
 {%- endif -%}
{%- endfor -%}
{{lights.light}}
#

it works!

#

also is the bot complaining about too many lines there or something?

charred dagger
#

The bot doesn't like jinja.

fossil totem
#

i'll play my watermelon card to defeat the bots X

timid osprey
#

ahh, I see now phnx how some of these are filters and some aren't

deft night
#

maybe it was disabled globally?

timid osprey
#

no, I just used it

fossil totem
#

@charred dagger that's... unexpected. are we not meant to use jinja or somesuch?

charred dagger
#

It's just saying that's not valid yaml syntax. Which it isn't.

timid osprey
#

the library discord uses for syntax highlighting doesn't have jinja

#

only like django and random other things

fossil totem
#

allright, just want to make sure i'm not being a bad chatter etc

timid osprey
#

you should be able to use django but the templating will still be fucky 😛

fossil totem
#

anyway @dreamy sinew you are a wizard my friend and i sure appreciate the input

timid osprey
#

odt, can you give me the exact state of your check.last_ping and I'll try to make 'er work for ya

deft night
timid osprey
#

thanks

deft night
#

well, thank you 🙂

#

really weird it doesnt do anything for me

#

its such an old timestmap, cant be any timezone weirdness

dreamy sinew
#

default behavior for most things that were added from HA is to return what it got sent if whatever it tries to do fails

#

that's what relative_time() wants to do

timid osprey
#

yeah, it is fun because as_timestamp has magic that makes it work I guess if it is a string 😛

#

forgiving_as_timestamp

#

she forgiving

deft night
#

seems so yeah

#

so probably a strptime format will work

timid osprey
#

I am using strptime to try and get it for you

#

yeah

#

if you want to toy with that, that is what I was doing

#

but might be easier to make it unix before parsing, lol

deft night
#

hmm, i made my node red http request return a json object instead of a string but that just breaks the entire attribute

#

(there is json to yaml conversion before the sensor is created)

#

last_ping: '2021-01-18T18:02:02+00:00' pretty sure it's the best Node Red can do

#

startAt: '2022-01-27T20:00:00.000Z' would be a proper datetime obj I guess

#

so its an issue with the API I use to get it from

timid osprey
#

I am doing something wrong, lol

deft night
#

might aswell do the conversion in node red, it has moment.js

dreamy sinew
#

i'm a fan of moment

deft night
#

plus makes it easier on the frontend

timid osprey
#

I used to use it but it was just massive and I like date-fns a lot more now

#

{{ strptime("2021-01-18T01:03:55+00:00", "%Y-%m-%dT%H:%M") }} not sure what I am overlooking 😛

#

no worky

dreamy sinew
#

you gotta account for the tz

timid osprey
#

okay, uno momento

#

hrmm, I don't see one for TS that have :

#

I thought it would at least give me something even though I didn't do the z yet

dreamy sinew
#

nope because the format you're defining doesn't match the string you're sending

timid osprey
#

ahh, I just was hoping it would return the bits that did match

#

I tried to strip the z jjust as a test and still wonky

#

oh, I am blind as usual

dreamy sinew
#

"%Y-%m-%dT%H:%M%z"

timid osprey
#

NO

#

I JUST GOT IT

dreamy sinew
#

lol

timid osprey
#

I was missing a : but you are too, lol

#
{% set time_sz = "2021-01-17T01:03:55+00:00" %}

{{ relative_time(strptime(time_sz, "%Y-%m-%dT%H:%M:%S%z"))  }}
dreamy sinew
#

oh i just copy-pasted what you had

timid osprey
#

@deft night DID IT

#

YEAH< THAT IS THE PROBLEM

#

I AM BLIND

#

😛 ❤️

#

my rubber_duck debugger is on the fritz

dreamy sinew
#

lol

deft night
#

thanks a ton

#

i can never understand timestamps in a table 🙂

timid osprey
#

no problem. I wanted to learn that now so i didn't deal with it later

#

I imagine HA will eventually expose some of the internal date functions they have eventually

#

or just some of the native ones

deft night
#

thanks again! now I can leave it for another time how to figure out how to append a new object into an array using jsonata

meager orchid
#

Need a 2nd set of eyes on this one please:

#
  • platform: template
    sensors:
    radiant_energy_cost:
    value_template: {{ ((states('sensor.radiant_kwh_raw_data') | float * 0.13)) | round(2) }}
    friendly_name: 'Radiant Cost Today'
    unit_of_measurement: "$"
#

Error is:

#

Error loading /config/configuration.yaml: invalid key: "OrderedDict([("((states('sensor.radiant_kwh_raw_data') | float * 0.13)) | round(2)", None)])"
in "/config/configuration.yaml", line 1906, column 0

#

Oddly, if I put a $ sign before {{, it evaluates properly

#

but that makes it a string, and my graphs won't accept a string

brisk temple
#

you need "" around your value_template

modest sparrow
#

Hey guys, hope you can help. I'm building a script that uses an input_select. Based on the value of input_select I'd like to start one automation or another. No issues here, however: Both services need different attributes to be set, I can't get this to work with templates.

#

Meaning: I can set a value to a specific attribute but one service needs different service data than another. If I specify too much service data the service wont work

#

For example, see this code:

#
  • service: media_player.play_media
    data_template:
    entity_id: >
    {% if is_state("input_select.chromecast_radio", "Kitchen") %}media_player.kitchen
    {% elif is_state("input_select.chromecast_radio", "Everywhere") %}media_player.home_group
    {% endif %}
    media_content_type: 'audio/mp4'
#

I'd only like to specify media_content_type if "input_select.radio_station" is not Spotify. If it's Spotify I shouldn't send media_content_type because the service spotcast.start doesn't accept it

#

Hope you can point me in the right direction. I saw a solution another based on automations, but I don't want to immediately start something on a change of the input_select

brisk temple
#

just do another if/elif/endif in media_content_type based on the input_select.radio_station like you did for the entity_id

modest sparrow
#

But won't that still send media_content_type itself?

meager orchid
#

@brisk temple thanks - I swear I tried that - but it works now - thanks

modest sparrow
#

If I try to call the service in Developer Tools, I get an error stating extra keys are not allowed. Testing this:

#

entity_id: media_player.kitchen
media_content_type: ''
uri: "spotify:playlist:29aiPfdrGUh6TDEjvsJV3r"

#

Because media_content_type is not accepted for the service spotcast.start

dreamy sinew
#

are those options hard-coded?

#

for each?

#
{% set service_data = {'spotify': {'entity_id': 'media_player.kitchen', 'uri': 'spotify:playlist:29aiPfdrGUh6TDEjvsJV3r'}, 'input2': {}} %}
{{ service_data[states('input_select.radio_station')] }}
#

oh, you're using 2

#

probably need to stack a few things but could make it work

#

maybe even make a macro

lime grove
#

I have lots of sensors in my configuration.yaml, how do I split them out to make it tidier?

ivory delta
modest sparrow
#

Thanks phnx, didn't know about service_data. I'll take a look around your suggestion, sounds like it could work 🙂

#

Thanks for helping along!

dreamy sinew
#

that's just a random var name

#

it can be whatever you want it to be

modest sparrow
#

Figured as much, sorry don't understand the concept so much yet..

#

Need to figure out how to use variables in setting these states, but I'll Google my way around first 🙂

#

"{{ service_data[states('input_select.radio_station')] }" just lists all the stuff I've set in the previous line right? To dynamically assign the required service attributes?

dreamy sinew
#

you set keys in that dict for each input value. that will return the payload for that input value

modest sparrow
#

Thanks again 🙂

dreamy sinew
#

probably need to do a bit further

#

since you're working against 2 input selects

modest sparrow
#

Yeah, now trying to figure out to set a variabele based on one input select to include in the mentioned service_data dict

dreamy sinew
#
{% set location_map = {'Kitchen': 'media_player.kitchen', 'Everywhere': 'media_player.home_group'} %}
{% set entity = location_map.get(states('input_select.chromecast_radio'), 'media_player.YOURDEFAULT') %}
{% set service_data = {'spotify': {'entity_id': entity, 'uri': 'spotify:playlist:29aiPfdrGUh6TDEjvsJV3r'}, 'input2': {'entity_id': entity}} %}
{{ service_data[states('input_select.radio_station')] }}
modest sparrow
#

Wow

dreamy sinew
#

for a total of:

- service: media_player.play_media
  data_template: >-
    {%- set location_map = {'Kitchen': 'media_player.kitchen', 'Everywhere': 'media_player.home_group'} -%}
    {%- set entity = location_map.get(states('input_select.chromecast_radio'), 'media_player.YOURDEFAULT') -%}
    {%- set service_data = {'spotify': {'entity_id': entity, 'uri': 'spotify:playlist:29aiPfdrGUh6TDEjvsJV3r'}, 'input2': {'entity_id': entity}} -%}
    {{ service_data[states('input_select.radio_station')] }}
#

meh, my spacing is off

modest sparrow
#

No worries, this is a huge help already

#

Also not looking for copy/paste answers, this is more than I could wish for

dreamy sinew
#

its kinda hard to explain without giving examples

#

kicks @ivory delta

ivory delta
#

Ouch

dreamy sinew
#

😛

#

i'd probably take that even further and make a macro to save on memory but meh

modest sparrow
#

Perfect, I understand the code @dreamy sinew, will adapt it to match my situation. Thanks for giving me some insight and learning me some new approaches

dreamy sinew
#

np these challenges can be fun

lime grove
#

How would I take energy in kwh, then times it by my unit price to give me a visual representation of cost?

modest sparrow
#

Perhaps I do need some more help 🐵

silent barnBOT
modest sparrow
#

Giving me the following two errors, but I cant figure out why:

#

Invalid config for [script]: [data_template] is an invalid option for [script]. Check: script->data_template. (See /config/configuration.yaml, line 15).
Invalid config for [script]: expected dict for dictionary value @ data['sequence'][1]['data_template']. Got None extra keys not allowed @ data['sequence'][1]['mode']. Got None. (See /config/configuration.yaml, line 15).

#

Would you mind to take another look @dreamy sinew ?

modest sparrow
#

Brought it down to this: https://pastebin.com/6kiAx9hS Now I only get the error "Invalid config for [script]: expected dict for dictionary value @ data['sequence'][1]['data_template']. Got None"

#

I think the error is in "{{ service_data[states('input_select.radio_station')] }}" but I've selected a proper value (Spotify in this case). Also if I use "{{ service_data[states(music_type)] }}" (which I want to do because I want to set it dynamically) I get the same result

silent barnBOT
north acorn
#

can someone point me in the right direction with creating 'smart' templates? Basically I want to create some kind of 'auto-fill' template, but my templating skill is lacking. I basically want to create a template sensor like 'auto-entities' card, that populates the sensor (if that's possible).

So this code, will be shorter and I don't have to update it each time I install a new sensor. Code is above this post

silent barnBOT
#

@north acorn Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

Please take the time now to review all of the rules and references in #rules.

ivory delta
#

That's... slightly over 15 lines. Please pay attention to the rules.

#

What you want is maps. Here's an example (not quite what you're after but it's a starting point):
{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list | count }}

#

It'll count up how many entities match that pattern.

north acorn
#

thanks for the advice! So I can use that kinds of templates for a template sensor if I understand correctly right?

north acorn
#

follow up question: is it also possible to use multiple variables to search, to look into multiple entity_id types? And to also tie in the state (so to only show matching entities that are also on)?

little plinth
#

Where can I define a unit of measure? I want to make it handle W (Watt) as number.

versed idol
#

how to create input_datetimes for - 1060 seconds before sensor as my template only able to triggered manually please

https://paste.ubuntu.com/p/cS5zXxtRH5/

still confuse creating input_datetimes in config.yaml

input_datetime:
sholat_subuh:
seconds: 1060

eternal basalt
#

haven't had luck googling, reading stuff, or just testing things out, trying to use and operator in notify message...simplified message that works is message: '{% if is_state("sensor.sensor2", "12") %} "Test Alert for Kitchen Alarm" {% elif is_state("sensor.sensor3", "12") %} "Test for Basement Alarm" {% elif is_state("sensor.sensor4", "12") %} "Test for Hallway Alarm" {% endif %} trying to use an and function alongside these something like message: '{% if is_state("sensor.sensor2", "12") %} "Test Alert for Kitchen Alarm" {% elif is_state("sensor.sensor3", "12") %} "Test for Basement Alarm" {% elif is_state("sensor.sensor4", "12") %} "Test for Hallway Alarm" {% endif %} suggestions what terms i'm not searching for to try and find examples?

timid osprey
#

dev tools

#

templating

#

There are links at the top for jinja and the built in HA jazz

eternal basalt
#

templating examples don't seem to quite follow the same format in message:, will read over it again

#

or at least haven't figured out where to put and || etc

#

thanks

#

50/50 is just a syntax i'm missing lol

timid osprey
#

look at jinjas examples as they will focus on syntax rather than the HA particulars

eternal basalt
#

awesome

dreamy sinew
#

what are you trying to and?

eternal basalt
#

trying to give a message: if sensor1 and sensor2=0

#

message: '{% if is_state("sensor.sensor1", "0") and is_state("sensor.sensor2", "0") %} "Test Success" {% endif %}'

#

trying to figure out where to put an and operator

#

also can't seem to get the multi-line strings working in the message: but that's secondary after i figure out the and

dreamy sinew
#

that should be correct

#

multiline:

message: >-
  {% set thing = "foo" %}
  {{ thing }}
eternal basalt
#

ha, so i did have it right, ya, was just a syntax thing, % before { gets me often typing fast =/

#

awesome, thanks for pointing that out

#

and operator working just fine now

dreamy sinew
#

way i remember it:
{% %} logic statements
{{ }} print statements

eternal basalt
#

multi line a bit wonky, may try the literal \n escapes, but at least my full single line stuff is working

dreamy sinew
#

gotta strip the newlines from your logic blocks

#

{%- -%}

#

that'l ensure that they would render completely inline

thorny snow
#

@ivory delta
earlier you posted this : "{{ states | map(attribute="name") | map('regex_search','light.bed.*') | select('true') | list | count }}" and I can't figure out what's it's supposed to do

dreamy sinew
#

i think that was mono

thorny snow
#

it returns zero for me, and i can't find any docs on the map function

#

Ooops. you are right

#

oh, I cahnged name from entity_id

#

I have been trying to get it to do anything beside error or "0"

dreamy sinew
#

takes all states in the system and pulls out their friendly name if it exists and the entity_id if it doesn't and makes a list. Searches that list for items that contains light.bed in their name as a list of true/false pulls out the trues maps it to a list and then gives a count

thorny snow
#

it's just seeing how many bed lights are on?

#

or have frinedly name?

dreamy sinew
#

probably a better way to do it would be

{{ states.light | map(attribute="entity_id") | map('regex_search','light.bed.*') | select('true') | list | count }}
#

would be better to force the entity_id since that is what is getting tested against

#

that would be a count of the entities with light.bed in their name

#

dunno what the practicality of that would be but it is a thing

thorny snow
#

well, I can't get it to work, which is what's bothering me

timid osprey
#

I like to remove pipes from the back and work my way to the front to understand what is happening along all of the pipes

#

'just easier to sort things when you can see it

thorny snow
#

I've tried that also

#

back to list gives me " []" and removing list gives me "<generator object select_or_reject at 0x7fd350272dd0>"

#

anything with the map command dies

dreamy sinew
#

what's the full thing?

thorny snow
#

huh?

#

Ok, this is straight from the docs: {{ users | map(attribute="username", default="Anonymous")|join(", ") }}

dreamy sinew
#

so do you get a bunch of anon, anon, anon?

thorny snow
#

no, nothing. except the errors I just listed

timid osprey
#

add the | list back on the end and remove the stuff before it, sorry

dreamy sinew
#

i don't get anything back for {{ users }}

thorny snow
#

I populated users with a for persons

timid osprey
#

Ignore me. I don't want to interrupt phnx helping you

dreamy sinew
#

{{ states.person |list }}

thorny snow
#

I was trying that right now 🙂

#

that lists both users correctly

eternal basalt
#

ha, it auto formatted it for me once i saved the automation message: >- {% if is_state("sensor.first_alert_brk_brands_inc_zcombo_smoke_and_carbon_monoxide_detector_alarm_type_4", "12") and is_state("sensor.first_alert_brk_brands_inc_zcombo_smoke_and_carbon_monoxide_detector_alarm_level_4", "0") %} "Hallway Alarm Test" {% endif %} title: Smoke Alarm - Kitchen

#

i entered it as single line, HA is telling me i should use the multiline eh

dreamy sinew
#

lol

#

@thorny snow i'm having a hard time pulling attributes from those objects

#

they might have values mapped out weirdly

thorny snow
#

as I said, this is straight from the docs, and is not working for me: {{users|map(attribute="username", default="Anonymous")|join(", ") }}

#

when I populater with users

#

it's weird

#

map seems broken for me

timid osprey
#

phnx, the user thing isn't what he is actually even trying to do, right? just an example of the same sort of thing

#

map works fine

#

I feel like I am missing something, sorry 😛

thorny snow
#

is that regex off?

#

well, it's using a dot, but it shold be escaped.. finctionally the same

dreamy sinew
#

map generally works but i think there's something up with this object. the __repr__ that you're seeing isn't showing direct attributes

thorny snow
#

I am kinda not even seeing the purpose, when can't we just easily pull attributes without map?

#

easily evaluate their state, list and count them

dreamy sinew
#

yeah the person object really doesn't have much on it

#

those aren't attribs of person

#

you can only get things that are marked as @property

#

you can without a map. the map just pulls all of them at once

#

person was just a bad thing to start with

thorny snow
#

hahah figures

dreamy sinew
#

the person object is really limited

#
{% for person in persons %}
{{ state_attr(person.entity_id, 'friendly_name') }}
{% endfor %}
#

that works

thorny snow
#

I see that!! So that regex just looks at the entire objext and returns a count of the true...

dreamy sinew
#

nah, the regex is a test so that returns true/false on its own

#

if the regex matches on each

eternal basalt
#

final message template turned out very nicely, entire alert for the first alert zcombo (first gen, not G) smoke alarms works well

#

thanks for the assistance, hope i can find a couple threads to update as others definitely have had issue getting these to play nice lol

modest sparrow
#

So, I've tried some more after figuring out I can use the Developer Tools to test my templating (that took me a while...). Maybe someone can tell me why this isn't working:

#

{%- if is_state("input_select.radio_station", "Spotify") -%}
{%- set music_type = 'Spotify' -%}
{%- else -%}
{%- set music_type = 'Radio' -%}
{%- endif -%}
{%- set service_data = {'Spotify': {'entity_id': entity, 'uri': 'spotify:playlist:29aiPfdrGUh6TDEjvsJV3r', 'random_song': 'true'}, 'Radio': {'entity_id': entity, 'media_content_id': channel, 'media_content_type': 'audio/mp4'}} -%}
{{ service_data[states(music_type)] }}

#

If I use {{ service_data[states('input_select.radio_station')] }} it works (as long if its set to Spotify), but I can't get it to work with a custom variable. {{ service_data[states('Spotify')] }} also fails. I'm not sure how to declare the custom variable in the last line

deft timber
#

music_type is a variable, not a state

#

{{ service_data[music_type] }} at the end

modest sparrow
#

That makes total sense. Thanks @deft timber ! That solved the last piece

#

Hmm, perhaps it didn't. I know the stuff gets outputted correctly but I still receive an error after loading my script. See the script and error: https://pastebin.com/kbHcR1e9

deft timber
#

Could you try replacing data_template with data ? this has changed some versions ago

#

not sure it will change your issue though

modest sparrow
#

Same error unfortunately. If I try to specify the data manually under data_template it works as expected

deft timber
#

I understand from the error that you cant return a dictionary as you do, but that you should do something like this:

data: 
  entity_id: >-
    {{ ... }}
  media_content_id: >-
    {{ ... }} 
  media_content_type: >-
    {{ ... }}
#

and split yor template in 3

modest sparrow
#

The problem with that approach is that depending on the service I call (either spotcast.start or media_player.play_media, it requires different values for data. spotcast.start won't accept media_content_type for example and wont run it I specify it

#

That's why I was hoping I could use a dictionary as service data

deft timber
#

Maybe a choose: is necessary then

modest sparrow
#

I could do it with an automation, but then it'll get triggered on the input_select change, where I want to start it when executing the script

#

Hmm, didn't know choose: will look into that, thanks

glossy viper
modest sparrow
#

Thanks @deft timber, conditions/choose was the solution in the end. Took me some struggling but I managed to get it working 🙂 https://pastebin.com/TDgWUWcc is the final script

#

Some redundant code still, but that's something for later. At least now my lovelace multi-room-audio selector is working 🙂

deft timber
#

And the last template could be written this way:

media_content_id: >
  {% set radios = {"NPO Radio 2": "https://icecast.omroep.nl/radio2-bb-mp3",
   "Veronica": "https://20723.live.streamtheworld.com/VERONICA.mp3",
   "3FM": "http://icecast.omroep.nl/3fm-bb-mp3",
   "Sky Radio": "https://19993.live.streamtheworld.com/SKYRADIO.mp3",
   "RTV Oost Radio": "http://streams.rtvoost.nl/audio/oost/mp3",
   "NDR 2": "http://www.ndr.de/resources/metadaten/audio/m3u/ndr2.m3u",
   "Antenne": "http://vip-icecast.538.lw.triple-it.nl/WEB17_MP3",
   "Star FM": "http://85.25.209.152/berlin.mp3"} %}
  {{ radios[states("input_select.radio_station")] }}

A (little) bit clearer 🙂

modest sparrow
#

Thanks again for the feedback! Will incorporate the last piece of code and read up on deduplication of code

velvet coral
#

Hi all ... I'm struggling to fathom out a template sensor which I think I need to use to add a unit_of_measure for an image_processing.sevensegment_ocr_seven_segs SSOCR value. Fair amount of googling and referencing the template example at https://www.home-assistant.io/integrations/seven_segments/.

- platform: template sensors: power_meter: friendly_name: "Electricity monitor" unit_of_measurement: 'kWH' value_template: "{{ states('image_processing.sevensegment_ocr_seven_segs') }}"

I can't find how to access that sensor.

I'm very new to HA and struggling to get my head around templates. Any pointers, please? Keen to fathom this out because I will use it plenty in future I'm sure.

deft timber
#

I don't know if it a copy-past issue but your indentation is wrong

#

should be```yaml

  • platform: template
    sensors:
    power_meter:
    friendly_name: "Electricity monitor"
    unit_of_measurement: 'kWH'
    value_template: "{{ states('image_processing.sevensegment_ocr_seven_segs') }}"
#

and you can check if your sensor is well created in the devtools Tool > State screen

velvet coral
#

Thank you ... could be blasted indentation ... thanks for th pointer - restarting now.

#

Easy when you know how eh! Thanks again.

#

sorted

young jacinth
#

hi, is it possible to template the automation trigger?

    trigger:
      - platform: state
        entity_id: group.lighting_~area
        to: "on"

this wont work

deft timber
#

where is your area defined ?

#

you can create a template trigger

#
trigger:
  - platform: template
    value_template: "{{is_state('group.lighting_'~area, 'on')}}"
young jacinth
young jacinth
deft timber
#

It should work :-p. Can you share the entire automation?

young jacinth
#

oh you dont want that

deft timber
#

if you replace the template with:

trigger:
  - platform: template
    value_template: >
      {% set area = "what_area_should_be"%}
      {{is_state('group.lighting_'~area, 'on')}}

does this work ?

#

to check if it comes from the definition of the area

young jacinth
deft timber
#

Did you try what I proposed above?

#

I don't think you can use variables

#

in trigger

#

I made a test and it does work if you define the variable in the template, not if you define it in the variable: part, so it seems you can't use it in a trigger 😦

young jacinth
#

mh thats sad... i have to rethink my whole automation then...

#

too bad we cant template entity_ids too

deft timber
#

you can but not using variables define outside of the template

young jacinth
#

i mean like templating XXXX. in a package for example

input_select:
  natural_lighting_mode_XXXX:
deft timber
#

ok that you can't 🙂

young jacinth
#

there are reasons i think

deft timber
#

@lunar jasper , it will look like this:

#
{% set ns = namespace(list=[]) %}
{% for option in state_attr("input_select.playlist_options_filtered", "options") if option != states("input_text.playlist_chosen_random_source") %}
  {% set ns.list = ns.list+[option] %}
{%endfor%}
{{ns.list}}
#

if I understood correctly what you want

lunar jasper
deft timber
#

👍

edgy umbra
#

I’m trying to do a between color for my battery badge I’m using the code below at the moment but like to become another approach. If battery is above 60% color green, between 30/60% orange and below 30% red. Anyone know how this can be done. Thx in advance.

:host {
—label-badge-blue: {% if is_state(‘sensor.iphone_battery_level’, ‘> 60’) %} green {% else %} red {% endif %};
}

deft timber
#

is_state doesn't support '>'

#

states('sensor.iphone_battery_level') > 60