#templates-archived

1 messages · Page 126 of 1

inner mesa
#

You have to use the appropriate service for the entity you’re trying to control. homeassistant.turn_on for groups

dusty hawk
#

Gotcha, I'll go look. Maybe I am using light.turn_off with a group.

#

Odd, I use light.turn_off exactly once in automations, against a light and not at all in scripts. I use homeassistant.turn_off for groups. Yet, I get this error in the logs: Error executing service: <ServiceCall light.turn_off (c:f2faf8ad3b870a7fb2535d7e180e9133): entity_id=['light.dining_hallway', 'light.dining_sitting_area', 'light.dining_table_spots', 'light.kitchen_bath', 'light.kitchen_hallway', 'light.kitchen_work_area']>

#

I'm passing a group to a script that uses the above templates

inner mesa
#

You’ll need to share what you’re actually doing

dusty hawk
#

automation: ``` action:
- service: script.turn_off_only_if_on
data_template:
entity: group.dining_kitchen_lights

#

script: ``` sequence:
# make sure the entity is on else quit (condition)
- condition: template
value_template: "{{ is_state(entity, 'on') }}"
- service: homeassistant.turn_off
data_template:
entity_id: "{{ entity }}"
- wait_template: "{{ is_state(entity, 'off') }}"
timeout: '00:02:00'

inner mesa
#

That won’t cause that error. It’s something else

#

The error says light.turn_off

dusty hawk
#

Far as I know, that's the only place I use that group of entities (shown in the error message). Yea, I only use light.turn_off in one place, against a single light. I'll have to dig more I guess.

#

Here's the full log entry. It looks like my script, with the group, does get run and somehow homeassistant.turn_off morphs to light.turn_off. Perhaps zwjs is doing this? https://paste.ubuntu.com/p/7Ky2F49NRs/

inner mesa
#

Could be. It will internally call the turn_off service of light

#

Try it from devtools -> Services and maybe file an issue

surreal orchid
#

Hey templates, I am looking for a little bit of help trying to figure out how to build my list of entity ids in my template. I receive the following error when checking my configuration file:
2021-05-12 15:32:21 ERROR (MainThread) [homeassistant.config] Invalid config for [automation]: not a valid value for dictionary value @ data['action'][0]['choose'][1]['sequence'][0]['target']['entity_id']. Got None. (See /config/configuration.yaml, line 35)
https://paste.ubuntu.com/p/MHdZfjRDTx/

inner mesa
#

Get rid of the leading ‘-‘ in each one. And I’m assuming that target: accepts templates, which I haven’t tried

surreal orchid
#

removing the -s didn't help.

dusty hawk
#

I just tried the group in services, and no go. A single light works fine as a target to homeassistant.turn_off.

inner mesa
#

Try changing target: to data:

inner mesa
surreal orchid
#

slightly similar error:
2021-05-12 15:40:33 ERROR (MainThread) [homeassistant.config] Invalid config for [automation]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['action'][0]['choose'][1]['sequence'][0]['data']. Got None. (See /config/configuration.yaml, line 35).

inner mesa
#

You’re missing a %

surreal orchid
#

I see the same behavior as my previous code where it still seems like it's trying run another automation while running this one (I think this is looping itself somehow)

inner mesa
#

Well, yeah

dusty hawk
#

Using data: it finally turned off, but it took a while...

inner mesa
#

You’re triggering on the thing you’re changing

#

Your logic is wrong

surreal orchid
#

I want it so if you change either of those entities (on, off, brightness) it would fire and "sync" the other entity. I'm not sure how I am going to set the property of the other entity without it firing off another automation?

inner mesa
#

the way it's written, it's going to go poorly

dusty hawk
#

do associations sync brightness?

inner mesa
#

I would just make a group

#

one entity, on or off

surreal orchid
#

I tried group -- it doesn't sync brightness

inner mesa
#

light.group, then

silent barnBOT
surreal orchid
#

Switching to use a group as the entity_id I see the same thing

ivory delta
#

Groups aren't the same as light groups. Follow the link Rob just shared.

dusty hawk
#

Back to templates, should I use data_template: here for my group entity, or data: in a script? - service: homeassistant.turn_off data_template: entity_id: "{{ entity }}"

#

Its (recently) been failing this way. If it hurts, change it, I guess. We'll see

inner mesa
#

data_template: was deprecated about a year ago

#

data: for everything

surreal orchid
#

@ivory delta same problem using light group. It seems to actually be worse using the light group unfortunately.

dusty hawk
#

So, how do data: and target: differ?

inner mesa
#

I don't know what the point of target: is. maybe for devices? it's fairly recent, and you can always use entity_id to specify what you want to affect

#

data: just starts a generic data block

dusty hawk
#

Is service_template deprecated as well?

dusty hawk
#

Thanks, while he's {cleaning up some templates in scripts}

inner mesa
#

if you use VSCode with the Home Assistant extension, it makes it quite clear that they're deprecated

dusty hawk
#

Hmm, been using vim. I'll look into VSCode.

ivory delta
#

vim 😍

dusty hawk
#

Big step above ed on a 1200 baud modem

surreal orchid
#

@inner mesa is the extension for vs code the Home Assistant Config Helper? I see syntax coloring, but no intellisense/error highlighting

dusty hawk
#

I need vscode for raspbian buster

ivory delta
#

You don't need VS Code on the host. You use your local VS Code and SSH in.

dusty hawk
#

I suppose community edition is good enough for us old retired guys (who still use vim).

inner mesa
#

I'll admit that it lacks the charming snark of Discord, but it's there and it's helpful

ivory delta
#

GitLens too. Noice.

inner mesa
#

I love that

surreal orchid
ivory delta
#

You're just trying to get them to sync?

surreal orchid
#

Yes, sync both on/off and brightness.

#

While the light group may work via HA app, it doesn't work if I walk up to the wall switch and flip it on.

ivory delta
#

The for: is so they don't get stuck in a loop if I toggle things too quickly (I got bored of my house looking like a disco).

inner mesa
#

One day I shall have a lounge

ivory delta
#

You'd use a light group in your action but it's the same idea.

surreal orchid
#

for: "00:00:02"

I think this is the magic piece I'm missing

ivory delta
#

This bit is also going to save you a bunch of lines:
service: "homeassistant.turn_{{ trigger.to_state.state }}"

#

Template the service name instead of using a choose:.

surreal orchid
#

The reason why I did the choose is to specify the brightness property. If I leave that in for turn_off I'll receive an error

#

Do templates support conditional properties?

ivory delta
#

Maybe not. If it causes problems without a choose, keep it your way.

dusty hawk
#

I think that part (or much) of my issue with passing a group to homeassistant.turn_off is that the group includes both lights and switches (hence my choice of generic service). When HA morphs ha.turn_off into light.turn_off, switches may cause a problem. Grasping here.

ivory delta
#

No, that service is generic and can perform any generic on/off/toggle on anything in the group.

drowsy field
#

Okay, Thank you very much. Let me try it now.

surreal orchid
dusty hawk
ivory delta
#

Then you have something else controlling the switch, moo.

drowsy field
#

Nope... The warning is the same....

ivory delta
surreal orchid
#

@ivory delta this is the only automation I have 😦

silent barnBOT
#

@surreal orchid Generally, don't tag people to ask for help - it comes across as bad manners, you’re demanding somebody answers you. It’s different if you’re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.

Similarly, please don’t DM (direct message) people asking for help. It also comes across as demanding, and means that others can’t learn from what you do.

Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on). When using Discord's new Reply feature it defaults to pinging the person you reply to, click @ ON to @ OFF to stop this - on the right side of the compose bar.

drowsy field
#

May I ask why my MQTT sensors cannot get values by HA?

ivory delta
#

They can't? MQTT sensors are commonly used.

drowsy field
#

I even try to ask for float...

#

This is my new Configuration.yaml

sensor 1:
  platform: mqtt
  name: "analog"
  state_topic: "M1"
  qos: 0
  unit_of_measurement: " "
  value_template: "{{ value_json.a|float }}"
ivory delta
#

What's the message on that topic?

drowsy field
#

My json format message can be heard from the integration

#
{"id":4CC441123123,"a":1,"a_s":0,"a_1":2,"a_s_1":0,"a_2":1,"a_s_2":0}
#

When I tried to ask for a gauge, the message on the lovelace is "Instance is not a number".
If I tried to use "Instance" in the lovelace,it will show that the value is unknown.

ivory delta
#

What's the value of the entity in HA?

drowsy field
#

sensor.M1

ivory delta
#

Not its ID. Its current state.

drowsy field
#

M1

dusty hawk
drowsy field
ivory delta
#

Dev Tools > States > search for that entity

silent barnBOT
#

@drowsy field When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.

drowsy field
#

sensor.M1

#

unkown

ivory delta
#

That's why it's not a number in Lovelace 😉

drowsy field
#

Uh, then how can I solve it?

#

IS there anything wrong with my configuraiton.yaml or ?

ivory delta
#

You probably have the wrong topic.

drowsy field
#

Uh, I can heard the message with this topic...in Setting->Integration->MQTT setting->Subscribe Topic

ivory delta
#

That's the full topic? There's nothing before it?

drowsy field
#

Yes

ivory delta
#

Have you saved your edits and reloaded MQTT sensors?

drowsy field
#

I always restart HA

surreal orchid
drowsy field
#

Is there anything I missed?

#

😭

ivory delta
dusty hawk
#

moo, hang in there. Try indenting your "- platforms:" and children and "- choose: and children. Maybe

drowsy field
#

I just feel like moo 😥

dusty hawk
#

You could well have triggers that are hitting and causing it all to go wacky. Some delays may help

drowsy field
#

What is the input of state_topic?

#

Is it must be "topic"
Or 'topic'

#

I can see they have difference colors in VS code

surreal orchid
#

Appreciate the words of encouragement, but I'm going to step away for awhile to decompress. One thing I did notice though is if I use the automation ui out of the box, I receive the same "Already running" error... so that tells me that any time a change is made to an entity it will recursively call itself. Would be nice if there was a flag you could add to the template to tell ha to ignore a state change request.

ivory delta
#

The style of quotes doesn't matter but it's best to keep them consistent.

ivory delta
surreal orchid
drowsy field
#

Is there any hidden topic prefix possible?
I can really get msg from that topic....Why it can not be get by template?

ivory delta
#

I think you have the templates part solved. The rest sounds like automations, moo. We try to keep things in the right channels so the right people see it (while answering and for when other people search the history).

ivory delta
drowsy field
#

Okay let me try it.

dusty hawk
#

It may be moo that you get into race conditions with these two devices triggering either within the automation. I'd look for a way to have automations for each device separately that gently hit the other one. They may not be instant with each other, but may work.

