#templates-archived

1 messages · Page 18 of 1

half pendant
#

I created a Reimann sensor that’s created from a template of an energy sensor but it doesn’t reset daily, how do i fix that? Here is the template

    - name: TV Room Aircon Energy
      unit_of_measurement: W
      state: >
          {{ state_attr('switch.tv_room_aircon_outlet', 'current_consumption') }}```
still plank
half pendant
formal ember
#
service: light.turn_off
target:
  entity_id: "{{ states.light | map(attribute='entity_id') | list }}"

Any ideas how to put an exclude in this template?

marble jackal
#

what do you want to exclude?

#

based on entity_id, state, color_mode?

formal ember
#

light.wled_christmas_tree_master

#

it turns off the wled master switch which we don't use

marble jackal
#
service: light.turn_off
target:
  entity_id: "{{ states.light | map(attribute='entity_id') | reject('eq', 'light.wled_christmas_tree_master') | list }}"
formal ember
#

nice! whats eq?

#

equal?

marble jackal
#

yes, you can also use == or equalto

mighty ledge
#

You changed the variable from sensor to people which broke it. You have to change the other sensor in that line to people as well.

paper hazel
#

I changed it back, using your default as posted and for some reason it fails on the condition. I'm now going through it line by line

marble jackal
#

@paper hazel I briefly scrolled through the posts above, do you have other anniversaries in the custom anniversaries integration besides birthdays?

paper hazel
#

I'm sure I made a mistake somewhere, but unsure where at this stage 😟

paper hazel
mighty ledge
paper hazel
#

Thank you!

marble jackal
#

okay, you could also use
integration_entities('anniversaries') | select('search', 'birthday_') | list
instead of
states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list

paper hazel
marble jackal
#

oh wait, I see you also select on the state now

paper hazel
#

This part seems to render fine, it fails on the condition, which tests the variable items. But for the life of me I cant see why states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list

#

petro was kind enough to assist in the wee hours of this morning with this. My original implementation I was working towards was much longer and more complicated...

marble jackal
#

Veels geluk! Hoop dit is n mooi jaar... is this Afrikaans?

#

never realized you can use replace in map(). I always joined them, did the replace, and then split. I've been stupid 🙂

green scaffold
#

How to copy input temperature data from 1 thermostat to anotherr?

mighty ledge
#

or, revamped to cover each method and show them as tests, filters and methods

#

@paper hazel try changing

{% for sensor in sensors if config.get(sensor, False) %}

to

{% for sensor in sensors if config.get(sensor) is not none %}
#

and if you don't plan on using name, then....

#
- alias: Notify Birthday Message on Whatsapp
  id: 'rtWpsuf0G8BVEviZK2aeGaM9wDRBWJOuttiDhWVvHX83koW2yWZsJ1LwdboEgLZl'
  mode: queued
  trigger:
  - platform: time
    at: "07:04:34"
  variables:
    config:
      test_person: "2712345678@s.whatsapp.net"
    people: >
      {{ states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'birthday_', '') | list }}
    items: >
      {% set ns = namespace(ret = []) %}
      {% for sensor in sensors if sensor in config %}
        {% set ns.ret = ns.ret + [ config[sensor] ] %}
      {% endfor %}
      {{ ns.ret }}
  condition:
  - platform: template
    value_template: "{{ items | length > 0 }}"
  action:
  - repeat:
      for_each: "{{ items }}"
      sequence:
      - service: whatsapp.send_message
        data:
          clientId: default
          to: "{{ repeat.item }}"
          body:
            text: "Veels geluk! Hoop dit is n mooi jaar..."
marble jackal
mighty ledge
#

@paper hazel another way to do items would be

    items: >
      {{ config.items() | list | selectattr('0', 'in', sensors) | map(attribute='1') | list }}
#

i'd probably go that route tbh

#

I don't know why I didn't think of it last night

#

probably because I assumed you wanted the name too

marble jackal
#

must have been the hangover 😛

mighty ledge
#

maybe 🤣

marble jackal
#

where is sensors defined? Or do you mean people

#

I think you need to replace sensors with people in the for loop as well

#

or just name the variable sensors instead of people

paper hazel
paper hazel
mighty ledge
#

lol, that's 100% unrelated to any of the code you've been posting

#

data['condition'][0] tells you the condition is failing

#

I see the error

marble jackal
#

{{ config.items() | selectattr('0', 'in', sensors) | map(attribute='1') | list }} this also works without the | list after items() BTW 🙂

mighty ledge
#
  condition:
  - condition: template
    value_template: "{{ items | length > 0 }}"
mighty ledge
#

@paper hazel see my previous response with the condition change.

marble jackal
#

but anyway, sensors should be replaced with people

mighty ledge
#

oh ffs, he changed that too? ok, yes

marble jackal
#

the variable is named people, not sensors

mighty ledge
#

@paper hazel here's the changes, please don't change names of things 🤣

- alias: Notify Birthday Message on Whatsapp
  id: 'rtWpsuf0G8BVEviZK2aeGaM9wDRBWJOuttiDhWVvHX83koW2yWZsJ1LwdboEgLZl'
  mode: queued
  trigger:
  - platform: time
    at: "07:04:34"
  variables:
    config:
      test_person: "2712345678@s.whatsapp.net"
    people: >
      {{ states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'birthday_', '') | list }}
    items: >
      {{ config.items() | selectattr('0', 'in', people) | map(attribute='1') | list }}
  condition:
  - condition: template
    value_template: "{{ items | length > 0 }}"
  action:
  - repeat:
      for_each: "{{ items }}"
      sequence:
      - service: whatsapp.send_message
        data:
          clientId: default
          to: "{{ repeat.item }}"
          body:
            text: "Veels geluk! Hoop dit is n mooi jaar..."
marble jackal
#

I'm still failing to see what was wrong with the condition BTW 😛

mighty ledge
#

lol

#

it's a simple one

#
- platform: template
#

vs

#
- condition: template
marble jackal
#

aaah crap

mighty ledge
#

YEP

marble jackal
#

💩

mighty ledge
#

yaml error, nothing to do with the template

marble jackal
#

would have been more obvious if they would have used trigger: template instead of platform: template

mighty ledge
#

don't get me started on all that

#

they should have been consistent with it all

paper hazel
#

and there it suddenly passes flawlessly....

#

Thank you both so much - kinda feel a bit stupid for not spotting it....

mighty ledge
#

next time just share the error, it's something none of us would have spotted

#

but the error poitns right to where the issue is and we've helped enough people to know what each error means

paper hazel
#

Just a last question - Can I duplicate the automation, and split the people, depending on language and just alter the text? I believe it should work...

mighty ledge
#

sure if you want... but...

#
- alias: Notify Birthday Message on Whatsapp
  id: 'rtWpsuf0G8BVEviZK2aeGaM9wDRBWJOuttiDhWVvHX83koW2yWZsJ1LwdboEgLZl'
  mode: queued
  trigger:
  - platform: time
    at: "07:04:34"
  variables:
    config:
      test_person: 
        whatsapp: "2712345678@s.whatsapp.net"
        message: "Veels geluk! Hoop dit is n mooi jaar..."
    people: >
      {{ states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'birthday_', '') | list }}
    items: >
      {{ config.items() | selectattr('0', 'in', people) | map(attribute='1') | list }}
  condition:
  - condition: template
    value_template: "{{ items | length > 0 }}"
  action:
  - repeat:
      for_each: "{{ items }}"
      sequence:
      - service: whatsapp.send_message
        data:
          clientId: default
          to: "{{ repeat.item.whatsapp }}"
          body:
            text: "{{ repeat.item.message }}"
paper hazel
#

I understood from your explanation yesterday that this line should stop the process if no match is found under config. So duplicating it in its original form and splitting the lists should function as intended, or did I understand incorrectly.```
{% for sensor in sensors if config.get(sensor) is not none %}

mighty ledge
#

right, but that old template isn't needed because you aren't creating or using the persons name, so all you need for items is

{{ config.items() | selectattr('0', 'in', people) | map(attribute='1') | list }}
#

which does the same thing

#

essentially

paper hazel
#

Is there a massive drawback using the original one vs the simpler one - Reason for asking, I have 110 people in the list, and to add those attributes is gonna be quite an admin task. There are only 13 exceptions currently which would use english vs Afrikaans.

#

Could probably get the attributes added in with notepad++, and I perhaps see the option to add more customised message per person...

#

There might be more value, for the current manually input needed...

mighty ledge
#

Ok, just make the 2 automations then

#

no big deal then

paper hazel
#

Cool Stuff! Thank you for all your help - It has been a massive learning experience for me. Hopefully I pay it forward some time...

hollow mortar
#

How to do this so it outputs ia properly:

{% set variable = 'ia' %}
{{ var' ~ variable ~ 'ble }}
still plank
#

{% set variable = 'ia' %} {{ 'var' + variable + 'ble' }}

marble jackal
#

the ~ was fine as well, that converts all the parts to a string

#

This will fail:

{% set variable = 123 %}
{{ 'var' + variable + 'ble' }}

This will work:

{% set variable = 123 %}
{{ 'var' ~ variable ~ 'ble' }}
hexed laurel
#

Hello all! I have this on my front end UI the problem is when my sensor goes to a single digit it get's messed up. It's as if its comparing only the first digit when the sensor goes to say 9%, any ideas?
{% if states('sensor.processor_use') >= '35.' %} --paper-item-icon-color: #b81414;

mighty ledge
#

you're comparing strings not numbers

#

strings work left to right when comparing

#

character by character

hexed laurel
mighty ledge
#

so no matter what, '9' is always greater than '1' even if it's followed by a 0

hexed laurel
#

Thank you!

#

I was driving myself crazy.

hexed laurel
mighty ledge
#

convert your state

hollow mortar
mighty ledge
#

states(..) | float

hollow mortar
#

I want ia

hexed laurel
mighty ledge
marble jackal
hollow mortar
#

