#templates-archived

1 messages ยท Page 148 of 1

inner mesa
#

You missed the |float

visual gust
#

so value_template: "{{ states('sensor.weather_wind_dir') }|float }" and not value_template: "{{ states('sensor.weather_wind_dir') }}" ?

inner mesa
#

You did it in the first one

visual gust
#

dooh yes saw it now

#

btw... the file is saved as UTF-8 but i cant use the special danish chars we have in the alphabet ( ร† ร˜ ร… ) they are replaced with ? so the wind directions look stupid

#

have i made another fail?

visual gust
#

figured it

zenith junco
#

@buoyant pine - Just wondering if you had any time to look at that MQTT integration for that json output from whatsminer

urban token
#

Curious if anyone has a template that will show on the sidebar when the front door is locked or unlocked....

buoyant pine
#

@zenith junco yeah, i sent you some DMs on sunday

zenith junco
#

Oh... Shoot I didn't see them, it didn't flag it as message waiting for me. I'll take a peek. Thanks much

#

Wow - that is awesome - I'll work on it tonight

buoyant pine
#

i was wondering if i had just scared you away ๐Ÿคฃ

zenith junco
#

Nope, just never saw it, Very excited!

buoyant pine
#

unfortunately i have no way of testing it, so if there are issues, i'll be relying on you for logs

zenith junco
#

Sounds good!

urban token
#

Figured one out...

  - platform: template
    sensors:
      front_door_status:
        friendly_name: "Front Door Status"
        value_template: >-
          {% if is_state('lock.front_door', 'locked') %}
            Locked
          {% else %}
            Unlocked
          {% endif %}
buoyant pine
#
value_template: "{{ states('lock.front_door').title() }}"
urban token
#

you made it easier haha

#

i added this to my raw config for my sidebar. The status changes from locked to unlocked just fine, but I want to add an icon to change based on locked/unlocked.

    <li>
      The front door is {{states('sensor.front_door_status')}} {{'\U0001F512'}}
    </li>
silent barnBOT
main spade
#

lmao

#

This is probably really easy but i'm missing something.
I'm trying to provide a local image to the TV notification service, but i believe the output is missing quotes.

#

path: '{{state_attr(''camera.front_door'', ''entity_picture'')}}'

#

turns to

         /api/camera_proxy/camera.front_door?token=xyz```
#

I believe /api/camera_proxy/camera.front_door?token=xyz needs to be surrounded in "" quotes. How can I do this in the template?

#

ah nvm i think the issue is that my path is not public?

marble jackal
urban token
#

Yeah.. icon works.. Just tried that code snippet and it doesnt seem to work though

marble jackal
#

I assume you changed the 2nd icon to something actually existing, and not the gibberish I've put there

tawny coral
marble jackal
#

which template, there are 3 of them?

#

And did you check them in devtools > templates

tawny coral
#

the first one

#

ugh i just found it. it's incorrect indentation, not comma. I'm using the file editor add-on

marble jackal
#

BTW, you could simplify them if you use an `{% else %} to default to the most frequent option

#

eg the last one could be:

          {%- if is_state("input_select.vent_vsr500_mode", "High") %} 
            4
          {%- elif is_state("input_select.vent_vsr500_mode", "Medium") %} 
            3
          {%- else %} 
            2
          {%- endif %}
tawny coral
#

Hmm there still seems to be an issue with the ventilation get mode

marble jackal
#

You did not define a result for some of the options in the ventilation get mode

#

If you format your template like I did, it would be clear immediately

tawny coral
#

hmmm ok i think i see it. It's the ones with the switch in them

urban token
silent barnBOT
tawny coral
#

Right, thanks ๐Ÿ˜„

marble jackal
#

Whoops :), well look at the link

urban token
#

I had a typo.... worked @marble jackal thanks!

marble jackal
#

You had state instead of is_state

tawny coral
#

argh it's still saying i have an issue

#

Invalid config for [automation]: [data_template] is an invalid option for [automation]. Check: automation->action->0->target->data_template. (See /config/configuration.yaml, line 9).

marble jackal
#

Well, data_template is already depreciated for ages now

tawny coral
#

what should be used instead?

marble jackal
#

data: and you should remove 2 spaces in front of it, you now placed it under target:

tawny coral
#

i see it

marble jackal
#

also remove 2 spaces in front of option: and leave the template where it is. It should be intended 2 spaces

tawny coral
#

it's becoming worse hehe

Invalid config for [automation]: template value should be a string for dictionary value @ data['action'][0]['data_template']. Got None. (See /config/configuration.yaml, line 9).
marble jackal
#

Well, if you renamed data_template to data, then this is about another automation

#

I see you did not do that

#

Check the template in devtools > template

#

it probably doesn't give a result

#

the first error is the old one

tawny coral
#

testing it now. And yeah it's complaining about a missing paretheses

#

fixed that

#

now it seems to give a result. i didn't know about the template developer tool

marble jackal
#

Well, now you do ๐Ÿ™‚ Really nice to build your template there before you add it to your config

tawny coral
#

yeah absolutely

distant plover
#

How do I get 20:00 from 2022-01-28T20:00:00Z ?

mighty ledge
lime radish
#

How can I use the value of an input select in an automation ?

#

I know about is_state but I want the value and not checking each value

distant plover
buoyant pine
#

states() @lime radish

mighty ledge
#

for example, post the full attempt you have there, because it's close

buoyant pine
distant plover
#

{{state_attr('sensor.something', 'Pickup start') | timestamp_custom('%H:%M:%S')}}

glossy aurora
#

So i wanna use my last called alexa, i got a sensor that states the last used alexa (sensor.last_alexa)

mighty ledge
glossy aurora
#

now i wanna use the notify service but
notify.{{states('sensor.last_alexa')}} doesnt work

distant plover
mighty ledge
#

I.e. look at the alexa_media_player docs

#

don't use the offical docs because alexa media player is custom

mighty ledge
#

so you have to convert it to a timestamp (which is an integer)

glossy aurora
#
    - service: notify.{{states('sensor.last_alexa')}}
      data:
        message: ok
        data:
          type: tts

#

before i used a set echo via

mighty ledge
glossy aurora
#
  • service: notify.echo_kitchen
    data:
    message: ok
    data:
    type: tts
distant plover
glossy aurora
#

notify.{{states('sensor.last_alexa')|string}} returns notify.media_player.uhr

#

as a string

mighty ledge
#

does notify.media_player.uhr look like a valid entity_id?

glossy aurora
#

oh

#

yickes

mighty ledge
#

yep

glossy aurora
#

mb gotta look at the sensor again

#

ty

mighty ledge
silent barnBOT
glossy aurora
#

forget about that

#

had to switch from media_player to alexa_media aswell

little lion
#

i have used the {{trigger.to_state.name}} field to let me know which device triggered a automation however i have a automation set up that when my people group is not_home to check all my door sensors and if one of them open to alert me. how would i do the same type of thing but reference a condition instead of a trigger??

inner mesa
#

as in which condition was true? conditions are "and" by default

little lion
#

yeah

inner mesa
#

and with a more complex condition, there's no straightforward way to identify the thing that caused it to be true because it's a condition and not a trigger

little lion
#

gotcha. yeah basically i just have a simple automation when everyone leaves, check if all the doors are closed, if 1 door is open send me a notification telling me a door is open. it would be awesome if it could tell me "which" door is open

inner mesa
#

you can do that with a choose: or a template in the action

silent cobalt
#

You'd have to do it in the body of the script. Use a choose block. If all doors are closed, do your thing, else figure out which door is open and notify.

inner mesa
#

a template would be straightforward and could be embedded directly in the notification

silent cobalt
#

Absolutely. Both work.

little lion
#

i dont see a choose section or anything on the template literature?

silent seal
#

Choose is an action

little lion
#

alright thats where im reading currently

silent cobalt
#

