#templates-archived

1 messages ยท Page 112 of 1

mighty ledge
#

@royal rampart you have vastly different hardware than most

royal rampart
#

yes, I decided to waste a bunch of cash paying someone to install stuff I probably could have built myself for the convenience of having it done before the plaster went on the wall - I both regret and don't regret this at the same time

mighty ledge
#

what devices are these?

#

what integration gets them into HA?

royal rampart
#

dynalite switches and apparently fan controllers

royal rampart
amber zodiac
#

I have been using now().day in a dynamic link of a website. But the link needs 0 padding for 1-9 of the month like 01, 02, 03 rather than 1, 2, 3. now().day doesn't have padding. How do i add it?
i tried {{ now().strftime(โ€™%dโ€™) }} but its only outputting 01 everytime

inner mesa
#

It says 03 for me, which is correct

amber zodiac
#

my rpi instance date is wrong i guess? how do i correct it. it says 01 for me . just checked again

inner mesa
#

What does now() say?

#

It uses NTP, so if the day is wrong like that, itโ€™s probably your network

amber zodiac
inner mesa
#

๐Ÿคทโ€โ™‚๏ธ

#

Thatโ€™s not correct anywhere in the world, so youโ€™ve evidently invented a time machine

amber zodiac
#

Thanks . i will file a patent soon after i fix the problem๐Ÿ˜ƒ . how do i fix time?

inner mesa
#

๐Ÿคทโ€โ™‚๏ธ

grim flicker
#

I did that but its giving me the error Logger:ย homeassistant.config Source:ย config.py:415 First occurred:ย 3 december 2020 19:25:44ย (9ย occurrences) Last logged:ย 9:52:52 Invalid config for [automation]: Unexpected value for condition: 'None'. Expected numeric_state, state, sun, template, time, zone, and, or, not, device @ data['condition'][0]. Got None. (See /config/configuration.yaml, line 11).

deft timber
#

Something like that should be sufficient:

  condition: "{{ is_state_attr('media_player.android_tv', 'app_name', 'Netflix') }}"
#

@amber zodiac , with smth like date --set="Fri Dec 04 10:25:59 CET 2020"

#

depending on the machine your HA is running on of course

grim flicker
#

I think i dont need to use value template i guess

#

not really sure how to clean up my code

#

it says that the output is none. and that could be the case. if i look at te attributes when google tv is off then this attribute isnt active. it becomes active when google tv is on. Not really sure if this has something to do with it?

deft timber
#

yep you wrote "{% ... %}" instead of "{{ ... }}"

#

{% .. %} is for if, else, endif, and other logic statements. {{...}} is to actually returns something. Here you want to return the result of the is_state so you need to use {{ }}

grim flicker
#

oops my bad... i knew that but didnt see it. but with the {{ }} it gives the same error

deft timber
#

It is condition: "{{ is_state_attr('media_player.android_tv', 'app_name', 'Netflix') }}"

#

and not ```
condition:

  • condition: "{{ is_state_attr('media_player.android_tv', 'app_name', 'Netflix') }}"```
#

If I'm not mistaking

grim flicker
#

YES! that seems to work thanks a bunch! there are allot of forum posts with incorrect examples ๐Ÿ˜…

amber zodiac
#

I just checked log and I see this error 3 times in 5 seconds
2020-12-01 21:35:53 WARNING (MainThread) [homeassistant.setup] Setup of input_datetime is taking over 10 seconds.

deft timber
#
  1. i have homeassistant core, this command need to be executed on the linux machine. I have no knowledge over other installation methods
  2. CET can be replaced by your timezone (either search in internet, or get the current value with time command)
  3. maybe your ntp service is not up for some reason. It is the service having the role of getting the time from internet
#

This warning has nothing to do with your problem

amber zodiac
#

Thanks
I used the same pi ( its a rpi0 w) for a week and time was fine. Never did any commands. The only thing that changed was I upgraded core and supervisor to 2 new versions I think.
Also If NTP is not working is there a way to troubleshoot? I am asking is because I think without NTP, if my pi has a downtime due to power or reboot, it will keep lagging. right?

deft timber
#

Possible. I donโ€™t know if the rasp has a little battery to keep the time during shutdown

#

About troubleshooting ntp, of course it is possible, but not in this chat room ๐Ÿ™‚

fallen oyster
#

I'm very new to templates. I'm trying to add a condition to a webhook automation to check a query key for an auth code... I see that trigger.query is available as a template variable, but is it just {{ trigger.query.<keyname> == <authcode> }} ?

ivory delta
#

Do you know the name of the key it comes in on?

#

If so, yes... it's just like you said ๐Ÿ™‚

fallen oyster
#

I can make it whatever I want

#

also, what's the difference between {{ and {% for templates?

ivory delta
#

{{}} returns something. {%%} just evaluates something.

fallen oyster
#

ok, never used jinja before

#

thanks!

#

Awesome, got it to work how I want it to!

amber zodiac
deft timber
#

I donโ€™t have any issue on my side but thanks for the info ๐Ÿ˜‰

solar sluice
#

hi. Im wondering how these templates are working. I really dont seem to get it. I made a mqtt sensor that reads my battery voltage. Sensor outputs milliVolts and i'd like to get it as volts. How would i suppose to do this? I understand that it might be possible with templates.

ivory delta
#

You'd multiply by 1000

#

{{ something x 1000 }} - I don't know what your something is.

solar sluice
ivory delta
#

And you likely need to cast it from a string to an int/float (number types).

solar sluice
#

variable_name / 1000. in that example template, in configuration? i mean developer tools.

ivory delta
#

Well if you're already using an MQTT sensor, you can include a value_template to do the math for you.

#

You probably just want {{ value | float / 1000 }}, where value is a variable that HA already has access to in that sensor.

#

The | float pipe is just to ensure that if you're given a string '5', it turns it into the number 5.

solar sluice
#

yes, that value_template is baffeling me, are those (for example) value_json.RSSI in that link something that is already in hassio or do i need to make it myself?

ivory delta
#

value is whatever was sent on that topic in MQTT.

#

value_json is the same thing parsed from JSON to an in-memory object.

#

If what you shared in your paste works to display mV, you just need what I said... value_template: "{{ value | float / 1000 }}" will do the trick.

solar sluice
#

ok, just value would be enough? I'v tried to use sensor.name etc.. as the value. ๐Ÿ™‚

ivory delta
#

value is a variable...

#

Do you understand any programming?

solar sluice
#

yes i do, multiple languages ๐Ÿ˜„ understanding this is somehow hard for me.

#

just as a small time hobby, and i know also good deal about electricity ๐Ÿ˜„ i just feel so dumb with hassio alltogether.

ivory delta
#

Think of it like JavaScript... you might have var data;. Then something else does data = 'hi'. Now you can ask for data and it equals 'hi'.

#

Same thing with that value variable. Something else that you don't see assigns a value to it. You don't need to know where it came from, only where to find it.

solar sluice
#

yes. ๐Ÿ™‚

#

would i need to restart hassio from server control, every time i modify configuration.yaml ?

ivory delta
#

Depends what you're changing. Integrations, yes. Lots of other stuff, no.

solar sluice
#

wow. it actually worked ๐Ÿ™‚

ivory delta
#

If you see a button to reload it under server controls, a restart isn't necessary.

solar sluice
#

thank you.

ivory delta
#

No problem

solar sluice
#

what is that bottom part, some addon? i only got server managment.

ivory delta
#

Maybe you need advanced mode on for that ๐Ÿ˜„ It's not an add-on.

solar sluice
#

ok, where could i find advancd mode?

#

found it.

#

๐Ÿ™‚

narrow surge
#

I want to make a condition that checks if a certain light has a certain rgb:
{{ is_state_attr('light._bedroom__bed', 'rgb_color', [255,159,39]) }}
When I check the entity of the light it is in this RGB mode:

rgb color
255, 159, 39

Any idea why the condition reports false?

mighty ledge
#

Use ==

narrow surge
#

{{ is_state_attr('light.bedroom_bed' , 'rgb_color' , (255, 159, 39)) }}

#

I am guessing

ivory delta
#

Or do what petro just suggested...

#

{{ state_attr('light._bedroom__bed', 'rgb_color') == [255,159,39] }}

#

If is_state_attr performs strict equality checking, the two lists you were comparing weren't the same.

narrow surge
#

Somehow that returned a false while mine returned a true

ivory delta
#

Then why 'I am guessing' if you'd already confirmed it? ๐Ÿค”

narrow surge
#

Yeh edited my query later on, but it didn't work, but had to refresh the page, sorry ๐Ÿ˜ฆ

spring path
#

I have a doorsensor, so it's a binary_sensor. I want the state to be different the 'stock'
Normal, because it's a device_class: door, the states are Open and Closed.
I want it to be 'Geopend' or 'Gesloten, but can't get it to work..

platform: template
sensors:
terrasdeur_status:
entity_id: binary_sensor.terrasdeuren
value_template: >-
{% if states.binary_sensor.terrasdeuren.state == 'off' %}
Gesloten
{% elif states.binary_sensor.terrasdeuren.state == 'on' %}
Geopend
{% else %}
n/a
{% endif %}

#

Also tried it with this one, but it results only in changing icons and no changed state. The state doesn't do anything at all

platform: template
sensors:

terrasdeuren_status:

friendly_name: Terrasdeuren status

entity_id: binary_sensor.terrasdeuren

value_template: "{% if is_state('binary_sensor.terrasdeuren', 'on') %}Gesloten{% else %}Geopend{% endif %}"

icon_template: "{% if is_state('binary_sensor.terrasdeuren', 'on') %}mdi:face-woman{% else %}mdi:party-popper{% endif %}"

ivory delta
#

You have to follow the standard states for sensors. If you want them to show differently in Lovelace, that's another matter.

spring path
#

so, you're saying it's not possible what i want or am i in the wrong channel?

ivory delta
#

I'm saying what you're trying is the wrong approach.

#

You only care about the language it displays the state in when it's used in the UI. For everything else, use the standard values.

#

If your UI is set to use Dutch, Lovelace should be showing the state in Dutch.

spring path
#

Don't only care about the language, this is just an example..

#

Instead of the dutch 'Geopend', can also be the case i want i to be 'Vrij' (means 'Free')..

#