Yes its a simplified code of a much larger line, I want it like I wrote before "variable inside variable"

mighty ledge
#

bro, you just said you want only ai after thefes gave you the right answer

marble jackal
#

I just wanted to explain why it's better to use ~ instead of +, that's why I changed it to 123

hollow mortar
#

Yes but dont change it to 123, I want it to be ia to prove what Im trying to do

still plank
#

you mean you want to output the name of the variable, not the value of it?

hollow mortar
still plank
#

then just {{ ia }}

hollow mortar
#

Im gonna copy whole code, sec

mighty ledge
#

no he's just terrible at explaining, the answer he wants is just

{% set variable = 'ia' %}
{{ 'var' ~ variable ~ 'ble' }}
hollow mortar
still plank
mighty ledge
#

what do you want. To output just 'ia' or 'variable', because you've said you want both

still plank
hollow mortar
#

Just ia

still plank
#

if you don't want 'var' and 'ble' parts then don't put them in the expression

hollow mortar
#

Its a bad example, let me copy the real one.

mighty ledge
#

ok, then that's simply just

{% set variable = 'ia' %}
{{ variable }}
#

if you're trying to concatenate a string to access a variable in the current namespace, that's not possible.

hollow mortar
mighty ledge
#

yep, that's not possible

hollow mortar
#

I need to install discord on PC to copy code, sec

mighty ledge
#

you can do it with a dictionary, but not with the items in the namespace

hollow mortar
#

ok so this is the code:

{{ 'states.' ~ states.sensor.ramses_0_00.attributes.entity_id_climate ~ '.attributes.schema.schema' }}
{{ 'states.' ~ states.sensor.ramses_0_00.attributes.entity_id_climate ~ '.attributes.schema.actuators' }}

{% set sensor = 'states.' ~ states.sensor.ramses_0_00.attributes.entity_id_climate ~ '.attributes.schema.sensor' %}
{% set actuators = 'states.' ~ states.sensor.ramses_0_00.attributes.entity_id_climate ~ '.attributes.schema.actuators' %}
{% for x in actuators %}
  {% if sensor is not in x %}
    {{ sensor }}
  {% else %}
    {{ none }}
  {% endif %}
{% endfor %}
#

the first two lines output the correct entity but in a string

#

where it errors is in 3rd and 4th lines (both set)

marble jackal
#
{% set stuff = { 'variable': 'some output' } %}
{{ stuff['var' ~ 'ia' ~ 'ble'] }}
hollow mortar
#

its effectively the same as that previous simplified variable

marble jackal
#

{{ state_attr(state_attr('sensor.ramses_0_00', 'entity_id_climate'), 'schema').schema }}

hollow mortar
#

while doing this Discord on PC, was also googling and I solved it by doing:

{% set sensor = states[states.sensor.ramses_0_00.attributes.entity_id_climate].attributes.schema.sensor %}
{% set actuators = states[states.sensor.ramses_0_00.attributes.entity_id_climate].attributes.schema.actuators %}

so putting [ ] instead of ' ~ ~ '

marble jackal
#

that would work for the first one

#

yes, but it's adviced to use state_attr() and not what you are doing now

hollow mortar
marble jackal
#
{% set entity = state_attr('sensor.ramses_0_00', 'entity_id_climate') %}
{{ state_attr(entity, 'schema').sensor }}
hollow mortar
marble jackal
#

petro already answered that, not in the same namespace, only when using a dictionary like my example above

hollow mortar
#

which one is a dictionary, can you reply to it?

marble jackal
#
{% set stuff = { 'variable': 'ia' } %}
{{ stuff['var' ~ stuff.variable ~ 'ble'] }}
#

that will output ia

hollow mortar
#

😄

#

thanks again @marble jackal ! just wasted 2 hours for a simple thing and made an elephant out of a fly, atleast learned something new again !

marble jackal
sonic nimbus
#

"{{as_timestamp(states.binary_sensor.nuki_front_door_door_open.last_changed) | timestamp_custom('%A %d-%b-%y, %H:%M:%S')}}"
I created this template and it is correct, but Im missing only a condition for state, when was from "Locked" to "Unlocked" state.
Im not sure that I can put it here in this template?

mighty ledge
#

if you want that, you'll have to make an automation that stores the datetime in an input_datetime

#

or use an SQL sensor to look into the database

proud cradle
#

How do I setup an availability_template that makes sure several different sensors are available?

mighty ledge
#

however you want to set it up

#

it depends on the devices

proud cradle
#

For one sensor I've done this, right or wrong I'm not 100% sure?

availability_template: >
  {{ states('sensor.electricity_price_osthammar') }}
#

Also how do you get the nice, color encoded code snippets? Three ` does not do the trick..

inner mesa
#

add "yaml" after the backticks

#

and assuming that you're using that with a legacy template format, which is where it's valid, that doesn't return "true" or "false" and won't work

#

it returns a string

plain magnetBOT
#

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

mighty ledge
#

did you make taht template or did you copy it

proud cradle
#

I made it

mighty ledge
#

ok, then you should know how to make the availability_template return True or False then?

#

right now it just returns the state of your entity

#

so if you want it to be available, it needs to return true

sonic nimbus
proud cradle
#

Ahh oki, makes sense. What is this new template format? I presume I'm using the old.

mighty ledge
inner mesa
#

but the new one allows lots of different values for availability

#

it's more friendly

mighty ledge
proud cradle
#

Do you know if there is any good documentation I can read which explains the new format and what has changed?

analog leaf
#

Aaahh, how do I convert an int to a string. It's nowhere in the docs.

mighty ledge
#

| string

inner mesa
#

although any integration that has a state of "yEs" should be killed

analog leaf
#

Could you send me a link, I literally can't find it and thanks!

inner mesa
#

first link in teh channel topic

mighty ledge
#

beat me to it

inner mesa
#

to be fair, nothing there says that 1|string is the right syntax

#

the Jinja docs are weird that way

mighty ledge
#

I mean, it says "Convert an object to a string" 🤷‍♂️

analog leaf
mighty ledge
#

my man

#

jinja is built off filters

#

it's literally all over the docs

analog leaf
#

And the jinja I found but that doesn't work in {{ ... }} these brackets right?

inner mesa
#

I ❤️ filters

mighty ledge
#

filters are great, if you bother to learn them

mighty ledge
inner mesa
mighty ledge
#

{{ }} -> outputs whats in the brackets
{% %} -> runs the line of code without outputting

proud cradle
#

Is there a way todo this without creating a separate group entity?

{% set sensors = ['sensor.electricity_price_total'] | list %}
{{ sensors
    | rejectattr('state', 'in', ['unknown', 'unavailable', 'restored'])
    | list | count > 0
}}
inner mesa
#

no need to tag me. I'm sure that Petro can help too 🙂

analog leaf
#

When I do {{string(10)}} is says it cant find string but the docs say string(value)

mighty ledge
#

@analog leaf it's a filter

#

not a function

inner mesa
#

that's because the docs don't really show how you use them

mighty ledge
#

|filter

#

function()

inner mesa
#

for a filter, the first argument is always the incoming object/collection

#

if there are more arguments, then you do |filter(x, y, z)

analog leaf
mighty ledge
#

e.g.

some_code(x, y, z) # As a function
x | some_code(y, z) # As a filter
mighty ledge
#

and stop assuming

#

we didn't make the language

#

it's not made by home assistant

#

it's made by some other nerds (not us, the HA nerds)

#

we just use it

analog leaf
#

I'm not complaining to you guys, you're awesome for helping idiots like me, I'm just complaining about the docs!

mighty ledge
#

Sorry, but it's a short fuse with me because everyone and there mother complains to us, like we are going to fix it or change it

proud cradle
#

I'm answering my own question - but this seams to work fine to check that all sensors are available .

{% set sensors = expand(
        'sensor.electricity_price_total',
        'sensor.electricity_price_osthammar'
        ) | list %}
{{ sensors
    | rejectattr('state', 'in', ['unknown', 'unavailable', 'restored'])
    | list | count == sensors | count
}}
mighty ledge
#

that's how I normally approach these things

#

i.e. put all things the template uses into a list, then ensure that they are all available

plain magnetBOT
#

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

inner mesa
#

local vs. UTC, I assume

#

you can add |as_local

#

I don't know what sensor resolves to

analog leaf
inner mesa
#

sorry, that's too much to read

analog leaf
#

I went with {{as_datetime(as_timestamp(states('sensor.date_time_iso')+ "+01:00" ))}} now as it seems to be a string and I can just add the timezone myself.

inner mesa
#

ok?

#

{{ states('sensor.date_time_iso')|as_datetime|as_local }}

#

boom

analog leaf
#

❤️

inner mesa
#

that's what I was getting at above

analog leaf
#

That works even better as I don't have to provide the timezone!

floral shuttle
#

not sure what type of input_datetime id use best for the ease of calculating the time spent between the 2 of them

marble jackal
#

Why don't you just set variables in your automation?

#

If I understand correctly you want the time that the switch was on

floral shuttle
#

yes, indeed. we now have the time the action bolock takes, or even more precise, the time for the whole automation. Id love to narrow that down to the actual 'on' state for the switch

marble jackal
#

or the binary sensor?

floral shuttle
#

no, the switch yes the binary.... sorry

marble jackal
floral shuttle
#

oeh, that's nice, I didnt understand what you meant with variables, never used it like that before. It's what I do with the input_datetime (see my extra post in the community), but then way easier 😉 . Ill copy your full code in that same thread, unless you would like to do that? So our fellow commmunity members can see that too. (did it already now)

mighty ledge
#

You’ve never used them like that before?

formal ember
#

I just had a thought, this isn't taking into account day of the week is it? The tariffs are different on weekends

mortal summit
#

I'm not sure where the best place is to ask my question: I'm trying to build an automation that uses a counter helper. I want it to repeat till the counter is at it's maximum, and then stop.

I'm just struggling with how magical the templating seems to be

floral shuttle
mortal summit
#

Can someone help me figure out what is wrong with this?

#
 - condition: numeric_state
   entity_id: counter.tooth_seconds
   value_template: "{{ state.state - state.attributes.Maximum }}"
   below: 1

In 'numeric_state': In 'numeric_state' condition: template error: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'Maximum'

#

(I'm building a tooth brushing timer for my kids)

inner mesa
#

where did "state." come from?

#

seems made up

formal ember
mortal summit
inner mesa
#

I don't really know what you're doing there

floral shuttle
mortal summit
#

Yeah

#

that's where I started

inner mesa
#

well, that's a trigger

mortal summit
#

yes, I can see that now

inner mesa
#

but it's also a thing for conditions

mortal summit
#

I'm building a new automation, I dont' have any triggers right now,

#
trigger: []
action:
  - repeat:
      until:
        - condition: numeric_state
          entity_id: counter.tooth_seconds
          value_template: "{{ state.state - state.attributes.Maximum }}"
          below: 1
inner mesa
#

that won't actually do anything

mortal summit
#

basically I want to repeat until the counter.tooth_seconds value (state?) reaches it's maximum

#

Yeah, I know that, I'm trying to explain what I want it to do. If it worked I wouldn't be here :p

#

lol

floral shuttle
mortal summit
#

Imma need you to ELI5 here

inner mesa
#

won't that stop immedaitely?

floral shuttle
inner mesa
#

0 - 30 = -30

#

for instance

mortal summit
#

Okay, I can figure out the math

inner mesa
#

perhaps you wanted "while"

mortal summit
#

no

#

I just need to know how to get the two numbers, so I can compare them

inner mesa
#

anyway, does that entity have an attribute called "Maximum"?

mortal summit
#

I'll fix the math later

formal ember
#

Hey Rob, do you know much about the template I have been replying to, how to insert weekday vs weekend on it?

mortal summit
#

That's what i'm using

floral shuttle
#

besides the point Rob makes, I do believe you need to make sure the template returns a number. Since all templates are strings, you would explicitly need to 'float' the result. Like the example in the docs. numeric expects a float

inner mesa
#

I don't have one, but I suspect that it's "maximum" and not "Maximum"

#

and yes, you need to convert at least the state to a number

mortal summit
#

yeah..

#

that was it

#

I think I saw some UI had capitalized it and it got stuck

#
editable: true
initial: 0
step: 1
minimum: 0
maximum: 120
icon: mdi:toothbrush-paste
friendly_name: tooth_seconds

This is what i get from the counter on the devtools

inner mesa
#

devtools -> States is the definitive source of truth. Elsewhere, it gets translated and mangled

mortal summit
#

so, anything in that list will be on the state.attributes object then?

inner mesa
#

state.attributes is a dict, and those keys/values are all part of it

mortal summit
#

pedantic question but dicts are objects too?

#

Thanks for the help too

inner mesa
#

you can see that if you type {{ states.counter.tooth_seconds.attributes }} into devtools -> Templates

#

yes

mortal summit
#

man, I forgot about the templates thing

#

like my brain saw the word, and was like "nope, you don't need that"

#

Thank you

inner mesa
#

Templates are Life

mortal summit
#
condition: numeric_state
entity_id: counter.tooth_seconds
value_template: "{{ state.attributes.maximum - float(state.state) }}"
above: 0
#

I ended up with that

inner mesa
#

"{{ state.attributes.maximum - state.state|float(0) }}" would be better

mortal summit
#

explain?

#

oh, i'm using float wrong?

inner mesa
#

What you did will work, but it's not typical of how you modify data in Jinja. You would normally use filters, which is what I did

#

and the (0) is specifying a default in case the state cannot be interpreted as a number. Otherwise, if that happens, the template render will just fail

mortal summit
#

so float() can cope with both methods of being called, but piping with a default is the recommended way?

inner mesa
#

yes

mortal summit
#

Thanks, any tips for dealing with WLED devices in an automation?

inner mesa
#

some filters are also functions, but most aren't

mortal summit
#

cause, dang the presets are a PITA

inner mesa
#

I don't use them and know nothing about them

mortal summit
#

okay, what the number.set_value service call

#

can any of those also take a value template?

#
- service: number.set_value
  target:
    entity_id: number.wled_intensity
  data:
    value: "69"
inner mesa
#

the docs will say

#

but in general, anything under data: or service: or target: can take a tempalte

mortal summit
#

I get "state is undefined"

#

so I suppose i have to use states.counter?

inner mesa
#

I don't know what you're doing

mortal summit
#

I got it sorted

gaunt scaffold
#

Anyone have any experience with light templates and effect lists? My template reports no errors when checking YAML, and I don't see any errors , but when I turn the light on there is no drop down list . I have values set for effect_list_template, effect_template, and set_effect. Am I missing something, or can someone recommend how to troubleshoot this?

effect_template: "{{ states('input_select.treeeffect')}}"
set_effect:
          - service: input_select.select_option
            target:
              entity_id: input_select.treeeffect
              data:
              option: "{{ states('input_select.treeeffect')}}"```
