#templates-archived

1 messages ยท Page 40 of 1

amber hull
#

I and a couple of others posted yesterday about an issue with a template that stopped working.

#

value_template: >
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}

{% set degree = state_attr('sensor.buoy', 'WDIR')|float (0) %}

  {% set degree = state_attr('sensor.buoy', 'MWD')|float (0) %}
  {{ direction[((degree+11.25)/22.5)|int] }}
inner mesa
#

it had nothign to do with that

#

it had everything to do with the fact that you used a unit_of_measurement with a non-numeric state

amber hull
#

Is the unit of measure assumed?

inner mesa
#

it's just a string

#

there is no unit_of_measurement

#

how many norths today?

amber hull
#

Not understanding (what else is new). The exact same template works for my weather app. Doesn't work for my buoy reading

inner mesa
#

๐Ÿคท

#

do you have a unit_of_measurement?

amber hull
#

Where do I look?

inner mesa
#

did you use one when you created the sensor?

amber hull
#

The states for the sensor does not

inner mesa
#

this is all your stuff

amber hull
#

I did not create a unit of measure for either.

inner mesa
#

share the whole sensor that works and the one that doesn't

amber hull
#
  ny_harbor_wind_direction:
    friendly_name: 'wind direction buoy'
    value_template: >
      {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
      {% set degree = state_attr('sensor.buoy', 'MWD')|float (0) %}
      {{ direction[((degree+11.25)/22.5)|int] }}
#

Fails

#
      wind_direction:
        friendly_name: 'wind direction'
        value_template: >
          {% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
          {% set degree = state_attr('weather.home', 'wind_bearing')|float (0) %}
          {{ direction[((degree+11.25)/22.5)|int] }}
#

works

obtuse zephyr
#

What does "fails" mean and are there any other attributes associated with either or those sensors that appear after value_template?

amber hull
#

It means that the direction is wrong. It shows N no matter what the degrees are. I don't understand the question on other attributes associated with?

#

I did the troubleshooting steps I was given yesterday and the degrees show correctly

#

I fixed it. Had a duplicate sensor. Thanks for everyone's help.

pastel moon
#

should these two not show the same?

{{ states.binary_sensor.closet_motion_1_occupancy.last_changed }}
{{ state_attr('binary_sensor.closet_motion_1_occupancy','last_changed') }}
#

I know the latter one is the one that should be used, but...?

#

Only the first gives output, the second "null"

lyric comet
pastel moon
lyric comet
#

That is what I meant by special. state_attr only looks in the attributes table, but the last_changed is no an attribute, it is another item at the same level in the tree as the attributes.

pastel moon
#

Aha, got it, thanks ๐Ÿ™‚

heavy crown
#

Hi, in search of a template solution for this, I'd like to show the moon phase with left of it the previous phase and right of it the next phase. I can get the 'current' index from the list of 8 phases and with -1 and +1 this would work, except when current index =1 where I would need 8 as previous OR when current index = 8 where I would need index 1 as next. I can of course add an if curren= 1 then next = 1... but maybe there is something smarted..... I hope I made it clear?

#

this is that I have right now ['first_quarter', 'full_moon', 'last_quarter', 'new_moon', 'waning_crescent', 'waning_gibbous', 'waxing_crescent', 'waxing_gibbous']

#
{% set phases = states.sensor.moon_phase.attributes.options %}
{{ phases[states.sensor.moon_phase.attributes.options.index(states('sensor.moon_phase')) - 1] }}
{{ phases[states.sensor.moon_phase.attributes.options.index(states('sensor.moon_phase'))] }}
{{ phases[states.sensor.moon_phase.attributes.options.index(states('sensor.moon_phase')) +1 ] }}
#

which returns

#
new_moon
waning_crescent
waning_gibbous
#

as current index = 4 but how to deal when curren moon = waxing-gibbous or first_quarter

mighty ledge
#

it will work if it's the first, it won't work if it's the last

#

-1 chooses the last object

#

so when you're on the last item, you need to handle the last item only, because that's the only time it will go beyond the limit

#
{%- set phases = state_attr('sensor.moon_phase', 'options') %}
{%- for current in range(phases | length) %}
{%- set last = current - 1 %}
{%- set next = current + 1 if current + 1 < phases | length else 0 %}
{{ current }} {{ phases[last] }}
{{ current }} {{ phases[current] }}
{{ current }} {{ phases[next] }}
{%- endfor %}
heavy crown
#

ah... yes.... I should have know 'last' .. THANKS!

pastel moon
#

I don't have any more hair to spare... Please help with this. I am trying to set a date & time to a input_datetime helper. It seems to have some sort of cache, not overwriting when I want it to. Why? I had an "initial" value set in configurations.yaml, but that is commented out, and HA restated several times. This statement still won't update the helper...

#
  - service: input_datetime.set_datetime
    data:
      entity_id: input_datetime.morning
      date: >
        {% set date = now().strftime('%Y-%m-%d') %}
        {{ date }}
      time: >
        {% set delta = range(0,30) | random | int %}
        {% set time = '05:45' | today_at %}
        {% set morning = (time + timedelta(days=0,hours=0,minutes=delta)) %}
        {{ as_datetime(morning.strftime(states('input_text.datetime_format'))) }}```
#

the last as_datetime was my last try, did nothing so removed again

obtuse zephyr
pastel moon
obtuse zephyr
#

So you're including a date in your time

#

You know there's a datetime field you can just set both at once? ๐Ÿ™‚

pastel moon
#

Yeah. I removed the last as_datetime()

mighty ledge
#
  - service: input_datetime.set_datetime
    data:
      datetime: >
        {% set delta = range(0,30) | random | int %}
        {% set time = '05:45' | today_at %}
        {{ time + timedelta(days=0,hours=0,minutes=delta) }}
#

pays to read the docs ๐Ÿ˜‰

pastel moon
#

Perhaps easier to do it all at once.. Will try that, thanks. Well I have read it and just thought this ought to work

mighty ledge
#

and if it complains about it needing to be a string,

  - service: input_datetime.set_datetime
    data:
      datetime: >
        {% set delta = range(0,30) | random | int %}
        {% set time = '05:45' | today_at %}
        {{ (time + timedelta(days=0,hours=0,minutes=delta)).isoformat() }}
pastel moon
#

and it works fine in dev-tools... so not easy to find

mighty ledge
#

if you want to set them separately... like you had above

#
  - service: input_datetime.set_datetime
    data:
      entity_id: input_datetime.morning
      date: >
        {{ now().date() }}
      time: >
        {% set delta = range(0,30) | random | int %}
        {% set time = '05:45' | today_at %}
        {{ (time + timedelta(days=0,hours=0,minutes=delta)).time() }}
#

FYI Your range only does between 0 and 29 minutes

#

if you want 30 minutes, you need to change the 30 to 31

pastel moon
#

I tested the joint approach now first, it won't bite either... :/

mighty ledge
#

post the error

#

I'm goign off memory

#

the first or second example should work. so if the one doesn't, the other will

pastel moon
#

no problem, will revert to what I had and try yours ๐Ÿ™‚

obtuse zephyr
#

All of those examples work, so there's another problem if it's not working for you

mighty ledge
pastel moon
#

I do believe you. Just stumped why it refuse to for me...

obtuse zephyr
#

Well, does it come up w/ another error?

mighty ledge
#

Yes, asked for an error quite a while ago

pastel moon
#

still using old initial values from configurations.yaml

mighty ledge
#

You'll be getting an error somewhere

pastel moon
#

which is commented out...

mighty ledge
#

what do you mean "old values"

#

are you reloading the script/automation?

pastel moon
#

this is what I ran with now

  morning:                              
    name: morning                       
    has_date: true                      
    has_time: true                    
#    initial: "1900-01-01 07:00:00" ```
mighty ledge
#

If yes, and config check is passing, but it's not reloading, then there's an error in your logs

pastel moon
#

I am restarting HA even

#

so yes

mighty ledge
#

that has nothing to do with the automatio

#

that's the intial values of the datetime, which will be stored regardless

#

what happens when you run the script or automation?

pastel moon
#

I would say so. It is part of the input_datetime helper definitions

mighty ledge
#

there will be an error if it does not set

pastel moon
#

no?

mighty ledge
#

No

#

input_x's restore state

pastel moon
#

well, it is... But if that is not supported, we may have found the issue...

mighty ledge
#

so you're falsly thinking it's broken, when it's working as intended if the previous state was the initial

#

dude, are you running the automation?

#

yes or no?

pastel moon
#

Everytime it restarts, yes

mighty ledge
#

Ok, look at the damn trace and look for errors.

pastel moon
#

I have...

mighty ledge
#

Ok, then it will say something

#

post it here if you can't debug it

#

there will be errors in your logs or the trace will show you what it set

#

there's nothing else to this

#

don't look at the ending state if it'snot setting it

#

look at the trace

#

click on the service call and see what service data it sent

#

in the trace

#

this is debugging 101

pastel moon
#

format is still wrong. It at least looke correct when we started

#

Ill fix and retry

mighty ledge
#

You're making this really difficult for anyone to help

steep raven
#

how can i create an automation that turns on a switch if a sensor is this numeric state + 20?

mighty ledge
#
  1. You aren't posting errors
  2. You aren't sharing your code
  3. You're just saying "i messed it up i'll fix it" without posting what's messsed up.
mighty ledge
steep raven
pastel moon
#

still not working ๐Ÿ˜ฆ

mighty ledge
steep raven
steep raven
#

not like a + 15

steep raven
# mighty ledge

i do not need the above or under conditions defined so how does this work

mighty ledge
#

you said, you only want to do something if your state is 20 above...

steep raven
#

it always need to do something but it needs the current sensor data + 20

mighty ledge
#

ah

pastel moon
#

now getting Invalid time specified: 2023-05-18 06:09 for dictionary value @ data['time']

mighty ledge
#

seriously man, you are so fucking frustrating to work with

pastel moon
#

ans how do you think I feel about this? I appriciate the help though

mighty ledge
steep raven
#

always the same switch

#

the trigger is a changing sensor temp value

mighty ledge
#

which you aren't doing

steep raven
#

but the trigger / automation is only allowed to execute if another temp sensor is this state + 20

mighty ledge
pastel moon
#

fun shit. Thanks for nothing then

steep raven
mighty ledge
#

why?

#

why?

#

why?

#

Literally makes no sense

#

"Hey I need help but I'm not going to share what's breaking"

#

"Thanks for not helping me"

mighty ledge
steep raven
#

switch.dak_pomp_switch_0 can only be turned on when sensor.dak1_temperature is 20 degrees hotter then sensor.tank_onderin_temperature

mighty ledge
#

Ok, then for the condition all you need is

#
- condition: template
  value_template: "{{ states('sensor.dak1_temperature') | float(-20) + 20 > states('sensor.tank_onderin_temperature') | float(0) }}"
#

the float(0) and float(-20) are default values if the sensor's fail to work

#

if you want to be 100% sure it only works when both sensors are available...

steep raven
#

what

#

๐Ÿ˜…

mighty ledge
#
- condition: template
  value_template: >
    {% set dak = states('sensor.dak1_temperature') %}
    {% set tank = states('sensor.tank_onderin_temperature') %}
    {% if dak | is_number and tank | is_number %}
      {{ dak + 20 > tank }}
    {% else %}
      False
    {% endif %}
#

that's a condition

#

use that as a condition in your automation that turns on the switch

#

Do you know how to make conditions in automations?

steep raven
#

yes but not with yaml code

mighty ledge
#

just select the template condition and paste the code only in the box

plain magnetBOT
mighty ledge
#

the code is this part...

steep raven
#

cant send screenshots here sadly

mighty ledge
#

Just keep in mind, you'll have odd behavior if you lose connection with 1 of the sensors

#

the second template I posted will not turn on the switch at all costs if 1 of the sensors is disconnected

#

food for thought

steep raven
#

it does nothing ๐Ÿ˜…

mighty ledge
#

dak needs to be 20 above tank for it to work?

#

if yes, I have the math wrong

steep raven
#

i changed it to this tho but still nothing

mighty ledge
#

it would be {{ dak - 20 > tank }}

steep raven
#

and this does what exactly?

mighty ledge
#

sorry it's

#
{{ dak | float - 20 > tank | float }}
#

or you could add the 20 to tank, whatever floats your boat

steep raven
#

how would this behave if one of the sensors doesnt report anything or something else then a number?

mighty ledge
#

False

steep raven
#

good

mighty ledge
#

this here

#
{% if dak | is_number and tank | is_number %}
#

checks if they are both numbers before checking

#

if they aren't numbers (i.e. unavailable), then it just returns False

#

make sense?

#

the |float turns it into a number, all states are strings unless told otherwise

steep raven
#

its kinda working

#

i pasted this code aswell for the turn off switch and made it {{ dak | float - 10 > tank | float }} but it turns off inmedtialy

mighty ledge
#

make it a if then else instead of a condition

steep raven
#

its a different automation

#

so it should work right?

#

it turns on perfectly now

mighty ledge
#

it will but it'll be more confusing to work with

steep raven
#

that doesnt matter

mighty ledge
#

๐Ÿ‘

steep raven
#

what matters is is its turning it off even always on change ๐Ÿ˜‚

#

and not on dak is + 10 from tank onderin

mighty ledge
#

so, wouldn't you want to turn it off when it's below 20?

#

you know what I mean on when +20, off else

#

unless you want it to stay on from 10 to 20

steep raven
#

so

#

turning it on works now when its + 20

#

i want it to turn off when its only + 10

#

in a different automation

mighty ledge
#

Ok, so...

steep raven
#

with static numbers this worked great but as the day goes on the tank will warm up and then you are constantly adjusting manually xd

mighty ledge
#
- condition: template
  value_template: >
    {% set dak = states('sensor.dak1_temperature') %}
    {% set tank = states('sensor.tank_onderin_temperature') %}
    {% if dak | is_number and tank | is_number %}
      {{ dak | float - 10 < tank | float }}
    {% else %}
      False
    {% endif %}
#

notice how I flipped the > to <

#

that's less than or greater than

steep raven
#

it can be the same automation tho if possible but then how would i know / verifiy its off?

mighty ledge
#

you can put conditions in a choose

#

so, choose: switch is off & > 20.... turn on, choose: switch is on & < 10 turn off

#

and then no default for the choose (to keep it whatever the state is)

#

but keep in mind, if one goes unavailable with the off, and it's on, it'll stay on

#

so you'd need to decide if you want to change that func

steep raven
#

seems to work perfectly now with this on seperate automations ๐Ÿ™‚

mighty ledge
#

personally, Id keep the logic how i described and just notify myself when those sensors go offline

#

if they are that important

steep raven
mighty ledge
#

just make a normal automation separate from these

#

with a trigger for when the sensors go to 'unknown' or 'unavailable'

steep raven
#

will try

mighty ledge
#

no templates will be involved, so it should be pretty straight forward

#

state trigger, notification action

#

very short, very straight forward

steep raven
pastel moon
# mighty ledge "Thanks for not helping me"

I don't need the attitude. You're usually nice and helpful, but different today. Let's just leave it at that. If you are intrerested, it is a problem with my home assistant database..

mighty ledge
#

There's no way it's an issue with your database.

#

that does not cause an automation service to fail

#

And I'd be nicer to you if you actually provided the information that was asked

#

but for some reason, you continue to not provide it

#

2 things requested multiple times were: Logs and full automation

#

things that were provided when requested: 0

#

Put yourself in another person shoes. If someone is taking the time out your day to help someone, and they aren't giving you the information you ask for, would you be happy to continue to help?

#

especially when you get nothing out of it?

#

No.

#

So, you don't listen, you don't provide information, you get pissed off helpers.

steep raven
#

@mighty ledge idk is this is the right channel but can i embed like graphs from dashboards inside emails that home assistant sends via an automation?

mighty ledge
steep raven
#

i have now one that sends current sensor statusses but entire graphs would be awesome

mighty ledge
heavy crown
mighty ledge
#

What would be the correct order?

#

just hard code that instead of using 'options'

weary drift
#

I hope this is the correct place to ask this.
I've got a binary sensor that looks like this - it returns unknown.

platform: command_line
name: embysessionplayroom
command: "curl -H \"Content-Type: application/json\" -H \"X-Emby-Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\" -X GET \"http://ip:port/emby/Sessions\" | jq -r '.[] | select(.DeviceId==\"xxxxxxxxxxxxxxxxxxxxxxxxx\") | .Id'"
scan_interval: 4

But if i run the curl command in the terminal in HA without escape characters like this curl -H "Content-Type: application/json" -H "X-Emby-Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxx" -X GET "http://ip:port/emby/Sessions" | jq -r '.[] | select(.DeviceId=="xxxxxxxxxxxxxxxxxxxxxxxxxxx") | .Id' i get the response i want.

What am i missing here?

mighty ledge
#

also keep in mind that it will be unknown at startup until it's polled

weary drift
mighty ledge
weary drift
#

Ooh

mighty ledge
#

it's a binary sesnor, it has a value of on or off

weary drift
#

Ah of course. I'll have to use something else

mighty ledge
#

a normal comand_line sensor can pull the payload and do things with it

weary drift
mighty ledge
#

np

hearty verge
#

How do i add items to a dictionary in a template?

inner mesa
#

you can't, but you can create a new dict based on the original. See this from a couple of days ago (last line): #templates-archived message

hearty verge
#

Im' trying to process some JSON data into a dictionary withy float keys ... i'll give that a look

#

Any way to get around:

SecurityError: access to attribute 'update' of 'dict' object is unsafe.
inner mesa
#

yes, you need to see the example

#

as I said, you cannot update an existing dict

hearty verge
#

Your exmaple talks about removing keys

#

not modifying them

mighty ledge
#

You canโ€™t modify collections

hearty verge
#

But i can iterate through a collection and "convert" stuff and then make anew collection rightg?

inner mesa
#

you asked how to add a key to a dict, and the example shows that

mighty ledge
inner mesa
#

specifically, it shows how to modify a key (which really just means remove the old one and add a new one)

hearty verge
#

Let me rephrase ๐Ÿ™‚

Given a dictionary of "string:"string and i want to convert it to float:string (where the keys are floats) is that doable

mighty ledge
#

Yes but you need to create a new collection.

hearty verge
#

I asusme i can process | items and do ac onvert

#

This gives me pairs right?

{{ json_input | to_json | items  }}

So I'm assuming i can apply a function to the key? is that correct

mighty ledge
#

Youโ€™d want from_json

hearty verge
#
{% set json_input = {"0":"#FEC4FF","10":"#D977DF","20":"#9545BC","30":"#4B379C","40":"#31B8DB","50":"#31DB8B","60":"#6ED228","70":"#FFFF28","80":"#F87E27","90":"#CF3927","100":"#A12527"} %}
{{ json_input | to_json | items  }}

It doesnt work with from_json

mighty ledge
#

Because your data isnโ€™t a string

hearty verge
#

ah!

#

gotcha

inner mesa
#

it's already a dict

mighty ledge
#

Iโ€™m on mobile but youโ€™d need to iterate the items. Create a new list of key value pairs that have the transformed values. Then you create the dictionary using fromkeys

hearty verge
#

i'll look into fromkeys

#

so items will return tuples...

mighty ledge
#

Thatโ€™s sort of what you have to do

hearty verge
#

Thats 100% i think what i need

#

thanks

mighty ledge
#

Itโ€™s not a great example but it would work

#

I need to update that code

hearty verge
#

so going from dict -> items -> list gives me a set of tuples

#

modify the 1st entry of the tuple

#

reassemble to a dictionary

mighty ledge
#

Right

#

But youโ€™ll have to use namespace to create the new list

hearty verge
#

Namespace? like {% set new_list =}

mighty ledge
#

Because you canโ€™t modify with jinja, only create

hearty verge
#

interesting

mighty ledge
#

584 creates a list in namespace

hearty verge
#

I've not seen that before

mighty ledge
#

589 adds to the list

#

Youโ€™ll be adding a tuple with a key and a value

#

E.g. (key, value)

hearty verge
#

so i could do a k,v in dict|items

#

this is cool

#

i'll play with it

mighty ledge
#

Yes, and alter the value there, then pass the namespace variable you created in 584 to from_keys (after the loop)

hearty verge
#

Thanks!

#

I think i'm on the right path

#

Way to go namespaces! ๐Ÿ™‚

mighty ledge
#

Thatโ€™s the only path, so yes itโ€™s the right path

hearty verge
#

Of course I'm going down this rabbit hole to make a totally obscure feature in a blueprint i have no idea if anybody will use ๐Ÿ™‚

mighty ledge
#

Yep! Sounds about right

hearty verge
#

Trying to let people enter their own color array ... to render temp ranges on an awtrix clock

inner mesa
#

I've never used dict.from_keys() before. it's cool

mighty ledge
#

It allows you to create a dict using all the no-no characters

hearty verge
#
{%- macro json_to_float_dict(json) -%}
  {%- set ns = namespace(tuples=[]) %}
{%- for k,v in json_input | from_json | items -%}  
  {%- set key = k|float %}
  {%- set ns.tuples = ns.tuples + [(key,v)] %}      
{%- endfor %}
{{ dict.from_keys(ns.tuples) }}
{%- endmacro -%}
inner mesa
#

interestingly, the Python dict.fromkeys() seems less useful

mighty ledge
#

I think fromkeys is old

inner mesa
#

you can only specify one value to be repeated

mighty ledge
#

Thatโ€™s nice if you want to create a quick dick with none in all values from a list

#

List of keys

inner mesa
#

not helpful at all with our limited Jinja support

mighty ledge
#

Yep

#

Itโ€™s nice in python tho ๐Ÿคฃ

lament garnet
#

Is it possible to calculate once and return all values with different attributes? Along the lines:
- sensor: unique_id: panel name: panel state: >- {% set degrees = 31 %} {% set radians = (pi/180) * degrees %} {{ degrees }} attributes: degrees: "{{ degrees }}" radians: "{{ radians }}"

hearty verge
#

Good question... i need to figure out how to add attributes to some of my stuff

inner mesa
#

variable scope is to the template, typically

mighty ledge
#

Well it is with a trigger sensor

inner mesa
#

you can set the state and then refer to the state in the attributes

maiden magnet
#

is there a possibility to display the time formatted? I don't want it to look like this "2023-05-18T19:46:33. 161018+00:00", but May 18, 2023, 23:05

inner mesa
spice current
inner mesa
#

Nobody is going to help with raw ChatGPT output

spice current
# inner mesa Nobody is going to help with raw ChatGPT output

It's hard to summarize it tbh but i can just copy and paste my initial request for chatgpt if that's what you want;

I have a homeassistant instance with the following devices:

  • light.ceiling_light
  • light.floodlight
  • light.led_strip

I want you to create a config entry for input_select.lights_color that has the following options:

  • Off: Should turn off all lights
  • Bright: Should turn on all lights with cold white color and 100% brightness
  • Red Bright: Should turn the floodlight off, ceiling_light and led_strip to 100% bright red
  • Red Dark: Should turn floodlight and led_strip off, ceiling_light to 5% red
  • White: Should turn the floodlight off, ceiling_light and led_strip to 100% bright warmwhite
spice current
obtuse zephyr
#

What are you having problems with? That sounds like an automation you can make solely using the Automation UI if you wanted

spice current
#

it's a pain in the butt to split it into a lot of scripts 'n stuff tho. the way gpt proposed it looks really slick using service_template and data_template to get everything into one compact automation

obtuse zephyr
#

You can get all of that in a single automation if you want... the problem with what it proposed is the fact that it doesn't work and is non-sense

ornate ruin
whole oracle
#

How can I see what the output is on a aqara fp2 sensor? It clear and detected. The aqaua app log shows someone is going away, someone is approaching. and other things. Ho can I find these in home assistant sensor?

lament dust
#

Is there a way to see when an entity was last in X state?

#

For instance with a binary sensor want to basically say if device X didn't detect motion in the last 10 minutes

inner mesa
#

the easiest generic way to do that is to create a template binary_sensor that checks for that condition, and the use the last_updated property of that entity

#

but for your specific use case, it sounds like you just want an automation with a state trigger and a for: block

arctic sorrel
mighty ledge
#

Holy crap that's alot of text

#

it's using outdated functionality and making up functionality. Oof, that's why people who know better don't bother with chatgpt

lament dust
# inner mesa but for your specific use case, it sounds like you just want an automation with ...

Not sure what you mean exactly. Basically I have a binary sensor for if the washing machine is on or off. When it goes from on to off I send a notification saying it's done. I have all of this working already.

But I want to add a check to basically say if movement was detected in the laundry room in the last few minutes then don't send a notification because it was likely emptied already

obtuse zephyr
lament dust
#

Hmm possibly is there a way to say any state but on?

#

So something like if state is off, or unavailable, etc.
for greater then 5 mins send notification

obtuse zephyr
#

You won't get something like that without coming up w/ a template sensor like Rob mentioned

lament dust
#

Okay so how would you suggest I do it? I'm open to other ideas

obtuse zephyr
#

Does it actually go unavailable where that's a case you need to handle?

lament dust
#

Yeah it does quite frequently otherwise I wouldn't bother

#

It's a BLE sensor from UI

#

It's not usually for long periods of time more like it drops for a few seconds

mighty ledge
#

an if then else can do that.

#

if with condition on, else... yadda yadda yadda

#

You can also make triggers using not_to

#

with for

#

there's about 100 different ways you can make this automation

obtuse zephyr
#

and that way.... if your motion sensor flips to on... flips back to unavailable and then flips to off within the span of a minute, and then a minute later your trigger goes off, you won't get a notification

mighty ledge
#

in fact, that's what I did

#

but my washer is a dumb washer, so it's a bit more complicated

#

I had to time cycles to figure out when it's done

#

luckily, the final rinse cycle is exactly 10 minutes long, so I just key off that

spice current
sonic ember
#

Something strange suddenly, and I don't think I changed anything. In VSCode for each file I open, I now see:
Unable to load scheme from 'http://schemas.home-assistant.io/integration-template': No content.
Is something wrong with HA, or did something happen to my instance?

#

Basically says it as a notice on the first line of the file.

obtuse zephyr
#

The plugin in the latest VSCode add-on version is broken

#

Restore your backup of the prior VSCode add on

sonic ember
#

Ah, so it's an add-on issue. Just have to wait then or restore indeed. Thanks

obtuse zephyr
#

Namespaces typically aren't in DNS necessarily

sonic ember
#

Is it a breaking change in terms of using VSCode, or just the checking of the template structure and colouring, etc.

obtuse zephyr
#

It's just breaking schema validation

sonic ember
#

Ah, so risky in case I make a mistake ๐Ÿ™‚ Thanks

obtuse zephyr
#

You can still use VSCode, but it won't scream at you if you don't follow the schema

#

Correct

sonic ember
#

Let me restore then, safer I think

obtuse zephyr
#

Indeed, it's been broken for over a month at this point so a restore is the best option

spice current
#

you could always do CTRL+SHIFT+P -> Check config tho right?

sonic ember
#

Is there a simpler way to restore than copy-pasting the directory from my backup?

obtuse zephyr
#

Settings -> System ->Backups... find the VSCode one

sonic ember
#

Ah yeah, thanks! 5.5.6 is the last working one, correct?

obtuse zephyr
#

Yep

sonic ember
#

Thanks!

#

Man I wish all my utilities, phone provider, insurance, etc. etc. was open/community sourced

lament dust
#

So after usage drops below a few watts for 2 minutes I assume its done and send a notification

#

Thats been working great. I just want to avoid a notification if I go in before its done and take it out, or get their before the notification fires

obtuse zephyr
#

Contact sensor is good for that as well

gusty blaze
#

I don't know if this is the right place to ask, bug I'm having trouble using unique_id on a command_line sensor... I have the following:

sensor:
  - platform: command_line
    name: CPU Temperature
    unique_id: rpi_cpu_temperature
    command: 'cat /sys/class/thermal/thermal_zone0/temp'
    unit_of_measurement: 'ยฐC'
    value_template: '{{ value | multiply(0.001) | round(1) }}'

but when I restart HA, the id loads as sensor.cpu_temperature

mighty ledge
#

your entity_id is built off the name, not the unique_id

#

unique_id is for the UI to know what device is what so you can adjust it's settings in the UI

#

There's no way to set up an entity_id that differ froms the name in yaml without using customize.yaml

plain magnetBOT
#

@gusty blaze By default, all of your devices will be visible and have a default icon determined by their domain. See customizing devices for how to change that.

gusty blaze
#

I see, so to achieve what I want I'll have to set the name to RPi CPU Temperature and then customize the friendly_name to CPU Temperature... I think I got it, thanks

willow wing
#

Hey, is it possible to give tem state an wildcard to track all calender entities?
{{ now().replace(second=0)|as_timestamp|int -(state_attr('calendar.xxxxxxxx_googlemail_com','start_time')|as_datetime - timedelta(days=1))|as_timestamp|int }}

mighty ledge
#

no, you have to iterate all calendar entities

willow wing
#

ok, thanks

steep raven
#

i have 1 humidity sensor and i want it to turn on a switch 10 mins after it has been above 70% how can i do this?

steep raven
mighty ledge
steep raven
mighty ledge
sonic nimbus
#

hello I ahve this error: Message malformed: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sequence'][0]['if'][0]['value_template']
And Im trying to check if my variable coresponds to exact string

alias: New Script
fields:
  command:
    description: command type
    example: mute-speakers
icon: mdi:desktop-classic
mode: parallel
max: 10
sequence: 
  - if:
    - condition: template
      value_template: > 
        {{ command) == 'mute-speakers'}}
    then:
    - alias: Mute Office Speakers
      service: button.stefanpc_speaker_mute
obtuse zephyr
#

You've got a ) after command

inner mesa
#

The error message even says that

rancid pelican
#

hi guys

#

i genting some error in my sensor template

#

can someon help me

#
  • platform: template
    sensors:
    angulo_coletores_rebatido:
    friendly_name: Angulo Coletores Rebatido
    unit_of_measurement: "ยฐ"
    value_template: >-

        {% set Azimute = states('sensor.azimute_solar') | float %}
        {% set Zenite = states('sensor.angulo_zenite') | float %}
        
        {% if (Azimute < (-90))%}
        {% set A = (Zenite + (90)) %}
         {% else %}
        {% endif %}
        {{A}}
    
mighty ledge
#

A isnโ€™t declared if azimuth is greater than -90

karmic elk
#

I am creating a template which shows the value of time left to charge in minutes , I would like to be shown like say "2 hours and 32 mins " . Is there any pre defined formula available ? or I need to use something like "/60" ?

marble jackal
karmic elk
karmic elk
marble jackal
#

@karmic elk You said the sensor displayed the number of minutes

#

It actually shows the time it's finished

#

In the case, just use the state of the sensor as input

karmic elk
marble jackal
#

int(0) converts the part before it to an integer with 0 as it's default

#

But that's not what I meant, however as you are providing images of code, I can't really copy paste your input any correct it.
What I meant is you should use the state of the sensor as input of the macro

karmic elk
#

sorry , here is the code and result

{{state_attr('sensor.time_charge_complete','minutes_to_full_charge') }}
{{states('sensor.time_charge_complete')}}```
result
```2023-05-20 08:01:00.432890-07:00
380
2023-05-20T15:00:01+00:00```
marble jackal
fallow gulch
#

I have a template sensor that's supposed to use the value of my solar generation if it's available, and replace it with 0 if it's unavailable. It's not working, and I don't know enough about templates to understand why.

{% if states('sensor.solar_pac') != 'unavailable' %}
  {{(float(states.sensor.solar_pac.state))}}
{% else %}
  {{ 0 }}
{% endif %}
marble jackal
fallow gulch
#

Yeah, I get an error

#

I'm sure it used to work

marble jackal
#

Aaah, an error.. which one specifically?

fallow gulch
#

I think it's to do with my inverter turning off when the sun is down

#

UndefinedError: 'None' has no attribute 'state'

#

if the inverter is off when HA starts, and there's nothing to pull the data from, then the entity isn't created. So there's no 'state'.

marble jackal
#

If that's the error, your sensor doesn't exist

fallow gulch
#

yeah, not something I can overcome I guess

marble jackal
#

Check in developer tools > states

#

Yes, you can, by using states() like you did in the if statement

fallow gulch
#

ah so instead of float, gotcha

marble jackal
#

And not state.sensor.bla.state

#

No, instead of that

fallow gulch
#

ah

marble jackal
#
{% set s = states('sensor.solar_pac') %}
{{ s if s | is_number else 0 }}
fallow gulch
#

much more elegant

#

thank you

#

I have a similar one, which is giving me a different error. I'm trying to have a sensor use the value of my HA Glow when the sun is down, and a CT clamp when the sun is up.

#

It seems my electricity supplier changed something on my meter, and now the pulse light isn't showing my imported energy anymore

#

it's flashing on bi-directional supply now

#
  {{(float(states.sensor.power_sensor_live_power))}}
{% else %}
  {{(float(states.sensor.house_power_consumption))}}
{% endif %}```
#

I'm getting TemplateSyntaxError: expected token 'end of statement block', got '='

#

I'm guessing I can't use sun.sun in that way

obtuse zephyr
#

== for equality

#

Should use states() to grab the state value as well

fallow gulch
#

yeah, I've rewritten it

#
{% set esp32 = states('sensor.house_power_consumption') %}
{% set sun = states('sun.sun') %}
{% if sun == 'above_horizon' %}
  {{d1}}
{% else %}
  {{esp32}}
{% endif %}```
#

that looks like it's working

silent vector
#

Is there a way to use template triggers in automations to emulate time pattern without using time pattern? Under certain conditions I would want the automation to trigger every minute and others not trigger. I can use a condition and a time pattern but I was not sure if it is better for performance to not trigger at all unless needed. Rather than triggering every minute only to hit a condition to stop the automation.

obtuse zephyr
#

In any case, there'd still be the need to evaluate whether to trigger, whether it's through a template or time pattern. Without knowing what your actual condition is, it's hard to give a concrete answer. Condition is probably the easiest route, depending on how frequently it'll need to actually execute, you could have another automation to turn on/off this automation though, too.

silent vector
#

Yeah that's something I thought about as well.

#
{{ (now().hour * 3600 + now().minute * 60 + now().second) % 75 == 0 }}

would this work as a trigger? It's not 1 time a minute but I'm curious.

thorny snow
#

Does anyone know if I can hardcode a template into a blueprint, so I can share my blueprint with others? The template has some logical converters so the vallues in the blueprint can be easily adjusted by a number input field.

#

This has to be transcoded to the automation after one published the automation

marble jackal
silent vector
#

Interesting. So just use now() and xyz for me to get a trigger when xyz is true?

sacred sparrow
#

is there a way I can:
a) make it only one decimal point
b) have it shown as "kB/s"

    - name: "NAS Total Throughput"
      availability: "{{ states('sensor.nas_download_throughput') | is_number }}"
      icon: mdi:cached
      device_class: data_rate
      state: "{{ states('sensor.nas_upload_throughput')|float + states('sensor.nas_download_throughput') | float }}"```
inner mesa
#

Yes. |round(1) and add a unit_of_measurement

sacred sparrow
#

any reason why its showing as "scanning" even though its above 300 and below 1000?

inner mesa
#

Those statements aren't formatted properly

#

They don't make sense

#

1 < x < 2

#

Not what you gave

#

Just think about the syntax

sacred sparrow
#

sorry I am not following

#

isn't >= 10 < 300 greater than or equal to 10 but less than 300?

inner mesa
#

No, there is no such syntax

#

You made it up

sacred sparrow
#

oh I see haha

inner mesa
#

I showed you the right syntax

sacred sparrow
#

thats the part I am not following sorry

#

I think this will work better ๐Ÿ™‚

inner mesa
#

It will, yes. But you should learn how to do what you originally tried as well

sacred sparrow
#

Ahh that makes sense. Thanks for that

sonic ember
#

Having an issue with a template that used to work fine. Think something changed in the new versions and my code isn't compatible. This is the error:
Dishwasher - Set Start Time: Error executing script. Invalid data for call_service at pos 1: Invalid datetime specified: 2023-05-20 12:00:00+02:00 ## My Template for dictionary value @ data['datetime']

plain magnetBOT
marble jackal
#

The error comes from s script in which you issue a service call

#

Not from a template sensor

sonic ember
#

And this is the template that sets the "cheapest hour"

#
  - name: "NextEnergy Cheapest Hour Dishwasher"
    unique_id: 0f509f15-5e37-4366-920c-2e0981e16eda
    icon: mdi:clock
    state: >
      {% set hour_threshold = states('input_number.dishwasher_hours_ahead') | int(0) - 5 %}
      {% set time_threshold = now().replace(minute=0, second=0, microsecond=0) + timedelta(hours=hour_threshold) %}
      {% set items = state_attr('sensor.energyprices','raw_today') + state_attr('sensor.energyprices','raw_tomorrow') %}
      {% set lowest = items | selectattr('start', '>', now()) | selectattr('start', '<=', time_threshold) | sort(attribute='value') | first %}
      {% set lowest_price = lowest.value * states('input_number.nextenergy_additional_electricitycosts') | float(0) %}
      {% set cheapest_time = lowest.start %}
      {{ cheapest_time }}
obtuse zephyr
#

You've got a "comment" of ## My Template somewhere that got into the datetime value

gentle zealot
#

I was wanting the AC to turn on to cool in a certain zone if an outside temp is higher than certain temp. I have a zoned system with 4 Thermostats and need HA to check if none of them are set to heat. I was wondering if this is the Template i need to use in an automation because the {{ is_state('climate.first_floor_thermostat', 'heat') }} template will only give me a false answer. The iif Template below seems to work in Developer tab Template i just needed some direction and advice.
{{ is_state('climate.first_floor_thermostat', 'heat') | iif('False', 'True')}}
{{ is_state('climate.basement_thermostat_2', 'heat') | iif('False', 'True') }}
{{ is_state('climate.master_bedroom_thermostat_4', 'heat') | iif('False', 'True') }}
{{ is_state('climate.second_floor_thermostat_3', 'heat') | iif('False', 'True') }}

sonic ember
#

Sorry, accidental @ ๐Ÿ™‚

obtuse zephyr
#

The error indicates that it's making it into the value from what I can tell

sonic ember
#

Lets see what happens if I remove it

waxen meadow
#

Hi guys, i want in State only when is power more than 2W+, is it possible to do it?
- platform: history_stats name: Boiler Heating Time entity_id: sensor.boiler_power state: ">= 2" type: time start: "{{ now().replace(hour=0, minute=0, second=0) }}" end: "{{ now() }}"

inner mesa
#

You need to make a template binary_sensor for that, and then use it for history_stats

waxen meadow
#

ok thx

waxen meadow
#

Can someone tell me where I'm going wrong?
** - platform:
sensors:
boiler_heating:
friendly_name: Boiler Heating
icon_template: mdi:water-boiler
device_class: heat
value_template: >-
"{{ states('sensor.boiler_power')|float > 2 }}"**

marble jackal
#

Don't use quotes around your template if you use the multi line format

waxen meadow
#

same problem

inner mesa
#

You didn't say what the problem was

#

You also didn't format your code

waxen meadow
#

Invalid config for [binary_sensor]: string value is None for dictionary value @ data['platform']. Got None. (See /config/configuration.yaml, line 44).

inner mesa
#

Seems clear enough

waxen meadow
#

after when i create this binary sensor

inner mesa
#

You didn't follow the format

waxen meadow
#

sorry I didn't see it platform: template

dim roost
#

I've got a relatively basic question about templating yet again. I have the following and I'd like to make it more generic with the device name in the value_template and both entity_ids:

#
  - platform: template
    switches:
      ac_toggle:
        friendly_name: "Air Conditioning"
        value_template: "{{ not is_state('climate.fujitsu_ac', 'off') }}"
        turn_on:
          service: climate.turn_on
          target:
            entity_id: climate.fujitsu_ac
        turn_off:
          service: climate.turn_off
          target:
            entity_id: climate.fujitsu_ac
#

possibly also the friendly_name

#

or, if there's a better way, I'm all ears. Weird that there's no climate.toggle

marble jackal
#

There's not much you can do here to make it more generic, unless you either add the object id in the entity id or friendly name

dim roost
#

Ok, that's fine then - thanks

marble jackal
# dim roost Ok, that's fine then - thanks
switch:
  - platform: template
    switches:
      toggle_fujitsu_ac:
        friendly_name: "Air Conditioning {{ this.entity_id.split('_')[1:] | join(' ') | title }}"
        value_template: "{{ not is_state('climate.' ~ this.entity_id.split('_')[1:] | join('_'), 'off') }}"
        turn_on:
          service: climate.turn_on
          target:
            entity_id: climate.{{ this.entity_id.split('_')[1:] | join('_') }}
        turn_off:
          service: climate.turn_off
          target:
            entity_id: climate.{{ this.entity_id.split('_')[1:] | join('_') }}
dim roost
#

I see what you mean. I think I'll just put in all 3, just in case I want to change things later

stuck remnant
#

TemplateError('ValueError: Template error: float got invalid input 'unknown' when rendering template '{{ states('sensor.192.168.100.35_sound')|float > 150 }}' but no default was specified') while processing template 'Template<template=({{ states('sensor.192.168.100.35_sound')|float > 150 }}) renders=4>' for attribute '_state' in entity 'binary_sensor.bathroom_threshold'

#

what must I do

marble jackal
#

define a default for the float filter, or add an availability filter to your template sensor

#

if it's a template sensor

fickle sand
marble jackal
#

and that ๐Ÿ™‚

#

check the correct entity id in developer tools > states

plain magnetBOT
stuck remnant
#

wow didn't catch that, cheers

bitter falcon
#

I can't get piper or whisper on my system

#

I'm up to date

mighty ledge
#

This is the template channel.

pastel moon
#

Hi. I have used the top one up until now because it gave me a value even when the light was turned off. This does no longer work and I have to resort to the lower notation which does not. Is there a way of achieving the same functionality?

{{ states.light.speaker_rgb.attributes.brightness }}
{{ state_attr('light.speaker_rgb', 'brightness')}}
mighty ledge
#

That's not true

#

the first one would error out if the attribute didn't exist

#

that's never changed

#

that's why the first method is not suggested

#

@pastel moon ^

pastel moon
#

Well, now it does yes. But my code is unchanged since it did work... ๐Ÿ˜ฆ Oh well, will have to find another way then. Thx

mighty ledge
#

ther'es no well now it does, it's always been like that

#

literally

#

it's a dictionary, if the item doesn't exist, it will error

#

and lights from day 1 do not have the brightness attribute when off

#

so that code would have errored from day 1

pastel moon
#

Will not argue, so will check my backups. Something is not adding up, but agree that the first sounds unlikely.

#

Now it's a mystery. Backups from december show the same statement, and back then I know it did work. That aside then (I hear you), is there any way to mimic that behaviour?

#

ie to get the brightness level for a light?

marble jackal
#

you can default it to 0 when it's off

#

{{ state_attr('light.speaker_rgb', 'brightness') | default(0, true) }}

pastel moon
#

Thanks, that's an improvement, but I would need the last set level as baseline for a calculation...

mighty ledge
marble jackal
#

If you need the last level you need to store it in an input_number, using an automation, or in a trigger based template sensor

pastel moon
#

Thanks, I'll have to modify it to use that then.

mighty ledge
#

If you had that behavior in the past, this must have been a light that you manually created or a custom integration. If it was a built in integration, then post what integration that light came from

pastel moon
#

Philips HUE in this case, connected through Z2M. Can the code have been lingering and removed about last week in some update?

mighty ledge
#

that would be an MQTT light

pastel moon
#

Ok

mighty ledge
#

I've been using that for about a year now

#

and those have always had no brightness when the light is off

#

did you use auto discovery or did you use manual configuration?

pastel moon
#

It hasn't thrown an error at least

#

To include it? I really don't remember, it was a long time ago

mighty ledge
#

Can you post the code you were using?

pastel moon
#

Auto I assume

#

Yes, give me a minute

#

it is called by an automation to set some parameters, but brightness was read from the script itself

mighty ledge
#

Are you 100% sure you've ran this when the lights are off?

#

this would have errored for years

#

there is countless forum posts about this

pastel moon
#

Absolutely. It is suppose to flash lights when for example the washing machine is done, which happens regardless of lights on or off

mighty ledge
#

I don't see how this could have ever worked

pastel moon
#

I don't know now either... :/

mighty ledge
#

That script can't be that old

#

you're using this.entity_id

#

that's maybe a year old now

pastel moon
#

Yes, I try to keep it reasonably updated...

#

I suppose I have to settle for a set default value then. It'll do the job. Nice with reading the brightness was it was never too bright. But not the end of the world...

#

The default @marble jackal mentioned makes it work, so happy with that. Thanks for having a look

spiral imp
#

I have an sensor attribute of "300" that is in seconds, so 5 minutes. I am trying to create a template that adds that attribute value to the state change of a switch. This template gives me the last state change of the switch: {{ as_timestamp(states.switch.bhyve_back_central_zone.last_changed) }}

marble jackal
#

{{ states.switch.bhyve_back_central_zone.last_changed + timedelta(seconds = state_attr('your_sensor', 'the_attribute')) }}

spiral imp
#

Thanks, had too add in the second ")" at the end but it other worked

floral steeple
#

hi all, im trying to create a sensor for imap_content but, im not sure where it place this code from the docs
https://www.home-assistant.io/integrations/imap/
it says i can use the " data in a template sensor."
its not accepting the word trigger when placing it in my templates.yaml in sensor.

inner mesa
#

Don't put template: in templates.yaml, just put the rest

#

you already presumably have template: in configuration.yaml

floral steeple
#

correct, but it does not accept the word trigger

#

maybe I have to place the sensor part in sensor.yaml?

inner mesa
#

its not accepting the word trigger when placing it in my templates.yaml in sensor.
What is not accepting it?

floral steeple
#
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['date'] }}'
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['headers']['Delivered-To'][0] }}'
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['headers']['Return-Path'][0] }}'
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['headers']['Received'][0] }}'
Template variable error: 'trigger' is undefined when rendering '{{ trigger.event.data['headers']['Received'][-1] }}'
inner mesa
#