or that i use this binary_sensor device for something, while there isn't a device_class for.

ivory delta
#

But you're still talking about how it's displayed. That's a Lovelace problem.

#

Internally, binary sensors are all just on/off. The device class just helps Lovelace use the right terms.

spring path
#

Ok, but how is it possible that, the state isn't changing but the icon is?

#

Also a Lovalace thing?

ivory delta
#

No. For that, you probably broke your template ๐Ÿ˜„

#

But... if you just use the normal binary sensors, everything will 'just work'.

spring path
#

The icon is changing according the right state, so that shouldn't be broken?!

ivory delta
#

The icon is changing according to a binary sensor, right?

spring path
#

Yeah, it works with the normal stuff... But don't want to use the stock part..

#

correct

ivory delta
#

Binary = on/off, 1/0, True/False, etc.

#

How can something binary understand Geopend/Gesloten/etc?

#

If you're just trying to change the language that's displayed in Lovelace, change it there.

spring path
#

value_template: "{% if is_state('binary_sensor.terrasdeuren', 'on') %}Gesloten{% else %}Geopend{% endif %}"
icon_template: "{% if is_state('binary_sensor.terrasdeuren', 'on') %}mdi:face-woman{% else %}mdi:party-popper{% endif %}"

I mean, here above it won't change to 'Gesloten' or 'Geopend', but it changes icon from 'face-woman' to 'party-popper'

#

so, there i know for sure the template-part is correctly ?!

ivory delta
#

Test the template in devtools > Templates. It works for me.

#

At least partly... I don't have that sensor, so it does the 'else' and shows me 'Geopend'.

spring path
#

it works over there, but it won't change in the Lovalace part..
Also it won't change in Developer -> states..

ivory delta
#

Well your config looks okay based on what you've said. The only other thing I can suggest is to change the template to this:
{{ 'Gesloten' if is_state('binary_sensor.terrasdeuren', 'on') else 'Geopend' }}
Functionally equivalent but only uses the {{}} block.

spring path
#

Unfortunately, the state remains 'off'

ivory delta
#

Then I'll go back to my original point for the last time. This is better handled in Lovelace. Even if a native Lovelace card doesn't support templates, you can use this custom card to allow it: https://github.com/iantrich/config-template-card

spring path
#

can you take a look at this?

ivory delta
#

Your choice what you do with it but I'm outta ideas on the backend. #frontend-archived if you want help with that.

spring path
#

in this post it works..

ivory delta
#

๐Ÿคทโ€โ™‚๏ธ

#

I've told you the easy option. Your choice if you do it or not but I'm done here. Good luck.

spring path
#

okay, thanks for the help ๐Ÿ‘

blazing burrow
#

@ivory delta is that card much different from card-templater?

mighty ledge
#

@spring path if lovelace doesn't show the correct state or icon, you're using the wrong entity_id. If the icon is correct but the state is not, clear your cache and refresh the page.

spring path
mighty ledge
amber rose
#

Ohai! ๐Ÿ™‚ I'm trying to setup a light.template with the set_color option specified so I have a color-picker. However, whenever I select a color it's not stored in the attributes of this light. When I specify set_white_value and set_temperature they both set their respective options (color_temp & white_value). Is this intended?

mighty ledge
#

@amber rose you havenโ€™t implemented any of the fields that set the light information...

amber rose
#

@mighty ledge That's correct, considering the attributes were still updating I figured it wasn't a big issue.

#

Because it looks like I can only add actions which is not really what I'm looking for

#

Mind you, I have also tried using an action to set the rgb_color using light.turn_on and the same entity_id but that wasn't setting the attributes either

mighty ledge
#

Do you understand what the template is doing for the integration?

#

Also do you understand the point of the template light integration?

amber rose
#

I think I do, yes.

mighty ledge
#

Ok, so without implementing turn_on or turn_off, how would this new light that you're creating turn on or off?

#

without implementing a color template, how would the light know what color it is?

#

without implementing set_level, how would the light know what brightness it's at?

#

or level_template for that matter

amber rose
#

Yeah I get your point, but in what I'm trying to achieve this wasn't relevant afaik

mighty ledge
#

the only thing you implemented was value_template. So your light would only show a state and have nothing else

amber rose
#

I think I try to do something hacky here

mighty ledge
#

what are you trying to do exactly

amber rose
#

Okay, here we go .. ๐Ÿ˜›

mighty ledge
#

your original post doesn't really explain it

amber rose
#

I understand ๐Ÿ™‚

#

I'm trying to create 6 different 'lights' which don't really exist, I only want to use the color-picker function to set an RGB value. The RGB value for each of those lights will then be used to add to an array that the new Lidl Christmas Tree lights support

mighty ledge
#

what does the lidl christmast tree lights integration create?

slate tundra
#

can anyone help with a template that gives true when the day is an impair number?

ivory delta
#

Impair?

amber rose
#

It's a zigbee device exposed through zigbee2mqtt, the only thing that works out of the box with HA light turn on/off, brightness and RGB for the whole led string

#

I'm using node-red to gather information on what I want to see for this led string and publish that in an mqtt topic for this light

mighty ledge
#

Yes but does it create a light? or a switch?

amber rose
#

It creates a light

ivory delta
#

Assuming you mean odd numbered days, something like this: {% if now().day % 2 == 1 %}. That would be True when the day of the week is an odd number.

slate tundra
#

it should use now().day i guess

#

yah something like this

mighty ledge
#

it creates 1 light, but you want to separate that one light into 6 lights?

slate tundra
#

that's it mono

#

thanks

amber rose
#

Yes, but only to use the RGB attributes. There are effects you can select (which are not exposed to HA but I added an input_select for that) which supports an array with 6 different RGB values to show on the strip. So I still use the original light to turn everything on and off

#

That is the actual device I'm talking about

mighty ledge
#

is there a way to access these RGB values from zigbee?

#

or HA

#

like, can you look at a topic and see these 6 rgb values?

amber rose
#

Yes

mighty ledge
#

Ok, then light template is what you want

amber rose
#

Let me pastebin it

mighty ledge
#

You need to implement a turn_on, turn_off, value_template, color_template, and set color

amber rose
#

Ok

mighty ledge
#

Your color_template should get the rgb values out of that color list

#

the format should return [r,g,b]

#

your set color will call a service that SETS that color into that topic

#

or it will call whatever function your plan to use to push the color to the device.

amber rose
#

Right

mighty ledge
#

turn on and turn off are required, so you'll have to set something up for them

#

typically, i would just create a template looking at the main entity

#

{{ is_state('light.main', 'on') }} for value_template

#

nothing else

#

turn_on should probably just turn that main light on

#

you should probably implement a level_template as well that pulls the light level from the single light

#

and set level should do the same.

#

all 6 will have the same on/off state and have the same turnon/turn off implementation

#

whenever your main light is on, those other six should also be on

amber rose
#

Is it a problem if not all of them were on? Some effects support max 3 different rgb values so my idea was to show the light is on (if it is) and if this Nth light is still usable for the rgb valus

#

For example, light 4 5 and 6 will be 'off' if I selected an effect which only supports 3 different rgb values

mighty ledge
#

only if you care

#

will that list only contain 5?

#

or 4? instead of 6?

amber rose
#

Yes

mighty ledge
#

then you'd probably want to build that into your value_template

#

and if you don't want those individual lights to actually have a turn_on/off functionality, put a dump service in them.

amber rose
#

Ah okay, yeah I might do that since my main goal is to only use the functionality to just pick a color for the led strip

mighty ledge
#

Actually

#

you're going to need to make it a scrdipt

#

script*

#

and you'll need to conditionally run the script based on the number of available items in that list

#

because the only way to set color is through the light.turn_on service

#

so you have to implement that.

#

tha'ts the only way the color picker will work

amber rose
#

Okay, that shouldn't be a problem

#

This helped a lot, thank you very much

mighty ledge
#

np

mighty ledge
#

just make it a dummy service

#

you do need a set_color service

amber rose
#

Okay

#

I'm going to cook dinner now, watch F1 so I'll probably get to this later today or tomorrow, I'll let you know when I successfully implemented it ๐Ÿ™‚

#

Also, looking back I didn't 100% understand the integration ๐Ÿ™‚

mighty ledge
umbral drift
#

Hello, I want to extract only one value out of an attribute but I don't succeed... Can someone help me please? This is an example of the attribute of my vibration sensor: "orientation: 0, 77, 13". I want to extract the third value out of it.

spring path
mighty ledge
#

The problem is that you're creating a template in the binary_sensor domian

#

binary_sensors can only be on or off

#

and the translation happens on the UI though changing your language in the main menu

#

If you want to set states that are not the same as your language, then you need to make a sensor, not a binary_sensor.

#

sensors can be set to any state

spring path
#

ah, okay..

#

pity..

#

no way to make from a binary_sensor a regular sensor ?

mighty ledge
#

instead of making a template binary_sensor, make a template sensor...

ivory delta
#

Or customise in the front-end...

#

All of this was just to get different text on the front-end.

spring path
#

Not only, also having aan Toon (Thermostat) which is using the state..
Wanted to display a different state there also..

mighty ledge
#

just move that template sensor from the binary_sensor section to the sensor section and it will work

#

you currently have...

binary_sensor:
- platform: template
  sensors:
    garagedeuren2_status:
      ...
#

change it to

#
sensor:
- platform: template
  sensors:
    garagedeuren2_status:
      ...
spring path
#

Thanks ๐Ÿ™‚

#

That was easy ๐Ÿ™‚

#

Never thought this was possible this way..

mighty ledge
#

keep in mind that your automations will have to check for the state on the sensor now and not on/off

#

but you can just use the original binary_sensor for automations with on/off

spring path
#

okay, thanks for the headsup..

Have to check the automations then..

#

Thanks man ๐Ÿ™‚

mighty ledge
#

np

narrow surge
#

I got the following template in a condition, however the condition should not run when this condition is true (light is on and in certain rgb mode), how can I change it around?

{{ is_state_attr('light.bedroom_bed' , 'rgb_color' , (255, 159, 39)) }}
hollow bramble
#

Just put not at the beginning

#

{{ not is_state_attr('light.bedroom_bed' , 'rgb_color' , (255, 159, 39)) }}

narrow surge
#

ow wow, that's easier then I expected ๐Ÿ™‚

young plank
#