formal ember
gaunt scaffold
# formal ember whats the end goal? automation?

yeah, the end goal is to call the MQTT service to control the effects on the light. The entity doesn't natively support effects, but I can send effects via MQTT , so I was trying to create a single entity that consolidated both

floral lichen
#

Anyone able to do up a quick example for me. Trying to do a "if the data from the json = text" then condition is met for an automation. message: "{{ trigger.json.state }}"

gaunt scaffold
floral lichen
#

What kind of lights are you using?

gaunt scaffold
#

Twinkly lights, powered by falcon player with the falcon player home assistant add-in

floral lichen
#

Oh yea cant help with that haven't used any of it.

gaunt scaffold
#

the example in the documentation looks to be invalid , as it doesn't set an effect_template , but even with one set i can't get it to work

floral lichen
#

Link?

gaunt scaffold
floral lichen
gaunt scaffold
#

the add-in brings it in as an MQTT auto discovered light

#

no effects..

#

but .. well... 💩 .... its a me problem.. i pasted in the sample code into my configuration and fixed the missing effect template... mine doesn't work the sample does

floral lichen
#

If it is auto discovered then it is telling it what it has.

gaunt scaffold
#

so I messed something up lol

floral lichen
#

Yea have a look at the Flacon hass add in thing and see if you can get it to also add in the effects.

#

My MiLight hub has a list called 'Group state fields' where I have to check a box to say I want the effects list posted.

formal ember
#

I made a manual list for WLED once, do you think that would help?

#

so i could go thru the list, like hit next and go to next effect

lethal bison
#

I'm not familiar with the lingo. I have roughly 30 smart switches installed. Is it possible to automatically add the physical switch to an automation if a related boolean switch is set to true?

kind olive
#

I want to count the number of switches that are on given the entity_id starts with switch.zwater, alternatively count all switches that are on in two devices.. any help appreciated! I am currently at the following template {{ states.switch|selectattr('state','equalto','on')|list|length }}, but filtering the entities is my headache..

marble jackal
formal ember
#

Hey Fes, does that template you helped me with take into account weekdays vs weekends? (When you have time of course)

kind olive
marble jackal
#

search is mentioned in the jinja docs, and accepts regex

marble jackal
#

Don't think so, can't remember you mentioned there was a difference

formal ember
#

It changes on weekends

#

There is no peak on weekends during summer and winter

marble jackal
#

Okay

#

Can you put the latest code for the tariff here

formal ember
#

Sure give me a couple

hollow talon
#

Hi!
I am very new writing templates and I am stuck at the following:
template: sensors: ampere_shelly_1a: friendly_name: Ampere Shelly EM1a unique_id: ampere_shelly_1a unit_of_measurement: A value_template: '{{ ((states("sensor.em1_1a_power")|float) / ((states("ssensor.em1_1a_power_factor")|float)*(states("sensor.em1_1a_voltage")|float)))|float|round(3) }}'

marble jackal
#

You are mixing the legacy and new format

formal ember
# marble jackal Can you put the latest code for the tariff here
    state: >
      {% set n = now() %}
      {% set summer = [ 11, 12, 1, 2, 3] %}
      {% set winter = [ 6, 7, 8 ] %}
      {% if today_at('07:00') < n < today_at('22:00') %}
        {% if (now().month in summer and today_at('14:00') < n < today_at('20:00'))
            or (now().month in winter and today_at('17:00') < n < today_at('22:00'))
        %}
          peak
        {% else %}
          shoulder
        {% endif %}
      {% else %}
        offpeak
      {% endif %}
kind olive
marble jackal
#

The device_id is not in the state object

formal ember
marble jackal
marble jackal
# formal ember ```jinja state: > {% set n = now() %} {% set summer = [ 11, 12, ...
    state: >
      {% set n = now() %}
      {% set summer = [ 11, 12, 1, 2, 3] %}
      {% set winter = [ 6, 7, 8 ] %}
      {% if today_at('07:00') < n < today_at('22:00') %}
        {% if ((now().month in summer and today_at('14:00') < n < today_at('20:00'))
            or (now().month in winter and today_at('17:00') < n < today_at('22:00'))) and now().isoweekday() < 6
        %}
          peak
        {% else %}
          shoulder
        {% endif %}
      {% else %}
        offpeak
      {% endif %}
formal ember
#

that simple?

#

And trying to help another guy out in #energy-archived earlier today. His is peak 3pm-9pm on weekdays only, offpeak all other times, would this be the way for him to go?

    state: >
      {% set n = now() %}
      {% if today_at('15:00') < n < today_at('21:00') %} and now().isoweekday() < 6 %}
          peak
      {% else %}
        offpeak
      {% endif %}
marble jackal
#

That would work

formal ember
#

sweet, will let him know. thanks again Fes

inner mesa
merry marsh
#

Is there an "easy" template, jinja, etc. to get from a timestamp exactly this, what the frontend is doing: in 14 minutes, in one hour, tomorrow, etc, (and this of course 😉 best case in German language (as the frontend is able to do as well)).?