where do you see that?

floral steeple
#

core logs

inner mesa
#

that doesn't make sense

mighty ledge
#

You're looking at old logs or the wrong spot

#

Also seems odd to me that you have those logged errors without a timestamped line

inner mesa
#

you probably didn't have the trigger: part when it produced those logs

mighty ledge
#

which leads me to believe you're looking in the wrong spot

floral steeple
#

lol let me try this again

#

one second

mighty ledge
#

where did you get those logs from?

floral steeple
#

it was in core after I refreshed tamples

#

let me trying again....

mighty ledge
#

what do you mean "in core"

floral steeple
#

core logs

mighty ledge
#

from the UI?

floral steeple
#

when I press refresh template enties

#

I get this error

mighty ledge
#

the friendly_name above shows me that you're putting this in the wrong spot

floral steeple
#
The following integrations and platforms could not be set up:

template (Show logs)
Please check your config and logs.

log

Logger: homeassistant.config
Source: config.py:982
First occurred: 9:27:44 AM (2 occurrences)
Last logged: 9:51:18 AM

Invalid config for [template]: [trigger] is an invalid option for [template]. Check: template->sensor->31->trigger. (See /config/templates.yaml, line 1).
mighty ledge
#

or the friendly_name above is not correct

#

ah ok, based on that error, your indentation is too indented