hi there

silent barnBOT
young plank
languid trellis
#

Hi Everyone. I need to create a sensor that shows time since last high value (temperature). Any pointers?

narrow surge
#

How can I check if there WAS motion (detected) in the last 5 minutes? I am trying this one, but this just checks the last update time of the motion group, which doesnt exactly check if there was motion detected?

      - condition: template
        value_template: <- {{ (as_timestamp(now())-as_timestamp(states.group.motion_bedroom.last_updated)) < 180 }}
#

Because it will also update when motion goes from detected to clear.

young plank
#

how to get the time like 17.44 ?

#

17:44*

hollow bramble
#

{{ now().strftime('%H:%M') }}

long basalt
#

Trying to make a command_line sensor value that is a integer and will natively be graphed by Home Assistant

- platform: command_line
  command: ./ezsp_counters.sh COUNTER_MAC_RX_BROADCAST
  name: EZSP_COUNTER_MAC_RX_BROADCAST
#

The shell script returns 11 then ascends

#

Add value_template: '{{ value | int }}' enough to cast it?

#

^ Doesn't seem to be

deft timber
#

Are you sure ./ is the right path ? And is your script executable by HA?

#

What is wrong exactly ? The cast in int? Or the execution of the command?

long basalt
#

data is being returned fine, I was just hoping to have HA graph the value natively

deft timber
#

Thatโ€™s not linked to your cast. States in HA are always string

long basalt
#

k, thank you

deft timber
#

Maybe it is because in the historic at some point you have a non number value

long basalt
#

I did nuke the sqlite db and restart a few times

deft timber
#

You have to define a unit of measurement

long basalt
#

Thanks -- is there a unit_of_measurement for a counter or integer?

deft timber
#

You choose whatever you want, it is a free string

long basalt
#

Perfect ๐Ÿ˜€

terse spear
#

I'm attempting to implement fwd/rew for my chromecast and not having a lot of luck - time stamps seem somewhat arbitrary. Anyone tried something similar? ```chromecast_forward:
alias: Chromecast Forward
sequence:

  • service: media_player.media_seek
    data:
    seek_position: >
    {{ state_attr('media_player.chromecast', 'media_position') + 15 }}
    entity_id: media_player.chromecast
    mode: single```
#

(Implemented as a script)

deft timber
#

I suggest you convert state_attr('media_player.chromecast', 'media_position')to an int before adding 15

#

{{ state_attr('media_player.chromecast', 'media_position') | int + 15 }}

terse spear
#

That's interesting. What would be the gain there?

deft timber
#

Attributes are strings. If you try to evaluate this {{"4"+2}} in the template testing screen, it will fail. I'm surprise it doesn't fail in your case but maybe HA is wrongly converting the string in unicode or something like that... Juste a tought ๐Ÿ™‚

#

which wouled give the impression of a random behavior

terse spear
#

Ouch! Thanks ๐Ÿ™‚

ivory delta
#

String maths smart

terse spear
#

Hm. No change.

#

What did change things I think is pausing before running the seek. There is an odour about this integration.

deft timber
#

๐Ÿ˜ข

terse spear
#

Type cast insight was excellent though ๐Ÿ™‚ No fan of dynamically typed adventures on this end ๐Ÿ˜‰

#

I'm at pretty close now, so I'll use it for a bit and see if I can discern a pattern for a git issue / forum thread ๐Ÿ™‚

inner mesa
#

Attributes arenโ€™t necessarily strings - they can have real types

deft timber
#

Yes that's what I realized yesterday

inner mesa
#

States are always strings

#

Oh, I just saw that was quite a while ago ๐Ÿ™‚

narrow surge
#

Do I need the <- in this?

value_template: <- {{ (as_timestamp(now())-as_timestamp(states.binary_sensor.bedroom_door.last_updated)) < 60 }}

It seems this template is doing the opposite of what I want it to be doing, simply changing < to > gives a an error:

block scalar
  in "/config/automations.yaml", line 594, column 25
expected a comment or a line break, but found '{'
deft timber
#

Wirte it that way : value_template: "{{ (as_timestamp(now())-as_timestamp(states.binary_sensor.bedroom_door.last_updated)) < 60 }}"

#

you should use > if you have a multi-line template, which is not the case here

#

Other solution:

value_template: < 
  {{ (as_timestamp(now())-as_timestamp(states.binary_sensor.bedroom_door.last_updated)) < 60 }}
deft timber
#

oups sorry

#

indeed ๐Ÿ™‚

#

copy-paste is bad

mighty ledge
#

lol, we've all been there

steady citrus
#

i'm using the following in a service call:

#
entity_id: camera.front_doorbell_cam
filename: "/media/local/camera/snapshots/{{ entity_id.name }}/{{ as_timestamp(now()) | timestamp_custom('%Y-%m-%d_%H-%M-%S') }}.jpg"
#

but the entity_id.name comes back as Front Doorbell Camera. Is there a way for me to get the entity_id itself which is camera.front_doorbell_cam ?

rugged laurel
#

entity_id.entity_id

steady citrus
#

damn can't believe it was that simple

#

i was trying entity_id.id and getting nothing

#

lol

rugged laurel
#

Im just guessing, but since name works, entity_id should be the state object

steady citrus
#

it works

#

ty

azure tinsel
#

hello, need help on template to check multiple battery sensors at once?
Do i need to create template sensor or somehow can list them in automation condition?

#

idea is if i have sensor.*battery_level below 10% to fire notification

narrow surge
mighty ledge
#
field: single line
field: >
  multiline
deft timber
narrow surge
#

aha!

dreamy sinew
#

change to >- to strip extra whitespace too

young jacinth
#

hi, i want to extract the minute value of a timer via a template

"{{ state_attr('timer.trockner','remaining') }}"

it would be 00:58:00 in this case. how do i have to modify the template?

#

to only get 58 out

#

{{ strptime(state_attr('timer.trockner','remaining'), '%H:%M:%S').minute }}

this is the solution for people that are interested!

knotty berry
#

Hello! I'm trying to write a template that gets an attribute from a sensor. That attribute is a list and I would like to get the item in the 4th index of the 0th index in that list. Here is my template so far: "{{ state_attr('weather.smhi_home', 'forecast') }}"What I get is: "[{'datetime': '2020-12-08T20:00:00', 'temperature': 3, 'templow': 3, 'precipitation': 0.2, 'condition': 'cloudy'}, {'datetime': '2020-12-09T12:00:00', 'temperature': 3, 'templow': 2, 'precipitation': 0.3, 'condition': 'cloudy'}, {'datetime': '2020-12-10T12:00:00', 'temperature': 3, 'templow': 2, 'precipitation': 0.3, 'condition': 'cloudy'}, ....................................................}]" So I want to choose today's forecast and then precipitation.

ivory delta
#

Looks like the list is in date order. Is it always sorted?

#

If so... {{ state_attr('weather.smhi_home', 'forecast')[0].temperature }}

knotty berry
#

Yes it is. So the 0th index will always be today's forecast.

ivory delta
#

Each item in that list is a dict (object), so you don't reference by index. Instead, reference by name using 'dot notation'.

knotty berry
#

Oh, I see. Thanks for the help!

late island
#

Can someone who understands a bit of yaml help me understand this? https://pastebin.com/qFQLFt7d This is a script from CCOSTAN according speech processing & engine.

ivory delta
#

Help you understand what? What's the problem?

late island
#

That part after "media_player:"
I can do and understand easy stuff like this:

   media_player.echo_dot_wohnzimmer
   {% else %}
    media_player.echo_dot_schlafzimmer
    {% endif %}```
#

But I pretty much dont understand what is done there and that pastebin after media_player

ivory delta
#

It's basically just returning a list of players unless there was already a single player specified.

late island
#

Ahh. That makes sense. So Bascially when I would have that top part with ยดif group.computer.state == onยด I dont really need that?

ivory delta
#

Well since you haven't said what you're trying to achieve, no-one can say what you need to do.

wet sail
#

I'd like to overlay today's temperature graph with yesterday's temperature graph. Ideally I'd like to use the same sensor and in the graphing card add some type of template conversion to offset the second display by -24 hours. Any recommendations on how I can do this?

balmy terrace
#

guys

#

I have a question

balmy terrace
#

if an automation triggers after an entity changes its state from off to on, a test for the Trigger Data would be {{ trigger.to_state == 'on' }}

#

is that right?

dreamy sinew
#

You could do that but why?

#

trigger.to_state.state

deft timber
#

@wet sail you could create an sql sensor that retrieve the temp of yesterday same time. So that you can display that sensor + todayโ€™s temperature on the same graph

balmy terrace
deft timber
#

trigger.to_statewill return the state object which contain the state, the attributes, and so on. So if you want the state string, you need to add .state at the end

#

state object which is actually a dict object

balmy terrace
#

what would be the syntax for {{ is_state(A, x) AND (is_state(B, y) OR is_state(C,z)) }}

#

I hope you understand what I mean hahaha

deft timber
#

Replace AND with and and you are good

balmy terrace
#

are the parentheses right?

#

(is_state(B, y) OR is_state(C,z))

#

can I use 2 parentheses like that?

#

I'm not a programmer , don't know the syntax . tried to google but didn't find the answer for that

#

{{ is_state('sun.sun', 'below_horizon') and (is_state('switch.entrance_light', 'on') or is_state('switch.christmas_tree', 'on')) }}

deft timber
#

yes that's correct

balmy terrace
#

Thanks slashback

tame hazel
#

Hi Ho, hope this is the right place to ask. I tried to set the device_class for a door/window binary_sensor which is in that case on a window to the following:
binary_sensor.shelly_badfenster_links:
device_class: window
Problem is, icon doesnยดt change. Itยดs still a Door instead of a window. Reloaded the customize.yaml and triggered the sensor already but no change. Any idea why? thx.

ivory delta
#

Wrong channel, nothing to do with templates ๐Ÿ˜‰

grim flicker
#

I have this code: {% if state_attr('weather.mylocation', 'temperature')|float <= 0 > -40 %} The temperature is between 0 and -40 degrees {%- else -%} The temperature is above 0 degrees {%- endif %}
when testing in the dev portal it seems to work... but it looks kinda strange. Can anyone confirm this is correct? I know in my php time you needed && between values but this is another language so this could be ok

ivory delta
#