hazy basin
#

Hello, If I have a list of boolean values. How can I 'and' or 'or' them together to get out a single boolean value?

marble jackal
#

But there are probably posts on the community forum which do what you want

merry marsh
marble jackal
#

There is relative_time but it only works on datetimes in the past, and it will be in English

plain magnetBOT
#

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

formal ember
#

throwing it into the template in dev tools it returns UndefinedError: 'trigger' is undefined

marble jackal
#

are you triggering it manually?

#

by pressing the button in settings?

formal ember
marble jackal
#

If you trigger it manually it won't work, as there is no trigger

#

it relies on the change of state of the sensor

#

does it work for you? Does your tariff change during the day?

formal ember
#

yeah mine does 🙂 but its slightly different because of the third tariff

#

makes me wonder if i got it all right for him in the end?

marble jackal
#

my guess would be his template sensor with the current tariff type isn't named sensor.electricity_tariff

formal ember
#

i will get him to double check all the entities

formal ember
#

Not really template related but what we have been talking about, the utility_meter sesnor I made, it has the 3 tariffs in it which create tariff entities... is there a way to set a friendly name for those?

marble jackal
#

for the tarrifs itself? No, they are named based on the settings in Utlity Meter

#
utility_meter:
  daily_energy:
    source: sensor.energy
    name: Daily Energy
    cycle: daily
    tariffs:
      - Diamonds
      - Peanuts

This would result in a select entity with Diamonds and Peanuts as options.

willow elk
#

Logger: homeassistant.components.rest.sensor
Source: components/rest/sensor.py:170
Integration: RESTful (documentation, issues)
First occurred: 30. November 2022 um 16:29:33 (20622 occurrences)
Last logged: 13:58:33

JSON result was not a dictionary or list with 0th element a dictionary

#

Can Someone help me where to start with this Error?

marble jackal
#

Looks like you are performing some actions on the result of the rest query, which can't be processed if there is no result for example

willow elk
#

Can this be fixed with something like a default Value if there is no result fro the Restsensor?

marble jackal
#

yes

#

What is the template you are using?

willow elk
#

The thinks that are not getting Result are: 'layer_height' , 'object_height' and 'thumbnails'

marble jackal
#

I don't see those in the link you shared

willow elk
#

Sorry, wrong Link.

#

That should be it, i cant seem to find a way to post my config because its to long for Discord

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.

marble jackal
#

but this is fine as well

willow elk
marble jackal
#

what's the state of that sensor you use in the resource template when nothing is being printed

willow elk
#

What Sensor do you mean?

#

Here is my Config, if you need it

willow elk
#

"sensor.3d_printer_state" is "standby" if nothing is printing

plain magnetBOT
#

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

mighty ledge
#

@green scaffold what's the problem, that looks like it should work

atomic blade
#

Trying to get all device_trackers which aren't assigned to an area. Any suggestions on how to do this? Particularly the filtering for entities without an area. Only thing I can think of is to manually specify each of my areas and then get a list of all device trackers and exclude the former list from that

mighty ledge
#

templates

atomic blade
#

lol yes I mean that's why I'm here

inner mesa
#

plastics

atomic blade
#

That's not why I'm here 🙂

mighty ledge
#
{% set ignore = states | map(attribute='entity_id') | map('area_id') | reject('none') | unique | map('area_entities') | sum(start=[]) | unique | sort %}
{{ states | map(attribute='entity_id') | reject('in', ignore) | list }} 
atomic blade
#

Wow thanks, petro! You're really a master of templates

inner mesa
#

Wow, that right there is convoluted 🙂

#

I wouldn't have thought to go from entities to areas and back to entities in the same expression 🙂

mighty ledge
#

lol

#

it's because we don't have a way to list areas

#

if we had a way to list areas, this would be less rediculous

silent seal
#

I want a way to list areas so badly.

mighty ledge
#
{{ states | map(attribute='entity_id') | map('area_name') | reject('none') | unique | list }}
#

if you want something you can access at all times without redoing that template.................................

silent seal
#

I mean that I'd like this to exist/work 😂

{{ areas }}
mighty ledge
#

well, it would be areas()

silent seal
#

I envision it to be like states.

mighty ledge
#

that might not be possible

#

oh no, it's possible

#

wouldn't be too hard

silent seal
#

Nope. As it is I was trying to do something via web sockets to provide me with a list as a sensor the other day. Then I got flu so I stopped work on it.

mighty ledge
#

when I say possible, I mean it could be added

#

we could make an areas object and not make it callable

silent seal
#

Do it! There's still time in this beta 🤓

mighty ledge
#

maybe sunday

#

but it wouldn't get in for the beta

silent seal
#

Darn. But please add it. I'd love to use it!

sly urchin
#