#

so as it turns out

#

you're incorrectly using friendly_name and you spaced it out wrong

inner mesa
#

and the binary_sensor: below says that you've messed up your indentation

mighty ledge
#

the - trigger: should be at the same indentation level as - binary_sensor:

#

and because I have a feeling you're going to omit doing sensor... sensor needs to be the same indentation level as trigger, but without the dash.

#

I have no idea how you manage to do yaml

#

I'm trying to just look at your image and find out the spacing you have above and it doesn't match any standard practice, and it doesn't match what you have below on - binary_sensor:

#

Oh wait, I guess you're doing

- field:
    - field:
        sub_field:
#

if that's the case, then just copy/paste this.

#
- trigger:
    - platform: event
      event_type: "imap_content"
      id: "custom_event"
  sensor:
    - name: imap_content
      state: "{{ trigger.event.data['subject'] }}"
      attributes:
        Message: "{{ trigger.event.data['text'] }}"
        Server: "{{ trigger.event.data['server'] }}"
        Username: "{{ trigger.event.data['username'] }}"
        Search: "{{ trigger.event.data['search'] }}"
        Folder: "{{ trigger.event.data['folder'] }}"
        Sender: "{{ trigger.event.data['sender'] }}"
        Date: "{{ trigger.event.data['date'] }}"
        Subject: "{{ trigger.event.data['subject'] }}"
        To: "{{ trigger.event.data['headers']['Delivered-To'][0] }}"
        Return_Path: "{{ trigger.event.data['headers']['Return-Path'][0] }}"
        Received-first: "{{ trigger.event.data['headers']['Received'][0] }}"
        Received-last: "{{ trigger.event.data['headers']['Received'][-1] }}"