If it works, it's correct ๐Ÿคทโ€โ™‚๏ธ

#

I don't think you're accounting for the temperature being below -40 though. Looks like you're testing if 0 is more than -40.

#

Yes. You can prove it with this: {% if -60 <= 0 > -40 %}

#

You need to flip your logic around: {% if 0 >= -60 > -40 %}

#

And then you also need another return value for when the temp is under -40. Yours will tell you it's 'above 0 degrees'.

grim flicker
#

yeah well i dont think the temperature is gonna get below -40 any time soon here... maybe when an ice age happens

ivory delta
#

Then why bother specifying it?

grim flicker
#

i want to set the heater off half an hour later when the temp outside is below zero and above -10

ivory delta
#

{% if state_attr('weather.mylocation', 'temperature')|float <= 0 %}

grim flicker
#

and an hour later when it is below -10

#

the tricky part is to account for the fact that between half an hour and an hour the temp can change in which both dont apply

deft timber
#

you can set your automation to off during 30 min (?)

#

Or play with an input_boolean

grim flicker
#

That's a good one. Thanks

young jacinth
#

hi, how do i get the state before the actual state of an entity like {{ states(''person.sam'') }}

grim flicker
#

What do you mean by "before"

young jacinth
#

the state before the actual state
like if person.sam is home now it was not_home before

grim flicker
#

So you want to get the info out of the history

young jacinth
#

yes

grim flicker
#

That's a good question. Never did something like that before. I guess it's possible.

young jacinth
#

i like to do it with a template so i can paste the old state in a notification message

#

like
message: Sam left _the old location_

grim flicker
#

you can put the value of a state in a helper. And on it changing trigger an automation that posts the old one. And then update it to the helper

young jacinth
#

i was hoping that i can solve this without the use of a helper..
but good point i thought about that too

grim flicker
#

no time to read it all

young jacinth
#

i tried to use an input_text helper at the end of the automation but they dont like templates i guess

#

entity_id: input_text.sam_old_zone
value: "{{ states('person.sam') }}"

tried it with this but nope does not work in automations

#

i just get {{ states('person.sam') }} in the text of input_text.sam_old_zone

#

this is weird

raw dust
young jacinth
#

thanks alot
this was what i have been looking for!
i hope this works out as it seems that i cant test this automation with a manual trigger

#

templates are great :)))))

wet sail
deft timber
#

sensor.test_addtime gives me 2020-12-08, 18:18

#

which is yesterday time

wet sail
#

when running the query in sqlLite Web I get near "(": syntax error

deft timber
#

oh ok it is sqlite ๐Ÿ™‚

#

I'm on MySQL

#

query needs to be adapted then

wet sail
#

if I remove () from current_timestamp() I get no such function: addtime

#

i'm on HA OS running on a RPI, I've never really considered what version of SQL I am running

deft timber
#

The standard is sqlite. Use this instead DATETIME(..) fct instead

#

datetime('now', '-24 hours')

wet sail
#

that works! Will I need to wait 24 hours before this new sensor has all the data or is it populated in real-time when queried?

deft timber
#

you'll have to wait

marble sigil
#
- id: '1607529390367'
  alias: test
  description: ''
  trigger: []
  condition:
  - condition: template
    value_template: '{{ False }}'
  action:
  - service: light.toggle
    data: {}
    entity_id: light.wled_1
  mode: single

Why does this automation still toggle the light? Even when I straight up made the condition False ??????

bronze tide
#

hi there!
I have got the following condition as part of an automation:

      - condition: template
        value_template: >
          {%- set new_state = trigger.event.data.new_state %}
          {{ new_state.object_id.startswith('l0') or new_state.object_id.startswith('l0') }}

My questions:

  1. how can this template be improved?
    I am a newbie and have got the feeling that there is a better way to get the entity id of the object which triggered the automation.
  2. how can I find out whether the entity id ends in 'pir 01'? as you might guess i tried ...endswith(... .
  3. where does one find such wonderful functions as startswith?
ivory delta
bronze tide
ivory delta
#

No push pin icon?

bronze tide
# ivory delta No push pin icon?

Ooops ... Just found them... ๐Ÿ˜‰

Funny as it is - it looks as if my eyesight is still not good enough to find some pointer towards docs.
With the keyword 'jinya' from the template test page i found docs thanks to google.
Can you please point me where I can find pointers in the pins to do some RTFM on e.g. startswith?

ivory delta
#

Only if you stop tagging me ๐Ÿ˜‰

deft timber
#

You can also use regex: {{ entity_id|regex_match("\.l0.*pir01$")}}

jagged tulip
#

Hello everyone, i had a working next alarm template now the entity_id: option is deprecated, iv deleted the entity id and have been trying to get it to work but the binary sensor just wont change from off to on. this is my old template # My next alarm

  • platform: template
    sensors:
    ians_next_alarm:
    entity_id:
    - sensor.ians_mobile_next_alarm
    - sensor.time
    friendly_name: "Ians Next Alarm"
    value_template: >-
    {{now().strftime("%a %h %d %H:%M %Z %Y") == (((state_attr('sensor.ians_mobile_next_alarm', 'Time in Milliseconds') | int / 1000) + 0*60 ) | timestamp_custom('%a %h %d %H:%M %Z %Y'))}}
#

Any ideas why it would not work by just deleting entity_id:
- sensor.ians_mobile_next_alarm
- sensor.time

deft timber
ivory delta
#

Why? I thought they changed it so now() properly evaluates templates.

#

Fewer things to get wrong if you don't need to introduce intermediary layers.

deft timber
#

as far as I understood, a change in now() will not trigger a refresh of the templates. a change in the datetime sensors will do

ivory delta
#

That used to be true.

deft timber
#

well apparently it is refreshed every minutes

ivory delta
#

Go put {{ now() }} into the Dev Tools. You'll see a note under the right hand side stating that it'll update once per minute. If that's good enough, there's no need to do anything else.

deft timber
#

so, my bad

ivory delta
#

๐Ÿ‘Œ

#

It was a fairly recent change and advice had previously always been to use time_date, so don't worry ๐Ÿ™‚

jagged tulip
deft timber
#

well apperently it won't change anything

deft timber
#

BTW, you could have made a binary_sensor instead of a sensor

#

but in won't fix your issue though ๐Ÿ™‚

raw dust
#

I'm not sure this belongs here, but is it possible to get the entity_id from the entity_registry if I have the device_id?

#

it does not matter which entity_id

#

the device name would be fine as well from the device_registry

desert quail
#

hi people, i'm trying to do a phone template for my wall (replacing switchs) but i want to get ride of menu bar on top, how to do it?

raw dust
desert quail
#

what? thats a template question

silent barnBOT
scenic mica
#

I'm trying to setup a very simple MQTT Fan. There is one MQTT topic (zway/livingRoom/ceilingFan) with a number from 0 to 99. How do I configure 'payload_on' to be any value greater than 0?

ivory delta
#

As the name suggests, that allows the use of templates. You could have a template for value_template that simply checks it's greater than zero.

scenic mica
#

got it ... thanks a bunch

mighty ledge
#

@scenic mica state_value_template: "{{ value_json > 0 }}"

jagged tulip
# jagged tulip Would you do it like this? ...

Just in case anyone has the same problem with the template for next alarm, It is now working the solution is value_template: "{{((states('sensor.mobile_next_alarm')|as_timestamp|int - now()|as_timestamp|int)/60)|int}}"
availability_template: "{{ not is_state('sensor.mobile_next_alarm','unavailable') }}"
attribute_templates:
time: "{{ state_attr('sensor.mobile_next_alarm','Local Time') }}"

mighty ledge
#

you got a few too many int casts in there

jagged tulip
mighty ledge
#

it won't, just making observations

#

Wh y do you want a sensor that outputs the next alarm in minutes anyways?

#

wouldn't you rather have a friendly format?

jagged tulip
#

i would but no one could help me with it iv just struggled to get it all up and running, being a beginner at code like this

mighty ledge
#

All you need to do is output the timestamp and change the device_class to timestamp and it wll have a freindly format like "in 4 hours"

#

and your mobile_next_alarm sensor looks like it's a formated timestamp already

#

so all you need to do is add device_class: timestamp to it in customizations and when you place it in an entities card it will give relative time

jagged tulip
mighty ledge
jagged tulip
mighty ledge
#

No, you'd need to tailor the template to return true when the alarm timestamp matches the current time

#

what's the format of your sensor.next_alarm_time state?

jagged tulip
mighty ledge
#

{{ states('sensor.mobile_next_alarm')[:16] == as_timestamp(now()) | timestamp_custom('%Y-%m-%dT%H:%M') }}

jagged tulip
daring tendon
#

I am playing around with templates and noticed that my lights have an attribute 'supported_features: 41' Is this another list of attributes I can access somehow?

torn meteor
#

hey there. my input_boolean.last_changed time does not match what is in the UI for history. I am using astimestamp() to get the right time zone. Iโ€™m getting 30 minutes ago (wrong) from this template. The history on the entity UI is 5 hours ago (correct)

inner mesa
#

Did you restart HA in that time period?

#

I donโ€™t think the last_changed times survive a restart

daring tendon
#

Would anyone know why a simple template such as

  action:
    service: "{{ light.turn_off }}"

Results into this config check error:

Invalid config for [automation]: Service {{ light.turn_off }} does not match format <domain>.<name> for dictionary value @ data['action'][0]['service']. Got None. (See /config/configuration.yaml, line 9).
#

It seems like my Jinja is not evaluated at all

raw dust
#

try with service_template instead

daring tendon
#

That actually worked. I am a bit confused, why do I need to use service_template instead of just service? Is there an x_template equivalent for all types?

#

By "it works" I mean, it doesn't throw a configuration error. I haven't tried using it yet.

torn meteor
#

@inner mesa so if last_changed times don't survive, what the heck is the UI in Lovelace using to accurately persist that correct time?

silent barnBOT
daring tendon
#

@raw dust can you help me out on this one then? I am trying to populate the entity_id field in an action with a template as well. Getting a similar error. Link is above.

raw dust
#

there is no such thing as entity_id_template, it's just entity_id: and template

daring tendon
#

Tried that as well, it threw me this:
Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['entity_id']. Got None. (See /config/configuration.yaml, line 9).

#

But throwing my template into the Developer Tools > Template - It print out an entity ID

raw dust
#

could you share the code for the second error?

daring tendon
#
  action:
    - service_template: >
        {% set toState = (['on', 'off'] | random) %}
        {{ 'light.turn_' + toState }}
      entity_id: >
        {{ states['light'] | 
          rejectattr('state','eq', 'unavailable') |
          rejectattr('attributes.is_deconz_group') |
          rejectattr('attributes.supported_features', 'eq', 0) |
          map(attribute="entity_id") |
          list | 
          random }}
raw dust
#

try it with data_template like:

- service_template: >
        {% set toState = (['on', 'off'] | random) %}
        {{ 'light.turn_' + toState }}
  data_template:
    entity_id: >
daring tendon
#

@raw dust thank you! That worked!

inner mesa
#

You should update HA. It seems like youโ€™re several versions behind

terse spear
#

I'm looking for a means to read/write some settings to permanent storage (like write current state of this light, then read it back later) and while the File integration looks promising for the read part, it does not appear to support writing. So I was thinking maybe I am missing some other method for permanent settings storage? Or is that sort of thing just not available at this time?

deft timber
#

The input_* are persisted in the DB

#

so you can use it

young jacinth
#

hi,

data:
  type: tts
message: test
target: >-
  {% if is_state('binary_sensor.wz_besetzt', 'on') %}-
  media_player.wohnzimmer_alexa {% endif %}{% if
  is_state('binary_sensor.sz_besetzt', 'on') %} -
  media_player.schlafzimmer_alexa {% endif %}

i want to use a template for the targets in this notify service call, but i cant get the syntax right

ivory delta
#

It'll output a native list from the template, rather than you trying to write a list in plain text (which I don't think works).