Hi there, I'm getting "No Statistics found" in the History section of my template sensor. It is meant extract the power usage from my localtuya plug, which works live, but no history. Can anyone help at all?
` - platform: template
smart_plug_power:
friendly_name: "Living Room Power"
icon_template: mdi:flash
value_template: >-
{{ states.switch.living_room.attributes.current_consumption }}
unit_of_measurement: 'W'

mighty ledge
#

use the new template format and add a state_class, device_class, and unit_of_measurement

#

also, power is not compatible with energy

#

energy is power over time, which is required for the energy panel

sly urchin
#

Is there documentation for this new template format?

mighty ledge
#

yep, it's in template integration

plain magnetBOT
sly urchin
#

Also as I understand it I use the integration function to convert to energy
- platform: integration source: sensor.smart_plug_2_power name: Living Room unit_prefix: k round: 2

mighty ledge
#

yep

#

that's the sensor that needs the proper device_class, state_class, and unit_of_measurement

#

your power entity does not need that, so you could stick with the legacy format

sly urchin
#

But I want to see the power history, I had this before I moved to localtuya. This is a problem before I get to the integration part

mighty ledge
#

then add the device_class, state_class, and unit_of_measurement to it using the new format

#

device_class, state_class, and unit_of_measurement control long term stats, that's what you need to see long term stats

#

the legacy template format does not support state_class

#

so you're forced to use the new format

sly urchin
#

Ok gotcha, working my head round it now

#

Thanks for the help

sly urchin
#

Is there a way replicate Friendly name? My entity names are smart_plug_1 etc but friendly names had the locations. Doesn't look like it can be changed from UI

mighty ledge
spark tangle
#

Trying to get the color of a light to set the icon color in the Mushroom template card.

{{ state_attr('light.hue_lightstrip_02', 'rgb_color') | list | join(',') }}

Using this in the "Primary information" field just gives the rgb color without commas (2552555255), not (255,255,255)
Using it in the actual "Icon color" removes the icon entirely.
Using it in the template section in developer tools returns

Result type: list
[
  255,
  255,
  255
]
mighty ledge
#

you just want the literal text (255,255,255)?

spark tangle
mighty ledge
#

you're trying to template the icon color?

#

why are you putting the template in the primary field then?

spark tangle
spark tangle
mighty ledge
#

it already does that without templates though

#

Are you trying to use a the template card to display some other information on the light but you want the icon to be the color of the light?

#

anyways, usually these fields require rgb(255,255,255) as the output for them to work if it's an rgb color

spark tangle
spark tangle
mighty ledge
#

just needs to be rgb({{ state_attr('light.hue_lightstrip_02', 'rgb_color') | join(',') }})

#

if that's not working then the docs might help spell out what the requirements are

#

typing in what get's the color to change without a template?

mighty ledge
#

because based on what you said above... i.e. "255,255,255" paints it white, then all you'd really need is {{ state_attr('light.hue_lightstrip_02', 'rgb_color') | join(',') }}

spark tangle
mighty ledge
#

can you post the field and the template when you use the template

#

i.e. post the whole line

#

or the whole config that you're trying

plain magnetBOT
#

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

mighty ledge
#

i don't see why that wouldn't work

#

I do find it odd that you're using |-

#

I'm guessing you just copied from someone else though

odd maple
#

can the whole data: block of a service call be jinja generated?

tired sandal
#

Can someone assist me with some jinja syntax?

I want to filter an array of objects where object.datetime is in the >= now.

But I also want to preserve the other object properties.

#

I know how to do this in JS but not jinja

mighty ledge
#

needs to return dict

silent seal
#

Give an example of the objects you have, but you'll be using the selectattr filter

mighty ledge
tired sandal
#

oh right, thanks

mighty ledge
#

array_of_objects | selectattr('datetime', '>=', now())

tired sandal
#

yeah there will always be datetime

#
const data = [
    {
        datetime: '2022-12-01 20:00:00',
        weather: 'snowy',
    },
    {
        datetime: '2022-12-01 20:01:00',
        weather: 'rainy',
    },
].map((condition) => ({
    ...condition,
    datetime: dateLibrary.convertToDateObj(condition.datetime)
}))
.filter(({ datetime }) => datetime >= currentDateTime())
#

that's roughly what i want to do (in JS)

marble jackal
#

Those look like strings to me

mighty ledge
#

exactly

#

you can't do lambda's in jinja

#

the object stays what it is

plain magnetBOT
#

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

tired sandal
#

@mighty ledge Yes i know, I'm just using JS for an example because that's what I'm most familiar with

#

@marble jackal they are - I'm trying to convert date/times as strings into a proper datetime type, then filter the list by that

mighty ledge
#

right, but what I'm saying is you can't convert types with any function in jinja, map can do it, but then it changes the object

tired sandal
#

right, i understand that

mighty ledge
#

i wish there was a lambda func

tired sandal
#

i understand you can't use lambdas in jinja, but that's the rough approximation of what I'm trying to do

marble jackal
#

You can use strftime() on now() and do a string comparison

odd maple
mighty ledge
#

well, the closest thing is select, reject, selectattr, rejectattr, and map

tired sandal
mighty ledge
#

the first 4 will preserve the object

#

map will change the object into what you're mapping

tired sandal
#

maybe i should back up a bit

mighty ledge
#

but you won't retain the original object with map

tired sandal
#

gotcha

marble jackal
tired sandal
#

@marble jackal oh right.

#

I want to look at the next 24 hours of weather (weather.home_hourly) and then decide if the next 24 hours are going to be <= freezing and if there's going to be any precipitation

mighty ledge
#

or just use a forloop instead of filtering down

marble jackal
#

But a string comparison will be fine with this format

mighty ledge
#

yep, that's what I do

tired sandal
#

is HA's hourly forecast >=now()?

mighty ledge
#

format utcnow() to match the forecast values

tired sandal
#

or does it include < now()?

mighty ledge
#

ha's forcast is strings

#

in UTC

tired sandal
#

yes i understand that

mighty ledge
#

without microseconds or the TZ

tired sandal
#

what I'm asking is - is the data in forecast present and future data or does it include historical data from earlier too?

#

...I don't care if it was freezing 3 hours ago, I DO care if it's going to be freezing tonight.

mighty ledge
#

using string comparison works when you use utcnow().strftime("%Y-%m-%d %H:%M:%S")

tired sandal
#

Right

#

but my question (right now at least) is about the age of the data in forecast

mighty ledge
#

its the last 24 hours

#

or the last 10 days

tired sandal
#

right, so it's going to include things that are old.

mighty ledge
#

depending on the platform

#

just do 2 selectattrs

tired sandal
#

...in other words - I am going to need to filter it

mighty ledge
#

right

#

with string comparisons

#

your options are to use string comparisons and 1 loop, or transform then compare with 2 loops

tired sandal
#

yes.

mighty ledge
#

which one do you think is optimal?

tired sandal
#

I'm still not entirely sure why I'm doing string comparison here

mighty ledge
#

because the forecast does not have datetime objects

#

it has strings

tired sandal
#

yes i know that, but jinja can convert ISO date strings into datetime objects, no?

#

(albeit in a loop)

mighty ledge
#

sure you can

#

but what do you think is optimal?

#

making 24 datetime converstions and 24 datetime comparisons? Or 1 datetime to string conversion and 24 string comparisons?

tired sandal
#

I'm just not understanding how one would do date time math with string comparison

mighty ledge
#

'2' > '1'

#

'2022' > '2021'

tired sandal
#

and is '2022-05-01' > '2022-06-01' ?

mighty ledge
#

No

#

so that will fail

#

just try it 😉

tired sandal
#

what about '2022-04-01T05:00' and '2022-04-01T08:00'

mighty ledge
#

that's why you use UTC

#

which the forcast is already formatted in

tired sandal
#

sorry, format issues

#

i fixed it

mighty ledge
#

full circle, your wrenches won't work here

tired sandal
#

should've been T not +

mighty ledge
#

the T won't make a difference

#

just try it

tired sandal
#

the T is the date/time separator

#
  • denotes UTC offset
mighty ledge
#

this is python 101 my man, not js

tired sandal
#

this is ISO8601 my man, not python

mighty ledge
#

You're welcome to continue to argue, but it's clear you don't understand string comparisons in python/jinja

tired sandal
#

I'm not arguing about string comparisons, I'm saying that,.....forget it.

mighty ledge
#

You have an unalterable object that's in UTC fully fleshed out isoformat timestamp

#

you compare it to a fully fleshed out ISO formatted UTC timestamp and >, <, >=, and <= will work.

#

I know what you're asaying but youre complicating it for no reason

#

you have a hammer and you want to use it, I get it

#

but sometimes you have to act like you ahve other tools aside from your hammer

tired sandal
#

...no, I'm just trying to work out how the hell jinja works with strings

mighty ledge
#

it goes character by character and evaluates each one

#

that's it

#

very simple

#

so if you keep the TZ the same, there's nothing to convert because those characters are negligible

#

and the good news is, the format of the string for forecast is already UTC

#

so you don't have to care about it when you have utcnow() that you can use

#

and actually, they use isoformatted strings

#

so you just need utcnow().isoformat()

#

Also, FYI if you're struggling with getting an hour of the day today in UTC, the code would be: {% set today = today_at("07:00").astimezone(utcnow().tzinfo) %} for 7am

#

then it would just be today.isoformat()

vestal aspen
#

can someone help me get a minutes until the next hour into a sensor state?

cosmic viper
#

in the documentation i see the yaml for a state-based template binary sensor, but where do i put the code?

inner mesa
vestal aspen
#

UndefinedError: 'datetime.datetime object' has no attribute 'minutes'

inner mesa
#

Something like that

vestal aspen
#

this works in the dev tools template editor.

#

{% set t = now().replace(hour=1, minute=0, second=0, microsecond=0) %}
{% set r = ((t + timedelta(days=0) if now() > t else t) - now()).total_seconds() %}
{{ r | timestamp_custom('%-Hh %-Mm' if r > 3600 else '%-Mm', false) }}

#

i just can't figure out how to jam that into a sensor i can use.

inner mesa
#

Ok

#

Well, you have <- when you need >-

#

I still claim that's way too complicated

vestal aspen
#

yea sorry i had fixed that, pasted an older copy. i am also trying to get count down to other time vales with the same script too,

timid heart
#

not sure it's the right place so please feel free to point me elsewhere. I am wondering if it's possible to display the value of a counter in esphome?

inner mesa
#

If you expose it as an entity, you would access it like any other entity

fickle kettle
#

In an automation template (triggered by a sensor update), is there some reason to use trigger.to_state rather than states('sensor.whatever')?? (is the latter expected to be updated before the automation is called?)
cc @formal ember

mighty ledge
#

You want to use trigger

#

It’s the information that caused the automation to trigger, which may not be what you get from the states method

formal ember
#

for some reason his automation is not being triggered - @fickle kettle is the automation failing to trigger at all, or is it running and not changing the tariff?

fickle kettle
#

It looks like it ran, but didn't change the tariff (and I didn't see it in traces).
it's triggered on a change in the tariff (top bar), and changes the price (bottom graph)
#energy-archived message
When I manually changed the tariff just now, it changed, and changed back OK
🤷‍♂️

#

actually.... I think I know the problem.

formal ember
fickle kettle
#

It probably ran perfectly at 9pm, but the value was already low, since the earlier job that should have set it to high failed, because there was some mistake in the value (extra %})

formal ember
#

im excited

#

ahhhh yes

#

so now it should be fine?

fickle kettle
#

the manual test was OK (the up/down on the right), but let's see at 3pm 🙂
Then I might add it to energy dashboard. (don't want to break my previous solution, which works fine, until then)

formal ember
#

bonus of having 3 tariffs is i get to find out sooner if things actually work 😄

#

but, will be interesting to see how the weekend tariffs go

fickle kettle
#

I don't actually import any power at all from about 0700 to 1900 (solar), so although the price will swap, it won't have $$ impact.

formal ember
#

thats so good. wish i had a system like that. what was the cost to install?

fickle kettle
#

Full retail would have been about $25k I think, but with govt rebates and all that stuff, I think I paid about $8k

formal ember
#

holy shit!

#

I had to fork out 11k for my system

fickle kettle
#

Actually, looking at emails. Was $8850 + $5k deposit that I paid

formal ember
#

8.25kw inverter but really only get solar from 10am-5pm at the moment

#

still, that is amazing, how long ago?

fickle kettle
#

six months?

formal ember
#

!!!!

fickle kettle
#

I've got 20kw inverter + panels.

formal ember
#

vic must have huge rebates

#

what brand inverter?

fickle kettle
#

Goodwe. I'm not suuuuuper happy with it - it's super noisy, and I'm trying to get the installer to move it outside (my workshop). But at least the HA integration is OK.

formal ember
#

ah yep. I heard some can be noisy. ours is outside, Solaredge. Took a while (and a few visits from the installer) to get the monitoring right with visibility of import, export, consumption etc

fickle kettle
#

I did all that myself, with HA integration via modbus, and ct-clamps on the wires etc (iotawatt)

formal ember
#

if i were to do it again, i'd have optimisers or micro inverters installed at the panels because of the shading we get

fickle kettle
#

But we're offtopic for here 🙂

marble jackal
elder moon
#

I am using a following template for binary_sensor template: value_template: "{{ states('sensor.openweathermap_temperature') | float()) > 1.5 and (states('sensor.openweathermap_wind_speed') | float()) < 7 and (states('sensor.outside_temperature') | float()) > 1 and (states('sensor.outside_wind_max_speed') | float()) < 5 }}"
Is there any way of making it still work when one of those sensor will be unavailable (so the template still renders based on the remaining ones)?

mighty ledge
#

add defaults to float

#

also, you have miss-matched parenthesis

pine belfry
#

i want to have a sensor that shows me the electricity cost of just 1 smart plug. I understand I have to use history_stats platform, but i have no clue what the state of my sensor is. {{ states('sensor.tz3000_typdpbpg_ts011f_summation_delivered')}} returns a number

#

all the examples i can find are about on/off sensors

marble jackal
inner mesa
#

Lots of Insidious Silly Parentheses

mighty ledge
#

I mentioned that over use of parenthesis in math made it harder to read on Reddit the other day and got downvoted to hell and back

#

apparently people think parenthesis are easier to understand than pedmas

#

🤷‍♂️

mighty ledge
#

Yeah it was those people who were downvoting me 🤣

#

Some guy even replied with lisp saying that he was a dev for it

elder moon
floral steeple
#

I'm not sure where to start with this one. I have a weather station and it has an built-in heater because when it gets cold, the wind readings become wrong, however, the heater also causes some local heating so the outdoor temperature can be inaccurate. For example, at -27oC true temperature, it can be off by 4oC, ie. it report a temperature of -23oC. Anybody know how to approach this and create a sensor based on this issue to compensate for the heater? It should only compensate for temperature when its below +5oC, and even then, it would be a "gradient" as the temperature gets colder, so (+5,0) and (-27, +4)...

floral steeple
#

assume a linear equation

proud cradle
#

I have this string and would like to calculate the minutes it is from now. Could someone point me in the right direction? 2022-12-02T19:00:00.000+01:00
Though this should have outputted the local time, but it still showed the same for some reason.

{{ state_attr('sensor.run_heater_when','heater')[0].startsAt|as_datetime|as_local }}

Output:
2022-12-02 19:00:00+01:00

inner mesa
#

what did you expect the offset to be?

proud cradle
#

I though it would give a datetime without the timezone?

#

So 20:00

inner mesa
#

it should reflect your local time. For me, that gives "2022-12-02 10:00:00-08:00`, which is correct for me