floral steeple
#

got it! that was it, placing the above ^

#

thank you!

#

thank you @mighty ledge and @inner mesa

inner mesa
#

now would be a good time to study that and understand how YAML indentation works ๐Ÿ™‚

floral steeple
#

yes, I had the impression that only sensor or binary_sensor was allowed as primary (left most entries), but as I learned today, that is not he case ๐Ÿ™‚

plain magnetBOT
final abyss
#

I want to use 2 input selects to output a value. 1 for meat type and 1 for cook temp. 1 selects Pig 1 selects Medium and i want a sensor outputting 160. My template skills are lacking.. Any ideas? (Json table to pick values from posted above)

mighty ledge
final abyss
#

Thanks!

earnest arrow
#

ok i have to be missing something completely obvious

#

value_template: "{% for device in json_data.devices %}{% if device.serial_num == 'xyz' %}{{ device.soc }}{% endif %}{% endfor %}"

#

The system cannot restart because the configuration is not valid: Invalid config for [rest]: template value should be a string for dictionary value

marble jackal
earnest arrow
#

a number

mighty ledge
#

no quoting issues

earnest arrow
#

i assumed the error meant the template itself needed to be a string in the yaml

mighty ledge
#

๐Ÿคทโ€โ™‚๏ธ

earnest arrow
#

