#templates-archived

1 messages · Page 117 of 1

candid scaffold
#

Is there anyway to get an object/entity with the current user? Can't find any references to that in the Developer Tools

#

Something like {{ user.is_admin }}

dreamy sinew
#

the templating system isn't aware of "who" is doing things

candid scaffold
#

So I can't make a "Welcome {{ user.username }}"-thingy on my dashboard, without getting this parsed to the templating system somehow?

dreamy sinew
#

not in the templates we talk about in this channel

#

there might be a custom card that can do something

edgy umbra
#

Any change explaining how I can become this. Battery greater than 60% green, between 30-60% orange and below 30% red. Thx in advance

candid scaffold
dreamy sinew
#

probably color_template in customize

#

or icon_template i don't remember

dreamy sinew
#

@subtle shore ugg gross i see what's happening

#

working something out

thorny snow
#

are templates the way to go for logging the amount of coffee my coffee machine makes a day?

subtle shore
dreamy sinew
#

this works

#
{% set d = {
  "state": states.light.ge_14294_inwall_smart_dimmer_level.state,
  "attributes": dict(states.light.ge_14294_inwall_smart_dimmer_level.attributes)
} %}
{{ d|to_json }}
subtle shore
thorny snow
#

its a rest based coffee machine that can make upto 12 cups per time it's run

dreamy sinew
#

lol discord hicup

#

@subtle shore i subbed in an entity i had to repro. you can swap that back with your trigger.x and it should work

subtle shore
#

i thought so.
but at first = copy and replace with my entity. 😛

dreamy sinew
#

yeah, you don't need the whole thing

#

i just split it out that way to make testing easier

subtle shore
#

so atm i got an initial json payload.
but if i start a playback the script fails

dreamy sinew
#

and easier to read on the tiny template tester box

subtle shore
#

Object of type datetime is not JSON serializable

dreamy sinew
#

ahh you have a datetime in there

timid osprey
#

that's odd. not casting for the JSON. neat

dreamy sinew
#

hmm, i'm not sure how to deal with that datetime

#

since you can't pop

silent barnBOT
subtle shore
#

ahh. damn+

dreamy sinew
#

hmm, i need something with a timestamp

timid osprey
#

I have that shit from yesterday that makes a timestamp

#

let me scroll up

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

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

yeah, but where its being accessed is gross

#

media_position_updated_at and tzinfo

timid osprey
#

oh, I misunderstood you before.

dreamy sinew
#

can't namespace hack it either

timid osprey
#

I wonder if adding filters is supported by custom_components, probably not

ivory delta
#

Nope

timid osprey
#

quits googling

dreamy sinew
#

no, that's managed by core/homeassistant/helpers/templates.py

timid osprey
#

thanks

ivory delta
#

I've never actually looked into it but whatever they've done to lock down the functionality of Jinja, I doubt there's a quick hack to add stuff back in.

subtle shore
#

i cant even get a valit time/date format for my payload alone? o.O

dreamy sinew
#

i can't find a way to get down to those values

#

probably have to build that dict out manually unfortunately

#

and it has to be done all at once since you can't modify a dict after it is created

subtle shore
#

so - lets build a python script.
my first at all. 😛

ivory delta
#

There's a first time for everything. Good luck.

subtle shore
#
# python3 ./python_dict_to_json_dict.py "{'state': 'paused'}" "{'attributes': {'volume_level': 0.66, 'is_volume_muted': False, 'media_content_type': 'video', 'media_title': 'Test Video', 'media_album_name': '', 'media_series_title': '', 'media_season': -1, 'entity_picture': '/api/media_player_proxy/media_player.livingroom_libreelec?token=XX&cache=XX', 'supported_features': 186303}}" "homeassistant/indoor/debug"

{"state": "paused"}
{"attributes": {"volume_level": 0.66, "is_volume_muted": false, "media_content_type": "video", "media_title": "Test Video", "media_album_name": "", "media_series_title": "", "media_season": -1, "entity_picture": "/api/media_player_proxy/media_player.livingroom_libreelec?token=XX&cache=XX", "supported_features": 186303}}
homeassistant/indoor/debug

seems fine for that

ivory delta
#

Easy with the code walls...

subtle shore
ivory delta
#

That's... what I said.

dreamy sinew
#

yeah, could definitely do it in python

#

but you can't import json no?

#

i don't remember the limitations of python_script

brisk temple
#

correct, you can't do imports on python_script

timid osprey
#

How did I not know about python_script, neat

subtle shore
silent barnBOT
#

@subtle shore 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.

brisk temple
subtle shore
#

i think i got it - til the mqtt.publish part. i use pyscript
is someone able to tell how i insert the variable service_data into this: mqtt.publish({service_data}, retain="false" )
translate python dict to json dict was not that hard at all. its actually 4 lines of code.
but i dunno if i can call that script as imagined. will see that.

young jacinth
#

hi,
i saw the template {{ user }} in the markdown card to pass the username of the logged in user. is something like this possible for scripts?

dreamy sinew
#

No

signal isle
#

Trying to get Aqara Cube's Side, when I read state of the sensor, it's

<template TemplateState(<state sensor.aqara_cube_action=; action=, angle=-23.71, battery=62, linkquality=131, side=1, voltage=2935, friendly_name=Aqara Cube action, icon=mdi:gesture-double-tap @ 2021-01-19T22:24:44.618917-05:00>)>

#

Any ideas on extracting the "side"? states.sensor.aqara_cube_action.side does not work

dreamy sinew
#

{{ state_attr('sensor.aqara_cube_action', 'side') }}

#

please review the template docs

signal isle
#

Got it!

mint viper
#

hi i need help getting a time template to work. the as_timestamp function is returning none

deft timber
#

Share your template please

mint viper
#
{{as_timestamp(now()) - 30*60 >= as_timestamp(strptime(states('input_datetime.work_day_alarm'),'hh:mm'))}}
#

ok i have no idea what the ❌ means

#

anyway the first half befor the comparison works

deft timber
#

what returns states('input_datetime.work_day_alarm') alone?

mint viper
#

and the strptime works (i think but the dev tools dont actualy say the data type)

mint viper
#

i think

deft timber
#

just time ? no date ?

mint viper
#

no date

#

the input helper is just for time

deft timber
#

that's why it doesn't work. as_datetimeworks on datetime only, not on time alone

#

you can't compare a date time (left part of your test) with a time alone

mint viper
#

i am not using as_datetime

deft timber
#

sorry, I meant as_timestamp

mint viper
#

ah

#

is there a way to "add" todays date to the time from the helper?

deft timber
#

yes

#