young jacinth
#

mhh thanks, but how do it get the conditions in?

ivory delta
#

Almost like you're doing now. Just change it so you start with an empty list, add each target to the list if it's turned on, return the list at the end.

young jacinth
#
{% if media_player | length == 0 %}
              {% set media_player = [
              {% if is_state('binary_sensor.wz_besetzt', 'on') %}
              media_player.wohnzimmer_alexa {% endif %}
              ] %}
            {% endif %}
            {% if media_player is not string and media_player is sequence %}
              {% set media_player = media_player|join(', ') %}
            {% endif %}
            {{ media_player }}

this wont work

ivory delta
#

That's not what I said.

#

I'm on mobile, so I'm not going to write it for you.

terse spear
#

@deft timber Ah so I would be able to read/write the full state to input_text. Very cool.

#

Thanks ๐Ÿ™‚

young jacinth
silent barnBOT
dreamy sinew
#

ehh adding things to a list in HA's implementation of jinja is kind of a thing

#
{% for thing in things %}
{% set ns.l1 = ns.l1 + [thing] %}
{% endfor %}
{{ ns.l1 }}
young jacinth
dreamy sinew
#

other jinja envs aren't as picky

#

list.append() is a thing in jinja but the specific env that HA uses disables that

ivory delta
#

TIL. Still, it's the right approach.

young jacinth
#

iam quite overhelmed with templates
i get basic ones going but that is to difficult for me

dreamy sinew
#

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

#

@ivory delta ๐Ÿ˜›

#

or:
{{ ", ".join(states.binary_sensor|selectattr("state", "eq", "on")|map(attribute="entity_id")|list) }}

ivory delta
#

There are many ways to skin a cat

dreamy sinew
#

i usually try to avoid loops and namespacing whenever i can

ivory delta
#

Yeah, the pipes are probably easier to reason with and also result in more concise templates.

dreamy sinew
#

and that's all built in jinja filters. Nothing HA specific other than the states object

ivory delta
#

I love seeing the stuff people do with |map. I need to make better use of it.

#

I'm getting to the point where I have enough devices to justify custom attributes to map by room.

dreamy sinew
#

i had to look it up again for this. I can never remember how to use it properly

thorny snow
#

https://hastebin.com/ilihefegug.yaml the automation not work and I don't know why. can someone help me? it is a timer created with a slider to be able to choose the duration. Everything works except the trigger and the final action of turning off the light. In practice, everything works but the automation does not start or stop when the light status changes.

ivory delta
thorny snow
#

in automations they told me to ask for help here

ivory delta
#

They also suggested you test the template. Did you do that?

thorny snow
#

I don't understand how to do it

#

ok i tested now

#

UndefinedError: 'trigger' is undefined

ivory delta
#

And that only exists in an automation. Replace it with the real entity's name.

thorny snow
#

ok. thanks. i attempt

ivory delta
#

Yes... You can't use trigger outside of an automation.

daring tendon
#

In my automation I am picking a random light and turning it either on or off using templates. However, I would like to know what state my randomly picked entity is in so I can pick the opposite state from on to off and off to on. How do I get my randomly picked result for entity_id into the template for service_template?: https://pastebin.com/8QhcCLLj

ivory delta
#

Seems an ideal use case for variables.

#

Or... just use light.toggle smart

daring tendon
#

Alright, good call I'll properly go with light.toggle. I wasn't aware of that! But lets just say, I still want to parse a variable from one template section to another. Does templates in the same configuration share scope? Would I be able to do something like this?

  action:
      - data_template:
          entity_id: >
            {% set randomEntity = pickRandomEntity() %}
        service_template: >
          {{ randomEntity }}
#

Just clarifying, above is just pseudo code.

ivory delta
#

Nope. Different scopes.

#

But you could possibly use variables.

#

Honestly... if you ever wanted to do something like that, just make it a script and pass the randomly selected entity in instead. Way less ugly, way easier to maintain.

daring tendon
#

I am not familiar with scripts yet so I am not exactly sure how that would look that.

ivory delta
#

Well I just linked the docs, have a read ๐Ÿ˜‰

#

You've used scripts already (that's all the actions of an automation are). The bit you didn't realise is that you can define scripts that stand alone too.

daring tendon
#

How would a script be different from what I was already doing in my pastebin? Isn't it more of a tool to isolate your code pieces and reuse them?

ivory delta
#

Exactly my point. Your action in the automation would only be responsible for picking a random entity ID and calling a script with it. The script's responsibility would be to check the state of that entity and call the relevant service.

#

Isolation and reuse in a nutshell ๐Ÿ˜‰

#

You've essentially just created a 'toggle entity X' script.

daring tendon
#

Oh, so my randomly picked entity_id becomes an input parameter for the script which is then accessible throughout the entire script?

ivory delta
#

Bingo

daring tendon
#

Neat, I'll try and take a stab at it. Thank you @ivory delta ๐Ÿค˜

#

Just to clarify, I do still need to use variables? Even though I am moving my silly "toggle service" to a script, I still need to be able to parse my randomly selected entity_id to my custom script.toggle, right?

#

From what I can read this is how I invoke a custom script:

  action:
      - data_template:
          entity_id: >
            {% set randomEntity = pickRandomEntity() %}
        service: script.toggle
          entity_id: [[INSERT RANDOM ENTITY_ID]]
ivory delta
#

Nope

#

Just assign the template that picks a random entity to entity_id:

#

No need for the last line and also no need for data_template:, just use data:.

#

Some docs still need to be updated. No need for the _template suffix anymore.

daring tendon
#

I am not sure I follow. How does my script access my randomly selected entity_id if I don't parse it in as an input parameter?

ivory delta
#

This bit is gibberish and would fail validation:

        service: script.toggle
          entity_id: [[INSERT RANDOM ENTITY_ID]]```
#

This is good enough:

  action:
      - data_template:
          entity_id: >
            {% set randomEntity = pickRandomEntity() %}
        service: script.toggle```
#

Well, move the entity ID under variables, as documented in the section I just linked.

daring tendon
#

I believe I follow you now.

ivory delta
#

We're into #automations-archived territory at this point as well. If you have any more questions about it, ask over there. I'm done for the night but someone else will help.

daring tendon
#

Alright, thank you so far @ivory delta

silent barnBOT
blazing burrow
#

trying to figure out why this isn't working... ^

#

this template: {{ states("input_number.wled_preset") | int }} does evaluate to the correct integer i've got selected by the input_number, and this call works in postman: curl -L -X POST 'http://192.168.1.189/json/state' -H 'Content-Type: application/json' --data-raw '{"psave": 16}'

#

but calling the rest_command doesn't actually save the preset

#

same call in postman does

#

so i'm thinking i've got formatted wrong?

#

but can't figure out what's wrong

#

ohh i need to pass the content type as header maybe

#

that didn't seem to help ๐Ÿค”

blazing burrow
oblique mural
#

hey folks, having an issue with a value template as i am trying to build out an alarm using a SDR and Honeywell Door/Window sensors

#

value_template: '{% if value_json.id is equalto 860776 and value_json.event is equalto 160 %} {{value_json.state}} {% else %} {{value_json.state= "off"}} {% endif %}'

#

this is what i have and the open portion works, but the setting of the state to off is not working. i have tried a few ways to no avail

#

does anyone have any suggestions for me

blazing burrow
#

well firstly I'd work on your syntax

#

that is basically gibberish

oblique mural
#

its may look odd, but it works other than {{value_json.state= "off"}} which i know is wrong

#

i have poked at it, tried declaring the var etc

#

this is not expected to work but as an example of what im trying to do

blazing burrow
#
value_template: '{{ "on" if value_json.id == 860776 and value_json.event == 160 else "off" }}'
#

something like that should do

oblique mural
#

well thats a nice simple way and it works, awesome thanks @blazing burrow

quaint inlet
#

does someone have a good...idk blogpost or something explaining simple templating with examples? I've read the docs page several times but....some concrete examples would help. Mostly what I want is all my door sensors as triggers, and the body of the notify message to contain the sensor name and new state....at least I think templating is what I want for this?

node-red was suggested in automations but that doesnt really seem like the way i want to go, if templating or something similar would let me do that, i'd rather do that

blazing burrow
#

that probably is a good use of templates yeah

#

in an automation, you could use {{ trigger.to_state.name }} for the name, and {{ trigger.to_state.state }} for the state

quaint inlet
#

well, that's a good start. do you have pointers to something... a little more verbose than the template doc with more examples?

blazing burrow
#

not really besides others examples

quaint inlet
#

hm. ok...well i'll give starting off with that a shot

blazing burrow
quaint inlet
#