works fine in the dev tools template editor too

earnest arrow
#

works even better when i have it indented properly ๐Ÿ˜‚

sonic nimbus
#

is there any way to get from trigger from_state how much that entity was in state on, and when its changed the state to ask something like '{{state.from_state.entity was more 10min}} then do something'

marble jackal
#

trigger.to_state.last_changed - trigger.from_state.last_changed

silent vector
#

Is it possible if I have a list like this to grab 2 starting from the highest 3 digit value so 4.
Would return
foo003, foo004

{% set foo = ['foo001','foo002','foo003','foo004'] %}
inner mesa
#

The highest 3 digit value or the one you specify?

#
{% set foo = ['foo001','foo002','foo003','foo004'] %}
{{ (foo|sort)[-2:] }}
#
{% set foo = ['foo001','foo002','foo003','foo004'] %}
{% set input=4 %}
{% set index=foo.index('foo' ~ "%03d"|format(input)) %}
{{ foo[index-1:index+1]|join(', ') }}
silent vector
#

Thank you that's really much simpler than I thought lol

hidden coral
#

Hi I am trying to create a sensor that can alert me of Power Outage. I am using a voltage sensor value for this. Whenever voltage becomes Unavailable. My sensor gives me a state that Utility Power is Unavailable. Issue is that logs are not appearing for state change. Only history bar is showing up. I can't trigger an automation using it's states as well. Following is my code:

  - sensor:
      - name: "Utility Power"
        state: >
          {% if is_state('sensor.ground_floor_channel_1_voltage', 'unavailable') %}
            Unavailable
          {% else %}
            Available
          {% endif %}```
sonic nimbus
#

I want to say I want to measure only trigger.from_state where state was "on"

#

I wan to to know duration how long was my entity in state "on" before went to state "off"

inner mesa
hidden coral
#

It does not acknowledge Available state as trigger in automation. I don;t know why but whenever i try to trigger it upon state change from Unavailable to Available. and vice versa The Automation never triggers.

inner mesa
#

you can type whatever you want

hidden coral
#

I am thinking as it is a template sensor and not a binary sensor. That's why it's causing these issues

inner mesa
#

no

#

Unavailable and Available are just strings

#

there should be no problem using them in a trigger

hidden coral
#

Should i type them with "

#

I usually type them as is

inner mesa
#

shouldn't need to, but won't hurt

#

in any case, your problem doesn't seem to be with the template sensor, but with an automation

#

s long as the state of the sensor is reflecting properly in devtools -> States

hidden coral
#

here is the trigger inside an automation. It has never triggered.

trigger:
  - platform: state
    entity_id:
      - sensor.utility_power
    from: unavailable
    to: Available
condition: []
action:
inner mesa
#

unavailable and Unavailable aren't the same

hidden coral
#

Here is another automation that was created moths ago. Never triggered. In this Unavailable is with capital U.

trigger:
  - platform: state
    entity_id:
      - sensor.utility_power
    to: Unavailable
    from: Available
    attribute: current
condition: []
action:
inner mesa
#

attribute: current

#

details matter

hidden coral
#

sorry for that i have tried without attribute as well. Never worked.

inner mesa
#

I can't fight a strawman

#

without the attribute line, it should work just fine

#

try it now

#

both of what you've posted have clear issues

hidden coral
#

It was my last hope finding something that might work that i added this redundant line attribute. Believe me i have tried without attribute as well.

inner mesa
#

again, I don't know what to say

#

it's not redundant, it's just wrong

#

that attribute won't ever be either of those values

hidden coral
#

I know it's wrong but i have tried the correct as well.

inner mesa
#

ok. I have no more feedback, then

hidden coral
#

Btw can you tell me how can I alter this Utility_Power sensor so it can give me state change logs as well. Right now it's only showing history bar. Thanks for the input.

hearty verge
#

Is there a way to get historical data?

#

From a sensor via template

obtuse zephyr
#

Not directly. SQL sensor or a trigger template sensor, depending on your scenario

#

There are some stats integrations as well, depending on what you need

stuck remnant
#

this what the data looks like, I dunno if I have the template down correctlyhttps://imgur.com/a/wriijDe

#

the sensor does update when the proximity sensor is actioned but the state is always "detected" (on, basically)

grand quarry
#

Can you share that data in its original/raw form as text/JSON?

stuck remnant
#

{"proximity":{"unit":"cm","data":[[1684820556475,[8.0]]]}}

#

like this?

grand quarry
#

Yes. The template looks correct if you want to get the 8 in this case

stuck remnant
#

hmm forgot to say I have it as a binary sensor

#

don't mind how it looks like. either the 8 or off is fine by me

#

on would be 0 (cm) - i.e. when the prox sensor is actioned

stuck remnant
#

I switched it to a regular sensor and it went through. Thanks!

sacred sparrow
#

Currently I have:

    - name: "Kitchen Motion Hybrid Sensor"
      device_class: motion
      state: "{{ is_state('binary_sensor.kitchen_motion_sensor', 'on') and is_state('binary_sensor.kitchen_motion_sensor_mmwave', 'on') }}"```
