#templates-archived

1 messages · Page 99 of 1

dreamy sinew
#

Oh, that doesn't work that way

north helm
#

Bad paste...

#
tcm_starttimestamp:
        friendly_name: Start Timestamp
        value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'
inner mesa
#

That’s not an attribute of the sensor

#

Maybe that’s another sensor

north helm
#

That was my intention.... Making it its own.

inner mesa
#

But you’re using it as though it’s an attribute of sensor.tcm

cerulean cipher
#

yeah it's being called like an existing attribute

north helm
#

Ahh, ok. So what would be the correct way to do that?

inner mesa
#

Replace that block with sensor.tcm_starttimestamp

#

states(‘sensor.tcm_starttimestamp’)

north helm
#

{{ states(‘sensor.tcm_starttimestamp’) | timestamp_custom("%H:%M", 0) }}

#

?

cerulean cipher
#

try it

north helm
#

Tried it. Error rendering template: TemplateSyntaxError: unexpected char '‘' at 10

inner mesa
#

Try that in devtools -> Templates

#

I think you have the wrong kind of quote

north helm
#

K. One moment.

inner mesa
#

Some smart quote

north helm
#

That was it. However, it's still coming over as integer time.

#

{{ states('sensor.tcm_starttimestamp') | timestamp_custom("%H:%M", 0) }}

#

1596412800

inner mesa
#

You may also need to filter the state with ‘|int’ before passing it to time stamp_custom

cerulean cipher
#

ctime

north helm
#

Better....

cerulean cipher
#

I have a quick question @north helm you said you're pulling the time from API? but it comes back EST And not MT?

north helm
#

@cerulean cipher That is correct.

#

That worked in Templates, but when I add it to sensors.yaml, I get.

cerulean cipher
#

because with Ctime there is raw offset and DST offset

north helm
#
      tcm_realtime:
        friendly_name: Start Time
        value_template: '{{ states('sensor.tcm_starttimestamp'') |int | timestamp_custom("%H:%M", 0) }}'
#

Dangit

#

Sorry

#
Error loading /config/configuration.yaml: while parsing a block mapping
  in "/config/sensors.yaml", line 42, column 9
expected <block end>, but found '<scalar>'
  in "/config/sensors.yaml", line 43, column 37
#

Not following about Ctime...

cerulean cipher
#

CTime aka unix time

north helm
#

Ahh

cerulean cipher
#

is what you're getting your time from the API in

north helm
#

No, coming out of the API it's timestamp: '2020-08-02T21:49:28'

cerulean cipher
#

where did 1596412800 come from then

inner mesa
#

You’re also using the same quotes inside and out

north helm
#

@cerulean cipher That's coming from

#
tcm_starttimestamp:
        friendly_name: Start Timestamp
        value_template: '{{ as_timestamp(states.sensor.tcm.attributes["timestamp"])|int - 7200 }}'
#

@inner mesa Yes, I see that now in the editor.

#

Just changed to double quotes and it checks properly now. Reloading

#

Interesting. It's coming out at 02:00. I wonder if I'm subtracting 7200 minutes rather than seconds.

inner mesa
#

You should be able to work out the math in dev->templates

north helm
#

Agreed.

inner mesa
#

I would just bumble around until I got it right

north helm
#

I won't take up any more of your time. I appreciate your help and your patience, @inner mesa and @cerulean cipher!!!!

inner mesa
#

Np, glad to help

north helm
#

Bumbling is my middle name.

#

You're most kind. Have a great night!

cerulean cipher
#

no one bumbles like me, no one.

#

I bumble myself by bumbling.

north helm
#

{{ states("sensor.tcm_starttimestamp") |int | timestamp_custom("%H:%M") }} works like a beauty. There was an extra ,0 in the timestamp_custom

inner mesa
#

Excellent. Yeah, was wondering what that was doing, but figured you knew 🙂

north helm
#

Copying and pasting blindly. 🙂 It's what happens when a guy's native platform is "codeless coding"

cerulean cipher
#

you're coding in google

#

and that's OK

north helm
#

Cherwell Service Management, actually.

dreamy sinew
#

Mapp?

north helm
#

I use mApps all the time.

dreamy sinew
#

Was just involved in writing an integration with cherwell, was interesting

north helm
#

It's a fun platform to work on for sure.

#

What kind of integration?

dreamy sinew
#

Cmdb and incident

north helm
#

My project that is (FINALLY) about to deploy is redoing how CMDB and Incident and Approvals all interplay.

#

I'll be submitting our redesign and new Portal for consideration for awards this year.

dreamy sinew
#

Noice

north helm
#

I feel really silly when I can't do templating in HA, because I'm no dummy if I do say so myself.

#

It's just two completely different skillsets.

dreamy sinew
#

Templating is an interesting bird

silent barnBOT
dreamy sinew
#

I introduced jinja2 to my team and we've been using it all over our product now

north helm
#

I could've written the Turner Classic Movies web service call and presentation in ... an hour - tops ... in Cherwell.

inner mesa
#

we have our share of cough inexperienced cough users and it's a challenge to separate them from the folks who are this far away from figuring it out

north helm
#

Someone offhandedly said "We've got a new blank spot on the portal. Sure would be nice if we could have weather info there." "Hold my whiskey."

cerulean cipher
#

I was wondering if tcm was Turner Classic

#

LOL

north helm
#

I'm old. I decided this morning that I was sick of going to the TCM site all the time on the weekend when deciding what to watch.

dreamy sinew
#

I'm basically to the "hold my beer" with jinja. Getting there with python too

cerulean cipher
#

@north helm I'm almost old. But trying!

north helm
#

My philosophy is that I can make Cherwell wash your car, but get me into the yaml world and I'm a total noob despite using HA for almost 5 years. I've got RF integrations, hacked blinds.

#

@cerulean cipher Got you beat. Turned 50 last month.

cerulean cipher
#

that's ok, you have a healthy lead but the trick is to not let me catch up

#

39 in January here

north helm
#

Just a pup.

cerulean cipher
#

but it feels a lot older having a 14 year old kid

#

@north helm I have brothers older than you so I know 😛

north helm
#

IF there was a kid out there, he'd be 33 now.

#

Woke up at 3 last night and one of my boxes was going nuts. Couldn't figure out why, so I threw in a netdata docker and put it in HA and went back to sleep.

#

Isn't "woke up at 3" a fun thing to look forward to, kids?

cerulean cipher
#

I've done that most of my life

#

it's currently 12am and I haven't slept yet tho maybe if I had gone to bed 2 hours ago I'd be up at 3

north helm
#

I did it 17-35. Then I married a guy who does food for a living. I think his alarm is set for 01:30 tonight

#

We're getting off track a bit, though.

#

😄

#

So, in my world, hh is 12-hour time and HH is 24. This doesn't seem to apply in HA.

#

HA looks like it's either %H or more funky modifiers.

cerulean cipher
#

syntax curve

#

😄

dreamy sinew
#

That's the format

#

Python syntax

fickle spire
#

Hey guys, im trying to make a template binary sensor.
When i paste this: "{% if is_state('binary_sensor.server_zeus_ping', 'on') %}Online{% else %}Offline{% endif %}" into the dev tools template section it shows "Online" but when I add it into de configuration.yaml it always shows off. Any ideas?

lapis quarry
#

@lapis quarry you copied that from the forums? It has the invalid quote type. Replace all your quotes with the non-fancy quotes
@mighty ledge That did it Petro, what an eye!! Now it works thanks very much, I copied it from RobC sugestions last night while editing the template

velvet glen
#

Quick help/scan of my sensors.yaml file? I'm 'trying' to tidy up by adding a secrets.yaml and pulling the sensors into a config.yaml. I've done this and syntax seems to pass, but my influxdb sensors have disappeared from frontend - so clearly something daft I'm doing. Would someone mind scanning this file and letting me know if there's something wrong here? https://paste.ubuntu.com/p/7v5NKkVrXp/

fossil summit
#

Hey guys, I am having an issue with a template.. and the issue seems to be in the "name" of the array in a json payload. This is the test I am doing on the template test page in HA: https://pastebin.com/82Y4dWQ4

#

And it is returning: Error rendering template: SecurityError: access to attribute 'update' of 'dict' object is unsafe.

#

If I change "update" to "whatever".. it works 😄

charred dagger
#

update is a built-in function of any object which can be used to update several keys at once.

#

Try value_json['update'].state.

fossil summit
#

Cheers!

velvet glen
#

Hey, quick one - configuring the inbuilt sun sensor and it's displaying by default in UTC - ie: 2020-08-03T04:21:19.050Z - do I need to configure a template for this to be human readable in the configuration.yaml or is there an 'in application' or 'in lovelace' way of doing this?

mighty ledge
#

if you place it in an entities or entity card, it will display it as a relative time. You just need to set the device_class to timestamp in the customize section. If you want it as a time, like on a digital clock, then you need to make a template.

velvet glen
#

Ah ok, so if I wanted to convert it to display as: 'Monday, 3rd August' then it's a template job?

#

Any reason this can't be done in the frontend? (just usually something that's normally loaded on the client side to render - eg javascript, css, jquery, react etc) - would be miles quicker to debug without having to reboot each time!

ivory delta
#

You can test templates in the Dev Tools without rebooting.

hard apex
#

Hi, if I need 2 conditions (and one needs delay_on) for a sensor, am I forced to built 2 binary_sensors for the conditions and a third one for combining those ?

inner mesa
#

you can use for: in conditions to replicate delay_on: and delay_off: in sensor definitions

#

and conditions are default "and", so just specifying more than one condition ensures that all are true before proceeding with the action

#

I guess for: doesn't "replicate" the others because the sensor will change state immediately, but you can choose not to act on that state change unless it's been in that new state for a while

sinful bison
#

