#templates-archived

1 messages · Page 6 of 1

marble jackal
#

Okay, and when you check devtools > states, that sensor actually exists and has a valid state?

#

It could also be the working version now has _2 added

rancid pelican
#

Hi Guys.
i want to make a automation that will make some kind off value template
in that i need to work with with the now time.
i used cod but no sucess
{% set start_time = (state_attr('input_datetime.followers_start_time', 'timestamp')|int ) %}
{% set now_time = (state_attr('sensor.time', 'timestamp') |int ) %}
{% set runned_time = (now_time - start_time) %}
{{ runned_time | timestamp_custom('%H:%M') }}
can someone help me??

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
rancid pelican
#

'''

#

'''

marble jackal
#

You can perform the tests in #botspam

rancid pelican
#

here is my example

#
    action:
      - service: input_datetime.set_datetime
        entity_id: input_datetime.followers_runned_time_since_start
        data_template:
          time: >
            {% set start_time = (state_attr('input_datetime.followers_start_time', 'timestamp') | int ) %}
            {% set now_time = (state_attr('sensor.time', 'timestamp') | int ) %}
            {% set runned_time = (now_time - start_time) %}
            {{ runned_time | timestamp_custom('%H:%M') }}
marble jackal
#

This should do the trick
{{ (now() - states('input_datetime.followers_start_time') | as_datetime | as_local).time() }}

#

Corrected above

rancid pelican
#

i will try

gentle zealot
#

i looked over the derivative sensor i may try that also. I noticed my 10 minutes ago sensor is not showing but my 24 hour ago sensor is working. i am not sure what is different i need to dig a little deeper.

    - name: Rain 10 Minutes Ago
      unit_of_measurement: in
      value_template: "{{ value | float }}"
      group_function: first
      measurement: '"autogen"."in"'
      field: '"value"'
      where: 'time > now() - 10m AND "entity_id"=''atlas_rain'''
    - name: Rain 24 Hours Ago
      unit_of_measurement: in
      value_template: "{{ value | float }}"
      group_function: first
      measurement: '"autogen"."in"'
      field: '"value"'
      where: 'time > now() - 24h AND "entity_id"=''atlas_rain'''
marble jackal
rancid pelican
#

AttributeError: 'NoneType' object has no attribute 'tzinfo'

marble jackal
#

Replace it with your input_datetime

rancid pelican
#

@marble jackal

#

one more help??

marble jackal
#

Quick then 😉

rancid pelican
#
    action:
      - service: input_datetime.set_datetime
        entity_id: input_date.followers_position_requested
        data_template:
          numeric: >
            {% set time_now = (state_attr('input_datetime.followers_runned_time_since_start', 'timestamp') | int ) %}
            {% set time_move = (state_attr('input_datetime.followers_movements_time', 'timestamp') | int ) %}
            {% set step_pos = (time_now / time_move) %}
            {{ step_pos }}
#

i Want that division of the times give-me a numeric value

#

is taht wiat the correct?

#

is that way correct?

marble jackal
#

data_template has been depreciated for over two years, you can just use data:

#

And numeric is not valid for an input datetime

rancid pelican
#

i changed to number

#

but contiouns not working

marble jackal
#

Also number is not valid, should you not use an input_number here

#

An input datetime expects a date, a time, or both

rancid pelican
#

maybe i dont tell you right what i want

#

i have two input_datetime that i want divide to get a numeric value

inner mesa
#

You're just not following the docs for that service call

silent barnBOT
rancid pelican
#

@inner mesa Hi

#

maybe that work

inner mesa
#

There's no 'numeric' or 'number' in there as a parameter

rancid pelican
#
service: input_number.set_number
entity_id: input_number.followers_position_requested
data:
  number: >
    {% set time_now = (state_attr('input_datetime.followers_runned_time_since_start', 'timestamp') | int ) %} 
    {% set time_move = (state_attr('input_datetime.followers_movements_time', 'timestamp') | int )%}
    {% set step_pos = (time_now / time_move) %} 
    {{ step_pos }}
#

what you think?

inner mesa
#

I think you are now not following the docs for an inout_number

#

You are making things up

rancid pelican
mighty ledge
silent barnBOT
marble jackal
#

The bot didn't warn you for no reason, now you edited the wall of text back in

silent barnBOT
#

[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).

marble jackal
#

You are using an average filter on an empty list

#

That's where this error comes from fmean requires at least one data point

opaque marlin
#

What is the best way to do math a math operation based on values received by multiple sensors and then pushed back out to a new sensor?

I assume a template sensor, but I am having some trouble doing the kind of operations I want to within the constraints of my understanding of Jinja templates. Namely setting the value of a variable to the value of one sensor and then using that variable in a function

jagged obsidian
#

{% set val = sensor_id %}

#

sensor_id being one of state... options explained in templating docs

#

Template preview in dev tools is your best friend here

opaque marlin
# jagged obsidian `{% set val = sensor_id %}`

Thank you that helps a lot. I had the set in the wrong place. Still getting a "unknown tag low_temp. was looking for elif, else, or endif"

                     {% for i in range(1,24) %}
                     {% if  (state_attr('weather.openweathermap', 'forecast')[i].temperature) <= low_temp %}
                     {% low_temp = (state_attr('weather.openweathermap', 'forecast')[i].temperature) %}
                     {% endif %}
                     {% endfor %}```
jagged obsidian
#

set low_temp

#

Same way you set it in the first line

opaque marlin
#

oof dumb
Thank you

jagged obsidian
#

Not sure why you reuse the same variable name

opaque marlin
#

I am trying to find the lowest in an array of 20

#

So I need a starting value (index 1) and then if there is something lower, set low_temp to the value of that index, and if its not, keep checking

#

Hmm... yeah that just returns the value of index 1

                     {% for i in range(1,24) %}
                     {% if  ((state_attr('weather.openweathermap', 'forecast')[i].temperature) <= low_temp) %}
                     {% set low_temp = (state_attr('weather.openweathermap', 'forecast')[i].temperature) %}
                     {% endif %}
                     {% endfor %}
                     {{ low_temp }}```
jagged obsidian
#

I usually run some "debugging prints" by displaying values mid function to see what happens

opaque marlin
#

Alright yeah adding some prints shows that the value is set properly in the if statement, but is not returned outside of the if statement. If I print low_temp inside the for statement before the if, its just always equal to index 1

#

Okay this doesnt work in python either so I am clearly goofing up

inner mesa
#

the problem is the for loop. You need to use a namespace to access a variable you set within the loop outside it

#

something like:

{% set ns = namespace(low_temp = 0 %}
...
{% set ns.low_temp = xxx %}
...
{{ ns.low_temp }}
opaque marlin
#

Just to confirm, the following will just return the value of ns.low_temp to the template sensor correct?

        value_template: " {% set ns = namespace(low_temp = 0) %}
                          {% set ns.low_temp = (state_attr('weather.openweathermap', 'forecast')[1].temperature) %}
                          {% for i in range(1,24) %}
                          {% if  ((state_attr('weather.openweathermap', 'forecast')[i].temperature) <= ns.low_temp) %}
                          {% set ns.low_temp = (state_attr('weather.openweathermap', 'forecast')[i].temperature) %}
                          {% endif %}
                          {% endfor %}
                          {{ ns.low_temp }} "```
marble jackal
#

@opaque marlin Yes, but with a template like that I would use the multi line format

#
forecast_low:
  value_template: >
    {% set ns = namespace(low_temp = 0) %}
    {% set ns.low_temp = (state_attr('weather.openweathermap', 'forecast')[1].temperature) %}
    {% for i in range(1,24) %}
      {% if  ((state_attr('weather.openweathermap', 'forecast')[i].temperature) <= ns.low_temp) %}
        {% set ns.low_temp = (state_attr('weather.openweathermap', 'forecast')[i].temperature) %}
      {% endif %}
    {% endfor %}
    {{ ns.low_temp }}
marble jackal
#

I would also change it a bit:

forecast_low:
  value_template: >
    {% set ns = namespace(low_temp = 0) %}
    {% for item in state_attr('weather.openweathermap', 'forecast') %}
      {% if loop.first or item.temperature) <= ns.low_temp %}
        {% set ns.low_temp = item.temperature) %}
      {% endif %}
    {% endfor %}
    {{ ns.low_temp }}
#

On second thought, you could use simply this:
{{ state_attr('weather.openweathermap', 'forecast') | map(attribute='temperature') | min }} }}

foggy monolith
#

Hi. Can someone say, whats wrong with this code?

#

- name: "Wetterstation Solarspannung" unique_id: "wetterstation_solarspannung" unit_of_measurement: "V" icon: mdi:solar-power state: "{% if state_attr('sensor.0x00124b000cb0d756_l1', 'device_l1') == "40-01" %} {{ state_attr('sensor.0x00124b000cb0d756_l1', 'voltage_l1') }}" {% endif %}

inner mesa
#

Many things

fossil venture
#
        state: >
          {% if state_attr('sensor.0x00124b000cb0d756_l1', 'device_l1') == "40-01" %}
            {{ state_attr('sensor.0x00124b000cb0d756_l1', 'voltage_l1') }}
          {% else %}
            What do you want here? When device l1 is not 40-01
          {% endif %} 
foggy monolith
#

Okay. The code works now, but my idea how to differentiate two values on the same attribute wont.

nocturne chasm
#

i have a script i use to turn on random lights. After the script runs, i use this to tell me which lights are on:

#

{{ dict((states|selectattr('entity_id', 'in', state_attr('group.inside_switch_card_2', 'entity_id')))|groupby('state'))['on']|map(attribute='name')|list }}

#

i have a similar script that turns lights off and a similar notification that tells me which lights are on. if all the lights are off, i get a template error. Is there any way in a script to tell which lights were recently turned off? Like a trigger to state for scripts?

mighty ledge
#

Remove the dict and groupby, use selectattr instead

#

Actually, that whole thing is poorly optimized and it’s throttled to 1 update per minute