Try something like this : {{as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm'), "%d/%m/%Y %H:%M:%S"))}}

mint viper
#

that works but something it is doing is messing up the time zone so it is returning utc time

deft timber
#

You can try something like this?
{{as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm')~" +04:00", "%d/%m/%Y %H:%M:%S %z"))}} to add an offset of 4 hours

#

Or
{{as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm')~" CEST", "%d/%m/%Y %H:%M:%S %Z"))}}

mint viper
#

btw is ~ a string join?

deft timber
#

yes

#

+ can also works, but ~ force the conversion to strings, where+ doesn't, reason why + can fail in case of concatenation between strings & numbers

distant flare
#

How can I check if a certain state entity is in a certain group?

#

I tried to expand an entity in combination with my group, and look at its length, but that doesn't seem to do the trick...

mint viper
#

ok so the first one did infact work i was just converting to normal time with a converter that did not understand time zones

#

ok so my full template is this {{as_timestamp(now()) >= as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm'), "%d/%m/%Y %H:%M:%S")) - 30*60}} the intent is to have a trigger half an hour befor a time helper

#

the problem is i have 2 time helpers so they way i have it set up is that the automation goes off at 4am (because i hope that is befor my alarm) but i want to have this dynamic as well. is there a way to have a template to trigger it say 35mins befor the earlier of the 2 times?

thin vine
#

read some time back on this channel that you can do this:

{{states(trigger.to_state)}}```
but it gives some vague error" ` AttributeError: 'dict' object has no attribute 'lower'` 
not only in the template developer tool but also when working with real triggers in an automation
#

so, states() doesn't work for trigger? how else can I cleanup trigger data that might not exist ( triggered manually, triggered by trigger that doesn't support the attribute like sun not having an entity_id etc. )

wraith blade
#

Hi, for templating value (eg. to show in the gauge card rounded value) the only possibility is to make another entity? Is there no option for customizing existing one entity or better, customizing just the displaying in the card value?

thin vine
#

customizing an entity doesn't change it's value, so yeah you have to make a rounded entity. Maybe some custom cards can do this, not sure

deft timber
thin vine
#

in this channel let me look it up

deft timber
#

if you want the state of the to_state of a trigger, just use trigger.to_state.state

thin vine
#

I get that. but if for instance entity_id doesn't exist ( for instance for the sun trigger) the automation trows an error, and I want to make it errorless

deft timber
mint viper
#

sort of

deft timber
mint viper
deft timber
#

well yes you can do that. In the template it is easy to just select the earlier of 2 time values, and to just use it in your existing template

thin vine
mint viper
deft timber
mint viper
deft timber
#

oh ok, like this ? {{ "on" if my_var == "abcd" else "off" }}

mint viper
#

sort of

#

i know it from java

deft timber
mint viper
#
condition ? true : false

=

if (condition) {
  true;
} else {
  false;
}
deft timber
#

yes, what I wrote is jinja version of it

mint viper
#

ok thanks

#

ok wow this is a mess. can you do variables in templates?

deft timber
#

yes of course !

#

{% set my_var = as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.work_day_alarm'), "%d/%m/%Y %H:%M:%S")) %}

#

but it can't be used in trigger:, only in action:

thin vine
#

and you can use templates to define variable too 😉

mint viper
#

ok thanks

#

im starting to think i realy should just split this into 2 automations

#

now that i have some other stuff worked out it would not be that hard

north acorn
#

can someone help me create a sensor template, that is on when state of other sensor > 15 and off if else?

#

I tried: value_template: "{{ is_state('bsensor.kantoor_schakelaar_pc_power', '> 15') }}", I think this code is not correct

thin vine
#

correct

#

you can only check with is_state for a exact match

#

you should try value_template: "{{ states('bsensor.kantoor_schakelaar_pc_power' ) >15 }}"

#

edited, typo, should be states() not state()

north acorn
#

Thanks, I have this code, but it gives unavailable:

  - platform: template
    sensors:
      kantoor_pc:
        friendly_name: Kantoor PC
        value_template: "{{ states('sensor.kantoor_schakelaar_pc_power' ) >15 }}"
thin vine
#

if you input the template part in developer tools > templates what do you get?

#

I suspect TypeError: '>' not supported between instances of 'str' and 'int'

#

in that case make it: "{{ states('sensor.kantoor_schakelaar_pc_power' )|float >15 }}"

north acorn
#

that seems to work!

#

I do notice that the state will be 'True' or 'False'. If I want it to be 'on' or 'off' should I instead create a binary_sensor template?

ivory delta
#

It won't be 'True' or 'False'. It'll be True or False.

thin vine
#

no that's the same status

ivory delta
#

The boolean values True and False are equivalent to on/off.

#

But in general, if you're creating something binary... yes, you should use a binary sensor 🤯

thin vine
#

well since he didn't show the template domain I couldn't tell but like mono says, put it under binary_sensor: not sensor:

ivory delta
#

Yes, that's the problem with people only sharing half the information 🤣

north acorn
#

thanks!

young jacinth
#

hi, iam not 100% sure if iam right here but here is my problem
is there a way to interpolate this sensor here https://imgur.com/a/rYWrKSX with a template?
i want a higher sampling rate

deft timber
#

In a template you only have access to the current version of an entity. So I don't see how you could do that

#

Maybe you can force a refresh of your sensor more frequently? but indeed, it is not a #templates-archived question

young jacinth
#

mhh tricky..
its the sun.sun component so i guess its not possible to force the sensor anything

deft timber
#

You can by calling homeassistant.update_entity service

young jacinth
#

mhh iam going to try that

wet lodge
#

Hi folks. I've created a template sensor with the following template:

  {{ states.persistent_notification | count + states("sensor.hacs") | int + 1 }}
{% else -%}
  {{ states.persistent_notification | count + states("sensor.hacs") | int }}
{% endif -%}```
In my testing, I see that the sensor updates just fine as new persistent notifications come in, but not as they are dismissed.  What's weird is that the template seems to update just fine in both cases when I test it in the Developer Tools view.  Is there something that I'm just doing wrong?
young jacinth
#

as elevation is used here

deft timber
#

? The update_entity updates the whole sensor, and therefore the attributes as well, no ??

young jacinth
#

then there are no new values ?

#

as they dont change

deft timber
#

maybe...

young jacinth
#

super weird that the sensor updates less the more the attribute value decreases

young jacinth
#

maybe i should create a sensor by myself....
next sunrise and next sunset are available in the sun.sun component so something similar should be possible

mighty ledge
young jacinth
#

i am building my own circadian/adaptive lighting automation as I don't want to use the custom components
the sun.sun sensor updates every ~ ten minutes if elevation is lower than -20
which is way to low as I want to adapt my lights every minute

mighty ledge
#

forcing an update isn't going to cause it to recalculate. And in order to do interpolation, you need to grab historical data. You either need to use a custom_component or dive into the database itself. Your other option is to do the calculation yourself. Seems like alot of work for no net gain when you can just use the custom component.

young jacinth
#

yup, it's a bit of work. i will try to calculate the curve with the sunset and sunrise values. let's see how this will turn out.
i don't want to have the exact same behavior as circadian/adaptive lighting components. i want to have constant color temp and brightness throughout day and night and only adapt between night and dawn /dusk and night
let's see how this will turn out
if it fails then I will have learned something at least

mighty ledge
#

so use the custom compontent and dump the values to a MQTT light or a template light with input helpers and use the values when you need

#

very simple to do, and an easy configuration.

distant flare
#

Any way to see if an entity is part of a group? I tried comparing {{ expand('group.alerts', 'input_boolean.inputbijk') | length }} and {{ expand('group.alerts') | length }}, but they are the same (input_boolean.inputbijk is not part of the group)

deft timber
#

{{ 'input_boolean.inputbijk' in state_attr('group.alerts', 'entity_id') }}

distant flare
#

Thanks @deft timber !

#

That totally worked....

deft timber
#

👍🏼

ivory pawn
#

Hello, the template fails because only 'color' or 'white' is sent in the payload. Can someone add if then else syntax or solve another way please? Thanks

        data:
          color: '{{ trigger.payload_json.color | int }}'
          white_value: '{{ trigger.payload_json.white | int }}'
        entity_id: light.test
#

i learnt a trick from someone here to use max function but that seems longer and unclean

#

"It is advised that you prepare for undefined variables by using if ... is not none or the default filter, or both." ... how would this go?

charred dagger
#

Just tag on | default(0) after | int.

#

Or maybe before | int... 🤔

ivory pawn
#

thanks, looking at jinja now .. but better still how do i use the 'if ... is not none' syntax?

ivory delta
#

What? How did you find that?

#

You're a wizard, SheeZy!

ivory pawn
#

thanks . thing is i dont want to set a default value.., I want only the 'color' OR 'white' data to be applied

#

the light cant handle non valid value so I cant just send a null value. and if a send a default value it overwrites the existing value

ivory delta
#

I don't think you can do what you're asking. The properties provided get validated... so you must provide a value entry with either color: or white_value:. You can template the values but not the property names.

ivory pawn
#

hmm... thats a shame. was hoping to put in an if not none on each of the data attributes

timid osprey
#

send the previous value for the one that isn't changing

ivory delta
#

Why do you need to have a single thing that knows what to do? If this is for an automation, you should use a choose:

timid osprey
#

choose is hawt

ivory pawn
#

yeah had that in mind or to create yet another condition / choose and call the service twice. but these methods increase overhead and the esp lights are only slow to react

ivory delta
#

Increased overhead? 🤔

#

HA can handle it.

covert cloak
#

Hi! I'm not sure this is a templating problem, but maybe related (There's no scripts channel): In trying to create function-like scripts that take parameters, how do I provide and then make use of a provided parameter? The scripts docs say that you can pass the service.script_name call a message with a data attribute, but I don't know how to access that data inside the script? Or am I wrong trying this with scripts and rather have to learn about templates? (haven't looked at them much). My use case: create an Alexa notify function that takes different to-be-announced messages.

covert cloak
mint viper
#

will it work to use == in a time based template or will it never be true because it only triggers every min so i is never exactaly equal?

#

eg ```yaml
{{as_timestamp(now()) == as_timestamp(strptime(now().strftime("%d/%m/%Y ")~states('input_datetime.non_work_day_alarm'), "%d/%m/%Y %H:%M:%S")) - 30*60}}

deft timber
#

No it won't work

#

if it is a trigger of an automation, replace with >=

sly zealot
#

Hi folls. First time using discord so please redirect me if this is not the place to post ..

I have home assistant on a raspi using the hassio image (not supervised)
I want to play some wav files on different events
I used the ssh addon to access the shell and used aplay there to get sound over the raspi jack (worked)
I used shell_commands in the configuration.yaml file to expose the aplay to the automations (didnt work, HA cannot find the file)
I created a sh file that calls "aplay myfile.wav", executed from ssh, works.
Execute from the "execute a command" in home assistant > file editor (addon) y says it cannot find aplay
I even copied aplay from /usr/bin to /config and called this copy from ssh, works
when executing it from "execute a command" now it can find aplay (the one I copied to /config ), but it complains "aplay: line 16: syntax error: unexpected word (expecting ")")"

How can I get the aplay (or any other sound player) to work from home assistant ???

mint viper
deft timber
#

no. HA will trigger only when the trigger becomes true

#

"When any of the automation’s triggers becomes true (trigger fires), Home Assistant will validate the conditions, if any, and call the action."

mint viper
#

ok i have worked it out

#

befor all the false triggers in the logs there is also a log of the automation being turned off

#

but no log for turned back on and i did not turn it off

#

does editing an automation in the UI cause a reload of the full automations.yaml and their for a refresh of all automations that would mean when the automation turns on the template is true for the first time?

deft timber
#

I actually don't know that

mint viper
#

ok thanks

earnest cosmos
#

Hi, there! I am to make a template to show state of a sensor, but would like to exchange on and off states with and _av, which is the Norwegian equivalent. I only need it in this template (not aiming to go via Customize .
Here is the template I want to change.

Help is highly appreciated 🙂

{{ trigger.to_state.attributes.friendly_name }} måler {{ states.sensor.pir_ute_paviljong_luminance.state}} lux. Setter Grunnbelysning {{ states.binary_sensor.dark_inside.state }}.
#

... and it´s the states.binary_sensor.dark_inside.state that report the state i like to change

ivory delta
#

What's the template for? If the language only matters in the UI, then really you should be fixing it in the UI.

#

If you really want to do it the template way...
{{ 'pa' if states('binary_sensor.dark_inside') else 'av' }}

#

Never use states.domain.entity_name.state if you can help it. The states() function is safer.

#

@earnest cosmos ☝️

earnest cosmos
ivory delta
#

Gotcha. Well there's a solution above (minus the Norwegian characters I can't type) 🙂

earnest cosmos
distant flare
#

I can't get this to work, and I'm probably doing it wrong 🙂

#

What I would like this automation to do is:

#
  • Run after each state change
#
  • Check if the entity that triggered the change is in a certain group
#
  • Check that the entity is off
#

If this is all true, I want to do something with the entity ID. For now, I try notifying my phone, to see if I can get this right, but I don't get any notification...

deft timber
#

In trigger: you can"t use the variable trigger

#

you have to create an event trigger

oak tiger
#

But the test for greeting message depends on the person name. If it is female some words are different.

deft timber
#

and on what part do you need help?

dreamy sinew
#
{% set gender = {'male': 'hey dudes', 'female': 'hey ladies'} %}
{% set greeting = {'name1': gender['male'], 'name2': gender['female']} %}
{{ '{} This is an alert!'.format(greeting[person]) }}
oak tiger
#

Makes sense. Thank you. Arrays in Jinja... Jeez.

#

Bit overcomplicated. Can't I do if/else/endif between string? Like: if person = X then "male string" else "female string"

dreamy sinew
#

this is less complex than that

#

and if you ever add more people, this is easier to expand

oak tiger
#

There will be more string that are different.

dreamy sinew
#

then change the structure of gender

#

.format(greeting[person]['intro'], greeting[person]['middle'], greeting[person]['end'])```
oak tiger
#

{% set welcome = {'name1': 'dobrodošel', 'name2': 'dobrodošla'} %}
{% set hello = {'name1': 'pozdravljen', 'name2: 'pozdravljena'} %}

welcome[person] ~ "nazaj doma " ~ person ~ ". hello[person] ~ spet doma."

#

I now have like this.

#

No error.

#

Different string per different person.

dreamy sinew
#

if that's al you're doing, why not just hard code the full thing and just drop in the string for the person?

oak tiger
#

Eh. Not working. hello[person] is not parsing.

dreamy sinew
#

{{ '{} nazaj doma {} {} spet doma'.format(welcome[person], person, hello[person] }}

oak tiger
#

Very nice. I think this looks best and easier to follow.

#

Thank you.

thin vine
#

oh... python print formatting... nice!

dreamy sinew
#

yeah, no fstrings though 😢

wanton elm
#

Hi guys, hope someone can help with a template sensor. I have a sensor called sensor.river_ultrasonic and want to make a new template sensor that takes 0.72 and deducts whatever value is coming from sensor.river_ultrasonic
(Its calculating the depth of a small stream in the garden)

Heres what I have but it doesn't return the correct value
`#River Depth Template

  • platform: template
    sensors:
    river_depth:
    friendly_name: 'River Depth'
    entity_id: sensor.river_depth
    value_template: "{{ states('sensor.river_ultrasonic') | int - 0.72 }}"
    unit_of_measurement: meters`
dreamy sinew
#

what gets returned?

#

also what you have written doesn't match what you have stated

brisk temple
#

entity_id in template sensors are no longer supported

wanton elm
wanton elm
dreamy sinew
#

what is the value of that sensor and what is the math you actually want to apply?

wanton elm
thin vine
#

int 0.43 = 0

#

you want float instead of int

brisk temple
#

does it actually say meters in the state? If so you'll have to strip it out, or if the number is in attributes you can grab it from there

wanton elm
brisk temple
#

what do the attributes look like

dreamy sinew
#

go to devtools > templates and do
{{ states('sensor.reiver_ultrasonic') }}

#

what is the output?

wanton elm
dreamy sinew
#

seem slike you just have your math backwards then

wanton elm
wanton elm
dreamy sinew
#

{{ 0.72 - states('sensor.reiver_ultrasonic')|float }}

wanton elm
#

Got it along with making it a float @thin vine - thanks to you all, really appreciate it @brisk temple @dreamy sinew

wanton elm
dreamy sinew
#

{{ ( 0.7 ... |float)|round(2) }} order of operations

#

| happens first

timid osprey
#

I was going to ask that exact question

#

I always wrap things like that in () but won't now

wanton elm
#

"{{0.72 - states('sensor.river_ultrasonic'|float)|round(2) }}"

dreamy sinew
#

because you didn't do what i demonstrated

wanton elm
# dreamy sinew because you didn't do what i demonstrated

You are right, my apologies. Got it thank you. Had to run a 50m ethernet cable down the garden in the UK rain to get this sensor on 😩 - one of those days. Thanks again
"{{ (0.72 - states('sensor.river_ultrasonic')|float)|round(2) }}"

teal cove
#

how do I render a list from an if-template?

#

(according to google it doesn't work, but that was before templates strictly rendered strings)

dreamy sinew
#

need more context

deft timber
#

Theoretically:

{% if ... %}
  {{ [1,2,3] }}
{% endif %}

works, it depends on what you need...

teal cove
#

what I tried```
{% if is_state('device_tracker.dd', 'home') -%}
[["text1", "/btn1"], ["text2", "/btn2"]]
{%- else -%}
["text2", "/btn2"]
{%- endif %}

#

oh with braces?

dreamy sinew
#

list of lists? seems odd

teal cove
#

i guess

#

telegram bot

dreamy sinew
#

weird

teal cove
#

ye

dreamy sinew
#

yeah, need to do a "print" statement

teal cove
#

thats how it eats its "keyboard"

deft timber
#
{% if is_state('device_tracker.dd', 'home') -%}
  {{[["text1", "/btn1"], ["text2", "/btn2"]]}}
{%- else -%}
  {{["text2", "/btn2"]}}
{%- endif %}```
teal cove
#

print statement?

#

will try @deft timber

dreamy sinew
#

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

teal cove
#

ahhh @dreamy sinew

#

ehh too many values to unpack (expected 2) 😩

#

Ok. I don't know why or how it works, but after trying forever, this ended up working for some reason. a bit ugly

{% if is_state('device_tracker.dd', 'home') %}
  Text1:/btn1,Text2:/btn2
{% else %}
  Text2:/btn2
{% endif  %}
#

no list somehow works

#

Sorry for disturbing and thank you for your help anyway 🙂 🤝

gusty nimbus
#

hi i want to know how much energy i have left
Solar - used power =

binary_sensor:
  - platform: template
    sensors:
      netpower:
        value_template: '{{(states.sensor.alex_energy_today_kwh.state | float ) - (states.sensor.electriciteit_verbruik_per_dag.state | float)}}'
        unit_of_measurement: 'kWh'
        friendly_name: Net Power

i tryed but i have error
[unit_of_measurement] is an invalid option for [binary_sensor.template]
i'm i doing this correctly i just want to know how many kWh i have left on a day for as far i know the numbers

#

or do i just have to remove the united_of line?

dreamy sinew
#

well, you're trying to do math in a true/false

gusty nimbus
#

hm

#

where to do the math in numbers? 🙂

dreamy sinew
#

you're using the wrong integration

gusty nimbus
#

hm

dreamy sinew
#

binary_sensors are for true/false

#

on/off

gusty nimbus
#

oh ok

#

i guess it should be sensor:

#

have no errors in config now tx

#

stupid of me 🙂

#

maybe some small thing more

#

it shows now -14,745999999999999 kWh
and i have set this do i do it wrong for less after the , ?

        value_template: '{{(states.sensor.alex_energy_today_kwh.state | float ) - (states.sensor.electriciteit_verbruik_per_dag.state | float) |round(5)}}'
dreamy sinew
#

as is, you're only rounding the 2nd number

#

order of operations says that the | are processed 2nd

gusty nimbus
#

hm i just want to have the total rounded

dreamy sinew
#

need to wrap the whole thing you're rounding in ( )

#

PPEMDAS
Paren, Pipe, Exponents...

gusty nimbus
#

hm

#

im not very great in coding 😉

dreamy sinew
#

as is, this is the only bit being rounded:
(states.sensor.electriciteit_verbruik_per_dag.state | float) |round(5)

gusty nimbus
#

i think for the most correct use i only have to round the outcome of the -

#

the total i mean

dreamy sinew
#

so you need to group everything together before the round filter is applied

gusty nimbus
#

hm

#

maybe place an extra ( inhere

'{{((states.

and end with a ) more

|round(5))
#

thats not working to pf

dreamy sinew
#
value_template: "{{ ((states('sensor.alex_energy_today_kwh') | float ) - (states('sensor.electriciteit_verbruik_per_dag') | float))|round(5) }}"
gusty nimbus
#

hm nice

#

i think i was almost there

#

many thanks !

#

i really needed this thing

#

belgium is fucked up with their digital power meter

#

normally the disk turns back now suddenly they quited that

#

works

sonic nimbus
#
{{not is_state(states.media_player.avr_zone1.state, 'off')}}```
#

first is off, and why Im getting true for second one

dreamy sinew
#

because you're reversing the result with the not

sonic nimbus
#

but should be then true without not?

dreamy sinew
#

oh wait

#

oh, because you're using is_state() incorrectly

#

check the docs for the proper usage

earnest cosmos
#

Any way to simplify this?

        data_template:
          entity_id: >-
            {%- if states.binary_sensor.workday_sensor.state == 'on' and states.input_boolean.vacation.state == 'off' and states.input_boolean.company.state == 'off' and states.calendar.holidays_in_norway.state == 'off' and states.calendar.work.state == 'off' -%}
              script.morning_lights_weekday
            {%- else -%}
              script.morning_lights_weekend
            {%- endif -%}
dreamy sinew
#

Using is_state() could help some but that's about it

earnest cosmos
dreamy sinew
#

Or you could add a template sensor to do those checks and use that in your automation instead

earnest cosmos
#

You mean defining each of the if/else statements as separate template values?

dreamy sinew
#

No, create a template binary_sensor that evals that template and then you just key off of the one value for your automation

earnest cosmos
#

got it. Thanks

#

.. and could this

    condition:
      - condition: template
        value_template: "{{ states.binary_sensor.garasjeport.state != 'off' }}" 

Be simplyfied to this?

    condition:
      - condition: template
        value_template: "{{ is_state(binary_sensor.garasjeport]' }}" 
dreamy sinew
#

Gotta provide a state

earnest cosmos
#

Not this either? "{{ states.binary_sensor.garasjeport.state }}"

dreamy sinew
#

You should review the template docs

earnest cosmos
#

I was looking for a way not to include the !=, and have been playing by the book/doc. now I just was imagening it wold work in a more simple form.

#

I stick to the original then. It works... 😉

sage aurora
#

Trying to debug a template to pull from ecobee using Developer Tools. Going well. So I've got {{ states.climate.home }} and the output is this :

<template TemplateState(<state climate.home=heat; hvac_modes=['heat_cool', 'heat', 'cool', 'off'], min_temp=7.0, max_temp=35.0, fan_modes=['auto', 'on'], preset_modes=['Home', 'Away', 'Sleep', 'Telework'], current_temperature=22.9, temperature=23.0, target_temp_high=None, target_temp_low=None, current_humidity=28, fan_mode=on, hvac_action=fan, preset_mode=Home, aux_heat=off, fan=on, climate_mode=Home, equipment_running=fan, fan_min_on_time=40, friendly_name=Home, supported_features=91 @ 2021-01-21T11:59:40.647605-05:00>)>
Fan <template TemplateState(<state climate.home=heat; hvac_modes=['heat_cool', 'heat', 'cool', 'off'], min_temp=7.0, max_temp=35.0, fan_modes=['auto', 'on'], preset_modes=['Home', 'Away', 'Sleep', 'Telework'], current_temperature=22.9, temperature=23.0, target_temp_high=None, target_temp_low=None, current_humidity=28, fan_mode=on, hvac_action=fan, preset_mode=Home, aux_heat=off, fan=on, climate_mode=Home, equipment_running=fan, fan_min_on_time=40, friendly_name=Home, supported_features=91 @ 2021-01-21T11:59:40.647605-05:00>)>
#

But if I eval {{ states.climate.home.equipment_running }}, nothing is output.

#

Okay I got it - value_template: '{{ "fan" in state_attr("climate.home", "equipment_running") }}'

edgy fulcrum
#

Similar to @sage aurora I'm just looking at getting the climate info into a template sensor. I'd sorted how to get an actual named attribute out. What I can't get is the current "master" setting? In the above example I'm trying to get the "heat" answer, where it says the state is: state climate.home=heat;

#

(although I live in AU so mine will say "cool" right about now 😉 )

#

ok that turned out to be easy.{{states('climate.daikin_ac')}}

thin vine
eager crystal
#

Morning all! I'm trying to get "custom" attributes using json templates from an MQTT message, i.e. format them and give them a custom name this is what i have tried any ideas? https://paste.ubuntu.com/p/nvBzGvS73z/

deft timber
#

And what's the result of that? In value_template you have is_state(entity_id,\"on\") but entity_idis not defined.

eager crystal
#

the trigger and sensor it self work perfect, just the attributes, entity_id in this case is self referential i believe: https://imgur.com/1UZgdvN

deft timber
#

I guess it should be 'sensor.hall_motion_camera'

deft timber
#

ok, I'm surprise it works, but good for you 🙂

#

indeed, i learned something 🙂

eager crystal
#

Yep me too when i found it 🙂 just trying to sort out the attributes, will also be useful in rest sensors and such

deft timber
#

did you test the template in the dev tool?

#

it says 'timestamp_local' is undefined

#

I suggest using strptime to parse the date string in a date object

eager crystal
#

i shall remove the timestamp formatting for now, and do a restart, mostly concerned about getting the attributes layed out 🙂

deft timber
#

{{ {'Last Motion': '~strptime(value_json.currentTimestamp, "%Y-%m-%dT%H:%M:%S%z")~', 'Motion Area': value_json.details.name, 'Timestamp': value_json.currentTimestamp } | tojson }}

eager crystal
deft timber
#

fyi you do not need to restart for that. If you are already in advanced mode, you can just relead MQTT entities

eager crystal
#

ooo yes there is a button for that, used to having to reload for rest sensors and such!

#

got "TypeError: Object of type datetime is not JSON serializable" on that one

deft timber
#

yes you have to create a string out of the date you created with strptime. So either you keep the initial date string or you use strftime to format the datetime with whatever format you want

#

{{ {'Last Motion': strptime(value_json.currentTimestamp, "%Y-%m-%dT%H:%M:%S%z").strftime("%Y-%m-%d %H:%M:%S"), 'Motion Area': value_json.details.name, 'Timestamp': value_json.currentTimestamp } | tojson }}

ivory delta
#

It's so... pretty

young jacinth
#

or how can i get this to work?

thin vine
#

I believe because you use target instead of entity_id. Target I think is only for blueprint targets if I remember correctly

young jacinth
#

mhh iam using targets in combination with the notify group platform

thin vine
#

I see. you seem to be wanting to make list, but currently you are making a string, maybe one of the template guru's here can give a good way to do it in this case.. I'm struggling with that part still

young jacinth
#

i hope so. iam struggling there too. jinja templates are still hard. would really like to see some advanced tutorial in combination with HA

ivory delta
#

There are guides in the topic here, and Jinja itself is well documented on its own site.

thin vine
young jacinth
thin vine
#
            {%- if is_state('binary_sensor.wz_besetzt','on') and is_state('binary_sensor.ku_besetzt','off') %},{%- endif -%}
            {%- if is_state('binary_sensor.ku_besetzt','off') -%} media_player.kuche_alexa{%- endif -%} ]``` I think....
wheat cargo
#

hi, I have a sensor (sensor.foo) whose value is a number that is always increasing (once per day or so). I'd like to create another sensor (diff_foo) which is updated each time the first one is updated and contains the difference with respect to the previous value. I saw I can use an automation for that, but I actually want to do the same for like 17 sensors so I'd like to avoid creating 17 automations if possible. What's the recommended way to do that?

ivory delta
wheat cargo
young jacinth
ivory delta
#

If that's for use in an automation/script, don't even try to handle all the possible combinations in a single template.

#

Use the choose: block.

deft timber
#

Easier to manage several binear_sensor/media_player

#

Or

{% set my_list = [] %}
{% set my_list = my_list + (["media_player.wohnzimmer_alexa"] if is_state('binary_sensor.wz_besetzt','on') else []) -%}
{% set my_list = my_list + (["media_player.kuche_alexa"] if is_state('binary_sensor.ku_besetzt','off') else []) -%}
{{my_list}}
thin vine
#

yeah much better, hence my hesitation to give a solution

#

also, what mono says, choose: in automation / scripts is a life saver much better than trying to do everything in templates or a gazillion automations with big conditions

brisk sonnet
#

Can anyone see where i am going wrong here ?

#
  red
{% elseif states(config.entity)|int > 29 and states(config.entity)|int < 34%}
  green                 
{% else %}
  blue
{% endif %}```
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/.

ivory delta
#

And if you don't say what it should do, it's going to be hard to help fix it.

deft timber
#

and you miss the % for the > 29

thin vine
#

it's the % of %}

deft timber
#

oh !!

#

:)D

#

😄

#

Sorry :-p

thin vine
#

I was also confused at first

deft timber
#

What is the value of config.entity ?

#

And replace elseifwith elif

thin vine
#

{% elseif should be {% elif

brisk sonnet
thin vine
#

hehe you beat me to it slashback

deft timber
#

ok, so just try to apply the fix we proposed

brisk sonnet
#

This is a working one FYI ```badges:

  • entity: sensor.zeversolar_generated_power
    name: Solar Power
    style: |
    :host {
    --label-badge-red:
    {% if states(config.entity)|int >0%}
    green
    {% else %}
    red
    {% endif %}
    ;
    }```
#

changes badge colour from green to red

#

Thanks the elseif --- elif seemed to be the culprit.

young jacinth
thin vine
#

hmmm not sure if integrations can use templates in this way and if it will evaluate more then just at startup

young jacinth
#

if it fails then i will try it with a script and use the fields function for the message. but i will see if i get home 😄

ivory delta
#

What on earth are you trying to do? Why do you have this weird template in the definition of an integration?

#

Even if that worked, it wouldn't be updated unless you restart HA...

#

🤔

young jacinth
#

i want to send messages from alexa only to rooms that are occupied

young jacinth
ivory delta
#

HA loads config. It doesn't monitor config.

#

All your YAML files are gathered together and loaded and that's it.

#

So... use a script/automation and use the choose: syntax.

sly zealot
#

Hi folks!
I'm coding an script and I'd like to ask ho does one check if a variable has been set at all ?

#

tried with

#
  • condition: template
    value_template: '{{if messageTitle}}'
#

and

#
  • condition: template
    value_template: '{{messageTitle == None}}'
#

nothing works, it always go through the "default" part of the condition

#

when calling from the dev tools > services, with no data defined

#

when setting the messageTitle it does apper as part of the message body (as expected) so the problem is not in the variables management

#

is just the syntax for cheking if set

#

also tried messagetitle == ''

#

does not work

#

also tied just

  • condition: template
    value_template: '{{messageTitle}}'
#

nothing . .

sly zealot
#

oh lord... I cannot find it 🙂

brisk temple
#

{{ messageTitle is defined == true }}

sly zealot
#

oh lord, now my HASS is rebooting and I cannot test it XDDD

#

I'm counting seconds 😄

brisk temple
#

{{ messageTitle != '' }} should work as well

sly zealot
#

can it be shorten to just {{ messageTitle is defined }}

#

!= '' did not work, I tested it to death

sly zealot
#

value_template: '{{messageTitle == None}}'

#

when writing this, do you use 'or " around the statement ?

brisk temple
#

use template editor

sly zealot
#

hum.. that would has been smart : )

brisk temple
#

you have to use the opposite of what your wrapping the value_template in

sly zealot
#

what would be the syntax for and AND in the value template in a Choose statement ?

#

{{ messageTitle is defined == true && messageBody is defined == true }}

#

or

#

{{ messageTitle is defined == true AND messageBody is defined == true }}

#

none of the mseams to work with jinja thingy

brisk temple
#

check the link in the pin messages

deft timber
#

it is neither 🙂

#

it is and

brisk temple
#

to help with formatting

deft timber
#

{{ messageTitle is defined and messageBody is defined }}

sly zealot
#

nooooooice

fossil hearth
#

hey guys ! 🙂 can someone explain why inst this working well ?

{% if   value_json.price is not number  %} Disconnected {% else %} {{value_json.price}} {% endif %}
{{value_json.price}}

result:

Disconnected 
1.2245
edgy fulcrum
#

{% set value_json = {"symbol":"ERUSUD","price":1.2245} %}

fossil hearth
#

but value_json.price extracts without the quotes ...

edgy fulcrum
#

no, it outputs a string

fossil hearth
#

so how can i fix this ?

#

minus quotes ? 😛

edgy fulcrum
#

there's nothing to fix? 🤷‍♂️ either you want it as a string or as a number. If you want to check it's a number, then make it a number. If you want it as a string, stop checking if it's a number.

dreamy sinew
#
{%- set value_json =  {"symbol":"ERUSUD","price":"1.2245"} -%}
{{ 'Disconnected' if not value_json.price|float else value_json.price }}
fossil hearth
#

but somtimes my rest api is unable to fetch the price , and is my calculation are messing up, i want it to show price when only the price is a number...

dreamy sinew
#

this will work if the price key is always there

#

might fail if it isn't

sage aurora
#

Can someone with an Ecobee let me know if they're able to access heating call info? I can pull in the info but I can never see any info.

#

I can grab my fan call, humidifier call... but the raw info never changes.

urban depot
#

Hey, I try to make an automation which create a snapshot, and want it to name the file the date. I using this parameter on the call name: "{{now().strftime('%Y%m%d')}}" but the name on the backup files is just {{now().strftime('%Y%m%d')}}

#

Can anybody help me understand what i'm doing wrong?

#

When I test the template in the developer -> template session it is showing the date: 20210122

ivory delta
#

From what you've said, the integration you're calling doesn't understand templates.

urban depot
#

that could be the problem the integration is hassio.snapshot_full

sage aurora
#

https://i.imgur.com/GHRfmA2.png hvac_action is never anything other than fan. equipment_running will sometimes be fan, humidifier but heating doesn't show up in it.

solemn patio
#

Hey team, quick question: has anyone ever tried to access 'supported_features' to get a list of all the lights with specific features? I can't seem to access that through selectattr.

#
  | selectattr("attributes.supported_features", 'defined')
  | selectattr("attributes.supported_features", 'eq', '43')  
  | join(', ', attribute="attributes.supported_features") }} ```
doesn't seem to work - it shows nothing.
timid osprey
#

I copied and pasted your exact template and it worked

#

well I don't think it is accurate, but I got more than nothing

solemn patio
#

To check it out, try removing the second line:

  | selectattr("attributes.supported_features", 'defined')
  | join(', ', attribute="attributes.supported_features") }} ```
#

See what you get back as a list from that.

timid osprey
#

I just realized what I did before, lol

#

@solemn patio I think you just need to use an int instead of a string

solemn patio
#

You're a legend, @timid osprey! I've been staring at that for hours!

#

Thank you so much! 😄

timid osprey
#

no problem

brisk nebula
#

Hi everyone, my mqtt sensor return values in double quotation marks i.e. '"value"'. Is there a way to get rid of the excess marks in some smart way?

lofty nymph
#

Hello! I want to lookup the device/friendly name of a device by a child (entity). Are there any lookup methods I could use?

#

The background: I've a automation which monitors the binary state of an entity (connection status). The automation shall notify about the device name which is offline. The connection status entities doesn't have a proper friendly name to know which device is offline.

#

I tried to avoid redundancy here.

young jacinth
#

hi!
i want to extract everything after the last "_" out of an entity id. can someone point me in the right direction here?

for example input_boolean.living_room_test
i want the output to be "test"

brisk nebula
#

having the entity name, you extract with .split()[]

lofty nymph
#

{{ 'input_boolean.living_room_test'.split('_')[-1] }} returns test

brisk nebula
#

@lofty nymph maybe you could help me out with getting rid of excess quotation marks in '"value"'?

ivory delta
#

You can use the same approach, assuming there are no quotes inside the string 😉

#

{{ '"some quoted string"'.split('"')[1] }}
should return the second item in the array that results when you split by double quotes.

#

You want the second because the split is going to return ['', 'some quoted string', '']

brisk nebula
#

Many thanks mono. That does the job.

young jacinth
#

for me too!

#

thanks

thin vine
ivory delta
#

It's not a feature of all languages. I've only seen it with Python so far.

#

Way easier than having to calculate the length of the array first and get the n-1 item.

thin vine
#

indeed. my python skills are weak. I do some basic scripting with it now and then, I can adapt other peoples work to suit my own, but not enough to write from scratch

ivory pawn
#

hello, is there a jinja or otherwise syntax that can be used for data of a service which tell the service that the data to be applied should remain unchanged? For example, where hue and saturation are needed for hs_color but only one is supplied? Thanks

          hs_color:
          - '{{ trigger.payload_json.hue }}'
          -  leave value unchanged
        entity_id: light.test```
lofty nymph
#

@ivory pawn May be the current value is stored somewhere (at the attributes of the entity?) and you can use it again?

ivory pawn
#

@lofty nymph yes thanks, that is possible and the work around but i was hoping for a 'special' value or function that might be put in place of 'leave value unchanged' to make easier coding and readability

lofty nymph
#

This line defines a validator which is strict: the list must have two elements. both elements must be float in range of ...

#

There are no declarations for "is optional" or something like this.

thin vine
#

my experience with lights is that not providing the variable ( like hs_color) keeps that one unchanged, unless you change for instance kelvin/temperature which will also change the color. BUt if you just adjust brightness, color will remain the same

lofty nymph
#

Take a look at the example. The user wants to pass the hs_color but just the hue component. He wants to skip the saturation (second component) of hs_color.

thin vine
#

ah, hmmm , yeah I misread the question in that case 😉

#

besides what you already sugested, reading the value from the entity, I don't know of any other way

ivory pawn
thin vine
#

@ivory pawn {{state_attr('light.staande_lamp', 'hs_color')[1]}}

candid scaffold
#

How do I get the last_changed-property for an dynamic entity_id?
{{ state_attr(entity_id, 'friendly_name') }} works well, but the last_changed isn't a state variable. {{ states(entity_id).last_changed }} does not work and making a string like {% set entity = 'states.' + entity_id + '.last_changed %} does just return "None" when I try to output it

lofty nymph
#

last_changed is an attribute, too. {{ state_attr(entity_id, 'last_changed') }} doesn't work?

#

Oh.

#

You are right.

#

It's part of the state_object.

#

And no attribute.

candid scaffold
#

Yes

lofty nymph
#

You could access the state object directly but I think this isn't as safe as using methods:

#

{{ states.light.office.last_changed }}

#

Okay. You are missing the dynamic part. 😛

#

Now I understand your entire question

candid scaffold
#

Problem is that I only have the entity_id as a dynamic string, so that will just output the string

lofty nymph
#

{{ states['light']['office']['last_changed'] }}

candid scaffold
#

{% set entity = 'states.binary_sensor.' + entity_id + '.last_changed' %}
{{ state_attr(entity_id, 'friendly_name') | replace(' contact', '') }}: {{ entity }}
Just outputs some like:
My Sensor Name: states.binary_sensor.my_sensor_name.last_changed

candid scaffold
lofty nymph
#

It's not elegant but you could replace in this example ({{ states['light']['office']['last_changed'] }} ) the string "light" and "office" by pieces of your entity.

candid scaffold
#

{{ states[entity_id]['last_changed'] }} seems to work 🙂

lofty nymph
#

Good job!

candid scaffold
#

Thank you! 🍺

lofty nymph
#

But be warned: It's possible your Home Assistant logs some error on start-up now.

#

Because you are accessing some structure before it's available.

#

If I remember correctly the state_attr() and states() method is some safeguard.

candid scaffold
#

I'll use it in an automation (in a value_template) so I don't think that will be the case here, right?

#

As the state have already been triggered

lofty nymph
#

If your automation doesn't trigger before your entity is available you should be safe. 😉

candid scaffold
#

👍

candid scaffold
#

Which version of Jinja does HA use?

sharp night
#

Okay, I'm almost there with this TTS automation / template I'm trying to build out... this is what I have so far in the template tools:

{% set my_list = [] %}
{% for player in my_players %}
    {% if is_state("switch."+ player + "_do_not_disturb_switch", 'on') %}
      {{ player }}
    {% endif %}
{% endfor %}

which will correctly output show_office as it is set to DnD and the others are not.

#

I was trying to figure out how to create "my_list" based off the states of those devices but I can't seem to get the syntax worked out how to build a device with a string for that...

#

trying something like this just as a test: ```{% set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] %}
{% set my_list = [] %}
{% for player in my_players %}
{% if is_state("switch."+ player + "_do_not_disturb_switch", 'on') %}
{{ player }}
{% set my_list = my_list + (["media_player.blahblahblah"]) %}
{% endif %}
{% endfor %}

{{my_list}}```
and "media_player.blahblahblah" never appears in the result

#

i think there's a scoping issue here, and thats probably my problem...

#

do i really need to build out an if statement for each device?

#

yup, definitely a scoping issue, nothing makes it out of that for loop

#

adding {{my_list}} inside the for loop gets a result

timber locust
#

I think you need to use namespace.

#

What if you use:

{% set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] %}
{% set my_list = namespace() %}
{% set my_list.my_list = [] %}
{% for player in my_players %}
    {% if is_state("switch."+ player + "_do_not_disturb_switch", 'on') %}
      {{ player }}
      {% set my_list.my_list = my_list.my_list + (["media_player.blahblahblah"]) %}
    {% endif %}
{% endfor %}

{{my_list.my_list}}

I think you can do that better, but I don't know enough about jinja to know how.

sharp night
#

there it is

#

that makes sense, i was barking up that tree but was missing the second assignment on line 3

#

seems so obvious now, lol

timber locust
#

So it works now? 🙂

sharp night
#

yup works great

timber locust
#

Nice. Happy to help! 🙂

sharp night
#

so, ultimately what I'm trying to do is pop this into a list for notify.alexa_media

#
{% set my_list = namespace() %}
{% set my_list.my_list = [] %}
{% for player in my_players %}
    {% if is_state("switch."+ player + "_do_not_disturb_switch", 'off') %}
      {% set my_list.my_list = my_list.my_list + (["media_player." + player]) %}
    {% endif %}
{% endfor %}

{{my_list.my_list}}```
#

Okay, this might be back into the automations topic, but trying to figure out how to use this now for a list of devices. I thought something like this would work: ```service: notify.alexa_media
data:
message: '{{ message }}'
data:
type: tts
method: speak
target: >
{% set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] %}
{% for player in my_players %}
{% if is_state("switch."+ player + "_do_not_disturb_switch", 'off') %}
- media_player.{{player}}
{% endif %}
{% endfor %}

#

but it is not

#

not seeing an error anywhere that i can find

timber locust
#

What happens when you evaluate the template?

sharp night
#

oh

#

oka

#

so, it's a string

#

so, that might be my problem

#

also, it's all spaced out

#

is what it looks like

timber locust
#

I think then you need to use dashes inside the brackets {%- blabla -%}

sharp night
#

ultimately I'm trying to do something like this:

data_template:
  message: '{{ message }}'
  data:
    type: tts
    method: speak
  target: >-
    {% set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] %}
    {% for player in my_players %}
    {% if is_state("switch."+ player + "_do_not_disturb_switch", 'off') %}
    media_player.{{player}}
    {% endif %}
    {% endfor %}```
timber locust
#
    {%- set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] -%}
    {%- for player in my_players -%}
    {%- if is_state("switch."+ player + "_do_not_disturb_switch", 'off') -%}
    media_player.{{player}}
    {%- endif -%}
    {%- endfor -%}
#

Try that

#

Ah hold on. You want to send a tts to a lot of speakers?

sharp night
#

yeahhhhh

#

ok

#

so, basically I'm trying to filter out the speakers that are set to DnD

#

but, the states of the DnD for speakers aren't attached to them...

#

so, bascially i'd create a group called "tts speakers" or whatever and populate it with a template sensor?

timber locust
#

Ooh. That's a good point. You want the group to be empty... Hmm...

sharp night
#

yeah, which can work

#

right?

#

just monitor for the dnd and if it pops take it out

timber locust
#

But you cannot create an empty group.

sharp night
#

actually

#

it doesnt need to be empty

#

i just need to be able to remove objects

#

when they're dnd

#

so, that might work even better

timber locust
#

Then again, if I look at my file, you should be able to just use the original template, but then do:
{%- set my_players = ['dot_living', 'show_kitchen', 'dot_master', 'dot_masterbath', 'dot_garage', 'show_office'] -%}
{%- for player in my_players -%}
{%- if is_state("switch."+ player + "_do_not_disturb_switch", 'off') -%}
- media_player.{{player}}
{%- endif -%}
{%- endfor -%}

#

But you would need to remove some %'s to allow for creation of newlines

sharp night
#

ah ok, so with a blank group

timber locust
#

I mean, my template group creation does the same thing as what you want, right?

sharp night
#

i think it does

#

this helps a lot

#

and is easier to maintain i think

timber locust
#

You want to programmatically make a list that reads

  • media_player.mancave
  • media_player.bdsm_basement
  • media_player.killroom
#

Right?

sharp night
#

yeah

#

definitely bdsm_basement

timber locust
#

And parse that to notify alexa.

sharp night
#

yup

timber locust
#

I do the same thing, but then parse that to group.create.

#

You should just modify my template to suit your needs and boom! Voices in your basement.

sharp night
#

to match the ones in my head, fantastic!

timber locust
#

Yeah

#

Be sure to check an if statement: if {{ not message == safeword }} do nothing

#

You don't want Alexa to call out the safeword by surprise in your basement.

sharp night
#

correct

timber locust
#

Oh wait. I just realised that group.set accepts a list of comma separated entities as in input. I don't know if it will still work for notify.alexa.

sharp night
#

wait

#

im not sure i understand your sensor

#

lol

timber locust
#

Basically I have a sensor that detects all unavailable entities. However, I have some devices that have multiple entities. For example if my smart plug is offline, I really don't care about the energy today, current voltage, current power, etc. all being unavailable. I therefore programmatically create a group that contains all those secondary entities if the main device is offline. I think the important part is the automation from line 100 onwards. I basically create a list of entities there and parse that to group.set. That's all.

sharp night
#

ohhh

#

i didnt look down far enough

#

lol

#

im like, i dont see how this sensor is doing anything to a group

#

it helps to scroll...so they tell me

timber locust
#

Have you got it figured out now? @sharp night

sharp night
#

@timber locust nope

#

lol

#

this is what I have for my automation, it's so close

silent barnBOT
sharp night
#

good bot

#

that seems to evaluate out to what i want in the template area

#
2021-01-23 14:50:24 ERROR (MainThread) [homeassistant.components.automation.update_dnd_stuff] While executing automation automation.update_dnd_stuff```
#

oh wait

#

word wrapping!

#

no

#

trailing comma

deft timber
#

I recommand the following

        {%- set entities = namespace(entities=[]) -%}
        {%- for entity_id in states.group.base_alexa_announce.attributes.entity_id -%}
          {%- set player = entity_id.split('.') -%}
          {%- if is_state("switch."+ player[1] + "_do_not_disturb_switch", 'off') -%}
            {%- set entities.entities = entities.entities + [entity_id] -%}
          {%- endif -%}
        {%- endfor -%} 
        {{ entities.entities }}
#

it avoids to play with the comma

#

and it returns a list, which seems to be accepted by the group.set service

sharp night
#

I been switching back and forth between so many ideas. lol

#

that worked perfect

#

thanks!

deft timber
#

Great

sharp night
#

that's working perfect, and i setup my trigger run on the state change on all of those do_not_disturb switches, works like a champ

fast mason
#

I've got a dehumidifier that has tank_show attribute as a True/False. Even though it changes to True the bellow template always stays as Empty

{% if is_state('humidifier.midea_dehumidifier_18691697727728', 'tank_show'), 'False' %}
  Empty
{% else %}
  Full
{% endif %}
#

Am I being stupid?

fossil totem
#

I wouldn't say stupid but you are doing it wrong 😄

#

check out state_attr

#

is_state is going to check the state of humidifier.midea_dehumidifier_18691697727728, and return true if the state is tank_show

fast mason
#

oooooh

#

🤦‍♂️

fossil totem
#

allright i have a bit of weird challenge here, not sure if it's blueprints or templates but i'll start here

#

working with a blueprint, using a device selector, and that returns a device id in the format 3fde16be76f2758625733f72e25d569f

#

what i'm trying to do is to turn that back into a friendly_name or similar, using a template

#

and... well that's as far as i got.

silk smelt
#

hi all! can someone tell me why this doesn't work?

entity: climate.panelovn_kontor
style: |
  :host {
    --paper-item-icon-color:
     {% set mode = states(climate.panelovn_kontor) %}
     {% if mode == "heat" %} red
     {% else %} blue
     {% endif %}
     ;
   } ```
ivory delta
#

3 backticks at the end too 🙂

silk smelt
#

hehe thanks! i do not dare to repost, so i edit 🙂

#

yeah!!

ivory delta
#

What's the problem/error?

silk smelt
#

the icon doesn't change color if the state is "heat"

#

I'd like a red colored icon if the climate unit is in state "heat"

fossil totem
#

what does it do in the template editor?

silk smelt
#

i get UndefinedError: 'climate' is undefined

#

but climate.panelovn_kontor is an entity

fossil totem
#

in your template editor, try {{ states("climate.panelovn_kontor") }}

#

note the quotes. i suspect that's your problem.

silk smelt
#

like this?

     {% if mode == "heat" %} red
     {% else %} blue
     {% endif %}
fossil totem
#

does it work?

silk smelt
#

puts out TemplateSyntaxError: expected token ':', got '}'

#

hmm

#

thank you for helping me btw 🙂

fossil totem
#

oh get rid of the nested template too

#

so instead of {% set mode = {{ states("climate.panelovn_kontor") }} %}

#

do {% set mode = states("climate.panelovn_kontor") %}

silk smelt
#

that worked!! thank you so so much!

#

if i might bother you with another question. how do I check one of the attributes?

fossil totem
#

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

#

if you're using it to test, try is_state_attr('device_tracker.paulus', 'battery', 40)

#

make sense? first one just returns that attribute, but if you're using it in an if you can save yourself a little typing and use is_state_attr with the test condition. keep that page above bookmarked, you're going to be referring to it a lot 😄

silk smelt
#

you are a rockstar! your first example worked!

#

thatnk you so much

fossil totem
#

you're welcome, glad you got it sorted!

silent barnBOT
narrow topaz
#

Hi, is there a way to make {% set lights = ['light.dining_bulb', 'light.hallway', ...] %} dynamic. So that all light entities are included?

dreamy sinew
#

states.light |map(attribute='entity_id')|list

#

Depending on what you want to do

narrow topaz
#

Thanks that will work! Just want to change lights that already on

#
{{ expand(lights)|selectattr('state','eq','on')|map(attribute='entity_id')|join(',') }}```
#

seems to work

dreamy sinew
#

Overkill

narrow topaz
#

I'm an amateur lol. Just trying to piece together code from different sources 😆

dreamy sinew
#

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

narrow topaz
#

right.. that looks better! Thanks

low coral
#

Hey All
I keep getting the following two logs, which repeat every minute on the dot. I've loaded a sample here: https://paste.ubuntu.com/p/pnzn8GyxhZ/
I've looked through all of my helpers and can't find AllStates or any helpers that use a template for that matter, so I'm not sure if this is the correct location to post.
I've also running a debug logger (below the logs) and it doesn't give me any more information.
Appreciate any help with this
2021-01-24 15:35:00 ERROR (MainThread) [homeassistant.helpers.condition] Error during template condition: UndefinedError: homeassistant.helpers.template.AllStates object has no element False 2021-01-24 15:35:00 ERROR (MainThread) [homeassistant.helpers.condition] Error during template condition: UndefinedError: homeassistant.helpers.template.AllStates object has no element True
logger: default: info logs: homeassistant.components.automation: debug homeassistant.components.script: debug homeassistant.helpers.condition: debug homeassistant.helpers.template: debug homeassistant.helpers.template.AllStates: debug

floral river
#

Does anyone know if it's possible to check if a service exists inside a template or if it is possi le to detect it in any other way either in a template or in an autotomation's condition?

low coral
bright carbon
#

Hi everybody! I am trying to declutter and icon template via the decluttering card addon and I have an issue with the icon:

#

If I put this piece of code in my ui-lovelace.yaml it works

#

If I do the same via the decluterring card the icon is blank 😦

#

The issue is for sure located in this line but don't know how to fix it:

#

${ states['cover.volet_cuisine_level'].state === 'open' ? 'mdi:window-shutter-open' : 'mdi:window-shutter' }

low coral
thin vine
#

since the last one covers better for unavailable states

#

oops wrong reply to... @bright carbon it was meant for your question

stray merlin
#

Hey,
I'm still new to the whole template thing and trying to get my head around this.

I'm trying to create a Wunderground Forecast Sensor based on an rest api call.
So far everything is working. I'm trying to link two JSON-Values together.

My Sensor looks like:

    pws_forecast_1d:
      value_template: '{{ states.sensor.pws_forecast.attributes.daypart[0].daypartName[0] + states.sensor.pws_forecast.attributes.daypart[0].narrative[0] }}'
      friendly_name: Wettervorhersage 1D

If I only extra one value everything is working.
Is it not possible to link two values in one sensor?

thin vine
#

you can. are these numbers or strings?

stray merlin
#

Both are String

thin vine
#
  • can only be used for numbers
#

use ~ for strings

stray merlin
#

Thanks @thin vine , looks good...
😩 using HA for almost 3 years now, and still so much to learn...

thin vine
#

haha 3 years too. and learning new bits every day as well

#

and try templates out in devtools -> template first, that way you get errors early

stray merlin
#

I did, and there it worked

thin vine
#

that's weird

stray merlin
#

An it even Says it a string

#

But hey, now it worked. Maybe I'm getting closer to my first "Share your Project" Post in den Forums

thin vine
#

🙂

bright carbon
#

@thin vine thanks for your feedback.

#

I tried by implementing this line into the decluterring template but still no luck 😦

thin vine
#

try it in devtools -> template first, it should be working there

#

else something else is wrong, I tried the syntax in my own dev template

bright carbon
#

{{ 'mdi:window-shutter-open' if states('[[entity]]') == 'open' else 'mdi:window-shutter' }}

#

Correct, in template it is working

#

so this is the implementation in the decluterring template which is the issue 😦

candid scaffold
#

Is the external_url stored into a variable, so I can get it in template?

#

Have tried {{ get_url }}, {{ external_url }}, {{ network.get_url }} ect.

deft timber
#

not that I know

tranquil isle
#

how do i actually add a template

ivory delta
#

That's a pretty vague question. It depends entirely on what you're doing that needs a template.

timber locust
#

What Mono says. But maybe if you mean how to implement a template for a certain entity or line, you just write the template behind the entry that you need. So if you want to use a template for an entity id, you should write:

 - entity_id: {{ states('input_select.entity_selector') }}
ivory delta
#

With quotes around it, of course 😉

jagged obsidian
#

is there a way to template some data from a Device trigger? something in the vein of {{ trigger.device.model }} ???

thin vine
#

with that you can then get attributes from the device, including the model, as long as that is an attribute of the entity

jagged obsidian
#

not an entity, its a Device trigger

ivory delta
#

states[trigger.to_state.entity_id]
Functionally equivalent and far easier to read. Whoever wrote that example on the docs needs to be shot.

fossil totem
#

@jagged obsidian one of us is going to find an answer to this problem 😄

jagged obsidian
#

just keep trying

fossil totem
#

my problem is that it isn't even a trigger, so the trigger. approaches aren't going to work

jagged obsidian
#

i think noone knows 😄

fossil totem
#

i think it can't be done, but i'm going to chase it down just in case i'm wrong

#

it's been known to happen

thin vine
narrow topaz
#

Is something like the following possible? set_lights_onoff: alias: Reconfig Lights OnOff sequence: - service_template: > {% for ieee in ['XX:XX:XX:XX:XX:XX:XX:XX', 'XX:XX:XX:XX:XX:XX:XX:XX'] %} - zha.set_zigbee_cluster_attribute data_template: ieee: {{ ieee }} endpoint_id: 11 cluster_id: 768 cluster_type: in attribute: 3 value: 65536 {% endfor %}

modern hearth
#

Also as a noob it would seem some things folks use templating for (like button icon / color changes on state change) should eventually be part of the cards function using simpler key pairs in yaml. This would make HA more accessible to more folks. But I dont understand backlog so won’t pretend that this is important now.

thin vine
desert flume
#

This is probably a very noob question. I'm trying to create an automation with templating. Switched the automation editor to YAML view, and pasted this:

description: Test
trigger:
  platform: state
  entity_id: sensor.ikea_tradfri_switch1_click
action:
  service: >-
    {% if trigger.to_state.state == 'on' %}
      light.turn_on
    {% else if trigger.to_state.state == 'off' %}
      light.turn_off
    {% endif %}
  target:
    entity_id: light.ikea_tradfri_bulb1_light```
When trying to save it the UI says:
`Message malformed: Service {% if trigger.to_state.state == 'on' %} light.turn_on {% else if trigger.to_state.state == 'off' %} light.turn_off {% endif %} does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']`
It seems it doesn't acknowledge the template and tries to literally use it as a service name? What am I doing wrong? 😐
silent barnBOT
thin vine
#

2ND statement should be elif instead of else if or just else without de check

desert flume
#

wow, that was it. thank you!
yeah sorry, forgot this syntax in Python. 😊

thin vine
#

actually templates are Jinja

silent barnBOT
spring zenith
#

I made a helper (DAYS as a number) . How do i round it of? It shows 3.0 days now. Would like that it shows 3.

modest sparrow
#

How I can check if a variable/field in a script is a list or a single item?

#
  • wait_template: "{{ is_state(output, 'idle') }}"
#

output would normally be a single media player, i.e. media_player.kitchen, but I want to make the script work with a list of media_player as well, so I can specify one or more when calling the script

fossil totem
#

@spring zenith if your helper is an entity something like input_number.days, you can use something like {{ states("input_number.days")|int }}

#

@modest sparrow use the length filter

#

for example, i can get a count of the number of automations i currently have defined: {{ states.automation | length }}

#

now that i say that.... if it's a single item instead of the length of the list you get the length of the characters in the single item

modest sparrow
#

Great, thanks @luma! 👍

silent barnBOT
fossil hearth
#

can somone please help me with the above link ? i think its very simple..

deft timber
#

You have to make a for loop to iterate on the elements of values

fossil hearth
#

aha... can you please show me how its done ? thanks ❤️

deft timber
#

assuming your json is in the variable json_value:

{%for value in json_value["values"] if value[0] == "test 2" %}
   {{value}}
{%endfor%}
#

and you can replace {{value}} with wathever ou want ({{value[i]}} i being between 0 and 3)

ancient garnet
#

I want to create a templated sensor which combines the values of two entities. Is there a way to then hide those entities (without disabling them), so I don't accidentally pick them in an automation instead of the templated sensor?

deft timber
#

nop

ancient garnet
#

ok thanks, assumed not but worth asking 🙂

fossil hearth
#

guys.. command line entities don't have attributes ?

#

attribute template i mean ...

signal niche
#

Can I make a template to reset a scene to the way it was before.

#

I making a scene to that goes off when my van alarms goes off . lights flash etc .. So when i tell alexa reset van alarm all the lights and that go back to the state they was before ?

ancient garnet
#

How would it know what scene to revert back to? I guess you'd need to record it in a variable each time the scene is changed

#

but yes it's possible... maybe not as easy as youd like tho 🙂

timid osprey
#

it's very simple. on the fly scenes but not template related

ancient garnet
#

would this revert back?

timid osprey
#

you make a new scene before you do anything and then go to it when done

#

except for the creation of them, I guess

#

not restoration

fossil hearth
#

how can i give attributes to command line sensor ? its for google sheets api
am using command line since there are above 255 characters, but i don't want to call the api every single time, i wane do attributes.. how to do in this case ?

thanks 🙂

dreamy sinew
#

looks like you just define a list of keys to pull out of a json response

fossil hearth
silent barnBOT
dreamy sinew
#

trying to get in to values? don't think you can drill down. will just need to pull the whole thing and parse it out with template sensors

fossil hearth
#

the whole things is above 255 tho.. i tried that

fossil hearth
silent barnBOT
#

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
#

not sure if you can bypass that

fossil hearth
#

like only if command line had template attributes it could have worked..

#

coz i dont want to abuse the api.. just one pull

dreamy sinew
#

might be be better off writing a custom integration

fossil hearth
#

like a py script ?

#

cant belive this is the only way tho 😦

#

all these tools ... theres gotta be a way haha

dreamy sinew
#

well, that is one of the tools

fossil hearth
#

just need the whole thing and then ill te,mplate it 😛

dreamy sinew
#

why does it need to be command line?

fossil hearth
#

rest api is not able to pick it up due to its own limitations

#

its a curl -x get command

dreamy sinew
#

gotcha. probably going to need a custom integration then

fossil hearth
#

i see :/

#

thanks buddy ... just worried coz am no programmer

#

well figured it out

#

json_attributes: has no limits

#

was able to pull the whole thing out

dreamy sinew
#

ah ok

silent barnBOT
flint crown
#

I want to use a template for input_number.set_value

See here my automation:
https://paste.ubuntu.com/p/P57hBsgCGX/

But I got these error:
voluptuous.error.MultipleInvalid: expected float for dictionary value @ data['value']

jagged obsidian
#

you're templating the result {{3.5 | float}}

#

just 3.5 should do it if input number accepts decimals

sterile storm
#

Hi! I sent a wall of code in the wrong channel. This was my original message https://paste.ubuntu.com/p/MptRCgCdZS/

Long story short: I'm trying to make an automation that will turn on a light with a specific set of brightness + color temp depending on the sun position.

arctic sorrel
flint crown
# jagged obsidian you're templating the result `{{3.5 | float}}`
entity_id: input_number.heizung_vorlaufzeit
value: '{% if states("sensor.temperature") | float > 16 %} 1.0 {% elif 8 < states("sensor.temperature") | float <= 16 %} 2.0 {% elif 2 < states("sensor.temperature") | float <= 8 %} 2.5 {% elif -5 < states("sensor.temperature") | float <= 2 %} 3.5 {% else %} 4.5 {% endif %}}'

I get here the same error. Can you help me ?

jagged obsidian
#

you have an extra } at the end

flint crown
#

ok, thx

jagged obsidian
#

always run your stuff through the template editor

flint crown
#

but same error with the }

#

i run this template in the template editor
{% if states("sensor.temperature") | float > 16 %}1.0 {% elif 8 < states("sensor.temperature") | float <= 16 %}2.0 {% elif 2 < states("sensor.temperature") | float <= 8 %} 2.5 {% elif -5 < states("sensor.temperature") | float <= 2 %}3.5 {% else %} 4.5 {% endif %}

and get 3.5

#

input_number.set_value says: expected float for dictionary value @ data['value']

#

It worked

sterile storm
# arctic sorrel I wonder actually if _Blueprints_ (<https://www.home-assistant.io/docs/blueprint...

Well, actually I'm playing with that but IDK which would be the best way to do it. For example, IDK if I should do an automation just for the white lights with the condition: state of the sun and one for the yellow lights. Actually that was working, but I started to wonder if that abstraction level was a bit too much

https://github.com/JorgeAnzola/home-assistant-config/tree/master/automations/lights/kitchen
https://github.com/JorgeAnzola/home-assistant-config/tree/master/blueprints/automation/lights

arctic sorrel
#

Eh, it's personal taste

#

Now I'm on a version that supports Blueprints I'm starting to investigate them. I don't know it's going to make it easier to write automations, but at least I can keep logic in only one place

sterile storm
#

I'm not sure 😂

#

Maybe it's my way to not learn how the data_template thing really works

arctic sorrel
#

Well, it's no longer data_template anyway 😛

#

It became just data back around 0.115

sterile storm
#

See? I was already wrong hahaha

arctic sorrel
#

0.115 brought sanity in that it no longer required you to specifically say this service call/data block has templates

sterile storm
#

Would be nice if among with condition: and action: would be an else:

arctic sorrel
#

It's not called else, but yes, it's there 😉

sterile storm
#

😨

arctic sorrel
#

HA moves fast - it's easy to miss new, awesome, features

sterile storm
#

Maybe the answers I was looking for it's not in the automations/blueprints

#

Yes, mate, jeezus

#

I think that's perfect, thanks!

unique harbor
#

I seem to be struggling with a template, it's supposed to turn OFF a list of automations when boolean is ON and the other way around, but it only turns them OFF, never ON. Any help is appreciated!
https://paste.ubuntu.com/p/yntCSHXgpg/

unique harbor
deft timber
#

can be shorten

service_template: >-
  {{ "automation.turn_"+trigger.to_state.state }}
unique harbor
#

Thank you!!

copper seal
#

*user:password

deep echo
#

hello all, quick question. I am trying to get an alert from the minecraft server integration that alerts me when a specified user logs on.
I am basing my automation on the players_online state change and I want to check the attribute players_list. I am not sure how to address that one entity attribute in the value_template though.

deep echo
#

why am I getting an error using this in my call service notify action?
message: > {{ states('sensor.blah_minecraft_server_players_online') }}

#

tried that as well as using double quotes around the {{}} stuff

dreamy sinew
#

what error?

spring zenith
dreamy sinew
#

pick a different name

deep echo
# dreamy sinew what error?

it is all but impossible to copy the errors in the UI. let me look and see it if is in the logfile on the server. 🤦‍♂️

amber thicket
#

so im trying to create a pair of sensors from one API call using the REST sensor... the API returns this: {"error":null,"result":{"effective_hashrate":987654321,"reported_hashrate":123456789}}
however i think I'm having trouble with the template. the sensor config is here: https://paste.ubuntu.com/p/6ttFQyVtBr/ any ideas?

long nymph
#

Hi everyone. I have three rooms controlled by one nest thermostat in the spare bedroom. The two occupied rooms' temperature varies drastically from the spare room during the day. Can someone point me toward a template that would poll the temp sensors in the two occupied rooms, average the temps, and control the thermostat? Is this even the right approach?

ivory delta
#

I can't believe someone thought the old one was a good idea.

thin vine
#

also my first PR 😜🎉

silent barnBOT
dreamy sinew
#

isn't trigger.entity_id a thing?

#

couldda sworn i used it before

#

@amber thicket state_attr('sensor.mining_hashrates', 'effective_hashrate')

amber thicket
#

for the value_template?

dreamy sinew
#

use that for your calls for the attributes

amber thicket
deft timber
#

I think you need to set json_attributes_path

#

With {{value_json.result}}

#

And in your value template you search for value_json[0].result.name which refers a field I don’t see in your json

amber thicket
#

hmm

glossy viper
#

hi....i want to use statistics and i have some challenge. i want to have template sensor only when attribute driving is true in device tracker

#

driving can be true/false

muted fox
#

I'm looking for some help. I want to create a template sensor from a attribute that has an EPOCH time in it. I want a sensor that basically says "Dustbin emptied 39 minutes ago" and later turns into Dustbin emptied 1 day ago" etc etc

#

{{ ((as_timestamp(now()) - (state_attr('vacuum.rockrobo', 'last_bin_out') | int / 1000))) }}
so this will spit out the time difference in EPOCH

#

but how to I get this to say what I want?

#

Dustdin emptied {{ ((as_timestamp(now()) - (state_attr('vacuum.rockrobo', 'last_bin_out') | int / 1000))) | timestamp_custom("%M") }} minutes ago
this wil give me the minutes. So I guess now I have to wrap it in more templating to convert it into hours when its more than 59 minutes

#

no, nevermind that isn't correct %M will just go from 00 to 59

haughty karma
#

What might explain a template-based sensor not getting any logbook/history entries despite changing states and seeing those changes reflected in the UI / developer tools? The state values are either '0', '1' or '2' This is the value_template: "{{ states.sensor.chargepoint_list.attributes['station_list']['summaries'][0]['port_count']['available'] }}"

haughty karma
amber thicket
#

still fighting with ```sensor:

  • platform: rest
    resource: https://<API>
    name: mining_hashrates
    json_attributes_path: '{{ value_json.result }}'
    json_attributes:
    • effective_hashrate
    • reported_hashrate```, its putting the entire json result from the api server as the sensor's state instead of parsing out its attributes, any suggestions?
#

with sample results of the api call looking like {"error":null,"result":{"effective_hashrate":153333332,"reported_hashrate":111211946}}

#

I mean this looks simple but I’m not a coder so my brain is melting over here

royal vortex
#

~~```yaml

  • condition: template
    value_template: '{{ ( as_timestamp(now()) - as_timestamp(state_attr("binary_sensor.hue_motion_sensor_1_motion", "last_changed")) |int(0) ) > 900 }}'```

How do I get the time the sensor last changed states? That doesn't work. I'm trying to use it as a conditional so that it doesn't turn the lights off on me unless motion hasn't been detected for a bit.~~

#
value_template: '{{ ( as_timestamp(now()) - as_timestamp(states.binary_sensor.hue_motion_sensor_1_motion.last_changed) |int(0) ) > 900 }}'``` This works. Not sure why I can't pull it with `state_attr`, but it doesn't seem that I can.
boreal fiber
#

who can help me with a nested template of sorts? i currently have 3 ups and am using this to message myself which ups has lost power "message: "{{trigger.to_state.name}} has lost main power!"

but i want to include a state template to find the remaining time left of the ups that just lost power with
{{states('sensor.ups_main_ups_time_left') }}

but need to replace that entity with whichever one triggered it? make sense

#

states('trigger.to_state.name') or similiar?

#

but idk time left is another entity to the device main ups.

dreamy sinew
#

@royal vortex last_changed isn't an attribute 😉

#

@boreal fiber need to know where the data is coming from before we can make suggestions

boreal fiber
#

mqtt is polling apcupsd. each ups is a device that has 2 entities im trying to work with. status online/commlost and time left

dreamy sinew
#
{% set map = {'trigger_entity_1': 'sensor.entity_1_time_remaining', 'trigger_entity_2': 'sensor.entity_2_time_remaining'} %}
{{ '{} has lost main power! {} minutes of charge remaining.'.format(trigger.to_state.name, states(map[trigger.entity_id])) }}
fossil hearth
#

how can i have this list out the friendly names instead of the values under the same conditions.
{{states|selectattr('entity_id','in',state_attr('group.test_branches','entity_id')) | map(attribute='state') | reject('in', ['unavailable', 'unknown']) | map('int') | select('gt', -5 ) | list}}

thin vine
#

i've tested this on some of my own:
{{states|selectattr('entity_id','in',state_attr('light.woonkamer','entity_id'))|rejectattr('state', 'in', ['off', 'unavailable']) | selectattr('attributes.brightness', 'gt' , 0)| map(attribute='name') |list}}

#

so don't do the map's until you want to map what's in you list.

#

{{states|selectattr('entity_id','in',state_attr('group.test_branches','entity_id')) | rejectattr('state', 'in', ['unavailable', 'unknown']) | selectattr('attributes.int', 'gt', -5) | map(attribute='name') |list}}

#

if I didn't make any mistakes 😉

fossil hearth
#

hey ! 🙂 thanks for the help but i got this as an error UndefinedError: 'mappingproxy object' has no attribute 'int'

#

we need to run the value against the state

thin vine
#

so the state is a value, unless it's unavailable or unknown?

fossil hearth
#

yes that is correct!

thin vine
#

{{states|selectattr('entity_id','in',state_attr('group.test_branches','entity_id')) | rejectattr('state', 'in', ['unavailable', 'unknown']) | selectattr('state', 'gt', -5) | map(attribute='name') |list}}

#

should be it then ( I hope ) 😉

fossil hearth
#

it works ❤️ just needed to add '' around the -5

#

you are the man !

#

bless you dude

#

thanks

silent barnBOT
deft timber
#

You have to indent the entity_id: to be bellow data:

#
    - service: 'input_boolean.turn_{{"on" if trigger.event.data["args"][0] == "activate" else "off"}}'
      data: 
        entity_id: >
          {% set option = trigger.event.data["args"][1] %}
          {{expand(option)[0].entity_id}}
#

and replace data_template with data

uncut path
#

Oh man I feel dumb, thanks a lot for you help. I copy the call of the service from the automatisation UI panel and the entity_id was outside data

#
action:
  - service: input_boolean.turn_on
    data: {}
    entity_id: input_boolean.notify_lucas
deft timber
#

this last one is correct, but if you use template in entity_id, it needs to be under data

uncut path
#

Oh ok this is the difference thanks

#

And why move from data_template to data ?

charred dagger
#

Because you can.

#

They're interchangeable for now, but data_template will disappear eventually.

uncut path
#

Haha yeah sure, I started all my telegram automation with data

#

Ok I picked the wrong one, thanks I will update everything

charred dagger
#

A while back, picking data_template made sense.

mighty ledge
shell ferry
#

Could someone help me, (I think) I'm having a templating problems. https://paste.ubuntu.com/p/Pc7fGQ4t4M/
What I want to achieve: sensor.total_consumption_shelly_plug should summarise the value of the 5 listed Shelly plug sensors total_consumption value into one.
Everything works like a charm, until I restart my HA. Then at the start, all of the Shelly sensors total_consumption value is unknown or empty or 0 something, therefore the value of my sensor.total_consumption_shelly_plug is also empty, which will then be updated in a matter of few seconds into the correct value, which leads into my utility meter to have wrong data.

Before restarting my HA my utility sensor had value of 8.81 and after the restart it was 15.93, because (this is only my assumption) the utility meter thought that I spiked ~8kWh consumption in couple of seconds.

So, does someone have an idea how should I resolve this issue? can I add conditions into the sensor , like that it would not update its value, unless all the 5 Shelly plug sensors contained a proper value?

dreamy sinew
#

i wonder if min_max would handle this better

silent barnBOT
dreamy sinew
#

nope

#

it doesn't sum

#

lame

#

"unav" | float -> 0 is your problem

shell ferry
#

hmh?

#

so I should remove the | float after each sensor? or completely from the pasted yaml?

dreamy sinew
#

wouldn't be able to add otherwise

#

you'd just get wonky string math

shell ferry
#

ok, gonna give it a try

dreamy sinew
#

if you remove the float casting you're just going to combine all the strings

#

{{ "4" + "5" + "9" }} -> "459"

shell ferry
#

meh

dreamy sinew
#
{{
  [
    states('sensor.shelly_makuuhuone_total_consumption'),
    states('sensor.shelly_norttinurkkaus_total_consumption'),
    states('sensor.shelly_nuutin_huone_total_consumption'),
    states('sensor.shelly_tv_taso_total_consumption'),
    states('sensor.shelly_tv_taso_viihde_total_consumption')
  ]|map('float')|sum|round(2)
}}
#

little more compact

#

would have the same problem though