drowsy field
#

It's just blank.

ivory delta
#

Stop tagging me.

drowsy field
#

Sorry

#

Where can I cancel it?

ivory delta
#

I don't know why you're not seeing a value. If the topic is correct, the rest should work.

silent barnBOT
#

When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.

drowsy field
#

I know HassBot but where....

ivory delta
#

It's when you do a reply that quotes people. Bottom right of the window.

drowsy field
#

Is it possible that my json msg is too long?

ivory delta
#

No, it's quite short.

drowsy field
#

Well, actually, I "could" get value from these in Feb...

#

I was trying to split my yaml file then.

#

However, after I update the HA from 5.10 to 5.13.
I even tried to just put all these in the configuration.yaml

#

HA still can't get any value from it.

ivory delta
#

I don't know the answer, so I'll let someone else take a look.

drowsy field
#

Thank you very much!

#

I really appreciate that,

modern flower
#

Is it possible to use a template for entity_id trigger param in an automation? Like so:
trigger:
platform: state
entity_id: "{{ states('input_select.entity_id') }}"
to: 'on'
input_select.entity_id is just a list of entities

drowsy field
#

When I try put publish msg from MQTT broker in HA.
Just purely publish the {"a":10}

#

Then, the HA can get the value and show it on the lovelace.

nocturne chasm
naive wagon
#

Is this the correct syntax?

#
  - platform: template
    sensors:
      home_secure:
        friendly_name: "House Secure"
        device_class: lock
        value_template: >-
          {% if is_state('binary.sensor.doors', 'on') or is_state('binary_sensor.windows', 'on') %}
            on
          {% else %}
            off
          {% endif %}
#

Doesn't seem to be changing the state of the entity.

astral pebble
#

does it work in developer tools test

inner mesa
#

should be okay. seems like you want a binary_sensor though

naive wagon
#

Yeah ^ we're all good in template and no errors in Home Assistant. It just doesn't change anything at all. The windows / doors template changes but doesn't impact the home secure

#

Ignore my last.

inner mesa
#

actually, your entities are wrong

naive wagon
#

It works now

dreamy sinew
#

{{ 'on' if is_state(...) else 'off'}}

inner mesa
#

binary.sensor.doors is probably binary_sensor.doors

naive wagon
#

^ yeah that's correct

dreamy sinew
#

Also probably want an and in there

#

Instead of or

inner mesa
#

I was hoping to sneak in through a window

naive wagon
#

Or seems to be the best option just because if a window or a door is open then the house is not secure, the and would mean a door and a window would have to be open no?

inner mesa
#

depends on what you mean by "on" and "off"

naive wagon
#

on is open, off is closed.

inner mesa
#

I just had this philosophical discussion a few days ago, but "on" to me means "closed, secure"

#

HA agrees with you onthat

#

it's backward to me

dreamy sinew
#

Ah that probably got me too there

modern flower
#

@dreamy sinew It didn't work for me. It said entity_id is not valid with the following:
trigger:
platform: state
entity_id: "{{ states('input_select.entity_id') }}"
to: 'on'
I couldn't find any examples with entity_id being computed in an automation

dreamy sinew
#

I feel like this would get obnoxious if you add more sensors over time though

#

Expand to the rescue maybe?

#

@modern flower what is the output of that template in the tester?

naive wagon
modern flower
#

@dreamy sinew switch.living_room

dreamy sinew
#
{% set sensors = ['entity1', 'entity2'] %}
{{ expand(sensors)|selectattr('state', 'eq', 'on')|list|length > 0 }}
nocturne chasm
#

I don’t think you can use a template in entity_id like that can you? He is trying to use the state of an input_select

#

Without a template trigger at least

dreamy sinew
#

Ah maybe, haven't messed with that in a while

modern flower
#

No, I am trying to get the state of the entity that's currently selected in the input_select

#

like the input_select has a bunch of entities and I want the automation to use whatever is selected as opposed to hard coding it.

nocturne chasm
#

Template trigger

surreal orchid
#

Is logic for setting entity_id in a state condition supported in templating? Each time I try to check if my template is valid, it says the value is None but if the logic were to run it would have a value

inner mesa
#

It does not work for me

pastel moon
#

I am trying to figure how to do operations on turned on lights only. I want it to be dynamic, and only have this so far https://paste.ubuntu.com/p/xkdq92g3Pr/ I believe I need to "grep" entity_id's into some sort of list to loop through for adjusting the lights?

gilded gale
#

hey, is it possible to get the device name from device_id or otherway around?

nocturne chasm
gilded gale
nocturne chasm
#

Does it work in the template editor?

#

Auh, maybe it is not possible

#

Is there a reason you are using device id over the entity id?

gilded gale
#

I`m using ESPHome with custom events and want to trigger automations based on these events. The Idea was to send the host name in the event data to determine which ESP sent it

#

maybe there is a better way

mental ember
#

Is last_changed a default hidden attribute for entities?

fossil venture
#

It's not an attribute. It's a property.

mental ember
#

I want to use different if statements based on when this person last changed its position

fossil venture
#

{{ states.person.bieke.last_changed }}

mental ember
#

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

Text is what I want to archive, bottom is what I've tried to make of it. First time ever doing templates so still lots to learn and lots of things unclear to me. How to best handle the time condition? I tried to format as you can see on the bottom but that does not work, any help?

pastel moon
inner mesa
#

Sure, that’s only in the context of that script

pastel moon
#

Noted, but that's all I need. It went belly up when all rooms used the same helper, so instead of creating one for each, I tested this... 🙂

inner mesa
#

Those are a relatively new invention and I didn’t even think about it

pastel moon
#

Aha, cool! Really didn't think I invented something, but wanted to let you know I appreciate the help I get and will try to return if I can... 🙂

nocturne chasm
fresh ibex
#

Hello everyone. I am trying to set a timer for our airconditioning unit to see how much time left before it turns off. I want the timer to get its duration from the input datetime but i cant get it to work. here's my attempt. thanks

timer:
aircon_timer:
duration: {{states('input_datetime.aircon_timer')}}
name: remaining time
icon: mdi:air-conditioner

inner mesa
#

You can’t just use templates anywhere, so you need to review the docs to see where they’re allowed

#

In this case, you should be able to use the timer.start service to set the duration using a template (because it’s in a data: block), but you need to format it as the service expects

mental ember
inner mesa
#

You don’t nest {{}} like that

#

Also, there’s no context for where that string is being used. It may or may not be valid. Further, you’re converting the time to a string and then trying to compare it as though it’s still a time. You’re unlikely to get the right answer

mental ember
inner mesa
#

You’re comparing strings and not times.

#

If you want to find out if one time is less than another, convert them to timestamps

#

Or datetimes

mental ember
#

Ah I see what you mean, a string 07:30 cannot be smaller or larger than a string 07:31

inner mesa
#

Otherwise you’re doing a string comparison, and that’s going either lead to an error or at least unpredictable results

#

It has no idea what that really means

mental ember
#

Though I've spent an hour and landed on what I currently have as that was the only one which pulled out the hour and minute from last_changed

inner mesa
mental ember
inner mesa
#

If you can make sure that the string comparison will work, I guess it’s okay. In any case, that thread should be instructive

#

My other point still stands. If you want to return a string, just return the string. Don’t add more {{}}

mental ember
#

Well, going to be honest, no clue what I have to change.

inner mesa
#

Ok

mental ember
#

I understand what you say, but not how to implement that in what I currently have. I've tried some different time conversions but none return the hour and minute from last_changed

modern flower
inner mesa
#

The action of an automation is a script, so maybe

narrow shale
#

Any ideas how I can show (as a card) an entities state "entity_picture" attribute image?

inner mesa
mental ember
#

FYI @inner mesa managed to get it working even as a string, not sure how it even works but for some reason it does

modern flower
mental ember
#

Stupid question but cannot seem to find the right answer on google; How do I actually create a new entity when I have my template all written out?

inner mesa
#

It depends on the problem you’re trying to solve

#

Template sensor?

mental ember
#

My template returns a string value which returns my girlfriends work shift as a string

#

So I'd like that as an entity so I can add it to a presence card

inner mesa
#

So template sensor

mental ember
#

I guess? I have it written out in the development tools now but unsure what to do next

inner mesa
#

Usually one approaches the problem the other way

ivory delta
inner mesa
mental ember
inner mesa
#

Decide that you need a sensor and then work on the template that goes in it

mental ember
#

Aah well, been a HomeAssistant user for a few years but started actively using it for the past half year. Never looked or used the template option till this afternoon so still learning a lot here

inner mesa
#

It’s kinda semantics, but I would start with the end product and work backward.

mental ember
#

So I add the binary_sensor, platform: template to my configuration.yaml right?

inner mesa
#

it's a string, not a binary value

#

so "sensor"

mental ember
#

Blargh just nevermind, this template/yaml thing ain't my thing. Spending an entire afternoon on a 5 line template which still isn't working is not productive 😋

crimson spoke
#

is there a way to get a automations next trigger date? I want to create template sensor I can show on my UI to say when it's next going to trigger, based on its trigger time setup

ivory delta
#

No, because for almost every automation, there's no way to tell when it will next trigger.

#

And if you know when it'll next trigger, you don't need a way to guess it.

crimson spoke
#

Yeah I figured that might be the case, time based triggers are only a subset. It's only really relevant for
- platform: time hours: '/1' minutes: '00' seconds: '00'

ivory delta
#

Again, that's predictable, so you don't need a way to determine it. If you really want something on your dashboard to show the next time, just use a trigger that shows the next hour.

inner mesa
#

now().hour+1

drowsy field
#

Dear mono, I got the problem of the statement from the HA logs. Could you please help me with this?

#

I can see the whole msg if I comment out the value_template

crimson spoke
#

In my case its going to change the frequency/times based on input_datetimes and input_numbers 😅 I was hoping to not have to duplicate the logic in both the sensor and the automation, but so be it

drowsy field
#

What I saw in the HA logs is that

Template variable error: 'value_json' is undefined when rendering '{{value_json.a}}'
inner mesa
#

most timer algorithms only pay attention to the very next thing that will happen. when that happens, they repeat that algorithm

ivory delta
#

What does the sensor show if you just use '{{ value }}' as your template?

drowsy field
ivory delta
#

Yes

copper venture
#

I'm trying to write a condition that's a template, which extracts using a regex from the trigger variable. I'm getting an error, and wondering if I'm doing it wrong. Can someone take a look? Here's what I'm trying and the error I get:




Message malformed: invalid template (TemplateSyntaxError: expected token ',', got '{') for dictionary value @ data['condition'][0]['value_template']```
ivory delta
#