Quick question for you all. What is the scope of variables set in templates? (e.g. {{ set b = 0 }}.

I try to do a loop that ramps up brightness to a light fixture over time. I'd really like to have a variable that is the current brightness and just increment that by a step value until it exceeds a max. I tried doing that with {%...%} syntax but am getting undefined errors.

buoyant pine
#

local scope

mighty ledge
#

however, the scope will still be limited to the loop only if you define the variable inside the loop

#

looping like that has to be done with the repeat action

silent cobalt
#

Makes sense. So can I modify a script variable within a template statement?

#

Or is there any other way to modify an existing script variable?

mighty ledge
#

You can't overwrite what's passed to the script

#

so, just create a new variable

#

using a variables action

silent cobalt
#

Yeah, I'm not passing anything to the script, just defining some vars via the variables statement. Can those then be modified later in the script somehow (template or otherwise)?

topaz cave
#

Hi there, I'm trying to trigger an automation with the following template code but can't seem to get it working, any ideas what I'm doing wrong?

platform: template
value_template: >
  {%- set output = namespace(sensors=[]) -%} 
     {%- for state in states.sensor | selectattr('attributes.device_class', '==', 'battery') -%}
       {%- if 0 <= state.state | int(-1) -%}
         {%- if state.state | int <= 20 -%}
           true
         {%- endif -%}
       {%- endif -%}
     {%- endfor -%}
mighty ledge
#

that won't return true/false

#

that will return true, true, true, true, true

#

also your if statement for 0 <= state seems suspect, that's going to always resolve true unless the state is invalid

plucky wyvern
#

Hi, sorry for Interruption your chat. I have a issue with my garage door. I have created a

- platform: template
    covers:
      garage_door_left:
        device_class: garage
     # ...

It's working so far, Only thing what's annoying is that when I open the door and let's say after 2 seconds I stop it. I can't click open (up arrow) because it's greyed out

topaz cave
#

Thanks @mighty ledge, I'll try to work out how to return true/false.

mighty ledge
mighty ledge
silent barnBOT
topaz cave
mighty ledge
#

@plucky wyvern all those output states are incorrect for value_template

plucky wyvern
# mighty ledge

Ok cool. I will have a look at that. Thank you very much ๐Ÿ™‚

mighty ledge
#

np

#
platform: template
value_template: >
  {%- set output = namespace(sensors=[]) -%} 
     {%- for state in states.sensor | selectattr('attributes.device_class', '==', 'battery') -%}
       {%- if 0 <= state.state | int(-1) <= 20 -%}
         {%- set output.sensors = output.sensors + [ state ] %}
       {%- endif -%}
     {%- endfor -%}
  {{ output.sensors | length > 0 }}
#

keep in mind, it will only trigger when you go from zero low batteries to n low batteries. Each additional battery will not trigger this.

#

@topaz cave

#

lovelace doesn't accept templates and if it did, you're missing the outside quotes

plucky wyvern
# mighty ledge your value_template doesn't account for that state then

Sorry, I don't know what I am doing wrong. At the moment my code looks like this:

value_template: >-
          {% if is_state('binary_sensor.garagentor_links_auf_status','on') %}
            open
          {% elif is_state('binary_sensor.garagentor_links_zu_status','on') %}
            closed
          {% endif %}

I have two sensors for open and closed as you can see. How can I tell HA the middle state?

mighty ledge
#

you have 4 cases

#

on-on, on-off, off-on, and off-off

#

I would wager that on-on is impossible

#

so you only have 3 cases you need to check

plucky wyvern
mighty ledge
#
{% set auf = is_state('binary_sensor.garagentor_links_auf_status','on')  %}
{% set zu = is_state('binary_sensor.garagentor_links_zu_status','on') %}
{% if auf and not zu %}open
{% elif zu and not auf %}closed
{% elif not zu and not auf %}opening
{% else %}none
{% endif %}
plucky wyvern
mighty ledge
onyx juniper
#

Hi guys,
I'm currently trying to dimm some light's. Since there are multiple of them I added their names to a input_select. And then build a template_light around that. Now I need the template_light to accurately report the current brightness level of the selected light. I just can't seem to figure out how to get it.
- platform: template lights: lichter_unten: friendly_name: "Lichter unten" level_template: ?? turn_on: service: light.turn_on target: entity_id: "{{states('input_select.lampen_unten')}}" turn_off: service: light.turn_off target: entity_id: "{{states('input_select.lampen_unten')}}"

marble jackal
#

@onyx juniper "{{ state_attr(states('input_select.lampen_unten'), 'brightness') }}"

onyx juniper
#

Thank you @marble jackal , that did the trick ๐Ÿ™‚

acoustic wedge
#

That did it. Thanks. I'm now trying to get the friendly names of the sensors in sensors to use in the action (notification) part.

upbeat delta
#

hi all How can i convert the below text into 2 switches in home assistant using Json??
tele/GNSPanel01/RESULT {"NSPanel":{"ctype":"group","id":"1","params":{"switch":"on","switches":[{"switch":"on","outlet":0}]}}}
tele/GNSPanel01/RESULT {"NSPanel":{"ctype":"group","id":"1","params":{"switch":"off","switches":[{"switch":"off","outlet":0}]}}}
tele/GNSPanel01/RESULT {"NSPanel":{"ctype":"group","id":"2","params":{"switch":"on","switches":[{"switch":"on","outlet":0}]}}}
tele/GNSPanel01/RESULT {"NSPanel":{"ctype":"group","id":"2","params":{"switch":"off","switches":[{"switch":"off","outlet":0}]}}}

marble jackal
dull bloom
#

Hey, not sure how to search for the answer to this so thought human interaction might get faster results... What is the [[[ ]]] notation for in templating?

mighty ledge
#

if you don't have those custom items, then those templates are meaningless to you

silent barnBOT
dull bloom
inner mesa
tired sandal
#

Hey folks, quick question - can set a variable in the middle of a template?

I know I can do

{% set foo = "bar" %}
{{ foo }}

But what do I do if that's a place that's expecting just a print statement?

#

(for example, a template sensor)

Can I do this?

  value_template: >-
    {% set foo = "bar" %}
    {{ foo }}
marble jackal
#

Yes, that works fine

tired sandal
#

it wasn't working for me, but I think maybe I was doing something wrong, then

#

Cool, thanks - by the way, is there a way to make HA re-reat the state of certain sensors without restarting HA?

#

i.e: If I want to make changes to my template sensor, restarting HA multiple times is somewhat tiresome.

marble jackal
#

Reload template entities from server settings

tired sandal
#

I don't have that option

marble jackal
#

It should be there, as long as you had at least one template entity the last time HA started

tired sandal
#

I have

  • Location & customizations
  • Automations
  • Groups, group entities, and notify services
  • Input booleans
  • Input date times
  • Input numbers
  • Input selects
  • Input texts
  • People
  • Rest entities and notify services
  • Scenes
  • Scripts
  • Timers
  • Zones
#

I'm running Home Assistant 2021.12.8

marble jackal
#

Well, except for the first one they are ordered alphabetically, it should be between Scripts and Timers.
But are you sure you already have a working template entity?

tired sandal
#

I mean, I thought so...I have a "working" template sensor that's pulling in data (albeit the wrong data)

#

is there a way to check?

marble jackal
#

That should do the trick. Not what's the issue with the wrong data?

tired sandal
#

Oh, y'know what...I'm an idiot ๐Ÿคก

#

I don't have any template sensors

#

I have a rest sensor that's using templates to manipulate the data

#

๐Ÿคก

marble jackal
#

Then you should reload Rest entities and notify services

tired sandal
#

Yeah :p

#

Though, saying that - the data I'm getting back from it still doesn't make sense.

#

So, here's my REST sensor:

- platform: rest
  resource_template: "https://www.republicservices.com/api/v3/holidaySchedules/schedules\?latitude\={{ state_attr('zone.home', 'latitude') }}\&longitude\={{ state_attr('zone.home', 'longitude') }}"
  name: 'trash_holidays'
  json_attributes_path: '$.data'
  value_template: "OK"
  json_attributes:
    - date
    - description
    - name
    - specialNotes
#

I would expect the value of that sensor to be "OK"

#

Right now it's showing (probably stale) data from the API endpoint.

marble jackal
#

With value_template: "OK" I would also expect that

tired sandal
#

I should point out - those escape sequences in that URL are wrong, so I've fixed that...but it's still not getting me "OK"

marble jackal
#

So if you put that template in devtools > templates and paste the result in your browser, you get some json?

#

The resource_template

tired sandal
#

yeah

#

The "states" tab in dev tools is showing me stale JSON data again

#

I'm also seeing errors in my logs that don't make sense

#

Template variable error: No first item, sequence was empty. when rendering '{% set date = value_json.data | map(attribute="date") | map('as_datetime') | select('gt', now()) | list | first %} {{ (value_json | selectattr('LOB', 'equalto', 'Residential') | selectattr('date', 'search', date.isoformat().split('+')[0]) | first).name }}'

#

I previously had that code in value_template to parse the JSON returned from the server, bu tI took it out for debugging and HA seems to think it's still there.

#

I'm running HA in a container - I wonder if my updates to the config are somehow not being persisted into the container

#

Nope, looks like it's there.

marble jackal
#

Maybe a silly suggestion, but did you save your changes before reloading?

tired sandal
#

Yeah I did

#

...offs.

#

I was editing config/sensors/date.yaml

#

The actual sensor being referenced is in config/sensors.yaml

marble jackal
#

๐Ÿ˜…

tired sandal
#

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

#

Please excuse me while I move to mongolia, where I will live out the rest of my life as a goat.

marble jackal
#

๐Ÿ

tired sandal
#

Anyway - one actual question I did have....in what order are the manipulations applied?

#

So, I can obviously manipulate the data returned using value_template

#

...but also the values returned using json_attributes

#

The API returns something like this:

{
  status: 200,
  data: []
}
#

I'm tweaking my value_template so that it filters the $.data and gets the first result, but I'm not sure in what order those two things affect each other if that makes sense

#

So, if I make my value_template return an object, will that break json_attributes?

marble jackal
#

I don't have experience with these sensors, but I would say the value_template is what the state of the entity will be. It has no effect on the attributes

tired sandal
#

Right, but I'm trying to figure out if value_template gets fed the output from json_attributes or the other way round

marble jackal
#

Neither I think. For the value_template you can use all the data in the json (and even other data from HA). The attributes are a select part of the json data

#

But again, based on no experience with these kind of sensors ๐Ÿ˜Ž

#

But as the attribute data is a part of the full json data, you can use the attributes in your value_template

tired sandal
#

gotcha.

#

so what's the point of json_attributes then?

marble jackal
#

To provide attributes to your entity

tired sandal
#

Wait....so json_attributes provides the actual attributes and value_template provides the actual state value.

#

...oh.

#

I mean, I guess it was kind of obvious but...

#

For some reason, I thought they both provided the state attributes.

#

I take it, one can't manipulate the json_attributes?

marble jackal
tired sandal
#

Okay? Why might I do that?

marble jackal
#

Because that might be the value you're interested in instead of the complete dict

#

It was just an example

tired sandal
#

Gotcha.

#

Yeah - so this is the website of the company that does my trash pickup.

#

That status will likely never be anything other than 200

#

data is a list of upcoming holidays and whether or not it affects trash pickup

#

lemme get you an example

silent barnBOT
tired sandal
#
[
  {
    "date": "2022-01-01T00:00:00.0000000Z",
    "description": "Your pickup will be delayed by one day due to the holiday.",
    "name": "New Year's Day",
    "specialNotes": ""
  },
  {
    "date": "2022-05-30T00:00:00.0000000Z",
    "description": "Your pickup will be delayed by one day due to the holiday.",
    "name": "Memorial Day",
    "specialNotes": "Service will be on a one day delay due to the Holiday this week. Please place your cans out by 7 A.M. the day after your normal scheduled pickup day. Happy Memorial Day from Republic Services."
  }
]
#

There.

#

So, right now I'm getting back New Year's Day because it's the first element in the list.

#

Really, what I want is Memorial Day because New Year's day is passed and I don't care about it.

#

Thinking about this some more, perhaps it would make sense for the value to simply be true or false to indicate whether or not there is a disruption. And then, the state attributes to contain the dict explaining what the interruption is.

#

The only issue is that I can manipulate the value- but not the state attributes. So I can manipulate the value to search for the entry I want that's after today...but there seems to be no way to do that for the attributes.

marble jackal
#

Do the attributes provide a list with all data in the json data?

sonic nimbus
#

is this automation is ok?

#

I want to try for first time trigger.id in automations..

marble jackal
sonic nimbus
#

but there is some kind of error, if I put just this in my yaml file

#
    - platform: time
      at: "00:00:00"
      trigger_id: "on"
    - platform: sun
      event: sunrise
      trigger_id: "off"
  action:
    - service: >
        light.turn_{{trigger.id}}
      entity_id: light.bedroom_wall_wled```
marble jackal
#

But you can template the entire data section:

data: >
  {{ {} if trigger.id == 'off' else { 'brightness': 1 } }}
marble jackal
sonic nimbus
#

I fixed it..instead of trigger_id it needs just id

#

thanks, I will try this script

tired sandal
marble jackal
tired sandal
#

..wouldn't it?

marble jackal
# tired sandal I mean, they could - why?

Don't know, but if you have the data of more than just the first date, you can use templates to actually get the information you want (like the next date the pickup date will be different)

marble jackal
#

By use of templates

tired sandal
#

But you can't use templates with the attributes

#

only the value

#

...y'know what?

marble jackal
#

Not in the sensor itself, but you can create an actual template sensor (the ones you can reload with the template entities button) based on that data

tired sandal
#

Yeah - what about this for an idea

#
  1. I screw with the value_template to represent the next holiday date.
  2. I then use that date in a template sensor to query the data and pick out the stuff I need.
#

Does that seem like a reasonable way to do this?

marble jackal
#

Well, 1 should not be a big problem to actually achieve though

tired sandal
#

Yeah. I already have the code to do that (more or less)

tired sandal
#

If I have a REST sensor - can I use templates inside json_attributes_path?

inner mesa
#

json_attributes_path string (optional)

#

no

tired sandal
#

๐Ÿ˜ฆ

#

The problem right now then is that json_attributes_path gets the wrong data

inner mesa
#

make a template sensor out of it:

#

attributes map (optional)
Defines templates for attributes of the sensor.

attribute: template template REQUIRED
The attribute and corresponding template.

tired sandal
#

Right, but that still doesn't really solve anything

inner mesa
#

why?

tired sandal
#

...let me rephrase - I can't figure out a way to make that work

inner mesa
#

you wanted a template, and that lets you use a template

tired sandal
#

Right, but I want a dictionary and afaik you can't have a dictionary as the state value....can you?

inner mesa
#

correct. states are strings

#

still not following why that doesn't help you

tired sandal
#

Because I need a way to store the dictionary. Seemingly I can only do that in state attributes, and I can't find a way to set arbitary attributes in state.

inner mesa
#

attributes can store any data type

#

attributes are not states

tired sandal
#

I'm aware

inner mesa
#

set the attributes however you want with a template

#

with whatever data type you want, from whatever source

tired sandal
#

So, I can use templating for state attributes in a template sensor?

inner mesa
#

"state attributes" is confusing

#

but attributes, yes. see above

tired sandal
#

Right, and I can do that without having to have one sensor for each attribute?

inner mesa
#

entities can have many attributes

#

that's why it says "map" up there

tired sandal
#

Right.

#

So that brings me to my next problem.

#

I make the REST request to get the data from that endpoint, I filter it down and extract the date of the next trash holiday

#

I need...somewhere to store the rest of the data so that I can then query that data using the date

#

So. For example..

sensor.next_trash_holiday - the state of that sensor is 2022-02-21T00:00:00+00:00

#

(I made it a datetime device class)

#

But that isn't helpful unless I can somehow store the list of objects somewhere...

inner mesa
#

in the attributes

tired sandal
#

Yeah, I tried that - I got an error.

inner mesa
#

sigh

#

ok

tired sandal
#

One sec lemme paste my code.

inner mesa
#

if you go straight to the actual problem, it will go faster

tired sandal
#

Yep. I'm getting there

#

I can only type so fast though ๐Ÿ™‚

inner mesa
#

it sounded like you just needed a template

tired sandal
#

I'm not entirely sure what I need

#
- platform: rest
  resource_template: "<URL>"
  name: next_trash_holiday
  device_class: timestamp
  json_attributes_path: '$.data'
  json_attributes:
    - date
    - name
#

I've snipped out the value_template field

#

Anyway, that gets me this error: " JSON result was not a dictionary or list with 0th element a dictionary "

#

Which is odd because as far as I know, the API response looks like this:

{
  status: 200,
  data: []
}
inner mesa
#

there's no date or time in there

tired sandal
#

Right. Each element in data is an object that has name and date

inner mesa
#

and that's a list

tired sandal
#

Yeah. It's expecting a dictionary, or list that has a dictionary as the 0th element

inner mesa
#

you see that data there is an empty list?

tired sandal
inner mesa
tired sandal
#

Yeah, maybe - I'm playing with this: https://jsonpath.com/ and just $.data seems to work - but it's likely a completely different implementation from the HA/Python one.

#

Y'know what....on that link I posted using just $.data wraps the whole thing in an array

inner mesa
#

In any case, I don't think a template is what you need here

tired sandal
#

using $.data[*] stops that happening

#

so that might be the issue

tired sandal
inner mesa
#

magic

tired sandal
#

Yeah, I was looking at the json path syntax but didn't spot that.

#

I was trying [.] etc.

inner mesa
tired sandal
#

Hmm....$.data[*] looks to have just returned the 0th element

#

I'll keep digging though

inner mesa
#

I would just have to play with it

tired sandal
#

Yeah, I was going to ask if I could play with this in the templates thingy

#

does that have a json path parser?

inner mesa
#

that's for Jinja

tired sandal
#

Thought so.

#

Wasn't sure if json path was some kind of magic run though jinja or not though

#

guess not

tired sandal
#

Ah, it seems to be working now with $.data.* but it looks like the state attributes just stores the 0th element

#

I think this is why I thought I needed a template.

tired sandal
#

...yeah - I can't get it to let me store a list in the attributes for a sensor, only a dictionary. Is there something I'm missing?

halcyon island
#

Hello all, I search an idea to make a template for make a multi price (time base) for electricity from one general counter

glossy aurora
#

so now().weekday is 0 to 6 and now().month is 1 to 12 ?

EDIT: day to weekday

marble jackal
#

And day 0 is Monday

glossy aurora
#

ty alot

marble jackal
#

now().day is 1 to 31

glossy aurora
#

mb

#

i used weekday

#

so my 0 to 6 is right

#

sorry

#

is there a delay function via templates ?

mighty ledge
#

delay what

glossy aurora
#

i wanna use it in a tts msg

marble jackal
#

How do you mean? A template can't perform an action, do there is nothing to delay

mighty ledge
#

you'll have to elaborate because that still doesn't make sense

#

if you want to delay the notification, add a delay service call before the notification

glossy aurora
#

Hi my name {%wait 2 sec%} slimshady

mighty ledge
#

that's not possible

#

I doubt any notification service would support that either

#

it'll be 2 notifications, separated by 2 seconds

glossy aurora
#

amazon polly got <break time="1s"/>

#

but i am using normal notify.alexa tts

mighty ledge
#

just send 2 notifications

#

it's tts, it doesn't care

glossy aurora
#

its rough the waiting should be done in 3 ifstates

#

so i cant really do that

mighty ledge
#

you can do that with choose

glossy aurora
#

how would that look like ?

glossy aurora
#

{{ [
'xyz.',
'zwerw.',
'twetw.',
'454353',
'234234 (HERE I WANT TO WAIT 5 SECS) 2354252'
] | random }}

mighty ledge
#

yep, you can still do that with choose

glossy aurora
#

alright will look into it

mighty ledge
#

you'll need to use variables to set up the random choice and then your actions will be based on that choice using choose

glossy aurora
#

got it

#

ty

rare panther
#

How to get the data from history and make calculation on that? For example, there is a step counter from android which stores the data as cumulative (total_increasing). How can I extract the data for , say each day? The History_Stats platform does not help as it needs a specific state and the state in this entity changes based on the steps

mighty ledge
rare panther
#

Hmm. Will use appdaemon then much simpler for me

mighty ledge
#

Iโ€™d be surprised if appdaemon has access to history unless itโ€™s a new addition

glossy aurora
#

I want more organic tts msg, so i created random answers. Now i got a script for "Interruptions" like "pardon me", "sorry to interrupt" etc.
Now I wanna use this script before other tts scripts. The problem is i cant define a static delay since every interrupt msg has a different playtime. Is there a way to check if the tts is done before doing the next tts
right now my 2 tts msg clip into each other
and i dont wanna add the interruption part to every tts msg i need . it
would be alot of copy&pasted code

#

cant I define the random part as an overall function
then just call {{ randommsg() }} in my scripts where i need it ?

#

cant check if my media player is idle or not

glossy aurora
acoustic wedge
#

Hi, can I pass a variable from the trigger template to the action in an automation? I see that I can use trigger.entity_id but what if the trigger is a template?

acoustic wedge
#

Thank you very much

#

Does that mean that if I have this in the trigger:

{%- set sensors = [ 'sensor.aqara_1', 'sensor.aqara_2', 'sensor.aqara_3' ] %}
{{ expand(sensors) | selectattr('last_changed', '<', now() - timedelta(minutes=15)) | list | count > 0 }}

I cannot use sensors in my action?

fossil venture
#

Correct.

trail estuary
#

Is there a way I can use a template to check if a specific event happened within the last minute? I found something that works for last_triggered towards an automation, but I want to check if an event coming from an actionable notification has happened in the last minute...

#

FWIW, here is the template I get to work on the automation:

{{ (now()|as_timestamp - state_attr('automation.notify_if_garage_door_is_open_at_night','last_triggered')|as_timestamp) < 60 }}
marble jackal
#

Entities have a last_changed object

trail estuary
#

But events are not entities, are they?

marble jackal
#

No, my bad, didn't read properly

#

Is it really one specific event? You can create a binary_sensor with the event as trigger

trail estuary
#

It is really one specific event. So I have an actionable notification triggered at 10pm every night to remind me to close the garage door. If I click the action on my phone to close the door, and th state still is open a minute later, I am sending a reminder notification that warns me that something might have blocked the door from closing. But I don't want the reminder notification to be sendt if I did not click to close the garage door to begin with... If that even makes sense...?

marble jackal
#

Makes sense

trail estuary
#

So I was thinking that I can put a condition in there, that only allows sending the reminder notification if the event from the notification has happened during the last minute or so

#

But, I cannot see if there is a way to check that...?

marble jackal
#

You can also use a wait_for_trigger which waits for the event, with a timeout of 1 minute, and sends the reminder on wait.completed

trail estuary
#

Hmmm... Would require some rethinking on the logic, but could work! ๐Ÿ‘

#

Thanks!

marble jackal
#

๐Ÿ‘๐Ÿผ

trail estuary
#

What ended up working was your inital idea of using the template binary sensor with an automatic 65s timeout... That way, when the minute (wait/delay) has passed, if the sensor is on, the reminder is sent. It works perfectly! ๐Ÿ™‚

rare panther
fading patio
#

Morning all! Trying to take an attribute from Sonoff S31 for power and current into its own sensor. The values shown in Developer are floats like 0.08 and 5.11.
This isn't working. Hopefully something simple for you all.

  - sensor: 
    - name: Wheelchair Charger Plug Power
      state: '{{ switch.sonoff_10011f94d9.attributes.power | float }}'
      unit_of_measurement: 'Watts'
      state_class: measurement
    - name: Wheelchair Charger Plug Current
      state: '{{ switch.sonoff_10011f94d9.attributes.current | float }}'
      unit_of_measurement: 'Amps'
      state_class: measurement
marble jackal
#

Good afternoon

#

You should use state_attr('switch.sonoff_10011f94d9', 'power')

#

And casting it to a foat is useless, as the state will be a string anyway

fading patio
#

tried that and studio code gave error red squigly

#

lemme get message

marble jackal
fading patio
#

unexpected scalar at node end

marble jackal
#

probably because you also use single quotes outside your template

#

use different ones inside and outside the template (I always use double quotes outside, that's why I used single quotes in my example above)

#

What you had is advised against, and you should have put states. in front of it

fading patio
#

ahh so states.switch.[..]

#

ok double quote resolved the error...restarting

#

GG, worked like a champ using first example. Thanks!

marble jackal
#

You dont't have to restart, you can reload template entities from server controls

hollow girder
#

hello I would like to pull a topic to a sensor state, and every 10 seconds refresh the sensor, and when I do that I would like to retrive the current sensor:

#
- trigger:
    - platform: mqtt
      topic: "room_presence/+"
      payload: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-100-1"
      value_template: "{{ value_json.id }}"
    - platform: time_pattern
      seconds: "/10"
  sensor:
    - name: Room Updates
      state: >
        {% if trigger and trigger.topic %}
          {% set sensor = trigger.topic.split('/')[1] %}
        {% else %}
          {% set sensor = this.state %}
        {% endif %}
        {{sensor}}
#

this works with the mqtt trigger, but when I get the time trigger I get a error

#

"'this' is undefined"

#

is there a way to retrive the current state and the current entity_id?

inner mesa
#

"this" is for information about an automation or script, not a specific instance or trigger

hollow girder
#

so we can't use the this in the template of a sensor

inner mesa
#

I don't know what it would represent there. If it's saying that it's not defined, no

#

you can just use states('sensor.xxx')

hollow girder
#

yes, no defined

#

ok, tks @inner mesa

dull aspen
#

I want to show the week number in a lovelace dashboard. I suspect i can do this setting up a Template sensor.
Anyone have any idea how i would do this?

marble jackal
tired sandal
#

Wonder if someone can help me at all. I have an API endpoint that returns a list of data. I'd like to load the one element from that list into state attributes based on a criteria (rather than just the first element, which seems to be the default). How do I do this?

#
{
  data: [
    { "date": "2022-01-01", "name": "Event 1" },
    { "date": "2022-02-09", "name": "Event 2" },
    { "date": "2022-03-14", "name": "Event 3" },
  ],
}
#

Right now, if I point json_attributes at $.data for json_attributes_path it'll just load $.data.0 into state attributes, and there doesn't seem to be a way to control that behavior.

#

I can write code to manipulate the sensor value, but that doesn't really get me anywhere because that can only ever be a single value.

marble jackal
#

Which one do you want?

lapis lynx
#

Is there a standard as to how your .yaml files should be, what to include where, how to reload on that part etc etc. I keep meaning to tidy stuff up and I never get around to doing it. My configuration.yaml is a mess. I only recently made a templates.yaml file and even then I'm not sure what actually goes into it? Right now I'm about to create a rest sensor and I've no idea where I should put it..

hollow girder
#

hello all! I have several warnings in my config, most of them on boot time, that say "{{ states('sensor.time')|as_timestamp }}", got invalid input 'unknown' when rendering template. I know the reason, just don't know the best way to solve this. I tried default, but does not assume "unknown" as a rigger to default. What is the best way to solve this that does not need me to add a bunch of lines to my yaml checkig all as_timestamp if the variable is loaded or exists?

mighty ledge
marble jackal
#

and you might want to use now() instead of states('sensor.time')

hollow girder
#

That was not my question... I would like to know if there is a default equivalent that matches unknown.

hollow girder
marble jackal
#

Well {{ states('sensor.time') | as_timestamp }} gives null for me in devtools > Templates

#

So I doubt that is what you want

hollow girder
mighty ledge
#

so that will always return none

#

null/none

hollow girder
#
template:
  - trigger:
      - platform: time_pattern
        seconds: "/10"
    sensor:
      - name: "time"
        state: "{{now()}}"

mighty ledge
#

anyways, to explicitlly answer your question: none is what you want to use

hollow girder
#

i only use this sensor to trigger the refresh in some sensor every 10 seconds

mighty ledge
#

ah, you're using a template sensor to create sensor.time, not the built in sensor.time

#

that explains it

hollow girder
#

the problem is when HA is starting the sensor is not loaded... and I get a lot of warnings

mighty ledge
#

yes, see my response

#

i've given the answer like 3 times now

mighty ledge
mighty ledge
hollow girder
#

yes i've seen it... tks... I was replying to @marble jackal

#

thank you both

marble jackal
#

I assumed you were referring to the standard sensor.time created by the platform: date_time sensor. ๐Ÿ™‚

#

Which I had in my config

lapis lynx
buoyant pine
#

potentially many or none

#

depends on the sensor platform and if it supports hot reloading. templates do for example, so reload templates would reload any template sensors in that file

lapis lynx
#

Ah got ya! So it actually doesn't matter what sensors are in the file it will only reload the platform that supports it, eg templates? I don't see rest listed so I assume it's not supported

buoyant pine
#

it is

#

but not until after you've already added it to your config

mighty ledge
#

and restarted

buoyant pine
#

(which is the case for anything that supports hot reloading)

lapis lynx
#

Oh so the button will actually appear once I've created something that uses it (and restarted HA)?

mighty ledge
#

may appear

#

depends on the integration

#

and the platform that it's using

#

add -> restart -> check if button exists, if yes, use button, if no, cry

#

however, some integrations allow for a reload service, but the button does not exist in the reload page

lapis lynx
#

I'll give it a go and hope I don't cry!

mighty ledge
#

it's inevitable with HA

inner mesa
#

Tears of joy, maybe

mighty ledge
#

that's not valid template syntax

#

even though you deleted it

thick prawn
#

how

mighty ledge
#

how what

thick prawn
#

to make it lool like soloam sent erlier

mighty ledge
#

you can't

thick prawn
#

... well this wil do.

#
        sensor_type: server_power_readings
        unit_of_measurement: "W"
        value_template: '{{ ilo_data.present_power_reading }}'```
mighty ledge
#

you mean format?

thick prawn
#
HP ILO Power Usage 2
(166, 'Watts')```
mighty ledge
#

3 back ticks before and after

#

`

#

that's a backtic

#

3 before your code

#

3 after

thick prawn
#

nice

mighty ledge
#

anyways, your '{{ ilo_data.present_power_reading }}' isn't valid

thick prawn
#

oo ?

#

why so?

mighty ledge
#

explain what you expect it to do

thick prawn
#

the config.ya... is:

        sensor_type: server_power_readings
        unit_of_measurement: "W"
        value_template: '{{ ilo_data.present_power_reading }}'```
output is:
```sensor.hp_ilo_power_usage_2
HP ILO Power Usage 2
(166, 'Watts')
#

i want a pure result i can input in energy tab

#

was that understandable?

mighty ledge
#

not at all

thick prawn
#

would be easy to send pickture but..

mighty ledge
#

everything about that configuration is wrong

#

unless you aren't using the normal template sensor

thick prawn
#

nono i have a platform and host.. just sent the data i have trouble with

mighty ledge
#

what integration

thick prawn
#

hp_ilo

mighty ledge
#

ok, so then that is a valid template

thick prawn
#
    host: XXX.XXX.XXX.XXX
    username: XXXX
    password: !secret ilo_password
    monitored_variables:
      - name: Power Usage 2
        sensor_type: server_power_readings
        unit_of_measurement: "W"
        value_template: '{{ ilo_data.present_power_reading }}'```
mighty ledge
#

whoever made that went against all HA rules and chose a random ass variable name instead of using the standards

#

is the state of the sensor (166, 'Watts')?

thick prawn
#

yes

mighty ledge
#
        value_template: '{{ ilo_data.present_power_reading[0] }}'
thick prawn
#

i want a result i can input in Energy tab. any ideas?

#

aaa

#

so close i have tried ".currentreading[0]"

mighty ledge
#

that integration is a perfect candidate for config_flow without needing templates

thick prawn
#

GR8 its exactly how i wanted it! THX

mighty ledge
#

np

pastel moon
#

Hi.. Did something change lately? This construct does not evaluate to true any more... {{ as_timestamp(now()) >= as_timestamp(states('input_text.morning')) }}

#

helper contains a datetime

mighty ledge
pastel moon
#

I suppose there are no better ways to compare this, or datetime objects?

mighty ledge
#

why even use an input_text when you have input_datetimes or just regular sensors

pastel moon
#

I found them earlier today, so yes, agree they would seem to be abetter fit, but still compares as string though

mighty ledge
#

right, but it ensures that it's a valid datetime for conversion

pastel moon
#

true

mighty ledge
#

where as there's no safety with input_text

#

and your template doesn't have safety either

#
{{ now() > states('input_text.morning') | as_datetime or now() }}
#

make sure your text datetime string contains a timezone, otherwise this won't work.

pastel moon
#

Cool! It is timezone aware, will try this, thanks!

pastel moon
#

Thanks @mighty ledge! It unlocked so much, works great ๐Ÿ™‚

thin brook
#

Hi,
I have a problem with an API answer I get. It should be json but is somehow wrong formated from the provider of the API.
What I get is:
"{"DeviceResponse":[{"DeviceID":"abc","DeviceName":"xyz","Medium":"Oil","LastUpdate":"2/1/2022 7:40:02 AM","MaxVolume":"5000","ActualVolume":"3645","ActualVolumePercent":"73","Battery":"2.7","Temperature":"33","MessData":"57"}]}"

thin brook
thin brook
thin brook
fading patio
#

is something like this legit storing to a variable to shorten the actual if/else lines:

      - name: Wheelchair Charger Status
        state: >
          {% set chg_current = (state_attr('switch.sonoff_xxxxxxxxxx', 'current') | float) %}
          {% set chg_state = states('switch.sonoff_xxxxxxxxxx') %}
          {% if chg_state == "off" %}
            Off
          {% elif chg_state == "on" and chg_current >= 0.04 and chg_current <= 0.09 %}
            Fully Charged
          {% elif chg_state == "on" and chg_current > 0.09 %}
            Charging
          {% elif chg_state == "on" and chg_current < 0.04 %}
            Idle
          {% else %}
            Off
          {% endif %}
mighty ledge
#

then your ifs would be

fading patio
#

NM, after finding one set example I now edited what I posted. I tested with templates developer and it did work

mighty ledge
#
if chg_state and ...
#

also...

fading patio
#

ahhh nice but the one i want "off"

mighty ledge
#
0.04 <= chg_current <= 0.09
fading patio
#

nice didn't know could do that with the in between

mighty ledge
#

yep

fading patio
mighty ledge
#

if not chg_state

fading patio
#

ok giving a try

#

works like a champ, thanks @mighty ledge

mighty ledge
#

np

fading patio
#

can I tie in an icon change with same logic and in the state: or do I have to replicate it under the icon:

ivory lily
#

Is it possible to get info from attributes if the attribute is an object? or an array of objects?

marble jackal
#

Yes

#

Can you give a more clear example? Maybe a copy of what is shown in devtools > states

#

If it is a lot of info, use:

#

~share

#

Hmm, bot is unresponsive

#

Well, a code share site

ivory lily
#

Yes, I'll put it on codepile... hang on...

marble jackal
#

state_atrr(entity, attribute)[1].price

ivory lily
#

Oh, nice... Works like butter (and it's case sensitive, I just found out), but you knew that. THANKS!

marble jackal
#

Everything in YAML/Jinja is case sensitive

ivory lily
#

I was hoping I could set entity_picture on a template sensor, but that seems to be impossible... Is this right? Do I need to add it in customize.yaml?

ivory lily
#

Doh... My reading skill needs an update... Thanks โ˜บ๏ธ

dusky python
#

hi =) if defining a template sensor. is there a good way of referring to the current sensor. i saw something like states('sensor.this_sensor') while googling around. but i'm not sure if that actually works or not.

mighty ledge
#

you reference the entity_id that is created by the configuration

dusky python
#

ok so there's nothing generic that you can use without knowing the entity_id within the template sensor ?

mighty ledge
#

nope

dusky python
#

ok =) thought so. thanks !

blazing burrow
#

i've been getting this error at startup for a while now:

Logger: homeassistant.components.automation.david_leave_home
Source: components/automation/__init__.py:461
Integration: Automation (documentation, issues)
First occurred: February 1, 2022, 7:49:43 PM (1 occurrences)
Last logged: February 1, 2022, 7:49:43 PM

Error rendering variables: TypeError: 'in <string>' requires string as left operand, not LoggingUndefined

i can obviously tell which automation it's coming from, but not which line... how can i debug that? what does it mean? lol

#

i'm thinking it's whenever the entities i'm referencing haven't been initialized yet (at start)

mighty ledge
#

selectattr('attributes.source_type', 'in', 'bluetooth') or selectattr('attributes.source_type', 'in', 'router')

#

left operand means the left side of the test

#

your test is: something in 'bluetooh'

blazing burrow
#

those... are strings right?

mighty ledge
#

yes, bluetooth is a string, but the left operand is not

blazing burrow
#

ok so it's as i suspected, something that hasn't been initialized

#

so maybe an "if attributes.source_type" before that?

mighty ledge
#

select('attributes.source_type', 'defined')

blazing burrow
#

ohhh

#

i didn't know that was a thing

mighty ledge
#

if that doesn't solve it, rejectattr('attributes.source_type', 'eq', none)

#

or both, with defined first

blazing burrow
#

every time i prepare to take a major update i try to clean up log stragglers so it's about that time lol

mighty ledge
#

eq may solve it

#

it depends on if the attribute exists

#

using defined and eq will definitely solve it

#

too

blazing burrow
#

seems those fixes did it ๐Ÿ‘

#

thanks!

dusky python
#

is there a variable you can get last HA restart from or similar ?

mighty ledge
#

Thereโ€™s integrations that tell you the current startup time

#

Via an entity

dusky python
#

uptime ?

mighty ledge
#

yep

dusky python
#

nice thanks . i'll check it out.

nimble spade
#

Is it possible to make a template and saving the result without without storing the initial values but only the result? in my case im reading octets from a router but converting it to megabits per second, i have no use for the original values

mighty ledge
nimble spade
#

SNMP - getting an ever increasing counter, derivative to get the change between intervals and template to turn into megabits per second

#

which results in "WAN in", "wan_in_der" and "WAN in Mbps" all getting stored in the database, of which i only need the Mbps (same goes for out)

mighty ledge
#

however, because you're using derivative as an inbetween, you're stuck using the current method you have

nimble spade
#

I guess alternatively i could just store the initial SNMP values and then convert it in my graphs / output instead

#

there's also no explanation of why it would no longer be recommended :/

north locust
#

some of my templates will fail to render in upcoming version , will they not work anymore ...?

mighty ledge
mighty ledge
nimble spade
#

guess i must have misunderstood ๐Ÿ™‚ thanks for the feedback @mighty ledge - i'll dig some more and see what i can figure out

mighty ledge
#

keep in mind, it currently only affects binary_sensor and sensor

nimble spade
#

gotcha ๐Ÿ˜‰

mighty ledge
#

and there are no plans to remove it

#

so no reason to change it

#

I.e. only change it to the new style if you need the 'new' template options

nimble spade
#

if it aint broken ๐Ÿ˜›

mighty ledge
#

exactly

spiral imp
#

I have this template that I got help on last week. It grabs the "min" value from the group of calendars. #templates-archived message
I am wondering if it is possible to get the attribute ("message") from whichever event is selected by "min"?

ivory lily
#

I'm trying to get data from attributes, but the attribute is an array of objects.
The problem is that the number of objects in the attribute varies, so I can't use "state_attr(entity, attribute)[index].key1", I need to find the index where key2 == criteria.
To be spesific, I need the price from the object where type = D. In this case, index will be 2, but it could be something else in a different sensor.
https://www.codepile.net/pile/LEnvr9E1
Is this possible?

sleek wing
ivory lily
#

Let me try...

#

Yes, now I got a list with one item, and it seems to find the right object. Thank you!

sleek wing
#

No problem. Just bear in mind you are still getting a list, so if there will be more D's you will get them all

gloomy ravine
#

hi folks, i was told you guys can help me with this it should be super simple: esentially when dishwasher starts to run I trigger this timer. all i want is know what time is the timer gonna be done. essentially sending a message with the end time (ex: dishwasher will be done by 8:34PM). something like state_attr('timer.dishwasher_timer', 'finishes_at') the whole trigger is here https://community.home-assistant.io/t/message-finishes-at-from-a-timer/387352

sleek wing
gloomy ravine
#

it says result type string

#

i even tried this: (as_datetime(state_attr('timer.dishwasher_timer', 'finishes_at')) - now()).total_seconds() | timestamp_custom('%H:%M:%S',
false)

sleek wing
#

And the value is empty? Just want to ensure myself - the attribute finishes_at exists, right?

gloomy ravine
#

well i got finishes_at from the developer/tools/States and this is what I got: duration: '1:35:00'
editable: true
finishes_at: '2022-02-02T20:38:08+00:00'
remaining: '1:35:00'
icon: mdi:dishwasher-alert
friendly_name: Dishwasher Timer

#

so yes

sleek wing
#

If you got it from states, then the retrieving should work. So if you got back to template you should see the value 2022-02-02T20:38:08+00:00 under Result type, while having this line {{ state_attr('timer.dishwasher_timer', 'finishes_at') }} in template editor.

gloomy ravine
#

yes that worked: 2022-02-02T20:38:08+00:00

#

so how do I know convert this to just time in my timezone?

#

now*

ivory lily
sleek wing
#

finishes_at is giving you time in different time zone? If so I think it would be easier to get remaining attribute and add to now()

gloomy ravine
#

ya is giving it to me in UTC. i can do that route too. same result. i thought this would be easier. any idea what would be syntex for that?

ivory lily
gloomy ravine
#

it didn't take it same result as without the formating

sleek wing
#

tbh am not good at all in converting date/time in JINJA, for me the easiest way is to use timestamps. I would do something like this:
{% set remaining = '1:35:00' %} {% set remaining_timestamp = remaining[:1] | int * 3600 + remaining[2:4] | int * 60 %} {% set now = as_timestamp(now()) %} {{ (remaining_timestamp+now) | timestamp_custom('%H:%M:%S') }}

#

I would need some help too. Am getting list of devices using filter and retrieving their states like that:
{% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | list
The problem is the state is float but am getting it as string and I need to make an average. How could I possibly convert the string to float? I tried use filters (but am not sure if it is even possible) and also use for loop, but nothing worked. Obviously | sum(attribute='state') does not work, since the result is list of strings

ivory lily
#

So {% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | float | list isn't working? (Maybe I'm missing some parentesis or twelve...)

sleek wing
#

Yeah the code is working am able to retrieve the entities and their values in a list like ['21.0', '22.0', '23.0']. But I can't summarize them since they have been retrieved as string.

#

So the code {{ therm_obj[0] is float }} returns False

ivory lily
#

OK. BTW, where can I learn this "magic" with selectattr, map, whatever?

gloomy ravine
sleek wing
ivory lily
#

WHAT! I actually helped? I'll take a virtual beer, thanks ๐Ÿ™‚

#

No, it wasn't me... Sorry!

gloomy ravine
#

you also helped! THANK YOU both

ivory lily
#

I tried...

sleek wing
spiral imp
#

The state of sensor.next_event is 2022-02-02 15:00:00. Is there a better way to strip out the time so I effectively get 2022-02-02 00:00:00? This worked but seems redundant. The end goal is to compare it to sensor.date to determine if the next event is Today.

{{ as_timestamp(states('sensor.next_event'),false) | timestamp_custom('%Y-%m-%d') | as_timestamp }}
inner mesa
#

.split(' ')[0] ~ ' 00:00:00'

mighty ledge
#

Or just convert to a local datetime and output .date()

#

| as_datetime | as_local).date()

#

Probably should add an as_date filter

#

Hmm

shy badge
#

Come I please have some help creating a sensor template? I want to create status for a machine of "Off" "Idle" "Running" based off the watts on a power monitoring socket.

#

so Off = 0W, Idle = 1-100W, Running = above 100W

spiral imp
inner mesa
#

states('sensor.next_event').split(' ')[0] ~ ' 00:00:00'

#

play with it in devtools -> Templates to get what you want

onyx totem
#

Wonder if someone can help:

I have a markdown template that shows all my power sensors by doing something like {%- for entity in states.sensor -%} ...

And I've noticed something really weird:
If I time the time that takes HA to return a static js file I get it in 30-50ms (curl <ha>/frontend_latest/250cbdbd.js)
but If I have the frontend opened on 5 tabs on my browser
Then it takes HA 5-10 seconds to return the same exact static js file
if I open some more tabs, well, you get the picture.

so, 1) how can I make the template have a custom rate-limit, so I can let it update say once every minute, not every second and avoid this
2) is this FE/webserver behaviour known? I wouldn't expect templates to have this much impact on HA HTTP server

spiral imp
#

I have the below template that correctly returns the minimum value (next event) from the entities in "event1". The entities also have a "message" attribute. Is it possible to get the "message" attribute from the entity that is "min"?

{% set event1_min = as_timestamp(expand(event1) | selectattr('attributes.all_day', 'defined') | selectattr('attributes.all_day', 'false') | selectattr('attributes.start_time', 'defined') | map(attribute='attributes.start_time') | min)  %}
inner mesa
#

not after you do the map(), but you could use that output to select from the original list

#

{{ expand(event1) | selectattr('attributes.start_time', 'eq', event1_min)|map(attribute='attributes.message')|first }}

spiral imp
#

thanks, I will probably have to get event1_min back into the same date/time format right?

inner mesa
#

You didn't manipulate it, so I don't see why

#

It does assume that there's only one item with the start_time you care about

spiral imp
#

I manipulated it in an earlier part of the template so it would be a UNIX timestamp for the min function

inner mesa
#

Bot you could re-add all those filters if you want

#

Ah, indeed

#

That's not what you did, though

spiral imp
#

the original format was was '%Y-%m-%d %H:%S:%S'

inner mesa
#

your |min is just based on the attribute

spiral imp
#

you are right, but when I execute {{ event1_min }} it returns 1643888700.0 but the input attributes are '%Y-%m-%d %H:%S:%S'. Why would that be?

#

doesn't this as_timestamp(expand(event1)...) convert to UNIX time?

inner mesa
#

because you did the conversion afterward

spiral imp
inner mesa
#

you missed the |first

spiral imp
#

yep, i was. It is now returning nothing, not error, just blank

sleek wing
#

Hi all, anyone able to help me with following? Am getting list of devices using filter and retrieving their states like this:
{% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | list
The problem is the state is string but information inside is float . How could I possibly convert the string to float? I tried use filters (but am not sure if it is even possible) and also use for loop, but nothing worked. Obviously | sum(attribute='state') does not work, since the result is list of strings

inner mesa
spiral imp
#

you are correct. I am doing that to compare with another entity but I can do that in the comparison instead. Thanks again for the help

onyx totem
#

the markdown card has a entity_id to give an entity to control renders. if I give it a timer of 30sec, it should only render the card every 30sec right?

marble jackal
sleek wing
marble jackal
#

In this case expand wasn't needed actually, because you didn't use map in your expression. This will also work.

{% set therm_obj = states.sensor | selectattr('entity_id', 'in', area_entities(area)) | selectattr('attributes.device_class', '==', 'temperature') | list %}
{{ therm_obj | map(attribute='state') | map('float', default='unavailable') | reject('eq', 'unavailable') | average }} 
sleek wing
#

Yeah I tried it right away and worked too.

marble jackal
#

expand is used when you have a list of eg entity_ids and you want the other data of the entities (like states, attributes etc)

sleek wing
#

I didn't know I can use several map filters in the same code, it bit changed my thinking about what is the purpose of map :D.

#

really appreciate your help again

marble jackal
#

No problem

atomic python
#

getting this logged, what do I need to change?

2022-02-03 10:27:48 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'int' got invalid input 'unknown' when rendering template '{% set battery_level = state_attr('sensor.downstairs_tablet_info', 'batteryLevel')|int('unknown') %} {% set battery_round = (battery_level|int / 10)|int * 10 %} {% if battery_level == 'unknown' %}
  mdi:battery-unknown
#

would changing int('unknown') to int(default='unknown') do it?

#

nope it does not

#

any ideas?

marble jackal
#

well, you first set battery_level to "unknown" (as default) and then try to do a calculation with it

#

what is the full template?

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

atomic python
#

I'm guessing it always worked but just wasn't logging the warning until recently

#

I know I had to do similar updates where I had float conversions, to float(0)

#

but not sure what the fix is here

marble jackal
#
        {% set battery_level = state_attr('sensor.upstairs_tablet_info', 'batteryLevel') %}
        {% set battery_round = iif(battery_level | is_number, (battery_level|int / 10)|int * 10, 'unknown') %}
        {% if battery_round == 'unknown' %}
          mdi:battery-unknown
        {% else %}
          {% if battery_round >= 100 %}
            mdi:battery
          {% elif battery_round > 0 %}
            mdi:battery-{{ battery_round }}
          {% else %}
            mdi:battery-alert
          {% endif %}
        {% endif %}
#

Multiple fixes possible, but this is one of them (assuming you are on 2022.2)

atomic python
#

changed warning now to None

#

[homeassistant.helpers.template] Template warning: 'int' got invalid input 'None' when rendering template

#

might just be something when HA starts, I never see it after

#

those attributes come via json from a rest sensor

#

maybe change this {% if battery_round == 'unknown' %} to or is = None?

mighty ledge
mighty ledge
#

your default should be an int, not the word unknown. unless you want to catch it.

atomic python
#

yes the new None warning is with his template

mighty ledge
#
{% set battery_level = state_attr('sensor.upstairs_tablet_info', 'batteryLevel') | int(none) %}
{% if battery_level is none %}
  mdi:battery-unknown
{% else %}
  {% set battery_level = battery_level // 10 * 10 %}
  {% set postfix = battery_level < 0 | iff('-alert', '-' ~ battery_level) %}
  {% set postfix = battery_level >= 100 | iff('', '-' ~ battery_level) %}
  mdi:battery-{{postfix}}
{% endif %}
#

or this

#
{% set battery_level = state_attr('sensor.upstairs_tablet_info', 'batteryLevel') | int(none) %}
{% if battery_level is none %}
  mdi:battery-unknown
{% elif 0 < battery_level < 100 %}
  mdi:battery-{{ battery_level // 10 * 10 }}
{% elif battery_level >= 100 %}
  mdi:battery
{% else %}
  mdi:battery-alert
{% endif %}
#

you have alot of options

atomic python
#

thx will try it right now

mighty ledge
#

the take away is: Only cast int 1 time.

marble jackal
#

@mighty ledge @atomic python I know why my template isn't working. I keep forgetting that iif evaluates both the true and false option, even though the statement is false. This will work:

        {% set battery_level = state_attr('sensor.upstairs_tablet_info', 'batteryLevel') %}
        {% set battery_round = (battery_level|int / 10)|int * 10 if battery_level | is_number else 'unknown' %}
        {% if battery_round == 'unknown' %}
          mdi:battery-unknown
        {% elif battery_round >= 100 %}
            mdi:battery
        {% elif battery_round > 0 %}
            mdi:battery-{{ battery_round }}
        {% else %}
           mdi:battery-alert
        {% endif %}
#

also removed the nested if, which was not needed

royal rampart
#

soooo I guess I can't put off upgrading my fan templates any longer...

mighty ledge
#

why...

royal rampart
#

cos I just upgraded and the old ones are making complaints

silent barnBOT
royal rampart
#

lol, so yeh that's what I had until today

#

actually it might be something in my !include

atomic python
atomic python
royal rampart
#

ok, had too goes at this, and now I'm getting hot cos I broke the running fan lol.
I have a few fans in this house and they're all available as a series of switches
switch.fan_$room_off, switch.fan_$room_low, switch.fan_$room_medium, switch.fan_$room_high
how on earth do I squeeze that into the new % based configs

#

even wrote a script that took entity_prefix cos I figured that'd save me a bunch of lines of yaml ๐Ÿ˜„

#

Failed to call service fan.set_percentage. not a valid value for dictionary value @ data['entity_id']. Got None odd

mighty ledge
royal rampart
#

https://pastebin.com/XGnmYgwK this gets me a different error, Failed to call service fan.set_percentage. Template rendered invalid entity IDs: "switch.bed_5_fan_high" so that's an improvement

#

oh, take out the quotes fixed

#

7 more fans to do ๐Ÿ˜„

#

is fan speed preserved when fan is off?

#

next thing is figuring out how to split up my config again... fan: !include fan.yaml, which has first line of - platform: template doesn't seem to work any more

marble jackal
royal rampart
#

oh that might just be vscode

marble jackal
#

ah, there is indeed a bug in vscode

royal rampart
#

sweet thanks, this is all working now! and I have a script so I can save 7 lines of yaml per fan ๐Ÿ˜„

#

(by the time I got it working the first time I was so tired copy pasta was the answer)

#

is there any way to reduce this further? set a variable at the top of the fan template? ๐Ÿ˜„

mighty ledge
#

not really

royal rampart
winter wigeon
inner mesa
#

that will trigger if it transitions from less than or equal to 5 to greater than 5

winter wigeon
#

yeah just saw need >= right?

inner mesa
#

whatever you want

#

the point is that it will trigger on the transition from false to true

winter wigeon
#

yeah so now it triggers if the delay is 5 or >5?

inner mesa
#
      {{state_attr('sensor.fangschleuse_bahnhof_grunheide_mark_to_zoologischer_garten_bahnhof_s_u_berlin','delay')
      | int > 5 }}
winter wigeon
#

but with >= it triggers when it hits 5 or more

winter wigeon
inner mesa
#

what "canceled status"?

winter wigeon
#

the sensor also got canceled

inner mesa
#

what does that mean?

winter wigeon
#

which can be true and false, now i want to trigger when it switches from false to true

#

the train got canceled

inner mesa
#

sensors don't get canceled

#

what is "it"?

winter wigeon
#

its an integration which is using a sensor

inner mesa
#

you're being very vague ๐Ÿ™‚

winter wigeon
#

deutsche bahn integration

inner mesa
#

in the end, you either have a state or an attribute, and you use an appropriate trigger for the appropriate one

#

I have no idea what that does

winter wigeon
inner mesa
#

let me point you to the docs

#

I thought you wrote that, but must have copied it from somewher?

winter wigeon
inner mesa
#

ok, it's pretty straightforward

winter wigeon
#

before i use int. is this a boolean now?

#

should be i guess

inner mesa
#

I have no idea

winter wigeon
#

mhmm can i use something like string == true ๐Ÿ˜„

inner mesa
#

there's a whole section in the docs for stuff like that

#

I recommend not guessing and peruse that instead. Then try what you want in devtools -> Templates

ocean onyx
#

Arduino Output

dull bloom
#

If I want to create a virtual entity for my electric fireplace, what would be the best thing? The fireplace exists in three states: off, lights only, lights + heat... I want to be able to track which state the fireplace is in and run automations to switch between states. Does that make sense?

thorny snow
#

hi, I have an issue with template that I want to use in UI for opacity control. It works in developer tools, but not in lovelace. {{ (states["input_number.slider1"].state) |int / 100 }}

mighty ledge
thorny snow
#

it works when I use light as driving source. opacity: "${states['light.hue_lightstrip_2'].state === 'on' ? (states['light.hue_lightstrip_2'].attributes.brightness / 255) : '0'}"

amber hull
#

How do I create a sensor for weather for date 0? I want today's high temperature. The issue I see is the integration uses the date for 0, 1, 2 rather than the number ,i.e datetime: '2022-02-03T12:00:00+00:00'.

marble jackal
amber hull
#

So 0 will pull today's date data?

marble jackal
#

[0] will take the first item out of the list of forecasts

amber hull
#

Thanks. Worked great.

gloomy bear
#

I'm trying to substitute the value of a datetime helper for the value of "start" and "end" times in an automation but whenI save the automation and return to it the template is changed to "[object object]": null

#

Anybody have an idea why this would be? its driving me nuts

#

This is what I type in : service: babybuddy.add_sleep target: device_id: ab979a9aa5e2021fe8784ae4a4254a75 data: start: '{{ states('input_datetime.samantha_sleep_start_time') }}' end: '{{ states('input_datetime.samantha_sleep_end_time') }}'

#

This is what it look slike when i save and then come back to it:
service: babybuddy.add_sleep target: device_id: ab979a9aa5e2021fe8784ae4a4254a75 data: start: '[object Object]': null end: '[object Object]': null

fossil venture
pallid flower
gloomy bear
#

Is my above issue related to "limited templates"?

#

Or do I need to convert the value of the datetime helper to a string or something? I'm really not sure what the issue is

mighty ledge
fading patio
#

Moved to Node-Red

inner mesa
#

Are you using Node-Red?

fading patio
#

Crap forgot i wasn't in that channel...thought i was.

#

I can post there, but you have a plan ๐Ÿ™‚ ?

inner mesa
#

Nope.

torn meteor
#

anyone else not able to get the new button template working?

#

i copied the example from the blog post and reloaded template entities - nothing

#

i would have expected the yaml to look like other templates, but it's different. usually you start with

#
button:
  - platform: template...
  - name: my_button
#

but instead, the example is

#
template:
  button:
    - name: my_button
#

it seems backwards...

inner mesa
#

The latter is the new format introduced months ago

torn meteor
#

oh hmm. so only the latter will work - should work?

#

can you mix both in the same config file?

inner mesa
#

If it's what the docs say, yes

#

They go in different sections

torn meteor
#

@_@

#

will the former method work

inner mesa
#

Just follow the docs

torn meteor
#

i see the docs. but i am not sure if i need to rewrite my whole config file to use the new format or not

inner mesa
#

No, you just add what it says

steel garnet
#

Hi everyone, in an attempt to deal with any left over template warnings before updating to 2022.2 I wonder if someone can point me in the right direction on the following:

#

Template variable warning: 'mappingproxy object' has no attribute 'current' when rendering '{{ (states.timer | selectattr('state', 'ne', 'idle') | list | count <=0) and (states.automation | selectattr('attributes.current') | list | count <=0) and (states.script | selectattr('attributes.current') | list | count <=0 ) }}'

#

{{ (states.timer | selectattr('state', 'ne', 'idle') | list
| count <=0) and (states.automation | selectattr('attributes.current') | list
| count <=0) and (states.script | selectattr('attributes.current') | list | count <=0 ) }}

#

It always renders correctly but always logs the error as well, any input greatly appreciated

marble jackal
marble jackal
#
{%- set ns = namespace(automation = []) %}
{%- for auto in states.automation %}
  {%- set current = auto.attributes.get('current', 'nothing') %} 
  {%- if current != 'nothing' %}
    {%- set ns.automation = ns.automation + [ auto ] %}
  {%- endif %}
{%- endfor %}
{{ ns.automation | count == 0 }}
steel garnet
tawny coral
#

i have a binary sensor with the following content and the following data parsed from a mqtt json blob

  json_attributes_topic: "BlueIris/driveway/Status"
  json_attributes_template: >
    {
        "trigger": {{ value_json.trigger}},
        "memo": {{ value_json.memo}},
        "type": {{ value_json.type}}
    }

data:
memo: car:92%
trigger: ON
type: MOTION_A

#

How would i go about parsing out the "car:92" to split them out into 2 values?

marble jackal
#

something like this: {{ value_json.memo.split(':') }} and if you are only interested in the percentage, it will be {{ value_json.memo.split(':')[1] }}

tawny coral
#

how would I remove the percentage sign to make it an integer that homeassistant can understand?

marble jackal
#

{{ value_json.memo.split(':')[1] | replace('%', '') }}

tawny coral
#

oof

#

would .strip() work maybe?

marble jackal
#

maybe, but what I posted will also work

tawny coral
#

alright, i'll plug that in

marble jackal
#

you can cast it to an integer after that if you want

tawny coral
#

wrap the entire thing in int()?

#

i know python, but not yaml ๐Ÿ˜„

marble jackal
#

This is not yaml, this is jinja

tawny coral
#

oh, well there you go. i know nothing

marble jackal
#

{{ value_json.memo.split(':')[1] | replace('%', '') | int }}

#

{{ value_json.memo.split(':')[1].strip('%') | int }} also works

tawny coral
#

yeah, that's what i figured but i went your first way now

thorny snow
mighty ledge
thorny snow
tawny coral
#
- platform: mqtt
  device_class: motion
  name: 'testd'
  state_topic: 'BlueIris/driveway/Status'
  value_template: "{{ value_json.trigger }}"
  json_attributes_topic: "BlueIris/driveway/Status"
  json_attributes_template: >
    {
        "trigger": {{ value_json.trigger}},
        "object": {{ value_json.memo.split(":")[0] }},
        "confidence": {{ value_json.memo.split(":")[1].strip('%') | int }}
        "type": {{ value_json.type}}
    }```
#

so i've created this now but it doesn't work, where have i gone wrong?

#

i've got a screenshot of what it puts out and its very strange. it just shows "trigger: ON" and "memo:" (empty). confidence and object don't even exist

pastel moon
#

Hi, I need to set hue_power_on_behavior for several lights and would like to script it. I think this is what I need, question is how I can run it in a script? What would be the correct way to do it? https://paste.debian.net/hidden/8546c5df/

#

command to set the parameter works on the command-line, just unsure how to make it run in a script?

inner mesa
pastel moon
#

Great, will check it out. Thanks ๐Ÿ™‚

fallen berry
#

hi i have an array of some data [ {task: "description", done: true}, ... ] id like to build a template that lops over this data so i can display each item in the array as a line

pastel moon
inner mesa
#

yeah, this part makes no sense:

#
          - condition: template
            value_template: >
                {% for light in lights%}
#

you should use a counter loop and index into the list

pastel moon
#

that makes sense... didn't think of that, will give it a shot, thank you ๐Ÿ™‚

tawny coral
#
- platform: mqtt
  device_class: motion
  name: 'testd'
  state_topic: 'BlueIris/driveway/Status'
  value_template: "{{ value_json.trigger }}"
  json_attributes_topic: "BlueIris/driveway/Status"
  json_attributes_template: >
    {
        "trigger": {{ value_json.trigger}},
        "object": {{ value_json.memo.split(":")[0] }},
        "confidence": {{ value_json.memo.split(":")[1].strip('%') | int }}
        "type": {{ value_json.type}}
    }```
i've got a screenshot of what the sensor and its very strange. it just shows "trigger: ON" and "memo:" (empty). confidence and object don't even exist. Any ideas?
mighty ledge
tawny coral
#

good eye, thanks

sterile nacelle
#

I'm having trouble converting "timestamp" from octoprint into a simple time to use in messages...
Basically i want to turn 2022-02-05T11:26:43+00:00 into just 11:26

inner mesa
#

It depends on whether it's really a datetime or just a string. This works for one of my entities where the attribute is a string:

#

{{ (state_attr('sensor.this_device_next_reminder', 'process_timestamp')|as_datetime).strftime("%H:%M") }}

#

if it's really a datetime object, then you shouldn't need the |as_datetime part

sterile nacelle
#

device_class: timestamp

#

{{ (states('sensor.octoprint_estimated_finish_time')|as_datetime).strftime("%H:%M") }}
Shouldn't this work?

#

entity: sensor.octoprint_estimated_finish_time
state: 2022-02-05T11:29:58+00:00
device_class: timestamp
friendly_name: OctoPrint Estimated Finish Time

inner mesa
#

does it?

sterile nacelle
#

Nope

#

Failed to call service notify.mobile_app_pixel_2_xl. template value should be a string for dictionary value @ data['message']. Got None

#
data:
  message: {{ (states('sensor.octoprint_estimated_finish_time')|as_datetime).strftime("%H:%M") }}```
inner mesa
#

{{ ("2022-02-05T11:29:58+00:00"|as_datetime).strftime("%H:%M") }} -> 11:29

#

all I did was replace the states() call with the string your claim it returns

#

you need to surround your template in quotes

#

rule #1

sterile nacelle
#

OMG, found out what it was:
message: test {{ (states('sensor.octoprint_estimated_finish_time')|as_datetime).strftime("%H:%M") }}
that works
but without the "test" it doesn't :S apparently it doesn't class it as a string i supppose

inner mesa
#

yes, rule #1

#

surround your template with quotes

#

here

#
service: notify.mobile_app_pixel_2_xl
data:
  message: "{{ (states('sensor.octoprint_estimated_finish_time')|as_datetime).strftime('%H:%M') }}"
sterile nacelle
#

grr... YAML and Python is pissing me off, coming from PHP, Javascript and C++... These syntax differences xD

#

Thanks alot, it works now ๐Ÿ˜„

inner mesa
#

because YAML is a superset of JSON, it interprets the { as the start of a JSON structure and barfs on the rest

#

you need to tell it to consider it to be a string

cerulean furnace
#

im trying to add a mqtt light with rgb support and effects. I've been trying to follow the homeassistant guide for adding it to my configuration but every time i think ive added it all i see is a brightness slider rather than a rgb pallet and an effects drop down

silent barnBOT
tropic breach
#

Hi! Should this template condition work?

condition:

  • condition: and
    conditions:
    • condition: template
      value_template: >-
      {{ trigger.event.data.new_state.attributes.device_class == "on" and
      trigger.event.data.new_state.attributes.device_class == "door" }}
    • condition: state
      entity_id: trigger.entity_id
      state: 'on'
      for:
      minutes: '1'
inner mesa
#

Not at all

#

device_class == 'on'?

#

And also 'door'?

tropic breach
#

state.device.class

#

the first part works

inner mesa
#

Still makes no sense

tropic breach
#

you mean this:
{{ trigger.event.data.new_state.attributes.device_class == "on" and
trigger.event.data.new_state.attributes.device_class == "door" }}

inner mesa
#

Yes

tropic breach
#

this makes sense and it workls

#

i tested it

inner mesa
#

That is 'never'

#

Ok

tropic breach
#

wait

inner mesa
#

Yeah

tropic breach
#

maybe i copied the wrong text, hang on

#

this should look better?
`condition:

  • condition: and
    conditions:
    • condition: template
      value_template: >-
      {{ trigger.event.data.new_state == "on" and
      trigger.event.data.new_state.attributes.device_class == "door" }}
    • condition: state
      entity_id: trigger.entity_id
      state: 'on'
      for:
      minutes: '1'`
silent barnBOT
merry dawn
#
  - platform: command_line
    switches:
      door_lock:
        friendly_name: "Door"
        command_on: !secret command_lock
        command_off: !secret command_unlock
        icon_template: >
          {% if is_state('sensor.door_lock_last_event', 'unlock') %}
            mdi:lock-open-variant
          {% else %}
            mdi:door
          {% endif %}```
Hey, i cant get this Switch to change icon, everything looks good under the template designer, but it seems it doesnt apply the icon anyway.. any ideas?
Why i use this over lock is because i run a curl commando to open a door.
midnight quest
#

How do i template this the best way? Or should it work as i made it below?

 - service: notify.device
    data_template:
      title: xxxxxx
      message: > xxxxx
      data:
        actions:
          - action: "OPEN"
            title: "Open Google Maps"
            uri: "https://www.google.com/maps/dir/?api=1&origin={{sensor.mydevice.state}}&destination=home" 

I would like the google travel time origin and destination in the URI action.

inner mesa
#

That's not a valid template

midnight quest
#

I tested it out, and it seems to work:

uri: https://www.google.com/maps/dir/?api=1&origin={{state_attr('device_tracker.iphone', 'latitude')}},{{state_attr('device_tracker.iphone', 'longitude')}}&destination={{state_attr('zone.home', 'latitude')}},{{state_attr('zone.home', 'longitude')}}

๐Ÿ˜€

tropic breach
inner mesa
#

new_state isn't the state

#

new_state.state is

marble jackal
#

I made a suggestion in the automations channel

inner mesa
#

That too

marble jackal
#

You can create a template sensor with a count of binary sensors which are open for more then 30 minutes, and the entity ids as attribute. Then you can trigger on that

#

Without testing: {{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'in', ['door', 'window']) | selectattr('last_changed', '<', now() - timedelta(minutes=30)) | list | count }}

#

And for the attribute: {{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'in', ['door', 'window']) | selectattr('last_changed', '<', now() - timedelta(minutes=30)) | map(attribute='entity_id') | list }}

tropic breach
#

ok thank you. I have to understand which to put where in the logic... have not spent much time with automations/templates in ha yet

#

@marble jackal the first template sensor has to go to configuration.yaml as new sensor, right?

marble jackal
#

But test them first in devtools > templates

tropic breach
#

thxxxxx

marble jackal
#

You can change the number of minutes in the timedelta for testing

tropic breach
#

will do and come back with more educated questions ๐Ÿ™‚

marble jackal
#

I'm on mobile, so I did not test it, and maybe made some errors

lyric socket
native aurora
#

Does anybody have a clue how to parse a JSON as a sensor which has the following layout:

{"fields":[
{"name": "ABC", "value": "123"},
{"name": "XYZ", "value": "789", "unit": "123"}
]}

And I want to extract the value (of "value") linked to name "XYZ".

I've been googling this for 2 hours, but getting stuck...

inner mesa
#
{% set data = {"fields":[
{"name": "ABC", "value": "123"},
{"name": "XYZ", "value": "789", "unit": "123"}
]}
%}

{{ data.fields|selectattr('name', 'eq', 'XYZ')|map(attribute='value')|first }}
#

-> 789

native aurora
#

Actual code now looks like:

- name: DSMR Power Consumption Actual Total value_template: "{{ value_json.actual | selectattr('name', 'eq', 'power_delivered') | map(attribute='value') | first | float }}" device_class: "power" unit_of_measurement: "kW" - name: DSMR Power Returned Actual Total value_template: "{{ value_json.actual | selectattr('name', 'eq', 'power_returned') | map(attribute='value') | first | float }}"

Any pointers where I could find more background documentation? python.org docs can't find selectattr

formal ember
#
    dishwasher_energy_total:
      friendly_name: "Dishwasher Energy Total"
      unique_id: dishwasher_energy_total
      unit_of_measurement: kWh
      device_class: energy
      state_class: measurement
      state: >-
      {{ states('sensor.dishwasher_smartplug_energy_today')|float }}

Created this template to bring the correct reading out of a smart plug to go into my energy dashboard, looks fine in the template section of devtools - but when I check configuration before restarting, I get an error.

silent barnBOT
inner mesa
#

' an error'

#

You're mixing up the template formats

formal ember
#

oh

#

now im even more lost ๐Ÿ˜„

inner mesa
formal ember
#

Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('sensor.dishwasher_smartplug_energy_today')|float", None)])"

regal temple
#

I created a manual alarm_control_panel. I want to be able to to change the arming_time before arming the home. I tried to set the arming_time in the alarm_control panel with a template: {{ states('input_number.arming_time_zone1') | int }}
. The template seems to work fine but I can't find out how to put it in the config for the alarm_control_panel. Is that impossible or should I be able to put it in?

#
alarm_control_panel:
  - platform: manual
    name: Alarm Zone 1
    arming_time: {{ states('input_number.arming_time_zone1') | int }}
    trigger_time: 60
    disarmed:
      trigger_time: 0
    armed_home:
      arming_time: 0
      delay_time: 0
#

This did not work as expected...

lament fjord
#

in action on an automation how can i make this work, i think the error could be in line 14
http://dpaste.org/8qtX
whats confusing me it works in template editor

    brightness_pct: 
      {% if states('sensor.chimney_temp') | float <= 89 %} 100
      {% elif states('sensor.chimney_temp') | float > 90 %} 40
      {% elif states('sensor.chimney_temp') | float < 125 %} 20
      {% else %} 0
      {% endif %}
arctic sorrel
#

I already gave you a fixed version of that facepalm

#

Did you not look at it?

lament fjord
#

i thought it was the same, sorry

arctic sorrel
#

Nobody is going to re-paste what you pasted, just for giggles

unreal merlin
#

Howdy ๐Ÿ™‚

#

I'm seeking advice on template / expand / area_entities. The idea is to get specific sensor data from mulitple areas: e.g. illuminance from front/back of the house