yeah. which...has one okayish example towards the bottom...but then goes on that you should follow these 4 rules that are not clicking and also dont seem represented in the examples

#

follow up question: how do I abstract away open and closed to words? state 23 is closed and state 22 is open...at least so far as I've ever figured out with these zwave sensors

blazing burrow
#

for your notification, or for some logic to see which state they're in?

quaint inlet
#

for the notification. I'm not sure your to_state.state will be helpful but about to test

blazing burrow
#

that same page goes on to talk about the trigger object btw, which is the important part here

#

trigger being the entity which triggered the automation, to_state being a representation of its state after whatever change made it trigger, and state being the actual state

#

to_state.name would be the name of the entity

#

those are in contrast to from_state, which would be the state of the trigger entity before the automation was triggered

quaint inlet
#

is there a way to regexp/clean up strings? for instance this sensor ends up being called FrontDoor_accessControl when i grab the name from {{ trigger.to_state.name }}

blazing burrow
#

well you could change the name of the entity

#

that'd be far easier than a regex

quaint inlet
#

each zwave sensor has like...5 things within it for whatever reason. tamper switch, access controll switch, battery level...and other things i've forgotten since i added them

blazing burrow
#

sure

#

entities

#

each device can have multiple entities

#

my aqara zigbee temp/humidity sensor device, for example, has a sensor entity for each of temp/humidity/pressure/battery

quaint inlet
#

hm ok the entities are different than i remembered...or did I hide some. for some reason i remembered it conflicting if i removed the accessControl from the sensor names

blazing burrow
#

names shouldn't conflict

#

IDs will though

#

like sensor.whatever

quaint inlet
#

ah, i hid the overall sensor that contains the entities from the entities view. so...i'd rename FrontDoor to FrontDoorSensor, and then FrontDoor_AccessControl to just FrontDoor is how you'd solve this issue?

blazing burrow
#

I guess, sure

#

up to you what you'd name them

quaint inlet
#

well. i mean, that's the sort of approach you're suggseting at least

blazing burrow
#

I'm just saying it'd be faster, easier, and more consistent, to just rename the entity, instead of trying to manipulate the string inside your template

#

probably you're going to want to use whichever entity actually changes state whenever the sensor is triggered

#

it's state will probably show as either "open" or "closed"

quaint inlet
#

right right, that part seems to work ok, just tested a door

blazing burrow
#

maybe "on"/"off"

quaint inlet
#

now i need to figure out how to change "22" and "23" to "opened" and "closed"

blazing burrow
#

yeah, so name that entity whatever you want to show in your notification, and use it to trigger your automation

#

the state of your sensor is 22/23?

#

I'm not familiar with zwave, tbf

quaint inlet
#

yeah. 22 means open, and 23 means closed...for whatever reason

blazing burrow
#

hmm, well

quaint inlet
#

ยฏ_(ใƒ„)_/ยฏ

#

but this: message: '{{ trigger.to_state.name }} {{ trigger.to_state.state }}' title: FrontDoor Open now yeilds "frontdoor 22"