{{ is_state(input_boolean.block_notify_{{ trigger.to_state.attributes.entity_id | match("binary_sensor\.([a-z_]+)_person_motion") }}, "off" ) }}
Templates inside templates is a no-no.

#

If you really must do it that way, just concatenate the values:
{{ is_state('input_boolean.block_notify_'~(trigger.to_state.attributes.entity_id | match("binary_sensor\.([a-z_]+)_person_motion")), "off" ) }}
Or something like that

drowsy field
#

I got the whole json msg

ivory delta
#

What about with '{{ value_json }}'?

copper venture
#

is ~ a concatenation operator?

ivory delta
#

One of them, yes.

copper venture
#

gracias

ivory delta
#

You don't want to concat different data types together without forcing them to both be strings.

#

Assuming you want a string, that is...

copper venture
#

right

ivory delta
#

My Python isn't great but a lot of languages will screw up if you do something like '0' + 1.

#

Should the answer be 01? '01'? 1?

copper venture
#

I'm getting closer. Now I guess match() isn't the right thing: ```Message malformed: invalid template (TemplateAssertionError: No filter named 'match'.) for dictionary value @ data['condition'][0]['value_template']

ivory delta
#

You just want to extract a name composed only of the characters a-z?

copper venture
#

[a-z_] underscore is valid also

ivory delta
#

Ah, I missed the underscore 😄

drowsy field
ivory delta
#

The pattern's always binary_sensor.xxxxxxxx_person_motion and you want to grab xxxxxx?

copper venture
#

yes

#

and xxxx is either text or _ right now

#

because then I have a input_boolean.block_notifify_xxxxxx

drowsy field
copper venture
#

essentially each camera has a matching input_boolean that if enabled, blocks notifications

drowsy field
#

Is it possible to cancel the tagging by default?

copper venture
#

oh, i need to use regex_replace or regex_findall_index

ivory delta
#

I would keep it simple then... forget RegEx:
{{ trigger.to_state.object_id.split('_person_motion')[0] }}

#

A state object's object ID is the part after the domain.

copper venture
#

oooo,!

ivory delta
#

Split is more commonly used with a delimiter like spaces or commas but there's nothing stopping you delimiting on an entire phrase.

ivory delta
copper venture
#

yeah, totally. i didn't know about object_id. I only knew about entity_id, which includes the domain

drowsy field
#

Dear mono,
So, what should I do next?

ivory delta
#

If you get back the full value from {{ value }}, that's your starting point. If {{ value.a }} doesn't work, it's because it's not an object, so you can't use 'dot notation' to access keys.

#

Share the full 'JSON' please.

copper venture
#

okay, it looks like this saves cleanly, with no errors: ```value_template: '{{ is_state( "input_boolean.block_notify_"~(trigger.to_state.object_id.split("_person_motion")[0]), "off" ) }}'

#

thanks for your help, mono

silent barnBOT
ivory delta
#

Oof...

silent barnBOT
#

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

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

For sharing code or logs use https://paste.ubuntu.com/.

ivory delta
#

Oops, tagging the wrong person 😄

#

Sorry, treelash, ignore that...

drowsy field
ivory delta
#

@crimson spoke - read the bot message above... and then move over to #integrations-archived for help with input datetimes.

drowsy field
#
{"id":4C1223451234,"a_h":0,"s_h":0,"a_b":0,"s_b":0,"a_l":0,"s_l":0}
#

That's all

ivory delta
#

You have no 'a' in there...

drowsy field
ivory delta
#

Ok. I don't think what you have is valid JSON. The ID doesn't have quotes but it isn't a number.

#

How is it being sent to MQTT?

drowsy field
#

OOOOOOOOHHHHH

#

That's the original msg

#

I see the point, let me change it

red locust
#

is there a way to add a line break to a template so when the sensor is pulled into lovelace, the break is preserved?

For example, this template outputs into a single line in a button card.

          {% set x = states('sensor.time') %}
          {{ day[now().isoweekday()] }} 
          {{ now().strftime("%B %d") + now().strftime(",  %-I:%M %p")}}

I was hoping to have [Day of week], [Month] [Date] on one line, then [Time] right under it:
Thursday, May 13
2:45 PM

ivory delta
#

Looks fine in the dev tools. Might be a quirk of that card.

red locust
#

I'm new to jinja and templates - would it normally be output on two different lines according to the code I posted?

ivory delta
#

Yes. That does output on two lines.

red locust
#

Okay, that's what I thought should happen. Thank for the verification!

drowsy field
pastel moon
#

How about adding possibility to save debug templates in Dev Tool? It seems to reset sometimes, and it would be helpful to be able to choose what's displayed there? Could be though of as a "working templates bank"...

jagged obsidian
#

it resets if you clear your browser cache, or use another browser

mighty flume
#

annyone have a clue why this isnt working

#

friendly_name: "Journey gallons left"
value_template: >-
{% set F = (states('journey_fuel_percent') | round(2))}
{% set M = '(0.2)'}
{% set G = (F*M)}
({-G | round(2) -})

#

i followed a differnt formula template and made some changes for my needs, the other one is working fine

#

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected '}') for dictionary value @ data['sensors']['journey_fuel_gallons']['value_template']. Got "{% set F = ((states('journey_fuel_percent') | round(2)))} {% set M = (0.2)} {% set Gallons = ((F*M))} {{-Gallons | round(2) -}}". (See /config/sensors.yaml, line 17). Please check the docs at https://www.home-assistant.io/integrations/template

jagged obsidian
#

you need to close each {% with %}

#

and this set M = '(0.2)' might be a string instead of a number

mighty flume
#

omg the answer is in front of me but im so dumb. didnt even see that when typing it out tunnel vision from working on a bunch of sensors i guess.

pastel moon
wise cedar
#

Hi, I am trying to create a template sensor which contains a date value of type date so I can trigger push message based on that. I have a pretty big if/elif statement to extract Norwegian month strings which is working, and I end up with this on the final line of my value template of my sensor:
{{ strptime(strdate, '%d %m %Y') }}
I have validated that the template works in the Template section, but I am not sure if I am returning a date value, and I am bit unsure how to verify. Any suggestions?

ivory delta
#

All templates in HA return a string.

#

The stuff within a template cares about the data types but the value that's eventually returned by the template is always a string.

torn meteor
#

does the script.my_script service call require data_template (vs just data) if the parameter value is using {{ template.stuff }}?

inner mesa
#

data_template was deprecated almost a year ago in 0.115

ivory delta
#

I would hope they're on at least 0.118 and yet they still weren't seeing datetimes returned.

inner mesa
#

I had my own trials with strptime and trying to get templates to return datetime types. I wonder if it has something to do with datetime not being JSON serializable, so those get converted to strings on return

#

but, it's not true that templates always returns strings anymore

ivory delta
#

@burnt silo I'm not sure what you're trying to achieve that can't just be done like this:

{%- for value in list -%}
  {{ value }}
{%- endfor -%}```
#

But your way works fine in the Dev Tools.

burnt silo
#

That was just a simple example to demonstrate it, the sensors which use it are mainly more complex. They were working in the Dev Tools for me as well until I updated to 2021.5.3

#

I've been able to refactor them to avoid using that now though, so everything is working now.

knotty timber
#

Hi Folks! I have what should be a really easy question...
How do I cast this incoming data from IFTTT as a number in the data_template in my automation?

      area: '{{ trigger.event.data.area }}'
      cycles: '{{ trigger.event.data.cycles }}'```
"cycles" is a number while "area" is a string
ivory delta
#

You'd just pipe them to an int or float.

#

{{ trigger.event.data.area | int }}

#

Although you'll get really weird results trying to cast a string to an int if it's not just a number inside quotes.

dreamy sinew
#

haha not weird, just 0

ivory delta
#

Most people would say that's weird 😄

#

{{ 'bananas' | int }}

#

Not as weird as the old JavaScript favourite... ('b'+'a'++'a'+'a').toLowerCase()

knotty timber
velvet leaf
#

Hey Everyone, I have been trying to figure this out and i'm getting lost. I'm trying to create a template to pull the HVAC_Mode that my Climate control is in so i can setup an automation depending on the season. I have the season automation setup, just cannot figure our how to get it to pull the 1 Mode that the unit is set to. Currently my sensor template is pulling the whole list... I.E. Off, Cool, Heat, Fan Only, etc...

inner mesa
#

it's just the state of the climate.xxx entity

#

if you just want the state, then states('climate.xxx'). If you want one of the attributes, state_attr('climate.xxx', 'yyy')

velvet leaf
#

sorry, i forgot to add that these are being pulled by MQTT, When i created the sensor to pull the "hvac_modes" attribute, this is what it displays as the state: ['off', 'heat', 'dry', 'cool', 'fan_only', 'auto']

#

< office_hvac_mode:
friendly_name: 'Office HVAC Mode'
value_template: "{{ state_attr('climate.office_a_c', 'hvac_modes') }}">

#

that is my sensor pull setup.

inner mesa
#

because that's the list of available states

#

it doesn't sound like what you actually want

#

so find what you want in devtools -> States

#

and access it using the functions above

velvet leaf
#

Thanks, i'm going to keep digging. Appreciate it!

#

awesome, got it working. Thanks again @inner mesa . You're my hero!

past apex
#

hi ppl

#

need a little help to retrieve a value from a attribute

#

alexa media player has a attribute called <id>_next_timer.sorted_all

#

and it looks like a json

#

but state_attr(sensor.my_echo_next_timer, "sorted_all") seems to return a string

#

i failed to convert it to a json while trying to use a |to_json

ivory delta
#

Share what it looks like and explain what you want to get from it.

past apex
#

sure! 1 min

#

i would like to get the "timerLabel" value

#

should i paste it directly here?

ivory delta
#

That's exactly how it displays? Two pairs of square braces around the whole thing?

past apex
#

yes

ivory delta
#

Try: {{ foo[0][1].timerLabel }}. What does that give?

past apex
#

great!! it worked

#

but not with "foo" but with bar (after converting to json)

ivory delta
#

Awesome. Do you understand why it worked?

past apex
#

haha, now i see what i did wrong

#

i had tried foo[1], but only got a "[" and thought that it was misprinting

#

yes, get the element 0 of the list and then the element 1

ivory delta
#

Ah. If you haven't converted to JSON yet, accessing by index gets the character at that index from the string 😄

past apex
#

thank you!

#

i want to use it as a condition for a automation. Hopefully i should be able to use "alexa timer tv 10 minutes"

fluid thorn
#

Hi guys, I’m trying to figure out if I can have a template that is like “if state was xxx < 1 min ago” how would I achieve this?

inner mesa
#

Look up relative_time and the last_changed property

#