#
{{ expand('group.inside_switch_card_2') | selectattr('state', 'eq', 'on') | map(attribute='name') | list }}```
nocturne chasm
#

auh, thanks for that.

#

{{ expand('group.inside_switch_card_2') | selectattr('trigger.to.state', 'eq', 'off') | map(attribute='name') | list }}

#

so would that work?

marble jackal
#

That would return the name of all entities in that group which have the state off

#

Wait, you need to change trigger.to.state with 'state:

#

You can replace 'off' with trigger.to_state.state if that is what you want

nocturne chasm
#

trying to fix this issue

#

{{ expand('group.inside_switch_card_2') | selectattr('state', 'eq', 'trigger.to.state.state') | map(attribute='name') | list }}

inner mesa
#

Don't quote variables

nocturne chasm
#

so no quotes around trigger.to.state.state ?

desert plover
#

here again, because my automation question was better suited here (sry for missposting in wrong channel :()

I have a variable that contains time with seconds and I want to get rid of the seconds => 1:50:32 should be 1:50 only

How can I do that with my automation that got a notification with {{ states('sensor.time_remaining') }} ?

indigo haven
#

as I was saying in #automations-archived
Trying to increment the value of a sensor in a bulb's brightness
I did a template like this:

brightness: >- {{states.light.luz_balcao.attributes.brightness + int(states('sensor.tuyaknob_action_step_size'), 0)}}

but it still doesnt work, I think the issue is that the value sensor.tuyaknob_action_step_size is back to None by the time the service runs.

#

So I guess I need to retain the value somewhere?

indigo haven
#

I need to figure out how to retain the value

#

I think I had an idea

I will create another sensor that retains its the value of other one as long as the value is not none

sensor:
  - platform: template
    sensors:
      knob_last_step_size:
        friendly_name: "TuyaKnob Last Step"
        value_template: "{{ state_attr('sensor.tuyaknob_action_step_size', 'action step size') not in ['None'] }}"
#

I think this is the way

#

ah this is returning a boolean uhhhh

#

What do I have to return in the value_tempalte so that the value is ignored

desert plover
violet tinsel
#

I'm new to template switches. Can I just start using them in my button-card or do I need to do something to enable them elsewhere first?

#

I see in the documentation that something needs to be added to configuration.yaml but it looks very specific.

inner mesa
#

This:

I see in the documentation that something needs to be added to configuration.yaml but it looks very specific.

violet tinsel
inner mesa
#

You need to define each template switch, yes

#

How else?

marble jackal
violet tinsel
inner mesa
#

No, it's defining the state of the switch

violet tinsel
#

Of the template switch, not the switch of the device, right?

inner mesa
#

Everything is about the template switch.

#

That is what you're defining

violet tinsel
#

Okay. And sensor.skylight is the actual device?

inner mesa
#

I don't know what you mean

#

Is it a device?

violet tinsel
#

That's the one in the example of the documentation.

#

I'm using my motion sensor for this.

#

So I thought it would be switch.hue_motion_sensor instead.

inner mesa
#

Your motion sensor is unlikely to be a switch

violet tinsel
#

I'm using it's on/off state for detecting motion.

inner mesa
#

Still not a switch

violet tinsel
#

What would it be?

inner mesa
#

What is it?

violet tinsel
#

I suppose I can find out.

inner mesa
#

Yes

violet tinsel
#

Let me look.

#

I can't upload the image here.

#

But under configuration, there is a switch called Motion.

#

And it's entity ID is switch.hue_outdoor_motion_sensor_1_motion

#

When I turn it off, my motion sensor won't detect motion.

#

And that's what I'm turning on and off in my button-card.

inner mesa
#

ok

#

so it's not actually an indication of whether the motion sensor is detecting motion, but whether or not it should be active

rare linden
#

what would be the correct syntax for this be? entity_id: "input_number.{{ area_id(trigger.entity_id) }}_light" as that doesnt seem to work

inner mesa
#

"doesn't work"?

#

I wish that everyone stating that provided a better explanation

rare linden
#
action:
  - service: input_number.set_value
    data:
      value: "{% if is_state(trigger.entity_id, 'on') %}128{% else %}0{% endif %}"
    target:
      entity_id: input_number.{{ area_id(trigger.entity_id) }}_light
inner mesa
#

still, what "doesn't work" about it?

#

not gonna just guess

rare linden
#

it doesnt set the number on the entity

violet tinsel
inner mesa
#

you're adding "input_number." onto a full entity_id that probably already contains it, but you're still only providing a partial snippet of your autiomation

#

more guessing

rare linden
#

how is it being added to a full entity id?

#

it's getting the area_id

inner mesa
#

it's not, I'm wrong

#

I suspect that you don't actually want "area_id" there, which is some long random string

#

you probably wanted "area_name"

marble jackal
#

No, if you've set up your areas less then maybe a year ago, they are actually meaningful

rare linden
#

is the result of area_id not the lower cased version of area_name? as it works when passing it into my script that takes the area_id in the format of kitchen living_room etc

marble jackal
#

Slugified versions of the name

inner mesa
#

ok, mine aren't

marble jackal
#

They used to be random ids like device ids

inner mesa
#

{{ area_id('switch.fr_reading_lamp') }} -> e195927a039b4c2fa712c58b864daf4b

marble jackal
#

I recreated them because of that

inner mesa
#

but I probably set them up a while ago

marble jackal
#

What does the trace show?

rare linden
#

it shows in the gui that it does call the service

marble jackal
#

Yes, with none as area_id

#

Looks like the motion sensor is not added to the area

#
"entity_id": [
                  "input_number.none_light"
                ]
rare linden
#

yeah that was it, I thought i had added them all earlier

#

thanks

violet tinsel
#

Is there a way to modify the configuration.yaml file from the Home Assistant web interface?

marble jackal
rare linden
violet tinsel
inner mesa
#

no, HACS has nothign to do with addons

violet tinsel
#

The alternative is to just access it via Terminal, I suppose?

marble jackal
#

You can use VSCode and create a connection using ssh

violet tinsel
#

I have HAAS running inside a docker container on Unraid.

marble jackal
violet tinsel
#

Since I don't know much about them, I figured this might be helpful.

inner mesa
#

no idea

#

here's a version of the solution that I've been recommending:

violet tinsel
#

Okay, that helps to visualize.

#

So turn_on: is indicating what happens if I turn on that switch?

#

And turn_off: the inverse.

inner mesa
#

yes

violet tinsel
#

Or instead of turning the switch on via my button-card, I call this template?

inner mesa
#

which is a switch

violet tinsel
#

Got it!

#

So my switch would be switch.copy in this example?

inner mesa
#

?

#

oh, yeah, that was from the docs

#

I didn't change the name

violet tinsel
#

So whatever the switch is named, I call that switch and turn it either on or off?

inner mesa
#

use the toggle action

violet tinsel
#

Okay.

#

I'll try putting it together.

violet tinsel
#

There it is with toggle.

#

I noticed that the color doesn't actually change anymore based on state (but it does stay blue for on).

#

Should I tie the state to the actual device switch?

inner mesa
#

the switch should already do that

violet tinsel
#

Hmm, let me check again.

inner mesa
#

that was the whole previous discussion

violet tinsel
#

I might have done something wrong then.

#

I checked the log book and it's not actually toggling the device or setting the datetime.

inner mesa
#

was the switch created? did you actually create the input_datetime?

violet tinsel
#

I put the switch in configuration.yaml.

#

Then I restarted the docker container.

inner mesa
#

that was more than needed, but the questions remain

#

and it sounds like you didn't check your config first, either

violet tinsel
#

The input_datetime needs to be created as a helper?

inner mesa
#

yes

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

inner mesa
#

BTW, there was an automation in there as well, so if you just slapped the whole thing in configuration.yaml, that won't go well

violet tinsel
#

Nah I only put the switch lol

#

Okay, that fixed the datetime issue.

#

It is not changing the state of the switch, though.

inner mesa
#

oh, I missed that

violet tinsel
#

I think I need to add that as part of the turn_on and turn_off, right?

inner mesa
#

the turn_off part

#
        turn_off:
          - service: input_datetime.set_datetime
            target:
              entity_id: input_datetime.motion_sensor_on
            data:
              datetime: "{{ now() + timedelta(minutes=30) }}"
          - service: switch.turn_off
            entity_id: switch.hue_outdoor_motion_sensor_1_motion
#

for the turn_on part, I'm just setting the input_datetime to 1 second in the future and let the automation do it

violet tinsel
#

The automation is giving me an error: "Message malformed: extra keys not allowed @ data['entity_id']"

#
alias: Front Patio (L) Motion Sensor On
trigger:
  platform: time
  entity_id: input_datetime.family_room_l_motion_on
condition: []
action:
  service: switch.turn_on
  entity_id: switch.hue_outdoor_motion_sensor_1_motion
inner mesa
#

oh, my fault. the trigger should use "at:"

#
trigger:
  platform: time
  at: input_datetime.family_room_l_motion_on
violet tinsel
#

@inner mesa Awesome! It works. Thank you so much for all of your help.

#

It's nice to actually understand how this functions now.

#

I'll try my hand at the input_boolean as well so that it doesn't run twice when I manually turn it back on.

inner mesa
#

yeah, that's a bit of a hack. You don't want the automation to run in 30 mins if you already turned it on, mainly because you could have turned it off outside of HA and want it to stay that way

violet tinsel
#

Yeah.

#

So just add the input_boolean as a condition to the automation, correct?

inner mesa
#

you could set the input_datetime in the past (1 second, 1 minute, whatever)

#

and then just turn it on in the turn_on: part

#

that's easier than maintaining a helper

violet tinsel
#

Ah, okay.

#

@inner mesa Is input_boolean.turn_off a valid service?

inner mesa
#

only one way to find out

silent barnBOT
violet tinsel
#

Ah, it is. Thank you!

violet tinsel
#

@inner mesa It looks like I actually don't need to make any modifications.

#

If I turn it off, turn it back on, then turn it off again, it waits the full duration before turning it on again.

#

It doesn't just wait the time from the first turn off.

inner mesa
#

right, there was nothing wrong with what I provided

violet tinsel
#

Oh, silly me.

inner mesa
#

you just didn't like it 🙂

violet tinsel
#

No, I do haha. I just didn't realize it would work that way.

#

I was under the impression that once the automation was triggered, you'd have to expressly stop it.

#

But now I'm realizing the automation doesn't trigger until the datetime reaches the stated time.

inner mesa
#

there's nothing there that keeps running

violet tinsel
#

So if you change it midway, the automation never ran to begin with.

#

So it'll just keep delaying it's start.

#

Yeah, okay.

#

Woo! Thank you so much for all the learning lol

#

This'll be really helpful when I go to create other automations.

violet tinsel
#

@inner mesa I've duplicated the first template for the other two. Now I'm having a strange issue. One of the copies I made worked, the other wasn't showing up as a switch. Then I tried commenting out the one that worked, and it was still working.

#

I restarted Home Assistant each time.

inner mesa
#

No idea

#

Sounds like you have a formatting issue, and I suspect that HA didn't actually restart because of it

violet tinsel
#

Oh

#

YAML file /config/configuration.yaml contains duplicate key "switch". Check lines 18 and 58

#

I thought switch: was generic.

inner mesa
#

You can only have and only need one switch:

still surge
#

hi to all, someone can help me with a variable? in a script i'm declaring a variable with value retrieved from a state (alexa volume level, decimal value between 0 and 1)

#

in script trace, i see variable's value sets right, but when i call variable, to re-set alexa's volume to variable's value, it's looking for a float value, and it's not working

#

i try to post just few lines there

#

the error is " Error rendering data template: AttributeError: 'float' object has no attribute 'lower'"

#

(now is different, proablyy due to contrent tryes!

#

variable's value seems ok

silent barnBOT
#

@still surge Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.

still surge
#

solved!

#

volume_level: "{{prev_vol}}"

nocturne chasm
#

still trying to figure out how i can change this from all the lights that are on to lights that just turned off
message: "Random light turned off - {{ expand('group.inside_switch_card_2') | selectattr('state', 'eq', 'on') | map(attribute='name') | list }}"

#

in a script so it doesnt have a trigger

unreal merlin
#

Howdy 🙂

nocturne chasm
#

something like last_changed <= 5

unreal merlin
#

this is very interesting - what am I not seeing here?

{% set d=expand(integration_entities('plex'))|selectattr('state', 'in', ['playing', 'paused'])%}

{{ d|list|count }}
{{ d|list|count }}

The output is:

1
0
weary drift
#

Hello,
I've got this template which gets the three cheapest hours of electricity from the sensor. The sensor have an attribute with raw_today: which have value. This works fine! There's also raw_tomorrow in the sensor which i would like to include in this. How would i add it?

    value_template: >-
      {% set l=state_attr('sensor.nordpool', 'raw_today')|sort(attribute='value') %}
      {{ (now() >= l[0].start and now() <= l[0].end)
      or (now() >= l[1].start and now() <= l[1].end)
      or (now() >= l[2].start and now() <= l[2].end) }}   
nocturne chasm
inner mesa
#

Pfft

rose scroll
weary drift
rose scroll
#

Ah so try concatenating the raw_today and raw_tomorrow lists, and then sort the resulting concatenated list. Should be able to do it with something like set l = (state_attr('sensor.nordpool','raw_today') + state_attr('sensor.nordpool','raw_tomorrow'))

weary drift
winter cape
#

Hi, I have this template, which I want to send to mobile when leaving. How to make "normal" text from it?

silent barnBOT
winter cape
#

In Developer tool it looks like that, but I would like: Pere pračka or Běží myčka a pere pračka or 4 okna jsou otevřena, pere pračka a běží myčka....

#

`4 okna jsou otevřena

    běží myčka
    
    
    
    pere pračka`
inner mesa
#

So you want 'elif'?

winter cape
#

Yes, I need only information what is on...

inner mesa
#

You just have a sequence of if statements

winter cape
#

And is another way how to do it?

inner mesa
#

You're checking if they're off

#

do you want to know if they're "on" or "off"?

winter cape
#

On.... when I hold switch, television, pc and other goes to off. This I need only for information - about windows, dishwasher.... which is usually not a problem when its on

inner mesa
#

then why are you checking if they're off?

winter cape
#

oh, sorry, its only for test in developer tools.. normally is in template on

nocturne chasm
inner mesa
#

I had just finished arduously typing that on my phone when you said "nevermind!" 🙂

inner mesa
#

with your logic, if they're all "off", it will print all three

#

what did you want?

nocturne chasm
#

its a script that just randomly turns off lights while we are on vacation. just trying to get notifications of whats going on to confirm things are working

#

in the beginning imwas showing lights on after i turned one off, but if they are all off it would error

winter cape
#

I would like to have a normal sentence. With a capital letter at the beginning, with a dot at the end.

inner mesa
#

since I can't read whatever language that is, it's hard for me to figure out what you want

#

but again, I've described what your logic will do. What do you actually want?

#

do you want it to print all three if all are "off"? Only some of them?

winter cape
#

Understand 🙂 sorry.... now its look like 4 windows are open dishwasher is on washing machine is on

inner mesa
#

and... what do you want?

winter cape
#

I want to print .... 4 windows are open (if are) and dishwasher is on. ( if is ).... or Dishwasher is on, washing machine is on and ......

#

I dont have problem with sensors, only with format of print

inner mesa
#

making these things grammatically correct is challenging and very language-specific

#

you seem to have a command of "if" statements, so you construct it with that

winter cape
#

Understand.... template is in my local language, its not problem.... only with capital letters at the begin , dot at the end...

#

its variable

nocturne chasm
#

TypeError: 'datetime.timedelta' object is not iterable

inner mesa
#

this is an example in English:

{% set data = ["foo", "bar"] %}
{% if data|length < 3 %}
{{ data|join(' and ') }}
{% else %}
{{ data[:-1]|join(', ') }}, and {{ data[-1] }}
{% endif %}
winter cape
#

Thanks, I'll give it a try.

inner mesa
#

better:

{% set data = ['foo', 'bar'] %}
{{ data[0]|title }}
{%- if data|length < 3 -%}
{{ ' and ' ~ data[1] }}
{%- else -%}
{{ ', ' ~ data[1:-1]|join(', ') }}, and {{ data[-1] }}
{%- endif -%}
.
#

this is just an exercise in playing with it in the template editor until you get what you want

#

this works well enough for me

winter cape
#

but I dont know how to add data/list from my sensors....

inner mesa
#

ok

#

I'm done with this

#

it's all straightforward from that example

winter cape
#

Ok, thank you

weary drift
jagged obsidian
#

is there a simple filter to turn f.e. "Name With Spaces" into name_with_spaces or is lower and replace the only way?

inner mesa
#

|slugify

weary drift
marble jackal
#

[2:8]

weary drift
#

I think i got it. I'm sorry if it's horrible :P. This get the five cheapest hours between 20:00 and 07:00 (rows 20:31).

    value_template: >-
        {% set l=state_attr('sensor.nordpool_kwh_se3_sek_3_10_025', 'raw_today') %}
        {% set g=state_attr('sensor.nordpool_kwh_se3_sek_3_10_025', 'raw_tomorrow') %}
        {% set v = l + g  %}
        {% set h =  v[20:31] | sort(attribute='value')%}
        {{ (now() >= h[0].start and now() <= h[0].end)
        or (now() >= h[1].start and now() <= h[1].end)
        or (now() >= h[2].start and now() <= h[2].end)
        or (now() >= h[3].start and now() <= h[3].end)
        or (now() >= h[4].start and now() <= h[4].end)}}
leaden perch
#

Coming back to this old conversation since my solution wasn't working. My understanding currently is that availability templates make sure the sensor goes unavailble when the original sensor goes unavailable, which is not what I want. I want my template sensor to be the last known value before the original sensor went unavailable.

#

At this point I'm almost starting to think what I would like to do is impossible

#

Although it seems like it should be so simple lol

marble jackal
rare linden
#
- name: Occupied (Bedroom)
  device_class: presence
  state: >
    {{
        is_state('binary_sensor.motion_bedroom', 'on') or
        (now() - states.motion_bedroom.last_changed).seconds < 5
    }}
  icon: >
    {% if is_state('binary_sensor.occupied_bedroom', 'on') %}mdi:bed-queen{% else %}mdi:bed-queen-outline{% endif %}

Can anyone see anything wrong with this? developer tools shows as unavailable, my one for the living room which is almost identical shows as on but kitchen and hallway also show unavailable all pretty much identical, the only real difference is I am in the living room currently

marble jackal
#

You are missing binary_sensor in the second part of the template

marble jackal
rare linden
#

Yep that was it, thanks

marble jackal
rare linden
#

remove that and replace with delay_off i imagine is the better solution

marble jackal
#

Yep

chilly locust
#

So I just found out there's a new, modern template setup and I want to start to transition over to it, but I can't get an attribute setup correctly. This displays the attribute, but the value is "null". https://hastebin.com/ulugugatin.less

inner mesa
#

It sounds like one or both of the entities is not a number

marble jackal
#

Seems you indeed missed the new, modern template to get a state

inner mesa
#

And specify defaults

marble jackal
#

(which was introduced before I started using templates)

inner mesa
#

It was carved on a stone tablet discovered around 2017

marble jackal
#

Ah, that's even before I started to use Home Assistant (well at least the attempt that succeeded)

#

Instead of rounding to 0 digits in combination with floor you can also do an integer division

#

@chilly locust here you go

template:
  - sensor:
      - name: "Pregnancy Week New"
        unit_of_measurement: "weeks"
        state: "{{ states('sensor.pregnancy_days') | int // 7 }}"
        availability: "{{ states('sensor.pregnancy_days') | is_number }}"
        attributes:
            days_in_week: "{{ states('sensor.pregnancy_days') | int) % 7 }}"
formal frigate
#

My brain is too fried from the day, but this page should have the answers for your multi-line issue

young lake
#

Thanks, mate.

#

Looking for help with a template variable in an automation.

#

I've played around with several iterations of this but I can't figure out why I'm getting an error.

#

This seems to be the problematic code:

notification_message: >-
"{% if is_state_attr('trigger.to_state.entity_id','friendly_name')%}
{% state_attr('trigger.to_state.entity_id','friendly_name') %}
{% else %}
Walter
{% endif %}
is in range!"
inner mesa
young lake
#

It throw the error: "expecting an 'else', 'elif', or 'endif' for the line with state_attr in it.

#

Is there another way to template the return value for the if statement?

rare linden
#

when creating a binary sensor can you define the area directly? instead of assigning a unique id then changing it in the gui? cant find any documentation on it

inner mesa
#

I don't think so

rare linden
#

Thats sucky, thanks

young lake
young lake
#

Update from using the template editor:

This seems to be correct syntatically:

"{% if is_state_attr('trigger.to_state.entity_id','friendly_name') %}
   {{ state_attr('trigger.to_state.entity_id','friendly_name') }}
{% else %}
Walter
{% endif %}
is in range!"
#

But the if conditional statement throws the following error:

TypeError: is_state_attr() missing 1 required positional argument: 'value'
inner mesa
#

there are many things wrong with it

#

first, you're surrounding the thing in quotes. remove them

#

second, you're surrounding the variables in quotes (like trigger.to_state.state). remove them

#

third, you need to indent your template

#

fourth, is_state_attr() takes three parameters and you've only provided 2

#

there may be more

young lake
#

Beautiful! Thank you!

chilly locust
urban cipher
#

Can anyone suggest a working template to determin if someone came in or out a front door? example, front entry door and screen door opens. then entry door closes, then screen door closes.

urban cipher
#

value_template: >
{% if ((states.binary_sensor.f_e_d.last_changed) > ((states.binary_sensor.f_e_d.last_changed) and is_state('binary_sensor.f_s_d', 'on')) %}

sick ice
#

((states.binary_sensor.f_e_d.last_changed) and is_state('binary_sensor.f_s_d', 'on')) would resolve to a datetime then an and statement to a true/false outcome. Are you meaning to collect the the two last_changed states as a a true/false outcome and use an and statement to the is_state?

chilly locust
#

Well I'm completely stuck. I can't get any new template to work at all now. I even straight-up copied the temperature example from the online documentation, only changing to my sensor names, and it still doesn't work. The issue is they don't even exist, no matter how many restarts I do or different browsers I use. I've tried putting them directly in the configuration.yaml file in case my !include wasn't working, but no luck either. Thoughts on where I should start?

inner mesa
#

~share what isn't working

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.

inner mesa
#

and you didn't mention checking your config

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

chilly locust
inner mesa
#

it looks fine to me

#

there's really not much to it

#

you're missing a ( in the attribute

#

I just stuck your code in my file and tried to reload templates. It immediately gave me an error message in the log

#

you can just remove the ')', as it's not needed

#

in short, when things don't work, review your log

#

And reload templates from devtools -> YAML, don't restart HA over and over again. The former will tell you what's wrong without preventing HA from restarting or starting at all

chilly locust
# inner mesa you're missing a ( in the attribute

You're kidding right? A single parentheses was the whole reason none of them have been working? Funny enough, that's a common theme with me sometimes. Everything's perfect except I miss a single punctuation somewhere and screws everything up.

#

I added that missing parentheses and all 3 of them show up now. Thank you!!!

inner mesa
#

the template loader bails when it hits something it doesn't like and then doesn't load anything

chilly locust
#

Good to know!

inner mesa
#

you can just remove the ) you have there as you don't need it

#

| has the tightest binding

rare linden
inner mesa
#

Yes, this part is all messed up:

is_state("input_boolean.override_light_{{ area_id(trigger.entity_id) }}",
      'off')
worn cloud
#

hey guys; i have around 20 Sensors in which i want to display an attr for.
Example: sensor.front_keypad_info - i want to display attr linkQuality - so i did this

{{ state_attr('sensor.front_keypad_info', 'linkQuality') }}

and this works for the one; but what would be an easier way to get this for all 2 sensors?

urban cipher
#

there are times that i travel and i have guest come over to let out my dogs. I cant seem to get them to arm my house when they leave. I have dogs in the house or i would use the lack of motion in the house.

sick ice
urban cipher
#

I was trying that but i am vary new to templatiing.

sick ice
#

I also find it helpful if the logic is complicated, to built a binary sensor that be complexed then build my automation from that sensor, where you can introduce time delays and conditions etc.

urban cipher
#

Thats what i am hopoing to do.

#

I have done it to others but i cant seem to get it to work correctly for this.

#
  • platform: template
    sensors:
    sleep_stage_3:
    friendly_name: "Sleep Stage 3"
    device_class: motion
    value_template: >-
    {{ as_timestamp(states.binary_sensor.bed_motion.last_changed) < as_timestamp(states.binary_sensor.sleep_stage_2.last_changed) }}
sick ice
#
{{states.binary_sensor.f_e_d.last_changed}}
{{states.binary_sensor.f_e_d.last_changed}}
{{is_state('binary_sensor.f_s_d', 'on')}}

start with these separately then work at introducing operators to see what they do. The two links on the template developer page for the templating documentation and jinja are hugely valuable.
I'm also really new to templating so I'm not the right person to tell you the best way to achieve something but can definitely tell you what I've found helpful to get things working for myself.

urban cipher
#

Thank you vary much.

sick ice
#

also very helpful to post code here between ` symbol so it formats correctly. Or use 3x of them to mark the start/end of a code block.

