#templates-archived

1 messages · Page 13 of 1

mighty ledge
#

you should be getting multiple entities

#

are you not, what does your output look like?

#

Also, have you gotten any new karate recruits?

frank gale
#

that's what i get back:

[
  "light.lowboard"
]
#

but I have 3 devices

mighty ledge
#

screenshot of that please?

frank gale
#

I cannot post any screenshot here

plain magnetBOT
#

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

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

frank gale
#

imgur didn't work with me (probably blocked by adguard)

mighty ledge
#

Are those other devices available?

#

It's working for me

frank gale
#

so If the entities are unavailable shouldn't be shown?

#

I powered the Wleds and now I got them shown

mighty ledge
desert crane
#

can i safely change int to float and it jut starts giving decimals or sensor entity gets borked due to how it's recorded in db and new one is made?
state: "{{ (states('sensor.temp_d1f650_temperature')|int)
into
state: "{{ (states('sensor.temp_d1f650_temperature')|float)

desert crane
#

(provided that input has them)

mighty ledge
desert crane
#

Okay great, thank you 🙂

gaunt trench
#

I have an entity with an attribute that contains a list. I want to show that list on my dashboard. How can I do that? I thought that I can just use a template as a custom sensor to show that with an entity card but it doenst work. My template shows the list in the developer tools but not on my dashboard.
The custom sensor looks like:

- platform: template
    sensors:
      my_card:
        friendly_name: "My Card"
        value_template: "{{ state_attr('card.my_stuff', 'stuff') }}" # as I said this line in the developer tools shows my list
plain magnetBOT
#

@rain crown I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

The source switch

gaunt trench
waxen meadow
plain tulip
#

Hi!
I have a quick question regarding tuya integration and accessing it's sensors data in templates. I'm trying to add custom template sensor with tuya sensor data, but without luck. Options that I've tried:

state: "{{ state_attr('sensor.fridge', 'cur_voltage') }}"
state: "{{ state('sensor.fridge.cur_voltage') }}"
state: "{{ states.fridge.attributes.cur_voltage }}"```
Do you have any suggestions what am I doing wrong?
marble jackal
#

2 and 4 should work, where 2 is the one you should use. If that doesn't work either your entity id, or attribute is incorrect

plain tulip
#

do you have any tip how can I check entity id of this device? "fridge" is the name that actually appears as device name from tuya

marble jackal
#

yes, Developer Tools > States

#

try to find the entity there, in the table below

#

If it is a switch, it's probably switch.fridge or a at least a switch entity

plain tulip
#

ok, I see it, thanks

#

but there is lack of another state, that I would like to use, but it's not implemented by tuya integration

plain magnetBOT
#

@plain tulip I converted your message into a file since it's above 15 lines :+1:

plain tulip
#

cur_current, cur_power and cur_voltage are implemented in integration and appears as sensor.fridge_current, sensor.fridge_power and sensor.fridge_voltage

#

what I would like to use is "add_ele" but it doesnt' appear anywhere, but in tuya developer tools I see that it's being sent

marble jackal
#

Then you should create a feature request for that

plain magnetBOT
#

If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.

plain tulip
#

so the only way is to make implement it in tuya integration? HA cannot access "raw" messages that weren't implemented in the integration?

fallow gulch
#

Ok so if each of these individual conditions is true, then why is the template result 'off'?

#
  on
{% else %}
  off
{% endif %}```
buoyant pine
#

below_horion

#

Also, you can just do this to return True or False btw:

mighty ledge
buoyant pine
#

It's because of below_horion petro

mighty ledge
#

🤷‍♂️ don't use sun.sun

waxen rune
#

or fix the typo 🙂

mighty ledge
#

but I do know that MQTT fields require specific outputs for templates to result in an on or off, same with some template entities

buoyant pine
#

below_horizon is what that should be

mighty ledge
#

Ah, I see that typo

#

@buoyant pine deconz, zha, z2m, are these all different ways to integrate zigbee?

buoyant pine
#

Yeah

mighty ledge
#

who thoguht that was a good idea

buoyant pine
#

Each with specific hardware requirements

#

I mean, choice is good

mighty ledge
#

Meh

#

Z2M seems too easy to set up

buoyant pine
#

|| unless your choice is deconz ||

mighty ledge
#

although it does not see when my bulbs get turned off

waxen rune
#

You means when you turn them off on the power switch and should get unavailable?

mighty ledge
#

go unavailable

#

I've put zero time into finding out if there's a way to detect that

waxen rune
#

You can configure that in Z2M

mighty ledge
#

yeah, I figured

waxen rune
#

Just found out last week

mighty ledge
#

It's funny, I spent all this time writing automations to bitch at people who turn them off via a physical switch. I go to test it and the topic still lists it as available

#

I like Z2M, but I expected control like Zwave2M

#

when it only allows you to name things, it seemed kinda odd

#

@buoyant pine I didn't call things in parallel and they still change states in parallel. It's pretty nice

#

so, no groups and it works well. I'm pleasantly surprised about Z2M

buoyant pine
#

That's good! It's still series but probably just fast enough to look parallel

mighty ledge
#

Yeah

buoyant pine
#

You'll probably see occasional blips

mighty ledge
#

Not concerned with that

buoyant pine
#

Yeah

mighty ledge
#

I see blips with my zwave atm

buoyant pine
#

Yep. Any wireless tech unfortunately

mighty ledge
#

I wrote an automation that guesses at the person who manually turns off the power to my bulbs

#

and alexa tells them to not do that

buoyant pine
#

Lol does it just choose a random name?

mighty ledge
#

it works really well, waiting for someone to do it now after i enable that availability thing

#

na

buoyant pine
#

Or based on the light

mighty ledge
#

I know who's home based on phones connected to the network

#

then I make guesses based on who's most likely to be the idiot

#

my parents have the highest weight to their names

#

As soon as I get BLE working for the phones, I'll definitely know who it was

#

Once everythings working, i'll commit it to my repo and you guys can steal it if you want

#

it's still a WIP

buoyant pine
#

I use smart switches so no need 😉

mighty ledge
#

but these are bulbs in lamps

#

with a turn knob

#

short of cutting off the knob, I kinda have to do this

buoyant pine
#

Ah

#

That's a big oof right there

mighty ledge
#

It's the lamps my wife likes

#

happy wife happy life

buoyant pine
#

Time to modify the lampholder

silent seal
#

Yeah, open it up, adapt the wiring so the switch doesn't do anything, or so the switch pings an ESP which relays it back to HA to toggle the state 😛

mighty ledge
marble jackal
dapper igloo
#

Hi all. I hope i'm in the right channel. How is it (or is it at all) possible to use AND in an if block ?

#

Like this: {% if now().month >= 10 and now().month <= 4 %}

#

that don't work here, but if I remove the AND part, it works (but not as intended)

marble jackal
#

now().month just gives you and integer, 10 at this moment

#

A number can never both above or equal to 10 and lower than or equal to 4

#

You need to use or instead of and in this case

inner mesa
mighty ledge
#

It's not a matter of if it will happen, it's when

dapper igloo
marble jackal
#

{% if now().month >= 4 and now().month <= 10 %} would work, but you could also write that as {% if 4 <= now().month <= 10 %}

waxen rune
#

Today I have this: https://hatebin.com/cvmurqonqs which works fine, but it is a lot of repeating text.
Can you do it shorter, like .. {% if is_state("sensor.mower_status_raw", "1", "4", "17") -%} or something like that?

inner mesa
#
{% if states("sensor.mower_status_raw") in ["1","4","17"] %}
young jacinth
#

hi,
i want to print a list of all sensors that have device_class "power"

iam stuck here
{{ states['sensor']|list }}

fallow gulch
#

This is what I get for working in yaml late at night

inner mesa
mighty ledge
inner mesa
#

The additional spaces give it more flavor...

young jacinth
#

another one,
i want to get the total of all the sensors in this group.

problem is that every item from the list is formated as a string, so {{ list|sum }} does not work

{% set list = expand('group.power')
|rejectattr('state','in',['unavailable','unknown','none'])
|map(attribute='state')
|list %}
inner mesa
#

add map('float')

marble jackal
#
{% set list = expand('group.power') 
| selectattr('state', 'is_number') | map(attribute='state') | map('float') 
| list | sum %}

With added flavor

modest violet
#

Anyone pulled RESTAPI from Hetrix Tools?

topaz cave
#

Hi there, I'm trying to get the following to trigger an automation but it doesn't seem to work?

Trigger:
  - platform: template
    id: Half Term Starts
    value_template: >-
      {{ (states("sensor.date") >=
      states("input_datetime.half_term_starts")) and (states("sensor.date")
      <= states("input_datetime.half_term_ends")) }}

The template returns True in the Dev tools.

deft timber
#

Your automation will trigger only when your template goes from false to true. So only when sensor_date becomes == input_datetime.half_term_starts

topaz cave
#

@deft timber Many thanks

graceful widget
#

Hello, I really need your help with this automation.
Somehow I only ever get Temp5 input_datetime.anne_sp5_wk executed.
The times are executed correctly. But, as in the example, it is always set to 24 degrees.

mighty ledge
#

@graceful widget there's not enough information for anyone to help you.

mighty ledge
#

in both spots

wanton coyote
mighty ledge
graceful widget
mighty ledge
narrow surge
#

Is {{ trigger.to_state.name }} template still valid to use with the following:

trigger:
  - platform: state
    entity_id: 
      - binary_sensor.attic_window
      - binary_sensor.kitchen_back_door
#

in:

  - service: notify.pushover_family
    data:
      title: {{ trigger.to_state.name }} is being opened
graceful widget
mighty ledge
#

did you write the template?

#

or did you copy it

graceful widget
mighty ledge
mighty ledge
graceful widget
#

i have copy the template from here

narrow surge
#

Can I do condition.to_state.name?

mighty ledge
#
      title: "{{ trigger.to_state.name }} is being opened"
mighty ledge
narrow surge
#

So I want to send a warning on the action that someopne has left the home, and the condition will be what device is left open:

trigger:
  - platform: state
    entity_id: group.family
    to: not_home
condition:
  - condition: state
    entity_id: binary_sensor.door_shed
    state: 'on'
#

So I have written 7 automations for this one... Looking to see if I can make it into one

mighty ledge
# graceful widget i have copy the template from here