But that only works if the state hasn’t changed in that time. If you want to trigger on some past state, you can’t do that without saving the state

fossil venture
fluid thorn
# inner mesa Look up relative_time and the last_changed property

I have managed to set that up, but I would like to see what the state was before its most recent update. What I’m trying to do is detect if somebody changed from away to home in the last 60 seconds. I wonder if I could create a virtual switch that changes via automations.

fluid thorn
pastel moon
#

Trying to use this template to have it return either number, but it is rather static. Using a greater range works fine. Is there a better method for this?
{{ (range(5,6)|random|int) }}

fossil hearth
#

Hi can anyone help me with this wierd things regarding getting automaton attributes.
so

last_triggered: '2021-05-15T10:06:37.910321+00:00'
mode: single
current: 0
friendly_name: fan on```
however when i do 
```{{states.automation.fan_on.last_triggered}}```
i get ```unknown``` i need the time stamp.. why is it unknown ? its right there
fluid thorn
#

@fossil hearth try {{ state_attr('automation.fan_on', 'last_triggered') }}

fossil hearth
#

Thanks man! ❤️

#

is this considered a timestamp ? coz i want shorten the output

#

for example {{ state_attr('automation.fan_on', 'last_triggered') | timestamp_custom("%m/%d/%Y")}} changed nothing in the output

fluid thorn
pastel moon
#

Try {{ state_attr('automation.fan_on', 'last_triggered').strftime("%m/%d/%Y") }}

fossil hearth
#

Thanks you soo much 🙂

pastel moon
#

Well, I jumped to fast. This one is more like it {{ states.light.floor_ct.last_changed.strftime("%m-%d-%Y") }}

pastel moon
#

I have a template I want to run exactly once a day. How can this be done please?

ivory delta
#

Explain what you're trying to do.

inner mesa
#

And every day is a time_pattern of ‘/24’ hours

pastel moon
#

My god... That's awesome!

ivory delta
#

If we're going to be pedantic, that's still a sensor. The template doesn't have a trigger 😄

pastel moon
#

hehe, true. I will give it a shot, thanks a bunch! 🙂

#

Ok, well, I'm creating this template https://paste.ubuntu.com/p/7JvtBtFVgn/ and need to feed the result into a input_text helper... I first thought of using a script for this, would that work?

inner mesa
#

Why does it need to be an input_text, and not just the sensor state?

pastel moon
#

Because I think I need it as a string value to compare later on. I will have more of these that will decide the outcome of the automation...

inner mesa
#

States are always strings

pastel moon
#

ah... then it may well work... 🙂

inner mesa
#

You saw the link I posted, right?

pastel moon
#

yes, did I miss something?

inner mesa
#

🤷‍♂️

pastel moon
#

I'll read that again...

inner mesa
#

A template sensor takes a template and returns the result as its state

#

With an optional trigger

pastel moon
#

A few of these and I believe it will do nicely...

pastel moon
inner mesa
#

Well, your comment is incorrect

#

That updates every hour

pastel moon
#

Yes, I googled and thought that should update every minute. I know you gave me /24 to use for once a day

ivory delta
#

Have you reached the top of the next hour since setting it up?

pastel moon
#

Nope

ivory delta
#

Then it won't have a value... yet.

pastel moon
#

I wanted to speed it up...

ivory delta
#

Wait a couple of minutes and see if it changes.

pastel moon
#

Yeah, I figured it might be the case, thanks for confirming 🙂

inner mesa
#

You can probably do homeassistant.update_entity to force it

pastel moon
#

cool, will try

ivory delta
#

Did it change since hitting the hour?

pastel moon
#

homeassistant.update_entity did the trick. Now I know it works and can relax a little... Thanks guys!

pastel moon
#

I have a template sensor defined with a value template, and would apart from that also show last_changed in Lovelace. Will I need to define another template for that?

inner mesa
#

last_changed is a property

#

Ideally, you’d use a card that allows a template to access that

pastel moon
#

True, that seems like the way to go, will look for a suitable one, thanks!

dusty crane
#

why does input_number have a decimal that i cannot get rid of?

#

dev, explain yourselves.

#

recockulous.

inner mesa
#

If you want to display an input_number as an integer, you can

ivory delta
#

And some manners wouldn't go amiss.

pastel moon
#

Hi guys, when HA is restarted sensors are read correctly, but the timed one did not seem to work... Or to be more precise, the property 'last_changed' hadn't updated as expected, it still shows a date/time from yesterday. Don't figure why... And as defined in configurations.yaml, how to debug that consistently?

template:
  - trigger:
      - platform: time
        # This will update nightly
        at: "03:00:00"
  - trigger:
      - platform: homeassistant
        event: start
mighty ledge
grim flicker
#

I have devided my room in 6 zones and want to vacuum the livingroom according to the segments i select. I was thinking of making 6 input booleans that i can turn on to select the zones i want and then press vacuum in which the selected zones are pushed to the script and the xiaomi roborock s5 max starts its thing. The real question now is, can i put in a template in the segment part of the script and if so how would i start?

    - service: xiaomi_miio.vacuum_clean_zone
      target:
        entity_id: vacuum.xiaomi_vacuum
      data:
        zone: [[30914,26007,35514,28807], [20232,22496,26032,26496]]

Just to explain: "[30914,26007,35514,28807]" is a single zone. So when a boolean is selected it needs to add those 4 numbers to the line. its something like the nanoleaf petro helped me with a few weeks back

pastel moon
#

I was just digging in the logs to find if it fired at all... But can not find anything, should it show in the log if it did?

mighty ledge
#

Look at the trace

#

Unless it’s a template sensor, and no it wouldn’t show in logs

pastel moon
#

It's a triggered template sensor that should only update once a day. Maybe there are better ways of doing that...?

ivory delta
pastel moon
#

Appreciate that, thanks mono!

#

To not cross post, should I remove this from here?

ivory delta
#

Leave it up, it's had responses now and always makes conversations look odd when one person deletes their comments 😄

pastel moon
#

When reading the last_changed using this template, it don't take summer time into account. How can I adjust it to do that?

{{states.sensor.period_of_day.last_changed.strftime("%Y-%m-%d, %H:%M")}}
grim flicker
#

i have a script like this: https://pastebin.com/tQ03wHPq
but i get the error: "Test vacuum zone: Error executing script. Invalid data for call_service at pos 1: expected list for dictionary value @ data['zone']"
when i test the template in developers tools it makes a perfect list. Can someone tell me what im doing wrong?

#

I also tested if zone can have a template. things like zone: "{{ [27337,26227,29737,27477] }}" do work. So i guess im making an error in my template somewhere

ivory delta
#

Your template will return strings. Just because you're writing something that looks like YAML, doesn't mean it's correct.

#

The YAML syntax for lists actually gets parsed into memory as a list structure. That's what your template should return (a list/array).

grim flicker
#

any thoughts on how i can do that? Or is there a webpage i can read that explains how to do this?

ivory delta
#

The search function on Discord is great.

#

Easy enough to get from that example to this:

{% set ns = namespace(result=[]) %}
{% set list_a = [1,2,3] %}
{% set list_b = [4,5,6] %}
{% set ns.result = ns.result + [list_a] + [list_b] %}
{{ ns.result }}```
#

You'll do some extra work to replace the middle 3 lines.

grim flicker
#

thanks ill try this

#

Above wont check for input booleans. I read on the forums that the best way to do something like this is to write a python script and run that. Never did that before though...

ivory delta
#

What do you mean it won't check? It'll do whatever your template says.

#

What have you tried?

pastel moon
#

Are templates 'naive' (not timezone aware)? I see on Dev Tools that States are returned in local time, but templates in UTC... Is there a trick to it or templates can't do it?

inner mesa
pastel moon
ivory delta
#

The blog isn't the docs. Always check the docs 😄

pastel moon
#

Shoot... lol, hadn't noticed that to be honest... Thanks for pointing that out... 👍

inner mesa
#

A blog post from 2017, no less

lone dragon
#

heyy guys

#

why cant i have the new "templates" integration inside a pkg? the same configuration gives error inside a package but not in configuration.yaml

inner mesa
lone dragon
#

Thanks. I also find a issue on github discussing it as bug vs feature

plucky wyvern
#

Hey, how can I solve this:

#
{% if states('sensor.home_temperature') | int >= 7 and <= 20 %}
#

It tells me: TemplateSyntaxError: unexpected '>='

#
{% if states('sensor.home_temperature') | int >= 7 and states('sensor.home_temperature') | int <= 20 %}
#

got it

inner mesa
#

or even more concisely:

#
{% if 6 < states('sensor.home_temperature') | int <= 20 %}
plucky wyvern
#

Oh that's nice, will take yours 😉 thanks

inner mesa
#

fixed off by one

sacred sparrow
#

anyone know why this won't work?

wait_template: >-
  {{ is_state('light.bathroom_front', 'unavailable') or
  ('light.shower_lights_smartplug', 'off') or
  ('light.shower_lights_smartplug', 'unavailable') }}
timeout: '00:45:00'
inner mesa
#

The syntax is wrong

#

You left is_state off the last two

sacred sparrow
#

ah perfect! thanks 🙂

tribal shoal
#

can you get to a sensors state as the type it was created as? eg, if the state value is an int, can i get to it as an int in a template without having to do states('sensor.thing')|int

inner mesa
#

No. States are strings

tribal shoal
#

ok

#

i thought i was being very clever by doing value_template: "{{ timedelta(minutes=value|int) }}" in an mqtt sensor, but it's hurting now that i want to do a comparison against it

inner mesa
#

Yeah, timestamp would be better

tribal shoal
#

i'll just keep it as an int

tribal shoal
#

thanks for the info

crimson spoke
#

how do I access an array from a template? I have {{state_attr('weather.home_2', 'forecast')}} which returns [{'datetime': '2021-05-17T06:00:00+00:00', 'temperature': 12.2, 'templow': 6.4, 'precipitation': 4.5, 'precipitation_probability': 55, 'wind_speed': 7.4, 'wind_bearing': 284, 'condition': 'lightning-rainy'}, {'datetime': '2021-05-18T06:00:00+00:00', 'temperature': 15.9, 'templow': 5.6, 'precipitation': 1.9, 'precipitation_probability': 40, 'wind_speed': 13.0, 'wind_bearing': 277, 'condition': 'lightning-rainy'}, [bla bla bla...] ].

How do I access a specific entry? {{state_attr('weather.home_2', 'forecast[1]')}} as I expected to do returns "None"

#

oh, state_attr('weather.home_2', 'forecast')[1] works, makes sense

silent barnBOT
quaint pond
#

Can anyone tell what is wrong with my template?

#

