#templates-archived

1 messages · Page 20 of 1

mental violet
#

I have 12 attributes all with the same long value_template. Except with one difference, a number value. But this value is also in the name of the attribute.

#

so instead of hardcoding it, I want to just do:
{%set number = this.attribute.thisname |replace('...','')%}

inner mesa
#

That's probably more characters than just using the name

#

But no, I don't know of a way to reference the name of the attribute that you're defining

mental violet
#

it would be cool, because now I need to access the attribute before the attribute I currentl defining

#

but thank you anyway^^

zealous drum
#

Can anyone help me - Do you see anything wrong with this??

is_weekend_day list: {{ is_state('sensor.day_of_the_week', ['Saturday','Sunday']) }}
is_weekend_day: {{ is_state('sensor.day_of_the_week', 'Sunday') }}
Day of Week: {{ states('sensor.day_of_the_week') }}

I get False, True, 'Sunday' for these 3...

inner mesa
#

You at least need to surround the template in quotes

#

But yes, you've made up some syntax there

zealous drum
#

? - not following. I'm doing this in the developer test area.

inner mesa
#

If you were to actually use it elsewhere...

#

Your first statement is using incorrect syntax

zealous drum
#

I'm attepting to check against a list - according to this documentation - https://www.home-assistant.io/docs/configuration/templating/

is_state compares an entity’s state with a specified state or list of states and returns True or False. is_state('device_tracker.paulus', 'home') will test if the given entity is the specified state. is_state('device_tracker.paulus', ['home', 'work']) will test if the given entity is any of the states in the list.

inner mesa
#

You can't just stick a list in there

zealous drum
#

is that documentation wrong? that's what they seem to do.

inner mesa
#

Really?

wheat junco
#

I see it listed in the docs too. Interesting.

inner mesa
#

Fascinating

zealous drum
#

I mean, it doesn't WORK... but that's what I'm trying to do

wheat junco
#

I just tried it on a local sensor myself and it does work.

zealous drum
#

did you try it in the developer test? Wonder why it's not working for me.

inner mesa
#

works for me too

wheat junco
#

Yes, I tested this {{ is_state('person.me', ['home','TF']) }} and it worked. It is case sensitive though.

zealous drum
#

looks like I'm a version behind. Let me update.

#

never know. 😄 maybe they fixed this exact bug. haha.

wheat junco
#