urban cipher
#

Will do, thank you.

rare linden
silent barnBOT
worn cloud
#

Hello; I have the following template that gets the attr from a group of sensors

#
{% set zwave_link = expand('group.ringallsensorsinfo') %}
{% for link in zwave_link | sort(attribute="attributes.linkQuality") %}
{{
  {
    'Name': state_attr(link.entity_id,"friendly_name"),
    'Link': state_attr(link.entity_id,"linkQuality")
  }
}}
{% endfor %}
#

it outputs like this:
{'Name': '1st Flr Carbon Monoxide Info', 'Link': 'ok'}

{'Name': '1st Flr Smoke Alarm Info', 'Link': 'ok'}

How would i convert this to JSON so i can pick out the value Link and set an automation if it ever says Bad to send me an alert?

marble jackal
#

Where are you using this template?

worn cloud
#

i am currently just using it under Developer Tools

#

later i would like to extract the json link value and if it says bad then do something

marble jackal
#

You could put it in a template sensor attribute, but not like you are doing now, you'll have to use a namespace then

#
{% set ns = namespace(zwave=[]) %}
{% set zwave_link = expand('group.ringallsensorsinfo') %}
{% for link in zwave_link | sort(attribute="attributes.linkQuality") %}
{% set ns.zwave = ns.zwave + [
  {
    'Name': state_attr(link.entity_id,"friendly_name"),
    'Link': state_attr(link.entity_id,"linkQuality")
  }] 
%}
{% endfor %}
{{ ns.zwave }}
marble jackal
eager kettle
unreal beacon
#