Error: Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got [OrderedDict([('name', 'Season')]), OrderedDict([('state', '{% if now().strftime("%B") == "February" and now().strftime("%-d")|int == 14 %}\n VALENTINES\n{% elif now().strftime("%B") == "July" and now().strftime("%-d")|int > 04 %}\n INDEPENDENCE\n{% elif now().strftime("%B") == "October" %}\n HALLOWEEN\n{% elif now().strftime("%B") == "November" and now().strftime("%-d")|int > 27 %}\n CHRISTMAS\n{% elif now().strftime("%B") == "December" %}\n CHRISTMAS\n{% else %}\n OFF\n{% endif %}')])]. (See ?, line ?).

#

It broke after an upgrade. I know there was a change to templates but I am trying to find what to do to fix it.

inner mesa
#

your definition is a weird amalgam between the old and new styles

quaint pond
#

I cant get the new style to work.

inner mesa
#

ok, then use the old one. what you have now is in between them

quaint pond
#

Only reason i was changing is because the old one is broken for me too 😄

inner mesa
#

ok. you presented it as "I updated and they broke". So you updated and changed some stuff?

quaint pond
#

ohhh sorry. I mean I updated HASS.

inner mesa
#

I get that, but it sounds like you also messed with the definition that you shared.

#

it's definitely wrong

quaint pond
#

Oh yeah I did. Want me to share the old version?

inner mesa
#

no, you have an example of the right way to do it above

#

mine are all the old style and they all worked fine with no changes

quaint pond
#

The error with this version: Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'integer') for dictionary value @ data['sensors']['season']['value_template']. Got '{% if now().strftime("%B") == "February" and now().strftime("%-d")|int == 14 %}\n VALENTINES\n{% elif now().strftime("%B") == "July" and now().strftime("%-d")|int > 04 %}\n INDEPENDENCE\n{% elif now().strftime("%B") == "October" %}\n HALLOWEEN\n{% elif now().strftime("%B") == "November" and now().strftime("%-d")|int > 27 %}\n CHRISTMAS\n{% elif now().strftime("%B") == "December" %}\n CHRISTMAS\n{% else %}\n OFF\n{% endif %}'. (See ?, line ?).

inner mesa
#

"OFF" is probably being interpreted as 0 now that templates can return native types

#

change that string to something else

#

"NOTHING" or similar

quaint pond
#

Changed it to "NOHOLIDAY" and I still get that error.

inner mesa
#

what if you copy that template into devtools -> Templates?

#

nevermind, I see it

quaint pond
#

Bad template?

inner mesa
#

it doesn't like the zero-padding of the integers

#

04 -> 4

quaint pond
#

You're a genius. That worked for me in the template editor. Let me try in the file now

inner mesa
#

I just started with the first "if", which worked, and then added the second, where it failed

quaint pond
#

Configuration valid!

#

Should I try to convert it to the new way or leave it?

inner mesa
#

your choice

#

the new way doesn't work with packages, so if you're using packages, stick with the old way or migrate the definitions to configuration.yaml

quaint pond
#

I will leave it for now then. Upgrade when I am forced. Thank you so much for your help @inner mesa

marble jackal
#

I want to have a random number in a certain range, but exclude some numbers (which will eventually be stored in a input text as comma separated values)
I have the following now, but that gives an TypeError: object of type 'generator' has no len() in the template checker. How should I fix this?

{% set exclude_list = '1, 3, 4, 7' %}
{{ (range(0, 11)| reject(exclude_list | list)| random) }}
reef shard
#

If I make a template sensor that is trigger based, which I want to update once a day at midnight-ish, it will show unknown after reloading templates (or restarting ha) until the time pattern is reached again. Can I get around this somehow?

#

Restart I can manage by another trigger I just realized. But reload remains

reef shard
#

I tried listening for the event in dev tools, but it doesn't seem to fire 🤔

reef shard
#

workaround: trigger on state change to unknown for the template sensors instead

twin wasp
#

Hi, I've got an issue, I've made a template and it's working fine on Developer tools, however, when I make it into a real thing on configuration.yaml I get an error upon reboot

#

ERROR (MainThread) [homeassistant.setup] Setup failed for template: No setup function defined.

jagged obsidian
#

what are the relevant yaml lines?

twin wasp
#

The yaml that I used in configuration.yaml is this

  - sensor:
    - name: "Diferencial Temperatura Zona 1 Exterior"
      unit_of_measurement: "ºC"
      state: >
        {% set exterior = states('sensor.temperatura_exterior') |float %}
        {% set interior = states('sensor.temperatura_zona_1') |float %}
        {{ ( interior - exterior ) | abs }}
jagged obsidian
#

and did you run the config check?

twin wasp
#

yup, came out valid

#

everything else loads fine, this is the only thing that fails

jagged obsidian
#

the - name indentation could be better with two more spaces

twin wasp
#

I'll try fixing that and restarting, just a sec

#

nope, same thing

Source: setup.py:138
First occurred: 11:57:41 AM (1 occurrences)
Last logged: 11:57:41 AM

Setup failed for template: No setup function defined.

I got that error on the log

marble jackal
#

Shouldn't state be value_template?

mighty ledge
marble jackal
#

Oh, okay :) I have some reading to do :)

twin wasp
#

any clues as to what might be happening here though?

#

I'm thinking maybe it's a broken install?

mighty ledge
twin wasp
#

core-2021.3.3

mighty ledge
twin wasp
#

ooh I see

#

thanks I'll look into the documentation for the old templates then 😄

fossil venture
#

Are there any plans to remove the legacy template sensor and template binary_sensor formats? Wondering if I should start moving my template sensors over to the new format.

inner mesa
#

the new format doesn't work in packages, so removing it would cause some breakage

fossil venture
#

But if the devs get it working with packages...?

inner mesa
#

it was seemed like more of a feature than a bug, from their perspective

pastel moon
#

When in DevTools testing {{ states.light|selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }} it also returns light groups. Can these be excluded somehow?

dreamy sinew
#

I don't think so unless there's something unique about them you can filter against

pastel moon
#

Ok, was afraid of that, thanks. Will figure another way then 🙂

ivory delta
#

You could set a custom attribute against them and use that to reject them.

pastel moon
#

Cool! I found this which works too ```
{% set domains = ['light', 'vacuum', 'switch', 'sensor', 'binary_sensor', 'zwave', 'lock'] %}
{% set filter = ['binary_sensor.remote_ui'] %}
{{ states | selectattr('domain', 'in', domains) | rejectattr('entity_id', 'in', filter) | selectattr('state','eq','on') | map(attribute='name') | list | join(', ') }}

#

How would the custom attribute work?

inner mesa
#

you could have to add an attribute to the entities through customization

pastel moon
#

Ok, could be one way, will check it out. I believe I briefly saw another suggestion about changing type of the group?

inner mesa
#

I don't know what that means

#

like a device_type?

pastel moon
#

No idea. I had no time to check out what it was. post was removed

#

I'll check out the attribute, thanks! 🙂

ivory delta
#

Once you've set an attribute, you'd select/reject like this:

{{ states | selectattr('attributes.room', 'equalto', 'study') | map(attribute='entity_id') | list }}```
pastel moon
#

Nice, thank you!

glacial matrix
#

Hey guys and gals, I think i need a template sensor, but not sure, I have a bulb energy meter that i have managed to get into HomeAssistant, but it only shows the total usage, How do i go about showing the usage for the month and day?

ivory delta
#

You don't use templates for history. You use #integrations-archived. Namely the integration integration and the utility meter integration.

pastel moon
#

Why do some config have to be under key homeassistant in configuration.yaml? As for example customize: !include customize.yaml

ivory delta
#

Just because

dreamy sinew
#

does anyone have a more elegant solution for this?

{% if 0 <= now().hour <= 11 %}
  {% set start = (now() - timedelta(days=1)).strftime('%Y-%m-%d {}%z').format(states('input_datetime.master_bedtime_start')) %}
  {% set end = today.format(states('input_datetime.master_bedtime_stop')) %}
{% else %}
  {% set start = today.format(states('input_datetime.master_bedtime_start')) %}
  {% set end = (now() + timedelta(days=1)).strftime('%Y-%m-%d {}%z').format(states('input_datetime.master_bedtime_stop')) %}
{% endif %}
{{ strptime(start, '%Y-%m-%d %H:%M:%S%z') <= now() <= strptime(end, '%Y-%m-%d %H:%M:%S%z')}}```
#

basically the start time is something like 22:00 and the end time would be 07:00 the next morning

#

since the hour wraps can't do a simple start < now().strftime('%T') < end

toxic dome
#

well you could if you just added 2 hours to everything right?

#

add two hours to start, end and now and then start < now().strftime('%T') < end

dreamy sinew
#

might work for that one but there's another that starts much earlier (toddler's bedtime)

toxic dome
#

well another option is just work in unix timestamps

dreamy sinew
#

the input helpers do not have dates

toxic dome
#

yea I know but it looks like you give them dates based on now

#

or were you hoping to get rid of all that?

dreamy sinew
#

right, that's the bit to simplify

toxic dome
#

if it always straddles midnight

dreamy sinew
#

to use timestamps i'd still have to do all the same work

toxic dome
#

then what about just two separate comparisons?
now().hour >= start or now().hour < end

#

drop the dates entirely

#

hour is an attribute of the helpers so yea

#
now().hour >= state_attr('input_datetime.master_bedtime_start', 'hour') or
now().hour < state_attr('input_datetime.master_bedtime_end', 'hour')
dreamy sinew
#

yeah, that's a lot simpler

toxic dome
#

haha yep, as long as they all straddle midnight that works great

#

any after midnight just adjust to the way you had it start <= now().hour < end

#

if you wanted to have the template ready to handle start being moved after midnight then you could throw in a conditional:

{% set start_hour = state_attr('input_datetime.master_bedtime_start', 'hour') %}
{% set end_hour = state_attr('input_datetime.master_bedtime_end', 'hour') %}
{% if start_hour > end_hour %}
  {{ now().hour >= start_hour or now().hour < end_hour }}
{% else %}
  {{ start_hour <= now().hour < end_hour }}
{% endif %}
dreamy sinew
#

i don't think that'll ever be a problem

#

or if it is, i can deal with it then

dreamy sinew
#

thanks!

#

i have a bad tendency to get overcomplicated in my templates 😛

#

for even more context this is for my fan control automation

#

need to bypass occupancy detection during sleeping hours to keep the fans from shutting of from sleeping too still

toxic dome
#

yea that makes sense

dreamy sinew
#

though i could probably just tap into my thermostat instead...

toxic dome
#

I have smart outlets next to the beds on the phone chargers. When they are in use between 10pm and 10am it assumes the corresponding person is asleep and turns off normal presence lights stuff in that room. When all are in use it assumes everyone is asleep and turns off al presence lights stuff until someone is awake again

#

Well I guess I should say when all are in use for all the people at home. Anyone not at home is excluded from the calcuation of figuring out when everyone is asleep

dreamy sinew
#

i already have 'kid bedtime' and 'Sleep' modes on my thermostat which is hooked in to HA, probably much easier to just key off of that

#

let it deal with the schedule

gusty nimbus
#

i have this in my configuration.yaml to read out my p1 meter for what i take from the net
but is it possible to have a longer timeout?
Since the p1 reader has a bad wifi connection atm
it could help to get the data i think now its saying unavailable

sensor:
- platform: rest
  resource: http://myip/api/v1/smartmeter?limit=1&json=object&round=on
  name: Huidig Electriciteit verbruik Netafname
  value_template: '{{ value_json.0.CONSUMPTION_W }}'
  unit_of_measurement: "W"
ivory delta
#

I don't think you can control the HTTP timeout, no.

gusty nimbus
#

oh ok np tx for the answear

tidal heart
#

Is there an easy way to just subtract a couple of minutes from a input_datetime that has both date and time?

#

Tried this but for some reason it is two hours wrong to begin with {{ ( state_attr('input_datetime.morgon_alarm', 'timestamp') | int - 600 ) | timestamp_custom('%H:%M', False)}}

EDIT: setting it to True instead of False sovled it 👍

arctic sorrel
bronze horizon
#

I have a script switch-presence.py that outputs {"result": {"state": "on", "id": 72251383255146496, "name": "MONSTER HUNTER RISE"}} on the command line. I was thinking it should work as a command line sensor like so:

- platform: command_line
  name: Switch Presence Python
  command: python3 /config/configs/commands/switch-presence.py
  json_attributes:
    - result
  value_template: '{{ value_json.result.state }}'

However this results in an unknown state and only the Friendly Name attribute being defined.

If I remove the json_atttributes and value_template parameters, the state matches the output from the command line, except that "s are replaced by 's. So the command_line integration seems to work with this script but has an issue with the JSON... Any suggestions to make this work?

#

I had been trying to mess around in the template editor, but it seems like that's going to change the formatting to string regardless

pastel moon
#

I noticed both of these syntax's work - Which one is the most correct?

1. "{{ states('sensor.period_of_day' in ['day', 'morning', 'evening']) }}"
2. "{{ states('sensor.period_of_day') in ['day', 'morning', 'evening'] }}"
charred dagger
#

The first shouldn't work.

pastel moon
#

🤔 And you are correct. Both checks let that through so (wrongly) just assumed...

charred dagger
#

It's syntactically correct. It just that it will evaluate to states(false) which will give an error.

bright quarry
#
  - data:
      data:
        photo:
        - caption: Motion is Detected
          file: /media/doods_lenovostick_screen_0_latest.jpg
      message: Motion is Detected
    service: notify.mobile_app_moto_g_6```