but was wondering how I can do 
is_state('binary_sensor.kitchen_motion_sensor', 'on')      THEN          is_state('binary_sensor.kitchen_motion_sensor_mmwave', 'on')
so it never triggers if the MMwave senses it first
marble jackal
#
{% set motion = is_state('binary_sensor.kitchen_motion_sensor', 'on') %}
{% set mmwave = is_state('binary_sensor.kitchen_motion_sensor_mmwave', 'on') %}
{% if motion %}
  {{ mmwave }}
{% else %}
  {{ motion }}
{% endif %}
sacred sparrow
#

amazing! thanks

hidden coral
#

@inner mesa you were right about my clear mistakes in the code.
Actually I was trying to edit in visual editor in the past. It was showing up as Unavailable in visual editor but in yaml it was showing up as unavailable. From now on I will confirm yaml.

icy jay
#

Hi,

im using a custom DHL integration for package tracking. It creates for every package a new entity named "dhl.12345"

I want to create a automation that notifys me for every new state of new packages.

How can i create this automation that finds the individual entitys every time new? (something like auto entity card but for the backend)

plain magnetBOT
cloud valley
#

How do I need to setup the template I need to get the automation to work the way I want it to work.

As the trigger only needs to look at the

        "ResponseText": "Lights ON room X"