proud cradle
#

Very strange... that's 25min from now (when my heater will turn on) and let me tell you... it's not on! 🤣🥶

#

How would get the time difference in minutes between that string and now()?

old compass
#
{% if forecast[0].condition == "clear-night" %}
    {% icon = "mdi:weather-night" %}
{% endif %}

{{ icon }}```

can someone help me debug my IF statement? I plan on putting this into a markdown card but when I add this into the card, the card goes blank which I assume the reason is a syntax error
#

as a sanity check, I've also done if "clear-night" == "clear-night" with no success

proud cradle
#

+01

inner mesa
#

then it's right!

marble jackal
#

The first string is already using that timezone

#

That's the +01:00 part at the end

proud cradle
#

Sorry guys I'm retarded... I forgot to filter out the values when the heater isn't running 🙈 Now it looks good, I just need to convert a formated datetime into minutes which I saw someone doing by adding lie ().minutes or something?

#
{%
  set runTime = state_attr('sensor.run_heater_when','heater')
  | rejectattr('value', 'in', [0])
  | map(attribute='startsAt')
  | sort
%}
{{ ((runTime[0]|as_datetime|as_local) - now()) }}```
```0:11:59.989734```
I would like just 11 or rounded to 12.
inner mesa
#

you would normally round a time like that by adding 30 seconds and then just taking the minute

proud cradle
#

Smart, unfortunately I don't know how todo that here.. I'm just an average php guy 😛

inner mesa
#

excellent

#

{{ ((("2022-12-02T20:23:42.000+01:00"|as_datetime|as_local - now()) + timedelta(seconds=30)).seconds/60)|int}}

proud cradle
#

😍

#

Where do you guys learn all this? I find the documentation a bit lacking when it comes to learning the language and its methods etc

#

Works perfectly btw, thanks a bunch @inner mesa 🙂

inner mesa
#

reading the docs and solving problems for you guys 🙂

proud cradle
#

Nice, then maybe you know if there is a function to either get the maximum value like max(-1, 0) and that should return 0 or if there is a way to do something like ifLessThanZero(-1,"return this") ?

marble jackal
#

Me mainly by asking questions here, in combination with the links in the pinned posts

#

[0, some_result ] | max

#

or
iif(some_result < 0, 0, some_result)

#

But I would go for the first one

proud cradle
#

That's brilliant! Thanks

#

Interesting -- the first suggestion from Rob inverted a negative number to positive when getting the delta in sec

inner mesa
#

I guess if the target date was less than 30s in the past

#

you can filter those out and don't do the math if that's going to be a problem

#

it sounds like an error condition based on your description

proud cradle
#

Yeap, this worked 🙂

{%
  set runTime = state_attr('sensor.run_heater_when','heater')
  | rejectattr('value', 'in', [0])
  | rejectattr('startsAt', 'lt', now().timestamp() | timestamp_custom('%Y-%m-%dT%H:%M:%S.000%z'))
  | map(attribute='startsAt')
  | sort
%}
time to heater starts {{ [0, (((runTime[0]|as_datetime|as_local - now()) + timedelta(seconds=30)).seconds/60)|int] | max }} min```
raw pumice
#

Hi, I do have defined a sensor by mqtt with a state class of total increasing:
- name: "Garagenkraftwerk Arbeit Gesamt" state_topic: "solar/116175200790/0/yieldtotal" device_class: energy unit_of_measurement: kWh state_class: total_increasing unique_id: "GaragenkraftwerkArbeitGesamt"
Sometimes, maybe because of rounding errors, it startes new measurement cycles. Is there any way to prevent this?

brisk nebula
#

Hi everyone, is there a way to obtain a localized state of an entity? {{ states('weather.myown') }} returns state in English.

mighty ledge
#

nope

#

@brisk nebula ^

#

you have to manually convert it yourself

brisk nebula
#

Thanks petro! That's what I ended up doing.

stuck remnant
#

hi, is there a value template for this to check if it has been true for 20sec?
- condition: numeric_state
entity_id: sensor.samsung_j3_ipcam_sound
above: '138'

marble jackal
#

Nope, you need to create a template binary sensor for that if you need it

stuck remnant
#

and how do I do that ^^

marble jackal
#

{{ states('sensor.samsung_j3_ipcam_sound') > 138 }}

plain magnetBOT
stuck remnant
#

this will make the sensor turn on whenever it has passed that threshold right?

marble jackal
#

Correct

stuck remnant
#

oh and it turns off if it goes downard of that value

#

and then I just use it as a condition with a time value attatched

#

thanks!

marble jackal
#

Correct again!

pastel crescent
#

I would like to monitor when washing machine and dryer turn off, so someone can go rotate laundry. These machines (specifically the washing machine) has periods of "soaking" with very little energy usage for a few minutes, so a simple threshold trigger (probably?) wouldn't work.

Could I make a template binary_sensor that would go "on" when energy usage goes over 20W, and "off" when it has been under 20W for 2 minutes? Is there a better way to do this?

silent seal
plain magnetBOT
#

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

dusty hawk
#

Shoot. I'll try again

inner mesa
#

rain['1h']

#

Please don't repost

dusty hawk
#

Thanks

#

{{ state_attr('sensor.openweather_report', 'current').rain['1h'] }

plain magnetBOT
#

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

paper hazel
#

Figured it out...

dusty hawk
#

Any idea if the keyword 'pop' (which is, Probability of Precipitation) is a HA template security-flagging parameter?
this:
{{ state_attr('sensor.openweather_report', 'daily')[0].pop }}
returns this:
SecurityError: access to attribute 'pop' of 'dict' object is unsafe.
All other parameters at that level work OK. Just this one fails.

#

WTH, a 2fer, this works: {{ state_attr('sensor.openweather_report', 'daily')[0]['pop'] }} Thanks, @inner mesa

#

what's special about 'pop'?

inner mesa
#

It modifies a collection

#

HA doesn't let you do that

dusty hawk
#

And, 'clouds' don't? What is pop in collection-speak?

inner mesa
#

It's a Python method

dusty hawk
#

Internal, ok

#

and [''] escapes it.

inner mesa
#

I wouldn't really call it 'escaping'. You're just indexing based on the string in such a way that it isn't misinterpreted

#

The dot notation for indexing is a Jinja thing that introduces ambiguity

dusty hawk
#

Ahhh, I was thinking that pop might have been a variation of PEEK and POKE that would well be disallowed, but was a keyword a vendor choose, inartfully, perhaps. Maybe so, anyway.

inner mesa
#

It's just a Python method

#

And HA doesn't let you modify data structures once they're created

dusty hawk
#

Hard to keep up as one who dives in as needed to javascript, Python, jinja, bash scripts, SQL, et al. I started with Fortran IV, and exited coding professionally after a loig tour through unix to about SQL Service Analysis Services writing Financial Services Multi-dimensional models. Thanks for helping.

inner mesa
#

It tells you what's wrong and what to do 🤷

quiet niche
#

you're right.

#

I just don't program YAML every day and the documentation and groups are full of depricated and il-advised methods

#

and I figure after an hour of mesisng and reading conflicting posts and documents, I to ask for help

#

Sorry about that

#

Here's a better question... Why does this work and return the right value in the templating sandbox?
value_template: "{{state_attr('weather.portland', 'temperature')}}"

inner mesa
#

I don't understand the question

#

It's the right syntax

quiet niche
#

It's the documentation

inner mesa
#

Ok?

#

I still don't understand what's what you're asking. Why does it work? It's correct and should work

quiet niche
#

In some of the documentation it says
`sensor:

  • platform: template
    sensors:
    solar_angle:
    friendly_name: "Sun angle"
    unit_of_measurement: "degrees"
    value_template: "{{ state_attr('sun.sun', 'elevation') }}"`
inner mesa
#

Not sure where the question is

quiet niche
#

and other places it says this:
- platform: template sensors: sensor name: friendly_name: "sensor friendly name" value_template: "{{ sensor value template }}"

inner mesa
#

I doubt that

quiet niche
#

stand by for the screenshot

inner mesa
#

I still don't know what you're confused about

#

No screenshots

quiet niche
#

Yeah I see that

#

here's what happened

inner mesa
#

I have no idea what you're asking. None

quiet niche
#

and maybe I mispoke when I said documentation

inner mesa
#

At all

quiet niche
#

the VScode drops the whole code block

inner mesa
#

Drops?

quiet niche
#

you type - platform: templ>>>>

inner mesa
#

Ignore it

quiet niche
#

and WHAM! there's some misshapen code that won't parse

#

so it's not the docs

inner mesa
#

Turn off code snippets

quiet niche
#

but the old and the new are hard to sift through

inner mesa
#

Ignore it. Get rid of it

quiet niche
#

gone

inner mesa
#

Don't let that confuse you

quiet niche
#

I'm old enough that I should know that I shouldn't assume things are "right"

#

so my bad

#

I'm tired

#

and cold

inner mesa
#

It's trying to help and it isn't. I turned all that crap off

quiet niche
#

I'm a hardware engineer, maybe that will explain my issues.

#

Anyways, thanks for the advice

ebon jewel
#

i'm trying to create a sensor that stores a value based on the output of a template. it's saving the data as a string - is there a way to make a template output a value that's stored numerically (so I can graph it over time?)

#

i see mention of a number template but i've not been ble to find any examples of it.

#

my actual goal is to calculate a statistic and save that statistic as a value over time.

#

thinking making a sensor template would be the best way

inner mesa
#

Just give it a unit_of_measurement

#

A template sensor is fine

ebon jewel
#

doesn't pass yaml test

#
in "/config/configuration.yaml", line 175, column 9
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 177, column 28```
#