dreamy sinew
#
{{ map.get(states("sensor.whatever"), "unknown") }}```
blazing burrow
#
{% if trigger.to_state.state == '22' %}
  open
{% else if trigger.to_state.state == '23' %}
  closed
{% endif %}
#

haha alright then I guess not

#

@dreamy sinew that works too I guess

#

seemed a bit overkill for just two cases

dreamy sinew
#

That covers 3 though

blazing burrow
#

but mine didn't work so ๐Ÿคท๐Ÿผโ€โ™€๏ธ lol

quaint inlet
#

er...so i'm editing this in the automation ui right now...does that go in the action as yaml or somewhere else

blazing burrow
#

ah yeah, good call

dreamy sinew
#

Eh, yours would work just isn't yaml as it is

blazing burrow
#

oh yeah right

#

I formatted the md as yaml instead of jinja lolol

inner mesa
#

And states are strings

blazing burrow
#

good catch as well

#

@inner mesa might you take a look at my thing in #integrations-archived and see if you can see where I'm wrong?

quaint inlet
#

so...like this?

'{% set map = {"22": "open", "23": "closed"} %}'
data:
  message: '{{ trigger.to_state.name }} {{ map.get(states("trigger.to_state.state"), "unknown") }}'
  title: FrontDoor Open
service: notify.notify

? or do i put that first line...somewhere else?

#

(ignore the title line for now, just working on the message line)

blazing burrow
#

that first line has to go into the message as well

quaint inlet
#

ah ok

inner mesa
#

@blazing burrow I think youโ€™re missing quotes around the template, meaning that youโ€™re not passing properly formatted JSON

#

You may need to assign the template to a variable first to get the quotes right

blazing burrow
#
payload: '{ "psave": {{ states("input_number.wled_preset") | int }} }'
#

I feel like that's right?

#

or maybe the quotes inside states messing it up?

#

I know I've got something wrong...

#

it should be an integer there, as the value of psave

#

I can get it working via curl with postman

#

just {"psave":16} or whatever id

#

I just like the whitespace in yaml, easier to read later

inner mesa
#

Ok

#

Plug it into the template dev tool and see what you get

quaint inlet
#

hm. the set map thing seems to have broken it

blazing burrow
#

{{ states("input_number.wled_preset") | int }} shows me an integer in the editor (whichever my input_number is on)

#

no quotes, but it also doesn't show quotes around strings lol

#

curl -L -X POST 'http://192.168.1.189/json/state' -H 'Content-Type: application/json' --data-raw '{"psave": 16}' this works from postman

quaint inlet
#

What I tried to put in was this: and save...but after restarting hass and reloading the page, it has something very different saved in there so...uh, maybe i made a syntax error

data:
  message: 
'{% set map = {"22": "open", "23": "closed"} %}'
'{{ trigger.to_state.name }} {{ map.get(states("trigger.to_state.state"), "unknown") }}'
  title: '{{ trigger.to_state.name }}'
service: notify.notify
blazing burrow
#

do this

#

message: >

#

then, on the next line, indented two more spaces

#

put the three template lines, without the surrounding ' '

#

also make sure the third line is indented with the rest

#

oh wait, is it two lines? sorry, mobile lol

#

ok, on the second line remove the }} {{ in the middle

#

lemme try

quaint inlet
#
data:
  message: >
    {% set map = {"22": "open", "23": "closed"} %}
    {{ trigger.to_state.name map.get(states("trigger.to_state.state"), "unknown") }}
  title: '{{ trigger.to_state.name }}'
service: notify.notify

?

blazing burrow
#
data:
  message: >
    {% set map = {"22": "open", "23": "closed"} %}
    {{ trigger.to_state.name + map.get(states("trigger.to_state.state"), "unknown") }}
  title: '{{ trigger.to_state.name }}'
service: notify.notify
#

I think this

quaint inlet
#

that second line of the message is on the same line as the one after it

#

ah, a plus. gotcha

blazing burrow
#

you need a + in the middle ๐Ÿ‘

#

add two strings

#

the > basically says, "up next is a multiline block"

quaint inlet
#

tfw the automation gets disabled by something while testing and you're trying to debug something when it's disabled ๐Ÿ˜ค

blazing burrow
#

I use that same sort of thing for converting the selection from an input_select into the selected index instead:

          preset: >
            {% set idx = {"Juggle": 1, "Rainbow Twinkle": 2, "Rainbow": 3, "Night Rider": 4,
                          "Fire": 5, "Rainbow Juggle": 6, "Drywet": 7, "Drywet Juggle": 8,
                          "Magripple": 9, "Preset 10": 10, "Preset 11": 11, "Preset 12": 12,
                          "Preset 13": 13, "Preset 14": 14, "Preset 15": 15, "Preset 16": 16} %}
            
            {{ idx[states('input_select.wled_preset')] }}
#

a bit different, but similar idea

quaint inlet
#

ok, i get messages again, but the template map thing still isn't working quite right yet. I get "FrontDoorunknown"

blazing burrow
#

@dreamy sinew I had been looking for a more efficient way, like a zip(a,b) -> {a[0]: b[0], ... a[n]: b[n]} method... but doesn't seem to be any way in jinja?

#

that means the state from the template isn't either 22 or 23

#

the map.get(..., "unknown")

#

means if it doesn't find something in the map, it gives you unknown

quaint inlet
#

right, but this is what triggered the whole automation:

platform: state
entity_id:
  - sensor.door_house_front_access_control
  - sensor.door_garage_roll_access_control
from: '23'
to: '22'
#

so...seems like an issue with the map more than the states being wrong coming into the automation

blazing burrow
#

what entities does your device give you, specifically?

quaint inlet
#

uh, can you rephrase that? based on the trigger i know the state has to be from 23 to 22, so i'm not certain what the entities are...mattering?

blazing burrow
#

ok, open up that device, and you said there's multiple entities there

#

what are they, and what are their current states?

quaint inlet
#

the zwave device has 7 entities

blazing burrow
#

look something like this?

#

ish

quaint inlet
#

yes, though the data is nowhere near as helpful as that pic heh

#

but let me pull that up on my phone and go open the door, because afaik, only teh 23 changes

blazing burrow
#

can you show?

quaint inlet
#

yeah only the 23 changes when I open the door...sec

#

..just as soon as i find a place to paste a picture

blazing burrow
#

might be a question for #zwave-archived at that point... OR try removing the quotes around "22"/"23" in your map

quaint inlet
#

imgur doesnt seem to like my adblock

blazing burrow
#

just to see

quaint inlet
#

would that make them integers isntead of strings or something?

blazing burrow
#

yes

balmy terrace
#

one simple question

#

"value_template: >-" what are '>' and '-' for at the beginning of a template?

blazing burrow
#

that is basically, "up next is a multiline block"

#

I sent an example above

#

a couple

balmy terrace
blazing burrow
#

tbh I don't know the difference

#

between the two lol

balmy terrace
#

what 's the difference between > and >-

balmy terrace
quaint inlet
#

@blazing burrow question, am i passing the trigger.to_state.state correctly to the map? That's not just passing the literal string to it right...actually the contents of the variable?

{{ map.get(states("trigger.to_state.state"),"unknown") }}
blazing burrow
#

ah no

#

map.get(trigger.to_state.state)

quaint inlet
#

๐Ÿคฆโ€โ™‚๏ธ well that'd explain it lol

blazing burrow
#

you COULD use

#

map.get(states("sensor.your_entity_id"))

#

but trigger.to_state.state is technically better

#

the former would be the CURRENT state

quaint inlet
#

oh no that's miles better, the goal is to have many triggers

blazing burrow
#

the latter would be the state that triggered the automation

quaint inlet
#

still getting unknown however...

blazing burrow
#

the latter is what you want for many triggers

#

go into the developer tools template tester and paste in your template

#

the lines after the >

quaint inlet
#

I just replace the for loop at the bottom with my test code, or the whole thing?

blazing burrow
#

or whatever

#

nothing in there is sacred

#

just scratch space for you to test

#

also the states tab can help you evaluate states at any given moment

quaint inlet
#

then i'd have to know how to define trigger it seems

blazing burrow
#

use the entity id way

#

in your test

#

trigger is only valid in automations

quaint inlet
#

hmmm. result: closed

#

so right now on my phone i see:
FrontDoor unknown 22

generated from

message: >
  {% set map = {'22': 'opened', '23': 'closed'} %} {{ trigger.to_state.name +"
  "+ map.get(states(trigger.to_state.state),"unknown")+"
  "+trigger.to_state.state }}
unreal lodge
#

I have some binary sensors that I'd like to use as device_trackers. How do I map them to this purpose?

quaint inlet
#

@blazing burrow derp. ok it works. i missed yet another typo on the trigger passing to the map ๐Ÿคฆ

#

@blazing burrow thanks for all the help

#

ok one final question, is it possible to have multiple "from" states and "to" states in the trigger?

#

i.e. could i make it so that this is triggered from 22 -> 23 and 23 -> 22 somehow?

platform: state
entity_id:
  - sensor.door_house_front_access_control
  - sensor.door_garage_roll_access_control
from: '23'
to: '22'
blazing burrow
#

you can leave off the from and to, and it'll trigger on any state

quaint inlet
#

I suppose that would work. i imagine it's not going to trigger on 22 -> 22 or 23 -> 23?

#

(i.e. just sitting there)

blazing burrow
#

you'd then use conditions to figure if it's the change you're interested in

#

or chooses in the actions, to make different decisions

quaint inlet
#

well...it seems to work as desired at the moment, so yay!

now I can start to slim down all my...idk 20 static rules (10 sensors, an open and close rule per sensor) to like...just a few

#

so, huzzah, that will accomplish everything I set out to do today. big thanks again @blazing burrow

blazing burrow
#

yeah man ๐Ÿ‘ I need to do the same lol

#

anyways, I'm probably going dark for the night lol but glad we got you figured out ๐Ÿ‘๐Ÿ‘

deft timber
#

Attention, it can trigger if 22-> 22 or 23 -> 23. If you donโ€™t set the from and to, it will also trigger if an attribute changes.

raven token
#

I know in the past, you would use entity_id for sensor templates, but I'm now seeing this message in my logs The 'entity_id' option is deprecated, please remove it from your configuration, does this mean that the option is entirely unneeded now or is there a replacement option? Do sensors now update automatically?

inner mesa
#

it is unnecessary now

#

they always updated automatically based on the entities that it could detect, but they now do a better job of it

raven token
#

Thanks

inner mesa
#

you can plug a template into devtools -> Templates and it will tell you what it's listening for on the right side

raven token
#

How do I escape None? I.e. This recently stopped working

{% if 1==1 %}
    None
{% endif %}
inner mesa
#

it's probably returning the native type now. How is it not working?

raven token
#

I just want it showing None as the sensor value. Right now, it shows unknown instead.

#

Although I just changed it to Never instead since None was giving me problems.

#

But for future reference

#

I would like it as just to read None as just a string.

inner mesa
#

if putting it in quotes doesn't work, you may be able to add "|string" to it

#

results of tests in devtools -> Templates are confusing

#

I would have expected the native type to be converted to a string for the sensor value, but could be a corner case

hollow bramble
#

Isn't None in python like null?

ivory delta
#

Yeah, don't use 'None', it'll always be cast to None.

#

The native type stuff is cool but there are edge cases like that which no longer work.

raven token
#

Yes it is, and thats precisely why its not working. I was looking for a way to hopefully escape it.

ivory delta
#

You don't. You change the name to something else that isn't a reserved word in Python.

hollow bramble
#

Even if you convert it to a string it will still cast to None?

ivory delta
#

The casting is done after the template is evaluated.

raven token
#

If I place quotes around it, it shows "None"

#

As the output

inner mesa
#

I wasn't sure what to make of my tests in the dev tools

ivory delta
#

The template will, big. And then it'll be cast to None.

inner mesa
#

if I put "None", it tells me it's a string

raven token
#

Yeah but the string includes the quotes

ivory delta
#

The Dev Tools tell you what the template is doing. They don't tell you what HA does next.

#

Seriously. You've seen for yourself that it doesn't work and you're still questioning me?

inner mesa
#

wait, don't tell me!

raven token
#

Oh...

inner mesa
#

no spoilers

raven token
#

Yeah I did rename it to something else. Just weird that it used to work.

hollow bramble
#

Not weird considering they changed how typing works

ivory delta
#

It used to work because HA didn't attempt to cast to native types after a template was evaluated. It does now.

raven token
#

Anyways, I am using some template that I wrote way back like 2 years ago. And haven't gotten around to changing it ever since

#

HA's changed a lot since then

ivory delta
#

Evaluate template > attempt to cast to native type > pass value to integration > integration may cast again (like string to number if a number is expected)

#

The second step is new and there's currently no avoiding it.

#

Bugs have been reported for cases just like yours. Time will tell if the devs find a workaround for people.

raven token
#

No its really unnecessary to fix

ivory delta
#

It's not though. What if you need to template something to generate a command and the command your integration expects is 'None'.

#

There's a strong argument to find a way to allow people to be in control of what their templates return... but it'll need to be done in a way that doesn't undo the amazing native type stuff.

#

But I'm not a Python dev and I barely understand HA code... so I'll leave that to the experts.

raven token
#

Hmm tbh though, with all the changes that HA has made over the years, templates have become less and less of a necessity.

#

For me at least.

#

Back then, it was practically required to do just about anything

ivory delta
#

Templates are almost essential to many people. The out-of-the-box solutions don't work for everything, hence the large number of integrations that allow templates.

raven token
#

Yeah its definitely not obsolete, just not nearly as necessary. I still use them for setting timers for my sprinklers, but people can get away with the same functionality now using automations

#

Maybe not as pretty but it totally works

balmy terrace
#

any ideias why this is happening ?

inner mesa
#

that's not what the difference is - if it's unknown, it's unknown

#

it prevents errors from dereferencing something that doesn't yet exist

balmy terrace
#

"For example, you would replace {{ states.cover.source.state == 'open' }} with this equivalent that returns true/false and never gives an unknown result:

{{ is_state('switch.source', 'on') }}"

#

that's what the doc says

inner mesa
#

That will return true or false

#

Thatโ€™s doesnโ€™t mean that the sensor canโ€™t be unknown

balmy terrace
#

{% if is_state('sun.sun', 'above_horizon') %} above_horizon {% else %} below_horizon {% endif %}

I was assuming the any other value different from 'above_horizon' would give me 'below_horizon'

dreamy sinew
#

it can return unknown but it won't throw an exception

balmy terrace
dreamy sinew
#

{{ 'above_horizon' if is_state('sun.sun', 'above_hroizon') else 'below_horizon' }}

#

if you try states.domain.entity for something that doesn't exist it'll throw an exception

#

say if the template starts up before the entity is ready

balmy terrace
#

what throw an exception means? (sorry , I don't know)

dreamy sinew
#

a crash

balmy terrace
#

thank you

blazing burrow
#

@inner mesa @rugged laurel you guys had helped me with this before, but i've just cracked it!

#
{% set ns = namespace(zipped={}, options=['a', 'b', 'c']) %}
{
{% for i in (range(1, ns.options|length + 1) | list) %}
  {% set key = ns.options[i-1] %}
  {% set value = i %}
  {{ key }}:{{ value }},
{% endfor %}
}
dreamy sinew
#

hmm

silent barnBOT
blazing burrow
#

seems right to me lol

#

dang it

dreamy sinew
#

for i in (range(0, ns.options|length)|list)
ns.options[i]

blazing burrow
#
{
  a:1,
  b:2,
  c:3,
}
dreamy sinew
#

to remove all that extra whitespace change your {% %} to {%- -%}

blazing burrow
#

oooooh

dreamy sinew
#

also, if you're wanting a proper object/dict there, you need to wrap your keys in quotes

#

{{ '{}'.format(key) }}:{{ value }}

#

might work

#

either that or change the ' to "

blazing burrow
#

yeah ๐Ÿ‘

#

umm, gotta handle the trailing comma

dreamy sinew
#

{{ '{}'.format(key) }}:{{ value }}{{',' if not loop.last else '' }} iirc

blazing burrow
#

holy crap

#

that totally seems to have done it

#

i don't even need the namespace

{
{%- for i in (range(1, ['a', 'b', 'c'] | length + 1) | list) -%}
  "{{ ns.options[i-1] }}":{{ i }}{{ ',' if not loop.last else '' }}
{% endfor %}
}
#

i'm starting at 1 for a reason ๐Ÿ˜‰

dreamy sinew
#

eh, different way to do it then

#
{%- for i in (range(0, ['a', 'b', 'c'] | length) | list) -%}
  "{{ ns.options[i] }}":{{ i+1 }}{{ ',' if not loop.last else '' }}
{% endfor %}
}```
#

less mucking with the index that way

blazing burrow
#

ah, got another snag

#

i want to use that in place of something like this:

#
        value_template: >
          {% set idx = {"Juggle": 1,
                        "Rainbow Twinkle": 2,
                        "Rainbow": 3,
                        "Night Rider": 4,
                        "Fire": 5,
                        "Rainbow Juggle": 6,
                        "Drywet": 7,
                        "Drywet Juggle": 8,
                        "Magripple": 9,
                        "RGB": 13,
                        "Ocean": 16} %}
          
          {{ idx[states('input_select.wled_preset')] }}
#

to "generate" the map for me

#

non-consecutive indices are not required

#

but i basically need to replace the set idx block

dreamy sinew
#

oh, might not work that way then