```c
portion of the received MQTT payload from the device
#

As when I have 1 template setup I can create multiple templates based on the same template. as the MQTT payload received by the device is always the same.

It is also the same when sending data to the device.

cloud valley
#

I am using the GUI to create a automation. I have not dived deep enough into using scripts and such

inner mesa
#

that's not "scripts and such". It's an automation trigger

#

start there

cloud valley
#

Yes I start with a MQTT trigger

#

How would this work in the GUI for automations?

#

As that is what I am getting confused on.

mighty ledge
#

and it will most likely be multiple automations or a template sensor

cloud valley
#

Do you mean like:

plain magnetBOT
cloud valley
#

They are Tuya switches, controlled trough the Local_tuya addon.

#

for the switch I am testing it there are 2 states:

  • type: turn_off
  • type: turn_on
#

For the moment there will be multiple automations.
Where the voice command response of the device will dictate what room/switch will be controlled.

        "ResponseText": "Lights ON room X"

#

Since this looks to be the easiest to implement/expand on.

As when I have it working for 1 switch with 2 states, it should work for other switches as well {curtain switch}

icy jay
#

the state is in german โ€žDie Sendung wurde erfolgreich zugestellt.โ€œ Means something like, the package got delivered.

icy jay
mighty ledge
#

Sry, busy work day, havenโ€™t had time

#

To respond

icy jay
#

Wait, it doestn let me copy properly ๐Ÿ˜ฆ

#

no problem mate, i figured it out, just dont know if its perfectly

plain magnetBOT
icy jay
scenic siren
#

hello and a nice good evening
i have problems with two entities from my huawei inverter from my solar system
the inverter provides one sonsor each for grid inport and grid export.
But the data of the sensor are total kwh values
but I need current and daily values in w/kw and kwh
I have read that you can do this with sensor templates.
Unfortunately, I have no idea at all about programming and although I have now searched and read several days on different sites, I could not solve my problem.
I have then tried to adjust the sensors via the helper, but also get no accurate values.

Can someone help me here?
The sensors are as follows:
total kwh import: sensor.power_meter_consumption
total kwh export: sensor.power_meter_exported

floral steeple
#

hi all, I would like to create a true condition using this template of an attribute sensor

- condition: template
    value_template: >-
      {{ 'true' if state_attr('imap_content', 'Sender',
      'Wifes Name') else 'false' }}

it does not seem to like the above.

obtuse zephyr
#

Just use {{ is_state_attr('imap_content', 'Sender','Wifes Name') }} ... but your entity ID is wrong anyway

#

So that alone won't work

#

Is it sensor.imap_content?

floral steeple
#

yes!

#

the sensor is sensor.imap_content

obtuse zephyr
#

So then the template route for that is {{ is_state_attr('sensor.imap_content', 'Sender','Wifes Name') }} , if Sender is the attribute name on that entity

floral steeple
#

thank you, that worked ๐Ÿ™‚

#

cheers

icy jay
#

Hi

i need a template as a condition in an automation, that checks if there is no entity in the system with a specified domain. How can i do this?

sullen karma
#

I have some time-throttled devices that sometimes get stuck at an old value. Here is the YAML

  - platform: filter
    name: "Garasje - Easee 1: Effekt_Filtered [W]"
    entity_id: sensor.garasje_easee1_effekt_live
    unique_id: sensor.garasje_easee1_effekt_filtered
    filters:
      - filter: time_throttle
        window_size: "00:02"

Here is a picture of the stuck devices:
https://imgur.com/a/BbL4sR6

icy jay
obtuse zephyr
#

You want if there's zero entities within a given domain?

icy jay
#

exactly

obtuse zephyr
#

{{ states.adomain | count == 0 }} would do that

#

adomain = whatever domain

icy jay
#

Thanks!

And if i want to count them?

obtuse zephyr
#

remove the equality and it'll give you the total number of matching entities

icy jay
#

perfect!

Thanks a lot ๐Ÿ™‚

cursive horizon
#

Is there a way to evaluate a template, to test the output?

cursive horizon
#

thanks

silent vector
#

Is there a clean way to ensure a list exists in it's entirety in another list.

{% set fooey = ['foo002','foo003','foo004',
'foo001'] %}
{% set bar = ['foo002','bar003','foo004',
'foo001'] %}

Bar must be a full match with fooey but not == meaning if fooey was this it should still work as long as every item of bar was in fooey

{% set fooey = ['foo002','foo003','foo004',
'foo001','foo005','foo006'] %}
inner mesa
#

I feel like you're asking about interview questions in real time ๐Ÿ™‚

#

Hope you get the job!

silent vector
#

๐Ÿ˜‚๐Ÿ˜‚๐Ÿ˜‚

#

No lol but it is work related

#

Trying to make sure 1 list is in another

#

But not ==

inner mesa
#

The answer is to start with the subset list, reject items that are 'in' the larger list, and check the length of the resulting list for == 0

silent vector
#

Oh yeah ๐Ÿคฆโ€โ™‚๏ธ if Petro was here I wouldn't hear the end of me not thinking of using reject lol

mighty ledge
#

Iโ€™m here silently judging

silent vector
#

Lol it's been a long day of troubleshooting issues I completely forgot about that method.

mighty ledge
inner mesa
#

I hope I got the job

silent vector
#

Lol no it's not an interview ๐Ÿ˜‚๐Ÿ˜‚. We use Ansible for automating infrastructure

floral steeple
#

hi, how to create a condition where I want the condition to fail because door was opened within the last 3 minutes of when the a trigger was triggered

#

if door was opened in the last 3 minutes, do not proceed

lofty mason
#
state: off 
for: 3 minutes
``` ?
floral steeple
#

oh yeah, that would work!

#

thanks

#
  - condition: state
    for:
      hours: 0
      minutes: 2
      seconds: 0
    entity_id:
      - binary_sensor.shed_door
      - binary_sensor.gate_front_door_side
      - binary_sensor.gate_garage_side
      - binary_sensor.back_door
    state: "off"

๐Ÿ˜

floral steeple
#

Ok, I have this automation that I only want firing no sooner than every 30 minutes between sunrise and sunset:

  - condition: template
    value_template: >-
      {{(as_timestamp(now()) - as_timestamp(state_attr("automation.bird_feeder",
      "last_triggered") | default(0)) | int > 1800 )}}

now, if I wanted to add another condition that I don't want it firing more than 5 times a day, any idea how I can set that condition up?

mighty ledge
#

Add a counter and reset the counter at midnight.

tawny coral
#

How do i figure out which "thing" is causing my error?

inner mesa
#

Is that a picture of some text? I didn't bother past the login

mighty ledge
tawny coral
grand quarry
#

Use a proper SSH client, get the log from the logs site in web interface or use something like samba to grab them

cloud valley
# mighty ledge Sry, busy work day, havenโ€™t had time

Could you please tell me how I can use the GUI for the template/check I want for my MQTT device?

since I get confused between the GUI and how to set it up script wise.

As I do not know where to put it, and the way it looks in the guide is different than how the jaml code looks in the automations portion

scenic siren
#

I have now tried to solve my problem differently

I have combined my 3 phases via the helpers into one sensor.
have this sensor then used, also works almost...
only has the sensor reversed values ๐Ÿ˜ฆ current that flows into the network is displayed as import...

have then searched again on the internet and came across a template that swaps the values.

have adapted this to my sensor but now get the following error

#