ah ok, so you just don't understand what it's doing. This is what your template should look like

              temperature: |-
                {% if now().isoweekday() in [1,2,3,4,5] %}
                  {% set weekday = {state_attr('input_datetime.anne_sp1_wk', 'hour'): states('input_number.anne_t1_wk'),
                                    state_attr('input_datetime.anne_sp2_wk', 'hour'): states('input_number.anne_t2_wk'),
                                    state_attr('input_datetime.anne_sp3_wk', 'hour'): states('input_number.anne_t3_wk'),
                                    state_attr('input_datetime.anne_sp4_wk', 'hour'): states('input_number.anne_t4_wk'),
                                    state_attr('input_datetime.anne_sp5_wk', 'hour'): states('input_number.anne_t5_wk')} %}
                  {{ weekday[now().hour|string] }}
                {% else %}
                  {% set weekend = {state_attr('input_datetime.anne_sp1_wknd', 'hour'): states('input_number.anne_t1_wknd'),
                                    state_attr('input_datetime.anne_sp2_wknd', 'hour'): states('input_number.anne_t2_wknd'),
                                    state_attr('input_datetime.anne_sp3_wknd', 'hour'): states('input_number.anne_t3_wknd'),
                                    state_attr('input_datetime.anne_sp4_wknd', 'hour'): states('input_number.anne_t4_wknd'),
                                    state_attr('input_datetime.anne_sp5_wknd', 'hour'): states('input_number.anne_t5_wknd')} %}
                  {{ weekend[now().hour|string] }}
                {% endif %}
plain magnetBOT
#

@narrow surge 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.

mighty ledge
#

share all the automations

graceful widget
#

I have only one automation for this room

narrow surge
#

for each door/window sensor a new one

#

Cannot use {{ trigger.to_state.name }} here because the trigger is someone leaving

graceful widget
mighty ledge
#

er wait, did your original template taht you posted grab states or state_attr?

wet zephyr
#

Hi guys! Any ideas how to create manually a new sensor, and the sensors value is only updated when different scripts run? I have couple of scripts that send IR-codes to AC, and I would like to update the current temperature to that sensor with the script.

graceful widget
#

You are right. But how do I get it to work the way I want it to.

mighty ledge
#

e.g.

narrow surge
#
      - binary_sensor.attic_window
      - binary_sensor.kitchen_back_door
      - binary_sensor.bathroom_window
      - binary_sensor.hallway_front_door
      - binary_sensor.garage_door
      - binary_sensor.bedroom_guest_window
      - binary_sensor.door_shed
mighty ledge
#

you doing this in the UI?

#

or in yaml

#

@narrow surge ^

narrow surge
#

YAML

mighty ledge
#

yeah but yaml in the UI or yaml yaml

#

🤣

narrow surge
#

YAML in the UI these days, its easier to reach than going into ssh and pods and stuff 🙂

mighty ledge
#

ok, well, if we do it in the UI, you'll have to manage 2 lists

#

if you do in in yaml yaml you can use anchors

#

i'll post both

#

wait, nevermind, you won't have to manage 2

narrow surge
#

You magician

mighty ledge
#
alias: Upon leaving and garage door is open
trigger:
  - platform: state
    entity_id: group.family
    to: not_home
variables:
  sensors:
    - binary_sensor.attic_window
    - binary_sensor.kitchen_back_door
    - binary_sensor.bathroom_window
    - binary_sensor.hallway_front_door
    - binary_sensor.garage_door
    - binary_sensor.bedroom_guest_window
    - binary_sensor.door_shed
  open: >
    {{ expand(sensors) | selectattr('state','eq','on') | map(attribute='name') | list }}
condition:
  - condition: template
    value_template: "{{ open != [] }}"
action:
  - service: notify.abc
    data:
      message: "{{ open | join(', ') }} {{ 'is' if open | length == 1 else 'are' }} open."
#

@narrow surge ^

narrow surge
#

wow, ok

#

I need some time to understand it 🙂

mighty ledge
#

{{ expand(sensors) | selectattr('state','eq','on') | map(attribute='name') | list }} -> expands your sensor entity_id's into a list of their current states. Then filters down to all that are on, then grabs just the name, then makes it a list

#

value_template: "{{ open != [] }}" -> checks if the list is not empty (I.e. some are open)

#

message: "{{ open | join(', ') }} {{ 'is' if open | length == 1 else 'are' }} open." -> tells you which ones are open

spiral imp
#

I need to count the number of times that the string "sonos" occurs in the attribute "group_members" for the entity "media_player.sonos_office". I did some searching and could not find a template for that.

mighty ledge
#

whats the output of group_members

spiral imp
#

media_player.sonos_office, media_player.sonos_roam for example

#

Could be more objects in the list as well

mighty ledge
#

and you just paste an example here

#

{{ state_attr('media_player.sonos_office', 'group_members') }}

buoyant pine
mighty ledge
#

put that in template editor and paste results

spiral imp
#

[
"media_player.sonos_office",
"media_player.sonos_roam"
]

mighty ledge
mighty ledge
spiral imp
#

or just counting the objects in that list would work too.

#

yes

mighty ledge
#

| count

#

🚀

buoyant pine
mighty ledge
#

you can't change the state of things via scripts

#

you can however, set an input text

wet zephyr
#

that could be the solution, can the value be used in graph for example?

mighty ledge
#

you'd have to make a template sensor on top of that input_text

#

you could aslo use an input number

buoyant pine
#

Was just about to say that lol

#

Petro over here creating a Rube Goldberg machine

mighty ledge
#

I still don't understand how you'll get the temperature from an IR signal that you send

wet zephyr
#

I dont, I just assume that when I send AC to warm to 21 degrees celsius the value is 21 etc.. I have couple of these when leaving home for e.g. the temp is dropped to 19 degrees. So what I try to do is make a sensor about it, and I can compare that value with the average temp in the house in a single graph

mighty ledge
#

you can make a custom event and call that event from the script that feeds into a template sensor

#

in your script.

- event: update_temperature
  event_data:
    temperature: "{{ temperature }}"

your template sensor

template:
- trigger:
  - platform: event
    event_type: update_temperature
  sensor:
  - name: My Temperature
    state: "{{ trigger.event.data.temperature }}"
#

@wet zephyr ^

wet zephyr
#

this looks great

narrow surge
#

Thanks @mighty ledge , i'm now also using it to check for open windows when it starts to rain:

trigger:
  - platform: state
    entity_id: weather.home
    to:
      - rainy
      - pouring
mighty ledge
#

you can put it all in 1 automation

#

make the trigger have an id

#
trigger:
  - id: It's raining and
    platform: state
    entity_id: weather.home
    to:
      - rainy
      - pouring
  - id: No one is home and
    ...

      message: "{{ trigger.id }}{{ open | join(', ') }} {{ 'is' if open | length == 1 else 'are' }} open."
narrow surge
#

Why is that?

#

To save duplicate text, or for functionality?

ancient lynx
#