hi
i can't find how to make {{ expand('group.battery') | selectattr('state', 'lt', '15') | list | count > 0 }} work, because my state return an string but i need an int to compare number :(
any idea ? i have try a lot of stuff :(

inner mesa
#

"|int"

#

I always have to play around with stuff like that in devtools -> Templates to get them to work, but that's how you turn a string into an int

sinful bison
#

sadly, i couldn't put the int in the selectattr

#

i have spend 4H in the templates menu yesterday trying any workaround i could think about.

#

any other idea @inner mesa ? or do you know where i could put it ?
selectattr('state|int', 'lt', '15') or selectattr('state'|int, 'lt', '15') doesn't work

inner mesa
#

unfortunately not. I'm sure a Jinja Ninja will be along shortly

dreamy sinew
#

i haven't touched groups in forever. let me make one

sinful bison
#

i hope, i am usealy pretty good at this, but home-assistant jinja is more limited that the one i'm use to (no do, no append ...) hard to find a workaround

inner mesa
#

you can always whip up a python_script

sinful bison
#

this is a template trigger for an automation, i'm not sure i can use a python_script that way ... can i ?

#

(and it look a bit overkill)

inner mesa
#

no, you could use a python_script to set an input_boolean or something. But better if you can figure out the template

dreamy sinew
#

oh, for a trigger, i don't think it'll work anyway

#

not with a group like that

sinful bison
#

why not ? doesn't group trigger when an entity state inside change ?

#

i have no way to build an array with condition if selectattr doesn't allow me this, and var.append('foo') is locked for security reason 😞

dreamy sinew
#
states('sensor.guest_bedroom_temperature'),
states('sensor.izzys_room_temperature'),
states('sensor.living_room_temperature')
]|map('int')|list %}
{{ sensors }}
{{ sensors|select('lt', 78)|list|count }}```
chrome temple
#

You might want to take a different tack. E.g., you could use an event trigger looking for a state_changed event. Then in the conditions check if the entity is in the group, and if the old value of its state, when converted to an int, is 15 or more, and if the new value of its state, when converted to an int, is less than 15.

sinful bison
#

hum ... i need to look what map do but this is intresting

dreamy sinew
#

simplified

#
states('sensor.guest_bedroom_temperature'),
states('sensor.izzys_room_temperature'),
states('sensor.living_room_temperature')
]|map('int')|select('lt', 78)|list|count %}
{{ sensors }}```
#

you could single line it if you want

sinful bison
#

looking for a state_changed event
@chrome temple
I'm always worry about the load issue by listening to all state change and then dooing a condition

chrome temple
#

You need to find something else to worry about. 😜

dreamy sinew
#

the template listener is looking for state.domain.entity and/or states()/state_attr() stuff specifically

#

if that's not there, it might not trigger or update

chrome temple
#

I think a template trigger, if it can't find entity IDs, evaluates on any state change.

dreamy sinew
#

unless i'm crossing sensors and triggers

#

i don't use HA automation

sinful bison
#

what do you use ? nodered ? appdaemon ?

dreamy sinew
#

appdaemon

chrome temple
#

But I'm not sure what happens when using expand('group.x'). I know there was some work done to try and figure out what entities that relies on, but not sure what the status is. I heard there were issues.

sinful bison
#

well {{ expand('group.battery') | selectattr('state') |list }} don't return what i expected :
[<template state sensor.aeotec_limited_zwa003_nanomote_quad_battery_level=100; node_id=20, value_index=0, value_instance=1, value_id=72057594379763713, unit_of_measurement=%, friendly_name=Aeotec Limited ZWA003 NanoMote Quad Battery Level, device_class=battery @ 2020-08-02T22:53:17.416003+02:00>,...]

#

not realy the state

#

and because i can't have a hard coded list {{ expand('group.battery') | selectattr('state') | map('int') | select('lt', 50)|list }} don' t work

chrome temple
#

Remove the first selectattr.

sinful bison
#

it have the full object to map on then {{ expand('group.battery') | map('int') | list }} [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

chrome temple
#

Actually replace it with map(attribute='state')

#

So, {{ expand('group.battery') | map(attribute='state') | map('int') | select('lt', 50)|list }}

sinful bison
#

damn !

#

that work

#

thank's ! i realy need to take a deeper dive into 'map'. never use it at work

#

now to try if it does trigger automation :)

dull bloom
#

Hey I'm kind of new to templates so I'm hoping for a gentle hand holding here... I am trying to set up a sensor for my security panel door... It's not a binary sensor because it can be one of several states: secure, not_ready, bypassed, tripped, etc.... I'm trying to find out how to build the template to read the state and make the display values more user friendsly... Secure -> Closed (for doors), not_ready -> Open, etc.... Should be simple (I think)

#

is it just state.state == "secure" or something like that?

sinful bison
#