This may be the wrong place, but it is a template i think

#
template:                                                                                                 
  sensor:                                                                                                 
    name: "Electricity Live Usage"                                                                        
    unit_of_measurement: "W"                                                                              
    state_class: measurement                                                                              
    device_class: power                                                                                   
    state: "{{ (states('sensor.frient_energy_monitor_power_meter')|float * 1000 / 800) | round(2) }}"     
    name: "Electricity Usage Total"                                                                       
    unit_of_measurement: kWh                                                                              
    state_class: total_increasing                                                                         
    device_class: energy                                                                                  
    state: "{{ (states('sensor.frient_energy_monitor_energy_meter')|float * 1000 / 800) | round(2) }}"   

#

Ive got this to translate some data from an energy reading device thingy

#

the "Usage Total" sensor is present, however the live usage, doesnt seem to appear,

#

nor does the validate check in YAML suggest that there is an issue?

#

but when i search in states its not present

#

ignore the quotes or lack of quotes around the unit of measurements, purely testing to see if that was the issue

marble jackal
#

You need to make it a list, every sensor needs to be a list item:

template:
  - sensor:
      - name: foo
        state: "{{ template }}"
      - name: bar
        state: "{{ other template }}"
marble jackal
unreal beacon
#

yeah i tried this before but it didnt seem to like it in the least... let me try again

#

thats done it!

#

i think i was missing the spaces between - and sensor

#

super thanks

#

so im guessing without the - and proper notation it iterates and just generates the last one in the list

marble jackal
#

If you don't provide it, and a list is expected, it will covert it to a list item itself, but in your case that caused duplicate keys

unreal beacon
#

ok cool, ill bear that in mind

#

star

rare linden
marble jackal
#
{{ is_state('input_boolean.override_light_' ~ area_id(trigger.entity_id),  'off') }}
rare linden
#

I did have {{ }} around it originally didnt know about the ~ syntax will give that a go, thanks

marble jackal
#

That will concatenate both sides of it as strings

deft timber
mighty ledge
noble pawn
#

can someome please give me a hint what i am missing? i got two mqtt sensors which are deliviering current power use and the current count of my smartmeter. using mqtt browser i get this information:

#

{
"timestamp": 1661859022456,
"value": 8744725.700000001
}

#

then i created a template sensor:

#

mqtt:
sensor:
- name: "Aktueller Stromverbrauch"
state_topic: "vzlogger/data/chn0/raw"
device_class: power
unit_of_measurement: "W"
value_template: "{{ value | float}}"

#

but i am not getting a value until i disable #value_template

#

:/

jagged obsidian
#

value_json.value

#

if that is the entire json you receive

mighty ledge
#

that should be it

noble pawn
#

{ "timestamp": 1661859127458, "value": 8744738.5 }

mighty ledge
#

don't need the float either

noble pawn
#

yep, thats all

mighty ledge
#

"{{ value_json.value }}"

noble pawn
#

but i could divide the value

#

right?

#

the count is 8744

#

the value is coming out with a wrong format

mighty ledge
#

yeah then just / 1000

noble pawn
#

alright will check

#

thank you so far

#

🙂

#

value_template: "{{ value_json.value / 1000 }}"

#

like that i guess? 🙂

#

or do i need to create another sensor which divides the value?

mighty ledge
#

nope, thats good

noble pawn
#

could you give me one more hint how to split / cut the value? currently i get: 8.746,0645 kWh but i only want 8.746,06... my sensor currently looks like:

#
  • platform: mqtt
    name: "Aktueller Zählerstand"
    state_topic: "vzlogger/data/chn1/raw"
    device_class: power
    unit_of_measurement: "kWh"
    value_template: "{{ value_json.value / 1000 | int | round(2)}}"
#

or even 8746 would be more than fine, without any decimals

mighty ledge
#

put parenthesis around the math portion. right now you're only rounding the denominator

inner mesa
#

And you're rounding an int

noble pawn
#

{{ (333333.3334,31 / 1000) | float | round(2)}}

#

ValueError: Template error: float got invalid input '(333333.3334, 0.031)' when rendering template '{{ (333333.3334,31 / 1000) | float | round(2)}}' but no default was specified

#

i think the combination of . , is bad

marble jackal
#

Correct, the decimal symbol is . (dot), not , (comma)

noble pawn
#

i know, but i get the value like this "8.746,06"

#

via mqtt 🙂

marble jackal
#

It's now treated as a tuple

rose scroll
#

Do you need the bit after the comma? If not, you can split the string on the comma, take the 0th part and cast that to float to subsequently do your math on.

noble pawn
#

i just neet the first digits in front of the dot

#

like 8746

#

sorry

rose scroll
#

Then you need not bother with the math.
{{ '12345.678,9012'.split('.')[0] }} gives 12345

#

Assuming of course that the mqtt output is a string.

noble pawn
#

value_template: "{{ (value_json.value.split('.')[0] / 1000)}}"

#

trying something like this

noble pawn
jagged obsidian
#

and what value from that would you like to display?