i think my code is identical to one of the examples

#
template:
  - sensor:
      - name: "Rainfall DarkSky"
        unit_of_measurement: "in"
        state: '{{ states('sensor.rainfall_over_last_48h_darksky')|float }}'
#

And I define that sensor as

sensor:
  - platform: statistics
    name: "Rainfall over last 48h - darksky"
    entity_id: sensor.dark_sky_precip_intensity
    max_age:
      hours: 48
    state_characteristic: sum
inner mesa
#

Your template uses the same type of quote inside and out

ebon jewel
#

lol; thaks

#

would have never spotted that

marble jackal
#

You are using the same quotes inside and outside the template

#

Oh, crap, apparently I wasn't at the bottom yet

manic onyx
#

Hi everyone.
Is it possible to generate a UUID from a template?

marble jackal
#

Why would you want that?

shrewd pilot
#

Hey I'm trying to make an automation trigger when I'm playing any game on steam.

I made this template sensor for it

steam_game_iisakki:
  friendly_name: "Iisakki's steam game"
  value_template: "{{ states.sensor.steam_76561199090611635.attributes.game }}"

The problem is that the resulting sensor has no value at all when I'm not playing a game. Is there a way to create a sensor that just returns "true" when playing any game and "false" when not playing?

#

The problem is that the attributes for the played game in the steam sensor disappears altogether when no game is played, instead of showing something like "not playing"

#

So I can't automate based on that.

#

What I'm trying to do is change settings for my wled strip behind monitor when I'm paying a game

marble jackal
#

@shrewd pilot {{ not state_attr('sensor.steam_76561199090611635', 'game') is none }}

shrewd pilot
heavy crown
#

Hi, I am trying to get a value of the forecast of tomorrow 05:00 using standard weather sensor with hourly forecast. This is what I have now...it works but I would not be able to explain this (trial/error)

#
{% set x = state_attr('weather.home','forecast')  | count %}
{% set pd = state_attr('weather.home','forecast') %}
{% for i in range(0,x) %}
{% if as_local(as_datetime(pd[i].datetime)) == now().replace(hour=5, minute=00, second=0, microsecond=0) + timedelta(days=1) %}
{{ pd[i].temperature }}
{% endif %}
{% endfor %}
#

any suggestions on this?

inner mesa
#

It's iterating through the list of forecast items looking for the one that has a timestamp of 5AM tomorrow

#

What did you want exactly?

#

It could be much shorter

#

{{ (state_attr('weather.home', 'forecast')|selectattr('datetime', 'eq', (utcnow().replace(hour=20,minute=0,second=0,microsecond=0)+timedelta(days=1)).isoformat())|list|first).temperature }}

marble jackal
#

Do you want 5:00 local time or 5:00 utc

inner mesa
#

doesn't look like anything template related

sly urchin
#

Ah shit sorry, over to integrations

marble jackal
#

@heavy crown If you want local time you can use
{{ (state_attr('weather.home', 'forecast')|selectattr('datetime', 'eq', (today_at('5:00').astimezone(utcnow().tzinfo) + timedelta (days=1)).isoformat())|list|first).temperature }}

inner mesa
#