Hey all. Have a regex question. I have a string with multiple words in it that has a trailing space I'd like to get rid of. I can't do a regex_replace and replace a space with a null character, because that gets rid of the spaces in between the words. I understand to do that in Regex itself would be %[^"]+, but how can I put that into a template for rendering?

mighty ledge
#

laziness

narrow surge
#

Ah, both need to have this?

#

I though the thing you wrote was already for a single automation

mighty ledge
#

both would have to have an ID

#

but the ID doesn't have to be an ID

#

it can be anything

#

in your case, it would be the start of your sentence

#

"It's raining and x, y, z door are open."

#

"No one is home and x, y, z door are open."

narrow surge
#

Thanks, modified it!

mighty ledge
#

what are it's intentions?

#

the syntax isn't correct for python

wet zephyr
ancient lynx
# mighty ledge what are it's intentions?

I have a sensor "{{ state_attr('calendar.f1', 'message')|string|regex_replace(find='\(([^\)]+)\)', replace='', ignorecase=False) which returns a string Free Practice 1 . I would like to get rid of the space after the "1".

mighty ledge
#

can you post the full message? There's likely a better regex we can use

ancient lynx
#

Sure.

#

{{ state_attr('calendar.f1', 'message') }} gives Free Practice 1 (United States Grand Prix)

mighty ledge
#

basically, you want to get rid of the () part

#

are they all going to have that format?

ancient lynx
#

I would like one template sensor that gives "United States Grand Prix" and give it the attribute of "Free Practice 1"

mighty ledge
#

ah ok

#

is the format always "letters numbers spaces (letters numbers spaces)"?

ancient lynx
#

Correct.

mighty ledge
#

ok, give me a moment

ancient lynx
#

And always with the session name (which is what I want to be the attribute) outside the parens, and the Event name (my desired sensor) in the parens.

#

Theoretically there shouldn't ever be any numbers inside the parentheses, if that makes any difference.

mighty ledge
#

meh, no big deal, just account for it anyways

#

so, is that always the entire message?

#

well no matter, this should work

#

hold on a sec

ancient lynx
#

Yes, that is.

mighty ledge
#
{% set fmat = '^([a-zA-Z 0-9]+) \(([a-zA-Z 0-9]+)\)$' %}
{% set text = state_attr('calendar.f1', 'message')|string %}
{% set session_name, event_name = text | regex_findall(fmat) or 'none', 'none' %}
{{ session_name }}
ancient lynx
#

So that would be for the attribute, but for the sensor would be the same with {{ event_name }} as the last line, correct?

mighty ledge
#

added a little safety

ancient lynx
#

Awesome. Thank you.

mighty ledge
#

np

ancient lynx
#

Trying it in my Developer Tool Template tab gives strange formatting:

[
  [
    "Free Practice 1",
    "United States Grand Prix"
  ]
]
#

Almost like json.

#

And event_name gives none.

mighty ledge
#

well that means there's no event

#

er wait

#

sorry

#
{% set fmat = '^([a-zA-Z 0-9]+) \(([a-zA-Z 0-9]+)\)$' %}
{% set text = state_attr('calendar.f1', 'message')|string %}
{% set session_name, event_name = text | regex_findall(fmat) | first | default or 'none','none'%}
{{ session_name }}
#

you could go without the | default or 'none','none' but it will error without a match

#

shortened

ancient lynx
#

Well it will always have a match, because it just shows what the next event is even if there isn't one currently.

mighty ledge
#

ffs, the or is causing problems

ancient lynx
#

So I think I'm good without it. However, it's still giving:

[
  "Free Practice 1",
  "United States Grand Prix"
]
mighty ledge
#
{% set session_name, event_name = text | regex_findall(fmat) | first | default or ('none','none') %}
ancient lynx
#

And both names are showing up under session_name, not splitting them into session_name and event_name.

mighty ledge
#

there we go

ancient lynx
#

Got it. That did it. Thanks again!

mighty ledge
#

brain fart

#

or is resolved before the ,

#

so it was causing issues

graceful widget
mighty ledge
#

with what?

#

I can't tell which automation you're using

#

i need to see what you're using to fix it

#

all the links you posted had differing results

#

first one had states() second had state_attr(, that stuff makes a difference

graceful widget
#

Maybe I am totally wrong with this automation. I actually just want to set up a heating schedule where I can enter flexible times and temperatures. I have been looking for a solution for days

graceful widget
mighty ledge
#

🤷‍♂️ can't help if I don't see exactly what you have in YOUR automation.

#

not links to posts

graceful widget
#

my automation ... i have sent it per File

#

oh there´s no file 🤦‍♂️

#

I can't attach a file or post code here. Hold on

ancient lynx
#

Also, I found an old forum post that suggests this as a human-readable countdown template. Is this still the recommended way to do that? Or is there a more-efficient way?

        {%- set seconds = (as_timestamp(state_attr('calendar.f1', 'start_time')) - as_timestamp(now())) | int %}
          {%- set map = {'Week': (seconds / 604800) % 604800,
              'Day': (seconds / 86400) % 7,
              'Hour': (seconds / 3600) % 24,
              'Minute': (seconds / 60) % 60,
              'Second': (seconds % 60) } -%}
        {%- for item in map if map[item] | int > 0 -%}
          {%- if loop.first %}{% elif loop.last %}, and {% else %},
        {% endif -%}
          {{- map[item]|int }} {{ item -}} {{- 's' if map[item]|int > 1 -}}
        {%- endfor -%}
mighty ledge
#

Yeah that would work

#

there's about 2834987324982 ways to skin that cat

#

if you just want it in the UI and you plan on using the entities card

#

just this will work

#

"{{ (state_attr('calendar.f1', 'start_time') - now()).seconds }}"

#

with device class set to duration, and unit of measurement set to seconds

#

but that will just be HH:MM:SS format

#

Also, that template you posted doesn't go over a week

#

so, that's not great

#

you can also just use a timestamp sensor and it will say "In x weeks" etc

#

which would just be

#

{{ state_attr('calendar.f1', 'start_time') }}

#

so you have options

mighty ledge
graceful widget
mighty ledge
#

that's fine, but whats not working? is it not setting the temperature at the time?

graceful widget
#

With this code, nothing happens to the temperature

mighty ledge
#

nothing will happen if you are hitting test actions

#

you actually have to let it trigger

#

remove the 2 |strings too

graceful widget
#

Yes, if I let it be triggered by the time. Wait until the set time is reached.

mighty ledge
#

what does the trace say?

#

what errors are in your logs?

graceful widget
#

Wait, that was my original code, I'll send it to you again.

mighty ledge
#

right, so, are there errors in your logs? What does the trace say?

graceful widget
#

And only this temperature is set at the set times:
```yaml
state_attr('input_datetime.anne_sp5_wk', 'hour'): states('input_number.anne_t5_wk')} %}

open hound
#

When creating a template sensor, is there a way to prevent any state change if a certain condition is met?

open hound
#

I upvoted those two, however, I would also like to consider the possibility of having a way to just break out of changing a state when using an if statement in the states. 😐

inner mesa
#

I show an example there of simply returning the current state

#

point is that there's no way to "just don't change the state" now

open hound
#

I might add a comment to the WTH to add that as a feature request as well.

#

Cause I assumed conditions were evaluated before the state was changed. 😐

#

To determine what the next state would be.

#

I use a light to determine the status of my door sensor (as my door sensor is not integrated directly with HA).

inner mesa
#

that's the point

#

but they don't exist right now, so implementation and behavior is still 🤷

open hound
#

I may just do a feature request for a Label Helper. 😐

#

Or Output Helpers. 🤔

#

That are for output exclusively.

#

They'd function like template sensors, but be changeable with scripts and automations.

#

(Not editable through the front end (Lovelace Dashboard, for example)

marble jackal
#

For that you can just use a trigger based template sensor with an event trigger

#

And then send an event with the wanted state in the event data

#

Which you can do in scripts and automations

open hound
#

... 😐

inner mesa
#

Anything is possible...

open hound
#

You can change template sensor states through a script or automation?

#

I guess I'm confused. 😐

inner mesa
#

Over you you, @marble jackal :). You break it, you buy it

plain zinc
#

I have a template that used to work... but I don't recall reading any breaking changes regarding the objects changing:

{{ states.device_tracker | selectattr('attributes.essid', '==', 'CoreGuest')| list | count}}

Errors out with UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'essid'

mighty ledge
#

it's saying it's not getting a number back from the template.

#

only way that would happen is if your triggering entity doesn't match the time it should fire.

vivid ridge
#

would someone be able to assist with my value_template: "{{ value }}" im not getting any numbers

inner mesa
#

That's very little context

vivid ridge
#

mqtt:
sensor:
- name: "GamingRoomTemp"
unique_id: sensor_gamingroomtemp
state_topic: "Gaming Room Temp"
value_template: "{{ value }}"
unit_of_measurement: '°C'

#

{"Id":"4a9bc0ea-5876-464c-a938-f832208005e5","Topic":"Gaming Room Temp","Title":"","Message":"","Data":[{"Name":"Gaming Room Temp","Id":"data\temperatures\5","Unit":"°C","Value":22.19}]} °C

#

i only want to display 22.19 °C

inner mesa
#

Ok, then just 'value' is wrong

#

value_json.Data[0].Value

vivid ridge
#

Unbelievable Thank you so much for that

#

works like magic

marble jackal
#
script:
  some_script:
    sequence:
      - event: update_sensor
        event_data:
          value: some value
thorny snow
#

Hi. Is it possible to get a state object for an entity in a template, using the unique id of the entity (and not the id)?
I have one template sensor which depends on another template sensor, but the user could change the id/name etc. of the entity from GUI and break the other entity.

mighty ledge
#

put the unique_id in the attribute then search all your sensors for entities with that attribute & unique_id. But that's overkill. Don't use unique_id if you don't want the user editing things.

thorny snow
#

Good idea, but yes it seems a bit overkill. Makes sense to not use unique_id then. But could be nice if it was possible, like we can do states('sensor.blabla') but with unique_id. Then user can change whatever they want from GUI without breaking dependencies.

Is it not possible to specify the entity id (e.g. sensor.<this part>) in the new sensor template format? Right now it is being generated based on the name property I set.

mighty ledge
#

The unique_id you actually enter is not the unique_id that's used

#

each integration has a unique_id that's attached to unique_id's to make the entity's unique_id unique in the entire system.

#

and that ID is not known unless you debug into the integration

#

also, no, it's not possible to suggest an object_id

#

you can use name, and your entity_id will be made based off the name.

thorny snow
#

Okay. Thank you 🙂

radiant spindle
#

How can I call two scripts on the same action ?

#

something like that (not working obviously)

#
  action: call-service
  service: light.turn_on
  service_data:
    color_temp: 500
    brightness: 50
    entity_id: light.room2

  action: call-service
  service: light.turn_on
  service_data:
    color_temp: 500
    brightness: 50
    entity_id: light.room2 ```
fossil venture
floral shuttle
#

please remind me again what template I need for 2022-10-20T22:00:00Z please, so I can use it in a rest sensors params like {{now().strftime('%Y-%m-%d')}}

marble jackal
#

as_datetime?

floral shuttle
#

almost! {{(now().strftime('%Y-%m-%d')|as_datetime).isoformat()}} still needs the Z (ulu time)

#

this is the full string I am rebuilding into a rest sensorhttps://api.energyzero.nl/v1/energyprices?fromDate=2022-10-20T22:00:00Z&tillDate=2022-10-21T21:00:00Z&interval=4&usageType=3&inclBtw=true

#

not sure about those actual times though, thinking of simply doing today and tomorrow, like```
params:
startTimestamp: >
{{now().strftime('%Y-%m-%d')}}
endTimestamp: >
{{(now()+ timedelta(days=1)).strftime('%Y-%m-%d')}}

floral shuttle
#

guess I can do params: startTimestamp: > {{(now().strftime('%Y-%m-%d')|as_datetime).isoformat()}}Z endTimestamp: > {{((now()+ timedelta(days=2)).strftime('%Y-%m-%d')|as_datetime).isoformat()}}Z too 😉

#

hey Mike.... though this should be an easier one (already json) I cant find the correct attributes_path and attributes combination for https://api.energyzero.nl/v1/energyprices?fromDate=2022-10-22T00:00:00Z&tillDate=2022-10-23T23:00:00Z&interval=4&usageType=3&inclBtw=true

#
    params:
      startTimestamp: >
        {{(now().strftime('%Y-%m-%d')|as_datetime).isoformat()}}Z
      endTimestamp: >
        {{((now()+ timedelta(days=2)).strftime('%Y-%m-%d')|as_datetime).isoformat()}}Z
      interval: 4
      usageType: 3
      inclBtw: true
    headers:
      Accept: "application/json"
    json_attributes_path: "$.Prices"
    json_attributes:
      - Prices``` returns no attributes, can you spot my mistake please?
rare linden
#

Heh, I love how if I click check configuration on the config page it tells me it's valid but also gives me a notification that it's not valid

rare linden
#

For anyone looking to reuse code for both performance and productivity i've come up with an easy method of getting an array of values as a sensor then reusing that in muliple other sensors

  unique_id: test_motion_sensors
  state: |
    {% set sensors = (states.binary_sensor|default([], true) | selectattr('entity_id', 'defined') | selectattr('entity_id', 'match', '^binary_sensor\.motion_') | sort(attribute='last_updated', reverse = True) | sort(attribute='state', reverse = True) | map(attribute='entity_id') | list)  %}
    {{ sensors }}

- name: '[Test] Sensor Get first from result of Sensor List'
  unique_id: test_motion_sensors_first
  state: |
    {% set sensors = (states.sensor.test_sensor_list_of_motion_sensors.state|default('', true)|trim("[]'")).split("', '")  %}
    {{ sensors | first }}```
#

test_sensor_list_of_motion_sensors should really be test_motion_sensors but since i added unique_id after creating the first version of the sensor, home assistant doesnt seem to have updated to use the unique id

toxic dome
# floral shuttle ``` params: startTimestamp: > {{(now().strftime('%Y-%m-%d')|as...

Drop json_attributes_path. Your json looks like this:

{
  "Prices": [
    ...Array of prices
  ]
}

json attributes path tells it to basically navigate to a field and then treat that as the response, ignoring everything above it. So you're basically making it into a top-level array.

Just drop that from the config entirely, you don't need it. You just want to keep the array of prices which is already in a field.

marble jackal
rare linden
#

The newer versions of HASS don't specify that, it just says "Configuration valid!" even if there are syntax errors in the included files which flag a notification, would be helpful it still stated it like that in the newer versions, i forgot it used to be like that

marble jackal
rare linden
#

ah, had thought it was an older version as i remember seeing that in older versions

marble jackal
#

No, this message is the new version, it used to be "configuration valid" or something similar

neon drift
#

I'm trying to do a service call to set the brightness of a light based on a helper variable, the template renders the correct value, but the service call claims it received None for the value. I have tried googling for the same scenario, some people say this works, some people don't. I don't see what I'm doing wrong, any pointer is welcome.

service: light.turn_on
data:
  brightness_pct: >-
    value_template: {{ (states("input_number.helper_toilet_brightness") | float(0)) }}
target:
  entity_id: light.livingroom_spot_left_light
rare linden
#

docker must be out of date then as i am on the latest image, cant check the version as it's experiancing a permissions issue currently

rare linden
#

also is your >- in the wrong place? shouldnt that be after value_template?

neon drift
rare linden
#

wait a mo, try removing value_template: should just be passing in {{}}

rare linden
#

otherwise you are passing in a string that includes equals value_template: 0

neon drift
#

Ah yes! Thanks so much 😄 makes sense

rare linden
#

np

neon drift
#

I still don't get why it 'Got None', instead of str. What would've been a great pointer.

rare linden
#

Yeah the debugging could definitely be improved in some areas

#

bah the docker image is only 2022.10.1

buoyant pine
rare linden
plain magnetBOT
#

@floral shuttle I converted your message into a file since it's above 15 lines :+1:

floral shuttle
#

o my bad, sorry for that..\

buoyant pine
#

Latest isn't a great idea

buoyant pine
#

Unless you want to potentially run a dev build

rare linden
#

thought latest meant latest stable, changing it to stable

#

thanks

floral shuttle
onyx quest
#

I'm trying to figure out how to get my garage door template cover to show "opening" and "closing" instead of just "opened" and "closed." It's a ZEN17 and a Ecolink tilt sensor. Here is the code that works but only shows opened and closed: https://hastebin.com/upumipekir.less

#

I tried changing the value template to value_template: "{{ states('sensor.garage_door')|float > 0 }}" but that gave me an error that I hadn't defined a default, and the cover didn't load

#

apart from that I am terrible at figuring out this templating stuff and am completely lost

rare linden
#

ok created a script to make sure docker compose keeps things updated correctly, now on 10.5

toxic dome
# floral shuttle please see: https://discord.com/channels/330944238910963714/672223497736421388/1...

The URL you sent me was this:

https://api.energyzero.nl/v1/energyprices?fromDate=2022-10-22T00:00:00Z&tillDate=2022-10-23T23:00:00Z&interval=4&usageType=3&inclBtw=true

That seems to have 5 query string params: fromDate, tillDate, interval, usageType and inclBtw. Looking at your config you seem to have changed fromDate to startTimestamp and tillDate to endTimestamp. Was that an accident or does the API accept those too?

floral shuttle
#

yes! sharp eye! I did a sloppy c&p.......```

  • platform: rest
    unique_id: energyzero_prices_rest
    name: Energyzero prices rest
    resource: https://api.energyzero.nl/v1/energyprices
    scan_interval: 900
    value_template: Ok
    params:
    fromDate: >
    {{(now().strftime('%Y-%m-%d')|as_datetime).isoformat()}}Z
    tillDate: >
    {{((now()+ timedelta(days=2)).strftime('%Y-%m-%d')|as_datetime).isoformat()}}Z
    interval: 4
    usageType: 3
    inclBtw: true
    json_attributes:
    • Prices``` works fine now, thank you sir.
floral shuttle
#

templates can now be like: {{state_attr('sensor.energyzero_prices_rest','Prices')[27].price}} and I hope to be able to create those time triggered trigger template sensors on those each day at the change of tariffs

#

fwiw, this can also be made using the rest: format using ``` sensor:

  - name: Gasprijs Energyzero uur 23
    unique_id: gasprijs_energyzero_uur_23
    value_template: >
      {{value_json.Prices[23].price}}
    json_attributes_path: "$.Prices[23]"
    json_attributes:
      #- price
      - readingDate``` etcetc for all hours, on that resource..
rare linden
#

Can anyone see anything wrong with this? https://pastebin.com/vpJjiYEd this is in a file that's being included from configuration.yaml it's a select:

the error is Invalid config for [template]: [id] is an invalid option for [template]. Check: template->sensor->2->id. (See /config/configuration.yaml, line 47).

inner mesa
#

there's no "id" in there

rare linden
#

yeah, hence my confusion, but found it, it was in a different included file, i do wish the debugging would include better info when it comes to includes

plain zinc
rare linden
#

np

buoyant cypress
#

Hello all. I have very little experience with templates and I am struggling. Can someone help? I want to make a history_stats sensor that shows the total number of hours a boolean has been on for a week. I have figured out how to make a "last 7 days" but what I need is one that counts from Tuesday at 00:00 to Tuesday at 00:00. I think "weekday" will be used but... I am lost.

plain zinc
# rare linden np

Hmm just giving me an empty list actually, but that totally makes sense, I can work it from here.

#

🤦 it's empty becaues that network is empty.

HEh thanks!

quaint moat
#

Is there a way to get the device name that is related to a sensor in a template?
I can grab the friendly name of the sensor, but that requires me to fix the friendly name meanwhile the device is the only value need.
{{ trigger.from_state.attributes.friendly_name }}

Im looking for something like {{ trigger.from_state.related.device.friendly_name }}

inner mesa
#

{{ device_attr('light.fr_torchiere_lights', 'name') }} -> Torchiere Lights (3C EB EC 1)

#

so ...

#

{{ device_attr(trigger.from_state.entity_id, 'name') }}

quaint moat
#

I thought automation triggers were considered "limited templates"

inner mesa
#

is that related?

#

that's clearly not a template trigger

quaint moat
#

Oh, I misspoke. Im using the template in an automation but not in the trigger part of the automation. That template I posted earlier was in the action side of the automation, which isnt a limited template.

strong idol
#

Hey everyone, I am trying to write a template that checks if a list (group_members of a media_player) has more than one entry. Does anyone have an idea on how to count list items? {{ states.media_player.mediaplayername.attributes.group_members }} is returning the list.

rare linden
#

looks like it was templating that had broken my hass as after yesterdays sanitization of my sensors code it's still up and running this morning, though my numbers and selects are not currently working which may also be a factor

rare linden
#

that will return true if any of those have that attribute so that means it must be greater than one, another way to do it if you wanted to get the actual value is ...

#

{{ states.media_player.mediaplayername | selectattr('attributes.group_members', 'defined') | selectattr('attributes.group_members') | list | count }}

#

though i just realised you probably want to count how many members are in the group_members attribute which i'll give you in a mo

#

forgot how to make groups it appears, i was gonna test thsi first, if group_members is a list of it's members this is how you'd do it {{ states.media_player.mediaplayername | selectattr('attributes.group_members', 'defined') | map('attributes.group_members') | list | count }}

#

that should do what you want

#

you might need an expand() around the states and selectattr before passing it to the map

#

also thinking about it you probably want states.media_player | selectattr('mediaplayername', 'defined')

#

that helps avoid getting erroneous entities

strong idol
#

Thanks a lot for your help. I just want to figure out, if a media player is grouped or not. The "group_members" attribute is always returning the media_players name, so it is at least a group of one. Trying your suggestion I am getting <generator object select_or_reject at 0x7f1399697ed0>

marble jackal
#

what did you currently use?

#

You probably did not add | list

strong idol
#

I tried {{ states.media_player.mediaplayername | selectattr('attributes.group_members', 'defined') }} when reporting back. 🙂

marble jackal
#

well, add | list at the end, and it will return the complete states objects of those entites with the group_members attribute defined

dapper igloo
#

Hi all. Does anyone know, if I use the platform rest, is it possible to extract all the Price1, Price2, etc. without specifying them one by one?

#

{
"records": [
{
"VATClass": "D02",
"Price1": 0.4322,
"Price2": 0.4322,
"Price3": 0.4322,
"Price4": 0.4322,
"Price5": 0.4322,

vestal narwhal
#

Can I ask an intuition question - I have been trying to use a input_number as a default value. So had some code like

{% if volume is defined %} {{float(volume)}} {% else %} {{float(input_number.sonos_volume)}} {% endif %}
#

This doesn't work without

states('input_number.sonos_volume')
#

But I have been using input_booleans as flags in tests

#

For context this was in the variables block at the top of a script

marble jackal
#

You could simplify that to

{{ volume | default(states('input_number.sonos_volume') | float) }}
vestal narwhal
#

But why the "states"

marble jackal
#

But states() is required

#

Because you need to get the state of the input number

vestal narwhal
#

So for input_boolean I am using them wrong?

marble jackal
#

Without it, it is just a string

#

The string input_number.sonos_volume

vestal narwhal
#

but isn't {{input_number.sonos_volume}} a number

marble jackal
#

No, now you didn't even add the quotes, making it a variable

#

To use the current state of an entity, you need to use states()

vestal narwhal
#

Ok - so these are entities and not variables

#

I have been thinking of them as "Globel variables"

#

But they are objects that store such a thing

marble jackal
#

Nope, they are entities, just like any other. An entity beloning to the input_number integration

vestal narwhal
#

tx

marble jackal
#

And the state of an entity is always a string, that's why you need to use float on it

vestal narwhal
#

Also good to know - so even further from a variable!

naive swan
#

Hey everyone, templates aren't my specialty, I'm trying to round my aqara temperature sensors so instead of saying 18.42c they'd round to just 18 etc I've tried the following but the log is spawning float errors. Can anyone assist?
{{ (states('sensor.bathroom_temperature') | float - 0) | round(0) }}

inner mesa
#

what's the - 0 for?

#

Whenever you say something like "spawning float errors", please do include them. Otherwise you're just much more difficult to help

#

They're probably about defaults, and you can find a post in the pinned messages specifically about that. And it means that your sensor state can't be converted to a float, such as if it actually has "c" in it and not just the value.

naive swan
# inner mesa what's the `- 0` for?

With the template I got it off the forums from someone who was looking to do the same as templates are something I'm yet to grasp myself so I try to find ones that work and then substitute, it works but it gives the error message
"TemplateError('ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ (states('sensor.bathroom_temperature') | float + 0.1 ) | round (0)}}' but no default was specified') while processing template 'Template("{{ (states('sensor.bathroom_temperature') | float + 0.1 ) | round (0)}}")' for attribute '_attr_native_value' in entity 'sensor.bathroom_temperature_rounded'" in the logs.

inner mesa
#

then see my reponses

#

the message is clear that your sensor state is "unknown"

patent flame
#

Hello, why {{sensor.shellyem_XPTO_channel_1_power_2}} gets me "UndefinedError: 'sensor' is undefined"?

marble jackal
#

because you are trying to get the value for the key shelly_XPTO_channel_1_power_2 out of a variable named sensor which you did not define

#

If you want the state of that sensor, you need to use {{ states('sensor.shellyem_XPTO_channel_1_power_2') }}

analog mulch
#

Hi. I have a group with a bunch (6) of number. entities with value range 0=<x=<100. I would like to have a template which counts how many of the 6 entities are above some threshold, say 50

mighty ledge
#

what kind of group

analog mulch
#

not sure how to convert to float and selectattr based on numeric condition

#

just a plain group defined in configuration.yaml

#

but it's only for this purpose, so I can redefine the group

mighty ledge
#

you have to use namespace

#

well, if you just want a count...

#
{{ expand('group.xyz') | map(attribute='state') | map('float', none) | reject('none') | select('>', 50) | list | count }}
analog mulch
#

lovely, I was kinda trying to come up with that!

marble jackal
#

I would use is_number
{{ expand('group.xyz') | map(attribute='state') | select('is_number') | map('float') | select('>', 50) | list | count }}

plain magnetBOT
#

@hollow girder I converted your message into a file since it's above 15 lines :+1:

hollow girder
#

my idea is to check the change for over x seconds, to avoid false positives. This works great, but when the sensor starts it keeps getting "unknown" because the template was never evaluated! Is there a way to solve this and ensure that the template is evaluated at start?

mighty ledge
#

after 10 seconds, it should be evaluated anyways

#

to either on or off

#

but in reality, do you even want the for on the off? Probably not.

hollow girder
hollow girder
mighty ledge
#

it'll evaluate when the states for the triggers change from false to true

hollow girder
#

I can do it on event restart.... but in that case I'm not able to check the "for"

#

but in that case probably I can forget it... and only go with less or more

marble jackal
wooden tusk
#

Rest sensor templating, i need some advice. Im trying to understand the mapping of json_attribute_path, json_attributes and value_template

#

The rest response provides an array with "$.[0].prices". The array contains field A, B and C.

#

json_attributes_path: "$.[0].prices"
json_attributes:
- A
- B
- C
value_template: "{{ value_json[0].name }}"

#

Is this the correct approach? What about value_template

plain magnetBOT
#

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.

inner mesa
#

please share the actual JSON response

wooden tusk
#

This is for the array of "prices"

#

The complete structure including the "prices"

#

This is a energy array using an algorithm to calculate if the current pricelevel is to be used for charging/discharging your home battery depending on the forcast of prices.

mighty ledge
#

ah nevermind, you posted this in an odd order

#

ok, you don't need to even set json_attributes path

#

simply

#
json_attributes:
- prices
#

and you'll get all the prices as a list

wooden tusk
#

So no path or value template?

mighty ledge
#

value_template you can output whatever you want

#

value_template: OK

wooden tusk
#

Im thinking how i in the best way visualise the result from the attributes

mighty ledge
#

what do you want from this information?

wooden tusk
#

Is like to follow the prices.level

#

It changes every hour with the timeelement

mighty ledge
#

ok, but which price?

#

you have a list

wooden tusk
#

The level shows the decision if the energy price level is "Cheap" or "Expensive"

mighty ledge
#

ok, do you want the cheapest?

wooden tusk
#

Yes, the array consist of 40 indexed vaues

#

They are all different

#

As you can see in the first array

mighty ledge
#

right, but you need to ask yourself "What am I going to do with this"

wooden tusk
#

id like to see into the future...

mighty ledge
#

Then there's not much more you can do

wooden tusk
#

This is the predicted energy levels in the future

#

Present +24h

#

The array shows the current level and the predicted future of 24h based on a algorithm

#

Every indexed value consist of level and time. eg. Current level "Cheap", but next hour "Expensive"

hollow girder
onyx quest
#

I'm writing an iOS notification that will take a user-input value and use it for a timer to turn off a fireplace. The notification is working properly, but I cannot figure out how to take the value from the textInput and pass it to delay: minutes:. Here is what I have so far: https://hastebin.com/odevopupix.less. I've tried a number of different things for the template of the delay: minutes: line, none of them work. Unfortunately my brain doesn't work with this stuff well and I just tend to get confused. Any help would be wonderful

marble jackal
#

don't you need the text_input from the wait trigger as well?

#

as this is a script, there will be no trigger object, only the wait.trigger object

#

If you look at the trace, you can exactly see how the trigger object is built

wooden tusk
#

Using a restful sensor and get the response that the "REST could not be parsed as json", im guessing a 255 char issue. How to restrict the response?

onyx quest
#

So I tried changing the line to minutes: "{{ wait.trigger.event.data[reply_text] }}" but that did not work either

cosmic hamlet
#

Hi there. I have a readme that states: check for {{ trigger.json.event == "incoming_call" }} e.g. in a "Choose" action type.
I need to check that or else my script is triggered on call and hangup. How do i do that?

inner mesa
#

Presumably that would be a template condition for a choose:, based on your description, so I would start there

cosmic hamlet
#

a google is my friend the name template condition was enough

onyx quest
#

and minutes: '{{ wait.trigger.event.data[reply_text] | float }}' gave me Error: UndefinedError: dict object has no element Undefined

marble jackal
onyx quest
#

Ok - that worked. But now, a new problem. I put "2" in the text box on my phone, but the trace shows delay: 120.

#

I'm guessing that prob means 120 seconds?

marble jackal
#

2 minutes is 120 seconds

onyx quest
#

Ok I figured that right as I hit enter lol

marble jackal
#

The standard input for delay is seconds

#

delay: 120

onyx quest
#

thank you so much -- once again a matter of syntax and formatting -- maybe one day I'll wrap my head around all of it lol

delicate sinew
#

is there something similar available like availability_template when using a command line switch? i want to grey out this switch on frontend when curl returns a non-zero code:

switch:
  - platform: command_line
    scan_interval: 10
    switches:
      relay1:
        friendly_name: "Relay 1"
        command_on: "/usr/bin/curl -X PUT -F 'mode=on' http://192.168.1.13/channel/1"
        command_off: "/usr/bin/curl -X PUT -F 'mode=off' http://192.168.1.13/channel/1"
        command_state: "/usr/bin/curl http://192.168.1.13/channel/1"
        value_template: '{{ value_json["mode"] == "on" }}'
rare linden
#

used to work fine but now when it calls the script the script receives a blank entry for brightness gives an error it recieved a dict

inner mesa
#

Where is 'value' set?

rare linden
#

cant remember where that came from, i had changed it to this.state but something went wrong with that so put it back to value, will change to state again

inner mesa
#

that's key to solving the problem 🙂

#

random changes, less so

#

I don't know what's happening with all the YAML anchors

rare linden
#

they are being passed into multiple other numbers

inner mesa
#

there's just not enough info there for anyone else to ehlp

#

other than pointing out that you seem to have used a variable that you haven't defined anywhere

rare linden
#

It's the entire code for that entity don't know what else I'm supposed to add

changed value to this.state and it's still blank when it reaches the script though when i hard code a number so the issue must be the script itself

#

its not the script as when i create an automation to trigger the script it works fine

#

cant find the documentation on template numbers that i once found

#

hence where it came from and like i said it used to work fine

#

it should equal the live state of the current number

#

have there been any changes to numbers in the last few versions?

rare linden
#

number still have their areas set so that's not the issue

vivid ridge
#

#templates-archived

“` type: custom:card-templater
card:
type: picture-entity
name_template: '{{ state_attr(''sensor.yellow_bin'',''days'') }} days'
show_name: true
show_state: false
entity: sensor.yellow_bin
state_image:
'0': /config/Home_Assistant_Images/Yellow_Bin.png
'1': /config/Home_Assistant_Images/Yellow_Bin.png
'2': /config/Home_Assistant_Images/Yellow_Bin.png
entities:

  • sensor.yellow_bin “`

how to i correctly access images in the home assistant directory

'1': /config/Home_Assistant_Images/Yellow_Bin.png

marble jackal
#

put them in the www folder and address them like this /local/image.png

rare linden
#

the issue is the brightness reguardless of what value i put even if i hard code a number to brightness doesnt reach the script it just complains about receiving a dict of value ''

#

if i manually trigger the script the script from a test automation it works fine so it's the entity at fault

marble jackal
#

What is the actual error you receive

rare linden
#

one mo

marble jackal
#

BTW the max brightness of lights is 255

rare linden
#

ok apparently disregard everything i just said as i just tested it to get the error and it's now working where it didn't before i went to bed

flint laurel
#

Hi all. I would like to access recorder data from a template. Is it possible? E.g. I want to get the max temperature of my boiler over the last 5 days. Thank you. Or do I need to create an new sensor just to do that?

marble jackal
#

templates only have access to current states

flint laurel
wooden tusk
#

Use a rest sensor to retreive data but get the warning "REST result could not be parsed as JSON"

#

json_attributes defined to array name, but array is indexed up to 47

#

Can i template as a filter?

turbid olive
#

ValueError: Template error: int got invalid input 'closed' when rendering template '{{ states(positionEntity) | int
How do I access the numeric state of my blinds from a template? states(positionEntity) returns me "Opend"/"Closed" which is not what I want.

coarse tiger
#
{{ state_attr('cover.cover', 'current_position') }}
mighty ledge
#

I'm not sure if you're using made up lingo or correct lingo

proven fog
#

I'm trying to create a sensor that tells me how many of my thermostat fans are 'on'. I currently have this:

{%- set count = 0 -%}
{%-if state_attr('climate.living_room', 'fan') == 'on'-%}
  {%- set count = (count + 1) -%}
{%-endif-%}
{%-if state_attr('climate.upstairs', 'fan') == 'on'-%}
  {%- set count = (count + 1) -%}
{%-endif-%}
#

But I feel like there's a way more concise way to do this

#

Any ideas?

uneven pendant
#

I'm struggling to get my template to use regex.

#

procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
0 0 0 127808 9088 41856 0 0 50 9 17 73 5 8 83 4

#

this is the output, trying to display only the free memory

#

value_template: >-
{%- set group = value.split("(?=\d)(?<= )") -%}
{{ group[5] }}

#

running it against this value template, and i'm getting nothing.

#

but if i run it against

  value_template: >-
    {%- set line = value.split("\r\n") -%}
    {{ line[1] }}
#

I get r b swpd free buff cache si so bi bo in cs us sy id wa

#

so it looks like it can do SOME regex, but not all

mighty ledge
mighty ledge
#
{% set lines = value.split('\r\n') %}
{{ lines[2].split()[3] }}
#

also, split doesn't run regex, taht's why your regex isn't working.

uneven pendant
#

@mighty ledge that introduces an issue though, the amount of spaces is variable, because the command has a variable amount of whitespace between numbers of different sizes, sometimes the free memory is 5 digits, sometimes it's 6 digits. Which would result in the displayed subset being a different value.

#

If i understand it correctly

mighty ledge
#

.split() without arguments strips all whitespace between

uneven pendant
#

knowledge makes life so much easier.

#

I'll go try it.

mighty ledge
inner mesa
#

Nice!

mighty ledge
#

still waiting on review?

inner mesa
#

languishing

#

excellent, now it has a conflict 🙂

mighty ledge
#

need a review?

inner mesa
#

with yours, I guess

#

yes

mighty ledge
#

haha, yes, I knew it was going to conflict

#

still wasn't too big of a conflict IIRC

inner mesa
#

I'm just watching the cars go by

#

it's really just this one line?
self.filters["states"] = self.globals["states"]

#

the thing is that I redid that whole section to make it easier to identify the requirements for each function/filter so that they can be handled/enforced, so each conflict calls out the whole thing

inner mesa
marble jackal
#

Very nice @mighty ledge

#

I like it

mighty ledge
#

i had to add a new method from Jinja to handle the tests

inner mesa
#

stupid github web editor:

This page is out of date. Start over

mighty ledge
#

by add, I mean import

inner mesa
#

that's not a conflict, though

mighty ledge
#

so it breaks your add_ext function

#

for what I added

inner mesa
#

oh

mighty ledge
#

So...

inner mesa
#

I guess I'll play with it. Unfortunate that it just stays broken

mighty ledge
#

well

#

you could add another arg

#

called...

inner mesa
#

I'm just amusing myself for now

mighty ledge
#

hmm

#

this change makes it a bit more difficult

#

add another arg called eval_test

#

with

#

            if eval_test is not None:
                self.tests[name] = pass_eval_context(test)
#

that's a band aide, but it would work

inner mesa
#

good tip. will investigate a bit later. I was already special-casing "states", so two more can't hurt 🙂

marble jackal
#

I was about to go to dev to test the new filters, until I was reminded the beta already starts tomorrow

mighty ledge
#

yeah, just be lazy and wait

uneven pendant
#

I couldnt' make that work but filtered the command providing the output and now it's working fine. @mighty ledge thank you so much for helping me.

vivid ridge
marble jackal
#

If you put them in www/Home_Assistant_Images

#

I would use lowercase though

#

But it should work like this as well

vivid ridge
mighty ledge
plain magnetBOT
#

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

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

vivid ridge
vivid ridge
#

was i suppose to config.yaml somthing

marble jackal
#

Does it work if you browse to it? http://ip:8123/local/folder/image.png

marble jackal
#

Oh, that's your external ip.. you should not have that open to the world without a certificate

vivid ridge
#

if i cared i wouldnt of sent it

marble jackal
#

If that works /local/home_assistant_images/yellow_bin.png should work internally

#

But you could also try the full url

vivid ridge
#

nope

marble jackal
wooden tusk
# mighty ledge You're going to have to explain more, your question doesn't really make sense

Let me try to detail out my problem. I have cloud service that is using a algoritm to predict the best way to control my Solar energy system battery of my home. It tells me if i should charge or discharge my battery depending on the size of my battery, consumption and current energy price. So every hour when i new price per kwh is activated it decides what to do. So id like to call the service not only for the current decision, id like to see what it predicts in the future. The price array will tell. The price array consist of the current decision but also 16h in the future. As long as the future prices are decided. But when i call this array i get in response that the "REST result could not be parsed as JSON". My guess its to big? Its an array with 47 records. Every record consist of the decision, price and timestamp.

#

Id like to put the complete array in the attribut so i can use a apex graph to display to future

mighty ledge
#

there's no limit to json read from an endpoint

#

take the result coming from the endpoint and run it against a json formatter

#

it'll tell you where the error lies

wooden tusk
#

It shows the array

mighty ledge
wooden tusk
mighty ledge
#

it formats fine, so that means there's hidden characters that are returned from the endpoint

#

{{ value[0:] | from_json }}

wooden tusk
#

I use the following in the rest sensor to map

#

json_attributes:
- prices
value_template: "OK"

mighty ledge
#

you won't be able to if it's outputting special hidden characters

wooden tusk
#

Hard to tell, the only debug i managed was to apply the logger to the rest sensor

#

It looks fine using the http request in Nodered

mighty ledge
#

I can tell you from experience, that's what it's doijng if it's failing to load the json.

#

yuou don't have to believe me, but I would bet money on it.

wooden tusk
#

🙂

boreal basalt
#

Trying to setup a if statement to check if rain is in the forecast for the next 10 hours. Currently have a template that checks if it is raining in the current hour, but not sure how to expand to check multiple attribute entries.


Bring Umbrella

{%endif%}```
#

This works, but the [0] makes it only check the current hour. Any idea how I check if in multiple hours

inner mesa
#

{{ state_attr('weather.home', 'forecast')[:10]|selectattr('condition', 'eq', 'cloudy')|list|length > 0 }}

#

we don't get rain in San Diego, so...

#

@boreal basalt

boreal basalt
plain magnetBOT
#

@shrewd python I converted your message into a file since it's above 15 lines :+1:

dark quest
buoyant pine
#

anything in /local (/config/www in HA) is accessible without auth

#

why they've decided to not use SSL/TLS is a mystery though

dark quest
#

yea use a VPN and connect locally if u really need to get to HA from outside the network...

#

anyway that's off topic from this channel 🙂

buoyant pine
#

well, having HA accessible remotely isn't as much of an issue with SSL/TLS, a strong password, and MFA

dark quest
#

agreed

dark quest
buoyant pine
#

they don't seem to care 😆

dark quest
#

i bet it's getting hammered

#

with attacks

buoyant pine
#

to be fair, i've had my instance exposed to the internet for years and i can count on one hand how many invalid login attempts i've seen

dark quest
#

pretty impressive

dull burrow
#

he could at least setup fail2ban in configuration.yaml

sturdy yarrow
#

Anyone here know how I can get equal and less than working in a template? My template now is only true when the date sensor and helper sensor is the same, but I would work better if the else part only came if it was the same or more... This is what I have now. I tried with | float < sensorname but that didn't work.. Here is what I have so far:

#

{% if states.sensor.date.state == states.input_datetime.helper_dato_for_hjemmekontor.state %}
{% else %}
{{ state_attr("input_datetime.helper_dato_for_hjemmekontor", "timestamp") | timestamp_custom("%d %B") }}
{% endif %}

#

The reason why I do not have anything before the "else" statement is cause I have a date on my dashboard that I only want to show up if todays date is before the date in the helper.

marble jackal
sturdy yarrow
coarse tiger
#

how can I get a Int of number of attributes of a entity?

#

I have multiple device_tracker entities of which some are from the ping integration - I specifically want to count the ones from the ping sensor and apparently these only have 2 attributes (source_type: router and friendly_name:) compared to many more from other device_tracker integrations

#

there might even be a better way but I don't know of any

#

{{ integration_entities('ping' ) }} does not work either

inner mesa
#

{{ states.device_tracker|map(attribute='attributes')|map('length')|select('==', 2)|list|count }}

#

-> 27

#

I suspect that the problem with {{ integration_entities('ping') }} is that it's configured in YAML and doesn't have a config_entry, but that's just speculation

coarse tiger
#

awesome, thanks!

inner mesa
#

just changed it to better match your need

coarse tiger
#

yeah the ping integration is somewhere between, like the known_devices relics 😄

rapid plinth
#

Quick question for one of you template wizards ... How to make this round up to "90" ??

#

{{ 88.55 | round(0, 'common') | int }}

inner mesa
#

I just guessed at round(-1)|int and it worked

rapid plinth
#

@inner mesa WOO HOO thanks man thats perfect 🙂

deep marsh
#

Hi! Is there any way to distinguish lights from light groups in a template? Since light groups can be created with helpers, I cannot really find a way to rule out light groups when I retrieve a list of lights that are on for example.

dull burrow
#

cant that be solved just by naming the group something different?

#

or you mean light.*

deep marsh
#

Yes, sure. That can be done, but then I need to use the word Group in the name for example. In the past you could exclude the domain: group. I don't think there is another option than changing the name 😒

slim elk
#

@deep marsh the light group helper has an entity_id attribute listing those entity members of the group that you could test on {{ state_attr('light.test', 'entity_id') is not none }}

deep marsh
dull burrow
deep marsh
#

I guess I need to use a name convention for groups. In that case it's easy.

dull burrow
#

That’s what I started doing. Ending in _group for zigbee groups and _all for hass lightgroups

deep marsh
marble jackal
#

But I don't think it works on Z2M groups, they don't have an something to identify them by in the attributes

deep marsh
#

Yes indeed

#

The thing is that light groups respond more reliable if you create them in Zigbee2MQTT. At least, that's my humble experience.

marble jackal
#

Yeah, that's correct. I use Deconz and they have an identifier

#

So in that case naming would be the easiest

deep marsh
#

Indeed. I used Deconz before and that was way easier. Maybe I can add a request to the Zigbee2MQTT github to send some sort of identifier for groups to Home Assistant.

#

Not that it will be done, but I can try.

dull burrow
#

im not sure if it's the best way but i have multiple zigbee groups (to turn on chandelier, cans, chand+cans+bulb) then i add say one zigbee group of all kitchen lights + kitchen leds (not zigbee) to one big home assistant group for kitchen_lights_all then i pass these all through to homekit for siri to be able to take advantage of the zigbee groups too

deep marsh
#

This is how I did it too in the past, but I didn't like the fact that I had "double" groups in Home Assistant. One big plus for creating light groups in Home Assistant and populating them with the same groups from Zigbee2MQTT is that if you want to migrate to for instance ZHA, you do not have to go through and check all your automations, scripts and scenes after that. Just fill the HA groups with the new groups from ZHA and everything should work right away.

dull burrow
#

in my case each led strip in each room is not zigbee so i need a home assistant group for them or need to use multiple entities for actions anyways

steady crane
#

Hey there 👋 I try to understand why a template in the data attribute (https://www.home-assistant.io/integrations/notify.rest/#data) for a RESTful notification always results in a string in the sent json payload. Setting e.g. priority: 1 sends out an integer ({"priority": 1}) but as soon as a template is involved, I always see {"priority": "1"} as output. I tried several things like e.g. |int or fixed integer values in the template. I even did some maths to see if the internal value is really an integer (priority: "{{ data.prio + 1 | int }}") which results in {"priority": "2"} . This indicates that not the template itself is the problem but something happening later? I read something about "schemas" and wonder if this might be my problem here but failed to understand them. If schemas are to blame, wouldn't that mean that priority: 1 would be broken too? Any hint appreciated!

obtuse zephyr
#

What's the best way to fetch how much time has elapsed since a motion sensor was active? Mine at least don't have any type of last_changed attribute.

inner mesa
#

that would be a property, not an attribute

#

type {{ states.binary_sensor.xxx.last_changed }} into devtools -> Templates

obtuse zephyr
#

Gotcha, that doesn't show in the attributes list in the States dev tools, but it does show up in templates

#

But... you did say it was a property

#

So that makes sense then I suppose

inner mesa
#

right, again, it's not an attribute

obtuse zephyr
#

thanks

waxen meadow
#

i have question how make a template for lowest temperature last 12 hours?

slim elk
waxen meadow
#

is not working

#

here is my code @slim elk

#
  • platform: statistics
    name: "Outside Feels like Temperature Lowest last 12 Hours"
    entity_id: sensor.outside_feels_like_temperature
    unique_id: 62da69ac-547d-11ed-bdc3-0242ac120002
    state_characteristic: value_min
    max_age:
    hours: 12
coarse tiger
#

check your indentation and have a look at the logs for related errors

waxen meadow
#

in reality it just works poorly @coarse tiger

coarse tiger
#

what works poorly?

waxen meadow
#

bad values

coarse tiger
#

have you read the docs?

#

specifically the part on state_characteristic:?

waxen meadow
#

last 12 hours lowest temp is 7.1

clear jungle
#

Is anyone available to help me create a trigger-based template sensor based on a zwave_js.value_updated trigger? I'm new to template writing and am looking for some guidance

thorny snow
#

I am trying to pipe/feed a tts script with the Google calendar integration.
The end goal is, if there is a meeting today, it should be spoken/displayed otherwise ignored since it returns the next meeting regardless of date.
I have not tried to take time into account at all, just the date.
The code was working yesterday but it doesn't anymore and I can't for the life of me figure out why.
I did do a upgrade to HAOS 9.3 from 9.2 but that shouldn't be a issue (or should it?)

{% if is_state(as_timestamp (state_attr ('calendar.english_reminders', 'start_time')) | timestamp_custom('%Y-%m-%d'), as_timestamp (now()) | timestamp_custom('%Y-%m-%d')) %}
There is an event today
{% else %}
There is no event today
{% endif %}
deft timber
#

The first argument of is_state(...) should be the name of an entity. In your code, it is a string representing a date. You should not use is_state(...) here.
Try this {% if(as_timestamp (state_attr ('calendar.english_reminders', 'start_time')) | timestamp_custom('%Y-%m-%d') == as_timestamp (now()) | timestamp_custom('%Y-%m-%d')) %}

thorny snow
#

Thanks, just gotta wait the for the calender integration to update to verify

#

Works! Great many thanks for sorting that for me @deft timber!

marble jackal
#

@thorny snow @deft timber both are a bit overcomplicated
{% if as_datetime(state_attr('calendar.english_reminders', 'start_time')).date() == now().date() %}

wet ruin
#

Hello,

i need ur help. Im building an automation which writes the current set temperatur to an input_number.

service: input_number.set_value
data_template:
  entity_id: input_number.current_set_temp{{ area_id(trigger.entity_id) }}
  value: "{{ state_attr('climate.bathroom ', 'temperature') | float }}"

That is working. But i want to automaticly get the temperatur from the climate.area_id (see example below which is not working. (result is 'none')


value: "{{ state_attr('climate.area_id(trigger.entity_id) ', 'temperature') | float }}"
marble jackal
#

@wet ruin you probably want this:
value: "{{ state_attr('climate.' ~ area_id(trigger.entity_id), 'temperature') | float }}"

wet ruin
marble jackal
#

to explain: if you put stuff between quotes, it is a string. If you want to use a function like area_id() you cant't put it between quotes

#

~ is used to combine the part left of it, and the part right of it as a string

wet ruin
#

Okey, now i got it. That's perfect.

deep marsh
onyx quest
#

I have a basic template cover set up for my garage door opener, with a ZEN17 and a tilt sensor. Is it possible to run any actions via the template between triggering the switch and the door closing? Or would I have to create a second template switch that would trigger an automation? Specifically I'd like to have a speaker announce that the door is closing, and browser_mod pop-up a view of the garage camera a second or 2 before the garage closes

deep marsh
inner mesa
#

You would do that with an automation based on the door state reported by the template cover

mighty ledge
inner mesa
#

oh, yeah. forgot that you can add multiple actions

onyx quest
thorny snow
rare linden
mighty ledge
#

so, what's up with {% set result = ((values | average | int + 1) / 4) | round * 4 %}

#

you're rounding dividing by 4 then multiplying by 4

rare linden
#

as integers so it's rounded down to the nearest 4

mighty ledge
#

ok

#

I don't see how it can get stuck at 160

#

well..........

#

you are seelcting greather than 31

#

well, no, that shouldn't matter

#

so, clarify something for me, is it going below 160 then snapping back to 160?

rare linden
#

yeah i can drag it below 160 and it snaps back to 160

#

and any number above 160 it will change and then jump higher than it was slided

#

192 jumps to 224 for example

mighty ledge
#

how many lights?

rare linden
#

on the room i'm testing only the one

#

i just realised there's also a light strip it might be picking up i added yesterday

#

but that is off so the select gt than 31 should filter it out

#

i'll test it under developer tools to make sure it's not an averaging issue

mighty ledge
#

where's value coming from?

#

nm

#

I don't see anything that would cause this

#

looks good to me

rare linden
#

ok there is another light getting picked up as the result before average is 191 and 255

mighty ledge
#

what's your script doing

#

ah, that would make sense

#

why aren't you using a light group for this BTW?

#

speaking from experience, I avoided them in the past... they are just too good now to avoid. No need for templates like this

#

yeah they take a little bit to set up, but they work really well. Specially if all the lights have the same supported features

rare linden
#

because i forgot to update it to use single entities over getting everything

originally didn't need it for most rooms as there's only one main light and originally i designed it for all the lights in the room as the kitchen has 2 bulbs and had issues with groups as the way home assistant turns on and off the light is uncompatible with those ulbs, i've since changed the script to have a work around where it directly sends mqtt to those bulbs

#

will change that now since i longer need to pole them all

rare linden
dull burrow
#

thx

dim iron
#

Well this was a fun bug that I was starting to bash my head against the wall until I found this issue…

stuck kelp
#

Trying to pickup {{ trigger.from_state.friendly_name }} but it shows in the automation trace that is is nested under "attributes" like:

trigger:
entity_id: person.human
from_state:
entity_id: person.human
state: home
attributes:
editable: true
friendly_name: Human

How can I get the template to render the attribute?

#

Giving this a go for the next trigger. Out of ideas after that:

{{ selectattr("trigger.from_state", "friendly_name") }}

#

Didn't work 😦

marble jackal
#

Your last template is a mismatch of the selectattr filter and state_attr

stuck kelp
#

I feel like I tried the attributes suggestion and it didn't work. Happy to try again

marble jackal
#

This would also work, but that's not always the attribute at the time if the trigger (however, friendly_name is normally static)
{{ state_attr(trigger.from_state.entity_id, 'friendly_name') }}

stuck kelp
#

Ahh I like that one

marble jackal
#

Note I did not use quotes around the trigger variable, as it is a variable 🙂

stuck kelp
#

Ah, pretty sure I wrapped it in quotes on one of my tries 😂

Cheers mate!

dry narwhal
#

Hi everyone,
anybody know why this works
title: states['input_select.days_back_to_show'].state+'d'
and this does not
title: 'Xiaomi'+states['input_select.days_back_to_show'].state+'d'
It seems to be allowed to append a string but not prefix.

deep marsh
#

@dry narwhal Tried it here and it works here with this code:

{{ 'd' + states('binary_sensor.office_motion_sensor_occupancy')+'d' }}

shows dond in my case

#

I never use square brackets when using states. Maybe that's it?

mighty ledge
mighty ledge
marble jackal
#

{{ states['input_select.days_back_to_show'].state }} this would work in jinja though

#

you need the square brackes if you want to include a variable

#

eg

#
{% set e = 'sensor.whatever' %}
{{ states[e].last_changed }}
dry narwhal
# mighty ledge where are you attempting to add this? 1. You don't have 'template' indicators....

This is created using config-template-card and passed to apexcharts-card.

type: custom:config-template-card
entities:
  - input_select.days_back_to_show
variables:
  span: states['input_select.days_back_to_show'].state+'d'
  days: |
    -states['input_select.days_back_to_show'].state+'d'+'1d'
  name: area_name('this.entity_id')
  title: 'Xiaomi'+states['input_select.days_back_to_show'].state+'d'
card:
.
.
        header:
          title: ${title}

Result should be "Xiaomi 2d". So I want to see the (changing) time span in the title.
(P.S.: area_name is not working yet. That is next on my list of "figure out how to do that")

marble jackal
#

that looks like it uses javascript

mighty ledge
#

That also requires [[[ and ]]]

marble jackal
#

BTW, the examples use this name: "${ some template }"

dry narwhal
mighty ledge
#

It’s needed at all times

#

Er, nope. What thefes said is needed at all times

#

Mixing up cards

dry narwhal
#

It works without the [[[ ]]]

dry narwhal
mighty ledge
#

It needs the ${ }

#

Is that field in your variables section?

dry narwhal
#

As you can see in my code above, I first define the variables, so without the {$}. Then I want to use that later.
And in the variables section I cannot get it to work with string+template+string, only with template+string

marble jackal
rich quarry
#

This would just output on if the current price is higher than the upperband price?```binary_sensor:

  • platform: template
    sensors:
    unload:
    value_template: "{{ states('sensor.day_ahead_current_price') | float > states('sensor.day_ahead_upperband_price')}}"```
#

Because currently it says it's unavailable constantly

#

even tho the two sensors are working

marble jackal
#

you need to convert the last sensor to float as well

rich quarry
#

because currently current price = 0.1 and upperband is 0.11

marble jackal
#

you are now comparing a numeric value with a string

#

Which you would have seen if you checked the log 😉

rich quarry
#

I should have, thanks!

#

Also, if i update this in the file editor, do i need to restart the system for it to take effect?

#

Maybe i've been doing it all wrong

#

Logs say something like can't turn string into float

marble jackal
#

what's the exact log message

#

and, what are the states of these sensors. is one of them unavailable maybe?

deft timber
plain magnetBOT
marble jackal
#

in developer tools, there doesn't seem to be a link available in the bot to YAML

#

but that's the tab you need

rich quarry
# marble jackal what's the exact log message

TemplateError('ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ states('sensor.day_ahead_current_price') | float > states('sensor.day_ahead_upperband_price') | float}}' but no default was specified') while processing template 'Template("{{ states('sensor.day_ahead_current_price') | float > states('sensor.day_ahead_upperband_price') | float}}")' for attribute '_state' in entity 'binary_sensor.unload' while all off the entities are available

marble jackal
#

are you sure you didn't make a typo anywhere. one of these states() functions returns unknown instead of a numeric state

rich quarry
#

Doesn't look like it, all the entity names are typed correctly

#

But the templates show both 1 on and 1 off, but nothing changes

marble jackal
#

sorry, what did you mean with that last sentence?

#

anyway, what does this return in devtools > templates

{{ states('sensor.day_ahead_current_price') }}
{{ states('sensor.day_ahead_upperband_price') }}
rich quarry
# marble jackal sorry, what did you mean with that last sentence?

Yea i didn't know how to say it properly, i have 2 templates i should have also said, 1 is load and 1 is unload. I have 2 input numbers and those change into the upperband price thing, so if i change the input numbers one of the upperband or lowercase should change to on but now 1 upperband is on and lowerband is off

marble jackal
#
binary_sensor:
  - platform: template
    sensors:
      unload:
        value_template: "{{ states('sensor.day_ahead_current_price') | float > states('sensor.day_ahead_upperband_price') | float }}"
        availability_template: "{{ states('sensor.day_ahead_current_price') | is_number and states('sensor.day_ahead_upperband_price') | is_number }}"
#

that would remove the errors in the log, and make binary_sensor.unload unavailable when one of the source sensors is not returning a numeric value

#

if they both do return a numeric value, it will be either on or off

rich quarry
#

Alr thanks! Will try that when i can use my laptop today

dry narwhal
#

I think now I have an actual template problem 🙂

I would like to convert a date delta to hours, starting from now and then adding an "h" so apex knows the unit is hours.
I would have thought that this should work, but again, I thought wrongly.
graph_span: {{ (now() - input_datetime.startdate)/60/60+'h' }}
Then I thought I might need timestamp, but that also failed.
graph_span: {{ ((as_timestamp(now()) - as_timestamp(input_datetime.startdate))/60/60) +'h' }}
Or is my adding if the string "h" read as a mathematical function?

cosmic hamlet
#
condition: template
value_template: >-
 {{ as_timestamp(state_attr('calendar.persoonlijk','start_time'))  |
  timestamp_custom("%Y-%m-%d") == states('sensor.date') }}

this states as true in templating but i cant get it work as a condition

arctic sorrel
#

Please share the whole automation then

plain magnetBOT
#

@cosmic hamlet I converted your message into a file since it's above 15 lines :+1:

cosmic hamlet
#

if i cast it to a hacks var its working :/

#

oh one sec

#

{{ as_timestamp(state_attr('calendar.persoonlijk','start_time')) |
timestamp_custom("%Y-%m-%d") == as_timestamp(now()) |
timestamp_custom("%Y-%m-%d") }}

marble jackal
#

@cosmic hamlet {{ as_datetime(state_attr('calendar.persoonlijk', 'start_time')).date() == now().date() }}

cosmic hamlet
#

ty

pastel moon
plain ridge
#

Hey, I have a window and i wanted to get a message every morning at 7 if its going to rain that day.
I have this so far but it does not say anything in the message

data:
  title: Weer Vandaag
  message: Expect {{state_attr("weather.forecast_thuis", "forecast"[0]).condition}} conditions with high of {{state_attr("weather.forecast_thuis", "forecast"[0]).temperature}} degrees, and {{state_attr("weather.forecast_thuis", "forecast"[0]).humidity}}% humidity

The message will look like:
Expect conditions with high of degrees, and humidity

mighty ledge
#

you have ...state_attr("weather.forecast_thuis", "forecast"[0]), it needs to be state_attr("weather.forecast_thuis", "forecast")[0]

#

@plain ridge ^

plain ridge
#

Ah thanks!

buoyant pine
#

expect a temperature and humidity

bronze prawn
#

I'm using this template a s trigger for my alarm system to detect open doors/windows:

{% set entities = [states.sensor.front_window,states.sensor.laundry_door,states.sensor.master_window,states.sensor.patio_door,states.sensor.front_door] %}
{{ entities | selectattr('state','in','open') | list | length}}

This works fine. I would like to expand this to show the 'friendly name' of any of these entities that have a state of 'open' so I can use it in a notification message. Can someone help me in figuring out how to do that?

marble jackal
#

Is this your trigger? This will only trigger if it goes from 0 (= false) to 1 (= true). Not if it increases further

rapid ibex
#

How can I adjust the decimal.places in an mqtt sensor

#

Right now it has several, I only need two or one

marble jackal
#

@bronze prawn I would suggest to put the entities in a group (old style in YAML) and then use that.
You can then use this for the names
{{ expand('group.sensors') | selectattr('state', 'eq', 'on') | map(attribute='name') | list }}

bronze prawn
#

I'm doing everything I can to do my configs from the interface and I do not think I can add these sensors to a group using helpers. Is that right?

marble jackal
#

Correct

bronze prawn
#

booo 🙂

marble jackal
#

I was about to suggest to create a template sensor with the count you use as the trigger now

#

Which also has to be done in YAML

#

But then you can trigger on a state change of that sensor

#

So it will also trigger if it increases from 1 to 2

bronze prawn
#

Right. I'm not against it and putting in group makes it easier to modify but just trying to get away from file based configs

#

It's for alarm so if it goes from 0 to 1 it won't matter if it goes to 2 or more.

#

Thanks for the help. What you provided will work great!

marble jackal
#

But it will only trigger once, so you will only ever see the first name. So sending the name will be very limited

bronze prawn
#

That's fine. What I'm trying to accomplish is :

IF [that list of sensors count of 'open'] is greater than 0 THEN set alarm to alarming AND send notification with name of door/window that is open

Can I trouble you to tell me how to roll that into the if statement in YAML?

I thought it would be like this but apparently not:

{% set entities = [states.sensor.front_window,states.sensor.gabrielle_window,
states.sensor.laundry_door,states.sensor.master_window,states.sensor.patio_door,states.sensor.front_door
] %}
{% if {{ entities | selectattr('state','in','open') | list | length}} > 0 %}
{{ entities | selectattr('state', 'eq', 'open') | map(attribute='name')|list }}
{% endif %}
inner mesa
#

you're nesting your template

#

{% if {{ entities | selectattr('state','in','open') | list | length}} > 0 %}

#

remove the {{ }}

#

you're also using "in" in the first and "eq" in the second line, which is weird, but should work

serene shore
#

Hey Guys, im struggling with a jinja 2 Template for my Waste Collection Schedule... The Numbers who should display are not in Numeric Order and i dont know how to fix the problem.

The Code is Below.

{% set liste = [(states('sensor.restmuell'), 'Restmüll:',),
(states('sensor.papiermuell'), 'Papiermüll:',),
((states('sensor.plastikmuell'), 'Plastikmüll:'))] %}

{% for tage, text in liste|sort(reverse=true) %}
{{ text }} in {{tage}} Tagen <br>
{% endfor %}

inner mesa
#

states are strings

#

You can add |float to each states() call, or you can maybe use |map('float')before the sort (but I don't know what that will do to your tuples)

stuck tiger
dull burrow
#

might be recreating the wheel here

inner mesa
#

meh, can't get map() to work on that

#

but yes, that custom component is The Way

dull burrow
inner mesa
#

?

#

nothing, it doesn't work

dull burrow
#

im not familiar with what map() is or does

inner mesa
#

ok, your question wasn't clear

#

"what do"

dull burrow
#

it's a meme 😦

inner mesa
#

I guess I'm too old for that

dull burrow
#

i try to keep up with the kids and sprinkle some stuff in. i dont go full "bet fam frfr" though

inner mesa
#

essentially, it can extract values from objects or apply filters to iterators

serene shore
#

sorry maybe you missunderstood me. I dont want to create a new Waste Collection Module:D i allready use one. But i want to Display the Values in the correct order on my MagicMirror. And therefore i need the jinja2 Template.

inner mesa
#

did my suggestion work?

bronze prawn
#

@inner mesa Thanks for the help. I'm using this in dev console templating and it is doing as expected. Trying to move as a trigger for automation but it is not triggering. This is what I'm using for trigger:

trigger:
  - platform: template
    value_template: >-
      {% if  entities | selectattr('state','in','open') | list | length > 0 %}True{%endif%}

I tought if I returned true it would fire.