what i would do, is in the template do a set foo={'Secure': 'Closed', 'not_ready':'Open ...} and then use door is {{ foo[sensor] }}

dreamy sinew
#

probably need to add a reject for unav and unk

chrome temple
#

@sinful bison you probably still need the > 0 part, because a template trigger basically needs a boolean expression. More specifically, when the template is rendered, stripped of leading & trailing spaces, and converted to lower case, it has to result in exactly the word true to fire.

sinful bison
#

yea un foo[sensor]|default('doomed') should work i think

dreamy sinew
#

foo.get(sensor, 'doomed')

sinful bison
#

better, and i should have think about it

#

@chrome temple yea thank's i've added that already but it was kind to remind me

#

@dull bloom is that understandable, or do you need something more "finished" to understand ?

dull bloom
#

I understand what you're saying but I only want to change "Secure" and "Not Ready" since "Bypassed" "Triggered" and any other states are exception states that I would want to see the true value of... So I'm wondering if an if else would be better since I don't want to change the value for every state, just two

#

and no, I don't want something more "finished" -- I'm brute forcing myself to learn this so as little help as possible is what I want 😄

dreamy sinew
#

foo.get(sensor, sensor)

sinful bison
#

you can then alway use the default value to return you... damn he is fast

dreamy sinew
#

haha

sinful bison
#

thank's

dull bloom
#

and can I save this as a global template so I don't have to retype this code for every door in my security panel?

dreamy sinew
#

woof

#

@dull bloom you cannot

dull bloom
#

ok

#

I was trying to model like the {{ value_json.door }} idea where I could use {{ value_json.secure_door }}

sinful bison
#

this is sadly something i miss, making fully templatised yaml file :(

#

the capability to exange variable between the trigger and action template is a roadblock i've hit a lot :(

#

and i've been use to have that ... it's hard to not think with it after having it

dull bloom
#

ok new help... I have this as a sensor:

#
  • platform: mqtt
    state_topic: "omnilink/zone23/state"
    name: "Office Door"
    icon: mdi:door
    value_template: >-
    {% if (state.state == "secure") %}
    Closed
    {% elif (state.state == "not_ready") %}
    Open
    {% else %}
    Current state is {{ state.state }}
    {% endif %}
#

returning a value of "Unknown" -- what did I do wrong?

#

and could I have cleaned it up? I tried the way you said but it returned an error

#

I'm thinking state.state doesn't work per the instructions

#

yeah... that's assuming state is previously defined... Trying to find a way to get the state of the current entity rather than having to spell out the entity name in the template

stray raptor
#

can we use templates in custom components?

#

ie:

type: "custom:clock-card"
title: "{{sensor.date}}"
dreamy sinew
#

Typically not in cards unless they specifically say they support them

inner mesa
#

I don't see "title" as an option for that card, either

silent barnBOT
rough lark
#

I have a question on regarding template locks. I have a z-wave lock and a door sensor that I have combined into a single template lock. Now every time I unlock and open the door, I get multiple notifications. Is there a way to add a delay so I get a notification only once ?

#
value_template: >-
      {%if is_state("lock.front_door_lock","locked") and is_state("binary_sensor.front_door","off") -%}
      locked
      {%- else -%}
      unlocked
      {%- endif %}
inner mesa
#

the notifications are coming from an automation?

#

it sounds like your issue isn't with the template, but with some automation

chrome temple
#

@rough lark I agree with @inner mesa, it sounds like the automation is the issue. If you shared it we could take a look. But making some assumptions, maybe something like this would work for you:

- trigger:
  - platform: state
    entity_id: lock.front_door_lock, binary_sensor.front_door
  mode: single
  action:
  # Your notification goes here
  - delay: 5
#

That will prevent the automation from triggering again for 5 seconds.

oak kiln
#

nvm it was just confused with ints

faint pagoda
#

Hey guys, I'm trying to output the brightness value returned by an IKEA E1744 "dimmer" (through zibgee2mqtt) using system_log.write but either I generally don't understand how to output sensor values or I'm not using the right path but this only output the string itself. Can anyone please shed some light on this for me?

- entity_id: binary_sensor.0xccccccfffe98fb45_update_available
    platform: state
    condition: []
    action:
    - data:
      message: '{{ states.sensor.0xccccccfffe98fb45_linkquality.brightness}}'
    service: system_log.write
    mode: single
dreamy sinew
#

{{ state-attr('sensor.your_sensor', 'brightness') }}

#

Also rule 1 of templating

silent barnBOT
faint pagoda
#

Damn, I went through the triggers and actions doc pages but never got to this one. Thanks for your help!

faint pagoda
#

Replacing "data:" with "data_template:" and the message value to what you suggested gets me a "Error rendering data template: UndefinedError: 'attr' is undefined" error. Any idea?

inner mesa
#

it should be state_attr()

#

I haven't looked at the actual issue that you're trying to solve, but that was a typo above

faint pagoda
#

Thanks @inner mesa, that was it!

dreamy sinew
#

Ah sorry, on mobile

inner mesa
#

typing proper YAML formatting on a keyboard while also adhering to discord code blocks is a challenge

#

need a YAML keyboard with Discord extension

daring musk
#

yeah

lapis quarry
#

Hey guys, what would be the correct way to write this in a more compressed way?

silent barnBOT
lapis quarry
#

can it be written as a list as we do when using entity_id?

ivory delta
#

Just have a list of entities that act as triggers, then a condition that checks the new state is 'offline'.

lapis quarry
#

thanks mono, makes sense, going to try rewrite it

silent barnBOT
#

@lapis quarry 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.

lapis quarry
#

something like the above makes more sense, right?

ivory delta
#

Please follow the rules. That's not your first codewall.

lapis quarry
#

very sorry

#

trying to compress it removing a lot of stuff before posting it

#

my bad

ivory delta
#

Just use a sharing tool like the bot did, and as described in the topic of many channels including this one.

lapis quarry
#

sure, noted

#

I get this error in the template: (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['action'][1]['data_template']['message']. Got None.

#

can somebody point me in the right direction about what im missing

ivory delta
#

At which line?

#

Never mind, it's clear enough

#

It's the bit you missed out of your paste by trying to 'remove a lot of stuff'...

#

Share complete code if you expect help. People here are good but they're not mind readers.

silent barnBOT
lapis quarry
ivory delta
#

I'm not sure this is even possible:
{{ {{ trigger.to_state.state }} if trigger.to_state.state == 'offline' else "is in an" }}

#

It's going to see the first pair of closing braces and think that's the end of the template.

#

You want something like this instead:
{{ {% trigger.to_state.state %} if trigger.to_state.state == 'offline' else "is in an" }}

#

Gotta escape them braces.

lapis quarry
#

what does the % do in this scenario?

inner mesa
#

does that even work? I would have expected to need an {% if xxx %} xxx {% else %} xxx {% endif %} block

ivory delta
#

I could be wrong, Rob 😄 I'm weak at templating.

lapis quarry
#

let me try

ivory delta
#

Do it Rob's way. But don't nest templates within templates.

dreamy sinew
#

nonono

#

oh, scrollback

ivory delta
#

Oh, and I think it'd be more like this:
{{ trigger.to_state.state if trigger.to_state.state == 'offline' else "is in an" }}

#

I'm a dumb dumb.

dreamy sinew
#

{{ trigger.to_state.state if trigger.to_state.state == 'offline' else "is in an" }}

ivory delta
#

Don't need those inner braces for anything,

#

Snap 🙂

dreamy sinew
#

beat me

#

this time

#

XD

ivory delta
#

Yeah, saw my own mistake. Not often I beat you or petro for template stuff.

lapis quarry
#
{{ trigger.to_state.state if trigger.to_state.state == 'offline' else "is in an" trigger.to_state.state "state" }}
#

this also correct?

ivory delta
#

Looks right, try it out.

dreamy sinew
#

no, that won't really work

#

else "is in an {} state".format(trigger.to_state.state)

#
{% sensor = trigger.to_state.state %}
{{ sensor if sensor == 'offline' else 'is in an {} state'.format(sensor) }}
lapis quarry
#
          message: >
            Keyring Receiver 
            {% sensor = trigger.to_state.state %}
            {{ trigger.to_state.name[7:9] }} is {{ sensor if sensor == 'offline' else 'is in an {} state'.format(sensor) }}, it might have been disconnected or needs to be reset
#

Invalid config for [automation]: invalid template (TemplateSyntaxError: Encountered unknown tag 'sensor'.) for dictionary value @ data['action'][1]['data_template']['message']. Got None.

brisk temple
#

need to set sensor

lapis quarry
#

isnt that what this line does:?
{% sensor = trigger.to_state.state %}

brisk temple
#

{% set sensor = trigger.to_state.state %}

dreamy sinew
#

oh woops

#

need the set

#

that's probably why it died

#

man, i'm flopping lately

ivory delta
#

You should hydrate.

lapis quarry
#

yes that did the trick

#

thanks guys, this templating stuff is very usefull

#

many possibilities, wish I had known all this earlier, learned a lot from you guys last few days

dreamy sinew
#

You should hydrate.
Nah, need a nap

hollow girder
#

hello, there are some things that I still do in CostumUI because is faster and easy to set that in Lovelace, une is the icon color, when I what it to be in all the place. Now I would like to do this:

customize_glob:
"*":
templates:
icon_color: >
if(attributes.config.autoon === true)
return 'rgb(0,0,255)';

Any entity with atrribute config.autoon === true, should set the icon to blue. I know that with states I can use if (state === 'on')
and it works, but I cant make it work with atrributes. Can any one help me?

mighty ledge
#

@hollow girder is the attribute named 'config' or 'autoon'?

hollow girder
#

config.autoon

#

I think that the problem is related with costumize_glob, because a normal configuration to the entity is working

mighty ledge
#

@hollow girder I could see you getting exceptions with your code with a glob. Because 'config' will not exist on all entities, but you're going a step further and asking for 'autoon' on config. That will cause an exception when 'config' doesn't exist.

rough lark
#

@rough lark I agree with @inner mesa, it sounds like the automation is the issue. If you shared it we could take a look. But making some assumptions, maybe something like this would work for you:

- trigger:
  - platform: state
    entity_id: lock.front_door_lock, binary_sensor.front_door
  mode: single
  action:
  # Your notification goes here
  - delay: 5

@chrome temple @inner mesa - Thanks for the response and sorry for the delay. In my case, it's actually not notifications via Automation. I use HomeKit support in HomeAssistant and the notifications are from HomeKit. The notification happens because the state of the template_lock entity changes quickly. On a similar note, is there a delay option we can add for the template sensors so that there are no immediate state changes say for 5 seconds?

hollow girder
#

@hollow girder I could see you getting exceptions with your code with a glob. Because 'config' will not exist on all entities, but you're going a step further and asking for 'autoon' on config. That will cause an exception when 'config' doesn't exist.
@mighty ledge yes, that is happening, HA will not even boot! Can I get pass this? like, if config exists and autoon exists, and autoon === true? 😩

mighty ledge
#

@hollow girder

            if("config" in attributes && "autoon" in attributes.config && attributes.config.autoon === true)
              return 'rgb(0,0,255)';
chrome temple
#

@rough lark what are you using for value_template in the template lock? And what do you have optimistic set to?

hollow girder
#

@hollow girder

            if("config" in attributes && "autoon" in attributes.config && attributes.config.autoon === true)
              return 'rgb(0,0,255)';

@mighty ledge worked 100%.. tks

mighty ledge
#

np

rough lark
#

@chrome temple - Optimistic is set to default. I tried setting it explicitly to false as well as removing it, but no change.
Here;s the value template.

value_template: >-
      {%if is_state("lock.front_door_lock","locked") and is_state("binary_sensor.front_door","off") -%}
      locked
      {%- else -%}
      unlocked
      {%- endif %}
silent barnBOT
chrome temple
#

It's not completely clear why you're wrapping this template lock around lock.front_door_lock. Can you explain what you're trying to achieve, and what binary_sensor.front_door indicates and why you're using it here? It would seem if the state of lock.front_door is changing quickly, it's not because of lock.front_door_lock but because of binary_sensor.front_door.

#

And is it even appropriate to use a template lock here instead of a template sensor???

safe knot
#

Hello, I'm new to templating in HA. I was wondering if it was possible to use the output of a sensor as an input for something like a Gauge which has min and max attributes. Does it have to allow being templated in order to do this?

hollow bramble
#

You mean use a sensor value for the min/max values?

safe knot
#

Precisely

#

Instead of an absolute and static value

hollow bramble
#

no that's not possible

safe knot
#

Oh ok. Thanks for the reply

rough lark
#

@chrome temple - Good question and I see I was not clear. For my front door, I have a z-wave lock (lock.front_door_lock) as well as a open/close sensor (binary_sensor.front_door) .

So in essence, I want to combine "Is the Door Unlocked ?" and "Is the Door open ?" in a single sensor.

I think template lock is required here because I want the ability to remotely lock and unlock this door.

daring musk
#

how to count time interval between two states?

9:00:08 PM ac turned off 8:50:56 PM ac turned on

chrome temple
#

@rough lark you can remotely lock & unlock the lock (i.e., lock.front_door_lock), but you can't remotely open & close the door, can you? (Or maybe you can???) I don't think a template lock makes sense here. The actual lock is locked or not independent of whether the door is open or closed. I think you should use a template sensor that tells you if the door is closed an locked, or not.

mighty ledge
#

I'd have to agree. You're not going to get a 1 entity solution here. You'd want to maybe use a custom lovelace card to handle the look in the UI

rough lark
#

@chrome temple @mighty ledge - Thanks. That's what I was using for some time now. I figured I could consolidate both of these into a single entity (that works in HomeKit as well as HomeAssistant UI. I am not sure a template sensor would work either

Here's what happens. Let us say, the door is closed and locked. I would unlock the door (Notification #1) and open it (Notification #2). I think the template sensor would run into the same issue. This might also be because of HomeKit triggering notifications.

Maybe an option might be to create a template lock (with a static value) and use automations to update the status of the template lock. I haven't tried it, but would that work ?

chrome temple
#

I guess I don't see why you're getting multiple notifications. With the way you have the template lock configured (and assuming you're not using optimistic mode), if either the underlying lock was unlocked, or the door was opened, the state of the template lock should change to unlocked. Now if the other is done (i.e., so that both the underlying lock is unlocked and the door is opened), that should not change the state of the template lock.

ivory delta
#

@young shadow What does that template say if you try it in devtools > Templates?

#

Also, it looks like you have a typo in there:
{{ states('sensor.polcz_garage_distance_sensor')|float > 0.1 or is_state('sensor.polcz_garage_distance_sensor', 'nan') }}
Your closing parenthesis for is_state was in the wrong place.

young shadow
#

@ivory delta i get this in at Templates: Unknown error rendering template i will try with the fixed typo

#

@ivory delta it was the typo, it works now. thanks!

silver pewter
#

Hello! I have a template for a sensor with names on who last unlocked my doorlock. I want to display the latest sensor value (name) on a card. how?
after searching on google for almost 2 hours i have to ask here. I'm too new to this xD

chrome temple
brisk temple
#

@daring musk where are you getting those times from?

daring musk
#

from logbook

brisk temple
#

you can try writing last_triggered or last_changed to 2 separate input_datetimes then do a comparison of the input_datetimes using as_timestamp(state('input.datetime.1')

daring musk
#

😄

chrome temple
#

Yeah, that's way over complicated. 😄 So you only want it updated when it turns on, right?

daring musk
#

yeah

#

i wanna know how long it takes to cool down the room, and based on interval change fan speed (low, med, high)

chrome temple
#

So you want to know how long it was off basically?

silver pewter
#

it is a MULTILINE WITH AN IF

And if you don't know how to do that last part, then ask in #frontend-archived .
@chrome temple
Yes i did! 🙂 this type : MULTILINE EXAMPLE WITH AN IF TEST

chrome temple
daring musk
#

oooh

#

😄

#

thank you

#

i forgot about it

chrome temple
#

@silver pewter sorry, I'm not following you. What is "MULTILINE EXAMPLE WITH AN IF TEST"?

silent barnBOT
chrome temple
#

So you have a template sensor. Ok. So do you still have a question? Or did you get your answer in the other channel?

silver pewter
#

I want to display the latest sensor value (name) in a card, is it possible?

#

name on the person who last unlocked door, next to door lock icon 😛

chrome temple
#

I guess I'm confused because you started by saying, "I have a template for a sensor with names on who last unlocked my doorlock." Now it seems you're saying you don't have that.

#

Wait, or is that the template sensor you shared? If so, then, again, if you're just asking how to display an entity (in this case a template sensor) in the frontend, then that's a question for #frontend-archived .

silver pewter
#

ok thank you 🙂

silent barnBOT
#

@silver pewter 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 not your first codewall. Please respect the rules.

silver pewter
#

Is it possible to hide "0" (Master) ?
I dont want want it in my sensor

#

oh, ok sry !

dreamy epoch
#

I am using the basic Entities card, how do I go about changing what 'on' and 'off' mean? I am using the Mikrotik Router add-on to do device tracking, but its showing 'Home' and 'Away' for 'online' status

ivory delta
#

Just take out lines 8 and 9 and it won't ever show 'Master'

dreamy epoch
#

is tehre a way to change what 'on' and 'off' mean? 😕

ivory delta
#

What do you think they should mean instead?

dreamy epoch
#

Online and Offline ?

#

not "Home" and "Away" thats for sure

silver pewter
#

haha is it so simple! Thank you !! 🙂

dreamy epoch
#

even a basic "on" and "off" would be better

ivory delta
#

'on' and 'off' is easy to achieve. Wrap the sensors you don't like in a binary_sensor.

#

Changing what's shown for other things is a UI choice - you're probably going to want to change that in your #frontend-archived

#

If you check in devtools > States, is the actual state 'on' or 'off'?

dreamy epoch
#

its on

ivory delta
#

Yeah, so it's the integration that's deciding to show 'Home', you don't get any control over that.

#

You either want to customise it in a Lovelace card somehow if you care about what it shows in cards or set up another integration to wrap it. binary_sensor for plain on/off, and a template sensor if you want to decide on the text yourself.

silver pewter
#

Just take out lines 8 and 9 and it won't ever show 'Master'
@ivory delta this is what happens when i did like u said 😛 see image. Sry for my bad english!
https://imgur.com/2NCn0vq

#

on the first pic i want the name of the latest person who unlocked the door. When someone unlocks the lock, it automatically locks by itself. and that is 0 master xD

dreamy epoch
#

not sure why a networking addon would chose "Home" and "Away" for device tracking status ?

silver pewter
#

is it possible to do something like (if state is 0, show the state that was before 0) 😛

ivory delta
#

Not the way you're doing it, no.

#

Use an automation to save that 'name' to a helper whenever it changes (but only when the new value isn't 'master'). Use the value of that helper wherever you need to see the name.

silver pewter
#

Can you please link the docs for that? sorry im a noob! 😛

#

the helper thing

ivory delta
#

Not everything is documented. The documents are a toolkit, you still have to build the finished product with those tools.

silver pewter
#

okey i see. Thank you

ivory delta
silver pewter
#

thank you mono!

mighty ledge
#

@dreamy epoch all location tracking devices are home/away. People use network connection to determine if they are home or not when gps fails.

dreamy epoch
#

ahh. do i have to order devices for a person in a particular way or HA figures it out based on most recent or something?

hollow bramble
#

It’s always the most recent

dreamy epoch
#

thnx

zenith fractal
#

hi, anyone want to assist me in a (for me) strange behavior of a binary sensor template?

#

i'm using the Developer - Template debugging, which shows a relative simple operation : {{ ( as_timestamp(now()) - as_timestamp(states.binary_sensor.slaapkamer_veluxraam_links.last_changed) ) < 60 }} , as True for the first 60seconds, and afterwards as False.

kindred trench
#

WARNING (MainThread) [homeassistant.bootstrap] Waiting on integrations to complete setup: person
My home-assistant seem to be stuck at this

zenith fractal
#

so, I should think that this operation would result in : 'on' state for a binary_sensor for the first 60sec and afterwards as : 'off' .. but it doesn't .. ?

kindred trench
#

I dont have person: in my configuration.yaml either

#

ah sorry, wrong channel

zenith fractal
#

my complete binary_sensor :

  • platform: template
    sensors:
    slaapkamer_veluxraam_links_last60s:
    device_class: window
    value_template: >-
    {{ ( as_timestamp(now()) - as_timestamp(states.binary_sensor.slaapkamer_veluxraam_links.last_changed) ) < 60 }}
brisk temple
#

@zenith fractal iirc now() doesn't cause updates, you'll need to use time & date sensor

little gale
daring musk
#

'true' is a string

chrome temple
#

Because the attribute is a bool, not a str. Remove the quotes around the word true.

fickle spire
#

Hey guys, im trying to make a template binary sensor.
When i paste this: "{% if is_state('binary_sensor.server_zeus_ping', 'on') %}Online{% else %}Offline{% endif %}" into the dev tools template section it shows "Online" but when I add it into de configuration.yaml it always shows off. Any ideas?

buoyant pine
#

Just do

#

But why make a binary template sensor for that 2Think

fickle spire
#

I would like it to show online or offline instead of home / away or connect or something other

buoyant pine
#

Oh so you want the actual state to be Online or Offline?

fickle spire
#

Yeah

buoyant pine
#

Ok so make a regular template sensor then, not a binary template sensor

#

Could even do

silent barnBOT
warped hornet
#

Any suggestions? Sorry for large code

#

Or any way to do a forloop for every key in json string?

fickle spire
#

Could even do

@buoyant pine that worked. Thank you 🙏

zenith fractal
#

@zenith fractal iirc now() doesn't cause updates, you'll need to use time & date sensor
@brisk temple Thanks, I'll look into this

dreamy sinew
#

@warped hornet what's the end goal?

dreamy epoch
#

hi, new to HA, i know about selectattr to filter based off attr value, but is there a way to filter based off logic, ie can i do selectattr('...', 'gte', 80) or something?

silent barnBOT
dreamy epoch
#

'gt', 80 worked i guess

dreamy sinew
#

search for tests

dreamy epoch
#

ahh thnx 🙂

#

alright one more, in either a autoamtion or script, can i wait until a specific timestamp (coming from sensor state attribute) i see you can wait for a state change but not a specific timestamp?

#

or i need to do some timestamp math

#

im guessing im goin to have to write a sensor or two to automate this

warped hornet
#

@warped hornet what's the end goal?
@dreamy sinew To have a list that I can iterate over instead of a big json tree

dreamy sinew
#

that is a mid goal, what is the end goal of the list?

warped hornet
#

To use it in auto entities together with multiple-entity-row

#

The json string is in an attribute of a sensor. And I would like to create a entity row for each key in that json structure

daring musk
#

what is the platform of your sensor?

#

you can use attribute_templates and map ur json there no?

warped hornet
#

The sensor is from the transmission integration

#

And it's torrent status is a long json string with every torrent name as a key. For each key is there som meta about the torrent

#

Very impractical I think

dreamy sinew
#

you can iterate over dictionaries

warped hornet
#

Yea, I found the method 🙂

vast harbor
#

I am trying to add an html wrapper to a template. How would I wrap the 'AM' and 'PM' in a <span> so I can style it?
{{ '{:02d}:{} {}'.format(hour if hour == 12 else hour % 12, time[3:5], 'PM' if hour>11 else 'AM') }} .

I tried a few options with Markup but nothing seemed to work. Any help?

dreamy sinew
#

try to get it rendering in the template tester first

#

once you get there, you can try adding the spans

#

we'd need to see the full thing you're trying too

vast harbor
#

Thanks @dreamy sinew I tried entering in the markup in the tester in a few spots but it just renders as a string and not html. Basically in a card, I have the time and AM/PM after it. I want to style the AM/PM to be smaller but it just renders the time and pm without any markup to be able to style it.

dreamy sinew
#

gotcha. i haven't touched the cards at all

thorny snow
#

I'm trying to make a template to select all my sensors of a certain 'device class' e.g. motion for a template automation.

#

Tried something like: {{ states|selectattr('device_class','in',['motion'])
|list|join(', ') }}

#

but without success

#

Any ideas what I'm doing wrong?

chrome temple
#

selectattr('attributes.device_class',...

thorny snow
#

should it be preceded by the states| ?

chrome temple
#

Everything else you had was ok as far as I could see. You just need to add attributes. into the selectattr().

#

selectattr() looks at the "attributes" of the State Object -- https://www.home-assistant.io/docs/configuration/state_object/ -- like state, last_changed, etc., so to get to what is usually called "attributes" in HA you need to use attributes.ATTRIBUTE_NAME (because attributes is an "attribute" of a State Object. Yeah, I know.)

thorny snow
#

Got it 🙂

#

Works

#

Great thx!

thorny snow
#

Hi, I'm trying to subtract two sensors. I don't understand why this is giving me an error:

#

{{ states('sensor.br_temperature') - states('sensor.bedroom_temp')}}

#

I'm getting "Unknown error rendering template"

#

Had to convert to float, it's working now.

lapis quarry
#

Hey guys, had this template that I thought was working but I rebooted HA and saw a error in the log file:

#

Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'

ivory delta
#

Well it's telling you the answer. Whatever entity triggered the automation apparently doesn't have a 'to_state'

#

Check that entity in devtools > States

lapis quarry
#

I see

#

so its the

      - platform: homeassistant
        event: start
ivory delta
#

That'll do it 😉

lapis quarry
#

I understand, any tips on how to get this to work when im reebooting HA all the time? I found the automation doesnt execute many times because of this

ivory delta
#

Well your question isn't actually about the templates, so head over to #automations-archived to pick up the rest.

lapis quarry
#

thanks mono

lapis quarry
#

back to templating, trying to figure this one out:

#

Living Room Motion DateTime Update: Error executing script. Invalid data for call_service at pos 1: extra keys not allowed @ data['data']

#

any tips on how to write it correctly?

lapis quarry
#

invalid template (TemplateSyntaxError: expected name or number) for dictionary value @ data['action'][0]['data_template']['value']. Got None.

#

off to bed, will be back tomorow

#

😴

mighty ledge
#

@lapis quarry if trigger.platfrom == ‘state’ and...

lapis quarry
#

Sorry Petro, I know and apreciate you are just trying to get me to learn and think but I dont get it..

buoyant pine
#

@lapis quarry remove the double quotes

#

(in the template)

lapis quarry
#

?

summer oasis
#

anyone know why this binary_sensor stays off?

    gym_shield_plex_in_use:
      entity_id:
        - media_player.gym_shield_plex
      value_template: >-
          {{ states.media_player.gym_shield.state not in ["off","idle","unavailable"] }}

the template evaluates to False when i put it in developer-tools/template (because the shield is unavailable)

buoyant pine
#

@lapis quarry those look the same

#

Remote the quotes from everything under value: >

lapis quarry
buoyant pine
#

trigger.to_state.name returns the friendly name of the trigger entity

#

You'd need to reference the friendly name, or use trigger.to_state.object_id (probably) instead

lapis quarry
#

but friendly name is set the same

#

motionlr01x

buoyant pine
#

Ah

lapis quarry
#

anyway thanks for that tip, changed it to object_id as it makes more sense and something good to know for the future

#

still same behaviour though 😦

buoyant pine
#

having a hard time figuring out what's wrong, but honestly what you could do instead is just write a timestamp to an input_datetime (or that input_text, even) instead of using the template and referencing last_changed @lapis quarry

#

or, rather, just use {{ now() }} as the value

lapis quarry
#

yes that works

#

good idea

#
        data_template:
          entity_id: >
            input_text.{{ trigger.to_state.object_id }}
          value: >
            {{ now()}}
#

a lot simpler 👍

gleaming urchin
#

Hi

silent barnBOT
gleaming urchin
#

And I have this as a light (platform template)

silent barnBOT
gleaming urchin
#

brightness works, as does on/off, but struggling with set_color

#

Please could someone nudge me in the right direction 🙂

silent barnBOT
#

@gleaming urchin 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
#

Use a code sharing tool for anything longer than a few lines please. There are links in the topic.

#

When you say you're struggling, what's the problem?

gleaming urchin
#

So I'm unsure in the template how to read the color and how to put it in the rest_command :/ (also sorryyy for wall spam)

buoyant pine
#
{{ (brightness /255*100) | int | round(0) }}
``` should be

{{ (state_attr('light.stairs_strip_strip', 'brightness') | int /255*100) | int }}

gleaming urchin
buoyant pine
#

btw | round(0) after | int is useless since | int already makes the number an integer (that is, no decimal places)

gleaming urchin
#

Sorry by the way, very new to all this :/

buoyant pine
#

did you see what i wrote above?

gleaming urchin
#

Thank you, applying that now 🙂

#

Brilliant, so I have the color wheel now! Now, when I change the brightness, the light turns off completely

#

In short, the body of the request to the API should be the following. It's just how do I read that information, and then put that into restful:

    "device": "C7:FD:A4:C1:38:BD:34:94",
    "model": "H6159",
    "cmd": {
        "name": "color",
        "value": {
            "r": 0,
            "g": 255,
            "b": 255
        }
    }
}```
#

I think for now, I'll have it as a brightness and on/off in HA, and can look at color in the future when I'm a bit more used to home assistant. Thanks!

brisk temple
#

how did you get their api? emailed them?

gleaming urchin
#

It's in the app, you go to about, and you can request an API key

#

it instantly emails it to you

brisk temple
#

thanks

gleaming urchin
#

If you get it working @brisk temple, please let me know!

brisk temple
#

i'd assume it would be states.sensor.sensorname.attributes["cmd"]["value"]["r"] to get the info

trim leaf
#

hi all - is it possible to access the last time a state changed from a template?

#

id like to try do some similar work in templates that you see in the state trigger

#

ie: if last change was 10 min ago, do this

ivory delta
#

Yes, you can do something like {{ states.switch.some_switch.last_changed }}

silver pewter
silver pewter
#

i see i forgot to add switch at "{% if is_state('SWITCH.auto_lock_dag', 'on') %}" but still not working 😛

inner mesa
#

"SWITCH" is wrong

#

"switch"

silver pewter
#

yeah it is switch 😛

#

still not working :/

inner mesa
#

does it work in devtools ->Templates?

silver pewter
#

What do you mean ? i am new to this

inner mesa
#

copy and paste exactly that into devtools ->Templates

silver pewter
#

okok

#

is it working ? 😄

inner mesa
#

Looks like it always returns mdi:lock-open-alert-outline. Did you expect something else?

#

Now you have ‘On’ where you want ‘on’

#

Pay attention to case

silver pewter
#

atm that witch is on, so i should be mdi:lock-reset ?

#

switch

inner mesa
#

👆

silver pewter
#

ok, it as "on" before. I try again 😄

inner mesa
#

Randomly changing things won’t help 🙂

silver pewter
#

true true !

inner mesa
#

When in doubt, watch the state in devtools->States and make sure you’re matching that

silver pewter
#

ok! it is "on" there 🙂

#

still wrong icon :/

#

Can it show the icon from the template there?

#

and that switch temple text is in this .yaml file : home-assistant\hass.io\homeassistant\paket\idlock.yaml ( packages: !include_dir_named paket . in comfiguration.yaml)

inner mesa
#

If you see the icon flipping back and forth in devtools ->Template when you manipulate the lock, I dunno what’s wrong

#

Are you sure that’s the same entity? It doesn’t show your friendly_name

silver pewter
#

ok i will try that

#

yes same entity

#

template in developer tools showing right icon when it is on/off

inner mesa
#

where did you get "lock-open-alert-outline" from? I don't see it in the Material Design icon list

silver pewter
#

found code there

#

mdi:lock-reset works but not lock-open-alert-outline

#

so maby thats why xD

inner mesa
#

it didn't show up in VSCode, so that was a clue. there's a lock-open-alert, which maybe has an "outline" variant

#

if you're referencing a non-existent icon, that would probably show up in your HA log

silver pewter
#

changed icon and rebooted, still wrong icon. i dont have to add anything on the card itself ? like "icon :mdi..." ?

inner mesa
#

I believe that HA is using v5.3.45 of the icons, and you may be looking at 5.4.55

#

shouldn't need to. I'm hacking something together now

silver pewter
#

ok, now i changed both icons to mdi:baby / mdi:bulb i tested them both on another card and i can see them. rebooted now and still wrong icon

#

mdi:baby / mdi:home **

#

Thank you for trying to help me 🙂

#

i have to seep now, thank you Rob! bye 🙂

inner mesa
#

seems like maybe it's the lack of a value_template

#

if you don't include one, it reverts to "optimistic" mode, which means that it just assumes that the device controlled by the switch actually changes state

#

if I give the switch a value_template, it changes the icon as I expect

#

you could do the same with the same template you're using for the icon

silver pewter
#

Can u please tell me what to add o value_template? 😄

inner mesa
#

{{ states('switch.auto_lock_dag', 'on') }}

silver pewter
#

ok i try 🙂

inner mesa
#

my example:

#
      auto_lock_dag:
        value_template: >-
          {{ states('switch.fr_table_lamp') }}
        turn_on:
          service: switch.turn_on
          entity_id: switch.fr_table_lamp
        turn_off:
          service: switch.turn_off
          entity_id: switch.fr_table_lamp
        icon_template: >-
          {% if is_state('switch.fr_table_lamp', 'on') %}
            mdi:thermometer-minus
          {% else %}
            mdi:thermometer-plus
          {% endif %}
#

works fine

silver pewter
#

Wohooo!!

#

Thank you!!

#

5h later it works!!

#

thx so much rob 🙂

inner mesa
#

np, I learned something as well 🙂

silver pewter
#

hehe good 😄

#

Goodnight!

silver pewter
#

Hello again @inner mesa The icon changed with that template but now i cant toggle it on/off . Do you know why ? :p

waxen rune
#

is it possible to access an add-ons log from a template? I want to monitor the last received date/time on my Tellstick sensors.
I can manually run hassio.addon_stdin with {"addon":"core_tellstick","input":{"function":"list"}} to get a list of all sensors and their values and last received date/time. But that info doesn't appear in the HA log.
Any tips how I could automate and template the actual last updated-value from the Tellstick add-on?

dreamy sinew
#

Not likely

inner mesa
#

@silver pewter Nope, worked fine for me.

dreamy sinew
#

@wispy bay
"{{ '-{}'.format(states('sensor.sensor_2')) if states('sensor.sensor_2')|float > 0 else '+{}'.format(states('sensor.sensor_3')) }}"

#

feel free to flip the sensor order around but that's the jist

wispy bay
#

@dreamy sinew Thanks! Im going to work on that right now!

dreamy sinew
#

oh oops. states('sensor.sensor_2) etc

#

alternatively, you can do math to flip the sign

#

-1 * states('sensor.sensor_2')|float if ... else states('sensor.sensor_3)|float

#

tweaked the full template again, wanted float instead of round

wispy bay
#

@dreamy sinew absolutely prefect! Thanks so much!

small wolf
#

I'm trying to create a sensor from some data. The data is in this format: {"dump" : "Aircraft:20\nPosition:14\nMsg/\s:49"}

#

this is my config: - platform: mqtt name: "ADSB Sensor" state_topic: "abc/def/ADSB" value_template: "{{ value_json.dump }}"

#

but my sensor keeps showing "unknown"

hollow bramble
#

are you sure that's the output of that topic?

small wolf
#

I believe so, this is what I saw during testing

#

oh, it won't let me upload a picture

silent barnBOT
#

Please use imgur or other image sharing web sites, and share the link here.

small wolf
hollow bramble
small wolf
#

yeah, it worked fine when I tested it, but it doesn't appear to be working in my configuration file

hollow bramble
#

try subscribing to the topic manually in HA

small wolf
#

how do I do that?

hollow bramble
#

Go to configuration > integrations > click on configure for the mqtt integration

#

and it will give you an option to listen to a topic

small wolf
#

well, there's my problem. I'm not getting anything...

hollow bramble
#

sounds like either a problem with your mqtt integration config or you're mistyping the topic

small wolf
#

probably the mqtt integration...I've tripled checked the topic

#
anonymous: true
customize:
  active: false
  folder: mosquitto
certfile: fullchain.pem
keyfile: privkey.pem
require_certificate: false```
#

that's my config

#

for the broker

hollow bramble
#

That looks like an addon config. You still have to integrate it into HA

small wolf
#

I have this in my config file, too

#
  broker: core-mosquitto
  username: xyz
  password: 123
  discovery: true
  discovery_prefix: homeassistant
  birth_message:
    topic: 'hass/status'
    payload: 'online'
    qos: 0
    retain: false```
hollow bramble
#

broker is supposed to be an ip address

small wolf
#

weird, I had it as core-mosquitto there and the addon-config (I guess from the guides?), but it was working fine for my Ring MQTT integration

#

it seems to be reading the topic now

#

let me check the sensor

#

seems to be working now, thank you!

#

Is there a way to further separate the data? Right now, my single sensor shows: Aircraft:8 Position:8 Msg/s:64. I'd like to separate each into it's own sensor so I can graph them.

buoyant pine
#

Make three sensors that refer to that sensor's state with .split(' ')[0] at the end (use 1 and 2 for the other two sensors)

small wolf
#

hmmm...this is weird. It was working fine for a while and now it hasn't updated in 15 minutes

#

it was updating once every 10 seconds

#

I should probably move this to another channel since this is getting out of templating. Which channel is best to discuss MQTT issues?

brisk temple
#

Can someone take a look at this and explain to me why my script isn't restarting? After 10 minutes the light goes off

#

I've confirmed the fibaro is sensing motion during the 10 minutes, going from off to on

brisk temple
#

I had to put restart in the automation as well, not sure why it felt it was still running as the delay was in the script

inner mesa
#

calling a script as you did now waits for the script to complete before returning to the automation

#

if you call it like this:

#
    - entity_id: script.nightlight
      service: script.turn_on
#

it will go run it separately and immediately return to process the next part of the sequence/action

#

@brisk temple

brisk temple
#

Ah, I saw that piece in the script page, thanks for the explanation

inner mesa
#

I believe the behavior of service: script.xxx changed with the latest additions

brisk temple
#

The bug fix, broke my work around hah

inner mesa
#

yeah, I had some like that as well. I started out by going through all my scripts and automations and transforming them to the new "parallel" version, and then I realized that I actually rely on the sequence in some cases 🙂

#

I have to say that everything is quite speedy now. Faster than it was before

buoyant pine
#

except startup. since the changes to startup i've seen slower overall startup times (but the frontend is available more quickly than before)

#

around 0.111 or so i saw 20 second startup times

#

35 seconds now. not really an issue though lol

inner mesa
#

the improvements came about the same time I moved to the OZW Beta, so it's practically light speed now

#

I wouldn't notice 10s here or there, it was the 3-4mins that I'm glad is gone

cerulean cipher
#

my startup times still take awhile but are MUCH faster

#

but that's my own fault for being on a rpi

trim leaf
#

Is there a way to use a variable when trying to access an object? I feel like I am doing something stupid...this isnt working

{{ states.sensor. ~ entity_id ~ .last_changed }}```
#

ultimately where I am setting entity, im actually trying to simulate entity being passed from trigger trigger.entity_id

dreamy sinew
#

Try states.sensor.get(entity_id).last_changed

#

@trim leaf

trim leaf
#

Try states.sensor.get(entity_id).last_changed
@dreamy sinew

Unknown error rendering template

#

unfortunately no luck

dreamy sinew
#

Hmm

trim leaf
#
{{ states.sensor.get(entity_id).last_changed }}``` does this look right?
#

assuming I didnt butcher using your suggestion

dreamy sinew
#

sec, let me test something

#
{{ states[entity_id.split('.')[0]][entity_id.split('.')[1]].last_changed }}```
#

since trigger.entity_id will have the domain

#

so you'll probably want

#

@trim leaf {% set entity = trigger.entity_id.split('.') %} {{ states[entity_id[0]][entity[1]].last_changed }}

north helm
#

Hello again, Template Gods! I've got another puzzle for you. Trying to put a line break between two sensor attributes entities like this:
`

#

{{ states.sensor.tcm.attributes["name"] }}{{" \n"}}({{ states.sensor.tcm.attributes["releaseYear"] }})

#

It works just fine in the template tool, but in an entities card, it still runs together.

dreamy sinew
#

why not just do

#
{{ states.sensor.tcm.attributes["releaseYear"] }}
north helm
#

You mean just throw the CR in between the lines? Tried that (because it worked in the tool too) but same effect.

dreamy sinew
#

card might be doing things weird

north helm
#

Well, POO! The vertical spacing is what I'm trying to avoid. Any suggestions?

dreamy sinew
#

i don't use that card so no ¯_(ツ)_/¯

north helm
#

I don't need to use an Entity Card if you hve a better idea.

dreamy sinew
#

i don't really

#

my UI is very basic

north helm
#

My UI is a hot mess.

#

I know you're surprised.

#

😛

dreamy sinew
#

haha

#

most of my stuff is either automation or voice commands

#

i'm the only one who looks at the ui

north helm
#

Me too. That's why I try to get fancy.

#

Oh well. I appreciate you trying.

dreamy sinew
#

typical templates, i got you. UI stuff is its own beast

#

iirc that card re-implements jinja2 in JS and they do their own thing

north helm
#

Since the last time I was here, I've come to LOVE the template tool.

dreamy sinew
#

the template tool is pretty awesome

#

i use it to test some things for my day job

north helm
#

Remind me your day job? Wasn't it you who did an integration with Cherwell?

dreamy sinew
#

because of HA i added template support to my project

#

heh my company did. i looked at it though

#

i wrote our SNOW integration

north helm
dreamy sinew
#

+1

real mauve
#

Hey Everyone - new to the server. Trying to configure my first template for a GoControl WAPIRZ-1, and ive been struggling with getting it to function all night - here is what my template looks like: binary_sensor: - platform: template sensors: garage_motion: friendly_name: "Garage Motion" device_class: motion entity_id: sensor.garage_motion_alarm_level value_template: '{{ is_state("sensor.garage_motion_sensor_alarm_level", "255") }}'

inner mesa
#

Your indentation is not consistent. 2 spaces, always

#

What’s not working?

real mauve
#

@inner mesa thanks, ill fix that. The sensors is just constantly showing motion detected in the UI

inner mesa
#

So the sensor itself is reporting unexpected values or the template sensor is?

real mauve
#

wait... its working now! only thing missing is the LED light on the sensor doesn't come on when motion is detected

#

it was the template sensor that was misbehaving

inner mesa
#

And not anymore

real mauve
#

yeah, seems to be working now, just a 3 min delay clearing motion detected

#

which others have said can happen with this sensor + home assistant

inner mesa
#

Those are probably device parameters

real mauve
#

is that something that can be adjusted?

#

within ha

inner mesa
#

Or maybe not. I know nothing about that device

real mauve
#

yeah, its old and was cheap - not too worried

#

just moving things off smartthings to retire that hub

trim leaf
#

@trim leaf {% set entity = trigger.entity_id.split('.') %} {{ states[entity_id[0]][entity[1]].last_changed }}
@dreamy sinew this works! it seems like we can just avoid splitting at all and doing somethign like this. The square brackets are key, im not totally sure what that syntax means but ill be reading up on it.

{{ states[entity_id].last_changed }}

I am puzzled as to why theres no need to put a . after states though. Either way thanks so much for your help!

charred dagger
#

a[b] is pretty much the same thing as a.b with the benefit that b can be a variable in the former.

#

The square brackets are a lookup, e.g. a[0] will get the first element of the list a ("zero indexed" - the element with 0 offset from the start), a[1] will get the second element etc.
a["hello"] will get the element designated "hello" from the object a.

ivory delta
#

Also, don't forget the cases where you must use the square brackets. HA doesn't like things that start with numbers like sensor.1234. In that case, you have to use sensor['1234'].

trim leaf
#

I see, thats where I was getting lost, why square brackets were necessary where normally I could just use the var name without any syntax

#

Why do I not have to include a . between sensor and ['111']

#

ohhhh because its an object...got it got it

ivory delta
#

👍

trim leaf
#

what kills me is lsat night I realized I dont need to specifcally do this because I can use the trigger to/from_state object. That being said this is still great learning of Jinja

ivory delta
#

If you ignore thomas's examples with indexes (a[1]), the rest are all just saying 'from object x, get the value of key y'.
So x.y and x['y'] are equivalent.

trim leaf
#

that makes total sense, and in this specific usecase the bracket notation actually works when i am trying to concat a object together from vars

ivory delta
#

You're technically not concatenating anything. You have a whole object already, you just want to access something by reference instead of knowing the name in advance.

trim leaf
#

Right got it, what is the technical reason why this:

{{ states.sensor.entity_id.last_changed }}``` 
 does not work, but 

{% set entity_id = "master_bedroom_thermostat_hvac_action" %}
{{ states.sensor[entity_id].last_changed }}

does work
ivory delta
#

Imagine you have an object like this:

myObject:
  foo: 'bar'
  fizz: 'buzz'```
`myObject['foo']` would be 'bar'
#

Now let's say you don't know what thing you're looking for until later. So you ask it to look for myObject[x] (important: no quotes around the x). x is a variable now, not a string.

#

If at the time it evaluates that, x = foo, then myObject[x] = 'bar'.

#

Likewise, if x was 'fizz', myObject[x] would have been 'buzz'.

#

In your examples... sensor.entity_id is equivalent to sensor['entity_id']. You're telling it to look for the key called entity_id, not for whatever the variable entity_id would be.

trim leaf
#

would you expect sensor.entity_id to work?

ivory delta
#

Not unless you have a sensor called sensor.entity_id...

dreamy sinew
#

Nope

trim leaf
#

yeah okay got it

ivory delta
#

You want to substitute that value and find the real name.

trim leaf
#

got it

#

i have arrived, im here with you guys now 😛

#

thanks to everyone

charred dagger
#

I was technically incorrect, by the way. As Mono said, a.b is equal to a["b"] with quotes, not a[b].

slate ermine
#

Does anyone happen to have an "Average Power Usage per Day" calculation template? 🙂

silent barnBOT
small wolf
#

I'm trying to have an icon changed based on the state of something. I have an MQTT device that sends either 1 or 0 if the device is running or not running. I've tried several different things, but I can't get it change icons like a light would if it were on or off. Any advice?

mighty ledge
#

@small wolf is it a binary_sensor?

small wolf
#

i've tried creating both ways

#

i've setup button-card and got it to do what I wanted

mighty ledge
#

@small wolf binary_sensor was the way to go and customize it with a device_class of your choice. If you wanted custom icon's not available under device_class, then you'd have to go about it a different way

small wolf
#

@mighty ledge I tried that, but I can't seem to get it to work. The devices show 'off' regardless if the input is 1 or 0.

#
  - platform: mqtt
    name: "READSB"
    state_topic: "xyz/123/ADSB"
    value_template: "{{ value_json.readsb }}"
    
binary_sensor:
  - platform: template
    sensors:
      readsb2:
        friendly_name: "READSB2"
        value_template: "{{ states('sensor.READSB') }}"
        device_class: power```
mighty ledge
#

well yeah, you didn't specify what makes it on or off.

        value_template: "{{ states('sensor.readsb') == '1' }}"
small wolf
#

oh 😅

mighty ledge
#

for what it's worth, you should have been able to just add device_class through customization on sensor.readsb without creating the second sensor

small wolf
#

oh ok

lapis quarry
#

Hey guys, I would like to store the time and date of an event in a input_text or input_date and compare it to actual time using the time sensor to know how much time has passed from one event compared to the current time. Been playing around in the template editor for the last few days but I cant seem to figure out how to write the template.

#

I have these 3 variables:

{{states('sensor.date_time')}}           (Outputs 2020-08-11, 21:55)
{{states('input_text.motionlr01a')}}     (Outputs 2020-08-11, 21:55)
{{states('input_datetime.motionlr01a')}} (Outputs 2020-08-11 21:55:06)
#

how can I substract one from another to get the time elapsed betwen them?

#

this is what im trying but doesnt seem to work:

"{{ ( as_timestamp(strptime(states('sensor.date_time'), '%Y/%m/%d %H:%M:%S')) - as_timestamp(strptime(states('input_datetime.motionlr01a'), '%Y/%m/%d %H:%M:%S')) ) }}"
dreamy sinew
#

try as_timestamp(states('sensor.date_time'))|float in the template tester and see what comes out

lapis quarry
#
{{as_timestamp(states('sensor.date_time'))|float}} - Outputs: 0

{{ ( as_timestamp(states('sensor.date_time'))|float - as_timestamp(strptime(states('input_datetime.motionlr01a'), '%Y/%m/%d %H:%M:%S')) ) }}
 Outputs: -1597168506.0
brisk temple
#

try using as_timestamp(now()) instead of sensor.date_time

#

(I also get 0 on as_timestamp(states('sensor.date_time'))

lapis quarry
#

i want to use the result as a trigger so i need it to be evaluated regularly

#

that is why im trying to use the time sensor

brisk temple
#

can't do it on a state change of one of hte input_text?

lapis quarry
#

no

#

im using the input text to store the time of an event, I want that time to be stored permanently and something else to trigger X amount of time after this event occurred, the reason to store it like this its so it trigger regardless of any HA reboot there has been in betwen

brisk temple
#

as_timestamp(states('sensor.date_time_iso')) seems to work

#

though the times are different than now()

#

slightly off i should say

lapis quarry
#

doesnt work for me, output is: none

brisk temple
lapis quarry
#

yes

brisk temple
#

paste your automation?

lapis quarry
#

have none, just playing with the template editor

brisk temple
#

what are you triggering then

lapis quarry
#

its to rewrite an automation im using For: hours to trigger something, but first i need to figure this out..

brisk temple
#

seems like you want to trigger on a motion detection? and see how much time since that motion was last detected?

lapis quarry
#

yes in this scenario yes, I just want it reliable betwen HA reboots

#

want to store when motion was last detected, and even if i reboot HA still have that time stored so I can still trigger something X amount of time later

#

I also need it for another automation I want to trigger 3 days after an event has been detected

#

and I can be rebooting HA dozens of times in 3 days 😅

brisk temple
#

you ain't lyin

#

you can do a time_pattern to check every x second/minutes if your condition value is the time you want

lapis quarry
#

yes I saw I could do that also

brisk temple
#

to keep time across reboots

#

then on timer stop, execute what i want, it won't do over 24hrs though

#

n/m, he updated it to do over 24hrs

lapis quarry
#

interesting

#

never used timers

#

was using For in my automations to count time

#

but this might make more sense, specially with what you just sent

#

thans PoPBox, I will give this a try, looks promissing, can a timer be used as a condition in a automation?

inner mesa
#

any entity can

ivory delta
#

With timers, you care about when they start/end/restart/cancel.

#

You can use those as triggers easily enough.

lapis quarry
#

ok i need to give this a good thought as it means a big rewrite in a lot of code and I will brake many things along the way

#

regardless, would still like to figure my previous issue out, if anybody can point me in the right direction as to what im doing wrong and how to get that to work I would apreciate, this:

#

this is what im trying but doesnt seem to work:

"{{ ( as_timestamp(strptime(states('sensor.date_time'), '%Y/%m/%d %H:%M:%S')) - as_timestamp(strptime(states('input_datetime.motionlr01a'), '%Y/%m/%d %H:%M:%S')) ) }}"

@lapis quarry

#

need to go to bed, will be back tomorow, thanks so much!!

keen stag
#

Syntax question with Templates. In the link below I have 2 examples of what I am trying to accomplish. Basically, I have a value in a sensor, and I want to math it into another value.

Top half of the example, have a value in hours in one sensor, and I want to make another sensor for the same value but in days. What I have is showing as invalid currently.

Bottom half of the example, I have a value for Total Memory of a machine, and Used Memory for a machine. Looking to do Total / Used * 100 = Percentage. What I have there is not working either, also invalid.

Can anyone take a look and tell me what I am doing wrong?

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

hollow bramble
#

you're referencing a sensor that doesn't exist

bronze sandal
#

Not as much of an expert in the syntax as others here, but shouldn't used % be used / total?

hollow bramble
#

and you're multiplying hours by 7 to get days (?)

keen stag
#

divide by 7, oops

hollow bramble
#

still not right

bronze sandal
#

divide by 24

#

24 hours in a day

hollow bramble
#

there aren't 7 hours in a day

keen stag
#

this Math is hard

#

Its been a long day

bronze sandal
#

7 hours is a pretty short day

keen stag
#

lol, math aside, @hollow bramble, using sensor that doesn't exist?

hollow bramble
#

you defined the template sensor as plex_vm_uptime_hours but you're trying to get the state of sensor.plex_uptime_hours

keen stag
#

🤦 I see

#

Second example I did not make that same mistake it seems though, right?

hollow bramble
#

well you're missing the actual states function in the last template

lapis quarry
hollow bramble
#

you just wrapped sensor names in parentheses without the function and without quotes

#

@lapis quarry you can do it either way

lapis quarry
#

👍

keen stag
#

You lost me lol. Am I missing the "|int" thing?

hollow bramble
#

you've written (sensor.plex_vm_memory_used_mb) instead of states('sensor.plex_vm_memory_used_mb')

#

actually, the same with your other template as well

#

the only ones you have correct are your state_attr templates

keen stag
#

🤕

#

I am still missing something

hollow bramble
#

post what you have now

keen stag
#

I am missing the ' '

hollow bramble
#

yes, and | int goes on the outside of the function

keen stag
#

value_template: "{{ (states('sensor.plex_vm_uptime_hours')|int) *24)|round(1) }}"
Right?

hollow bramble
#

Check your parentheses

keen stag
#

value_template: "{{ ((states('sensor.plex_vm_uptime_hours')|int) *24)|round(1) }}"

#

Got it

#

Quite honestly, I am not even sure why I have the |int there at all

#

I have learned today that I was not meant to script or code lol

hollow bramble
#

{{ states('sensor.plex_vm_uptime_hours')|int * 24|round(1) }} you can also just lose the logic-only parentheses. Your order of operations is linear

#

| int is necessary to be able to do math with it. Otherwise it will be a string

charred dagger
#

All states are strings, so in order to perform calculations with it, you need to convert it to a number via |int or |float.

keen stag
#

Thats what I was thinking. Integer

#

Okay. Giving that a shot

hollow bramble
#

I hope you're testing your templates before restarting home assistant 😉

keen stag
#

lolz

#

Didnt know that was a thing 🤦

hollow bramble
#

devtools > Template

#

paste a template in there and it will give you the rendered value

keen stag
#

Oh, I did know that. Dont know why I havent been using this lol

#

That seems like a success. But it is telling me 1632 Days online, and I know for a fact its been like 2

#

/24, not *24

#

Nailed it

#

Thank you all!!

brisk temple
#

{{ states('sensor.blah') is string}} is my go to

north acorn
#

Crosspost from automations, since I think I'll need a template for this:

anyone can help me with the following:
I want to create a 'wait untill' automation, where a source_list is the variable. In this case I use node red, but a HA automation is also welcome.

Use case: I use Spotify Connect on my PS4. I'm building an automation where I want to continue Spotify on my PS4 once that is turned on. However, it takes a while untill the PS4 becomes an available source on the Spotify media player. This causes the automation right now to be incosistent. I figured: what if I can create a 'wait until' node. So once the PS4 is available in the source list, it should fire the action.
I tried with Node Red, but I can't get it to work with the 'wait until' node. Most likely since it's a list and JSON isnt my strong suit, so I don't know what to use there

violet oyster
#

@north acorn

wait_template: "{{ "SpongeBobburu's PS4" in states.media_player.spotify.attributes.source_list }}"
#

just add that in the HA automation before the action to select source and play

little gale
#

What would a template look like that counts how many device_tracker entities are home?
I've tried this
{{ states | selectattr('entity_id','in', ['device_tracker'])|selectattr('state','eq','home') | list | count }}

small wolf
#

I'm using MQTT to report the status of a device. It sends "1" for healthy and "0" for unhealth. The problem is that the device needs to send the health. If I disconnect the device, the sensor I created in HA will keep the last known status (healthy) even if the server is disconnected. Is there a way to force a sensor to change state if it hasn't updated in X time?

violet oyster
#

@small wolf just change the template to include an unavailable state also

#

oh i see what you mean now

small wolf
#

I think I may have figured it out - testing now

violet oyster
#

i do something kind of janky that may work for you. start/restart a timer when the mqtt message publishes then change the template to say if the timer is over X time it is unavailable

small wolf
#

I just added expire_after: 10 to my MQTT sensor. That seemed to do the trick.

north acorn
#

@north acorn

wait_template: "{{ "SpongeBobburu's PS4" in states.media_player.spotify.attributes.source_list }}"

@violet oyster Thanks alot! Is it also possible to inject this into Node-RED?

violet oyster
#

no clue unfortunately. I don't use it. but itll work for HA

north acorn
#

that's fine, I'll just link something from Node-RED to kick in the automation in HA

violet oyster
#

that works too

tender prawn
#

what is wrong with this?

#
      cc18323:
        entity_id: 
          - sensor.caltex_gosford_west_pdl
        value_template: "{{states('sensor.caltex_gosford_west_pdl')}}"
        friendly_name_template: >
          {%- if state_attr('sensor.caltex_gosford_west_pdl', 'station_id') == 18323 -%}
            {{ Caltex 283 Manns Rd West Gosford }}
          {% elif state_attr('sensor.caltex_gosford_west_pdl', 'station_id') == 874 -%}
            {{ Caltex 30A Pacific Hwy West Gosford (From Gosford) }}
          {% else %}
            {{ Caltex 69-71 Pacific Hwy Gosford West (To Gosford) }}
          {% endif %}
        unit_of_measurement: ¢/L
#

nvm... don't need the {{ }}

stone siren
#

entity_id: timer.geschirrspueler
duration: "11000" -> works

#

entity_id: timer.geschirrspueler
duration: "{{ states('sensor.siemens_sn678x36te_remaining') | int }}" -> doesn't

#

or | float

#

tinkerer... can't find your answer anymore... regardin #1

buoyant pine
#

You have to use data_template: instead of data: when using templates. You can't use templates at developer tools > services (that field is data:)

stone siren
#

so in template editor i get a value... but when I want to use it as service data it doesn't work...

#

oooh.... i'll check

#

like this:
data_template:
duration: '{{ states("sensor.siemens_sn678x36te_remaining")|int }}'

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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

buoyant pine
#

Assuming the indentation is right, yes. You still won't be able to use that at developer tools > services though

stone siren
#
data_template:
  duration: '{{ states("sensor.siemens_sn678x36te_remaining")|int }}'
#

thanks 🙂

#

hmmm... then i get "extra keys not allowed @ data['data_template']

#

looks like I am still in data mode... when testing it in the development area under services....

violet oyster
#

development area doesnt take templates

stone siren
#

oh... but the syntax is right when using in automations?

buoyant pine
#

Looks fine

stone siren
#

I get the same error meesage under LOGS when I try to run the automation.... extra keys not allowed @ data['data_template']

#

it looks like service data under automations isn't allowing templates as well??

#

back to automations.yaml?

#

aaaah..... 🙂 now it is working!

#

perhaps a toggle switch would be nice, so that you can use the UI for creating automations and even test... to swtich between data and data_template?

frank tulip
#

I'm sending config topic to the MQTT broker with this payload:

{"name": "Shelly 1 87AA4499 Uptime", "stat_t": "~info", "exp_aft": 43200, "frc_upd": "False", "uniq_id": "shelly1-87aa4499-uptime", "qos": 1, "dev": {"ids": ["87aa4499"], "name": "Shelly 1 87AA4499", "mdl": "Shelly 1", "sw": "20190821-094851/v1.8.0@4148d2b7", "mf": "Allterco Robotics"}, "~": "shellies/shelly1-87AA4499/", "dev_cla": "timestamp", "avty_t": "~online", "pl_avail": "true", "pl_not_avail": "false", "val_tpl": "{{(as_timestamp(now())-value_json.uptime)|timestamp_local}}"}

Created sensor should show human-readable date, but shows timestamp. What is wrong with my template?

#

value_json.uptime is in seconds.

mighty ledge
#

is uptime an integer or a string

frank tulip
#

integer

#

Funny thing, when I configure this sensor manually (via YAML), the sensor displays the date correctly. The problem is with discovery.

daring musk
#

always use data: even if no templating

#

will help in the future

dreamy sinew
#

that will not work with templates

mighty ledge
#

@daring musk that is 100% incorrect.

daring musk
#

that will not work with templates
phnx is right, this statement is wrong for templates channel tho

ivory delta
#

Is there anywhere that data: is compulsory even if there are no contents?

mighty ledge
#

no, that would be invalid yaml typically

daring musk
#

i didn't know sorry 😬

brisk temple
#

there another way to write this without the two ifs?

#
                {%- for state in states.input_datetime -%}
                  {%- if not 'End' in state.name  %}
                    {%- if not 'Start' in state.name %}
                      {{ state.name }}: **{{ state.state }}**
                    {%- endif %}
                  {%- endif %}
                {%- endfor %}```
dreamy sinew
#

if not state.name in ['End', 'Start']

brisk temple
#

thanks!

vital pivot
dapper bridge
#

In a template am I able to find out what platform an entity Id belongs to?

ivory delta
#

Alternatively, just read the bit of the entity ID before the .. I.e. light.bedroom_light belongs to the light platform.

#

Should be able to split on . in Jinja easily enough.

dapper bridge
#

Isn't that the domain not the platform? What I'm trying to do is is create a "Dim If On" script that will loop through the entities in a light.group and if the entity is a single light I want to dim it if on (that I've already created) but if it's a light.group it needs to iterate into all it'sa entity Ids

#

so I need to know if a given entity id is a light.group as opposed to a light.zha etc

ivory delta
#

I thought a light.group's platform was still light. The integration is different but the platform is the same.

dapper bridge
#

I guess I might be able to check if the passed in light has the list of entity_ids that a light.group has

charred dagger
#

There's no way to know which integration created an entity, which I guess is what you want. But for the group stuff, looking for entity_ids kind of works.

dapper bridge
#

yeah thanks. What I'm ultimately trying to do is to create an asymmetric light to use with Alexa. If I say "turn off downstairs" all downstairs lights need to turn off. However if I say "turn on" I only want a small subset to turn on. Then if I want to dim lights I only want to dim the ones I have on

charred dagger
#

There's no guarantee that no other integrations will add the entity_ids property to their entities, though.

dapper bridge
#

I could create a PR to add something like hue does...
is_hue_group: true

#

I guess the other option is naming convention in my config make them all end in "_group"

charred dagger
#

Or adding a property attribute manually with customize.

dapper bridge
#

interesting - never really used those - I'll check them out - thanks

charred dagger
dapper bridge
#

ooo interesting

jagged obsidian
#

oooooooooooooo very interesting

dapper bridge
#

I'm trying to find an example how I can call the following Jinja (enriched with my own comments) from a script.

{% for state in state_attr('light.all_downstairs_lights', 'entity_id') %}
  {% if state_attr(state, 'entity_id') == None %}
    Call light.turn_on with entity_id from state and a brightness
  {% else %}
    Call script.dim_group_if_on with entity_id from state and a brightness
  {% endif %}
{% endfor %}
#

(this snippet would be inside script.dim_group_if_on so the else would be a recursive call)

#

actually scratch that - it isn't light.turn_on I want but my own script so if they are both a script it should be easy using script.turn_on

#

oh not that easy actually as I need to do...

sequence:
 - data_template:
     dim_amount: '{{ dim_amount }}'
     entity_id_to_dim: the entity we pulled out of entity_ids
     entity_id: <EITHER script.dim_group_if_on OR script.dim_light_if_on> depending on entity_id_to_dim
   service: script.turn_on
#

IS there a way to store a variable in entity_id_to_dim and use it later in a for loop in the same script?

ivory delta
#

Can't you use the new choose option to make that easier to read?

#

Don't try to put all the logic in the templates, move some out to the flow of the script instead.

dapper bridge
#

true I should be able to do that

mighty ledge
#

@dapper bridge should just be able to expand it {{ expand('light.all_downstairs_lights') | map(attribute='entity_id') | list | join(', ') }} and just use that in a few places. If you make it into a stand alone script, you can even pass 'light.all_downstairs_lights' as a variable.

dapper bridge
#

the expand didn't work on the light group it seemed to return light.all_downstairs_lights

#

Just tried in template editor and it returns "light.all_downstairs_lights"

mighty ledge
#

ok then change it to {{ states.light | selectattr('entity_id','in', state_attr('light.all_downstairs_lights', 'entity_id')) | map(attribute='entity_id') | list | join(', ') }}

#

had to edit, missed a )

dapper bridge
#

thanks - that works and gives me a comma separated list but not sure what I can do with that over the list of entity IDs I already have. would seem the list is more useful for then calling another script with the entity id?

mighty ledge
#

if you place that comma separated list into the entity_id inside data_template for a service, it will enact that on all lights included in said list

#

what exactly are you trying to do

#

end goal, not the gibberish you posted above

dapper bridge
#

Which bit is gibberish and i'll expand...
What I'm ultimately trying to do is to create an asymmetric light to use with Alexa. If I say "turn off downstairs" all downstairs lights need to turn off. However if I say "turn on" I only want a small subset to turn on. Then if I want to dim lights I only want to dim the ones I have on

#

The dim bit is the bit i'm working on

#

I have light.all_downstrairs_lights which is a light group that has 4 other light groups and a single light in it. E.g. light.kitchen_group, light.living_room,group, light.toilet, light.hallway_group

#

I've got a script called "script.dim_if_on" that takes a entitiy_id_to_dim and a dimming_amount. So I just need to call that with all the individuals lights I have downstairs

mighty ledge
#

Ok, then all you need for the dim the lights that are on:

- service: light.turn_on
  data_template:
    entity_id: >
      {% set lights = state_attr('light.all_downstairs_lights', 'entity_id') %}
      {{ states.light | selectattr('entity_id','in', lights) | selectattr('state','eq','on') | map(attribute='entity_id') | list | join(', ') }}
    brightness: 20 # Change this to whatever you want here.
#

as for the the other stuff via alexa, I belive you're going to have a hard time getting that to work. Alexa is the problem there

#

turning on a subset without a keyword in alexa is pretty much impossible.

dapper bridge
#

I'm using a light.template for that

mighty ledge
#

unless you break it up into rooms or sets yourself

dapper bridge
#

with an on script, off script and dimming script

#

so I have a light.downstairs_template_light but instead of listing out all the lights i'm trying to use it on light.group to make it easier. Then it will hopefully just be a case of changing the group

#

if I add new lights

mighty ledge
#

yep, then all you need is the service I just provided

#

you just need to come up with how you dim it

#

but that entity_id list will only produce lights that are on. Filtering out the ones that are off

#

You'll have to copy/paste the code in different areas for the light template though. Can't use a variable for that unfortunately.

dapper bridge
#

I think I still need a way to distinguish actual lights vs light groups

mighty ledge
#

why

#

if they appear in the list yes. Just add the reject filter

dapper bridge
#

if I call light.turn_on with a brightness on a group it will turn all of the lights on

#

damn this is trickier than I hoped!

mighty ledge
#

well, it would only do that if you nested your light groups...

dapper bridge
#

yeah I do :S

#

the kitchen has 5 lights so there is a light.kitchen_group

#

and to avoid repition the "all_downstairs" uses the groups

#

I might just put this into app daemon or node red where I think it will be easier

#

just preferred to rely on something in core home assistant

mighty ledge
#
      {% set lights = state_attr('light.all_downstairs_lights', 'entity_id') %}
      {{ states.light | selectattr('entity_id','in', lights) | rejectattr('attributes.entity_id', 'defined') | selectattr('state','eq','on') | map(attribute='entity_id') | list | join(', ') }}
#

that will reject light groups

#

but if you want it to recursively search into your light groups, then you need to use expand with groups. Or add a feature request to have expand work on light groups.

#

I understand you may not want to 'duplicate your efforts' but doing this will be painful in general with the configuration. You'd be better off using yaml anchors which does the duplication for you. And then just use easy templates.

dapper bridge
#

what do you mean by yaml anchors?

mighty ledge
#

a yaml anchor allows you to duplicate entries or combine things in yaml.

dapper bridge
#

ah ok - do you know how to make expand work on a component?

#

at a high level that is

mighty ledge
#

you'd have to add it to the core functionality by modifying HA code

#

or fork HA and make your own version with that change

#

either way, nothing easy.

#

This macro should recursively search light groups and return a list of lights without the group itself

#

try it out with light.downstairs. Ihaven't tested the code

charred dagger
#

Maybe this is really a python_script problem?

mighty ledge
#

{{ light_expand('light.all_downstairs_lights') }}

#

yeah, that would solve it too because it doesn't need any imports

#

TBH, making expand work on light groups would be nice. But Might get into a 'political debate' if people don't want it to expand light groups.

dapper bridge
#

that macro killed HA

#

although could easily happen if I've messed up and have a recursive light group... don't think I have but not tried this so far

mighty ledge
#

well it would break with that

#

it does not have a recursion limit