#templates-archived

1 messages Β· Page 168 of 1

arctic sorrel
#

Well, no

#

That'd be on when the sensor is off

golden widget
#

ok so value template is for the on state ?

#

ok cool

#

so i just do {{ is_state('binary_sensor.geyserwiseapielement', 'on) }}

marble jackal
#

What do you expect this switch to do when you toggle it?

golden widget
#

@marble jackal thats different. thats the turn_on and turn_off sections of the template switch. im just refffering to the state part of it

#

i think

marble jackal
#

I know that, but if the binary sensor represents the state of your switch, turning your switch off should cause the binary sensor to turn off as well

golden widget
#

well this is what i have

#

switch:

#
  • platform: template
    switches:
    geyserelementswitch1:
    value_template: "{{ is_state('binary_sensor.geyserwiseapielement', 'on') }}"
    turn_on:
    service: rest_command.geyserelementturnoff
    data: {}
    turn_off:
    service: rest_command.geyserelementturnoff
    data: {}
silent barnBOT
#

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

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

golden widget
#

sorry

#
  - platform: template
    switches:
      geyserelementswitch1:
        value_template: "{{ is_state('binary_sensor.geyserwiseapielement', 'on') }}"
        turn_on:
          service: rest_command.geyserelementturnoff
          data: {}
        turn_off:
          service: rest_command.geyserelementturnoff
          data: {}
inner mesa
#

you're turning it off in both?

golden widget
#

arg sorry will fix off to on in rest service

marble jackal
#

If that rest command causes the binary sensor to turn off, that will be fine

golden widget
#

the rest commands work if i go into developer tools and services and run those manually.

#

the binary sensor does update yes

marble jackal
#

πŸ‘πŸΌ

golden widget
#

looks like no errors thanks, just the thing is when i turn the switch on, it immediately goes off because the rest takes a min to update and then the binary sensor probably checks it via the api a bit later as well

#

binary_sensor.geyserwiseapielement is a rest binary sensor

#

any way to get around that

stuck jewel
#

Can you recycle friendly names?
I have a motion sensor and a smoke
Detector in the lounge area can I both name lounge ? Or is that bad form ?

inner mesa
#

they're completely unrelated and can be whatever you want

#

entity_id has to be unique, and HA will do what it can to ensure that if you don't (such as adding _2, etc.)

stuck jewel
marble jackal
#

It's a bit more complex though, as the area is not an attribute of the entity, so you need a for loop and a namespace to go through all entities to get a list of the areas

#
{% set group = 'binary_sensor.alarm_motion_sensors_away' %}
{% set ns = namespace(area = []) %}
{% for entity in expand(group) | selectattr('state','eq','on') | map(attribute='entity_id') %}
  {% set ns.area = ns.area + [ area_name(entity) ] %}
{% endfor %}
{% set areas = ns.area | unique | list %}
There a are entities on in: {{ areas[:-1] | join(', ') ~ ' and ' ~ areas[-1] if areas | count > 0 else areas | join }}
silent barnBOT
calm drift
#

what did I do wrong! my last post has been knobbled ...

shrewd grove
#

Hi, I am new to home assistant programming. Can someone help me with how to use variables in for loops? I want to get the gas station with the lowest price from a group of gas stations:

{%set lowestprice =100 %} {%set cheapest= states.group.tankstellen.attributes.entity_id[0]%} {%for entity_id in states.group.tankstellen.attributes.entity_id %} {%if((states(entity_id)|float)<lowestprice)%} {%set lowestprice = states(entity_id)%} {%set cheapest = entity_id%} {{cheapest}} {{states(cheapest)}} {%endif%} {%endfor%} {{cheapest}} {{states(cheapest)}}

The problem is that the update of cheapest or lowestprice in the for loop doesn't survive the iterations. The final output corresponds to the values that I defined in the first two lines.

silent barnBOT
#

@calm drift [Rule #6](#rules message): Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

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

For sharing code or logs use https://dpaste.org/ (pick YAML for the language) or https://www.codepile.net/ (pick YAML for the language).

spare saffron
#

Please help.
Trying to get a list of "installed_versions" of all integrations. Can't figure out the template for this.
Tried {{ states.update | selectattr('installed_version') | list }}
and it says the attribute installed_version does not exist. But I can see it in the state object.
What am I doing wrong?
thanks

marble jackal
marble jackal
#
{% set ns = namespace(lowestprice=0, cheapest='') %}
{% for item in expand('group.tankstellen') | selectattr('state', 'is_number') %}
  {% if loop.first or item.state | float < ns.lowestprice %}
    {% set ns.lowestprice = item.state | float %}
    {% set ns.cheapest = item.entity_id %}
  {% endif %}
{% endfor %}
{{ ns.cheapest }} {{ ns.lowestprice }}
thorny snow
#

Hey, quick question, i have a aqara door sensor, it has two states, either its open or closed, but im pretty sure that in the box where i have to enter the state, if i enter open it wouldn't work, so i wanted to ask if "open" or "on" should be used there ?

marble jackal
#

check devtools > states, but the state for a binary sensor is on or off

#

the gui translates it based on the device class

thorny snow
#

ok its off now while closed πŸ™‚ so that means on would be open πŸ™‚ thanks πŸ™‚

marble jackal
calm drift
#

@marble jackal sorry that should read assensor:

  • platform: template
    sensors:
    my_alarm:
    entity_id: sensor.nnudphone_next_alarm
    friendly_name: 'MyAlarm'
    value_template: >
    {% if state_attr("sensor.nnudphone_next_alarm","Local Time") != None -%}
    {% set my_alarm = state_attr("sensor.nnudphone_next_alarm","Local Time").split("GMT") %}
    {{ my_alarm[0] }}
    {%- endif %}
silent barnBOT
#

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. Here's an example

Don't forget you can edit your post rather than repeatedly posting the same thing.

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

marble jackal
#

Please format your code as code

calm drift
#
sensor:
  - platform: template
    sensors:
    my_alarm:
     entity_id: sensor.nnudphone_next_alarm
     friendly_name: 'MyAlarm'
       value_template: >
         {% if state_attr("sensor.nnudphone_next_alarm","Local Time") != None -%} 
         {% set my_alarm = state_attr("sensor.nnudphone_next_alarm","Local Time").split("GMT")  %}
         {{ my_alarm[0] }}
         {%- endif %}
marble jackal
#

and please edit your post the next time

#

instead of posting a new one

#

your indentation is completely off

#

well, my_alarm: and everything under that, should be indented

calm drift
marble jackal
#

indentation is very important in yaml

#
sensor:
  - platform: template
    sensors:
      my_alarm:
        friendly_name: 'MyAlarm'
        value_template: >
          {{ state_attr("sensor.pixel_5_next_alarm","Local Time").split("GMT")[0] }}
        availability_template: >
          {{ not state_attr("sensor.pixel_5_next_alarm","Local Time") is none }}
spare saffron
marble jackal
#

not sure what you are trying to achieve here though, this template will give you the entire state objects of all your update entities

calm drift
marble jackal
shrewd grove
inner mesa
#

Links in the channel topic

silent barnBOT
#
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 https://www.codepile.net/ or https://paste.debian.net/ to share code or logs

thorny snow
#

Hey all πŸ™‚ is it somehow possible to create automation that shows the time left of a dumb dishwasher ?
im kinda getting the idea to get the thing to notify me when its done ( will try that later today ) but it would be perfect if i could make a card that states time left πŸ™‚

inner mesa
#

Create a timer entity based on how long the cycle takes? No template required

thorny snow
#

but isn't it like sometimes a bit longer and sometimes a bit faster ?

inner mesa
#

It's your device 🀷

#

How do you know what the counter should show?

thorny snow
#

its connected through smart socket, maybe it would use different w in different steps or so ? πŸ™‚ that was kinda my idea of the plan ( forgot to mention it πŸ˜„ )

#

and like if i use different program the time would also be different...

inner mesa
#

You need to figure all that out before you try to write code for it

thorny snow
#

thats why im asking here, hopefully someone has something similar done already πŸ™‚ or is it again the false # for this ? πŸ˜„

inner mesa
#

I suggest a forum post

marble jackal
#

My dishwasher shows the time the program takes when I select it. I don't think dishwashers do some calculations like laundry washing machines usually do, but yours might proof me wrong there

inner mesa
#

He said it's dumb

thorny snow
#

i was thinking like it could take a bit longer when the water from line is colder than usual , or the waste water is a bit less because its stuck in some bowls what have been turner around and so on

mighty ledge
#

My dryer was easy

#

the washer was a PITA

thorny snow
#

its dumb in a way it's not home connect or so πŸ™‚

mighty ledge
#

watch the power on the circuit

#

that's waht I do

#

however, if your washer has cycles, it's a PITA to determine the end within a reasonable time frame

mighty ledge
#

you basically have to know the number of cycles (mine has 5) in order to get the EXACT end time. Otherwise you can just put a delay off and get your notification 4 minutes late

thorny snow
#

so just finished that πŸ˜„

#

the strange thing it, its not the same each time...

mighty ledge
#

yep

#

it's based on the water draining

thorny snow
#

it should be like 2 different programs at most here πŸ™‚

mighty ledge
#

hence why washers are a PITA

thorny snow
#

PITA ? πŸ™‚

mighty ledge
#

PAIN IN THE ASS

thorny snow
#

πŸ˜„

mighty ledge
#

this is mine

thorny snow
#

so for the job done notification, there is a really small bump, then there is like 10min of nothing and a bit bigger bump and its done, so i could use that for finish notification ?

mighty ledge
#

that's 2 washes

thorny snow
#

well Yours worse ;D

#

how were you able to post image here ?...

mighty ledge
#

i have unlimited power

thorny snow
#

what do you mean with that ?

mighty ledge
#

I'm a mod

#

I can do anything

thorny snow
#

oh ok, got it πŸ™‚

mighty ledge
#

anyways, make a template binary_sensor that is on or off based on the power level

#

you might need 2

#

it depends on how many 'blips' you have when it's not running

thorny snow
#

sorry, You've lost me...

#

what you've meant with blips here ?

mighty ledge
#

anomalies, like when your the power jumps but the washing machine is off

thorny snow
#

like the one at 22:51 ?

mighty ledge
#

yep

thorny snow
#

just rechecked with the queen of the household, from what i've understood so far, we are using only two modes of the dishwasher, so that would makes things a bit easier πŸ™‚

mighty ledge
#

yeah, but do those modes have 'sizes' to them?

thorny snow
#

sizes ?

mighty ledge
#

like, my washer has a bunch of modes, but you set the water level

#

or the clothing amount

thorny snow
#

nope, just simple 70c for her and 70c plus all three extra options for me

#

dishwasher here πŸ™‚

#

so no clothes, or we have been doing it all the time wrong πŸ˜„

mighty ledge
#

well run each one, see how they differ, then come up with an automation that senses them

#

or

#

just make a template sensor that's on/off depending on the power. Then make an automation that notifies you if the sensor is off for x minutes

#

but keep in mind, that method will not notify you exactly when it's finished.

#

trying to get the exact finish is going to require you to play around a lot and you'll have to test this with trial and error.

#

because there's no "1 solution fits all" for this

thorny snow
#

each of the small bumps are 10w - 11w and then there is a big pause, then comes 47,6w ( and a bunch of other w's ) and after like 3 min its 0w. thats the end sequence thats been almost the same for all cases i have

#

pause is like 16 - 20 min

thorny snow
#

in the pause time its using 3,9 - 5w

#

so thats all the info im having on the end sequence πŸ™‚

mighty ledge
#

or use the power as a trigger

thorny snow
mighty ledge
#

You're going to have to get creative with your automations

#

I'm not sure how else to explain this to you

thorny snow
#

im starting to think how could i get this to work but its like so messed up πŸ˜„

mighty ledge
#

this is something that you will need to do as none of us have your hardware

thorny snow
#

so trigger, power over 1500w, then wait for trigger 3,9w - 5w for more than 16min ( and just keep waiting until this happens ), then wait for trigger 0w and send notification

#

makes sense ? πŸ˜„

shrewd grove
#

Short question: I cannot use templates in lovelace cards? I would like to dynamically change the name of a sensor card

thorny snow
#

oh and thanks of course @mighty ledge but the estimated time left is a huge headache to make, so im just leaving it for now ...

marble jackal
hollow plaza
#

Hi There,
I have a light switch (no dimmer) and bought a smart bulb with temp and dimm. I am using mushroom light card and I set the entity to the Light bulb so I can have the temp and dimm control and a script on Tap which toggles the switch. The issue is I cannot control the icon color.
Do you pepps have any ideas about this? I'm new to HA.

royal vortex
#

I'm trying to figure out the last time an attribute of an entity was changed, so I can utilize it as a condition for an automation. Do attributes have the last_changed property accessible somehow? I referenced the awesome post from petro (https://community.home-assistant.io/t/last-updated-state-and-last-changed-in-lovelave/101701) and tried this: {{ as_timestamp(states.climate.grill_climate.attributes.current_temperature.last_changed) | timestamp_local }} (with and without the timestamp wrappers) and didn't get the expected returns (either got nothing, or None)

#

Do I have to wrap that attribute as it's own template sensor to achieve what I'm trying to do?

inner mesa
#

last_changed is a property on the state object and applies to the whole object - there isn't a separate timestamp for each part of it

#

if you want to track a specific attribute, make a template sensor for that attribute and then track the last_changed time for that new entity

opaque creek
#

Hey, I use this code in a markdown card to track train departures.
And this one is for when the train is on time:

{{ (state_attr('sensor.kode_to_goteborg_c', 'planned_time')| as_datetime | as_local).strftime('%H:%M') }}

But I also want the attribute IF the train happen to be late, it will be attribute "estimated_time" and I just go:

{{ state_attr('sensor.kode_to_goteborg_c', 'estimated_time') }}

Its fine, it will show me "None" if its on time.. but only when its not on time there will be a time here. And then I would like that time to be shown with strftime('%H:%M').
But if I go:

{{ (state_attr('sensor.kode_to_goteborg_c', 'estimated_time')| as_datetime | as_local).strftime('%H:%M') }}

It gives me an error that it has to be a string or number, but since its on time there is no number there. Is there a workaround to not give me this error when the train is on time? πŸ˜›

mighty ledge
opaque creek
mighty ledge
#

right, but we need to know the format when it's going to be late.

opaque creek
#

Ah! Its like the planned time so its like this: 2022-07-15T10:52:00+00:00

mighty ledge
#
{% set etime = state_attr('sensor.kode_to_goteborg_c', 'estimated_time') %}
{% if etime is not none %}
  {{ (etime | as_datetime | as_local).strftime('%H:%M') }}
{% else %}
  On Time
{% endif %}
opaque creek
marble jackal
#

Yes, you can use this in a markdown card

opaque creek
silent barnBOT
autumn matrix
#

Thank you @silent barn

#

I'm trying to use "states" in an is_illuminance (IF statement) but it does not seem to work. I get the error: Message malformed: expected float for dictionary value @ data['below']
If I change int to float I get the same error. I dont see a data part else I could have used data_template. Any idea's?

inner mesa
#

It probably doesn't support a template. Use a numeric_state condition with a value_template instead

marble jackal
#

or a template condition

autumn matrix
#

hmmm with that I get Message malformed: expected float for dictionary value @ data['action'][0]['choose'][0]['conditions'][0]['below']

#
          - condition: numeric_state
            entity_id: binary_sensor.presence_21
            below: "{{ states('input_number.luxbesturings_zolder_grenswaarde') | int }}"```
marble jackal
#

You can not apply a template directly in the below field

autumn matrix
#

that explains why it doesnt work either with the IF statement

marble jackal
#

easiest would be to use a template condition

#

btw that condition above doesn't make sense, a binary sensor is on or off. It doesn't have a numeric state

#
if:
  - condition: template
    value_template: "{{ states('sensor.zolderlux') | float < states('input_number.luxbesturings_zolder_grenswaarde') | int }}"
then:
autumn matrix
#

you are right.. selected the wrong entity

#

let me check the value_template because thats new to me

#

no errors any longer @marble jackal

#

This seems to work! awesome. Thx!

deft timber
#
if:
  - "{{ states('sensor.zolderlux') | float < states('input_number.luxbesturings_zolder_grenswaarde') | int }}"
then:
#

should work too

#

and I don't know if the following will works (it works with conditions:):

if: "{{ states('sensor.zolderlux') | float < states('input_number.luxbesturings_zolder_grenswaarde') | int }}"
then:
marble jackal
whole marsh
#

is there a way to limit a "for" by range in a template? I'm using this template:

{%- for x in state_attr('sensor.sonarr_upcoming_media', 'data') %}
{%- if x.title is defined %}
{{ x.poster }}
{{ x.title }} - {{ x.episode }} ({{ x.number }})
{%- endif %}
{%- endfor  %}

And want to limit the results to the first say 5 entries, not the whole gamut. There's another sensor I have that has the value I'd like to use (sensor.sonarr_upcoming).

inner mesa
#

The easiest way would be to collect them all in a list and just output the first 5

#

You'd need to use a namespace for that

marble jackal
#

Wouldn't this work

{%- for x in state_attr('sensor.sonarr_upcoming_media', 'data') %}
{%- if x.title is defined  and loop.index <= 5 %}
{{ x.poster }}
{{ x.title }} - {{ x.episode }} ({{ x.number }})
{%- endif %}
{%- endfor  %}
#

Not sure if the index starts at 0 or 1

silent seal
#

You could always slice the first 5 off the array to start with πŸ˜›

{%- for x in (state_attr('sensor.sonarr_upcoming_media', 'data') | slice(5)) %}
inner mesa
#

Now that's some thinkin'

whole marsh
#

loop works, slice does not. is there a way to make the 5 based on the value from sensor.sonarr_upcoming?

silent seal
#

What does that sensor produce?

whole marsh
#

the state is an integer

silent seal
#

Because if it loops, it should be sliceable

#

I did add brackets around the slicing of the state_attr, and those are important

autumn matrix
#

Am I doing something wrong or does delay: '{{ states("input_number.cameraactivatie_focus") | int }}' not work. Tracing looks like this (see below) and done stays at false

Executed: 15 juli 2022 18:12:09
Result:
delay: 120
done: false
whole marsh
#

thanks for the help, i spent more time than i care to admit bashing my head to get that to work

autumn matrix
inner mesa
#

Perhaps the automation triggered again?

autumn matrix
#

yes that was it.. and it was set to restart

#

so restart will kill everything that is still running?

inner mesa
#

Yes

#

There are other options for the mode if you want something else

autumn matrix
#

yeah, perhaps it should be a message in the trace? script interrupted by restart of automation

inner mesa
#

I think it says that it triggered again

autumn matrix
#

doesn't show up here... perhaps because the automation triggers a script

#

and i'm doing a trace on the script

inner mesa
#

You keep saying 'script', and you can call a script that runs in parallel and won't be killed

autumn matrix
#

my automation indeed executes a script

#

and my automation was set to restart

#

and on restart the script that was running on the background stays in limbo

inner mesa
#

Just pointing out that you have options

#

It's probably being killed

autumn matrix
#

yeah i appreciate it. I was suggesting an imrpovement so that you can see when a script is killed πŸ™‚

inner mesa
#

Hence the done: false

#

You can suggest that in the forum

autumn matrix
#

ill do that πŸ™‚

marble jackal
#
[
  [
    0
  ],
  [
    1
  ],
  [
    2
  ]
]
ember meteor
#

hoping to get some direction/assistance. Getting the following error on my sonos_say script. I looked around online and didn't find any specifics. Where can I share the YAML code so a second pair of eyes can help me?

Sonos TTS script: Error rendering Sonos TTS script delay template: TypeError: '>' not supported between instances of 'NoneType' and 'int'

https://dpaste.org/MQ9BH

#

online YAML checker shows no errors

marble jackal
#

You are first waiting until the player is not playing

#

At that point there will not be an attribute media duration

#

So you will be checking none > 0 which is not allowed

ember meteor
#

OK. looking again πŸ™‚

small rampart
#

Hi all. I previously had a template that looked at the forecast object in weather.dark_sky and summed the precipitation. I am now getting the error "UndefinedError: 'dict object' has no attribute 'precipitation'. Here is the orig. template used. Any ideas?

{{state_attr('weather.dark_sky','forecast') |map(attribute='precipitation')|map('float')|sum | round(2)}}

marble jackal
#

Is your dark sky sensor still working?

thick cipher
#

hi guys, i use this switch template on my yaml file, but i would like use it on button card, it is possiible? i dont want use this config anymore on yaml file.

silent barnBOT
small rampart
silent barnBOT
marble jackal
small rampart
marble jackal
silent vector
#

How would something like this be accomplished?

{% set test = 'sensor.weather_temperature_over_50' %}
{{ (now() - states.test.last_updated).minutes > 5 }}
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'
#

Yeah that didn't work.

{{ (now() - states.test.get('last_updated', now())).minutes > 5 }}
TypeError: 'NoneType' object is not callable
marble jackal
#

{{ (now() - (states.sensor.test.last_updated | default(now())-timedelta(seconds=1))).seconds > 300 }} works

#

There is no minutes attribute in a timedelta

silent vector
#

It didn't work with seconds either. I'll try this one.

marble jackal
#

now, because if test doesn't exist, there is no last_updated object

#

BTW don't you mean sensor.test or at least some domain

#

that could be your error

#

oh wait

#

you need to do this

silent vector
#

Seems impossible to access the variable. It's reading sensor.test as you said

marble jackal
#
{% set test = 'sensor.weather_temperature_over_50' %}
{{ (now() - states[test].last_updated).minutes > 5 }}
silent vector
#

That worked. After I switched out to seconds of course. Thank you.

silent vector
#

How can I replace today_at(next_start) with now + 3 hours let's say?

{% set weather = 'weather.openweathermap' %} {% set forecast =
    state_attr(weather, 'forecast') %}  {% set n = today_at(next_start).astimezone(utcnow().tzinfo).isoformat() | string %}  {%
    set temp = forecast | selectattr('datetime', '<=', n) |
    map(attribute='temperature') | list %}  {{ temp | select('>', 50) |
    select('<=', 55) | list | count > 0 }}
mighty ledge
#

(utcnow() + timedelta(hours=3)).isoformat()

#

FYI .isoformat() is always a string

#

so that | string is useless

silent vector
#

Thank you!

autumn matrix
#

Hmmm this does not seem to work?

type: no_motion
platform: device
device_id: 94bfcdbd75a0e1e2dbbc5d639f34f0ec
entity_id: binary_sensor.presence_38
domain: binary_sensor
for:
  hours: 0
  minutes: "{{ states('input_number.bewegingsbesturing_garage_timeout') | int }}"
  seconds: 0
id: PIRGarage
#

I get the error message: Message malformed: expected float for dictionary value @ data['for']['minutes']

inner mesa
#

it probably doesn't support templates

#

use a state trigger

autumn matrix
#

let me see if i can find that out

#

@inner mesa

platform: state
entity_id: binary_sensor.presence_38
to: "off"
for: "00:{{ states('input_number.bewegingsbesturing_garage_timeout') | int }}:00"
id: PIRGarage

Would this be it?

inner mesa
#

you don't need the |int there, but I would expect that to work

pale tusk
#

Hello, I'm trying change the position of my blinds by 10 percent

#

I'd like to do something like
data:
tilt_position: position +10

#

Do I have to create a variable ?

inner mesa
#

No, you just need a template calculated based on the current state

pale tusk
#

and how do I do that ?

#

service: cover.set_cover_position
data:
position:
{{ states('Rollladensteuerung.current_position') -10 }}

#

gives me '[object Object]': null

dark sparrow
#

Does anyone know how to convert this mqtt message into Homeassitant sensors: 20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;

inner mesa
#

Rollladensteuerung.current_position is not an entity_id

#

you have to use an actual entity

#

and all states are strings, so you need to use |float before using the value in an expression

pale tusk
#

Ok, my entity_id is cover.rollladensteuerung

inner mesa
#

then you need to use that

#

position: "{{ state_attr('cover.rollladensteuerung', 'current_position')|float - 10 }}"

pale tusk
#

Thank you πŸ™‚

autumn matrix
#

somehow this is not working while it worked with one state function.
could it be that only one state is allowed per automation?

#

i'm a bit confused 🫀 . Can anyone spot the problem? it just doesn't trigger

sonic nimbus
#

hello, how can I check last_triggered time for my nuki door lock?
lock.bottom_door_opener_lock

inner mesa
tulip spindle
#

hi guys what is wrong in this template?

#
      time_remaning:
        friendly_name: "Tempo restante"
        value_template: >-
          {% if is_state('script.contagem_zona_1', 'on') %}
            {{ states.timer.zone1.attributes.remaining }}
          {% elif is_state('script.contagem_zona_2', 'on') %}
            {{ states.timer.zone2.attributes.remaining }}
          {% elif is_state('script.contagem_zona_3', 'on') %}
            {{ states.timer.zone3.attributes.remaining }}
          {% elif is_state('script.contagem_zona_4', 'on') %}
            {{ states.timer.zone4.attributes.remaining }}
          {% else %}
            Em espera
          {% endif %}
#

thanks

inner mesa
#

What is wrong?

#

looks like you're printing out some state objects, but maybe that's what you want?

#

this isn't like a job interview, so explain what isn't doing what you expect rather than expecting everyone to guess

tulip spindle
#

I wanted to join 4 timers that appeared as the scripts turned on. I don't know if this is a silly question or if it will work.

inner mesa
#

"join"? you're output 4 different things, but in two completely different ways

#

<well, okay, you just ninja-edited>

#

there's no "joining" going on there, you'll just output one of them

tulip spindle
#
      watering_zone:
        friendly_name: "Zona a ser regada"
        value_template: >-
          {% if is_state('switch.rega1', 'on') %}
            Zona 1
          {% elif is_state('switch.rega2', 'on') %}
            Zona 2
          {% elif is_state('switch.rega3', 'on') %}
            Zona 3
          {% elif is_state('switch.rega4', 'on') %}
            Zona 4
          {% else %}
            Rega desligada
          {% endif %}
#

i want something like this. But let time be shown. and not something predefined

tulip spindle
inner mesa
#

your first example will do that for exactly one of them based on the order you listed them in, and only if the timer is paused or stopped

tulip spindle
#

that was wrong

tulip spindle
inner mesa
#

there's nothing in the entity that shows the countdown

tulip spindle
#

Is it possible or am I dreaming big?

inner mesa
#

you will be better off building your own timer with an automation and time_pattern trigger

#

timer entities don't work the way you want

tulip spindle
#

ok

#

thanks for de help...

winter pilot
#

Evening! Having trouble with reading JSON output, anyone around who could help ?

silent barnBOT
#

Don't ask to ask, just ask your question. Then people can answer when they're around.

When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:

  1. What version of the Home Assistant are you running? (remember, last isn't a version)
  2. What exactly are you trying to do that won't work?
  3. Is the problem uniform or erratic?
  4. What's the exact error message?
  5. When did it arise?
  6. What exactly don't you "get"?
  7. Can you share sample code, ideally with line errors where the error occurs?
winter pilot
#

Keep getting "Unable to parse output as JSON" returned in the log and no attributes showing up on the sensor. I am using a python script to json.dumps a string for processing. Tested on two sites and it parsed the data fine. I have tried to use plain output and " | jq" output with no luck.

#

Unable to parse output as JSON: { "Non-Spin_deploy": "0", "Non-Spin_recall": "0", "Watch_Date": "", "Watch_start": "", "Watch_end": "", "ocn_start": "2022-07-18", "ocn_end": "2022-07-24", "ocn_cancel": "0", "ers_deploy": "0", "ers_recall": "0", "prc_deploy": "0", "prc_recall": "0", "rr_deploy": "0", "rr_recall": "0", "updated": "2022-07-16 19:07:36" } { "Non-Spin_deploy": "0", "Non-Spin_recall": "0", "Watch_Date": "", "Watch_end": "", "Watch_start": "", "ers_deploy": "0", "ers_recall": "0", "ocn_cancel": "0", "ocn_end": "2022-07-24", "ocn_start": "2022-07-18", "prc_deploy": "0", "prc_recall": "0", "rr_deploy": "0", "rr_recall": "0", "updated": "2022-07-16 19:07:36" }

inner mesa
#

How are you parsing it?

winter pilot
#
  • platform: command_line
    name: Ercot Notices
    command: "python3 /config/enotice.py"
    value_template: "{{value_json['value']}}"
inner mesa
#

It kinda looks like you have a list of dicts without the []

winter pilot
#

I have specified all the attributes as well.

inner mesa
#

What was logged doesn't look valid

winter pilot
#

hmm... i'm a json newbie .... I was mirroring another json file and it didn't have those... do I wrap the whole output in [] after the {} ? IE: {[ ]} ?

inner mesa
#

Other way

winter pilot
#

I had a 50/50 chance lol

inner mesa
#

Perhaps describe the data structure you really want

winter pilot
#

I switch to JSON to get around the 255 char limit ... Easier to address items individually as attributes than parsing the entire string to get what I want. Hopefully that answered what you were looking for.

inner mesa
#

No

winter pilot
#

JSON should be "Field Name":"Field Data" it will be that format the entire string. So that would translate in HA as "attribute_name":"attribute_data"

#

I tried the [] wrapping and it didn't work either.

#

did an online json validator (jsonlint.com) and it said it's valid. so i'm very confused.

inner mesa
#

What you posted in the log is a set of dicts, but not a list

#

Perhaps share what you're actually sending

silent barnBOT
#

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

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

winter pilot
#

Share the script or the output from the script?

inner mesa
#

The JSON

winter pilot
#

This is the full output:

{"Non-Spin_deploy":"0","Non-Spin_recall":"0","Watch_Date":"","Watch_start":"","Watch_end":"","ocn_start":"2022-07-18","ocn_end":"2022-07-24","ocn_cancel":"0","ers_deploy":"0","ers_recall":"0","prc_deploy":"0","prc_recall":"0","rr_deploy":"0","rr_recall":"0","updated":"2022-07-16 20:07:00"}

inner mesa
#

The log says that HA is seeing a bunch of those at once

#

You see that, right?

winter pilot
#

I just noticed that. That is bizarre. I only output one set of data

#

could HA be sending the command twice ?

inner mesa
#

No idea

winter pilot
#

... Might have found something, checking into it. If it's what I think it is, can we pretend this conversation never happened today....

#

ok. I was never here, this never happened. Thanks for opening my eyes.

still lodge
inner mesa
#

Sheesh. That's a giant template

#

You should really turn that into a multi line template so that it's actually readable

still lodge
#

I am not super good with Yaml, especially multi line. I did break it down better in the second

#

My ultimate goal is to make this into a blueprint

inner mesa
#

I don't see the difference

#

first, you're still using data_template: over 2 years after it was deprecated

#

second, your indentation is not consistent. I suggest fixing that first

#

beyond that, I'm not going to try to parse the that giant single-line template

still lodge
#

Not gonna lie, I found data_template on some forum post because as much googling as I have done I cannot find a page that actual details how to use this

#

data_template or how to even problem use templates in this manner seem to be entirely undocumented from what I can see and the examples are lacking

inner mesa
#

there's lots of documentation in the channel topic here

still lodge
#

There is a fair amount on various template functions, but combining them or even finding stuff such as what attributes can be used with selectattr are entirely missing

#

Not to mention the bug currently on github where how the developer tools don't function the same as yaml currently

#

So far even getting data_template to work has been brute force from various blueprints that I know are working

still lodge
marble jackal
#

Had a quick look, as I'm on mobile, but it seems you don't need the for loops and namespaces.
Is your goal to select all switches which belong to frigate?

#

And have record or detect in their name?

marble jackal
dark sparrow
#

Does anyone know how to convert this mqtt message into Homeassitant sensors: 20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;

marble jackal
#

Which part do you need?

silent vector
#

I need trigger_sensors to use as a condition and then I also will need to know which sensor was true. I know which sensor is true, but without duplicating the variable taking it out of a list and inserting 'or' I was wondering if there's a way to check if my variable is true the way it's setup or do I just need to make another variable to use as a condition without using a list and use 'or'?

https://dpaste.org/39jQB

marble jackal
silent vector
#

Which it would be if it's false.

#

I would say is defined?

marble jackal
#

It will be defined

#

You can use iif(your_variable)

#

Or your_variable | lenght > 0

silent vector
#

It should be empty (null) if they are all false though?

silent vector
# marble jackal Or `your_variable | lenght > 0`

I made the variable false and this still shows true

{{ trigger_sensors is defined }}
{{ iif(trigger_sensors) }}

I checked it's false by switching my expand to listing false variables and it listed all 4

marble jackal
#

You should not check for trigger_sensors as that is a list of sensors

#

I assumed that whole template is resulting in a variable

silent vector
#

Nope, the expand is a second variable in the automation. Ideally the first variable trigger_sensors could be used to pass data to the second variable simultaneously being used as a condition. I just realized the second variable is what I can use to check if it's defined because that would be empty if it's false.

marble jackal
#
{% set trigger_sensors = ['sensor.weather_temperature_over_50_cool',
    'sensor.weather_temperature_under_50_over_45_off',
    'sensor.weather_temperature_under_50_off',
    'sensor.weather_temperature_under_45_heat'] %}
{% set results = expand (trigger_sensors) | selectattr('state', 'eq', 'True') | map(attribute='entity_id') | list | join(',') %}
{{ result }}
{{ iif(result) }}
{{ result | lenght > 0 }}
silent vector
#
select_sensor: >-
    {{ expand (trigger_sensors) | selectattr('state', 'eq', 'True') |
    map(attribute='entity_id') | list | join(',') }}

{{ select_sensor is defined }} would this work too? It should be null if nothing is true in the trigger_sensors variable

marble jackal
#

is defined will not work, as is will be defined, even if the value is none or '' or []

silent vector
#

This should work then?
{{ iif(select_sensor) }} looks like it does

#

Perfect thank you! Always teaching something new.

still lodge
#

Fes that is what I am trying todo and thanks for making it more streamlined. My more perplexing question is why whenever I put it into a template switch the entire yaml file fails to load

marble jackal
#

@still lodge See this post

#

And maybe also read the pinned post petro refers to

still lodge
#

Its odd that its not loading and yet I cannot find anywhere in any log that explains why

marble jackal
#

I assume you rebooted, or reloaded template entities?

still lodge
#

reloaded template entities. Let me try rebooting

#

rebooting no change, no obvious error in the logs and the switch is missing

marble jackal
#

Is the code places directly in configuration.yaml?

still lodge
#

No, its placed in its own Yaml file that is loaded via

  packages: !include_dir_named packages```
marble jackal
#

Do you have other packages in that folder which are working?

still lodge
#

Yes, I also had this in the same file as another and whenever I uncommented this code both would break

#

I have now moved them to two separate files so that my lights continue to work, lol

#

I originally had this in configuration.yaml and it took me a bit to figure out why everything was broken

marble jackal
#

Does the configuration check under developer tools mention anything

still lodge
#

Nothing at all

marble jackal
#

I can't access that

#

Error Missing signature

still lodge
#

oh right....I have a bug for that

#

Try now, since last update I have to view the link first before anyone else can

marble jackal
#

What i can see is that your item template is wrong

#

You need to wrap that in single quotes, but I think you can simply remove the curly brackets

still lodge
#

If I remove the curly brackets it complains

#

changing to icon_template: {{'mdi:camera'}} didn't help

#

with single quotes and no brackets however it loads.... intertesting

marble jackal
#

You need to put quotes outside the template if you use the single line notation

still lodge
#

Originally I just used double quotes because it would complain that it was formated incorrectly if it was double quotes there

marble jackal
#

icon_template: '{{ "mdi:camera" }}'

still lodge
#

I just did icon_template: 'mdi:camera' however icon_template: "mdi:camera" did not work

marble jackal
#

Instead of icon_template: {{ "mdi:camera" }}

still lodge
#

it would fail configuration check

marble jackal
#

Should make no difference, but okay

still lodge
#

I agree, hence why I didn't try single quotes before

#

Why is all of this failing without errors though ?

karmic lotus
#

Why am I not supposed to access state like this states.sensor.something.state?

arctic sorrel
#

See the warning there

karmic lotus
#

Ah, I see. Thank you!

dark sparrow
#

Cresta and the ID are the identifier of this simple weatherstation. It gives the temperature, humidity and battery status. Would like to create a HA-sensor from it πŸ˜€

marble jackal
still lodge
#

Sure, thats not my question. Why was there nowhere, not logs nor editor nor reloading that explained why it was failing or even that it was failing

marble jackal
#

I don't know

silent vector
inner mesa
#

use another trigger, add an id, and use a template in the state

#

you don't want "auto_off", you want "turn off when this trigger happens"

#

state: true doesn't make any sense

silent vector
#

Yeah I wasn't sure how to use the 2 triggers together.

#

Not exactly sure how your suggestion would look in yaml

inner mesa
#

oik

#
- trigger:
  - platform: zone
    entity_id: person.daniel
    zone: zone.away_zone
    event: leave
    id: leave
  - platform: zone
    entity_id: person.daniel
    zone: zone.away_zone
    event: enter
    id: enter
  binary_sensor:
  - unique_id: Daniel_Outside_Away_Zone
    name: "Daniel Outside Away Zone"
    state: "{{ trigger.id == 'leave' }}"
silent vector
#

I assume state would be true when leave and false when enter essentially. If I made another template sensor with the same id's, they won't interfere right because it's a separate trigger sensor?

inner mesa
#

right

primal copper
#

Do zones or people entities have any meta data related to one another? For example I'd like to do something if I enter zone 1 and I've been away from zone 1 for one hour or more. Our do I have to go the route of keeping track of that myself with custom sensors?

#

sensor.matte_last_left_home or something similar and then just update it with a zone left automation

marble jackal
#

The state of the zone is the number of person entities in it. It had an attribute listing the person entities in the zone

#

And the state of the person entity will be the zone it is in

inner mesa
#

I would create a template sensor with triggers for entering and leaving, with an auto_off

fringe temple
#

I have an error on startup with one of my scripts.yaml files.
Invalid config for [script]: expected a dictionary. Got OrderedDict ... ending in (See ?, line ?)
Free YAML LINT tools show it's valid so I'm wondering if there's a simple way to locate the issue?

inner mesa
#

You probably put script: at the top

fringe temple
#

@inner mesa I didn't in that specific file, which is referenced in configuration.yaml by script split: !include_dir_merge_named ./scripts
Does this create the redundancy you are thinking?

inner mesa
#

No. I suggest moving the files out to help identify the one that's broken

fringe temple
inner mesa
#

No, move them out of that directory/file to eliminate them

floral shuttle
#

having a state and quite a few attributes based on the state being true, I figured to do:```
state: >
{{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}}
attributes:
title: >
{% if this.state == 'true' %}
{{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}}
{% else %} No alert
{% endif %}

#

simply putting the state template in all of those attributes solves the issue, so I am positive thats ok. Should I have a guard on this too? If yes, what would be best?

marble jackal
#

Is it a trigger based template sensor?

floral shuttle
#

no just a regular template sensor, based on the state change of sensor.weatherbit_weather_alerts

#

thing is, all my other uses of this variable are based on an attribute, here however it is the state

marble jackal
#

Okay, just did a simple check, this works:

sensor:
  - name: Test 1
    unique_id: 28218f4f-e575-452d-9d0b-8bf7dc22f29a
    state: "{{ states('sensor.power_consumption') }}"
    icon: mdi:test-tube
    attributes:
      test_1: "{{ this.state }}"
floral shuttle
#

so does: attributes: title: > {% if states('sensor.weatherbit_weather_alerts')|int(default=0) > 0 %} {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}} {% else %} No alert {% endif %} just to proof the correctness of the logic

marble jackal
#
sensor:
  - name: Test 1
    unique_id: 28218f4f-e575-452d-9d0b-8bf7dc22f29a
    state: "{{ states('sensor.power_consumption') | float > 0 }}"
    icon: mdi:test-tube
    attributes:
      test_1: "{{ 'Hello' if this.state else 'Bye' }}"
#

This returns Hello, so it looks like this.state is parsed as a boolean already, so you should not test for a string

floral shuttle
#

right, that could be it!

marble jackal
#
        attributes:
          title: >
            {% if this.state %}
              {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}}
            {% else %} No alert
            {% endif %}
floral shuttle
#

let me try... brb

#

perfect. thx! even shorter...

marble jackal
#

for trigger based template sensors it seems to be one state behind

#

the this variable is created on the trigger, so before the state template is rendered, so it has the previous state

floral shuttle
#

I wonder what will happen in this case then. ofc, manually reloading the template now works fine, no state lag because of that.

marble jackal
#

test_1 is state based, test_2 is trigger based

#

for the state based sensor the state and attribute are the same, the trigger based attribute is one state behind

#
trigger:
  - platform: state
    entity_id: sensor.power_consumption
    from: ~
sensor:
  - name: Test 2
    unique_id: c4713163-8c99-40bf-9b6b-a0d233456830
    state: "{{ trigger.to_state.state }}"
    icon: mdi:test-tube-empty
    attributes:
      test_2: "{{ this.state }}"
floral shuttle
#

good te be aware of that. We had that in custom:button-card, until the triggers_update option was introduced. Didnt realize we had that same effect in the backend too

marble jackal
#

You could use it to your advantage, can be an easy way to log the last 5 states for example πŸ™‚

floral shuttle
#

you mean recursively template the attributes?

acoustic arch
#

a verrrry stupid question probably:
{{ states("OTGW_Outside_Temperature") }} gives me unknown, while in developer tools it gives me the temp.

floral shuttle
#

add 'sensor.'

acoustic arch
#

got it! i have to learn this each time i tinker hahaha

marble jackal
#

and slugify it πŸ™‚

marble jackal
# floral shuttle you mean recursively template the attributes?

like this:

trigger:
  - platform: state
    entity_id: sensor.power_consumption
    from: ~
sensor:
  - name: Test 2
    unique_id: c4713163-8c99-40bf-9b6b-a0d233456830
    state: "{{ trigger.to_state.state }}"
    icon: mdi:test-tube-empty
    attributes:
      prev_1: "{{ this.state }}"
      prev_2: "{{ this.attributes.prev_1 }}"
      prev_3: "{{ this.attributes.prev_2 }}"```
floral shuttle
#

yes, thats what I meant.. its really getting close the CC variable like this... wonder what Frenck feels about this, because now you are saving history in attributes in the state machine

#

sensor last_motion would be a scenario to think of using this

#
    sensor:

      - unique_id: last_motion_sensor_triggered
        name: Last motion sensor triggered
        icon: mdi:motion-sensor
        state: >
          {{trigger.to_state.name.split(' sensor Motion')[0]}}
        attributes: &attributes
          entity_id: >
            {{trigger.entity_id}}
          last_triggered: >
            {{trigger.to_state.last_changed.isoformat()}}
``` and then add some recursive attributes πŸ˜‰
mighty ledge
#

would forever grow though

#
  - name: Test 2
    unique_id: c4713163-8c99-40bf-9b6b-a0d233456830
    state: "{{ trigger.to_state.state }}"
    icon: mdi:test-tube-empty
    attributes:
      history: "{{ (this.attributes.history | default([]))[:2] + [ this.state ] }}"
marble jackal
floral shuttle
#

it would be almost literally what we did with the CC Variable, and its history attributes - service: variable.set_variable data: variable: last_motion attributes: history_1: "{{states('variable.last_motion')}}" history_2: "{{state_attr('variable.last_motion','history_1')}}" history_3: "{{state_attr('variable.last_motion','history_2')}}" history_4: "{{state_attr('variable.last_motion','history_3')}}" history_5: "{{state_attr('variable.last_motion','history_4')}}" history_6: "{{state_attr('variable.last_motion','history_5')}}" history_7: "{{state_attr('variable.last_motion','history_6')}}" history_8: "{{state_attr('variable.last_motion','history_7')}}" history_9: "{{state_attr('variable.last_motion','history_8')}}" history_10: "{{state_attr('variable.last_motion','history_9')}}"

mighty ledge
floral shuttle
#

wait, I missed the [:2], or?

#

yep, working nicely:```
- unique_id: last_motion_sensor_triggered
name: Last motion sensor triggered
icon: mdi:motion-sensor
state: >
{{trigger.to_state.name.split(' sensor Motion')[0]}}
attributes: &attributes
history: >
{{ (this.attributes.history | default([]))[:8] + [ this.state ] }}
entity_id: >
{{trigger.entity_id}}
last_triggered: >
{{trigger.to_state.last_changed.isoformat()}}

#

heck, it copied the new history over to my Area template πŸ˜‰ - unique_id: last_motion_seen_in_area name: Last motion seen in area icon: mdi:sofa state: > {{area_name(trigger.entity_id)}} attributes: *attributes

mighty ledge
#

that's a good way to be lazy, kudos

floral shuttle
#

yeah. I now see that I could just as well put the {{area_name(trigger.entity_id)}} in my first template, since I split that to only show the Area name πŸ˜‰ Saves yet another template (and db space on historic attributes....)

#

note to self: these attributes survive a restart... which Erik introduced after having discussed the trigger based templates for buttons. Had forgotten about that and added a default 'Not yet set' but upon restart see the full history on the attribute. nice.

marble jackal
#

aren't they basically the same sensor then?

acoustic arch
#

if i have an array of [0,0,0,0,2,4,6,0,0,0]

#

how do i average just 2 4 and 6?

#

find first non 0, find last non zero. then average all values inbetween those.... syntax?πŸ₯Ί

marble jackal
#

I already provided how you can find the right part of your array last time

#

Now instead of a count of the items in that part, you need to do an average

acoustic arch
#

yes you helped me well last time. I rewritten some parts for my own sake of sticking to something i can understand once i come back to it. I got it working so far:

silent barnBOT
acoustic arch
#

all i need now is to write the array position to a time (already working in last version), and see if there is a substatial peak rain compared to average

#

i know how to average a complete array, but not a part of it.

#

ill keep searching/googling

#

and just like that. after 30min

#

{{ regen_waarden_lijst[0:4] | list | average }}

floral shuttle
#

Wait, I now see the attributes list isn’t updated after it has reached the :8… so it only shows the first 9 elements, and not the last πŸ˜‰

marble jackal
#

you need to use the start and einde variables you already have

#
{% set regen_waarden_lijst = [0,0,0,0,2,4,6,0,0,0] %}
{% set start = regen_waarden_lijst.index(regen_waarden_lijst | reject('eq', 0) | list | first) %}
{% set einde = regen_waarden_lijst[start:].index(0) + start %}
{{ regen_waarden_lijst[start:einde] | average }}
floral shuttle
#

yes Petro, thats what I did now, and the list is building and keeps doing so. We do see the state lag Fes described above,

#

the attribute entity_id updates correctly, while the atttribute history is 1 behind

deft timber
#

Maybe I miss something bu why don't you just do this :

{% set regen_waarden_lijst = [0,0,0,0,2,4,6,0,0,0] %}
{{ regen_waarden_lijst | sum / regen_waarden_lijst | reject('eq', 0)  | list | count }}

?

acoustic arch
#

Thx I figured out it had to be start and einde. It was just an example. Sorry for making you reply

marble jackal
#

It was your own example 😜

summer slate
#

Is there a way to get historic data from an attribute?
I have the following:

  - sensor:
      - name: "downstairs_hvac_action"
        state: "{{state_attr('climate.downstairs', 'hvac_action')}}"```

But when I try to get history stats I need an entity id

```sensor:
  - platform: history_stats
    name: HVAC Upstairs Cooling - test
    en_id: upstairs_hvac_action
    state: "cooling"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}"```
inner mesa
#

You need to grab the data out of the DB via an SQL sensor

warm estuary
#

Hello guys, I was sent here from #automations-archived, I would like to use the foreach operator in a script to print out all of the days and the temperatures that are in the forecast.

#

I'm a total noob with this, so any help would be appreciated.

inner mesa
#

Print them where?

warm estuary
#

To TTS

#

Thats what I currently have

#

But instead of the tomorrow, I want it to iterate over the different days in the forecast.

#

Or is that a bit too much xd

inner mesa
#

It would drive me nuts

warm estuary
#

I like it :P

inner mesa
#

So you can either do what you were suggesting and loop through them with a 'repeat' construct and use the loop index for each day (where you currently have [0]), or construct a big message in a template and send it all at once

warm estuary
#

Yeah I would kinda like the repeat construction, makes it a bit more tidy and flexible imho

inner mesa
#

I suggest the former, as it is better documented and easier to do in the UI

acoustic arch
#

im sure it can be written prettier but they its now i can understand it

#

no more big IF ELIF lists to make something work πŸ₯³

fringe temple
#

This is basically a replication of what

sick ice
#

Is there a way to use templates in the general lovelace cards?

I'd like the name: of a gauge: card to be change based on the state of the entity.

inner mesa
#

nope

#

the markdown card is the only one that I recall supports templates

sick ice
inner mesa
#

it's fine, it's just a custom card/modifier

sick ice
#

another Q, this one is actually working but I feel like the nested brackets is poor code - I'm just trying to improve the way I write templates.
This entity is provided from a different system through a Long-Lived Access Token. Occasionally it becomes unavailable and breaks some charts.
Goal here is to return 0 when the entity is unavailable. Is there a tidier way to acheive the {% if %} part?

    name: TWC Charger Load Always W
    state_class: measurement
    unit_of_measurement: W
    device_class: power
    state: >
      {% if is_number(states('sensor.twcmanager_charger_load_w')) %}
        {{states('sensor.twcmanager_charger_load_w')}}
      {% else %}
        0
      {% endif %}```
inner mesa
#

I would do this:

{% set value = states('sensor.twcmanager_charger_load_w') %}
{{ iif(is_number(value), value, 0) }}
sick ice
#

much more concise and easier to understand

inner mesa
#

actually, it can be even simpler:

#
{{ states('sensor.twcmanager_charger_load_w')|float(0) }}
sick ice
#

What's the logic there if the entity doesn't exist? does using the float(0) filter mean that it will return a zero be default if it returns null?

inner mesa
#

it will return 0 if the input isn't something that float can convert to a float

#

you can test it in devtools -> Templates

#

{{ none|float(0) }} -> 0

sick ice
#

that's awesome, thanks for explaining

inland stag
#

Hi everyone, is it possible to track an energy sensors for changes and depending on the state of another sensor, add the difference to a template sensor? I get the energy from my heat pump via an SDM120 meter, which already returns the energy in kWh. Now I want to split this energy into Heating, Hot Water and Standby. So if the mode is set to Heating, all changes to the energy sensor should be added to a new template sensor Energy Heating.

#

otherwise I would need to track the power sensor with an integration sensor, but this will most probably lead to differences to the "real" energy sensor from the meter

spring zenith
#

with mushroom template card i would like to change the colour.
"{%-elif is_state('sensor.sonos_roam1_battery' | float < 70) %}
green"
But i am not so good in code. (as you can see ;-) ) What am i doing wrong ?

marble jackal
#

is that your complete template?

#

"{{ 'green' if is_state('sensor.sonos_roam1_battery') | float < 70 }}" should work then

marble jackal
#

Then based on the mode, add the difference between the to_state and de from_state

#

otherwise, keep the existing state

#
state: >
  {% set change = trigger.to_state.state | float - trigger.from_state.state | float %}
  {% set mode = state_attr('sensor.foo', 'mode') %}
  {{ this.state | float(0) + change if mode == heating else this.state }}
#

with:

trigger:
  - platform: state
    entity_id: sensor.pump_energy
    not_to:
      - unavailable
      - unknown
    not_from:
      - unavailable
      - unknown
silent vector
marble jackal
#

not sure either, are you sure it originates from this automation? Based on the message the action part seems to be missing, but it is present in the link you shared. It seems to be more related to #automations-archived anyway.

thorny snow
#

Hey all got sent here from #automations-archived I wanted to make an automation that sends me a notification when a window or door changes status, for example living room window opened, or storage room door closed. And all that when the group ( both iPhones ) are not home. I already have the group, and I kinda get the totals basic idea of notifications , in this case I would like to get the super important iPhone notification ( sadly no idea how that thing works ) but the biggest problem is for my plan to work I would have to create two automations for each and every window and door I have so that I would receive a correct message of the exact thing that changed status. I’m 100% it’s doable in easier way in YAML but so far I’ve done some super basic copy paste YAML stuff so writing and automation fully in YAML definitely not an option for me at the moment . Any ideas how could this be done in GUI ? Or maybe someone has this already done ? πŸ™‚

thorny snow
#

Thank You ! Will try to get it done a bit later today πŸ™‚

thorny snow
#
condition: not
  - conditions:
      condition: zone
      entity_id: device_tracker
      zone: zone.home

having some problems with this line, i used it from another automation and wanted to add it to the code @arctic sorrel gave a minute ago πŸ™‚

arctic sorrel
#

You really don't have to keep tagging me all the damn time @thorny snow

thorny snow
#

Ok i got that im doing something wrong again πŸ˜„ what do You mean with that ?

#

Oh the @ thing ? πŸ™‚

arctic sorrel
#

Yes

#

Every time you do that, I get a notification

thorny snow
#

Ok boss πŸ™‚

#

ohhh, ok sorry for that then πŸ˜„

arctic sorrel
#

But it's ok, I'll add you to my blocklist agooglethumbsup

thorny snow
#

i got discord like two days after HA so yep, as new to this as to HA πŸ˜„

#
condition: device
  domain: device_tracker
  entity_id: device_tracker
  type: is_not_home
marble jackal
#

As soon as you start using {{ or {% you are using templates

thorny snow
#

yep, thanks

thorny snow
#

So now it should be templates related, hopefully, so i have a entity that has a friendly name, and i have an automation that sends me a message if the state of the entity changes including the name of the entity in the message, but what i want is for the entity to keep its friendly name but have a different friendly name in the message im getting so one of the @Gods here told me this -> Then you'll have to build a really big templates that uses the entity ID to give you a hard-coded name of your choice <- this is the original automation with the message code

marble jackal
#

you can put a variable in your automation

#
action:
  - variables:
      mapping:
        0x00158d0008649a33_contact: Window Bedroom
  - service: notify.mobile_app_iphone_x
    data:
      title: "Yep it's happening!"
      message: "The {{ mapping[trigger.to_state.object_id] }} just {{ 'opened' if trigger.to_state.state == 'on' else 'closed' }}"
thorny snow
#

so just add a bunch of variables ?

marble jackal
#

no, only one

#

mapping

thorny snow
#

ohh got it

marble jackal
#

but add all sensors to that variable

thorny snow
#

like so ? πŸ™‚

#

had to edit the message text also ( didn't noticed that at first ) but now it works πŸ™‚ Huge thanks ! πŸ™‚ any knowledge in iOS notifications ?, i know about #ios_and_mac-archived but it's been quiet so far...

#

got it, spacing πŸ™‚

floral shuttle
#

back to this - unique_id: weatherbit_alert name: Weatherbit Alert state: > {{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}} attributes: title: > {% if this.state %} {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}} {% else %} No alert {% endif %} currently the state is false, and yet it passes the if....

#

so I do need to check if the state is actually true after all

#

was an error in the integration showing no alert (which as I typed this was corrected) but it did show the if this.state not to be solid..

mighty ledge
#

a populated string always returns true πŸ˜‰

floral shuttle
#

hi. yes, and a few posts up I tried if this.state == 'true' but that didnt help....

mighty ledge
#

you'd have to know the actual state

#

python, values are True or False

#

so I'd expect the string to be 'True' or 'False'

floral shuttle
#
{% set this = states('sensor.weatherbit_weather_alerts')|int(default=0) > 0 %}
{{this == true}}```
mighty ledge
#

my man, that's not what's resolved. That's just in jinja and your comparing objects

#

is that a sensor or a binary_sensor?

#

or you can just check what the state is in the states page

floral shuttle
#

its a template binary_sensor, with several attributes

mighty ledge
#

if it's a binary_sensor, ask yourself, what are the only possible states for a binary sensor?

floral shuttle
#

wait, the binary_sensor is on/off, but the state template isnt

mighty ledge
#

because...

floral shuttle
#

heck, I believe I see the light...... this.state is the state of the binary_sensor.....and not the state template..

mighty ledge
floral shuttle
#

exactly....

mighty ledge
#

πŸ˜‰

floral shuttle
#

thx....

marble jackal
#

Ah, sorry. I assumed you knew that, and actually used a sensor instead of a binary sensor

#

@mighty ledge I tested with a sensor instead of a binary sensor, and this.state was actually parsed as a boolean value

mighty ledge
marble jackal
#

I think my test was faulty indeed

floral shuttle
#

no need to fight over it πŸ˜‰ it was me who was confused to begin with....

marble jackal
#

No fight :)
Btw, this is a good use case for the new bool filter. You can use this.state | bool as a test

daring wedge
#

Hi all,
I have been using home assistant now for years, and I really like it πŸ™‚
I am currently helping to set up a home assistant instance for Project Kamp https://www.youtube.com/c/ProjectKamp (off-grid sustainable living community in portugal)
They have a nice 6 panel solar setup with a giant battery, it is all victron powered and I managed to get the data out of the system through MQTT
Main question:
How do I get an mqtt sensor (in Watts) to to show up in the energy dashboard? I tried templating and integrating, but so far no luck
Shall I share my config what I tried here?

marble jackal
#

You need to convert W to kWh using the Riemann Sum integral (available in the GUI under Helpers)

daring wedge
#

Okay I made a integral for the solar component, and it shows in kWh, but it does not allow me to select it as an option in the energy dashboard

lament dust
#

Hey folks, trying to figure out how to url enocode a string which seems not possible. I tried with a basic object too but the outpet in dev tools is blank which is confusing to me

{% set test = '{"testKey": "testValue"}'|from_json  %}
{{ urlencode(test) }}
marble jackal
dark sparrow
#

Does anyone know how to convert this mqtt message into Homeassitant sensors: 20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;

#

I need this part:

Does anyone know how to convert this mqtt message into Homeassitant sensors: Cresta = id , TEMP=00cf, HUM=09, BAT=LOW;`

dark sparrow
#

So, if the message contains β€œCresta”, the TEMP, HUM and BAT values must be placed into a sensor Cresta with attributes TEMP, HUM and BAT with corresponding values…

#

Who can make a template for it?

inner mesa
#

you!

inner mesa
#

This is a template that takes that data and turns into a dict that an MQTT sensor can process into attributes:

#
{% set data = "20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;" %}

{% set ns=namespace(fields={}) %}
{% set fields = data.split(';') %}
{% if fields[2] == "Cresta" %}
  {% for item in data.split(';') %}
    {% if '=' in item %}
      {% set keys=item.split('=') %}
        {% set ns.fields = dict(ns.fields.items(), **{keys[0]: keys[1]}) %}
    {% endif %}
  {% endfor %}
{% endif %}
{{ ns.fields|to_json }}
#

->

{
  "ID": "3601",
  "TEMP": "00cf",
  "HUM": "09",
  "BAT": "LOW"
}
#

you can put some version of that in json_attributes_template and it will populate the attributes from the resulting dict

low blaze
#

I'm having trouble understanding the depreciation of "entity_id" I have a lot of template sensors and I determined their entity_id and use that subsequently all over the place. If I remove that line that sets all the entity_id's in my template sensors, what does their id become? how can I make sure they are named the way I like?

#
    sensors:  
      p1bucket_midline:
        friendly_name: 'P1 Bucket MidLine'
        entity_id: sensor.p1bucket_midline
        value_template: >-
          {% set midline = (states('sensor.wl1_p1_ads1115_a1') | float) %}
          {% if midline < 100 %}
             Dry
           {% else %}
             Wet
           {% endif %}```
#

In addition, I experimented by removing that line from 1 of my sensors, and it still shows up and has the original name after even a reboot - but why? (and what happens if I write new ones)?

#

would change to ```

  • platform: template
    sensors:
    p1bucket_midline:
    friendly_name: 'P1 Bucket MidLine'
    value_template: >-
    {% set midline = (states('sensor.wl1_p1_ads1115_a1') | float) %}
    {% if midline < 100 %}
    Dry
    {% else %}
    Wet
    {% endif %}```
inner mesa
#

the entity_id: key was only required to tell the template engine what to monitor to decide when the template needs to be reevaluated

#

it has no effect on the name of the sensor that you're creating, and you only needed it if the entities to monitor were ambiguous from the template itself

#

if you just want to monitor sensor.wl1_p1_ads1115_a1, then you can just remove the entity_id line completely

low blaze
#

k thanks

#

is there a way to make a template sensor that shows change over time?

#

actually its probably not possible as what I am trying to do is check the health of recorder/MariaDB

daring wedge
marble jackal
#

You need to use customize

daring wedge
#

IT IS WORKING 😍

#

thank you @marble jackal

#

1 more question:
I am pulling information of the battery, and the value can be positive (while charging), or negative (while discharging), how do i separate them into 2 sensors?

merry marsh
#

Was there a change (and when), that I cannot filter directly with e.g. | selectattr('attributes.device_class', 'eq', 'battery') anymore, but have to filter on the availability of the attribute | selectattr('attributes.device_class', 'defined') before? Just went by chance through some old sensors, where I'm pretty sure, that they worked before, but now I get error messages without the check in developer tools.

dark sparrow
#

Does anyone know how to convert this mqtt message into Homeassitant sensors: 20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;

#

Zou dit graag willen hebben:

Id=waarde; alle items, die wil ik graag in 1 ha-sensor πŸ˜€

marble jackal
#

What was not working for you in the answer Rob gave above?

marble jackal
marble jackal
jagged totem
#

Created a sensor with history_stats, is there some way to reload them without a restart?

mighty ledge
mighty ledge
#

if there was a change it was to the attribute itself, specifically device_class, or __getitem__ on the attributes state object. But IIRC that's just an ordered dictionary.

#

we can't adjust how selectattr behaves, it's a built in to jinja

#

you can override it, but that was not done

#

Basically what I'm saying is, nothing was changed in templates. Something may have changed that affects templates. Maybe it's just semantics, but you should understand that accessing an attribute that doesn't exist should always start with is defined

merry marsh
#

Already changed all my templates. But I'm 100% sure, that it worked without feature check filter in the past. For years and without errors neither in execution nor in developer tools. It selected only the ones with the attribute.

mighty ledge
#

I have templates that are from day 1 that exclude attributes because they didn't exist and caused errors. Nothing changed with that. The state object is a special object, something may have changed on that. All of home assistant is built on state objects. Templates just use them. Something may have changed with that object, specifically with device_class as it's a special attribute. However, nothing changed with templates.

surreal storm
#

hi, how can Δ± grayscale if contact sensor is closed and if Δ± open sensor, its color on mushroom cards ?

marble jackal
#

icon_color: "{{ 'yellow' if is_state('binary_sensor.your_door_sensor', 'on') }}"

#

The default is grey

silent barnBOT
spring zenith
#

srry... didnt mean to do that

spring zenith
marble jackal
spring zenith
marble jackal
#

You need to use states() | float < 70

floral shuttle
#

well, I am back to using the full template in each attribute, because even {% if this.state == 'on' %} resulted in an error just now: 2022-07-20 16:16:32.470 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: list object has no element 0 when rendering '{% if this.state == 'on' %} {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}} {% else %} No alert {% endif %}' and that on all attributes. Replacing immediately solves the issue

marble jackal
#

That error comes from the state_attr

floral shuttle
#

thing is, if the binary is on, it means the ``` state: >
{{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}}

#

this works:```

  • unique_id: weatherbit_alert
    name: Weatherbit Alert
    state: >
    {{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}}
    attributes:
    title: >
    {% if states('sensor.weatherbit_weather_alerts')|int(default=0) > 0 %}
    {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}}
    {% else %} No alert
    {% endif %}
#

and this causes inconsistent errors:```

  • unique_id: weatherbit_alert
    name: Weatherbit Alert
    state: >
    {{states('sensor.weatherbit_weather_alerts')|int(default=0) > 0}}
    attributes:
    title: >
    {% if this.state == 'on' %}
    {{state_attr('sensor.weatherbit_weather_alerts','alerts')[0].title}}
    {% else %} No alert
    {% endif %}```
#

imight it also be the state lagging 1 state change behind I now realize? like we discussed on another template the other day? thats got to be it. Upon changing from on to off on the main binary sensor, the attributes are still in the previous this.state.. which doesnt happen when using the full template

marble jackal
#

I don't think that is the case, in our previous discussion I was referring to trigger based template sensors. In that case this is created on the trigger firing, when the templates are not rendered yet

floral shuttle
#

True, different scenario. Still this worked fine (== β€˜on’) until the source sensor changed. Replacing that as shown above fixed it.

frail olive
#

Hi,

How can I create a dummy switch which will be negation of tasmota relay?

Tasmota Relay1 - this is a physical one switch.valves_1
and I need R3= negation of switch.valves_1
Im gonna use R3 just as an indicator (just to animate icon opposit to switch_valves_1)

or maybe I could change something here:
type: picture-elements
elements:

  • type: state-icon
    entity: switch.valves_1
    style:
    top: 6.4%
    left: 35%
  • type: state-icon
    entity: switch.valves_2
    style:
    top: 45%
    left: 35%
  • type: state-icon
    entity: ! (some kind of negation here? )switch.valves_2
    style:
    top: 21%
    left: 47.6%
    transform: rotate(90deg)
    image: /local/water.png
spring zenith
silent barnBOT
#

@frail olive [Rule #6](#rules message): Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

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

For sharing code or logs use https://dpaste.org/ (pick YAML for the language) or https://www.codepile.net/ (pick YAML for the language).

spring zenith
marble jackal
spring zenith
lime forge
#

Hello, is there a command for updating core & supervisor. I would like to do updates using the button on the dashboard?

lime forge
#

Ok thx

inner mesa
#

And I'm pretty sure there is no service for that. You would need to ssh in and use ha core update for core

marble jackal
#

As he seems to run superviser, he can use the update entity

#

And the related service call

inner mesa
#

I thought that was for updating firmware

#

are you talking about the update.install service?

#

with update.home_assistant_supervisor_update?

marble jackal
#

I've set up an automation for core updates, and I can update from that notification

inner mesa
#

and update.home_assistant_core_update?

marble jackal
#

It provides a link to the release notes as well, which I always press first of course

#

Yes, those, although supervisor automatically updates, I use it for core and OS

inner mesa
#

ok, TIL

inner mesa
#

that's great. I stand corrected @lime forge

lime forge
#

Thx ☺

mighty ledge
#

it was a toss up between integrations, automations, or frontend

#

all 3 are better fits than templates.

inner mesa
#

#TheFesHasAllThe Answers

mighty ledge
#

that's why he's blue

#

maybe we need a new category, DEEEP BLUE

#

with only thefes

floral shuttle
#

hmm. ```ValueError: Template error: bool got invalid input 'na' when rendering template '{{value if value|bool is boolean else none}}' but no default was specified

#

figured the |bool was used just to check for this existence but now its needs a default itself?

#

used in a binary mqtt sensor like:```
binary_sensor:

- unique_id: amp_left_auditorium_state_binary
  state_topic: '70:B3:D5:6F:31:F2/powerswitch-zwave/c5745b57/state'
  name: Amp left Auditorium state
  <<: &binary
    payload_on: 'on'
    payload_off: 'off'
    device_class: power
    value_template: >
      {{value if value|bool is boolean else none}}```
inner mesa
floral shuttle
#

yes, thx Rob, I had missed that.{{value if bool(value,none) is boolean else none}} seems to fix it. At least in the dev template.

lament garnet
#

I keep forgetting how to display values as numbers instead of discrete colored blocks?

inner mesa
#

you mean "as a graph"?

#

add a unit_of_measurement

lament garnet
#
  • name: water_cold
    state_topic: 'kelder/coldwater'
    unit_of_measurement: 'l'
    value_template: "{{ value_json.Volume|int(unknown) }}"
    • platform: derivative
      source: sensor.water_cold
      name: water_cold_10min
      round: 0
      unit_time: h
      time_window: "00:10:00"
#

first shows nice graph but second one shows blocks. l/h is not recognized unit?

inner mesa
#

there are no recognized units, doesn't matter what it is

#

once you add a unit_of_measurement, the old unitless data needs to be flushed out

#

or you can purge it

undone jungle
#

Hi all, I was wondering if there is a simple method for adding a mean/median operation to a template sensor with simple algebraic operations, to receive a 1/10 down sample, or something similar?
I am trying to combine different electrical power measures, to get a better estimate of draw on different circuits, but unfortunately such ratios are very sensitive to desynchronized spikes, which are common in power monitoring.

#

- sensor: - name: Rest power draw state_class: measurement device_class: power unit_of_measurement: W unique_id: rest_power_draw state: "{{ states('sensor.house_power_draw') | int - (states('sensor.dishwasher_socket_power') | int + states('sensor.kettle_socket_power') | int + states('sensor.kitchen_tv_socket_power') | int + states('sensor.master_bedroom_tv_socket_power') | int + states('sensor.office_pc_socket_power') | int + states('sensor.reku_unit_socket_power') | int + states('sensor.server_socket_power') | int + states('sensor.wolf_boiler_socket_power') | int + states('sensor.lg_tv_power') | int + states('sensor.fridge_power') | int + states('sensor.washing_machine_power') | int + states('sensor.garden_pump_power') | int + states('sensor.vyper_3d_printer_power') | int) }}"

silent barnBOT
#

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

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

undone jungle
#

Any ideas??

sonic slate
#

What am I doing wrong in this really simple template? sensor.fridge_duty_cycle is a history_stats sensor configured to ratio. In the template tester in devtools, the tooltip shows the value just fine, but in the template {{ states('sensor.fridge_duty_cycle') | float }} it returns unknown. What am I doing wrong?

sonic slate
#

Nevermind, I borked my templates converting them to the new format. For some reason HA said the configuration was OK, I guess I forgot to save them first.

fiery rock
#

I have two near identical simple templates. One is working fine, the other is throwing an error.
The working one is {{ states.input_number.remote_pulse_time.state | int }} the faulty one is {{ states.input_number.partial_time_set_kitchen_shutters | int }}
The error I get is: Error: ValueError: Template error: int got invalid input '<template TemplateState(<state input_number.partial_time_set_kitchen_shutters=5.0; initial=None, editable=True, min=0.0, max=60.0, step=1.0, mode=box, unit_of_measurement=s, icon=mdi:alpha-p-circle-outline, friendly_name=Partial Time Set, Kitchen Shutters @ 2022-07-21T01:07:32.750320+00:00>)>' when rendering template '{{ states.input_number.partial_time_set_kitchen_shutters | int }}' but no default was specified

inner mesa
#

you're missing a ".state"

#

or really, you're not using states(...) as you should

#

you see that difference, right?

fiery rock
#

Oh man, yeah. Sigh.

#

Thanks. I should really go for a walk or something.

inner mesa
fiery rock
#

Got ya. Pretty new at templates and automation. Probably a good idea to embed the good habits straight of the bat. Cheers.

fiery rock
#

When changing

      milliseconds: '{{ states.input_number.remote_pulse_time.state }}'```
to
```  - delay:
      milliseconds: {{ states('input_number.remote_pulse_time') }}```
it results in the code being changed to 
```  - delay:
      milliseconds:
        '[object Object]': null```
Searching around it feels like I need to use something along the lines of a `data_template:` entry or `value_template:` entry however I've tried a number of different configurations and it always results in the same change to `null`.
inner mesa
#

You're missing quotes around your template

fiery rock
#

Thanks again mate.

heady trellis
#

#templates-archived I see that a lot of people have trouble with nested json . How to use this is documented here: https://www.home-assistant.io/docs/configuration/templating/#processing-incoming-data and thus I concider it as the holy grale. Yet if I try to process this json string {"Time":"2022-07-21T08:32:48","OPENTHERM":{"conn":"FAULT","settings":18,}} as per the manual with value_template: "{{ value_json.Time }}" and value_template: "{{ value_json['OPENTHERM']['settings'] }}" , I get in both cases the state value unknown .
Am I doing something wrong or is there room for improvement in the manual ?

marble jackal
#
{% set value_json = {"Time":"2022-07-21T08:32:48","OPENTHERM":{"conn":"FAULT","settings":18,}} %}
{{ value_json.Time }}
{{ value_json['OPENTHERM']['settings'] }}
#

This works fine for me in devtools >Templates

#

.share the entire yaml using these templates

silent barnBOT
#

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

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

heady trellis
heady trellis
autumn sedge
#

Hey, can I get some help setting a target based on the device that starts a script running?

I have Sonoff NSPanels connected via MQTT, I’ve configured it to run a script to start a playlist on my Sonos speakers in the same room it’s in. That works fine.

However, I have different panels in different rooms with different speakers. I want the same functionality to work without having to recreate the scripts for each room. I need to replace the target speaker based on the specific nspanel that calls the script.

Eg in the lounge, I want it to play on media_player.lounge_sonos, but in the kitchen I want it to play in media_player.kitchen_sonos

I can’t even work out how to detect which nspanel has called the script, the logbook just say β€œsupervisor”.

Thanks in advance!

mighty ledge
marble jackal
#

I thought so as well, but then I thought he might wat the "on" value instead of true

mighty ledge
#

{{ x if bool(x, none) is boolean else none }} is literally identical to {{ x | bool(none) }}

#

on will be converted to a boolean

#

because that's what bool() does

marble jackal
#

{{value if value|bool is boolean else none}} this will return "on" if value is "on"

#

and none if value is "unavailable"

mighty ledge
#

yeah but the templates for binary_sensors accept true as on

marble jackal
#

okay, true, I only looked at this template

#

should have looked at how he used it in the post after that πŸ˜›

mighty ledge
#

MQTT is unique in that you can assign what on/off means with payload on/off

#

so maybe he didn't set those and left them to default

marble jackal
#

because that makes {{ value | bool(none) }} perfectly fine

mighty ledge
#

which I think is 'on' or 'off'

#

Ah, yes, he left payload_on and off as 'on' or 'off' instead of True/ False

marble jackal
#

I don't use MQTT myself, so that's a bit of a blank spot for me πŸ™‚

mighty ledge
#

he can just remove the quotes from on and off and change the template

#

it's easy, you'd pick it up in 5 minutes

#

it's all documentation

#

I helped people for 3 years before actually using it myself

#

99% of questions for that integration can be solved with the docs

marble jackal
#
        payload_on: 'on'
        payload_off: 'off'

There's no Chinese in this indeed

mighty ledge
#

when people say the docs aren't good enough, they just don't understand the docs

#

Yeah, that's why he needed that verbose statement

#

so if he changes that to

        payload_on: on
        payload_off: off
#

or

#
        payload_on: true
        payload_off: false
#

then {{ value | bool(none) }} would be all he needs

#

that's the only binary_sensor platform that doesn't default true/false meaning on/off

#

that uses templates, so keep that in the back of your mind

#

also, removing the quotes from on/off in yaml change the field to a boolean that resolves to true or false

#

that's why quotes are needed when checking for on/off states everywhere

#

because yaml naturally converts them when they don't have quotes

marble jackal
#

understood!

tired gyro
#

Is there a built-in function or filter to determine the most frequent element in a list -- sort of like Python Counter's most_common() function?

#
Output : Dog```
#

I'm trying to create a template room presence sensor that combines data from three ESPresense mqtt_room sensors (an Apple Watch and two iPhones), and if two of the three sensors report the same state, I would like the template sensor to have that state, or if they all report different states, default to the state reported by the Apple Watch.

mighty ledge
#
{% set items = ['a', 'a', 'd', 'a', 'c' , 'b', 'b', 'a', 'd' ] %}
{% set ns = namespace(most_common={'item':none,'count':none}) %}
{% for item in items | unique %}
  {% set cnt = items | select('eq', item) | list | length %}
  {% if ns.most_common.item is none %}
    {% set ns.most_common = {'item':item,'count':cnt} %}
  {% elif cnt > ns.most_common.count %}
    {% set ns.most_common = {'item':item,'count':cnt} %}
  {% endif %}
{% endfor %}
{{ ns.most_common.item }}
tired gyro
prisma rivet
#

Hey guys i need some help to understand how to name files (images) by the source.

https://pastebin.com/t1xQkJ4H



2022-07-21 14:43:05 ERROR (MainThread) [homeassistant.components.automation.new_automation_2] Snapshot_TEST: Error executing script. Error for call_service at pos 1: Error rendering data template: UndefinedError: 'entity_id' is undefined


2022-07-21 14:43:05 ERROR (MainThread) [homeassistant.components.automation.new_automation_2] Error while executing automation automation.new_automation_2: Error rendering data template: UndefinedError: 'entity_id' is undefined```
#

The concept is working on my old installation but now when migrating to a less FUBAR installation it refueses to work 😦

#

this works on old installation

      - entity_id: camera.house_mainprofile
    file_out:
      - "/config/www/{{ camera_entity.split('.')[1] }}_latest.jpg"
      - "/config/www/images/{{ camera_entity.split('.')[1] }}_{{ now().strftime('%Y%m%d_%H%M%S') }}.jpg"
floral shuttle
#

it renders all mqtt sensors unknown.

#

also, I read your posts about changing payload, but its not for me to change that, its what the source publishes, so I am following that

mighty ledge
#

change your payload

#

ah ok

floral shuttle
#

but just to be sure, I tried what you suggested anyway. Unfortunately that renders 'unknown' too, so there's no choice in the payload.

marble jackal
# mighty ledge no easy way to do taht

This also works πŸ™‚

{% set items = ['a', 'a', 'd', 'a', 'c' , 'b', 'b', 'a', 'd' ] %}
{% set ns = namespace(most_common={'item':none,'count':none}) %}
{% for item in items | unique %}
  {% set cnt = items | select('eq', item) | list | length %}
  {% if loop.first or cnt > ns.most_common.count %}
    {% set ns.most_common = {'item':item,'count':cnt} %}
  {% endif %}
{% endfor %}
{{ ns.most_common.item }}
marble jackal
marble jackal
#

more filters, more fun is what I always say

marble jackal
thorny snow
#

Hey all πŸ™‚ question about input Boolean, so it’s kinda switch that gets flipped when the event happens, and then can be used in an automation. Ok so I got that far ( thanks @ Rosemary Orchard#7195 ) I’ve added the toggle in helpers menu. But like how to add info to it ? How to work with it ? In helpers section I could only add two things, name and icon…

#

If that helps the first thing is to get it to toggle when a device tracker enters a zone

marble jackal
#

You can manually toggle it, or toggle it in an automation to indicate something happened

thorny snow
#

So i have to create automation with it first ? so its like an empty shell, and only then i can use it in the main automation ?

marble jackal
thorny snow
#

πŸ˜„ i just came up with that while cooking πŸ˜„

#

ok, what # would it be ? πŸ™‚

marble jackal
thorny snow
#

It was just about understanding Boolean πŸ™‚

marble jackal
#

I guess yeah

#

Not that there is much to understand, it's a toggle which can be on or off and will do nothing on its own

thorny snow
#

Well I thought it’s like a ready to use toggle, and I didn’t knew that I have to make an automation to use it πŸ™‚ that was the problem here πŸ™‚

zenith rain
#

Anyone has a template that sends a notification every time any of the moisture sensor i have triggers?

marble jackal
#

Seems, more of an #automations-archived thing. If you use a state trigger you can use {{ trigger.to_state.name }} to get the name of the entity which triggered the automation

zenith rain
#

Moving it

prisma rivet
# marble jackal ```yaml alias: Snapshot_TEST description: '' trigger: - platform: state en...


2022-07-22 11:19:39 ERROR (MainThread) [homeassistant.components.automation.snapshot_test] Snapshot_TEST: Error executing script. Error for call_service at pos 1: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'


2022-07-22 11:19:39 ERROR (MainThread) [homeassistant.components.automation.snapshot_test] Error while executing automation automation.snapshot_test: Error rendering data template: UndefinedError: 'dict object' has no attribute 'to_state'```
deft timber
#

@simple edge :

{% set val= {"living_room": 10, "family_room":17} %}
{{ val["family_room"] }}
marble jackal
prisma rivet
#

i did a manual tricker and just read the a thread a bout manual triggering πŸ˜„

#

so just putting on my outdoor feet to test it out πŸ˜„

marble jackal
#

there is no no trigger then, so the trigger variables are not available

prisma rivet
#

thanks a milion!

earnest cosmos
#

Hi, all! I am using the Met.no Nowcast integration for weather, and defining a sensor for temperatureand humidity is working fine using
state_attr('weather.met_no_nowcast_buskogen', 'temperature').
Now, I want to define a sensor telling me if itΒ΄s any precipitation going on, but as you see below, this value is listed in an other way. How would i read values under the forecast: section?

temperature: 15.1
humidity: 91
...
precipitation_unit: mm
forecast:
  - temperature: 15.1
    precipitation: 4.5