noble pawn
#

the one behind "value", should look like: 8746

jagged obsidian
#

i understand that part but what number would you like to see from that value_

noble pawn
#

Everything in Front of the dot

#

And that Number divided by 1000

jagged obsidian
#
{{ (value_json.value / 1000) | int }}
{{ (value_json.value / 1000) | round }}

pick one

mighty ledge
inner mesa
#

Why different countries use the same characters for exactly opposite things is baffling

mighty ledge
#

Basically, what I’m saying is you’re incorrectly testing the template in the template editor

#

You need to take the value that's under the hood when testing. I.e. developer tools -> states page, use that value.

#

do not copy values from the front end to test in the template editor

#

so to recap, this is what's coming from your mqtt:
{ "timestamp": 1661859127458, "value": 8744738.5 }
And that's the number you should be testing with. Notice the lack of commas, and the presence of a period.

#
{{ (value_json.value / 1000) | round(2)}}
#

and for your testing...

#
{{ (8744738.5 / 1000) | round(2) }}
noble pawn
#

Yeah got this so far

#

But i feel like my Split Statement is wrong allthough i am using the dot

inner mesa
#

You don't need the split, it's a number

#

You saw petro's detailed explanation above?

mighty ledge
#

🤷‍♂️

#

He just needed parenthesis and he's now down this rabbit hole of wrong thinking.

#

@noble pawn read my responses.

noble pawn
quiet niche
#

Hey crew,
Is filtering (like lowpass) available in templates? Or do I need to build a new sensor?

mighty ledge
#

it's not, you have to build a new sensor

#

if you're just looking at the previous point, you can use the this variable to get the previous state before calculating the new state. Anything beyond that and you need to use the lowpass filter

quiet niche
#

do my own exponential filter with this is what you mean?

mighty ledge
#

use this.state to get the previous state. Then filter or not. That's what I mean. But you can't get historical data, so anything beyond 1 state would need to be spooled in your attributes (and wiped out on restart) or using one of the many integrations that looks at your history.

inner mesa
#

(and wiped out on restart)
apparently if you give the sensor a unique_id, they're retained

#

so I'm told

quiet niche
#

great - Thanks for the help. As long as I can get the previous value, I can math it - Sort alike... the new value's weight level, layered on the old value

#

So you don't' have to build up the whole time series

mighty ledge
inner mesa
#

I haven't tried it, but I think TheFes mentioned that they are, and I just believed it. It's all part of the state

deep gull
#

Hi. i have a sensor that outpots true or false. I would like it to replace true with Low and false with High. How can this be done?

inner mesa
#

with a simple template sensor, but it depends on whether entity state in HA is really the string "true" or "false"

deep gull
#

its from this code:

#
  • platform: template
    sensors:
    nordpool_highlow:
    friendly_name: Nordpool High Low
    value_template: "{{ (states('sensor.nordpool_diff_rank_20') | float ) > 0.8 }}"
inner mesa
#

change the value_template line to this:
value_template: "{{ iif(states('sensor.nordpool_diff_rank_20')|float > 0.8, 'Low', 'High') }}"

marble jackal
deep gull
#

Thank you, im testing now 🙂

#

That worked perfectly 👍 Many thanx

rare linden
#

is there a method of setting the value of a helper such as an input_number but in such a manner that it won't cause it to trigger an automation that relies on it?

mighty ledge
#

maybe you can elaborate on what you're actually trying to do

silent barnBOT
#

The XY problem is asking about your attempted solution rather than your actual problem.

This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.

rare linden
# mighty ledge maybe you can elaborate on what you're actually trying to do

Basically i have an input_number helper for every room to manually set the brightness of the light or other automations will automatically set the input_number so that it keeps track of desired brightness and stops automations accidentally setting one value over another.

This then triggers another automation to run a script that sets all lights brightness for that area to the value of the input_number

I want to make sure not to create a loop if i create an automation that syncs the input_number to the brightness just incase the brightness was different such as directly changing the light entity brightness or if it changes itself due to being turned off and on again at the swtich, etc

rare linden
#

i suppose i could just add a condition to every automation that is triggered by them to stop if there's no difference between brightness and helper

mighty ledge
silent barnBOT
mighty ledge
#

I'm just curious as to why this is even an automation, you could just make a template number instead of input_number, then it would only fire when you manually set it through the service.

worn cloud
marble jackal
#

You should use it as an attribute, not as the state

mighty ledge
#

welll seeing that no zwave device has linkQuality as an attribute, i would assume that's always empty

inner mesa
#

Looks like it's some Ring sensors

chilly locust
#

I got pretty much everything transitioned to the new template format, but now one of my sensors is being finicky again. Even the old code won't calculate it correctly. Essentially, the attribute needs to determine what day of the week it is and display it as a number (0-6). For me, Wednesday is Day 0, Tuesday is Day 6. Thoughts on this? Here is the full code for that, focusing on the pregnancy_weeks sensor & attribute.
https://hastebin.com/jafabomece.pl

mighty ledge
#

alot of those templates are mish mashing date times when they don't need to

chilly locust
marble jackal
#

Chrome keeps crashing on that link on my mobile

mighty ledge
#
{{ state_attr('calendar.baby_tengowski', 'start_time') | timestamp_custom('%-I:%M%p on %a, %B %d') }}
{{ (now() - states('input_datetime.pregnancy_last_period') | as_datetime | as_local).days }}
{{ (states('input_datetime.pregnancy_due_date') | as_datetime | as_local - now()).days }}
#

first 3

#
days_in_week: "{{ states('sensor.pregnancy_days') | int % 7 }}"
#

unless you want it days from monday, then it's different

#

but if you want it day in the week from the pregnancy date

marble jackal
chilly locust
chilly locust
mighty ledge
#

that's not how % works

#

% 7 will never hit the number 7

#

it will be 0 through 6 only

marble jackal
#

You will now end up with -1 to 5

mighty ledge
#

right

#

% is mod, it returns the remainder

chilly locust
#

Ahh that makes sense. I thought % was just a fancy /.

mighty ledge
#

so if you have 10 and you mod it with 7, you'll get 3

#

if you have 7 and you mod it with 7, you'll get 0

marble jackal
#

And 17 % 7 will be 3 as well

mighty ledge
#

right

#

basically, it returns the remainder

#

divide by this number and return the left over amount

#

that's probably a better explanation

chilly locust
#

So that fixes the attribute, but the state is now quite a large number (16.8571428571429). Just need it to be 16. I think that's why rounded it to 0 with the floor.

mighty ledge
#

the state for weeks?

#