cant insert a picture :(, thats my tamplate

#
template
sensors:
  sensor.3_phasen_in_out:
    value_template: >-
      {{ is_state('binary_sensor.sensor.3_phasen_in_out', 'off') }}
    friendly_name: sensor.3_phasen_in_out-inverted
    device_class: lock
#

on line 3 there is an error "can not read a block mapping entry; a multiline key may not be an implicit key" unfortunately I do not understand the error :/

plain magnetBOT
#

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

marble jackal
#

You are mixing the new format and the legacy format

#

Or maybe not, but in that case platform: template seems to be missing

#

Not clear because of missing code tags

scenic siren
scenic siren
marble jackal
#

You need to remove the sensor. part from sensor.3_phasen_in_out

marble jackal
#

The code you have now belongs under sensor:

#
sensor:
  - platform: template
    sensors:
      3_phasen_in_out:
        value_template: >-
          {{ is_state('binary_sensor.sensor.3_phasen_in_out', 'off') }}
        friendly_name: sensor.3_phasen_in_out-inverted
        device_class: lock 
#

Why device class lock?

#

And why not at binary sensor?

scenic siren
#

Unfortunately, I cannot answer these questions.
I have no idea about programming at all.
I'm just looking for a few days desperately a solution to adapt my sonsor.
on the search I have found a template which swaps the values and have simply entered my sensor :/

#

my inverter has only one sensor each for grid import and grid export in total kwh data
i thought i could get a current value with the 3 phases ๐Ÿ™‚
this actually works, only that the values are swapped.
therefore the template

#

thank you for your help.
I have deletet the

device_class: lock

at the end, now i don't get any error anymore.
when i wanted to use the new sensor, i could not because it shows that the sensor has no unique id.

i'm sorry to bother you with such trivialities, i just don't understand the whole thing.

cursive ice
#

just a quick one, trying to figure out a template for echo dots (because I want to use them in conditional) and want the template sensor to show a state if the say media_player.echo stat is standby or paused

#

I know now how to do one if state is return, but what if I want to use 2 of the states device can be in

rose scroll
cursive ice
#

basically yes, echo dots are either in standby or paused when you say stop, I want my conditional card to show calendar when echo is in either of them stats

plain magnetBOT
cursive ice
#

that obviously failed

rose scroll
#

Oh...it's because if you list multiple conditions in a conditional card, it will display only if all conditions are true.

#

Your intent is to implement the or logic in a template sensor, then use the state of that sensor for the conditional card?

cursive ice
#

yes

#

the two states are paused and standby

rose scroll
#

{{ states('media_player.xxx') in ['standby', 'paused'] }}

#

Pop that in the value_template of a template binary sensor.

cursive ice
#

there we go, thank you

#
    sensors:
      echo_dot_clock_state:
          friendly_name: 'echo dot clock state'
          value_template: >
            {% set state = states('media_player.echo_dot_clock') %}
            {{ 'standby' if  state == "paused", "paused" else playing  }} ```
#

ok that was wrong lol, not to hopeful for me

rose scroll
#

Why does it need to be a sensor?

#

That last line isn't valid Jinja.

cursive ice
#

ah, ok, my mistake was already thinking I can adjust something I already had for another sensor.

rose scroll
#

But I think you just need a binary sensor.

cursive ice
#

I only tried that as I have quite a few sensors done that way for example - platform: template sensors: washing_machine_current_course: friendly_name: 'Washing Machine Current Course' value_template: > {% set current_course = states('sensor.front_load_washer_current_course') %} {{ 'Program set' if current_course == "-" else current_course }}

#

I thought just adapting that to fit this would work lol

rose scroll
#

You can theoretically implement it as a sensor. But your adaptation didn't go far enough. == tests if one value is identical to another. What you want is in, which tests if one value is among a list [...] of values.

cursive horizon
#

Hey. Was redirected here from #automations-archived, need to create a condition in an automation to only run when triggered by a user and not run when trigger by script.
I tried to use a template condition:

condition:
  - condition: template
    value_template: "{{ context.user_id != None }}"

But when I test the condition, I get this error: In 'template' condition: UndefinedError: 'context' is undefined. Either I'm using context incorrectly or it isnt defined in conditions block?

#

Is it possible the context is not defined because its just a test?

#

I test by pressing the 3 dots and then pressing test

cursive ice
#
  - platform: template
    sensors:
      echo_dot_clock_state:
          friendly_name: 'echo dot clock state'
          value_template: >
            {% set state = states('media_player.echo_dot_clock') %}
            {{ 'standby' if  state in ["paused", "paused"] else playing  }} ```
#

thank you

rose scroll
cursive ice
#

yes your correct its paused, standby else playing

mighty ledge
cursive horizon
#

I see

#

The condition should be good yeah? Since the user_id will be none if a script causes automation to run

marble jackal
plain magnetBOT
scenic siren
#
sensor:
  - platform: template
    sensors:
      3_phasen_in_out:
        value_template: >-
          {{ is_state('binary_sensor.sensor.3_phasen_in_out', 'off') }}
        friendly_name: sensor.3_phasen_in_out-inverted
        device_class: energy
        unique_id: 'Test grid Sensor'
```now i can select the sensor and use it in the integration.
But now there is a new problem.  
the output value of the sensor is false?
mighty ledge
marble jackal
cursive horizon
mighty ledge
#

click on changed variables

#

for the whole trace

cursive horizon
#

None changed

#

oh

mighty ledge
#

You'll see all variables that exist in the automation

cursive horizon
#

so just click on the topmost trace element to see changed variables for the whole thing?

#

(topmost is trigger)

scenic siren
# marble jackal Yes, what did you expect the output to be?

my thought was, since my inverter only outputs total kwh values, to create a current value with the three phases.
I would like to have current values for grid export and grid import.
so i put the three sensors of the phases together via a helper.
this also works, but the values are interpreted incorrectly.
if i now consume electricity this is displayed as grid export, if i export electricity this is displayed as grid consumption.
therefore my idea to swap the sensor values over the template

cursive horizon
#

I had to use trigger.to_state.context

silent vector
#
{% set stuff = [{'hostname': 'foo001', 'ip_address':'1.1.1.1' }, { 'hostname': 'foo00', 'ip_address':'1.1.1.2' }] %}
{{ tst | random }}

Is there a way to remove a random n of items from a list of dicts?
Let's say there were 4 lists of dicts and I wanted to remove 2. It would remove 2 in a random order not necessarily the first or last items in the list of dicts.

marble jackal
#

Select one random item, reject that. Repeat that

silent vector
marble jackal
#

Yes, or just repeat the steps

plain magnetBOT
abstract parrot
#

hiya guys, need a bit of help with this. I'm trying to convert uptime to a more human readable information from IPP integration. So as some of you might already know that although the uptime entity (once it's enabled) showed the right information(in minutes). when it's queried via dev tools, it is showing in date and time format (of when the printer was initially switched on). HA seems to be doing its own calculation by subtracting now() with it's payload = time in minutes. I'm trying to set a simple automation just to send me an alert if uptime is more than certain minutes, but due to my lack of knowledge of template, even after reading the documentations along with some other articles I found, I still couldn't make the head or tail of this. Would anyone please help me to show me an example that I can do to get the info I need?

#

{{states('sensor.epson_et_3750_series_uptime') }}

#

currently that template gives out--> 2023-05-24T13:53:56+00:00

rose scroll
#

Where xx is the time threshold in terms of seconds

abstract parrot
#

Thanks @rose scroll - the result is still showing as this --> 2023-05-24T15:01:26+00:00, I just copied pasted it into template editor. am I meant to add anything else?

#

Ah, when I trimmed it down to just {{ now() | as_timestamp}}, the result is this --> 1684940828.728487

rose scroll
#

Umm...the result should be true or false, not another timestamp.

mighty ledge
#
{{ (now() - states('sensor.epson_et_3750_series_uptime') | as_datetime).total_seconds() / 60 > 10 }}

for 10 minutes

#

'greater than 10 minutes'*

abstract parrot
#

ahhhhhhh

#

now we are getting somewhere

#

Thanks @mighty ledge , I think I starting to understand how this works

mighty ledge
#

you can use as_timestamp too but it get's hairy when you do or don't have a TZ attached

abstract parrot
#

I'm now getting true or false

mighty ledge
#

so I just avoid it

abstract parrot
#

thanks both!

mighty ledge
#

just keep in mind that the value can go negative if your sensor for some reason is set to a value in the future

abstract parrot
#

ok ok

mighty ledge
#

but that would be the sensor messing up

#

it'll be false, so it shouldn't impact the tempalte

cloud valley
inner mesa
#

With an MQTT trigger for the topic and an if: or choose: based on the payload

mighty ledge
#

Yeah, just make an automation using the links posted by rob

#

Your template would just be {{ 'X' in trigger.payload }}

inner mesa
#

In this case, like {{ 'c' in trigger.payload_json.Data.ResponseText }}

cloud valley
inner mesa
#

you don't "enable" templating, you just use a template where it's accepted

cloud valley
#

And how do I do that?

inner mesa
#

type things?

mighty ledge
#

Do you know how to make an automation?

inner mesa
#

choose the right things in the UI

mighty ledge
#

Because thatโ€™s step 1

cloud valley
#

A automation trough the GUI?

Yes I know how

mighty ledge
#

Ok, then you should know how to create a trigger then

#

And a condition

#

Youโ€™d use an mqtt topic trigger

cloud valley
#

I have that.

#

" When an MQTT message has been received"

mighty ledge
#

Ok then your condition will be a template condition

#

Thatโ€™s the trigger

cloud valley
#

I have a empty template as a condition, I get stuck on how I need to have it do what I want it to do

mighty ledge
#

Use the template we supplied aboveโ€ฆ copy/paste

#

Change x to whatever you want

inner mesa
#

or I guess petro's would work if you just want a string search in the entire raw JSON ๐Ÿ™‚

cloud valley
#

Thank you this looks to be working.

fallow gulch
#

ok so I've got a bunch of trigger-based binary sensor templates, and their conditional icons aren't working.

plain magnetBOT
fallow gulch
#

this is from my templates.yaml ^^

#

I'm getting the 'else' icon even if the sensor is in its 'on' state

#

But only some of the time. The "Kitchen" one below was working fine for a little while yesterday, now it's back to the outline icon whether its off or on

#

Do the id's need to be unique to each instance of trigger?

haughty breach
#

Use the trigger id to define the icon too...

#

{{ iif(trigger.id == 'on', 'mdi:food', 'mdi:food-outline') }}

fallow gulch
#

I think that's worked. I had to trigger them all to get the icons to refresh, but I gather this was expected behaviour.

#

thank you!

floral shuttle
#

must be missing the obvious, but just about the only template sensor in my config I can not control the precision of is this:```
template:

  • sensor:

    • unique_id: length_of_day_factor
      name: Length of day # factor for circadian light calculation'
      icon: mdi:altimeter
      state: >
      {% set daylength = states('sensor.astral_daylight')|float %}
      {{((daylength*-0.0063616)+0.11131)}}```
#

and it really needs it....:

mighty ledge
#

well you don't have a unit of measurement

#

so, HA probably thinks it's a string

floral shuttle
#

right, I wasnt aware that would be a prerequisite.... (I now notice I can take out all the parenthesis too btw, its a legacy template I didnt revisit for some time now)

mighty ledge
#

why wouldnt' that be?

#

you can't set a precision on a string

#

unit of measurement controls everything about sensors

#

been like that since day 1

#

that's why the graphs aren't numerical when you don't have a UOM

floral shuttle
#

correct, and I had this before:```
{% set daylength = ((as_timestamp(state_attr('sun.sun','next_setting')) -
as_timestamp(state_attr('sun.sun','next_rising'))) /
3600) + 24 %}
{{((daylength*-0.0063616)+0.11131)|round(5)}}

mighty ledge
#

yep, still a string, and you rounded it yourself

#

Bet ya if you showed the history, it wouldn't be numerical

floral shuttle
mighty ledge
#

yes

#

unit_of_measurement: ""

#

You don't need a device_class

floral shuttle
#

seems a hack to me doing that.... but, I did now, and still cant set it in the ui:

mighty ledge
#

what's no unit? An empty string

#

clear your cache and refresh the page

#

you may also need to restart

floral shuttle
#

and no clearing cache or restart didnt fix that

mighty ledge
#

You're giving it "no units"

#

Make sure yaml is actually putting the UOM

#

if not, make it a space " "

floral shuttle
#

a yes I'll try that. btw this is what it is showing in dev tools now

mighty ledge
#

Try adding a stateclass

floral shuttle
#

and adding the space there helps!

mighty ledge
#

nice

floral shuttle
#

yep, much better

mighty ledge
#

๐Ÿ‘

#

so, i'd call the space a workaround

floral shuttle
#

heck what is with all these rabbit gifs on each post

#

oops, sorry too big, ill delete that

mighty ledge
#

it's fine

floral shuttle
#

thx Petro, 1 issue down

mighty ledge
floral shuttle
mighty ledge
#

having trouble following your issue there

#

oh apparently icon can be templated

#

color me surprised

floral shuttle
#

yes, me too, it's complex: 1- rest does not hot reload, 2- it throws errors, and 3- the icon template is not always used

plain magnetBOT
floral shuttle
#

Ive added that summary ;-0

mighty ledge
thorny cargo
#

I can see a list of options there of which i want to randomly choose?

mighty ledge
#

right, options

#

so look at your code...

#

what attribute are you trying to get?

#

hint, it's not option...

thorny cargo
#

Why is it not an option?

#

What else?

#

I want to choose an option from the list of options randomly?

mighty ledge
#

right the list of options

#

not option

#

I guess you aren't getting what I'm saying... you're missing the s on your attribute.

thorny cargo
#

Thank you. I just got it right before you said it.

mighty ledge
#

np

thorny cargo
#

Got another question. I got a hue tap dial switch. Is it possible to dim only the last controlled light?

mighty ledge
#

no idea

#

how would you even know what the last controlled light was

thorny cargo
#

Save it somewhere when it is controlled?

#

Like in a helper or something?

mighty ledge
#

you'd have to build that system if it's not already built by the tap dial

#

input text or a template sensor

plain magnetBOT