trying to push an image to my phone notification via the has app, the text appears but not the image. am i doing it wrong with "file:" ?
dreamy sinew
#

i have to say, i'm really enjoying the choose action

mortal egret
#
{{ states|selectattr('entity_id', "search", "fr_")|map(attribute="entity_id")|join(",") }}

running this in the dev tools results in this error

TemplateRuntimeError: no test named 'search'
#

any idea why?

inner mesa
#

which version of HA are you running?

#

that was new in 2021.5

#

and obviously adjust based on your actual entity_id values

earnest arrow
#

is there a good way to stick json in the template editor and use that to test out rest sensor value templates

inner mesa
#

{% set value_json = jsonstuff %}

mortal egret
#

@inner mesa yep, updating HA fixed it. now when I go to add it to my Logbook card, I get a different error that I didn't get in the dev tools

type: logbook
entities: {{ states|selectattr('entity_id', "search", "abode")|map(attribute="entity_id")|join(",") }}
hours_to_show: 24
#
Configuration errors detected:
missed comma between flow collection entries at line 2, column 62:
     ... r('entity_id', "search", "abode")|map(attribute="entity_id")|joi ...
inner mesa
#

you probably can't use a template there

#

you could create a template sensor with that and use it instead

mortal egret
#

man, being able to inline those templates into lovelace card config would be great

#

like I'm trying to also make a dashboard summarizing all People, and I could create different entity cards that use the same search on someone's name

earnest arrow
#

yay my rest sensors are all showing unknown 🙃

inner mesa
#

if you had something working in the template editor, it's usually that there's an extra level of encapsulation or an extra data: tag or something

earnest arrow
#

and value templates like so:

value_template: "{{ value_json.0.devices.0.real_power_w }}"
value_template: "{{ value_json.0.devices.1.real_power_w }}"
value_template: "{{ value_json.0.devices.2.real_power_w }}"
inner mesa
#

seems to work here, but maybe the data isn't available yet for your sensors

earnest arrow
#

ah, was using the wrong authentication

#

apparently this endpoint uses digest instead of basic auth

inner mesa
#

"didn't actually get the data" is always an option

earnest arrow
#

interesting. looks like the new template: syntax doesn't work in packages

#

Package envoy setup failed. Component template cannot be merged. Expected a dict.

dreamy sinew
#

yup, that's a thing

earnest arrow
#

that makes me make this face: ☹️

dreamy sinew
#

i keep hearing about new template syntax but never looked in to it, have a linky?

earnest arrow
dreamy sinew
#

oh interesting

inner mesa
#

There doesn’t seem to be an appetite for fixing the package support either

#

There’s an issue for it

mortal egret
#

can you create a template camera? e.g. I have a Eufy camera and a smart plug that I want to use to control the "on/off" state of the camera

astral pebble
#

Custom component / set state manually are the only ways I know of for that

jagged totem
#

how to handle when float(states.sensor.something.state) is "unknown"?

#

doing a sort/first and get TypeError: '<' not supported between instances of 'str' and 'float'

fossil venture
#

{{ states('sensor.something')|float }} will return 0 when unknown.

#

{{ states('sensor.something')|float(n) }} where n is a number, will return n when the sensor state is unknown.

jagged totem
#

nice, and how about if I have a list of values, how can I remove the unknowns (eg: I want average but discount the unknowns to not skew the result)

#

I have this currently {% set temps = [ states('sensor.temperature_upstairs_hall') | float, .... states('sensor.temperature_bedroom_3') | float ] %} {{ ((temps | sum) / (temps | length)) | round }}

fossil venture
#

You would have to use conditional statements. {% if states('sensor.something') not in ['unavailable', 'unknown', 'none'] %}

jagged totem
#

how would that work in a list? I'd expect something like listOfThings | filter('unknown')

fair verge
#

Does this approach look sane - to cope with unknown from states('sensor.hall_sonoff_temperature')
value_template: >
{% set offset = states('input_number.hall_temperature_offset') | float %}
{{ states('sensor.hall_sonoff_temperature') | float( states('sensor.hall_corrected_temperature') | float - offset ) + offset }}

It's attempting to return current value if unable to calculate new value

blazing burrow
#

ok so here's another one

#

how can i do something like this, but with a list of entities?

{{ ((now() - states.binary_sensor.front_door.last_changed).seconds < 300) or ((now() - states.binary_sensor.back_door.last_changed).seconds < 300) }}
dreamy sinew
#

does that even work?

#

no

#

oh, yes

#

ok

blazing burrow
#

that does, yeah

#

but say i wanted to give it like... ['binary_sensor.front_door', 'binary_sensor.back_door']

dreamy sinew
#

probably need to create a loop

blazing burrow
#

i'd be fine with that

#

but having trouble figuring out how to go about it

dreamy sinew
#

this works:

{% set sensors = ['binary_sensor.izzy_bedtime', 'binary_sensor.master_bedtime'] %}
{% for sensor in sensors %}
{% if (now() - states[sensor].last_changed).seconds < 300 %}
{% set ns.changed = True %}
{% endif %}
{% endfor %}
{{ ns.changed}}```
#

i don't think you can get it to work with existing filters

#

hah nasty but it works

#

i just toggled 2 input_bools on and both these examples return true right now

#
{% set sensors = ['input_boolean.living_room_fan_override', 'input_boolean.master_bedroom_fan_override'] %}
{% for sensor in sensors %}
{% if (now() - states[sensor].last_changed).seconds < 300 %}
{% set ns.changed = True %}
{% endif %}
{% endfor %}
{{ ns.changed }}
{{ states|selectattr('entity_id', 'in', sensors)|map(attribute='last_changed')|map('as_timestamp')|select('gt', as_timestamp(now() - timedelta(seconds=300)))|list|count > 0 }}```
#

note that both are using the sensors var there

blazing burrow
#

right on, i'm checking these out now

dreamy sinew
#

template tester is returning

True
True```
blazing burrow
#

the one with the loop was giving me errors on setup

#

second one doesn't so we'll see how it works when the automation runs

dreamy sinew
#

both work in the template tester so you probably did something wrong in your automation

blazing burrow
#

same here, both worked fine in the tester

#

can you not use templates in a condition entity_id? like:

condition:
  - condition: state
    entity_id: "{{ whatever }}"
    state: 'on'
dreamy sinew
#

i think you need to use a template condition for that

blazing burrow
#

ah yeah ok that makes sense

marble needle
#

should that be {{ not wait.trigger }} or {{ wait.trigger == "none" }} or {{ wait.trigger is none }}?

dreamy sinew
#

not wait.trigger and wait.trigger is none would be equivalent and correct

marble needle
#

oh wait! i can use the automation tracer to check this more easily now

jagged totem
#

cant find any docs (jinja site messed up). how to sum a list? [1,2,3] | sum without attributes? All the docs are summing up attributes in a dict

pine musk
#

ok, in the correct channel: I am trying to pick fields out of a sensor.

#

"{{ state_attr('sensor.next_launch','Launch_time') }}"
"{{ state_attr('sensor.next_launch','Agency') }}"

#

are returning None in the template editor

dreamy sinew
#

are those the correct attribute names?

#

these things don't typically have capital letters

inner mesa
#

you have an "_" where there's a space in your attribute list for "Launch_time"

pine musk
#

Launch time 2021-05-20T17:09:00Z
Agency China Aerospace Science and Technology Corporation
Agency country codeCHN
Stream false

inner mesa
#

there should be colons there somewhere

pine musk
#

found it by playing with char case

#

fixed

wintry sky
#

Just setup a new zigbee thermostat and I get a heat ‘on’ or ‘off’ in the state attributes. I want to use that to somehow create an energy used sensor. I know that each hour of being ‘on’ is 3Kw but no idea where to start to create something to track that. Ideally by hour then on to day/week/month. Any pointers please?

copper venture
#

is == a valid string comparison operator? specifically i'm using a condition template, kinda like: '{{ trigger.event.data.action.split("-")[0] == "CAMERASNOOZE" }}'

dreamy sinew
#

yep

tidal heart
#

Hey I'm new to JS, how can I convert this into a JS template? {{ now().hour < 8 or now().hour > 20 }}

ivory delta
#

It's going to look almost the same:
new Date().getHours < 8 || new Date().getHours > 20

tidal heart
ivory delta
#

You won't find many JS templates for HA because HA doesn't care about JS. The few things that accept JS templates are some custom cards.

#

You might get some help with it depending on who's around but it's not really a HA thing.

tidal heart
#

Like I'm trying to only show my media player card when it's actually playing but it won't accept this

[[[
  var state = states['media_player.sovrum_hogtalare'].state;
  return state == playing;
]]]
#

Oh damn the formatting did go wild here

#
[[[
  return states['media_player.sovrum_hogtalare'].state == playing;
]]]

Something like this is my first guess

ivory delta
#

That'll also be wrong. In most languages, you need quotes around strings else they'll be treated as a variable (which doesn't exist in your case).

#
  return states['media_player.sovrum_hogtalare'].state == 'playing';
]]]```
silent barnBOT
#