{{ states('sensor.pregnancy_days') | int // 7 }}

marble jackal
#

You changed // to /

mighty ledge
#

Is this another change that he made?

marble jackal
#

Yes

mighty ledge
#

// is an int division, it's different than /. // will divide a number a return only the whole number.

#

@chilly locust lol, it's better to not fix typo's from thefes

#

cause they aren't typos 🤣

marble jackal
#

Maybe I should have explained it as well 😛

chilly locust
rare linden
worn cloud
mighty ledge
#

and have the automation run off the helper

chilly locust
#

I put it back to what @marble jackal had and it's working now. Thanks for your help you two! Maybe I can convince the wife to use you as middle names. 😂

worn cloud
mighty ledge
#

in the name

worn cloud
#

which seems to be a valid JSON output but the template sensor does not have any states or attr to it

marble jackal
rare linden
#

Yes but setting it directly is still a possible scenario or like i said the light itself might change its value if it's turned off, and i want to account for it so the helper doesn't get out of sync with the real brightness

mighty ledge
#

make a number template that runs actions

#

instead of an automation that works off the input_number

marble jackal
mighty ledge
#

then you have a separate UI item that doesn't trigger automations and only adjusts your lights

rare linden
#

number template?

mighty ledge
#

number template

marble jackal
#

@worn cloud what is your template sensor config?

worn cloud
#

hmm, the state mentions: unavailable and the Attr section just says: friendly_name: Ring zWave Sensor Link

mighty ledge
#
template:
- number:
  - ...
worn cloud
#

the template sensor looks like this

silent barnBOT
rare linden
#

use it for what though? run an action depending on the brightness of the light?

mighty ledge
#

no, use that in the UI

#

to set your lights

#

your automation runs actions, correct?

#

based on your input_number

rare linden
#

yes

mighty ledge
#

so don't use the input number in the ui, make an template number that has the same actions as your automation

marble jackal
mighty ledge
#

post your automations if you don't understand and I'll show you the config

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.

marble jackal
#

It is too long for the state, and the state can't be a list of dicts, an attribute can

#

I'm off to bed now

worn cloud
#

ok, thank you for your help - I will read into this

rare linden
mighty ledge
#

Ok, so don't expose your input numbers, and just make 3 template numbers

#
template:
- number:
  - name: Light Living Room
    state: "{{ expand(area_entities('kitchen')) | selectattr('state', 'eq', 'on') | map(attribute='attributes.brightness') | map('int') | list | average | int }}"
    step: 1
    min: 0
    max: 255
    set_value:
    - service: light.turn_on
      target:
        area: kitchen
      data:
        brightness: "{{ value }}"
rare linden
#

do i just put that in my configuration.yaml?

#

never used templates before

mighty ledge
#

you got them all over your config

#

you've never used template entities before?

rare linden
#

ah i see template, as an action

#

you mean creating an entity from templating? only sensors and binary_sensors

mighty ledge
#

there's templates (Jinja) and then there's template entities which is just an integration based around templates (jinja)

rare linden
#

the template: bit was confusing me as i rarely see it since my other entities are !include(d) in, so yeah i just add them like i do with binary_sensors and sensors pretty much

#

will look into that, thanks

noble pawn
worn cloud
#

@marble jackal I ended up doing this

- platform: template
  sensors:
    ringsensorszwave:
      friendly_name: "Ring zWave Sensor Link"
      value_template: >-
        {{ states('group.ringallsensorsinfo') }}
      attribute_templates:
        data: >-
          {% set ns = namespace(zwave=[]) %}
          {% set zwave_link = expand('group.ringallsensorsinfo') %}
#

i cut the code a bit to just show the steps i took and the attr in HA now shows:

#

friendly_name: Ring zWave Sensor Link
data:

  • Name: 1st Flr Carbon Monoxide Info
    Link: ok
  • Name: 1st Flr Smoke Alarm Info
    Link: ok
  • Name: 2nd Flr Carbon Monoxide Info
    Link: ok
  • Name: 2nd Flr Hall Motion Info
    Link: ok
#

but i am not sure how i can extract this data now to show me if any of the Link values go from ok to bad to display me what name has gone bad and if more than 1 goes bad, to display multiples

marble jackal
#

@worn cloud You need to change the state to a count of those which are bad. Then you can use that as a trigger.
In the condition you can check if the value went up (meaning an additional item went bad) and you can compare the to_state with the from_state to see which one caused the increase

elder moon
#

Hey. I was wondering if anyone could help me. Ive got 9 (possibly more in the future) and i want to build an automation which will ensure that only one of them is going to be on. Triggered by any of the switches going on and switching off all other switches from the list except of the one which went on

#

I believe that the ideal approach to that would be some kind of cunning template populating turn_off service with all the switches except the one which triggered an automation

#

but ive got no idea how to do that

#

is anyone able to help with that?

elder moon
#

9 zigbee switches

#

and just to add - having more than one switched on at the time will not cause any electrical or hardware malfunction in my case, its not like controlling a fan with multiple windings

#

i just need an automation which is run by switching one of the devices on and which turns off the other devices

rose scroll
#

How about putting the switches into a group? Then execute this sequence of actions in your automation:

  • turn off the switch group
  • turn on switch x
#

Then in an automation, have 9 triggers, one for each switch, and tag the trigger id as the entity id of the switch. The trigger id can then be used to dynamically set the value of x in the action sequence.

marble jackal
#

I would create a template sensor with as state the number of switches on, and as attribute a list of switches which are on

#

Trigger on the numeric state of that sensor being since above 1, then compare the to_state of the attribute with the from_state, to see which one was turned on

#

Turn the others which are on off

#

But the approach of Daniel will also work

#

Or, you could simply create a state trigger with all 9 switches, and use the trigger.entity_id

marble jackal
#
trigger_variables:
  switches:
    - switch.switch_1
    - ...
    - switch.switch_9
trigger:
  - platform: state
    entity_id: "{{ switches }}"
    to: "on"
action:
  - service: switch.turn_off
    target:
      entity_id: "{{ switches | reject(trigger.entity_id) }}"
#

Not completely sure if a template is allowed for the state trigger though, otherwise also list them there

silent barnBOT
elder moon
#

except it doesnt really work 😦 I have tried adding it via YAML editor and get:
Message malformed: Entity {{ switches }} is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
error when trying to save

marble jackal
#

Okay, so you need to list all the 9 switches as well there

#

I already mentioned I was not sure this would be accepted

#
variables:
  switches:
    - switch.switch_1
    - switch.switch_9
trigger:
  - platform: state
    entity_id:
      - switch.switch_1
      - switch.switch_9
    to: "on"
action:
  - service: switch.turn_off
    target:
      entity_id: "{{ switches | reject('eq', trigger.entity_id) | list }}"```
elder moon
#

ok now its saved but doesnt turn off anything:
Error: Template rendered invalid entity IDs: <generator object select_or_reject at 0x7f671ea27d10>

marble jackal
#

Sorry, corrected above

elder moon
# marble jackal Sorry, corrected above

ok, added this, but now im getting:
Error rendering service target template: TemplateRuntimeError: No test named 'switch.private_office_console_strip_1_l2'.

marble jackal
#

You also don't need trigger variables now, just variables is okay

#

My bad, need coffee I guess

#

Corrected again

mighty ledge
#

you should use anchors on that so you only have to maintain 1 list

marble jackal
#

I was not sure how that worked in the GUI

mighty ledge
#
variables:
  switches: &switches
    - switch.switch_1
    - switch.switch_9
trigger:
  - platform: state
    entity_id: *switches
    to: "on"
action:
  - service: switch.turn_off
    target:
      entity_id: "{{ switches | reject('eq', trigger.entity_id) | list }}"
#

not sure if it does work, but just create a separate automation file for yaml ones

elder moon
marble jackal
#

Well, I'm feeling bad because I made all those mistakes in the first place 😛

rancid pelican
#

hi guys.

#

i have one hissue with a template automation.

#

can someaone 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?
rancid pelican
#

the automation dont continue after the wait

mighty ledge
#

well the syntax is wrong

#

and your template is comparing strings

#

there is no wait action

#

there's wait_tempalte and wait_for_trigger

rancid pelican
#

which one should i use?

mighty ledge
#

what do you think?

#

it's supposed to be wait_template

#

and you have

            - wait:
              template
rancid pelican
#

so in the comparation values i need to use wait for trigger ?

mighty ledge
#

no

#

I can't make it any more clear

#

you just need to use the correct syntax

#

instead of

#
            - wait:
              template
#

make it 1 line with an _

#
            - wait_template:
rancid pelican
#

i tried that to but not work

mighty ledge
#

because the tempalte is wrong

#

you're not comparing numbers, you're comparing strings

#

and you're accessing the state machine when you should be getting the states from the states method

#

e.g.
You have states.sensor.xxx.state

#

it should be states('sensor.xxx') | float if you want a number

rancid pelican
#

ok thanks

mighty ledge
#

where sensor.xxx is your entity_id

rancid pelican
#

i will try

#

@mighty ledge it works.

#

thanks

acoustic arch
mighty ledge
#
{% set forcast = state_attr('calendar.xyz', 'forecast') %}
{% set end = (today_at() + timedelta(days=3)).isoformat() %}
{{ forcast | selectattr('datetime', '<=', end) | map(attribute='temperature') | list | average }}
#

@acoustic arch ^^^

thorny sparrow
#

Just a quick question, how to include icons to the code? ?EX: icon: mdi:AppleFinder

mighty ledge
#

that's not a quick answer and we need more info

#

what do you expect it to do?

thorny sparrow
#
      battery_current:
        friendly_name: "Battery current"
        value_template: "{{ (states.sensor.*****_battery_power.attributes['current'] | float(default = 0)*1000000)| round(2)}}"
        unit_of_measurement: "mA"
        icon: mdi:BatteryArrowDown```
marble jackal
#

{{ state_attr('weather.whatever', 'forecast')[0:2] | map(attribute='temperature') | list | average }} was what I was preparing

acoustic arch
#

Thank you!!!!

#

Both 😉

thorny sparrow
mighty ledge
mighty ledge
marble jackal
mighty ledge
#

yah, i'm not sure as I don't use one

teal gate
#

Hi people, I am trying to work with the nordpool sensor to figure out if the price for the current and next hour is below average. And one of the attributes are defined as this:
today: 6.676, 6.573, 6.773, 6.257, 6.784, 6.994, 7.867, 8.205, 8.583, 8.124, 7.928, 7.904, 6.974, 6.66, 6.255, 6.541, 7.027, 7.945, 8.154, 8.49, 8.222, 7.959, 7.043, 6.626

What would be the best way to read eg. value number 4 (6.257)?

teal gate
#

I ended up using
{{ state_attr("sensor.nordpool_kwh_krsand", "today")[hour_now]}}
and that at least gives me exactly what I want 🙂

#

hour_now is defined as now().hour just before

versed lava
#

https://dpaste.org/EUM6G
When using this automation action, I get a "message malformed: template value should be a string for dictionary value" error. I'm not quite sure tho, where the error is hiding 😦

Edit: Forgot that Code shall be uploaded to dpaste etc.! fixed that

inner mesa
#

all your "=" should be "=="

#

or just use is_state_attr()

versed lava
#

oooooh...

inner mesa
#

In general, notify.notify isn't a very useful service as it's hard to predict what it will do. Better to create a notify group instead

#

but it depends entirely on what "doesn't work" means

#

but if you can paste the template in devtools -> Templates and it gives the expected output, then I suggest #automations-archived and to follow the standard test procedures

hollow hedge
#

Hello all! I am working to learn about templates using the template editor and I have gotten a couple to report correctly but I am having trouble with a specific one for an "if state_attr" request. I am trying to get a "connected" response when my BT headphones are connected to my phone and no matter how I word it, it always states "disconnected".

{% if state_attr('sensor.pixel_6_pro_bluetooth_connection','connected_paired_devices') == '82:4B:10:25:78:24 (TOZO-T10)' %} connected {% else %} disconnected {% endif %}

#

Sorry, not sure how to paste it in here correctly but would anyone what I am doing wrong?

#

This is an example of one that reports correctly for me.
{{ state_attr('sensor.pixel_6_pro_bluetooth_connection','connected_paired_devices') }} which returns ['82:4B:10:25:78:24 (TOZO-T10)']

rose scroll
#

Try {% if '82:4B...' in state_attr('sensor.pixel...') %}

rose scroll
hollow hedge
silent barnBOT
worn cloud
#

@marble jackal I tired this
value_template: >-
{% set ns = namespace(count=0) %}
{% set zwave_link = expand('group.ringallsensorsinfo') %}
{%- for item in zwave_link -%}
{%- if states[item.split('.')[0]][item.split('.')[1]].state == "bad" -%}
{% set ns.count = ns.count + 1 %}
{%- endif -%}
{%- endfor -%}
{{ ns.count }}

#

and then the attribute_templates: that i had showed you before but now i get no results

#

this is a hard one!

inner mesa
#

Your ' in the dict keys may need to be "

marble jackal
#

That's indeed more consistent

#

Corrected (and again to fix some more quote inconsistency)

inner mesa
#

It's proper JSON, but I dint know if it needs to be there

worn cloud
#

Thats amazing; thank you - I just had to change attributes_template: to attribute_templates: and now when the link goes from ok to bad, i can see the sensor state change from 0 to 1 and if 2 are bad, i see the state go to 2. Now based on the state change I can use that as a trigger and then I assume, i can see which sensor has gone bad and display the friendly_name?

marble jackal
#

Yes, you can trigger on a state change.
In the conditions check if the value increased, and then compare the from_state with the to_state to see which one changed to bad

worn cloud
#

thank you once again for all your help!!

eager kettle
#

so added a script for each moon sensor phase to push a ir button so many times depending on sensor.moon state (on script for each phase, can I turn this into one script)? https://hastebin.com/ocurusudaj.yaml one for last quater and https://hastebin.com/elobufajum.yaml for waxing gibbous and the rest assinged the same way, is there a simpler way to consildate all these into one script so a button press calls that script for conditons, would it be if then and repeat in automation?

eager kettle
mighty ledge
#

then to call it...

#
- service: script.moon_light
  data:
    moon: moon-first-quarter
eager kettle
#

it tunrs on the wall light to red on day the moon is a new moon so son knows that day there is no moon, the wall light back to normal color when there is a moon.

limber haven
#

Hopefully this is a simple one, I've got 4 templates that I've created that read the energy state of a smart device and do some basic math to give the 'correct' reading, but they dont show up as consumables on the Energy dashboard? not sure what (or if I can) do to amek them show up as such

#
        unit_of_measurement: "Kwh"
        state: "{{ states('sensor.chestfreezerusage')|float / 10 }}"
        state_class: total_increasing```
marble jackal
#

It needs device_class: energy

#

And kWh instead of Kwh

limber haven
#

Hm, so made those changes but they dont show up as a option still..

#
        unit_of_measurement: "kWh"
        state: "{{ states('sensor.chestfreezerusage')|float / 10 }}"
        device_class: energy
        state_class: total_increasing```
marble jackal
#

Does the sensor itself work?

rare linden
#

when creating a template entity such as a binary_sensor is there a way to refer to itself other than just hard coding the entity name? for example is_state(this.entity_id, 'on')

marble jackal
#

If you use the new format, there is the this object you can use

#

this.state == 'on'`

mighty ledge
#

Keep in mind It’s the previous state

#

Not the state you are going to

marble jackal
#

is_state(this.entity_id, 'on') would work for the current state

mighty ledge
#

Well current state is the previous state

rare linden
#

so is_state(this.entity_id, 'on') is not equivilent to is_state('binary_sensor.occupied_living_room', 'on') as 'this' referes to the entity object in it's previous state?

mighty ledge
#

All will return the same state

rare linden
#

so does that many mean all the is_state on the icons have never worked properly?

mighty ledge
#

Which is the previous state, ie whsts in the state machine. What thefes is referring to as “the current state”

#

No that will be current because attributes are resolved after the main state

#

It’s voodoo

rare linden
#

Alright, thanks

#

Also just to confirm which is best practice the this.state == 'on' syntax as TheFes alluded to? over is_state(this.entity_id, 'on') ?

mighty ledge
#

Both are similar

marble jackal
mighty ledge
#

Is_state v == have a minor difference that you shouldn’t have to worry about. But I’d just use this.state == because you already have the state

marble jackal
#

So for trigger based template sensors this.state and states(this.entity_id) can be different

rare linden
#

is the difference when they are resolved? aka if it's in a function like the latter in the previous example by TheFes it's triggered at the end, where as raw this is processed immediatly?

#

since it resolves on the id

marble jackal
#

For state based template sensors, the state template will be resolved first, and the this object will have the updated state for the attributes and icon template

rare linden
#

Alright, thanks

limber haven
marble jackal
limber haven
#

Says "No issue" for the template entities

waxen lynx
#

hi what am i doing wrong here in templating?
{% set battery = '{{states('sensor.oneplus_6t_battery_level')}}' %} {% if (battery >= 50 and battery <= 100) %} full charge {% elif (battery >= 20 and battery <=49) %} half charge {% elif (battery < 20) %} about to die {% endif %}
also i tried
{% set state = states('sensor.oneplus_6t_battery_level') %}

#

getting this error
TypeError: '>=' not supported between instances of 'str' and 'int'

#

how to change a sting or a int to a number?

marble jackal
#

You are nesting templates, remove '{{ and }}' in the first line

#

And states are strings, so you need to convert that to a number

#

{% set battery = states('sensor.oneplus_6t_battery_level') | float %}

#

Are you using this in a template sensor? Either add a default for the float filter, or add an availability template then

rare linden
marble jackal
#

Btw you can also do this 50 <= battery <= 60 instead of using and

waxen lynx
rare linden
# waxen lynx no just for templating details on front end.. but im interested to learn on how ...

an example of using that exact code in an automation could be used to pass the charge string into a script for example

that type of syntax can be used more or less anywhere to pass in specific data depending on various conditions, one i use is check the value of an input_select then pass specific RGB values into a light.turn_on command

and in scripts and automations you dont need to use the set var = syntax you can just specify variables: at the root level of the yaml and then add for example battery: {{ states('sensor.oneplus_6t_battery_level') | float(0) }}

#

would be nice if we could use that in configuration.yaml

rare linden
#

is there a way to get the model name of a device from the an entity id? i have a special light scenario for the lights in my kitchen based on area due to the types of bulb they are but would rather have that scenario trigger based on the device name just incase i add any other bulbs of the same type to another room (which i believe i have some extra of laying around) couldnt find a mention of it on the templating document page

mighty ledge
#

{{ device_attr('light.living_room', 'model') }}

#

@rare linden ^^^^

rare linden
#

Roger that, thanks.

worn cloud
#

I was getting help from TheFes today to get a template sensor that will increament the state from 0 to 1 and so on when the attr Link: changes from ok to bad. But i am having some issues trying to display the friendly_name in attr once that happens

#

my attr section looks like this:

#
connection_data: 
- Name: 1st Flr Carbon Monoxide Info
  Link: ok
- Name: 1st Flr Smoke Alarm Info
  Link: ok
- Name: 2nd Flr Carbon Monoxide Info
  Link: ok
- Name: 2nd Flr Hall Motion Info
  Link: ok
#

so lets say if the link for 1st Flr Carbon Monoxide Info goes from ok to bad, the sensor state will change from 0 to 1 but i dont know how i can extract just the friendly name from the sensot that just went bad

marble jackal
#

Okay, as said you need to trigger on a state change.
Then use this condition to check if there was an increase

- condition: template
  value_template: "{{ trigger.to_state.state | int(0) > trigger.from_state.state | int(0) }}"
worn cloud
#

would you know how i can use this in Node?

#

or would i put this in the same template sensor we made?

marble jackal
#

Ik don't use Node Red

#

Use this in a template to get the one which went bad
{{ trigger.to_state.attributes.connection_state | reject('in', trigger.from_state.attributes.connection_state) | map(attribute='Name') | join(', ') }}

worn cloud
#

Thanks once again, I will try this. Also what if 1 of the sensors is bad and the state goes from 0 to 1 then a 2nd sensor goes bad and count goes from 1 to 2. Will this display the first again along with the 2nd?

marble jackal
#

Nope, only the 2nd one

#

If you would like to have them all displayed, you don't need the attribute at all

#

{{ expand("group.ringallsensorsinfo") | selectattr("attributes.linkQuality", "eq", "bad") | map(attribute="name") | join(", ") }}

#

That will give you the names of all the bad ones in a comma separated string

wind snow
#

im kinda new to HA and yaml, can someone help debug? getting error ( Entity is neither a valid entity ID nor a valid UUID for dictionary value @ data['condition'][2]['conditions'][0]['entity_id'] ) on this condition template https://paste.debian.net/1252484/

#

i know i can put them each in a condition:template - value_template: format but i had to repeat this {% set hours = 5 %} for each condition and its bugging me. is there a way to simplify? or should i not bother to and just live with it as long as the automation works?

marble jackal
#

You can set hours in a variable

#
variables:
  hours: 5
conditions:
  - or:
      - "{{ }}"
wind snow
marble jackal
#

How did you exactly try this on devtools > templates, because this will not work there

#

This only works in the automation

#

For devtools > templates you need to do {% set hours = 5 %} to simulate the variable

wind snow
#

it does save the automation without errors tho just unable to test within the automation with the error.

marble jackal
# wind snow i tried to trigger it but the actions didnt fire so i guess the conditions are n...

You could also put it in one condition like this:

{% set h = 5 %}
{% set c = [ 'rainy', 'pouring', 'lightning', 'lightning-rainy' ] %}
{% set w = state_attr('weather.forecast_home_hourly','forecast')[:h]  | map(attribute='condition') | list + state_attr('weather.forecast_office_hourly','forecast')[:h]  | map(attribute='condition') | list %}
{{ w | select('in', c) | list | count > 0 }}
marble jackal
wind snow
#

Thank you so much! this kept me up late for 2 nights, i can now sleep in peace lol

marble jackal
#

Sleep well then!

astral turtle
#

Hi,
Please help me with a template for temperature sensors. It was working before, but then stopped working after some update. Basically I need to select lowest value from 2 values.

#

value_template: "{% set values = [\n
\x20 states('sensor.filtered_outdoor_temperature_1'),\n
\x20 states('sensor.filtered_outdoor_temperature_2')\n
\x20 ] | select('is_number') | map('float') | round(1)| list\n
%} {{ values | min | round(1) if values | count > 0 else 'none available' }}\n
\x20"

marble jackal
#

What's with all these \n\ rubbish?

#
value_template: >
  {% set values = [ states('sensor.filtered_outdoor_temperature_1'), states('sensor.filtered_outdoor_temperature_2') ] | select('is_number') | map('float') | list %}
  {{ values | min | round(1) if values else 'none available' }}
astral turtle
#

Thanks a lot for the help 🙂

marble jackal
#

The real issue was that you were applying the round filter too soon

marble jackal
# astral turtle Thanks a lot for the help 🙂
value_template: >
  {% set values = [ states('sensor.filtered_outdoor_temperature_1'), states('sensor.filtered_outdoor_temperature_2') ] | select('is_number') | map('round', 1) | list %}
  {{ values | min if values else 'none available' }}

Small improvement, mapping to round directly instead of float

analog mulch
#

In an automation with a template trigger containing multiple entities is it possible to extract the particular entity whose change caused the trigger to fire?

marble jackal
#

But these docs seem to be the same as for state trigger

analog mulch
#

I haven’t actually tried this, I just assumed it wouldn’t work. But maybe I’m wrong. I’ll try

marble jackal
#

It works, just tested it

#

The for_state and to_state are also available, just as the docs say

thorny sparrow
#

Hi, I'm trying to implement a custom power sensor from current and voltage multiplication. How is this done, when I created the Voltage and Current previously and the sensor entities are: sensor.battery_current and sensor.battery_voltage. My interpretation was like this yaml battery_watts: friendly_name: "Battery power in mWatts" value_template: "{{(state.sensor.battery_current*state.sensor.battery_voltage)}}" unit_of_measurement: "mW" PS: the current is in mA, and the voltage is in V

inner mesa
#

two things are wrong with that

#

state.sensor.battery_current is a state object, and not the actual state. The state would be state.sensor.battery_current.state, or more correctly states('sensor.battery_current').

#

second, states are strings and you need to turn them into numbers if you want to perform math operations on them

#

so...

#
  value_template: "{{ states('sensor.battery_current')|float * states('sensor.battery_voltage')|float }}"
thorny sparrow
inner mesa
#

Yes, you should provide a default if it's possible that they won't have a numeric value. You can do that simply with float(0)

thorny sparrow
marble jackal
#

Or add an availability_template to check if the sensors provide a correct state

earnest wave
#

Can anyone help me with implementing this #beta message ?
Currently I'm sending a MQTT message to HA with a running total of water usage at the time the signal is sent. I just want to see the number of gallons used since the previous message.

#
  - platform: mqtt
    name: "Water Meter"
    state_topic: "metermon/water"
    value_template: '{{ value_json.Consumption }}'
    unit_of_measurement: 'gal'```
marble jackal
#

Create a trigger based template sensor which triggers on state changes of this sensor.
Subtract trigger.from_state.state | float from trigger.to_state.state | float to get the delta

earnest wave
marble jackal
nova cove
#

Hello! I am trying to create a template sensor and it's not working as expected. I want to count the number of open windows in my house. I have a sensor for each window that can be in state "Normal" or "Violated". I also have door sensors that can have the same values, so I want to filter those out on the sensor attribute "definition". A window has the definition "burglar_perimeter_instant" so I created this sensor:

  sensors:
    open_windows:
      friendly_name: "Open Window Count"
      value_template: '{{ states.sensor| selectattr("definition","equalto","burglar_perimeter_instant")|selectattr("state","equalto","Violated")|list|length }}'```
But the count is always zero no matter if I open a window. Any idea what I'm doing wrong?
inner mesa
#

you need to use attributes.definition

nova cove
#

like this?:

  sensors:
    open_windows:
      friendly_name: "Open Window Count"
      value_template: '{{ states.sensor| selectattr("attributes.definition","equalto","burglar_perimeter_instant")|selectattr("state","equalto","Violated")|list|length }}'```
marble jackal
#

Like that

#

No, you need to check if the attribute exists first

#

selectattr("attributes.definition","defined")

nova cove
#

I restarted before you added that check - sensor seems to be working as expected without it. I'll add the check, but what is the down side of not adding it?

marble jackal
#

You don't need to restart to reload template sensors

#

You can do that from devtools > YAML

nova cove
#

ah - right, thanks!

marble jackal
icy basin
#

Hi! For a custom sensor I need the day/night state. This is working by using {{ 0 if is_state('sun.sun','below_horizon') else 1 }}. Now I wanted to add an offset. Can anyone guide me how to do it? Is it even possible? Thanks!

inner mesa
#

use the elevation attribute instead

icy basin
#

Thanks!

woven gulch
#

Hey folks. Been researching this and cant seem to find what I am looking for. I want to add a custom entity that is binary sensor class of running. My automations will togggle this but I need that control. It needs to defautl at startup to 0. I am confused on dealting with trying to set this up. Where and how is baffeling to me. If someone could help out is dunbing this down it would be appreciated.

inner mesa
#

you don't control sensors

#

you can use an input_boolean (toggle), or a template switch, but I don't know what you mean by "It needs to default at startup to 0". Do you mean "off"?

worn cloud
frosty temple
#

Anybody knows what's wrong with this code? Keep getting the "can not read a block mapping entry; a multiline key may not be an implicit key" error

marble jackal
frosty temple
#

shell_command:
pvoutputcurl: ‘curl -d “d={{now().strftime(”%Y%m%d")}}" -d “t={{now().strftime(”%H:%M")}}" -d “v2={{states.sensor.pv_power.state|round(0)}}” -d “v5={{states.sensor.inverter_temperature.state|round(0)}}” -d “v6={{states.sensor.pv_voltage.state|round(0)}}” -H “X-Pvoutput-Apikey: typeinyourapikeyhere” -H “X-Pvoutput-SystemId: typeinyoursystemidhere” https://pvoutput.org/service/r2/addstatus.jsp

#

Ah crap, didn;t paste good

worn cloud
#

Yes i have the sensor as a trigger and when it goes to 1 as an example - the template is coming out blank

marble jackal
frosty temple
#

shell_command:
pvoutputcurl: ‘curl -d “d={{now().strftime(”%Y%m%d")}}" -d “t={{now().strftime(”%H:%M")}}" -d
“v2={{states.sensor.pv_power.state|round(0)}}” -d
“v5={{states.sensor.inverter_temperature.state|round(0)}}” -d
“v6={{states.sensor.pv_voltage.state|round(0)}}” -H “X-Pvoutput-Apikey: typeinyourapikeyhere” -H “X-Pvoutput-SystemId: typeinyoursystemidhere” https://pvoutput.org/service/r2/addstatus.jsp

worn cloud
#

i am replicating it in Node as i have moved all my automations over - just dont know how it would look in yaml now. And i know you dont use Node, which is not in my favor

#

I have a trigger which is template you helped me with and when it moves from 0 to 1, i see it fire into a template which i pasted from above but the string is coming out empty

worn cloud
marble jackal
#

Yes, I asked you which of those you wanted, but you didn't reply

#

But those trigger templates comparing the for state with the to state won't work in node red

#

And I don't know how to do that in Node Red

woven gulch
marble jackal
worn cloud
#

with the other template you provided; is there a way to use that but to only 1 sensor and then if a new sensor goes bad - to just output that only? Or not possible with this method?

marble jackal
#

No, that is not possible with your current sensor

#

You could create a trigger based template sensor out of this sensor instead of the automation

rare linden
#

is there a good way to debug if you have a binary sensor causing all your custom entities not loading other than commenting them out one by one till they work?

waxen lynx
#

hi can someone help me on how to create a sensor based on:
{{ state_attr('light.bedroom_lamp','brightness:')}}
brightness value ranges from 0-255
i want to convert these to 0-0.9 values
dont know where to start

chilly locust
#

I've been doing lots of work on my template sensors the last few days. I have one that reports a cost value, but it has 4 decimal places (1.9454). How can I round it to be "1.95" with only 2 decimal places?

rare linden
#

it MIGHT be the otherway around 255 / brightness, it's been a while since i've done that conversion

waxen lynx
#

i did the same but missed | before float

waxen lynx
rare linden
#

do you want it rounded to the nearest decimal and the lowest value being 0.1 rather than 0?

#

min-max / max will always get you in the range of 0-1 if you want 0.1 then you'd need to do something like (brightness + 1) / 256 + 0.05 | round(1)

#

found a better way as i finally found hwo to do ceil

#

(brightness + 1) / 256 | round(1, 'ceil')

chilly locust
#

{{ (states('sensor.daily_energy')| float ) * (states('input_number.cost_per_kwh') |float ) | round(2) }}

rare linden
#

((states('sensor.daily_energy')| float ) * (states('input_number.cost_per_kwh') |float )) | round(2)

#

the first two needed to be in () and then rounded else you were just rounding the last one

rare linden
# waxen lynx yeah exactly

((state_attr('light.bedroom_lamp','brightness')|float + 1) / 256.0) | round(1, 'ceil') <-- should do it

chilly locust
rare linden
waxen lynx
rare linden
#

That's because my initial post forgot the brackets like I told tango

#

I edited the post, just add brackets around everything before the round

#

if you still get 3 then something weird is happening

waxen lynx
# rare linden any luck?

it works thanks:❤️....round(1, 'ceil') what does this part actually do i mean how it works?

rare linden
#

it rounds UP to the nearest 1 decimal

#

floor would round down and just round(1) would do regular round

#

that's also why you need the +1 on the brightness so it's never 0

waxen lynx
#

okay if i want it to round off to say 0.05 or 0.2 what should i do..just trying to learn

rare linden
#

0.05 round(1)

waxen lynx
#

soo ceal for decimal ?

rare linden
#

ceil means ceiling as in round up

#

1 means round to 1 decimal

#

0.05 would be round(2)

waxen lynx
rare linden
#

floor rounds down

#

for 0.2 assuming you wanted that as your starting digit it would be the same but you'd probably have to sanitize the brightness first something like (((((state_attr('light.bedroom_lamp','brightness')|float / 10) | round) + ((255 / 10) | round * 2)) * 10) / 255.0) | round(1, 'ceil')

waxen lynx
mighty ledge
#

you need json_attributes_path: "$.0.firewallEventsAdaptive"

#

no

waxen lynx
waxen lynx
# rare linden floor rounds down

actually instead of rounding up/off cant we just make a range value to fall into other range?
for example 0-255 to 0.1 -1
rounding up or off what happens is..it isnt just taking the low brightness values at all...is their any alternative way instead of rounding?

rare linden
#

thats why you add +1 and use ceil

opaque marlin
#

Is there a way to create a template with multiple attributes?

inner mesa
#

A template sensor? Sure

limber haven
#

Good lord templating is.. confusing x.x

jagged obsidian
#

Only if you don't know python and jinja

limber haven
#

I dont -.-

jagged obsidian
#

Better start learning 😉

limber haven
#

I've been trying to setup a template as part of an automation so I can use the same automation for every light-switch in my house (read the name then parse out the location/light it controls) I got it working fine with Deconz, but moving to MQTT and its just totally and utterly broken and I cant make it work at all 😄

#

It seems like this should work.. but it apparently does 'nothing' ```- alias: "MQTT Light Remote: Long Press On"
initial_state: True

trigger:
- platform: event
event_type: state_changed
# Only look at lights going off to on
event_data:
new_state:
state: "on_hold"
# old_state:
# state: 'off'

condition:
- condition: template
value_template: "{{ trigger.event.data.entity_id.startswith('sensor') }}"

action:
- service: light.turn_on
entity_id: light.office

#

(I know the action is wrong, thats just a simple 'is the trigger/condition actually working' without overcomplcating things at the moemnt

#

If Im in events, I can see a 'state changed' for new_state: entity_id: sensor.office_switch_action state: on_hold

waxen lynx
marble jackal
limber haven
#

Sounds like I need to abandon this idea for now then, dont really have the free time to setup HA & learn two programming languages 🤷

waxen lynx
#

{{ state_attr('light.bedroom_lamp','brightness:') | float / 255 }}
Not sure how to change these value to 0.2-1

thorny sparrow
#

Is it possible to make a sensor in HA that changes the unit_of_measurement based on the assumption that it's better to read 1W rather than 1000mW? And it's better to read 200mW rather than 0.2W. My bad code is here with an if else statement yaml value_template: "{{ {states('sensor.battery_current')|float(0) * states('sensor.battery_voltage')|float (0) if(battery_watts<1000){ return unit_of_measurement: "mW"}else{return unit_of_measurement: "W"}}}

fossil venture
waxen lynx
fossil venture
#

Change to |round(2)

waxen lynx
#

Tried but no changes

fossil venture
#

Exactly like this? {{ ( 0.003137255 * state_attr('light.bedroom_lamp','brightness') | float(0) + 0.2 )|round(2) }}