I was trying and failing to work out this bit: (today_at('5:00').astimezone(utcnow().tzinfo)

#

was wishing for an |as_utc filter

marble jackal
#

I knew it had tzinfo in it, and that petro posted it recently 😉

glossy viper
oak summit
#

Is there a way to get a template to output a list of device trackers associated with a person entity?

inner mesa
glossy viper
#

nok

#

i suppose that x = 2

#

if both hdd sensors are ok and both set variable = 1

inner mesa
#

seems easy enough to debug

oak summit
inner mesa
oak summit
#

Dang, okay. Thanks anyway.

glossy viper
inner mesa
#

seems like you're just guessing, though

#

look at each value

glossy viper
#

each value is set to 1 according to state ...so 1+1 = 2...template should say "ok"

inner mesa
#

I got nothing:

          {% set map = {0:"NOK", 1:"NOK", 2: "OK"} %}
          {% set n = 1 if 'ok' == 'ok' else 0 %}
          {% set z = 1 if 'ok' == 'ok' else 0 %}
          {% set x = z + n %}
          {{ map[x] if x in map.keys() else 'Error' }}
``` -> OK
glossy viper
#

true

#

than something is with the states 😦

inner mesa
#

again, this isn't rocket science. just check

glossy viper
#

probably the syntax is not correct , one day an idea will rise 🙂

inner mesa
#

🤷

#

syntax is fine

#

here

#
{{ states('sensor.nas_sam_smart_status_drive_0_1') }}
{{ states('sensor.nas_sam_smart_status_drive_0_2') }}
#

what does that say?

glossy viper
#

both OK

inner mesa
#

"OK" is not "ok"

glossy viper
#

aw

#

sorry for wasting time

ionic kite
#

hey maybe someone can help me 🙂
I have a Sensor which sends all 5 seconds the current time and I want to make a binary sensor which shows if the device send for more then 1 minute no new state, to indicate if the device is off or on
I know my code cant work this way .. but I should be something like this

binary_sensor:
  - platform: template
    sensors:
      pc_on:
        friendly_name: Zeigt an ob der PC im keller an ist
        value_template: >-
          {{ now() - state('sensor.desktop_lastactive_2')  60 }}
shell fractal
#

Hello, I am having a big problem with the template. I have a long configuration configuration and the sensors I added do not appear in the system...Can you help me?

inner mesa
#

maybe: {{ state('sensor.desktop_lastactive_2')|as_datetime < now() - timedelta(minutes=1) }}

floral steeple
#

hey, my template sensor keeps failing the check configuration and can't figure out why!! driving my crazy

inner mesa
#

It always helps tremendously when you say how it's failing, not just that it fails

floral steeple
#

ive tinkered with it a few times now (7 actually) now im not sure which one is the latest error message 🤣

#

here are the error messages

inner mesa
#

Ok, so friendly_name is no longer allowed and you have weird quotes

#

value and value_template are coming from some other template

#

My guess is that you're mixing up the old and new style templates

floral steeple
#

oh that was it, i removed friendly name and it passes now

#

thank you very much!

#

also, I'd like for the sensor to be 1 decimal place. if I place "| round(1)" after float condition, it doesn't seem to round it to 1 decimal place. Where do I place the | round(1)

#

sensor yaml here

#

{% set temperature = states("sensor.temp") | float(0) | round(1) %}

inner mesa
#

The last three won't be rounded. They go on to do more math

floral steeple
#

guess I have to put it on every line?

inner mesa
#

Everywhere you want it rounded

floral steeple
#

got it!

shell fractal
#

http://pastie.org/p/1BR2oz6Fcf4fGXOuHnLPgl this is my master configuration. I'm trying to add a sensor here that I have the code for. File manager gives a green notch, I can't find an error, I save and update the template assets again, but this sensor does not appear in the system. Where should I add this sensor in this configuration? `template:

  • sensor:
    • name: combi_boiler_current_power_usage
      unique_id: combi_boiler_current_power_usage
      unit_of_measurement: W
      device_class: power
      state_class: measurement
      state: >
      {{ is_state('switch.combi_boiler_relay_switch', 'on') | iif(states('input_number.combi_boiler_power_usage'), 0) }} ` I'm having trouble pasting the code here properly. I'm still very new to this platform. I will learn this as soon as possible. I apologise for the visual pollution. Actually, the codes I want to apply are on this page: https://seanblanchfield.com/2022/02/virtual-energy-meters-with-powercalc
thorny snow
#

Sensor attributes last_changed and automation attributes last_triggered are not in my local time, but UTC by default. What is the easiest way to change it?

thorny snow
#

Actually I'm not sure it is UTC, but what it shows is equal to UTC.

marble jackal
#

They are actually in UTC, but the frontend shows it in your local time

marble jackal
thorny snow
marble jackal
#
template:
- platform: template
  sensor:
      - name: "Estimated Battery Depletion Time"
        state: "{{ as_timestamp(states('input_datetime.estimated_battery_depletion_time')) | timestamp_custom('%-I:%M %p')}}"
        icon: mdi:clock
        
      - name: "Estimated Battery Depletion Time Countdown"
        state: "{{ (as_timestamp(states('input_datetime.estimated_battery_depletion_time')) - as_timestamp(now())) | timestamp_custom('%H hr %M min', false)}}"
        icon: mdi:timer-sand 

move this part all the way to the bottom, remove the - platform: template line and add a - before sensor

marble jackal
#

{{ states.sensor.latest_hemr_occupancy_sensor_on.last_changed | as_local }} will give you the local time

#

both are a correct representation of the time the sensor last changed, the timezone information is at the end (+00:00)

thorny snow
#

Yes, understood, thanks a lot!

manic onyx
# marble jackal Why would you want that?

sorry, was waiting for a reply for too long 🙂
I want to be able to change GUID on my phone companion app, as I use it to open garage door when I get home. But it offers no security and easy to clone and reuse.
The plan is for HA to generate new GUID and store in a helper. And automation will be comparing detected ble beacond GUID to that of a helper and actioning the automation if matched.
I can use Python script and call API from python, but thought it maybe easier just to do it on the fly

shell fractal
marble jackal
#

Well I started with this, but there is too much wrong in your config. Have a look at the documentation for the the template integration. The legacy format is at the bottom

#

Indentation is off for most of you legacy template sensors

plain magnetBOT
marble jackal
#

And the new format is a different integration, it should not be placed under sensor:

thorny snow
#

I have a template sensor problem, which might be buried deep in HA, but which there might be a solution to: I have a group of mqtt-based sensors. When I restart HA the sensors themselves do not change but when I iterate through the group using expand and display the last_changed attribute of each sensor, the last_changed times are the time of the restart. Is there any solution to this?

marble jackal
#

Well, the state did change, from something like unavailable or unknown to the actual state

#

so that's why last_changed is updated

thorny snow
#

I recognized that reboot makes a few seconds of unknown state.

marble jackal
thorny snow
#

Sure, I'll have a look at it. The strange thing is that when I look at the sensor itself in the history of the sensor, cannot see anything. Nor can I see this in the Dev Tools.

marble jackal
#

I think it filters these changes out for the frontend

#

where do you expect to see this in dev tools?

thorny snow
#

When I list the entity states, there somtimes is a last_changed attribute (second column: state) but isn't any.

marble jackal
#

It isn't an attribute

#

so it is not listed in the attributes section

thorny snow
#

At the top, I can see Last Updated and Last Changed.

marble jackal
#

yes correct

#

but it is not in the attributes section, because it isn't one

thorny snow
#

Got it!

thorny snow
marble jackal
#

It works for any entity

thorny snow
#

Is it enough if I apply it to the template sensor that works on the group of mqtt sensors, or I need to apply it on all individual mqtt sensor entities?

marble jackal
#

You need to add the individual entities to the trigger

thorny snow
#

All right!

formal ember
silent seal
#

utility_meter perhaps?

formal ember
#

had a look there and I cannot find it, just had a look at sensor.yaml and found this

- platform: integration
  source: sensor.dehumidifier_smartplug_power
  name: "Dehumidifier"
  unique_id: 1da30564-1ac1-4d0a-b413-c858e1d5c949
  unit_prefix: k
  round: 2
silent seal
#

What integration does the Related tab say created it?

formal ember
#

No related items found.

silent seal
#

And if you look in the entities list?

formal ember
#

i think i need to scrap this and start again...

whats the best way to make a sensor for the energy dashboard based off a device that shows you how many watts it is using?

silent seal
#

I said entities list, not states list 😉

plain magnetBOT
formal ember
#

just says integration

#

its like it turned on and just whacked 10kwh on to the sensor in one hit

silent seal
#

That is weird. The only things I have with integration in the name of the integration are the Riemann Sum Integrals

formal ember
#

aha!

marble jackal
#

That's exactly what the code above is

formal ember
#

is this the right way to monitor a power source to put it in the dashboard?

marble jackal
#

Which is also the method to convert power usage in Energy

formal ember
#

this suggests it is correct, but why would it jump like that?

plain veldt
#

I can't see what im doing wrong with the following template im trying.
light.all_lights is a group (helper) that i created via the UI.

# This returns 3 (which is correct)
{{ expand(states.light.all_lights) | selectattr('state','eq', 'on') | map(attribute='entity_id') | list | count }}

# This returns 1 (there is a bit of extra formatting)
{% set ns = namespace(res=0) %}{% for switch in state_attr('light.all_lights', 'entity_id') if is_state(switch, 'on') %}{% set ns.res = ns.res + 1 %}{%endfor%}{{( ns.res | string + " ") |  replace ("1 ", "1  ") }}
mighty ledge
#

@plain veldt expand takes grouped entities and breaks them up into their individual entities. You're not using it in the second template.

#

it's recursive BTW, so you most likely have nested groups

#

recursive means it continues to dig deeper into the groups and return only the non-group entities

proud cradle
#

I've been trying to get rid of this error with this availability template, but I've misunderstood something as it still shows up at times.
TemplateError('TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'')

      availability_template: >
        {% set sensors = expand(
                'sensor.electricity_price_total',
                'sensor.tibber_prices',
                'binary_sensor.run_heater'
              ) | list %}
        {{ sensors
            | rejectattr('state', 'in', [NoneType,'unknown','unavailable','restored'])
            | list | count == sensors | count
        }}

What shall I do to cover that case too?

#

Just add 'NoneType' to the list?

mighty ledge
#

you're not adding anything in that so the error is coming somewhere else.

proud cradle
#

Yeah it's from my template, but I presume it's one of the sensors that doesn't hold a valid value?

mighty ledge
#

it's not from that template.

#

I can 100% tell you, it's not from that template.

#

you are not adding in that template

plain magnetBOT
#

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

proud cradle
#

That's the actual template

mighty ledge
#

{% set prices = (state_attr('sensor.tibber_prices','today') + state_attr('sensor.tibber_prices','tomorrow'))

#

that line

#

and the heater line

proud cradle
#

Tomorrow is [] right now, shouldn't throw an error?

mighty ledge
#

at startup, those attributes will return None

#

so you should add an availability template that checks for those attributes existing

#

or not being none

proud cradle
#

Right now:

{{ state_attr('sensor.tibber_prices','tomorrow') }}

[]

plain veldt
mighty ledge
#

yes but at startup it will be None

#

so when you restart, it will error and fail the sum. i.e. the + operator that your error is throwing

#

TemplateError('TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'')

proud cradle
#

So I need to add one more check in the attribute_templates that looks for, but not fails at the attribute?

mighty ledge
#

it needs to check the attribute value for none

shell fractal
proud cradle
#

Any suggestion how I do that in a clean way?

mighty ledge
#

state_attr(...) is not none

proud cradle
#

Ahh so it won't fail when trying to access a property that do not exist?

mighty ledge
#

the attribute exists, but it's none

#

well, it might just be a byproduct of state_attr returning none if the attribute doesn't exist

#

regardless, do that

#

you could also just do this in your template

#

Nevermind, it complicates it. Just add the availability

#

well, maybe not

#

give me a moment

marble jackal
# shell fractal For some reason I find it difficult to find errors even when I browse... I've be...

example:

sensor:        
  - platform: template
    sensors:  
    adjust_slope_outside_temp_living_room: 
       friendly_name: adjust_slope_outside_temp_living_room
       value_template: >
           {%- set delta_slope = ((states('input_number.tado_max_slope')|float(default=16))-(states('input_number.tado_offset_slope')|float(default=16)))/12 -%}
           {{(states('input_number.tado_offset_slope')|float(default=16)+((states('sensor.outdoor_temperature')|float(default=16))*delta_slope))|round(2)}}
  • the object_id (adjust_slope_outside_temp_living_room: in line 457) and everything under it should be indented 2 spaces.
  • The same applies to the sensors after this one (lines 464-483) So basically lines 457 to 483 should be indented 2 spaces
  • The same applies to the sensors in line 521 - 542
  • then on line 564 you have a sensor with only a value template, no object_id
  • from lines 568 - 601 you have template sensors using the new format, they should not be under the sensor: key, but under the template: key
  • you have that template: key on line 606 but you added an additional - platform: template line which should not be included in the new format
mighty ledge
#
{% set today = expand('sensor.tibber_prices') | selectattr('today', 'defined') | map(attribute='today') | first | default([]) %}
{% set tomorrow = expand('sensor.tibber_prices') | selectattr('tomorrow', 'defined') | map(attribute='tomorrow') | first | default([]) %}
{% set items = today + tomorrow %}
#

@proud cradle work off items from that point on and you won't need availability at all

#

it'll always have empty lists

#

so...

proud cradle
#

Ohhh that's soo clean, big thank you @mighty ledge

shell fractal
mighty ledge
#

hold up

proud cradle
#

It goes to default now, something is up with how it selects the values I guess

#
[
  {'total': 2.8995, 'startsAt': '2022-12-05T00:00:00.000+01:00', 'level': 'CHEAP'},
  {'total': 2.7094, 'startsAt': '2022-12-05T01:00:00.000+01:00', 'level': 'CHEAP'}
]```
#

That's whats in the today & tomorrow properties.

mighty ledge
#

ok

#

well your format is wrong

#

for the comparison

#

I'm not sure why these guys didn't use ISOFormat

proud cradle
#

For the date? I'm not sure their tech department is ran by the most experienced devs tbh given how much downtime and issues they have

marble jackal
#

ah, they added microsends milliseconds

mighty ledge
#

yeah, but this will work

#
          {% set currentPrice = states('sensor.electricity_price_total') | float %}
          {% set gridFees = states('input_number.electricity_grid_fees') | float %}
          {% set threshold = 0 %}
          {% set onRate = 0.6 %}
          {% set alwayOnBelow = 1 %}
          {% set neverOnAbove = 6 %}
          {% set ts = (now() - timedelta(hours=1)).replace(microsecond=0).isoformat("#", "milliseconds") %}
          {% set today = expand('sensor.tibber_prices') | selectattr('today', 'defined') | map(attribute='today') | first | default([]) %}
          {% set tomorrow = expand('sensor.tibber_prices') | selectattr('tomorrow', 'defined') | map(attribute='tomorrow') | first | default([]) %}
          {% set items = (today + tomorrow) | rejectattr('startsAt', 'lt', ts) | list %}
          {% set prices = items
              | rejectattr('total', 'none')
              | map(attribute='total')
              | sort
          %}
          {% set threshold = prices[(prices | count * onRate) | int] + gridFees %}
          {% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
          {% set heater = items
              | rejectattr('startsAt', 'lt', ts)
          %}
          {% set ns = namespace(vars = []) %}
          {% for item in heater %}
            {% if item.total + gridFees < threshold %}
              {% set ns.vars = ns.vars + [{'value': 1, 'startsAt': item.startsAt}] %}
            {% else %}
              {% set ns.vars = ns.vars + [{'value': 0, 'startsAt': item.startsAt}] %}
            {% endif %}
          {% endfor %}
          {{ ns.vars }}
#

I'm sure the ending could be optimized, but I didn't feel like it 🤣

proud cradle
#

🙂
UndefinedError: list object has no element 0

mighty ledge
#

the integer selection you're doing is suspect too

proud cradle
#

It's the items array that's empty

#

Is any part of my code usable? 🤣

mighty ledge
#

well

#

it can be fixed, hold on