When using Discord's new Reply feature it defaults to pinging the person you reply to, which can get frustrating for the target. Click @ ON to @ OFF to stop this - on the right side of the compose bar.

ivory delta
#

If I'm here, I'll answer. If I'm away, I'll ignore notifications from strangers anyway 😂

tidal heart
#

So how does that work actually... you do a reply but ends the message with an @off?

#

Click @ ON to @ OFF to stop this make me confused

#

There should be a return on the time template right? Something like this?

[[[
return new Date().getHours < 8 || new Date().getHours > 20;
]]]
#

Does not seem to take it, like it's always false

ivory delta
mighty ledge
#

Explain to me how today’s date is greater or less that 8?

mighty ledge
ivory delta
#

D'oh... I messed up in that example 😄

#

I'd go with the simpler one-liner since you're probably not bothered about the instantiation of a second object. Performance difference will be negligible.

mighty ledge
#
[[[
const now = new Date();
return !(8 <= now.getHours() <= 20);
]]]
#

Or this, slow on mobile

[[[
return !(8 <= new Date().getHours() <= 20);
]]]
ivory delta
#

I didn't think this was valid in JS: (8 <= now.getHours() <= 20)

#

That's Python land.

tidal heart
#

Thanks to you both! Will try it out 🙂

hot acorn
#

Hi, how can I get a new line in a template sensor after evaluating a condition. Something like this
{% if is_state('somenthing', 'on') -%}
write somenthing
NEW LINE

ivory delta
#

You'd just write something on a new line 🤷‍♂️

#

What are you trying to output and why do you think it doesn't work?

#

Also, that's not a complete template, so it's hard to guess where you might be doing something wrong.

hot acorn
#

the new line is rendered well in the Developer Tools Template, but when i try to see this sensor in a entity card in lovelace I get all the text in one line

ivory delta
#

I don't think this is necessary: {{ '\n' -}}

#

You're already writing a multi-line template, so linebreaks should be preserved.

#

If I simplify your template for testing:

  Siren: Active{{ '\n' -}}
  Gateway: Active
{% endif %}```
I get this:
#

Line break is preserved. What makes you think it's not?

#

Same outcome without the {{ '\n' -}} too, you just have to pay attention to the whitespace before each line then because you're missing the -.

hot acorn
#

where I missing the "-"?

ivory delta
#

If you remove {{ '\n' -}}, you don't have the - that strips whitespace.

#

The '\n' is pointless, since the linebreak exists anyway.

hot acorn
#

however I also get the new line in the template testing area in Developer Tools, but the new line is not preserved in the entity card in lovelace

ivory delta
#

Right... so that's not the template. That's the way that card displays the info.

#

Something like the markdown card would handle multi-line values. I don't know if many of the others do.

hot acorn
#

ok so the entity card is not capable to render the new line.. Good to know.. I'll try to use the markdown card

#

thanks for the help

fair verge
#

\n means nothing in html

ivory delta
#

And yet the invisible linebreak introduced by spanning a value across two lines in a template is... wait for it... an \n

#

It's all down to how the card interprets that and builds the DOM.

dull bloom
#

I'm looking to build a simple binary sensor for outside light/dark. I want to use my tempest weather sensor lux levels (sensor.smartweather_brightness_2)... Greater > 0 = light, otherwise dark... Don't know the syntax for value template greater than or equal to.

#

I got it

#

ok... maybe not.. can I get help debugging this?

#
- platform: template
  sensors:
    light_outside:
      friendly_name: "Light Outside"
      value_template: >
        {%- if {{ states("sensor.smartweather_brightness_2")|int > 0 }} -%}
        "on"
        {%- else -%}
        "off"
        {%- endif -%}
#

Gets this error: Invalid config for [binary_sensor.template]: invalid template (TemplateSyntaxError: expected token ':', got '}') for dictionary value @ data['sensors']['light_outside']['value_template']. Got '{%- if {{ states("sensor.smartweather_brightness_2")|int > 0 }} -%} "on" {%- else -%} "off" {%- endif -%}\n'. (See ?, line ?).

#

no squigglies around states

#

fixed

inner mesa
#

you're nesting {{ }} inside the template, and you shouldn't do that

#
- platform: template
  sensors:
    light_outside:
      friendly_name: "Light Outside"
      value_template: "{{ 'on' if states('sensor.smartweather_brightness_2')|int > 0 else 'off' }}"
#
  • more compact version
#

@dull bloom

coarse tiger
#

no key available to grab from

#

e.g
{%- for x in value_json -%} {{x['name']}}{%- if not loop.last %}, {%- endif %} {%- endfor -%}
doesn't do nothing

dreamy sinew
#

if its actually json

#

if its not getting converted properly you can try this:

#
    {
        "name": "test",
        "id": "206272a5fee04101a7d426db92622b2c",
        "complete": true
    },
    {
        "name": "rest",
        "id": "b66af7f9081f4eafac3917ddb0a974fa",
        "complete": true
    }
]' %}
{{ ', '.join(value|from_json|map(attribute='name')|list) }}```
#

oh, you can get rid of the |list it isn't needed

coarse tiger
#

hm, trying to get that to work with the shopping list integration but no success

- platform: file
  file_path: /config/.shopping_list.json
  name: ShoppingList
  value_template: >
    {{ ', '.join(value|from_json|map(attribute='name')) }}```
dreamy sinew
#

I'm not sure how the file integration works

radiant dock
#

Hi all how to calculate numbber of entity is in particular state en filter just on entity group ?

#

example : how many light is on on entity group.light ?

silent barnBOT
radiant dock
#

but have the problem : String does not match the pattern of "DEPRECATED"

inner mesa
#

you've specified a bunch of entities and you can't/don't need to do that anymore

#

get rid of them

#

or add them as triggers

radiant dock
#

Ok thank's for your respond 🙂 what should i do then i don't understand

inner mesa
#

plug that template into devtools -> Templates and see what it's listening for. If it lists all those entities, just get rid of the whole entity_id: block

radiant dock
#

Ok I test this code :

  - platform: template
    sensors:
      number_lights_on:
        friendly_name: number lights ON
        unit_of_measurement: "On"
        value_template: >
          {{ states.light|selectattr("state", "equalto", "on")|list|length }}```
#

and is OK but count all my light and no just in specify group

inner mesa
#

ok

radiant dock
#

Ok I test and the result is

#

This model listens for the following state change events:

#
Entité: light.light_bureau
Entité: light.light_chambre_lenzo
Entité: light.light_chambre_parent
Entité: light.light_salon
Entité: light.light_sdb_mirroire
Entité: light.light_sdb_plafond
Entité: light.light_toilette```
#

It's normally to listens on group light and all the light in the group ?

inner mesa
#

🤷

radiant dock
#

finally is the same no ?

inner mesa
radiant dock
#

with this code :

    sensors:
      number_lights_on-2:
        friendly_name: number lights ON-2
        value_template: >-
          {{ expand('group.light') | map(attribute='state') | map('float') | sum }}
        unit_of_measurement: "On"```
inner mesa
#

cool

#

so it figured it out

radiant dock
#

ok but is it normal for him to look in the entity group + all the entities inside the group at the same time? it may be logical ....

inner mesa
#

it's okay

radiant dock
#

OK

#

I test to reload ha and view the result

#

ho...

#

error on check config

#

Invalid config for [sensor.template]: invalid slug number_lights_on-2 (try number_lights_on_2) for dictionary value @ data['sensors']. Got OrderedDict([('number_lights_on-2', OrderedDict([('friendly_name', 'number lights ON-2'), ('value_template', "{{ expand('group.light') | map(attribute='state') | map('float') | sum }}"), ('unit_of_measurement', 'On')]))]). (See ?, line ?).

inner mesa
#

it tells you what's wrong and what to do to fix it 🙂

radiant dock
#

ok the error is -2

#

change to _2 and it's ok

#

ha check result OK

#

thank's @inner mesa for your help

#

The good code is :

  - platform: template
    sensors:
      number_lights_on-2:
        friendly_name: number lights ON-2
        value_template: >-
{{ expand('group.light')|selectattr("state", "equalto", "on")|list|length }}
        unit_of_measurement: "On"```
#

and the result is fine 🙂

inner mesa
#

great

wicked parrot
#

I'm using the command_line senor to get some text/symbol/numeric garbage from a curl get call. I'm trying to do an if then to set the state of the sensor to True or False.

#

I'm guessing with {%- if value == 'bbblah123!' -%}, I'm using value incorrectly.

#
    {%- if value == '{"cmd":"$G0","ret":"$OK 1^31"}' -%}
      Connected
    {%- elif value == '{"cmd":"$G0","ret":"$OK 1^30"}' -%}
      Disconnected
    {%- endif -%}```
blazing burrow
#

hmm, not working for me either... i get a file: Error on device update! error

ruby peak
#

has anyone got a yaml template for "good morning, good evening etc"?

ivory delta
#

🤔

ruby peak
#

Yeah i worded that terribly

ivory delta
#

Templates take data and spit out other data. You need to explain exactly what you need... and what you've tried already 😉

ruby peak
#

I have a template that works, but whats the best way to output that to a value I can use in Node-Red when using TTS

{% if now().hour < 5 %}Good Night! 
{% elif now().hour < 12 %}Good Morning! 
{% elif now().hour < 18 %}Good Afternoon! 
{% else %}Good Evening! {% endif %}
ivory delta
#

I still don't understand. If it works, what are you asking for?