blazing burrow
#

ah yeah, i thought i'd cracked it lol

#

well this sure does look nice:

{% set ns = namespace(zipped={}, options=['a', 'b', 'c']) %}
{ {%- for i in (range(1, ns.options | length + 1) | list) -%} "{{ ns.options[i-1] }}":{{ i }}{{ ', ' if not loop.last else '' }}{% endfor %}}
{"a":1, "b":2, "c":3}
dreamy sinew
#

yeah, its valid yaml but it might not be usable if its a middle step

blazing burrow
#

i've got an idea

dreamy sinew
#

.update() is locked out due to the jinja env setting

blazing burrow
#

this works perfectly:

sensor:
  - platform: template
    sensors:
      wled_preset:
        friendly_name: WLED Preset
        icon_template: mdi:heart-outline
        value_template: >
          {{ state_attr('sensor.wled_preset', 'map')[states('input_select.wled_preset')] }}
        attribute_templates:
          map: >
            {% set ns = namespace(zipped={}, options=state_attr('input_select.wled_preset', 'options')) %}
            { {%- for i in (range(1, ns.options | length + 1) | list) -%} "{{ ns.options[i-1] }}":{{ i }}{{ ', ' if not loop.last else '' }}{% endfor %}}
dreamy sinew
#

hmm, ok

blazing burrow
#

state of sensor.wled_preset is the integer index of the selected value of input_select.wled_preset

blazing burrow
#

sweet, now I've even figured out how to make the map from wleds presets.json, so it can load the correct names and indices into HA

#

beauty

#

YES, works live when I add new presets and stuff

#

now I can just update MY input select, and it'll be perfect

deft timber
#

Why using a namespace here?

{% set options = state_attr('input_select.wled_preset', 'options') %}
{ {%- for i in (range(1, options | length + 1) | list) -%} "{{ options[i-1] }}":{{ i }}{{ ', ' if not loop.last else '' }}{% endfor %} }
terse spear
#

My attempt at storing state so far - not super successful in that the values don't seem to be read (returning "unknown") and that value seems to be written to all input_text fields ๐Ÿ˜• Any glaring mistakes / suggestions?

  alias: Store Settings
  variables:
    configuration_id: input_text.stored_state_1
    lights: light.test_light
  sequence:
  - service: input_text.set_value
    data:
      entity_id: '{{ configuration_id }}'
      value: '{{ lights.attributes }}'
  mode: single```
oblique mural
#

working on an update to a binary door sensor that will retain the states. i have created the following https://pastebin.com/raw/91VTKEqe trying to read off of this mqtt json string {"time":"2020-12-12 20:16:02","model":"Honeywell-Security","id":860713,"channel":10,"event":160,"state":"open","alarm":10,"tamper":0,"battery_ok":1,"heartbeat":0} can someone give this a sanity check, i feel like im missing something but its not obvious to me

thorny snow
#

Im guessing i am in the roughly right channel, so here goes.
ive just added and flashed some ex-tuya Gosund energy moniroting plugs with Tasmota. Added to HA, I can see the watts used etc.
What I would like to do is create a mathematical entity which takes the amount of energy used x cost per unit and returns a total cost in ยฃ for the daily usage. I can do that in excel, but can it be done in HA ?

ivory delta
thorny snow
#

Really ?

#

cool

#

Im not sure what to look out for though

ivory delta
#

Well you start by looking out in the #integrations-archived channel and following the links in the topic there.

stoic cedar
#

How in a template do I get the length of time a state was before the current template?

stoic cedar
#

The logs do not appear on the state object.

fossil hearth
#

how to get the value of the triggerd sensor

#

?

#

is there something like triggerd.sensor.state ?

stoic cedar
#

You can get the current state of a sensor

#

but i want to know something about its history

#

my sensor is noisy

#

@fossil hearth states('<your.sensor>') should work for the current state

dreamy sinew
#

in an automation trigger.to_state and trigger.from_state are both things

#

should be more of an explanation in the template docs

silent barnBOT
stoic cedar
#

@dreamy sinew i get that but the sensor jumps back and forth a bunch.

#

so just trying to maybe get a count of how many switches occursed in some time grame

#

kinda like I can see in the history of the sensor

silent barnBOT
dreamy sinew
#

Should be a thing you can use from there

#

Wrong thing

#

Sec

stoic cedar
#

@dreamy sinew that does not tell me how/if I can use it in a template.... I see the history in dev tools so it is enabled. Is there a way to run a query in a template?

#

ooo let me look into that

silent barnBOT
dreamy sinew
#

That one

stoic cedar
#

ah

dreamy sinew
#

That closer to what you want?

stoic cedar
#

yes!

#

i hope i can query it in a template

dreamy sinew
#

Looks like it supports some templating

stoic cedar
#

that is for the config of it

#

not something i could use in an automation config. At least these examples.

#

but let me enable these and maybe I get access within the templates!

#

thanks for the lead!

peak juniper
#

I'm trying to count how many of my steam sensors are "online"

#

I've found a few threads that show how to count all sensors or all "on" binary_sensors but can't quite find how to find count sensor.steam*

#

Closest I've got so far is:

{{ states.sensor
    | selectattr('state', 'eq', 'Online')
    | list
    | count
}}
#

but this shows all other sensors that are Online too, not just my steam sensors

#

is there a way to narrow it down to just the steam sensors?

peak juniper
#

ok I got it for anyone interested. I a made a group with all my sensors in and used the following:

{{ states | selectattr('entity_id','in',state_attr('group.steam_friends','entity_id')) | selectattr('state','eq','online') | list | count }}
ivory delta
#

I feel like some variation on this would work without you having to create groups. I just can't get it to return the entity ID's at the end ๐Ÿคฆโ€โ™‚๏ธ
{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list }}

#

I get a list of booleans at the end instead of a list of names ๐Ÿ˜ฆ

#

Oh... but you just want a count anyway...

#

{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list | count }}

#

Tweak the regex as needed.

#

And if you don't want it to evaluate on every state change, narrow it down to states.sensor like in your version, @peak juniper

peak juniper
#

brilliant - thanks @ivory delta

ivory delta
#

No problem. It was a fun learning exercise for me. I need more practise with templates ๐Ÿ˜„

knotty dagger
#

Hi all. I have a temperature sensor which always runs a little hot. If I want to drop it by say 7 degrees, what is the format for that if its current value template is:

#

value_template: '{{ value_json.temperature | round(1) }}' ?

next elm
#

Anyone know off-hand of a way to convert a timestamp to "minutes since timestamp was set"?

#

I have a ton of sensors/templates/automations that depend on the old Uptime sensor implementation, which just gave the number of minutes since HA was last restarted, so I need to emulate that prior to upgrading in order to keep everything from breaking the second I update.

mighty ledge
#

what was the state of it?

#

was it a datetime or number in minutes or hours?

next elm
#

Previously, it was just straight up number of minutes (which is what I need)

#

Like, my HA instance currently reports an uptime to "2136" minutes

#

After updating, HA will just timestamp when it started, and leave it at that. I still need to be able to find the number of minutes since the date/time in the timestamp, though

mighty ledge
#

ok, you'll have to implement the uptime integration and perform this calc: "{{ (as_timestamp(now()) - as_timestamp(states('sensor.uptime'))) / 60 | round(0) }}"

next elm
#

I'll give that a test now ๐Ÿ™‚

#

Thankfully I can test this before the update by using a helper to store a static timestamp

#

Well, that works, but round(0) isn't rounding the number to 0 decimal places.

mighty ledge
#

what version of HA are you on?

next elm
#

Getting a full 12 decimal places after the number

#

0.118.5

#

Last before the update that'll break the uptime sensor

mighty ledge
#

well, if you go to 0.119 you won't need to do anything

#

well, sorry

next elm
#

Fixed it
{{ ((as_timestamp(now()) - as_timestamp(states('input_datetime.last_start'))) / 60) | round(0) }}

mighty ledge
#

"{{ ((as_timestamp(now()) - as_timestamp(states('sensor.uptime'))) / 60) | round(0) }}"

next elm
#

Needed the extra parenthesis

mighty ledge
#

there was an error

#

yea

next elm
#

This'll do the trick for now. I have a lot of stuff that has a "uptime > 3 minutes" condition built-in to keep things from triggering incorrectly while HA starts up.

next elm
#

Hmm...ok, so everything is working, but excluding the new "sensor.uptime_minutes" sensor from history/recorder doesn't work

#

Still recording the state every 60 seconds

mighty ledge
#

if it's in the database you'll have to wait 24 hours before it's removed

next elm
#

Oh, it was excluded from the get-go

mighty ledge
#

then you have a typo

next elm
#

Double-checked... nope...
Sensor entity name: sensor.uptime_minutes
Exclusion:

  exclude:
    entities:
      - sensor.uptime_minutes
recorder:
  exclude:
    entities:
      - sensor.uptime_minutes```
#

Still recording ๐Ÿ˜•

mighty ledge
#

do you have duplicate recorder or history sections?

next elm
#

Restarting HA, one moment...

#

Nope, just those

#

There are other excluded entities in the lists, but I truncated them for the sake of brevity. The other exclusions appear to work.

mighty ledge
#

not sure what to tell you. There's nothing special with that sensor.

next elm
#

Yeah, it's just a template sensor I created

mighty ledge
#

if other things are excluded, then it should be as well is what I'm trying to say.

next elm
#

Yeah, not sure. All other entities in the list of exclusions aren't recording history, but this one still is..

mighty ledge
#

you're not going to have an integration like that only work on a 'few' entities

#

what's your definition of recording history?

next elm
#

I click the entity, it shows a line graph that's updating every 60 seconds

#

Other excluded entities just show "No state history found."

mighty ledge
#

so is it climbing or not?

next elm
#

it's climbing

mighty ledge
#

Not sure what to tell you then

#

recorder handles the recording

#

history handles the display

next elm
#

Well, it should be excluded from both, but it's not ๐Ÿ˜•

#

Guess I'll update, see if it clears up, and if not start looking into bug-hunting

mighty ledge
#

then it's one of the following issues: Spelling error (which you claim its not), bad configuration (which you claim its not)

next elm
#

I mean, i copy-pasted directly from the entity / config

#

So if it were a spelling error, it'd be there

mighty ledge
#

paste bin the sensor config