Found this in the docs detail: frenck Allow is_state to accept a list of values (#25031)…

zealous drum
#

in 12.1?

#

i was on 11.5

#

wow lol

inner mesa
#

I always do: {{ states('sensor.day_of_the_week') in ['Saturday','Sunday'] }}

zealous drum
#

such a subtle difference. I wonder what the benefit of one vs the other is

wheat junco
inner mesa
#

lol:

emontnemery merged 3 commits into dev from is-state-in-list 11 days ago

zealous drum
#

or if it's just another case of 20 different ways to do the same thing.

heavy mortar
#

What's the best approach for animation / flashing icons? Card mod?

inner mesa
#

well, we all learned something

wooden tusk
#

Counting lights in a group like this

#

{% set ns = namespace(res=0) %}
{% for lightg in state_attr('light.all_lights', 'entity_id') %}
{% for light in state_attr(lightg, 'entity_id') if is_state(light, 'on') %}
{% set ns.res = ns.res + 1 %} {%endfor%}
{%endfor%} {{ ns.res }}

#

How to make sure the state is returned as number? beacuse id like to use the result for a <> evaluation

inner mesa
#

that's quite overcomplicated

#

{{ expand(state_attr('light.foo', 'entity_id'))|selectattr('state', 'eq', 'on')|list|length }}

wooden tusk
#

Nice! This will result a number?

inner mesa
#

yes

wooden tusk
#

Template is working fine, i get the number. but when evaluating the result its not working.

inner mesa
#

what?

marble jackal
inner mesa
#

We need a "Only for Template Geeks" section

still plank
#

Is this right:

action:

  • if:
    • condition: template
      value_template: trigger.to_state.state == "on"
quiet creek
#

Is there a way to have a binary on off sensor to check whether I have an event with a specific name on my calendar for the current day? I have an google calendar that I am subscribed to and I want to check at the beginning of the day (before that event takes place) whether I have it or not. The name has two variations.

inner mesa
#

You don't need a template for that. Just a state condition

still plank
#

I think the formatting is right. I guess my query is quotes, {{ etc and if I want trigger.to_state or to_state.state

inner mesa
#

It is not

marble jackal
#

Unless the state changes really often a state condition will indeed probably be fine. But there is always a chance that the state has changed again between the trigger and the the if-then

still plank
#

Oh I see. Don’t bother with the trigger variable, just look at the actual entity state instead

#

My trigger is a schedule so it doesn’t change a lot

#

I’m using it/else in order to call either switch.turn on or off

#

An you use templates in the service name ?

marble jackal
#

Yes

slow vine
#

is this a valid template condition? value_template: "{{ media_command == 'pause'}}" obviously media_command is a variable that is set in the automation.

    - variables:
        media_command: "{{ tags[trigger.event.data.tag_id].media_command }}"
inner mesa
#

Yes, assuming that the variable has a valid value

slow vine
#

I am using it in an automation as part of a choose action. I can watch the event in event monitor and the command is coming as pause so i think that means its valid. I will try to put up what I have on pastebin. Or is a thread better?

inner mesa
#

What is wrong?

buoyant pine
#

Where do I begin

slow vine
#

The problem is the condition seems to not be evaluating properly.

#

I guess this means something.
while parsing a block collection in "/config/packages/media/rfid_jukebox.yaml", line 47, column 9 expected <block end>, but found '?' in "/config/packages/media/rfid_jukebox.yaml", line 56, column 9

inner mesa
#

Where is tags defined?

slow vine
#

ok ok. Don't kill me yet. It was an extra space.

#

I looked but sometimes yaml indents when they are a few steps in get confusing.

#

Its all good now.
tags are defined here:

automation:
  variables:
    tags:
      XX-XX-XX-XX:
rugged knot
#

Not sure where this question belongs, I'm trying to set up a helper, looks to be exactly what I want ... I can't seem to figure a way to make it "sum" two values with a negative (I'm assuming there's some way to use it to do "difference" right?)
I know I can do it with a template, I just wanted to test out the helper stuff
I should clarify, I mean the "combine the state of various sensors" part

somber hamlet
#

Can someone explain to me how I can put the result of this template into a template sensor? {{ state_attr('sensor.current_electricity_price_all_in', 'prices') | selectattr('from', 'gt', now()) | max(attribute='price') }}
De result of the template:{'from': datetime.datetime(2022, 12, 12, 17, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam')), 'till': datetime.datetime(2022, 12, 12, 18, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam')), 'price': 0.7424}I want to put the price in the template sensor.

inner mesa
#

Add ['price']

marble jackal
#

Or replace max(attribute='price') with map(attribute='price') | max

rugged knot
#

Is my question on helpers not something that people do, or is there something wrong with my question that is causing people to avoid answering?

somber hamlet
#

Great. Thank you both!

tropic pine
#

Hello Community, yesterday I did wrote a little code for tracing the position of my vacuum cleaner along the home and I don´t know exactly what happened.. I think there is an issue with the templates on the recent releases (I would report it in the core bug report web) .. by steps. In the Template Editor developer I could SET two variables easily (pos_x and pos_y) and then use those to in the remaining code where I compare those coordinates with this code : '''{% set vac_y = (state_attr("camera.xiaomi_cloud_map_extractor", "vacuum_position")).y%}''' and this can´t be used in the "template sensor". So I had to create two additional sensors for the X and Y values.. of witch states("vac_x") is the above code. Till here okay.. probably.. there is any how an issue as per.. on developer template the states return a sting instead of an integer and the check / validation on the core reload passed generating an "unknown" value of the template of the second sensor (to trouble shoot this it took a while) . What I´m trying to report.. is that there is a huge validation difference between the developer and and core validation.. (of course I wold give more details).. I´m just wander if this is normal "as it should be" or somehow a bug as I suspect.. that we would need to report on the appropriate channels.

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
#

@tropic pine share all relevant code using one of the websites above

#

Not only the template, but the full sensor yaml

tropic pine
#

this is the template editor code:

#

{% set vac_y = (state_attr("camera.xiaomi_cloud_map_extractor", "vacuum_position")).y%}
{% set vac_x = (state_attr("camera.xiaomi_cloud_map_extractor", "vacuum_position")).x%}
{% if (vac_x > 20191 and vac_x < 23043) and (vac_y > 22475 and vac_y < 24002) -%}
kitchen
{% elif (int(states("sensor.vac_x")) > 20214 and vac_x < 26082) and (vac_y > 23992 and vac_y < 27735) -%}
livingroom
{% elif (vac_x > 26204 and vac_x < 27631) and (vac_y > 22122 and vac_y < 24966) -%}
entrance
{% elif (vac_x > 23710 and vac_x < 26512) and (vac_y > 21954 and vac_y < 23876) -%}
bathroom
{% elif (vac_x > 26190 and vac_x < 30695) and (vac_y > 24474 and vac_y < 27615) -%}
bedroom
{%- endif %}

#

and this are the sensors (final version):

plain magnetBOT
#

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

#

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

plain magnetBOT
#

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

keen holly
#

im trying to put that if statement into a sensor whats the trick lol

marble jackal
#

@keen holly you are nesting templates

#

and you are using value_template where you should use state

#

I assume you don't want to have "state: " in the actual state?

#
  - sensor:
      - name: Estimated Boiler Runtime
        state: >
          {% if is_state_attr('climate.office', 'hvac_action', 'heating') and is_state_attr('climate.kitchen', 'hvac_action', 'heating') and is_state_attr('climate.dining_room', 'hvac_action', 'heating') %}
            heating
          {% else %} 
            idle
          {% endif %}
keen holly
#

ya im just trying to get get combined state from all of those sensors so il try that, i didn't know i could just put math after the state

keen holly
#

ok so with it like that my if statement is going true anymore

plain magnetBOT
#

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

keen holly
#

i changed my ands out for ors that was definitely wrong but its still only spitting ut the else, am i breaking any rules in my if statement?

marble jackal
#

you are back to square one, again nesting templates

#

and you replaced all my is_state_attr() with state_attr() == 'heating' again

keen holly
#

i didnt even see that change lol

marble jackal
#

basically the only thing you needed to do is replace all and with or in my version

keen holly
#

so i cant use the == alright

#

il hit the man pages yours worked right away

#

im sure there is a page on how to make if statements, but wasn't finding much for checking them against a string just all floats thank you very much

marble jackal
#

you can use ==

#

you can also use state_attr() == 'bla'

#

but it is advised to use is_state_attr() when possible

keen holly
#

ya thats much cleaner

still plank
#

can you set state attributes for a template sensor? or only the main state?

solid fox
#

Am I correct to use the template switch for turning my tado heating on and off through an input_boolean?

plain magnetBOT
#

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

solid fox
#

This ^^ crashed my home assistant and can’t access it for now.

I just want to have a toggle between heating on/off but also if I use the climate card and press there off or on, the toggle should switch with it

mighty ledge
#

that doesn't do what you think it does

marble jackal
#

That, and it is missing platform: template

mighty ledge
#

and I don't see how it would crash HA

solid fox
solid fox
#

And HA keeps “crashing” or at least unavailable…

mighty ledge
#

define crashing

#

adding that will not cause a crash. It simply won't reload your template sensors. If you're restarting, HA simply won't start. I.e. No crash

#

a crash is when HA stops working from a working state without the user doing anything.

solid fox
#

The “crash” I experience it trying to change something in config, checking the config and restarting but between config and checking my config it keeps loading. Refreshing browser gives me just an empty screen (no ha screen but just black) keeps trying for around 20min before being back available and still with old config

#

But anyway, I understand I can’t do the things I want with a template switch, if there is a solution for it, what is it?

marble jackal
#

It should not be in template.yaml, it belongs under switch

#

but you should just create an automation, which performs these actions triggered by a state change of that input_boolean

solid fox
marble jackal
#

you can put it in one

#

the shortest way it to use a template 🙂

#
trigger:
  - platform: state
    entity_id: input_boolean.verwarming_winter
action:
  - service: climate.set_hvac_mode
    data:
      entity_id: climate.woonkamer
      hvac_mode: "{{ 'auto' if trigger.to_state.state == 'on' else 'off' }}"
#

well, this is the one to change the climate based on the input_boolean

#

if you want changes made to the climate entity also reflected in the input_boolean, it's easiest to create a second automation

solid fox
#

Okay thank you! I’ll make a group first for both hvac_mode of my badkamer and woonkamer so I can toggle the group.

#

First gotta get that wrong config changed

marble jackal
#

you can also ditch the input_boolean completely, and do create a template switch

solid fox
#

I have created a dashboard with mushroom and got some sort of banner with a switch called “Wintermodus”. It displays “on” or “off” and should be setting the hvac on or off. For now I have 1 automation to put in on and I use a helper for this.

marble jackal
#
switch:
  - platform: template
    switches:
      verwarming_winter:
        unique_id: template_swicht_climate_woonkamer
        value_template: "{{ not is_state_attr('climate.woonkamer', 'hvac_mode', 'off') }}"
        turn_on:
          - service: climate.set_hvac_mode
            data:
              entity_id: climate.woonkamer
              hvac_mode: auto
        turn_off:
          - service: climate.set_hvac_mode
            data:
              entity_id: climate.woonkamer
              hvac_mode: "off"
#

If you use this template switch, the state will match the setting of the climate entity, and toggling it will turn set it to auto or turn it off

solid fox
#

Okay wow that’s a great help! Thank you so much! So I keep my helper called “verwarming_winter” and just put this in my config and configure my switch in the dashboard with this

marble jackal
#

no, you don't need that helper if you use this

solid fox
#

Even better! Thanks and sorry for bothering! Kinda lost my way in the docu

marble jackal
#

this will create switch.verwarming_winter which you can use to toggle the climate entity

solid fox
#

Thanks a lot!

royal rampart
#

so... I hammered google for a bit but now I'm here... I have an mqtt topic that is an array of warnings warnings = ["Cannot Ping e1.31 Channel Data Target 10.0.0.52","FPP Scheduler is disabled"] - I'm trying to set up a value template to be "on" or "true" if the array contains FPP Scheduler is disabled is that something I can do in a value_templaet?

floral shuttle
#

just noticed today.... that y startup script/notification doesnt pronounce the -. in the current temp that is.....```
sequence:
- variables:
temp: >
{{states('sensor.temp_current')}}
- service: script.intercom_message
data:
message_en: >
Good {{states('sensor.part_of_day')}}, Home Assistant is back up and running since
{{now().strftime('%A %d %B %X')}} and it is {{temp}} degrees.
message_nl: >
Goede{{states('sensor.dag_deel')}}, Home Assistant is weer actief sinds
{{states('sensor.dag')}} {{now().strftime('%-d')}} {{states('sensor.maand')}} en buiten is het
{{temp}} graden.

#

should I fix that in the template somehow? it would say: Maandag 12 December en buiten is het -1.4 graden.

marble jackal
royal rampart
#

I'd started down the path of writing for loops 😄

marble jackal
# floral shuttle just noticed today.... that y startup script/notification doesnt pronounce the `...

I've seen this before, not sure if it was here.
What you can do:

          message_en: >
            Good {{states('sensor.part_of_day')}}, Home Assistant is back up and running since
            {{now().strftime('%A %d %B %X')}} and it is {{ 'minus ' if temp < 0 }}{{ temp  | abs }} degrees.
          message_nl: >
            Goede{{states('sensor.dag_deel')}}, Home Assistant is weer actief sinds
            {{states('sensor.dag')}} {{now().strftime('%-d')}} {{states('sensor.maand')}} en buiten is het
            {{ 'min ' if temp < 0 }}{{ temp | abs}} graden.
floral shuttle
#

yep, will do, thx. its just that I was surprised to hear GA almost pause on the minus sign. (was the first freezing restart since a long time.....)

#

just try this

marble jackal
#

Guess it freezes on the minus sign 🥁

floral shuttle
#

haha yes, and when I change that to +5 it does say Plus 5

marble jackal
#

hmm, so it does the the +.. strange

plain magnetBOT
#

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

mental violet
#

hi, I need a template, that gets 3 lists 'previous_list' and 'should_be_in_list and 'should_not_be_in_list and does the following
if an element is in the should_be_in_list and NOT in previous_list, than add that element to previous_list
if an element is in the should_not_be_in_list and IN previous_list, than delete only that element from the previous_list
otherwise do nothing
I have this code, but it doesnt quite work, when something in the lists changes things get messy.
For convinience you can just put my code into template test area.

plain magnetBOT
#

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

stiff crane
#

What am I doing wrong here?
{{ cal_events.attributes.start_time | timestamp_custom('%Y:%m.%d') }}

slow vine
#

I'm trying to set a variable in the action part of an automation using data from the trigger and its not evaluating. how can I test it? I tested in dev tools using the actual device_id not from the trigger and it seems ok.

stiff crane
#

output without filter is: 2022-12-13 12:30:00

slow vine
#

heres what I tried:

  action:
    - variables:
        media_player_entity_id: >-
            {% for entity in expand(device_entities(trigger.event.data.device_id))|map(attribute='entity_id')|list %}
              {% if is_state_attr(entity, 'friendly_name', 'Media Players') %}
                "{{ states(entity) }}"
              {% endif %}
            {% endfor %}
slow vine
#

{{ cal_events.attributes.start_time | as_timestamp | timestamp_custom('%Y:%m.%d') }}

inner mesa
#

further, you need some sort of default to avoid that whole thing evaluating to nothing and blowing up

stiff crane
mental violet
#

@inner mesa do you have any help?

inner mesa
#

no

slow vine
#

I tried to come up with something for default:

{% set id = "default" %}
{%- for entity in expand(device_entities("ba27048b2237478aadb9d0af5b630328"))|map(attribute='entity_id')|list -%}
  {%- if is_state_attr(entity, 'friendly_name', 'Media Players') -%}
    {% set id = states(entity) %}
    {{id}} = id <--- for testing only
  {%- endif -%}
{% endfor %}
{{id}} <-- what we are looking at
#

but its not working. this is what i got:

media_player.squeezeplay = id <--- for testing only
default <-- what we are looking at
inner mesa
#

you need to use a namespace if you're going to be setting a variable within a for loop

#

the whole thing seems overly complicated, though

#

you're trying to get the state of the entity that has "Media Players" as its friendly_name?

#

like, this: expand(device_entities("ba27048b2237478aadb9d0af5b630328"))|map(attribute='entity_id')|list is exactly the same as device_entities("ba27048b2237478aadb9d0af5b630328"), right?

#
{{ expand(device_entities("ba27048b2237478aadb9d0af5b630328"))|selectattr('attributes.friendly_name', 'eq', 'Media Players')|map(attribute='state')|list|default(['Nothing'], True)|first }}
marble jackal
rugged knot
#

Hate to repost, my question yesterday seems to have gotten lost in the scrolling, but can anyone tell me how to make the helper "sum" take one number from another?

rugged knot
# tired sandal what do you mean

create helper -> combine the state of several sensors -> sum -> ... I want to take one room temperature from another, but I can't figure how to get a negative sign in there

tired sandal
#

....is this in the GUI?

rugged knot
#

yes

tired sandal
#

oh.

#

what expression do you have in there right now?

rugged knot
#

I can add the two temperatures together just fine. I just can't subtract one from the other no matter what I try.

tired sandal
#

...ok - can you show me what expression you have?

rugged knot
tired sandal
#

...oh

#

yeah i don't think you can do that - i think you need to create a template sensor

#

i could be wrong though

rugged knot
#

That combine helper would be really useful with a "difference" function if "sum" can't do it. I tried adding 'negatives' to the entities, but it doesn't seem to recognize the entity then

#

I know I can do it with a template, was trying to use the "new this version" feature that seemed like it was just the thing

#

I haven't yet figured out what language the template stuff is written in etc, hence attmepting to avoid it. I'm new to HA

#

Thanks for the help @tired sandal

inner mesa
#

It's Jinja

rugged knot
#

Ahh, thanks! I would never have found that without the pointer

mental violet
#

can I set the state of an input_number in a template?

mighty ledge
slow vine
# inner mesa like, this: `expand(device_entities("ba27048b2237478aadb9d0af5b630328"))|map(att...

I don't think so..? I am really using device_entities(trigger.event.data.device_id) not the actual deviceid. I want to return the entity_id that has friendly name of 'Media Players' but that belongs to the trigger.event.data.device_id I am basically using an rfid reader to control mediaplayers and which player should be controlled is based on the device that read the card, like the example in the blog at https://www.home-assistant.io/blog/2020/09/15/home-assistant-tags/ , with the difference that instead of a static device based on the scanner there is a select component to decide the entity_id. I couldn't figure out a less complicated way but I am deefinitely interested if there is. And I am not too good at this to really be able to tell if I can do it easier.
Thanks.

mighty ledge
inner mesa
#

it returns state objects?

mighty ledge
#
{{ device_entities(trigger.event.data.device_id) | select('is_state_attr', 'friendly_name', 'Media Players') | map('states') | list ...
inner mesa
#

look at you, using the new features

mighty ledge
#

I didn't add them for my health!

#

I thought it would be shorter, but then I forgot it was is_state_attr

#

YMMV

inner mesa
#

👍

willow heart
plain magnetBOT
#

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

thorn torrent
#

nevermind, forgot quotes around my template 🤦

grim flicker
#

i have this template https://hastebin.com/ihacetuqeq.php could someone have a quick look and tell me what im doing wrong here? I want to take all the valve positions and take an average. but only take the value if its available. the error states: TemplateSyntaxError: Encountered unknown tag 'gemiddeld'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.

#

i guess within an if i cant use {% , %} but how is it done the right way? {{ , }} obviously dont work either

marble jackal
#

You can use {% within an if

grim flicker
#

then im doing something else wrong but i dont know what

marble jackal
#

yes, you are not using set

#

for example on lines 9 and 10 you need to use {% set gemiddeld = gemiddeld...

#

you are now using {% gemiddeld = gemiddeld

#

{% if (states('number.badkamer_thermostaatkraan_valve_control')|float != 'unavailable') %} you should also remove the float filter here

#

with it the template will run in error if it is actually unavailable

#

Or use
{% if states('number.badkamer_thermostaatkraan_valve_control') | is_number %}

grim flicker
#

Thanks allot! it works like a charm now

#

didnt know i had to use set every time i thought i only needed it to start a variable

solid fox
marble jackal
#

So if the action to set the hvac_action to auto is not performed, the switch will indeed toggle back to off

solid fox
#

Can I post a video somewhere?

marble jackal
#

It seems the problem is the service call defined under turn_on. I don't have any climate entities, so I can not test this myself

solid fox
#

Can maybe also a problem with my tado

marble jackal
#

You don't need to post a video, I understand what is happening and just explained you why it is happening

solid fox
#

The code should be working so I’ll try and figure out what is wrong with it internally and if it’s my tado. Cause can I input multiple services (also climate.badkamer)?

marble jackal
#

what happens if you try this in developer tools > services

service: climate.set_hvac_mode
data:
  entity_id: climate.woonkamer
  hvac_mode: auto
solid fox
#

I get: alle beschikbare parameters: hvac_mode

#

New value of operation mode

#

Tado/hvac is unresponsive

marble jackal
#

can you turn it to auto in a different way which does work?

#

in Home Assistant?

solid fox
#

Oh yeah it’s working just very slowly

#

Okay no, corrction: it’s working!

#

Both off and auto

marble jackal
#

okay

#

they your switch will also work

solid fox
#

(Also heat) but i don’t use that

marble jackal
#

but it will toggle back first

#

then when the entity is updated it will go to the correct state

solid fox
#

Okay, so the toggle will switch back to on and after a while goes back to off

marble jackal
#

yes, as soon as the service call is processed and visible on the climate entity

solid fox
#

I see the climate entity switch immediately on my climate card but switch keeps toggling on. Should I put a delay on it? For it to process correctly?

#

Maybe the service switches a little bit late causing my switch so notice the not is_state_attr to not have changed states

grim flicker
#

I have the same issues with my switched for turning my tv and pc on. Home assistant updates the states to fast so i turn a swith on the pc turns on but because the pc hasnt yet confirmed its on to ha the switch goes back to off. when i wait until the pc updates its state to ha the switch is turned back on automatically.

solid fox
#

^

marble jackal
#

You can't put a delay on that state template

#

but if the climate card updates immediately, something is updated immediately

#

probably the state of the entity, instead of the hvac mode

solid fox
#

Imo, HA should make a function (without hassle or yaml) to connect some entities to a switch.
On = …
Off = …

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.

solid fox
#

Yes indeed. Hvac mode is possible since tado updates late

#

And also TheFes can I connect both climate.woonkamer and climate.badkamer in the same switch?

#

Or should I make a group?

marble jackal
#

you can just add more entities to the service calls

#
service: climate.set_hvac_mode
data:
  entity_id: 
    - climate.woonkamer
    - climate.badkamer
    - climate.zolder
  hvac_mode: auto
grim flicker
#

Wouldnt it be easier to just make an input boolean which runs some scripts when its turned on and off?

solid fox
marble jackal
#

you can add a whole array of actions to the turn_on section

#

basically the template switch is the same as an input_boolean and an automation

#

but then combined in one entity

solid fox
#

I know but for beginners it’s easier if you can configure 1 input boolean in simplified modus. But that’s off topic. I’ll adjust the data and see if that helps with the switch

marble jackal
#

if you open one screen with developer tools > states

#

then search for the entity in the table (climate.woonkamer)

#

and issue the service call to turn it to auto or off

#

(on a separate screen, or on your phone)

#

do you see something changing immediately?

solid fox
#

The change happens immediately. And I timed it and the switch turns back on after 3seconds

marble jackal
#

what exactly changes immediately?

#

probably not the hvac_mode

#

so what does change

#

the state itself?

solid fox
#

My climate card has multiple sensors: the hvac mode (auto, heat, off), geolocation mode (home, away) and temp sensor. I can see the hvac mode chance from auto to off when I press the button in dev tools > services

mighty ledge
#

I'd wager that your value_template isn't set up properly

#

as that's what determines the state in the UI

marble jackal
#

so the attribute hvac_mode changes immediately when you press the button?

marble jackal
#

value_template: "{{ not is_state_attr('climate.woonkamer', 'hvac_mode', 'off') }}"

solid fox
#

^

marble jackal
#

if the attribute changes immediately, that template should change immediately as well.. unless there is something I'm missing here

#

if you put that template in developer tools > templates, and then change the hvac mode using the service call, does it update then?

grim flicker
#

i think the correct question here would be. does it change multiple times in a short time

grim flicker
#

put this {{ not is_state_attr('climate.woonkamer', 'hvac_mode', 'off') }} in devtools > templates and watch the result when you change this hvac

#

the button should never switch back as long as the state of the attribute isnt changing

solid fox
#

It stays “True”

#

When setting to auto or off

grim flicker
#

its not like off is Off or something right? i have an AC that has some strange attributes with different ways of writing

marble jackal
#

yes, what is the state of the hvac_mode attribute when it is set to off

#

and this is case sensitive

solid fox
#

The hvac turns to auto and off just the switch reacts weirdly

marble jackal
#

so, again, what is the state of this attribute (hvac_mode) when you've set it to off

#

please copy paste it from developer tools > states

#

or post a screenshot using imgur

grim flicker
solid fox
#

It’s ‘off’

marble jackal
#

uhm.. there is no hvac_mode attribute in your screenshot @grim flicker

marble jackal
solid fox
#

hvac_modes:

  • ‘off’
  • auto
  • heat
marble jackal
#

I don't have a climate entity, you need to provide me the information I need

solid fox
#

But it’s not hvac modes 🤔

marble jackal
#

that's not what I need, that is a list of the possible hvac_modes, not the one currently set

solid fox
#

Ah

marble jackal
#

so again, WHAT is changing when you set the hvac_mode

solid fox
#

Yes sorry

#

hvac_action: heating

#

This?

marble jackal
#

what does that show when you set the hvac_mode to off?

grim flicker
#

i think the hvac modes as in my screenshot is also always the state of the climate

solid fox
grim flicker
#

so it can only be one in that list

solid fox
#

It changes to ‘off’

marble jackal
#

the hvac_action changes to off?

solid fox
#

Yes

#

And I think what’s happening is that my tado can be in auto mode also be ‘heating’

marble jackal
#

Then use:
value_template: "{{ not is_state_attr('climate.woonkamer', 'hvac_action, 'off') }}"

#

for the switch

grim flicker
#

i dont follow this. when you change hvac mode the climate state will change according to the choosen hvac mode. the hvac state is always the hvac_modes chosen attribute.

solid fox
marble jackal
#

no need to reboot

#

just go to developer tools > yaml and reload template entities (sjabloonentiteiten if you have your language set to Dutch)

marble jackal
grim flicker
#

if you have switch: configured in your configuration.yaml i dont think you can reload a switch like that

marble jackal
#

yes you can, everyting under the template integration or using platform: template is a template entity, and will be reloaded when you reload template entities

grim flicker
#

good to know 🙂

solid fox
#

Indeed good to know!

#

It’s working! 🎉 1 final question I have mushroom with a template card. I use it to replace the switch with the following code: {{ (states(‘switch.wintermodus_2’))}}

#

But that won’t work

marble jackal
#

place the yaml code of the entire card here

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.

#

Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.

marble jackal
#

grr

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

#

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

solid fox
#

Sorry! My bad

marble jackal
#

is should show on or off

#

what does it show?

solid fox
#

Always on and not being able to interact

marble jackal
#

entity: input_boolean.verwarming_winter

#

you defined that as entity so you are toggling that entity

#
  - type: custom:mushroom-template-card
    primary: Winter
    secondary: '{{ states(entity) }}'
    icon: mdi:snowflake
    layout: vertical
    icon_color: blue
    multiline_secondary: false
    entity: switch.wintermodus_2
    fill_container: true
    tap_action:
      action: toggle
    hold_action:
      action: none
    double_tap_action:
      action: none
solid fox
#

🤦🏻‍♂️

#

I see

marble jackal
#

You can refer to the entity you defined there using the variable entity

solid fox
#

I misread that

marble jackal
#

secondary: '{{ states(entity) }}'

solid fox
#

It’s fixed

#

Thank you! My bad just read over it

#

Was always thinking to just changing the secondary but yep my bad

#

You’re a life saver @marble jackal thank you for helping!

#

If coding is not your knowledge it’s great to have some help!

thorny snow
#

hey, I'm trying to make my smart coffee machine into a template that i can control on the dashboard, with the amount of cups i can set, and such like

marble jackal
#

Okay, sounds fun!

thorny snow
#

Any idea how I would get it to display a gauge and suchlike?

marble jackal
#

a template entity can just provide data

thorny snow
#

Ah ok

thorny bolt
#

I need a bit Help, to invert my Shutter

plain magnetBOT
#

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

thorny bolt
#

This Template ist working, but i need to invert the states Open/Closed/opening/closing too

#

I hate to have my Shutter at 100% when Open and 0% when closed

lethal locust
#

why you don't wire the shelly/whatever inverted?

thorny bolt
#

I use an HomeMatic BROLL with RaspberryMatic

#

When i invert it on the Hardware Side, the Buttons in the Switch are also inverted, and thats what infont want

carmine jungle
#

Hey, i am trying to create template sensors to format data obtained by the nextcloud integration. I have the issue that those values show as XYZ GB GB for the first sensor and XYZ GB MB for the latter one. Any idea what could be wrong?

template:
  - sensor:
    - name: "NextCloud Free Space (GB)"
      unit_of_measurement: "GB"
      state: >-
        {{ (states('sensor.nextcloud_system_freespace') | filesizeformat(GB)) }}

    - name: "NextCloud PHP Upload Max Filesize (MB)"
      unit_of_measurement: "MB"
      state: >-
        {{ (states('sensor.nextcloud_server_php_upload_max_filesize') | filesizeformat(MB)) }}
marble jackal
#

What's the state of these source sensors?

carmine jungle
#

You mean the last reported value, right? It is 917442527232 for the first and 10737418240 for the latter one without any unit after the value

marble jackal
#

well, if I try {{ '10737418240' | filesizeformat(MB) }} in developer tools > template, I get UndefinedError: 'MB' is undefined

#

same with GB btw

carmine jungle
#

Idk, i copied it from the forums and used MB as it seems it is defined. It also does work but it has the double unit suffix

marble jackal
#

it only accepts true or false and based on that is shows MB or MiB

#

the unit it shows is based on the input

carmine jungle
carmine jungle
marble jackal
#

unit of measurement doesn't make sense here, your ouput is a string, not a number

#

not sure what that link has to do with it though

carmine jungle
marble jackal
#

there is nothing regarding to filesizeformat() in that topic

carmine jungle
marble jackal
#

Well, it's not a good post

#

if you want the MB just divide your source sensor with1000000

#

if you want MiB divide it with 1048576

carmine jungle
#

Ohh i think i understand it now ^^

marble jackal
#

the filter you are using now will output a string, already including the unit of measurement

#

and based on how high your input is, it will return kB, MB, GB, TB etc

#

of KiB, MiB, GiB, TiB

carmine jungle
#

This is working now 🙂 I assumed i have to tell it what the input value is (bits, byte, kb, kib, etc.) and also what the format target is. It is actually just assuming Bytes and as you said the function parameter only toggles Bi notation

template:
  - sensor:
    - name: "NextCloud Free Space"
      state: >-
        {{ (states('sensor.nextcloud_system_freespace') | filesizeformat(true)) }}

    - name: "NextCloud PHP Upload Max Filesize"
      state: >-
        {{ (states('sensor.nextcloud_server_php_upload_max_filesize') | filesizeformat(true)) }}
marble jackal
#

yes, but these sensors will now not be usable to create graphs

#

you can use them on your dashboard though

carmine jungle
# marble jackal you can use them on your dashboard though

Yeah that was the main goal. I got to see when i have to bump the storage share plan as all my NC users have unlimited quota.
But what would i have to do to also make them work on graphs? Is this a simple addition or would i need a completely different setup?
Got to admit i am still at the very beginning with HA.

marble jackal
#

well, then you need to do something like

template:
  - sensor:
    - name: "NextCloud Free Space"
      unit_of_measurement: "GiB"
      state: >-
        {{ (states('sensor.nextcloud_system_freespace') | float(0) / 1024**3) | round(2) }}
#

but if your free space becomes less than 50 MiB, it will show 0 GiB as the unit will not change

carmine jungle
#

Ahh so graphs will only work with numeric values?

#

Seems familiar coming from prometheus 😅

inner mesa
carmine jungle
inner mesa
#

it's a filter, not a cast. And the docs are in the topic

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

carmine jungle
marble jackal
earnest cosmos
#

Is there a way of knowing what event the zone trigger was triggered by
I would like to make one automation and one notify message setup, only to differentiate the message related to event: leave or enter resulting in two different messages related to enter or leave

message: "{{ trigger.to_state.name }} arrived ZONE at {{now().strftime('%H:%M') }}"

inner mesa
#

Or just use the state of the person

earnest cosmos
#

Boy, I missed this setup.

#

Thanks

earnest cosmos
inner mesa
#

The state of a person is the zone they're in. Or not_home

earnest cosmos
#

I was looking for a way of notifying when entering/leaving this particular zone, as trigging a notify for every zone I have defined is not what I want. You have an example of using

The state of a person is in the zone they're in. Or not_home
inner mesa
#

It's just a state trigger

marble jackal
#

states(trigger.entity_id) will return the zone of the person entity triggering this automation

#

assuming you are using a state trigger on person entities

#

oh wait just use trigger.to_state.state

inner mesa
#

There no magic here, just entities and states

marble jackal
#

🪄

earnest cosmos
#

Sure. I can use this, but maybe you guys had som magic to spread on this huge code 🙂

message: >
  {% if (trigger.event) == 'leave' %}
    {{ trigger.to_state.name }} left {{ trigger.zone.attributes.friendly_name }} kl. {{now().strftime('%H:%M')}}
  {% else %}
    {{ trigger.to_state.name }} entered {{ trigger.zone.attributes.friendly_name }} kl. {{now().strftime('%H:%M')}}
  {% endif %}
marble jackal
#

what trigger are you using?

#

and that is not huge code

compact rune
#

at least it might be less repetitive to do something like {{ trigger.to_state.name }} {% if ... %}left{% else %}entered{% endif %} kl.{{etc.}}

#

but yeah, that doesn't seem bad to me either

earnest cosmos
marble jackal
#

I would personally use a state trigger

earnest cosmos
#

how?

marble jackal
#
- platform: state
  entity_id:
    - person.pal
    - person.eva
  from: "Name of zone"
inner mesa
#

...a state trigger on the person

marble jackal
#

I assume you also have a trigger for entering then

#

without the from you can use it for all zone changes

earnest cosmos
#

I sure have an enter trigger in my setup now

marble jackal
#

well, with from: ~

earnest cosmos
#

was hoping to make to code slimmer some how.

inner mesa
#

Ah, magical coding

acoustic wedge
#

Hi, I'm looking for a way to test if an entity belongs to a group. I don't see any in_group attribute or equivalent in the state of my light entities. Thanks.

#

I think I used something like is_group long time ago but can't make it working.

marble jackal
#
trigger:
  - platform: state
    entity_id:
      - person.pal
      - person.eva
    to: ~
variables:
  person: "{{ trigger.to_state.name }}"
  action: "{{ 'left' if trigger.to_state.state == 'not_home' else 'entered' }}"
  zone: "{{ trigger.from_state.state if action == 'left' else trigger.to_state.state }}"
earnest cosmos
marble jackal
#

then you can build your message like {{ person}} {{ action }} {{ zone }} kl. {{now().strftime('%H:%M')}}

earnest cosmos
#

So the to: ~ will trigger both ways?

marble jackal
#

yes, without it it will also trigger on attribute changes

#

like small updates of coordinates, without you actually changing a zone

earnest cosmos
#

I need to have the automation not trigger for all zones, just this single zone, as I have too many zones defined to want me to have it trigger on every enter/leave 🙂

marble jackal
#

then why bother with templating the zone name?

earnest cosmos
#

To have one string both for enter and leave

marble jackal
#

but it is the same zone, but in one line you are entering it, in the other leaving it

#

still the same zone every time

acoustic wedge
#

light group

#

Actually I would like to count number of on lights, without counting the individual bulbs that belong to a light group (which is already counted)

marble jackal
#

you can get a list of all entities which are in light groups with
{{ states.light | selectattr('attributes.entity_id', 'defined') | map(attribute='attributes.entity_id') | sum(start=[]) | unique | list }}

acoustic wedge
#

Then use that to reject them from the list of on lights, right?

marble jackal
#

yes

acoustic wedge
#

Thanks a lot

acoustic wedge
#

lights in the lights_in_groups list continue to appear in ns

patent flume
#

Is it possible to generate the nice "In X hours" from a datetime string in template? I am using template-entity-row from HACS (I wanted to make it show other things depend on state while still showing the original entity's panel when clicked, so a template sensor won't work) which doesn't support format parameter. I tried relative_time(as_local(as_datetime(states("sensor.octoprint_estimated_finish_time")))) but seems like it doesn't work.

inner mesa
#

It only works for times in the past

#

I think you'd have to build that string

green scaffold
#

Ask chat gpt for help. Works 8/10 times if you ask the right questions

inner mesa
#

then ask it to fix it if it's wrong

thorny snow
#

Is there a way to set multiple inline variables based on a input templated variable?

inner mesa
#

I'm not sure what you're looking for

thorny snow
#

So I have a light template, for my coffee machine, and I need to get it so I can set the number of cups using a script

inner mesa
#

you'll need to break that down a bit more. What exactly are you setting?

#

a light template (template light?) wouldn't obviously have anything to do with an espresso machine or setting a number of cups

thorny snow
#

Well, i figured it's the only thing that has a gauge that somewhat makes sense for that purpose

#

It has a coffee machine icon so my partner knows its for a coffee machine, but it's easier then a light

inner mesa
#

It sounds like you're talking about a card on your dashboard, not a template

thorny snow
#

The template being the math?

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

inner mesa
#

That

thorny snow
#

On the developer console my math works, but when I put it in a script, it doesn't

plain magnetBOT
#

Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.

floral shuttle
#

the integrtion provides attributes for Dewpoint and Estimated critical temp, but as far as I can see, this is not what I am looking for. What I want is a sensor calculating the required inside temp to get the mold indicator show no mold will happen (not sure what percentage that would be really), so I guess below 50%?

rose scroll
floral shuttle
#

yeah, I am not sure that is even possible (a lot of documents online simply state you need to ventilate, or not have your home cool down.....) but was hoping to find the calculation required for that inside this integration. I cant even find the mentioned MAGNUS_K2/3 values documented anywhere

merry marsh
#

If I get
Invalid config for [template]: not a valid value for dictionary value @ data['event']. Got None. (See ?, line ?).
is it wanted behavior to get only ? and not any further helping information? I found the root cause manually, but wonder, why no further information are provided.

#

And would it be possible to include this in config check as it gave no errors where studio code server showed the problem.

#

It was a wrong (copy&paste problem) event-value in platform: homeassistant`

plain magnetBOT
#

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

mighty ledge
#

So if you're asking about the error, that's a generic error produced from the configuration loading that comes from voluptuous (the library that validates our yaml). There's only so much information we can get from the raised exception. So that error is saying that it expects items inside event

#

so the homeassistant trigger requires the event key. When it's not provided, voluptuous populates that key with None and raises the error.

#

Both of these will return the same error

#
- platform: homeassistant
- platform: homeassistant
  event:
- platform: homeassistant
  event: None
#

well, all 3 of those...

mighty ledge
#

yeah, ignore my first comment, read the rest

#

basically, we cant get more information from the voluptuous library as it truncates everything, and when things are included it loses the placement in the file and what file it's reading from.

#

@ornate storm you can use this.state to get the previous state. Keep in mind that a restart wipes that out so you have to have a backup if this is not defined.

#
{{ this.state if this is defined else 22 }}
#

Also, you have to use that syntax, you cannot use iif

#

because of the order of operation that needs to occur

marble jackal
#

A trigger based template sensor restores it, bit you will still lose it if it's already triggered before the state is restored

merry marsh
#

Did so. Understood. Here it was a value, but not a supported one. So not blank nor None. And vsc shows the root-cause of course (wrong, not supported value), so I hoped, that the parser can/will check such things (eventually) as well.

marble jackal
mighty ledge
#

so, it's not a 1-1 case

#

I know that HA and the VSCode addon get out of sync on a regular basis

#

so it's definitely using something else

#

The difference is that it also doesn't combine things into 1 large config object, which is ultimately the problem for voluptuous as that wipes out the file, line, & column numbers

merry marsh
#

True. Was only a wish to get more help, as I only found the problem by chance with the help of vsc. Without line number or more error text, I would have been hard. But ok. It is as it is. Understood. Thx for the explanations.

mighty ledge
#

I think the only way we could solve that is if we rewrite the config parser to not include things and treat each section as it's own file. Or override the thing competely

#

IIRC it combines things prior to checking the schema

#

I'd have to go through the code again

thorny snow
#

I'm looking to get the HH and the MM value from an input_select which has several time options, such as 07:45. I want to input this in a input_datetime, and suppose I have to strip the 07 and set is as hour and 45 as minute in the input_datetime. I already have an automation set up that does this, but how can I extract those values from the input_select?

silent seal
#
today_at('{{ states(input_select.alarm_hours) | int(07) }}:{{ states(input_select.alarm_minutes) | int(30) }}')

Or similar

#

The whole action would probably be something like this:

  action:
  - service: input_datetime.set_datetime
    data:
      datetime: "today_at('{{ states(input_select.alarm_hours) | int(07) }}:{{ states(input_select.alarm_minutes) | int(30) }}')"
    target:
      entity_id: input_datetime.alarm_clock
#

Though you may want to just use a time datetime

thorny snow
#

Thank you, I will try to get this to work. To be able to understand this better in the future, I'm trying to understand what it does. Could you please help me with that? I understand the following:

This action calls the service set_datetime from input_datetime. That data it uses is what follows. That's where I don't really understand anymore. What is today_at used for, and what do int(07) and int (30) do? Looking at the documentation it seems that this influences the base, or is that incorrect?

It then sends this to the alarm_clock entity.

silent seal
#

So | int parses the input to an integer, and the (07) or 30 are "sensible defaults" in case there isn't a number there to read

marble jackal
#

today_at() is a template function, so the whole thing needs to be in curly brackets

#

datetime: "{{ today_at(states('input_select.alarm_hours')~':'~states('input_select.alarm_minutes'))}}"

#

As you are creating a string anyway, there is no need for an int filter

silent seal
#

Though if you had an empty option you wouldn't want that in there, it would cause weird problems

marble jackal
#

If the input select only has sensible options there is no need for a default

silent seal
#

Indeed

thorny snow
mighty ledge
thorny snow
#

If I do that, with the changes of TheFes, it gives me ValueError: could not convert str to datetime: 'unknown:unknown'

mighty ledge
#

then you didn't give it the correct entity_ids

#

you have to have those input_selects

thorny snow
#

I only have one input_select, which is input_select.smartsleep_set, with a value of HH:MM

#

Sorry if I didn't explain that correctly

mighty ledge
#

then it would just be {{ today_at(states('input_select.smartsleep_set')) }}

thorny snow
#

That indeed gives me the full details of the entity, but I would like to split this. The SmartSleep integration uses
number.smartsleep_alarm0_hours and
number.smartsleep_alarm0_minutes to set the alarm, so I would like to get the HH:MM from input_select.smartsleep_set and then send the HH to alarm_hours and the MM to alarm_minutes

marble jackal
#

Ah, so the other way around

mighty ledge
#

just .hours and .minutes from the today_at

#

or .hour

rose scroll
#

Just split the string on : and index the components?

mighty ledge
#
{{ today_at(states('input_select.smartsleep_set')).hour }}
#

that would also work

#
{% set hour, minute = states('input_select.smartsleep_set').split(':') | map('int') | list %}
{{ hour }}
{{ minute }}
thorny snow
#

Thanks a lot, this works! It surprises me that it "knows" that this input_select is in an hour:minute format without telling it.

rose scroll
#

Well...if you use today_at, it converts the string into a time which then has hours and minutes. If you use the string splitting, it really doesn't know that the string is a time, but it doesn't need to know so long as you can extract the info you want.

thorny snow
#

Ah, that explains, thanks!

plain magnetBOT
#

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

mighty ledge
#

@thorny snow you copied hours twice and you aren't setting minutes

thorny snow
#

Wow, damn, that's stupid

#

Thanks!

#

Still not working unfortunately, the trace in the automation is saying this:

expected float for dictionary value @ data['value']

rose scroll
#

What exactly are the options available in your input_select?

thorny snow
#

06:30, 07:30, 08:30 for now.

rose scroll
#

Share your latest automation yaml?

mighty ledge
rose scroll
# thorny snow 06:30, 07:30, 08:30 for now.

I'm about to go off to bed - good luck squashing this bug! But also, do consider to use an input_datetime storing a time only rather than input_select, as the former will be more flexible.

plain magnetBOT
#

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

thorny snow
mighty ledge
#

dude

#

you're still using hour twice

#

the error should also say what it's getting

#

e.g. expected float for dictionary value at data[value] but got; ksjdflkja

#

and i'm 100% sure it's .hour not hours

thorny snow
#

Sorry - pasted the wrong YAML. Already had changed it to minutes. But the hour instead of hours indeed was the problem!

inner mesa
#

That would be clear if you paste the template in devtools -> Templates

thorny snow
#

I'm now trying to rebuild things a bit and send it through an input_datetime (so I can also manually change it). This YAML works in the Templates section of dev tools and shows 6:30 as a value, but gives the following error in traces:

Triggered manually at December 14, 2022, 17:03:52

Input datetime: Set SmartSleep Time

Stopped because an error was encountered at December 14, 2022, 17:03:52 (runtime: 0.01 seconds)

must contain at least one of date, time, datetime, timestamp.

service: input_datetime.set_datetime target: entity_id: input_datetime.smartsleep data: value: '{{ today_at(states(''input_select.smartsleep_set'')) }}'

#

The step details also provide me with a valid timestamp:

Executed: December 14, 2022, 17:03:52 Result: params: domain: input_datetime service: set_datetime service_data: value: '2022-12-14 06:30:00+01:00' entity_id: - input_datetime.smartsleep target: entity_id: - input_datetime.smartsleep running_script: false limit: 10

mighty ledge
ornate storm
# mighty ledge <@185431277246218240> you can use `this.state` to get the previous state. Keep ...

so this would do it right?

{% if is_state('binary_sensor.livingroom_door_sensor_contact', 'on')  and  utcnow().timestamp() - states.binary_sensor.livingroom_door_sensor_contact.last_changed.timestamp() > 90 %}
  17
{% elif is_state('binary_sensor.livingroom_presence_group', 'on')  and  utcnow().timestamp() - states.binary_sensor.livingroom_presence_group.last_changed.timestamp() > 270 %}
  24
{% elif is_state('binary_sensor.livingroom_presence_group', 'off')  and  utcnow().timestamp() - states.binary_sensor.livingroom_presence_group.last_changed.timestamp() > 570 %}
 19
{% else %}
  {{ this.state if this is defined else 5 }}
{% endif %}
thorny snow
#

That seems to be the problem. I've changed it to time, but now it parses the whole timestamp which is not accepted

Invalid time specified: 2022-12-14 07:45:00+01:00 for dictionary value @ data['time']

#

*not timestamp btw, but the full date and time

mighty ledge
thorny snow
tropic hill
silent seal
#

In short: you can't.

#

Long version: if you create an MQTT device and add those entities to it (so it all has to be published via MQTT), you can. But there's not much/any gain.

chilly hemlock
#

Hey all, is there a way to display the last time an entity was in a specific state?

(I've outsourced most of the templating work to chatcgt, but he kept just giving me a template to show when an entity last changed)

inner mesa
#

no, but you can create a template sensor to keep track of that

#

or write an SQL sensor

chilly hemlock
inner mesa
#

templates are Jinja expressions. Template sensors use a template to represent their state and other components

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

chilly hemlock
#

Interesting thank you. I don't really use many templates, I didn't realise how deep this got

cedar knot
#

Hi, anyone that can help me create a sensor that shows total cost of a device? I have a sensor for total kWh used for the device, and i have a sensor that gives me my current $/kWh

marble jackal
#

You can multiply them them in a template sensor

#

{{ states('sensor.energy') | float * states ('sensor.price') | float }}

cedar knot
#

What should state_class, unit_of_measurement and device_class be set to?

marble jackal
#

state_class: measurement, unit_of_measurement: "$" (this one was obvious right) and no device_class: monetary

cedar knot
#

as my sensor.energy already have a value, the total cost of the device is incorrect, as it multiplies with the current $/kWh price. Any ideas how to fix that?

marble jackal
#

Maybe, if you can explain more clearly what the result should be then

cedar knot
#

i wanna know the electricity cost of a device

marble jackal
#

yes, per what? day, month, lifetime? That information is currently missing

cedar knot
#

Lifetime, and i wanna be able to make graphs that show the cost per hour for a day

marble jackal
#

Well, lifetime is what you have right now

#

if you want data per hour or day you need to create a utility meter out of the sensor

#

which will give you the hourly/daily/whatever consumtpion

#

and then create additional template sensors to multiply the price with those sensors

sacred sparrow
#

is there a way to make this "or" instead of "and":

{{ expand(['sensor.echo_beam_next_timer', 'sensor.echo_dot_next_timer', 'sensor.echo_show_next_timer', 'sensor.echo_spot_next_timer'])|selectattr('state', 'in', ['unavailable', 'unknown'])|list|length == 0 }}```
#

right now if one is unavailable or unknown it shows as false

marble jackal
#

Use rejectattr instead of selectattr and then use > 0 instead of == 0

sacred sparrow
#

perfect thank you 🙂

still plank
#

How do you get day of the week for a date time ?

mighty ledge
still plank
#

sensor entity is waste bin colletion day. value is like "2022-12-23". i want to be able to have a card saying bin collection is today, tomorrow, saturday, sunday monday etc.

#

easy to filter that into a datetime but i expected to find a filter for day of the week

#

i guess i could use timestamp_custom

#

{{ states('sensor.waste_this_collection') | as_datetime | as_timestamp | timestamp_custom('%A') }}

#

seems to do it

marble jackal
#

{{ (states('sensor.waste_this_collection') | as_datetime).strftime('%A') }}

#

No need to convert it to a datetime and then to a timestamp

thorny snow
#

Hello, I try to create a new sensor to copy the value of an existing one "pluie_today" the goal will be to copy its value at 11:59 pm. my code is the following
template:

  • trigger:
    • platform: time_pattern

      This will update every night

      hours: 21
      minutes: 01
      sensor:

    copie la valeur de précipitation du jour

    • name: "pluie_hier"
      state: '{{ sensor.pluie_today | float }}'

For the moment I'm not able to find my new sensor "pluie_hier" to display it with a gauge, do you know what is wrong ?
thank you for your help

marble jackal
#

state: '{{ states("sensor.pluie_today") | float }}'

#

I assume you canged the trigger to test it

#

You could also use a time trigger instead of time pattern

#
 - trigger:
      - platform: time
        at: "21:21"
thorny snow
#

It works ! thank you TheFes !

fallen tulip
#

Hi guys

#

need help with script.....

#

I want a script first testing some conditions before the run a sequence

fallen tulip
#

Yes I already read

#

but seems we can't do something like

#
  - if:
      - condition: 
          condition: and
          conditions:
            - condition: "{{ states('input_select.routeur_marche_forcee_sortie') == 'Sortie 2 (Géothermie)'  }}"
            - condition: "{{ states('binary_sensor.geothermie_fan_on') == 'on'  }}"
  - then: 
      sequence:```
#

maybe I am wrong ...

rose scroll
inner mesa
#

all good advice, but it's also missing the initial sequence:, and it would be better to use is_state() to check the state, rather than ==

marble jackal
#

expand(integration_entities('mqtt')) | selectattr('domain', 'eq', 'sensor') | selectattr('state', 'eq', 'unavailable') as a start of your template

half pendant
#

Managed this {{ expand(integration_entities('mqtt')) | selectattr('state', 'in', ['unavailable'])| map(attribute='name' ) | join('\n ') | default('none', True) }} but it gives me the (obviously) all of the sensors and i’m after the devices really, is there any way to only show devices that has an unavailible sensor attached to it?

marble jackal
#

{{ expand(integration_entities('mqtt')) | selectattr('state', 'in', ['unavailable']) | map(attribute='entity_id') | map('device_attr', 'name') | unique | select() | join('\n') | default('none', true) }}

fallen tulip
#

@rose scroll thx

remote void
#

Is there a way to add variables to a dashboard configuration? For instance I have one dashboard that sums all my temperatures in mini-graph-cards of the house. All those graphs use the same hours_to_show and points_per_hour, but whenever I want to change them, I have to change each one by itself. I'd much rather define one variable on top that affects all of those.

how would I do that in yaml?

still plank
#

only variables are input helpers, input_number for example. you can hide the entities once you've created them so they don't appear in the UI

floral shuttle
#

I have a sensor showing the timestamp of my next alarm. Id like to test if this is tomorrow. I can compare these 2```
{{states('sensor.next_alarm_timestamp')|int(default=0)|timestamp_custom('%d')}}

{{(now()+ timedelta( days = 1 )).day }}``` Is that the shortest? I do think it jumps the month/year correctly?

marble jackal
#

it will jump months/years

floral shuttle
#

just realized I have to |int the last one again:```
{{ (now() + timedelta( days = 1 )).day ==
states('sensor.next_alarm_timestamp')|int(default=0)|timestamp_custom('%d')|int}}

marble jackal
#

yep, that's true

still plank
#

{{ states.scene | expand }} outputs a list of objects like this one <template TemplateState(<state scene.hall_bright=unknown; group_name=Hall, group_type=room, name=Bright, speed=0.6031746031746031, brightness=100.0, is_dynamic=False, friendly_name=Hall Bright @ 2022-12-15T17:46:26.918385+00:00>)>

#

how can i filter the list on group_name

#

i.e iterate all scenes in a given area

still plank
#

ok i think i have managed to do it, but I expect i'm about to be shown how it could be improved a lot

#

{{ states.scene | expand | selectattr('attributes.group_name','defined') | selectattr('attributes.group_name','==','Hall') | map(attribute='entity_id') | list}}

marble jackal
#

you don't have to use expand here

#

states.scene will already have the expanded state objects

still plank
#

thanks

#

how can i select one an item in a list by index

marble jackal
#

sorry, I don't understand the question and end goal here

still plank
#

ah you can use [] to access

#

what i am working towards is having a button which can cycle through scenes in a room each press. mainly as a learning excercise.

#

without having to hard-code the list of scenes in the automation logic

#

so this gets the name of the entity with index=1

#

{{ (states.scene | selectattr('attributes.group_name','defined') | selectattr('attributes.group_name','==','Living room') | map(attribute='entity_id') | list)[1]}}

#

so now i can increment an input_number, roll it back to zero if it's past the scene count for a room, then get the name of the scene to activate based on the input_number value.

marble jackal
#

I know SmarthomeJunkie created a video tutorial on exactly this

still plank
#

thanks, i will look at that. but i think working through and figuring it out yourself is very helpful for learning.

cosmic hamlet
#

How do i get the last word of a entity value.

remote void
#

I confirmed the template works in dev-tools

still plank
still plank
remote void
#

oh no, so then there would be no solution for my problem. thats a bummer

cosmic hamlet
still plank
heavy crown
marble jackal
#

so you need to use a helper for that, like an input_select or an input_boolean. But that makes it a bit tricky to have it dynamically like you want to do

still plank
#

i appreciate that, but for my use case that's fine. i'm happy to just activate them in a cycle. the video you link to (i've not watched it yet but i will) rightly points out that this is emulating something that hue can do.

#

i understand i'll need to use a helper to track the cycle state

marble jackal
#

hours_to_show: "{{ states('input_number.temperaturedashboard_hours_to_show') }}"

marble jackal
#

what yo could do is create an automation which populates an input_select with the result of your template above

#

and then in each scene add an action to set the input_select to the option belonging to the scene

still plank
marble jackal
#

which input_helper do you want to use here?

still plank
#

an input_number

#

like this:

plain magnetBOT
#

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

still plank
#

but not with a hard coded count, instead i'd use the length of the list from above

marble jackal
#

ah okay, that could work, you don't need an if then though

still plank
#

don't I ?

marble jackal
#
action:
  - variables:
      list_lenght: 3 # user your template here
  - select: input_number.set_value
    target:
      entity_id: input_number.test_number
    data:
      value: "{{ (states('input_number.test_number') | int + 1) % list_lenght }}"
#

and you don't need to escape your quotes in your templates, just use double quotes outside the template and single quotes inside the template

still plank
#

understand your suggestion, looks good

#

i do wish there were some support for static variables in automations. it seems messy to need an input helper for this, when i wold never want to use it elsewhere.

plain magnetBOT
#

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

#

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

urban shard
#

Jesus...

marble jackal
#

stop posting it, I can see it

urban shard
#

I'm sorry... That just looks terrible in a 'file'

marble jackal
#

and you are not seeing an icon because you are mixing jinja with javascript

#
    icon: >
      {% if states("switch.nachtlampje_socket_1") == "on" -%} 
        mdi:account
      {%- else -%} 
        mdi:account
      {%- endif %}
urban shard
#

Hmm okay okay! These kind of examples I've been seeing a lot when I'm searching for an answer online

marble jackal
#

or even better, use {% if is_state("switch.nachtlampje_socket_1", "on") -%}

#

that's because a lot of cards use javascript templates, but mushroom uses jinja

urban shard
#

Oh gosh... So what would be the best solution in this case?

marble jackal
#

you can also use:

icon: "{{ 'mdi:account' if is_state('switch.nachtlampje_socket_1', 'on') else 'mid:account' }}"
#

the only solution (when using a Mushroom template card) is to use jinja

#

and I would use the last one I just posted, as it is a nice short single line template

urban shard
#

Didnt you mean

icon: "{{ 'mdi:account' if is_state('switch.nachtlampje_socket_1', 'on') else 'mid:account' }}"
marble jackal
#

yes sorry

#

I usually use single quotes inside my templates, but I copy pasted what you used

urban shard
#

No probs haha, but that also gives me no icons

marble jackal
#

this should give you mdi:account when in all cases

urban shard
#

Well I wish it did haha, but it doesnt

#

Can I post imgur pictures here?

marble jackal
#

what is your card config now?

#

you can post a link to an imgur picture

urban shard
#
type: horizontal-stack
cards:
  - type: custom:mushroom-entity-card
    entity: switch.nachtlampje_socket_1
    layout: vertical
    name: Nachtlampje R
    icon_color: light-blue
    hold_action:
      action: none
    double_tap_action:
      action: none
    icon: "{{ 'mdi:account' if is_state('switch.nachtlampje_socket_1', 'on') else 'mdi:account' }}"
marble jackal
#

does the template work in developer tools > template?

#

it works for me

#

oh wait, you are using a mushroom-entity-card

urban shard
#

yes I am

marble jackal
#

you can only use templates in a mushroom-template-card

#
type: horizontal-stack
cards:
  - type: custom:mushroom-template-card
    entity: switch.nachtlampje_socket_1
    layout: vertical
    primary: Nachtlampje R
    icon_color: light-blue
    hold_action:
      action: none
    double_tap_action:
      action: none
    icon: "{{ 'mdi:account' if is_state(entity, 'on') else 'mdi:account' }}"
urban shard
#

Ah yes that fixes it all!

#

and in Secondary Information how will i show the entity state?

marble jackal
#

I assume you want it in Dutch?

urban shard
#

Nope haha I like to have everything in english

marble jackal
#
type: horizontal-stack
cards:
  - type: custom:mushroom-template-card
    entity: switch.nachtlampje_socket_1
    layout: vertical
    primary: Nachtlampje R
    secondary: "{{ states(entity) | title }}"
    icon_color: light-blue
    hold_action:
      action: none
    double_tap_action:
      action: none
    icon: "{{ 'mdi:account' if is_state(entity, 'on') else 'mdi:account' }}"
#

Nachtlampje doesn't look very English to me 😛

urban shard
#

what does the | title do? So I can understand in the future?

marble jackal
#

It changes the first character of every word to uppercase

#

so it will show On instead of on

urban shard
#

Aaah okay okay makes sense!

#

I did take a look at your Github configuration. Looks pretty neat if I say so myself!

marble jackal
#

Thanks

urban shard
#

Can I discuss your setup a tiny bit in this channel?

marble jackal
#

if it relates to templates 😛

urban shard
glacial solar
#

I'm stuck. It's probably very simpel but how do I add 2 values into one? (100+100 = 200)? '{{ value_json.CIH + value_json.CIL }}' this does not work :p

obtuse zephyr
#

Error? Otherwise... maybe they're strings?

{{ value_json.CIH | float + value_json.CIL | float }}

glacial solar
#

nice !

#

that's it

#

thanks!

open coral
#

Hi Everyone. what would be the best way to achieve the following:
I have some RGB lights and a switch (using KNX) that has a little RGB indicator. I can send the RGB indicator a RGB value, and only accepts 0,0,0 to turn off. How can I create an automation that mirrors the colour of the light, and if the light is off, send a value of 0,0,0 to the indicator?

marble jackal
#

an if-then in your automation which sends 0,0,0 if the light is off (using a state condition) and {{ state_attr('light.your_light', 'rgb_color') | join(',') }} if it is not off

thorny snow
#

Is there any tutorial available for the basics of Jinja? The documentation starts too difficult for me, is there any way to get into that a bit easier?

thorny snow
still plank
#

given a dictionary like this: {% set translations = ({"RECYCLING":"Green bin","REFUSE": "Black bin"}) %}

#

if i have a sensor whos value is a list of one of more of RECYCLING etc, how can i transform that into a list of the translations?

mighty ledge
still plank
#

it's the attributes: they look like thispickup_types: REFUSE
area_name: SouthNorfolkUK
device_class: date
friendly_name: Next pickup

#

in this example there is just one, but it's a list

mighty ledge
#

ok, and what do you want from the list?

#

first, last, all?

still plank
#

{{ state_attr('sensor.waste_this_collection', 'pickup_types') }} shows ['RECYCLING']

mighty ledge
#

ok

#

so what do you want from that, just recycling?

#

does the list have more than one? If yes, do you want all of them?

still plank
#

i want ultimately to craft a message like, "put out the black bin, and green bin"

rose scroll
still plank
#

i was thinking of transformaing the values in the list

#

and then iterating it

#

but perhaps that's ass about face

#

and i just need to iterate the list and convert the values in the iteration

mighty ledge
#

if it's just 2 then you can simply do

still plank
#

no it could be between 1 and 4

mighty ledge
#
{{  state_attr('sensor.waste_this_collection', 'pickup_types') | join(' and ') | replace('RECYCLING', 'Green bin') | replace('REFUSE', 'Black bin') }}
#

if it's more than 2 then....

rose scroll
#

Unfortunately Jinja can't do something like [dict1[i] for i in list1]

mighty ledge
#
{% set items = state_attr('sensor.waste_this_collection', 'pickup_types') %}
{% set phrase = items[:-1] | join(', ') ~ ', and ' ~ items[-1] if items | count > 2 else items | join(' and ') %}
{{ phrase | replace('RECYCLING', 'Green bin') | replace('REFUSE', 'Black bin') | replace('xxx', 'xxx') | replace('yyy', 'yyy') }}
#

you don't really need to iterate when you have a small amount of 'translations' as you call them

#

just write the phrase and replace the strings

#

you can also just regex_replace

#

if you're dead set on generators

#

or just replace

still plank
#

Ok, thank you

mighty ledge
#

generators look like

#
{% set items = state_attr('sensor.waste_this_collection', 'pickup_types') %}
{% set items = items | map('replace', 'RECYCLING', 'Green bin') | map('replace', 'REFUSE', 'Black bin') | list %}
{{ items[:-1] | join(', ') ~ ', and ' ~ items[-1] if items | count > 2 else items | join(' and ')  }}
pine musk
#

ok, I have an MQTT rf433 binary_sensor, that should be on/off, but is showing true/false

#

how do I tell it to be on/off?

mighty ledge
#

actually, binary sensors have no translated device classes that display true/false, so you don't have a binary_sesnor, you have a sensor

pine musk
#

Thanks petro, I see that now.

mighty ledge
#

did you configure it via MQTT or is it discovered?

pine musk
#

it was giving 1/0. configured.

mighty ledge
#

show your configuration

pine musk
#
    - state_topic: "HomeAssistant/rtlsdr/event/234"
      name: Replace Outside Battery
      device_class: battery
      object_id: binary_sensor.rf433_ob001
      value_template: "{{ not(value_json.battery_ok) }}"
```
marble jackal
#

The key element is missing 😉

mighty ledge
#

use

mqtt:
  binary_sensor:
    - state_topic: "HomeAssistant/rtlsdr/event/234"
      name: Replace Outside Battery
      device_class: battery
      object_id: binary_sensor.rf433_ob001
      value_template: "{{ not(value_json.battery_ok) }}"
      payload_on: "1"
      payload_off: "0"
pine musk
#

aaaaaah

#

coool

mighty ledge
#

wait

#

you're template is modifying things

#

change your template to "{{ value_json.battery_ok }}"

pine musk
#

gewet rid of not?

mighty ledge
#

then swap your payload

marble jackal
#

The object id shouldn't contain the domain right?

mighty ledge
#

also, that

#
mqtt:
  binary_sensor:
    - state_topic: "HomeAssistant/rtlsdr/event/234"
      name: Replace Outside Battery
      device_class: battery
      object_id: rf433_ob001
      value_template: "{{ value_json.battery_ok }}"
      payload_on: "0"
      payload_off: "1"
#

that's assuming your value_template was correct

#

if you want it to be on when battery_ok is "1" for example, set payload_on to "1"

#

you can also just omit the payloads and make your template...

#
mqtt:
  binary_sensor:
    - state_topic: "HomeAssistant/rtlsdr/event/234"
      name: Replace Outside Battery
      device_class: battery
      object_id: rf433_ob001
      value_template: "{{ "OFF" if value_json.battery_ok else "ON" }}"
pine musk
#

mind blown. thats so easy

#

Invalid config for [mqtt]: [payload_on] is an invalid option for [mqtt]. Check: mqtt->mqtt->sensor->2->payload_on. (See /config/configuration.yaml, line 29).

#
mqtt:
  sensor: !include 433mhz.yaml
#

line 29/30

pine musk
#

fixed it

#

oh

#

broke it.

mighty ledge
#

yep

#

it needs to be in a separate mqtt section

#
mqtt:
  sensor: ...

  binary_sensor:
    - state_topic: "HomeAssistant/rtlsdr/event/234"
      name: Replace Outside Battery
      device_class: battery
      object_id: rf433_ob001
      value_template: "{{ "OFF" if value_json.battery_ok else "ON" }}"
pine musk
#

Thanks for the help, it's working as expected...

#

Learning something new every day

mighty ledge
#

np

zealous flame
#

I'm trying to display light % in lovelace. What am I doing wrong? In Secondary Info {{ states_attr('light.gus_light', 'brightness') }} works, but {{ states_attr('light.gus_light', 'brightness_pct') }} does not

mighty ledge
#

it needs to have that attribute

#

if it doesn't, then it can't display it

zealous flame
#

And so why wouldn't it have it? It seems you can reference brightness_pct as per some of the documentation

#

like why would it have the attribute brightness but not brightness_pct?

pine musk
#

take your brightness * 100 / 255 to get brightness %

mighty ledge
#

Developer tools -> states page will show you the attributes that exist on your light.

marble jackal
#

Make sure to turn it on first, it will not show much if it's off

vernal juniper
#

Hi all, is there a reason why the template cover doesn't have a "stopped" status? It can only be Closed or Open, but what if it is stopped in the middle? This makes it unusable because the Open status only allows to close it and the Closed status only allows to open. If it is stopped in the middle both command should be available. Is any improvement planned on this?

zealous flame
#

Hmm my blinds report % closed/open, @vernal juniper

marble jackal
#

Same here

#

And partly opened both the open and close service call work

vernal juniper
#

Can you share the yaml code please?

marble jackal
#
service: cover.open_cover
target:
  entity_id: cover.all_covers
#

Or

service: cover.close_cover
target:
  entity_id: cover.all_covers
thorny snow
#

Good morning, I created a template in which I'd like to add up all sensor values but I do not know how to convert each sensor value from 'str' to 'int': {{ states.sensor | selectattr('entity_id', 'search', 'adults') | map(attribute='state') | sum() }}

#

This is my current list: ['2', '2', '2', '0', '0', '2', '2', '1', '2', '2', '0', '0', '2', '0', '2', '0', '0', '0', '2', '2', '0', '1', '2', '2', '2', '0'] sum() of course does not work on strings.

inner mesa
#

|map('float')

thorny snow
#

And it works! Thanks a million!

tacit glen
#

Hello. Following the example on the tado integration page, I would like to make an automation that changes my tado temp sensor's value depending on an extermal temp sensor. The action part, which I need to use the yaml editor for instead of UI editor, gives me this error: Message malformed: template value should be a string for dictionary value @ data['action'][0]['data']

Here the snippet of code:

  - service: tado.set_climate_temperature_offset
    target:
      entity_id: climate.wohnzimmer
    data:
      offset: >
        {% set tado_temp = states('sensor.thermostat_wohnzimmer_hk_current_temperature')|float(20) %}
        {% set room_temp = states('sensor.wohnzimmer_temperature')|float(20) %
        {% set current_offset = state_attr('climate.wohnzimmer', 'offset_celsius') %}
        {{ (-(tado_temp - room_temp) + current_offset)|round(1) }}```

I read that a while back the UI yaml editor was the problem. Not sure if this is fixed, is my code faulty or is it a bug?
marble jackal
#

You are missing a }

#

In the line where you set room_temp

opaque creek
#

Heya! So I got this code:
https://paste.debian.net/1264366/
But I would like to change the values inside that code via input number. Is that possible?
Can I somehow replace the "3" after "numberOfSequentialHours" to
"states('input_number.elprisverktyg_antal_timmar')" so I can change it on the go not needing to change the code if I want to try another set of hours?

wary yew
#

I copied some templates from a community thread but I think I'm missing something when I split the config into template.yaml. Can someone help me fix it?

This is my entire current template.yaml: http://pastie.org/p/5JO04FrwXZHryAcjQheahP

And this is the errors I'm getting in the log, which seems clearly pointing at the "platform" lines. Just not sure how to fix it.

Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/template.yaml, line 0). Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/template.yaml, line 11). Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/template.yaml, line 19). Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/template.yaml, line 28).

void idol
#

Hi there

#

I have 2 REST sensors that get data from an api. Sensor 1 is setup to update every 30 mins. Is it possible to setup such that sensor 2 updates whenever sensor 1 updates?

#

Like, is it possible to link sensor 2 to sensor 1?

marble jackal
marble jackal
#

The old format is belonging to the sensor integration and can't be placed in template.yaml

#

The top 4 items should be placed under sensor:

wary yew
#

Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/template.yaml", line 1, column 1
expected <block end>, but found '-'
in "/config/template.yaml", line 40, column 1

#

I added:

`sensor:

  • platform: template
    sensors:

    wiser_boiler:
    value_template: >-
    {%- if states('sensor.wiser_hot_water') == "On" or states('sensor.wiser_heating') == "On" -%}
    {{ "On" }}
    {%- else -%}
    {{ "Off" }}
    {% endif %}`

#

ah or do you mean under sensor inside configuration.yaml instead of inside template.yaml?

opaque creek
#

I typed 3 in the input helper number, but the state is actually 3.0 could that mess things in the code maybe?

marble jackal
#

You need to convert it to int

#

I indeed forgot to add that
{%- set numberOfSequentialHours = states('input_number.elprisverktyg_antal_timmar') | int -%}

marble jackal
#

You can create a sensor.yaml

wary yew
marble jackal
#

You can only update the one with platform: template

#

The others only belong under sensor

wary yew
#

how can I update at least that one? How should it look with the new structure?

marble jackal
#

You have several examples in that file you posted

wary yew
#

yeah but can't figure it out. Nvm, I will look into that later.

For now, even when moving them into sensor.yaml, it's still giving me the error.

#

Error loading /config/configuration.yaml: while parsing a block collection in "/config/sensor.yaml", line 1, column 1

#

I think I fixed it. It was a couple indentations that I messed up

marble jackal
#

That should work as a new format template sensor

#

Not sure why you are not creating a binary sensor here though

wary yew
#

no particular reason. I'm just not able to understand the code yet. I'm just copy pasting what someone else did. That's the struggle. xD

#

thank you very much

silent seal
marble jackal
#

Yep, focused on old to new format, didn't really look closely at the template itself

cobalt echo
#

Help with using input_number ‘helper’ in a template condition. Basic problem statement: I defined a input_number.home_monitor_state that can range from 0 to 3 (seems to want to store as float but I really only need integer) and I want to test that state as a condition in an automation before taking some action. I have the latest HA OS, UI, COre, etc and have tried all kinds of variations based on what I read in these help sections but seem to just doing something fundamentally wrong. Keep getting ‘condition did not pass’ when I ‘test’ the template. Here is the snippet in basic form:

http://pastie.org/p/1WX590hQKO8hTRuXJqLJpD
Using dev tools to look at input_number.home_monitor_state presently shows it as 0.0

inner mesa
#

Yeah, that syntax is weird

#

value_template: "{{states('input_number.home_monitor_state') | float < 3.0 }}"

#

or, you can just use a numeric_state condition instead of a template

cobalt echo
#

Thanks - tried your suggestion in the value template and got the same result.

inner mesa
#

?

#

yours was completely broken

cobalt echo
#

Yes I don’t know how to fix it

inner mesa
#

ok

#

I can't imagine that yours even passed a config check

cobalt echo
#

The numeric_state condition is what I tried first - the problems I ran into with that is it wants an ‘attribute’ and the attribute did not let me get to the ‘value’ of the input_number. I’ll redo the example that way and post that.

inner mesa
#

test whatever you have in devtools -> Templates and debug from there, or just use a numeric_state condition

#

it does not require an attribute

#

just don't provide an attribute

cobalt echo
#

Oops

inner mesa
#

Using dev tools to look at input_number.home_monitor_state presently shows it as 0.0

#

above: 0

#

it is correct

#

90% of getting the logic right is just knowing what you want

cobalt echo
#

Agreed.

input number.home_monitor state
0.0
© Home Monitor State
initial: null
editable: true
min: 0
max: 3
step: 1
mode: box
friendly_name: Home Monitor State

inner mesa
#

Ok?

#

Your logic clearly excludes 0

#

What, exactly, do you want from that condition?

cobalt echo
#

Omg, that’s when u cannot see the forest thru the trees. I had tried to simplify the testing when I was using the value template to just test for less than 3.0 - I will go set that state to be 1 or 2 and see what happens. Duh.

#

Thank-you!

#

That worked.

devout plume
#

What is the template notation to retrieve the "last changed by" information?
e.g. when a light is turned off by the service "light.toggle", under the entity's ( light.schakelaar_toilet_beneden_right ) history tab - logbook header I can see: "turned off triggered by service light.toggle"
I want to differentiate between the button being pushed (no "triggered by" information) and a service call (by an automation).

My use case is a toilet door sensor and light. Door is opened, toggles light.
Currently, when a luser manually turns off the light and then opens the door, the light turns on.
I've already added in a template checking whether it wasn't turned off in the last twenty seconds, but that does not support back to back toilet visits if there's a queue.

wheat junco
devout plume
#

That only gives me the last change timestamp, not the source of the last change

wheat junco
#

My apologizes. Maybe someone else can chime in on that.

devout plume
#

Thanks for the attempt 🙂

inner mesa
#

That is in the context. There are lots of threads on this in the forum

#

And described in the docs for the state object

devout plume
#

Thanks RobC, looks like I should be able to figure it out based on this.

fossil venture
#

Ah December, here to test all my templates again```

  • name: "Next Bill Estimate" # monthly bill
    icon: "mdi:currency-usd"
    unit_of_measurement: "$"
    state: >
    {% if now().day < 18 %}
    {% set remaining_days = 18 - now().day %}
    {% else %}
    {% set remaining_days = ( now().replace(month=now().month + 1, day=18) - timedelta(days=now().day) ).day %}
    {% endif %}
    {{ (states('sensor.cumulative_energy_cost')|float(0) + states('sensor.average_daily_cost')|float(0) * remaining_days)|round(2, default = none) }}
#

This should do it, unless someone has a better way? ```
{% set next_month = now().month + 1 if now().month + 1 < 13 else 1 %}
{% set remaining_days = ( now().replace(month=next_month, day=18) - timedelta(days=now().day) ).day %}

fallow gulch
#

I'm having a weird issue with a template temperature sensor not keeping statistics

#

It's just taking the temperature from an existing sensor with 2 decimal places and rounding it to 1, and I have two other template sensors doing exactly the same thing and they're both keeping statistics

#

from template.yaml

plain magnetBOT
#

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

fallow gulch
#

nursery temperature has no statistics, but kitchen and bedroom do

fossil venture
#

Add this to them state_class: measurement

fallow gulch
#

that's fixed it, thanks!

white totem
#

Hi. I use a power meter to measure the power of our heat pump. The heat pump is used both for heating and hot water. I want to split out the energy use of those two.
First, I use a template to split the measured power.

state: >
   {% if is_state('sensor.prio_43086', 'HEAT') %}
     {% set power = states('sensor.power_heatpump_total') %}
   {% else %}
     {% set power = 0 %}
   {% endif %}
   {{ power }}
device_class: power

Then I user a Riemann helper to calculate the split energy from the split power.
The numbers don't add up after that. It seems the Riemann helper sees the period with value 0 as one point, and adds it to the sum total. Since power can go to 1kW instantly, that messes up the values considerably.
Should I try to fix it using the template? (I can give more information if you want, but I wanted to keep the question reasonably short).

onyx juniper
#

{% if is_state('binary_sensor.turkontakt', 'on') %} Door is open {% else %} Door is closed {% endif %} }}

Hi. I'd like to put this template as the name on a custom button card. The template works in the developer tools as expected. But how do I add this as the name of the custom button card (or any other card for that matter)?

marble jackal
#

The card has to support Jinja templates, not many do. I'm not sure about the custom button card, I don't use the myself

onyx juniper
marble jackal
onyx juniper
foggy monolith
#

Hi. Im trying to change a nan value to 0 with a template sensor. But im getting syntax error. Whats wrong with that?

#
  • name: "Leistung Solar"
    unique_id: "leistung_solar"
    unit_of_measurement: "W"
    state: >
    {% if is_state('sensor.inverter_watts', 'nan') %}
    {% set output = 0 %}
    {% else %}
    {% set output = (states('sensor.inverter_watts')|float)|round(3) %}
    {% endif %}
    {% output %}
white totem
#

Does it work if you replace
{% output %}
with
{{output}}
?

foggy monolith
#

Yes man. That was the error! Thanks 🙂

grim flicker
#

i have a template sensor like this. the outcome is 44.0 i had hoped with | round (0) to get 44. is there a way to actually round it to a round number. i tried | int but this also gives 44.0 in home assistant is there a way to get 44?

{% set setpoint = states('input_number.otgw_aanvoer_setpoint_y2')|float - ((states('sensor.huidige_temp_vandaag')|float - states('input_number.otgw_buitentemperatuur_x1')|float) * states('sensor.otgw_p_factor')|float)|round(0) %}
  {{ setpoint }}
#

never mind i missed () at the beginning and the end to specify what needs to be rounded. my bad

silk oak
#

I want to compare a state of a variable sensor with a value in a variable. This isn't working:
"state: - operator: "template" value: | [[[ return variables.ulm_card_vertical_button_sensor.state == variables.ulm_card_vertical_button_state; ]]]"

What am I doing wrong? In the variable ulm_card_vertical_button_sensor is a sensor defined. When I enter a value instead of a sensor and I use the variable without .state it is working.

inner mesa
#

That is Javascript for a custom card and belongs in #frontend-archived, but why would you add ".state" to the first part and not the second? Variables don't have a ".state"

#

this is confusing:

state of a variable sensor

#

that's not a thing

#

if you're trying to retrieve the state of an entity, there are many examples in the card docs for how to do that

verbal isle
#

Given the attribute state in the link. Is it any good at templating that can help me doing the following:

https://pastecode.io/s/yn782zby

  1. Get the full object that has the value=1.98
  2. Get the average of all value fields
inner mesa
#

looks like it's just {{ data|map(attribute='value')|average }} to get the average

#

and to get a single object with a specific value: {{ data|selectattr('value', 'eq', 2)|list|first }}

marble jackal
inner mesa
#

I still have no idea what that means

verbal isle
#

where data is the sensor attribute (the whole list of raw data?)

inner mesa
#

yes

#

I can't test it with all the datetime() stuff in there

verbal isle
#

The average one worked. Great! - the other one I get "UndefinedError: No first item, sequence was empty."

inner mesa
#

then there wasn't an object with that value

verbal isle
#

yeah stupid me. I need to be more specific on the decimals. Thank you Learned something new

inner mesa
#

{{ data|selectattr('value', 'eq', 4)|list }} if you just want the raw list

verbal isle
#

Oh yeah another thing. Is it possible via the template to access the "energy" values, like how much power cost is this far in the month?

inner mesa
#

there's no "energy" in there

#

what exactly are you looking for?

verbal isle
#

The day and month cost from the energy tab in native home assistant from sources

inner mesa
#

Then, no

#

I thought it was related to the earlier question 😦

verbal isle
#

no sorry

umbral ridge
#

Hi, I'm attempting to integrate my withings scale. I've been through the documentation for this and i was able to connect the scale from the app and get it integrated
I used the template provided in the doc to convert KG to LBS, there are no errors in the config.yaml and i have resstarted HA, but I'm not seeing any effects of using the template...I imagined that i would see additional entities that show the sensors in lbs ..or the values in the entities would display lbs instead of kg...what am i supposed to see by using the template?

inner mesa
#

what template did you use?

verbal isle
#

Will it slow down using templates directly in the frontend vs making a template sensor?

inner mesa
#

presumably you modified it for the appropriate entities?

umbral ridge
#

I replaced all the values with my profile name

#

yes

inner mesa
#

and checked your config?

umbral ridge
#

yes, no issues

inner mesa
#

what entities did you look for and can't find?

umbral ridge
#

In the withings integration, I have 34 entities that were all populated upon adding the integration, they all still display as KG and the values are still showing in KG...essentially nothing has changed for me after adding the template

inner mesa
#

what you added creates new entities

#

you can't change the existing ones

umbral ridge
#

yeah, that hasn't happened

inner mesa
#

that's why I asked what you were looking for and couldn't find, and you started taliking about the existing entities

#

those won't change

umbral ridge
#

unless they are being filtered, perhaps?

inner mesa
#

and you won't see them in the integration page

#

you've created completely new entities

#

devtools -> States

umbral ridge
#

AH! they were being filtered

#

i see them now

inner mesa
#

they are completely unrelated to the integration

#

other than using the entities from that integration, of course

umbral ridge
#

got it, ok happy with that, you gave me a clue , that helped, thank you!

hidden crag
#

What are you guys using for icon color changing based on a value?

fading patio
#

NFL Team Score Automation

young jacinth
#

how would i test if at least two states are true?

{% set wz_1 = is_state('binary_sensor.wz_motion_1', 'on') %}
{% set wz_2 = is_state('binary_sensor.wz_motion_2', 'on') %}
{% set ku = is_state('binary_sensor.ku_motion', 'on') %}

{% set list = [wz_1,wz_2,ku] %}
inner mesa
#

?

#

what do you mean?

young jacinth
#

the template should result true if at least two items off the list are true

inner mesa
#

got it

#

{{ [true, true, false]|select() | list | count >= 2 }}

young jacinth
#

thanks alot

fading patio
#

Having an issue with the attribute not properly working in my template. Trying to check whether the team_score attribute has changed by 6 or more. It is erroring saying Error: In 'template' condition: UndefinedError: 'homeassistant.core.State object' has no attribute 'attribute'.

  trigger:
  - platform: state
    entity_id:
    - sensor.philadelphia_eagles
    attribute: team_score
  condition:
  - condition: state
    entity_id: sensor.philadelphia_eagles
    state: IN
  - condition: template
    value_template: '{{ trigger.to_state.attribute.team_score|int(0) - trigger.from_state.attribute.team_score|int(0)
      >= 6 }}'

My thread is here: https://discord.com/channels/330944238910963714/1054149570298384384

inner mesa
#

it's "attributes"

fading patio
#

ahh so just add the "s"?
trigger.to_state.attributes.team_score

inner mesa
#

yes

fading patio
#

follow up how would i say in the notification how many points were scored...it says malformed.

service: notify.mobile_app_iphone_6s
data:
  message: Buccaneers Scored {% trigger.to_state.attributes.team_score|int(0) - trigger.from_state.attributes.team_score|int(0) %}
  title: NFL
#

that is in an automation

#

"Message malformed: template value should be a string for dictionary value @ data['action'][0]['data']"

silent seal
#

Your message isn't printing. {% in Jinja evaluates, you need {{ to output.