ruby peak
#

I dont want to have to keep using that template code in all my automations

#

i just want so i can query say idk, value.time_of_day

#

or whatever the correct type would be

ivory delta
#

So make it a template sensor.

ruby peak
#

ahhh its a sensor entity

#

ok right thats what i was after. Didnt really know what i was asking so was struggling a bit 😆

ruby peak
#

perfect thanks. The announcement that the dryer has finished is a bit politer now 🤣

upbeat gust
#

hey, maybe someone can help me. i want to build a tv remote with my harmony hub. if i choose a input select like tv, all my buttons should work for tv, when i choose firetv all buttons should work for fire tv. is it right to use templates for this?

blazing burrow
#

@upbeat gust I think you use a harmony remote for that...

upbeat gust
#

i have a harmony hub, yes. i dont know if i should use automations and scripts or if i should use templates

inner mesa
#

There’s no one answer for that

blazing burrow
#

I'd set up activities in the harmony app, then use the harmony integration

#

you can switch between activities, it creates switches for you

#

I mean that is what I've done

upbeat gust
#

for example my input select is tv und i push direction up it should work for tv, when using other input i want to chane the button function for the specific device

upbeat gust
upbeat gust
blazing burrow
#

so are you trying to build a virtual remote inside HA to use to interface with your physical hub?

upbeat gust
#

because i'm not statisfied with the activities.

blazing burrow
#

hmm

#

so you can use them lol they're just not what you want

#

or potentially more accurately, you haven't got them set up the way you want

upbeat gust
#

my problem is, i have 5 devices and when i create a "direction up" button i have to create 5 scripts for my input select, than i can use it with an automation

#

but maybe its easier to create

upbeat gust
ivory delta
upbeat gust
#

ok i will try, but maybe its a better idea to create a template for that?

inner mesa
#

seems like you want a script that takes parameters

dull flicker
#

hey

#

I was hoping to be able to print out the sun rise and sun set just like the entities details

#

for the entity sun

#

but

#

I don't know how to add that card like that to my lovelace interface?

ivory delta
dull flicker
#

right

ivory delta
#

But that's the more info popup, not a card.

dull flicker
#

well I got something to work

#

right i want to make that popup in to a card - meaning it can't be hard to do I wouldn't think

#

but i have found it challenging

ivory delta
dull flicker
#

I have stuff to get the next rising and setting in UTC

#

🙂

#

oik

unique harbor
#

Hi y'all! Anyone have a solution for how to convert a timestamp in YYYY-MM-DD-HH-MM-SS to unix timestamp? Or even better, is there a way to calculate a time difference for such a timestamp?

inner mesa
#

as_timestamp(strptime(‘xxx’)), where xxx is the time format

unique harbor
#

Thank you so much!!

unique harbor
#

Seriously, I swear I googled and checked the docs, but I must be blind as a bat, thanks Rob!

inner mesa
#

Np. Time/date conversions are all trial and error for me

unique harbor
#

That worked flawlessly, thanks again dude, y'all in the community helping out are what makes HA so great

violet geyser
mighty ledge
violet geyser
thorny snow
#

HI all. I'm fiddling around a bit with templates in the developer tools and I'm looking to convert a string time (e.g. "13:20") to a datetime object. What I find online is that I should use strptime(str, format), but if I do that I still can't call any of the datetime object methods (e.g. .isoformat(), .hour, . minute etc). I get an error stating 'str object' has no attribute 'isoformat'. Any ideas on what I'm doing wrong?

ivory delta
#

Scroll up a little, you'll see another conversation about datetimes and a link to the docs.

mighty ledge
thorny snow
#

I had found those docs, but failed to click the "format" link in there. And I was indeed using the wrong format 🤦‍♂️ Thanks!

ivory delta
#

The time stuff is probably the hardest stuff to get right with templates but the docs are pretty good.

autumn grotto
#

my googlefu isn't with me tonight - can I string multiple is_state calls in one if statement (with or's between)?
https://paste.ubuntu.com/p/MqSx8v3rFT/

Furthermore will the template renderer in developer tools actually check the state of input_selects and resolve the template appropriately?

autumn grotto
formal ember
#

Is it possible to have a template reverse the state of an entity? In this case, a cover that is showing as open when it should be closed

jagged obsidian
#

yes it is

formal ember
#

Will it show the original entity as reversed, or does it create a new one?

jagged obsidian
#

a template cover creates a new entity

formal ember
#

Ah cool. Thanks 🙂

thorny snow
#

I just noticed on the jinja docs that there's multiple versions (2.10.x, 2.11.x, 3.0.x), how do I know what version Home Assistant is using?

formal ember
#
- platform: template
  covers:
    bedroom_blind:
      friendly_name: blind
      value_template: "{{ is_state('cover.bedroom_rollerblind', 'off') }}"
      open_cover:
        service: switch.turn_off
        entity_id: cover.bedroom_rollerblind
      close_cover:
        service: switch.turn_on
        entity_id: cover.bedroom_rollerblind
      stop_cover:
        service: switch.turn_{{ 'on' if is_state('cover.bedroom_rollerblind', 'off') else 'off' }}
        entity_id: cover.bedroom_rollerblind```
#

does that look right?

#

or perhaps I have to change the off to closed

young jacinth
#
    - condition: template
      value_template: >-
        {{ trigger.entity_id == fan_trigger }}

why is this not allowed as choose condition in a blueprint?

fossil venture
#

because fan_trigger isn't an entity id of the form domain.object_id

dreamy sinew
#

@autumn grotto if you're checking one entity for multiple states i find its easier to use {{ states('my.entity') in ['state1', 'state2'] }}

young jacinth
silent barnBOT
stark wolf
#

Hey y'all! Trying to figure out templating. Gathering some info from a video endpoint to determine current call status. Not quite sure how to take this XML data and stick it into a sensor. Trying to snag the 'NumberOfActiveCalls' attribute in the above code snippet.

ivory delta
#

Assuming value_json parses XML (which from memory it does), you need to provide the full path to the field you're interested in:
{{ value_json.Status.SystemUnit.State.NumberOfActiveCalls }}

pine musk
#

hello world!
its me of the weird questions, again. I am trying to unpack NWS_alerts
{{ state_attr('sensor.davidson','alerts') }} gives:
[{'area': 'Robertson; Sumner; Macon; Dickson; Cheatham; Davidson; Wilson; Trousdale; Smith; Hickman; Williamson; Maury; Rutherford; Cannon', 'certainty': 'Unknown', 'description': 'The Tennessee Department of Environment and Conservation has issued a\nCode Orange Health Advisory for the Nashville area...in effect until\nmidnight CDT Monday night.\n\nA Code Orange Air Quality Alert for Ozone means ground level Ozone\nconcentrations within the region may approach or exceed unhealthy\nstandards. The general public is not likely to be affected. Active\nchildren and adults, and people with a respiratory disease such as\nAsthma, should limit prolonged outdoor exertion. For additional\ninformation...visit the Tennessee Department of Environment and\nConservation site at http://www.tennessee.gov/environment.', 'ends': None, 'event': 'Air Quality Alert', 'instruction': '', 'response': 'Monitor', 'sent': '2021-05-23T13:32:00-05:00', 'severity': 'Unknown', 'title': 'Air Quality Alert issued May 23 at 1:32PM CDT', 'urgency': 'Unknown', 'NWSheadline': ['AIR QUALITY ALERT IN EFFECT UNTIL MIDNIGHT CDT MONDAY NIGHT'], 'hailSize': 'null', 'windGust': 'null', 'waterspoutDetection': 'null', 'effective': '2021-05-23T13:32:00-05:00', 'expires': '2021-05-25T00:00:00-05:00', 'endsExpires': '2021-05-25T00:00:00-05:00', 'onset': '2021-05-23T13:32:00-05:00', 'status': 'Actual', 'messageType': 'Alert', 'category': 'Met', 'sender': 'w-nws.webmaster@noaa.gov', 'senderName': 'NWS Nashville TN', 'id': 'urn:oid:2.49.0.1.840.0.c75ef2fe8bfb1a7a07b346b1ee9fa49c1b0aad14.001.1', 'zoneid': 'TNZ027,TNC037'}]

how do I pull out the individual alerts/fields?

#

the [{ and }] make me thing it's an array of one entry?

stark wolf
ivory delta
#

How/where are you testing it?

stark wolf
#

Tested the curl command on my HAOS host.

#

gets a successful return so this tells me I am just templating the returned data wrong

#

which I am a complete newb at templating in HA

ivory delta
#

What happens if you just don't use the template in your command line sensor? What does it pull back as its state?

ivory delta
stark wolf
#

Note.....I want it to just store 0 or 1 so I can take a particular action when I am in a video call.

pine musk
#

thanks mono!

ivory delta
pine musk
#

'mono: still pushing against a mountain.

stark wolf
ivory delta
#

Yes, it refreshes. I don't recall what the default interval is but it may be customisable.

#

You can specify it: scan_interval: 60

pine musk
#

ok, mono, will admit that the json bit is driving mer buggy

#

i don't understand how to access the json payload, in the templating console??

#

i am trying this: {% set value_json= {{state_attr('sensor.davidson','alerts')}} %}

inner mesa
#

That’s wrong

#

Don’t nest {{}}

#

You’re already in a template, so it’s just a function call

pine musk
#

i know that much, just can't get to whats right..
you mean like -->>>> {% set value_json=states('sensor.davidson') %}

#

or {% set value_json=state_attr('sensor.davidson','alerts') %}

inner mesa
#

Whatever contains the JSON

pine musk
#

it keeps giving error messages... this time about result-type string

#

{% set value_json=state_attr('sensor.davidson','alerts') %}

{{value_json}} gives me the correct block of data, sort of

#

value_json[0] is closer, but still erapped in { }

stark wolf
#

@ivory delta - rest sensor worked perfectly! woohoo!

Just FYI - what I am doing is setting the mood in my office whenever I hop into a video call. Turn off overhead lights, turn on video lights, pause echo, turn on echo DND, pause appleTV.....

pine musk
#

whoa. it was double wrapped

#

{% set value_json=state_attr('sensor.davidson','alerts') %}
{% set vj=value_json[0] %}
{{vj.NWSheadline[0]}}
For: {{vj.area}}
{{vj.description}}

#

works

#

can you use that in markdown?

inner mesa
#

Try it

pine musk
#

hot Damn!@

#

that is too smurfing cool

nocturne chasm
#

If I have an entity whose state is a question and an answer and the question ends with ? How can I split them up. I have gotten this far
{{ states.sensor.dad_jokes.state.split('?') }}

inner mesa
#

then [0] and [1]

#

and you should use states('sensor.dad_jokes')