#templates-archived

1 messages · Page 42 of 1

undone jungle
#

This said, I still don't understand WHYY!!

mighty ledge
#

it's not a hunch, you're just recreating the same logic

#

it's happening because of your settings

#

if you aren't waiting long enough, then you'll get oddness

undone jungle
#

For me it was a hunch - since I am not as efficient in scripting templates, so assumed it would give the same result.

mighty ledge
#

e.g. door opens and updates in 0.5 seconds. gate opens and updates in 3 seconds

#

if you toggle the cover between 0.5 and 3 seconds, you're going to have oddness

undone jungle
#

Fair, but I don't.

#

I am not at home - drive up to my gate and call up Google to open both.

#

It asks for PIN and receives it.

#

Then it opens one but not the other

#

So there is no way for any additional toggles in the interim

mighty ledge
#

then 'the other' has the wrong switch entity_id

#

check for spelling errors

undone jungle
#

I'd love for it to be this simple!

#

It's a group from the UI, so how can there be spelling errors.

mighty ledge
#

there's nothing else to it other than your binary sensor not reporting the correct state

undone jungle
#

They are selected from the drop down menu

mighty ledge
#

in your original cover template

undone jungle
#

Wait, if the original template works OK for each gate separately, then there can't be a spelling error, since the group is selected from the UI.

#

Am I missing something?

mighty ledge
#

if they work separately, and they don't work in the group, then it's a hardware problem

#

do they come from the same hardware?

#

the momentary switches?

undone jungle
#

Yes!

#

Yes!

mighty ledge
#

ok, are you sure that device can except 2 signals at the same time?

#

because HA is extremely fast

undone jungle
#

Both integrated in exactly the same way with a nearly identical magnetic sensor for open/close detection

mighty ledge
#

wait, but are they separate hardware or the same hardware?

undone jungle
#

2 covers being actuated via a Satel alarm system which has magnetic sensor for closure detection

#

Different motors, and everything obviouslyt

#

You may be on to something that the Satel central unit receives two requests two quickly

mighty ledge
#

There's nothing else it can be

undone jungle
#

It may not handle any queues hence the request no.2 gets discarded, but how to know that is... tricky

mighty ledge
#

you'll have to add a delay between the two calls

#

and you can't use thefes's templates

#

if you want to get fancy, you could use your home/away state to open the gate first then the garage and vice versa

undone jungle
#

I live in a larger city and sometimes pass by my house on my way to the kid's school, so having things open on their own is a bit too much for my taste.

mighty ledge
#

No you're not understanding

#

I'm saying, when you press the button, if you are home it opens in x order, otherwise it opens in y order

undone jungle
#

Thanks for the clarification. This said, I wouldn't need more than one order of opening things

#

Just so that it opens both, which seemed super simple, but it isn't

#

I'll have to search the web for some example templates with entities having a delay between actions.

#

I'll need to have it so it's 'wife-safe' as well...

mighty ledge
#

you don't need templates...

undone jungle
#

Having things not work while I am out is a quick way to an Armageddon... lolz

mighty ledge
#

the turn_on section is an action section

#

identical to automation action sections

#

just put a normal delay in it

undone jungle
mighty ledge
#

between 2 turn on calls

#

0 templates

#
- service: switch.turn_on
  target:
    entity_id: switch.a
- delay:
    seconds: 1
- service: switch.turn_on
  target:
    entity_id: switch.b
undone jungle
#

But then if it's just a button with an action having a delay, I'll probably get myself into a pickle with the flip-flopping effect I discussed with @marble jackal .

#

If one gate is open and the other closed, it will start flip-flopping.

mighty ledge
#

Unless you use and in your value_tempalte for the cover

#

and requires both to be on to be on

undone jungle
#

I understand it must be frustrating, having it all laid out in your head, trying to explain it. Sorry for being less than quick in catching what you mean.

mighty ledge
#

you can also use chooses to conditionally choose which one should turn on if it's not.

undone jungle
undone jungle
mighty ledge
#

Do you know how to make a choose in an automation?

#

You seem to think this requires templates, but it does not

#

you already have your template

#

maybe you're confused about the name of the channel and the integration you're using

#

you're using the template integration to create a template cover

#

the word template does not refer to the templates in this channel

#

this channel is for jinja templates

#

which the template integration uses

#

this is a template {{ ... }} or {% ... %}

#

everything else is yaml

#

So, a choose is simply yaml. You can build the yaml in the automation editor and then just copy/paste it into your turn_on or turn_off section

undone jungle
marble jackal
#

the problem is that all actiosn (open, close, stop) use the same switch.turn_on action

mighty ledge
#

that's a momentary switch

marble jackal
#

it's basically a button press, which initiates an action based on the current state

mighty ledge
#

All my garages are binary_sensors w/ momentary switches

#

I do not have his problem

#

he has some hardware thing going on causing the confusion

undone jungle
#

I've been thinking of getting the gates out of Satel and putting some Shelly or other in there to get them to be smarter, but still, the garage door doesn't have an up/down - only a momentary switch in itself.

mighty ledge
#

I have a group of garage doors with template covers and they work great without delays and I have a similar setup to the template you created @marble jackal

undone jungle
#

I'll check inside the Satel software if there is some queue handling there.

marble jackal
#

I don't have a garage nor gate 😛

undone jungle
mighty ledge
#

#JealousOfEUTransportation

undone jungle
mighty ledge
#

you only need a template for value_template

marble jackal
mighty ledge
#

all the rest can be done w/ normal actions

undone jungle
#

So within the cover template created by @marble jackal I'll need to find a way to add a delay between the actions called.

#

Or am I still confusing things?

mighty ledge
#

no...

undone jungle
#

I am so sorry, I don't get it!

mighty ledge
#

choose

undone jungle
#

How do I go from a momentary switch integrated into HA to an operating cover???

#

I always assumed I need a template_cover

mighty ledge
#

my man, can you please go to the automation editor and look at choose in the action section

marble jackal
#
turn_on:
  - action 1
  - action_2
#

those actions are exactly the same as the action sequence in an automation

mighty ledge
#

I already have him the example above 🙂

mighty ledge
#

he just needs to use a choose for each of those if he wants them to always be in sync

#

with an added normal condition checking the binary sensor state

marble jackal
#

I had it on my to do list to add a hyphen in the docs for all template entities in those sequences, because it's unclear now that it can be a list

mighty ledge
marble jackal
#

true

mighty ledge
#

or someone uses scripts in the action to make the config smaller

#

really annoyed by the examples in general

undone jungle
#

Within choose I'd go about and list all 4 options, with both closed, one open, the other open and both open, correct?

#

Actually, that won't work, because this doesn't take into account what the intention is – to open all or close all.

plain magnetBOT
#

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

undone jungle
#

@mighty ledge not sure if this is what you meant.

mighty ledge
#

I would have made 2 separate chooses with a delay in between

#

the first choose would look at main_gate and only turn on the switch if it was not on

#

the second choose would do the same for garage_door

#

Then you'd apply the same logic to the close_cover section, but with 'off'

#

e.g. if door not open then open, wait 2 seconds, if second door not open then open

undone jungle
#

OK - working on it

plain magnetBOT
#

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

mighty ledge
#

yes, but not together like that

#

your open_cover will only do the turn on stuff

#

your close_cover will only do the turn_off stuff

undone jungle
#

It's not together now. It's only the turn_on (i.e. open).

mighty ledge
#

it is

#

you have it in 1 action section

#

so how do you plan to put that in the open_cover action section?

undone jungle
#

Nevermind, I didn't save something... sorry!

plain magnetBOT
#

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

undone jungle
#

Is that what your meant?

mighty ledge
#

yes

#

after you add them to your open_cover section and close_cover section, make sure to change the or in your value_template to and

#

also, when coping from that code, don't include the word action:

undone jungle
#

The open_cover and close_cover will accept the hyphen list?

marble jackal
#

yes

#

that's what I was referring to above, that the docs are confusing this way

undone jungle
#

I just saw you two discussing it but wanted to confirm it pertains to covers as well

mighty ledge
#

it pertains to all 'action' sections

#

I wish they never supported the non dashed list

undone jungle
#

How would I handle the stop in this scenario?

#

Since I want it to indiscriminately send another switch, making both covers stop moving

mighty ledge
#

don't use the choose

#

just call the switch

#

you'd still need a delay

undone jungle
# mighty ledge don't use the choose

It doesn't like this syntax:

        stop_cover:
          service: switch.turn_on
          target:
            entity_id:
              - switch.main_gate
              - delay:
                  hours: 0
                  minutes: 0
                  seconds: 2
                  milliseconds: 0
              - switch.garage_door
mighty ledge
#

right, because that's not valid yaml

#

look at the example I posted above

undone jungle
#

So annoying, this channel doesn't convert longer code into files (or I am to think to figure it out).

#

I arrived at this

mighty ledge
undone jungle
#

I am still confused as to why the choose would even be necessary if there is no choice of any kind

#

It's a list of operations one after the other.

#

If the condition is met, the operation takes place

marble jackal
#

you still have or in the icon template

undone jungle
mighty ledge
undone jungle
#

Unfortunately they don't.

mighty ledge
#

if one door is open and the other door is closed, your actions will keep them in sync

undone jungle
#

I just opened them and they both opened as planned

#

But I tried stopping them since it's an important safety feature

#

When I initiated the stop the garage door closed while the main gate remained open because it didn't finish opening.

#

I think this will always be the case since there is no way for both to know what the other one is doing

mighty ledge
#

that means your binary sensors do not output the states the way you described

undone jungle
#

There is no running parameter

mighty ledge
#

right

#

then it relies on the binary_sensors state

#

hence why you have all those 'choose's in there

#

if you stop it and the system thinks 1 is open and the other is closed, you're going to have oddness

undone jungle
#

I need to read up on the choose. I understand it is needed, but the naming is just confusing, since there is no actual choice taking place

#

At least in my head it should be sufficient to give a condition of if off, open and if on, close

#

But it seems like this is wrapped inside the choose action

mighty ledge
#

there is a choice though

#

you're choosing to only do the action if it's a specific state

#

it's doing nothing if it's not that specific state

undone jungle
#

Makes sense.

marble jackal
#

The problem is you only know when it's closed (when the magnetic sensor makes contact)

#

When it doesn't, you don't know if it is opening, closing or open

#

So that leaves you in the dark for the stop action, which should only be performed when it's closing or opening

#

And not when it's fully open, because then it will close again

mighty ledge
#

yes, but with momentary switches, that doesn't matter

#

the only thing that matters at that point is how each binary_sensor retains state

#

if he stops half way and 1 binary sensor says "on", the other "off", then that's the problem

#

they both need to report the same way, i.e. contact sensors that only report state when fully closed or vice versa

#

if one reports fully closed, the other reports fully open, keeping them in sync will be a pita

#

Oh yeah, one other wrench is the behavior of the motors

#

My garage doors do not continue their action after stopping. They reverse.

#

so when I stop half way, my next 'monetary switch' that is pressed will reverse what was just done

#

Both of his hardware would have to act this way

#

I'd wager that's an issue he's running into. 1 reverses the other continues forward

#

@undone jungle ^

undone jungle
undone jungle
#

Second, the gate closes on it's own from a timer (since this is the basic functioning of such gates)

#

Third, one can actuate both by other means - i.e. Wall pannel

undone jungle
#

I bought the house with it in place so would have to tear up the driveway

undone jungle
undone jungle
#

My issue is the length of time it takes to run each from close to open and the fact one closes on it's own, finally it's also that they are actuated from other places

#

I accept these oddities

#

I've been able for the first time today drive home and call up Google to get them both open.

#

I call this a success and need to just add the device_class so that they ask for a code beforehand

#

Currently it's a free for all and I don't like it

#

If I am not mistaken device classes gate, door and garage are 'controlled' correct?

mighty ledge
#

?

undone jungle
#

Because I don't see an option to indicate to Google which device to ask for a code and which not

mighty ledge
#

device_class only determines the icon for covers

#

and potentially how they are exposed to other apis

undone jungle
#

Yup, the latter part is what I care about

mighty ledge
#

I would assume both require a code

undone jungle
#

Probably Google recognizes barriers as 'controlled'

#

Without a device class it doesn't so I need to choose one of the once that do

mighty ledge
dire fossil
#

Hello, I do not have so much experience.
I need a counter that indicates how many entities have either the state "abc" or "def". I have from all entities the Ids.

Entity 1: abc
Entity 1: xyz
Entity 1: def
-> here the counter should give 2

How would I do this?

inner mesa
#
template:
  - sensor:
    - name: State Count
      state: >-
        {% set entities = ['sensor.entity_1', 'sensor.entity_2'] %}
        {{ entities|select('is_state', ['abc', 'def'])|list|length }}
inner mesa
#

I don't know if is_state does tricks like that

mighty ledge
#

well now my response looks dumb

inner mesa
#

Mission: Accomplished

mighty ledge
dire fossil
#

Thanks. will try that 🙂

mighty ledge
#

just checked

#

that was added pretty recently too

#

in the last year or so

inner mesa
#

I don't really do any of that fancy stuff in my install, so my exposure to it is posts here and testing them

dire fossil
undone jungle
# mighty ledge

Set it to Garage and it works like a charm. Thank you so very much @marble jackal and @mighty ledge for all your patience and assistance

wanton girder
#

Hey guys, i have 2 helpers that has a date/time value...I want to show the time past between then...the format is: 2023-06-05 00:00:00

#

helpers is called start and slut

inner mesa
#

{{ now() - states('input_datetime.date_test')|as_datetime|as_local }} -> 287 days, 2:57:24.654919

wanton girder
#

{{ states('input_datetime.rengoring_start') - states('input_datetime.rengoring_slut')|as_datetime|as_local }}

#

??

inner mesa
#

you need the same thing for the other one

#

I just gave you an example

wanton girder
#

same thing ?

inner mesa
#

yes

wanton girder
#

I dont understand

inner mesa
#

look at the two states() calls

#

understand what's going on

#

what's different?

wanton girder
#

{{ states('input_datetime.rengoring_start')|as_datetime|as_local - states('input_datetime.rengoring_slut')|as_datetime|as_local }}

inner mesa
#

yes

wanton girder
#

if it put it in a button card it doesn't work

#

No visual editor available for type 'custom:button-card {{ states('input_datetime.rengoring_start')|as_datetime|as_local - states('input_datetime.rengoring_slut')|as_datetime|as_local }}'.

inner mesa
#

custom button card uses javascript, not Jinja

#

I don't know how to do that in JS

#

other than creating a template sensor

wanton girder
#

arh okay...

#
template:
  - sensor:
      - name: renoeringstid
        state: >
          {{ states('input_datetime.rengoring_start')|as_datetime|as_local - states('input_datetime.rengoring_slut')|as_datetime|as_local }}
hazy radish
#

Hi, maybe someone can help me. I want to check if two bits from a json value are set. With a single bit it's work as mqtt switch with this: value_template: "{{value_json.infobt| int // (2**27)%2}}"

inner mesa
#

check out these:

Filter value_one|bitwise_and(value_two) perform a bitwise and(&) operation with two values.

Filter value_one|bitwise_or(value_two) perform a bitwise or(|) operation with two values.

#

the first one, in your case

hazy radish
#

This will not work value_template: "{{value_json.infobt| int // (227)%2 and value_json.infobt| int // (230)%2}}" or should i use & ?

inner mesa
#

what?

#

you create a bitmask with your two bits and then use bitwise_and

#

{{ 0x06|bitwise_and(0x03 * 2**1) == 0x06 }} -> True

hazy radish
#

Ok now i check how to Bitwise &
Thanks a lot!

lament garnet
#

- sensor: unique_id: total_house_power name: total_house_power device_class: power state_class: measurement unit_of_measurement: 'W' state: >- {% set gridpower = states('sensor.gridpower') | float(unknown) %} {% set pvpower = states('sensor.pvpower') | float(unknown) %} {{ (gridpower+pvpower) | round() }}
With this template I get two different value updates at the same second. I feel template is triggered both on gridpower change and pvpower change. How can I make sure it triggers only once?

marble jackal
#

What's the complete sensor code (the YAML)

lament garnet
#

gridpower and pvpower is updated every minute at the same time, or atleast in within few milliseconds. Is there a delay to wait if all inputs are settled in and then I can calculate template value?

marble jackal
#

As you are using the new format, you can use a template trigger which compares both last_changed values and triggers when the difference is less than eg 5 seconds

#

Your current template will return errors btw, if the value for one of the sensors is non-numeric it will fail because you didn't add quotes around unknown. It will search for a variable unknown

#

And if you add the quotes you will get an error because you'll end up with
('unknown' + 'unknown') | round()

#

You should use an availability template here

lament garnet
opaque wyvern
#

Time condition for serial template trigger sensor

frank beacon
#

Hey all. I'm taking my first leap into date/time in templates and it's giving me a real headache. I'd like to convert the current ISO date time into a simple HH:MM display.

I have this code but it seems convoluted, how can I simplify it?

{{ states('sensor.date_time_iso') | as_datetime() | as_timestamp() | timestamp_custom('%H:%M', local=true) }}

(yes I know there is a sensor.time sensor - this is more for my learning)

mighty ledge
#

and if the iso is UTC, then you'd need an extra

#
{{ (states('sensor.date_time_iso') | as_datetime | as_local).strftime('%H:%M') }}
frank beacon
mighty ledge
#

if yes, then...

{{ now().strftime('%H:%M') }}
#

all that extra datetime fluff is because state's are strings and you need to convert the string to a datetime object

floral shuttle
#

please let me get back on this generic templating question: what would be most efficient: have template sensors use a |round() to limit state changes on many decimals in the DB (as we all did before) opposed to the now available rounding in the frontend.

#

seems the round on all of those template sensors is an extra template step in itself, so it might be just as powerhungry for the system, albeit mayby not for the DB

mighty ledge
#

Personally, when I write code, I don't round things until I display them.

floral shuttle
#

its just that on an entity with 10 decimals, there are huge amounts of state changes all of the time, written to the DB

mighty ledge
#

I.E. leave it to the frontend

floral shuttle
#

yeah thats what I do now too

mighty ledge
#

If you want a smaller database, by all means, round it

#

I do not give two shits about my database size

floral shuttle
#

well, no, size doesnt matter.... it's the effort that counts 😉

mighty ledge
#

I'm at just over a gig for 40 days of history

#

and now with everything moving towards LTS, I'm not even sure I need 40 days

floral shuttle
#

bottom line would be: round (is costly in templates) and have fewer state changes, or dont round (costly in DB writes) and require additional Frontend power

floral shuttle
#

can we somehow escape the ! in {% set datum = !secret vj_marijn %}?

#

or use secret like this at all

mighty ledge
#

that's not possible

#

never has been

#

the best you can do is set it to a variable in an automation or attribute on a sensor. But remember, you won't be able to use this if you set it to an attribute as it will always be 1 state behind. But that probably won't matter if it's just your birthday.

floral shuttle
#

yeah that is what I am trying to do.As you witnessed yesterday, I rewrote all of my sensors to be verbose, and ditch the this.variable. But mainly because it causes trouble when using them as trigger template. set an attribute, and use that in state, and the state breaks. As regular template (but I dont want that, I want it to be limited to once a day) there is no issue at all

mighty ledge
#

Why not just put your dates in a macro

#

custom_macros\birthdates.jinja

{% set vj_marijn = '1901-10-04' %}

then in your template

{% from 'birthdates.jinja' import vj_marijn %}
{% set datum = vj_marijn %}
#

it's basically the same as secrets

#

hell, you can set them as datetime objects too...

#
{% set vj_marijn = '1901-10-04' | as_datetime | as_local %}
#

they will maintain their object

floral shuttle
#
      - unique_id: marijn_verjaardag
        state: >
          {% set event = this.attributes.secret|as_datetime|as_local %}
          {% set year = 1 if event.month < now().month or
                            (event.month == now().month and event.day < now().day)
                         else 0 %}
          {% from 'easy_time.jinja' import count_the_days %}
          {{count_the_days(event.replace(year=now().year + year)) }}
        attributes:
          secret: !secret vj_marijn
mighty ledge
#

sure, you can do that too

#

personally, I'd go the macro route.

floral shuttle
#

but no that breaks the state when used as trigger template

mighty ledge
#

not sure how it does

floral shuttle
#

nor am I, but it does, ive tested this extensively . with or without defaults

#

or the .get() format

mighty ledge
#

you're importing a mcro already, there's no way importing a second macro will break triggers.

floral shuttle
#

from what Ive been able to establish, is we can use this.state in attributes just fine, but when any of the main config options refers to a this.attrbutes.xxx, it breaks when used as a trigger template

mighty ledge
#

oh you're still talkinga bout that, not the macro

#

just use the macro

#

not to mention, it's more optimized

floral shuttle
#

let me try.

floral shuttle
#

when I do: {% from 'feestdata_macros.jinja' import vj_marijn %} {{vj_marijn}} an error is returned: expected token 'name', got 'end of statement block'

#

while this is in that file: {% macro %}{% set vj_marijn = '1910-05-27' | as_datetime | as_local %}{% endmacro %}

mighty ledge
#

no you don't need a macro

#

literally just this line in the file

{% set vj_marijn = '1910-05-27' | as_datetime | as_local %}
#

@floral shuttle ^

floral shuttle
#

ah yes, that helps. though, setting that on an attribute with datum: > {% from 'feestdata.jinja' import vj_marijn %} {{vj_marijn}} shows Datum 27 mei 1910 om 00:00:00 where using datum: '1964-05-17' reveals the neater:Datum 17 mei 1964

mighty ledge
#

Sure, but then you can't use it without converting all the time

#

do you really need 'datum' to be friendly?

#

if yes, just make a separate attribute

#

but TBH, it's pointless if you're just using it for notifications and you'll be translating it anyways.

floral shuttle
#

well no, I was surprised the frontend did that, and ofc, next one gets used to that 😉

mighty ledge
#

the frontend knows how to handle datetime objects

#

that's why everything should be datetime objects, let the frontend display it and the user should choose how they want it displayed

#

So user A could have a different display from user B

floral shuttle
#

just to give you an idea why all of this is done. And all of those attributes need that date...

mighty ledge
#

Yah, but for me, I wouldn't have any of those attributes.

#

I'd make a set of template sensors with 1 calc

#

1 for age, 1 for days away

#

days away would be used for an automation for notifications

#

age would be for display in the UI

floral shuttle
#

my frontend is made with these card: type: custom:template-entity-row entity: '[[entity]]' state: > {{states(config.entity)}} {{'dag' if states(config.entity)|int(default=-1) == 1 else 'dagen'}} secondary: > {% set event = state_attr(config.entity,'datum')|as_datetime %} {{state_attr(config.entity,'type')}}: {{event.strftime('%d-%m-%Y')}} and automation is using state = 1 or 0

#

wrap-up so instead of converting that date string 6 times per template sensor like: {% set event = '1964-08-27'|as_datetime|as_local %} {{(now() - event).days}}

#

I'd be better of importing those from custom_templates?

mighty ledge
#

just this portion '1964-08-27'|as_datetime|as_local

#

nothing else

floral shuttle
#

yes, that

#
            {% from 'feestdata.jinja' import vj_marijn %}
            {% set event = vj_marijn %}
            {{(now() - event).days}}```
hearty verge
#

If i use a media selector ... how do i do a trigger on the state change of the media player...

I have this block:

trigger_variables:
  media: !input media
  player: "{{ media.entity_id }}"

Do i need to use a template trigger if i want to access that player?

#

When i try to use "{{player}}" as an entity_id in a state trigger

solar star
#

Before I post, how do I paste code so it's nicely formatted and blocked like above?

lofty mason
#

Triple backticks (`)

hearty verge
#

Are you posting an answer for me!

inner mesa
mighty ledge
plain magnetBOT
#

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

hearty verge
#

So whats the point of the media selector?

mighty ledge
#

for use in targets

#

triggers are limited to 0 templates

hearty verge
#

ah

mighty ledge
#

so you have to get aroudn that limitation

hearty verge
#

so i need to select an entity and then also would use media to select the same entity + the media i want to play

mighty ledge
#

that means the output of your !input needs to be able to go directly into the field without needing a template

mighty ledge
hearty verge
#

I need a local file as well to play

#

Turning my fireplace scripts into a blueprint:

If fireplace on + no sound on sonos - play user selected "fireplace sounds"

#

so you need to select fireplace + a media_player + a sound

mighty ledge
#

Then you'll need both

hearty verge
#

alas

#

but thanks

inner mesa
#

lol that you need a sound system to make your fireplace sound like a fireplace

#

this is why we have technology

mighty ledge
#

gas fireplaces

#

lol

hearty verge
#

Yup... although I'd really like them to close out my PR to allow cloud control for the unit ... its unfortunately more reliable than local

#

I still need a trigger_variable right and then a template trigger?

#

oh nevermind

#

looks like i can use !input in the platform state

mighty ledge
#

you can use !input in any field as long as the output of the input matches what the field requires

#

!input is just a glorified secret

#

or yaml anchor

plain magnetBOT
#

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

mighty ledge
#

@royal vector No, the template sensor is not required, it used to be back in the day based on the intentions of the code. It baiscally was made to get the switches previous state. In the past, you weren't able to self reference in a template. Now you can with this.state.

royal vector
#

i didnt think so, but i cant find a way to get just the cover config referencing the state of the binary sensor to work as i expect it to. heres is my config that i was using

plain magnetBOT
#

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

floral steeple
#

Hi, how do I express this as a template value?
V = dT x Q

V = Volume (L)
dT = delta Time (h)
Q = Volume flow rate (L/h)

#

dT= last time stamp - (last time stamp before that)

#

?

mighty ledge
mighty ledge
#

if the answer is no, then you're at an impasse

#

unless you're looking for Q

#

and you have V

#

TLDR, wtf are you looking for and what data do you have

inner mesa
#

Mmm...algebra

mighty ledge
# inner mesa Mmm...algebra

remember when I said all that crap about the config helper in VSCode? this just popped up when I started it at my house 🤣

inner mesa
#

I just configured it once and good to go

mighty ledge
#

well apparently I installed it and then never did anythng with it @ my home PC

floral steeple
#

lol I have a water meter that only reports instant flow rate for example, 0 L/h or whatever x L/h. I want to calculate total consumption from this based on the time.

#

it updates everytime the flow rate changes

#

no flow = 0 L/h

mighty ledge
#

does it have a device_class and state_class?

#

if yes, just use the energy tab

#

it does it for you

floral steeple
#

really, from a rate it can calculate that?

mighty ledge
#

Yes, all you need is the rate and you can calculate V for any timeperiod

floral steeple
#

fantastic! then I just have to create a template sensor with the device_class and state_class

mighty ledge
#

you can just customize it

#

via customize.yaml

floral steeple
floral steeple
#

just confirm, if I made a customize.yaml !inlcude file (under homeassistant: in my configuration.yaml)
the sensor should have this state and device class

  device_class: water
  state_class: 'total_increasing'
floral steeple
#

unfortunatly, even with the settings above and correct class, it won't allow me to use it as a water consumptions sensor because the units are L/h not, L, gallons, etc. So, it seems it does not accept rate unless I did something wrong

compact rune
#

I'd guess you need a riemann sum on top of the rate to get an accumulated value

floral steeple
#

how do I get it to drop the time unit though? I have ~~divide ~~ multiply by dT

#

V = dT x Q

bronze tide
#

can anybody give me a hint how to calculate the difference between {{ now().time() }} and a input_datetime helper with time only? I want to find out whether the time in the input_datetime helper is not yet reached.

inner mesa
#

I would do something like:
{{ now() > today_at(states('input_datetime.test2')) }}

bright quarry
#

hi. how can i display the volume level of my media player in the frontend ui?
media_player.home_assistant_speakers
attribute is called; volume_level:

opaque wyvern
#

Why Does this not work?

bronze tide
boreal pilot
#

Good evening all, trying to grasp still all the possibilities of templates in HA.
I have a sensor that provides me with a lot of data via its Attributes.
In these attributes I find item A, item B, Item C and so on.
I would like to create automatically for each item a button(image) that shows me some information gained from within these attributes and when clicked calls a service.
I am already fiddling around under developer tools -> template.

Is this possible? Or should I create each button manually.
Just trying to get a headstart, quick learner here 🙂

This is what I currently have in the template editor:
http://pastie.org/p/4lH2HRoPmUIe5F78Di5pzX
It allows me to get the necessary values, but I cant seem to get them working as sensors of some sort. My modifications to the configuration.yaml dont create them as actual sensors, so I am kinda stuck.

rose scroll
#

Follow the format in the template sensor docs closely.

marble jackal
#

With clever use of YAML anchors you can maybe simplify the code, but you can't template the entire YAML code for your config

#

it might look valid in the template checker, but that doesn't check for valid YAML

#

if you really want it dynamically, put all the data in a attribute, although if you have a lot of items, it might get too big to store it in your database

boreal pilot
marble jackal
#

that's what I mean, create one new template sensor with a state of just ok or whatever, and take the 2 values you need and put those in an attriubte

#

however, if it is for displaying it on a dashboard, you won't gain anything in that way

#

You might be better of using a Markdown card, which accepts templates

boreal pilot
#

The goal is to create a separate button for each item on the dashboard, each button includes an image and the info gained from the 2 lines.

merry marsh
#

I wonder, what is the most used or best way to check if "2023-06-07T08:00:00+00:00" is today. Most probably an often-used step, but I was not able to find examples in the community. Or I searched in a wrong way. Any example or proposal would be appreciated.

marble jackal
#

as_datetime("2023-06-07T08:00:00+00:00").date() == now().date() is what I would do

marble jackal
#

it can dynamically create cards based on templates

boreal pilot
#

@marble jackal Thanks, I'll have a look 🙂

boreal pilot
#

Trying it in a different way as well, just to see if I can create one sensor.

  - binary_sensor:
      - name: Ice Tea + '{{states.sensor.grocy_stock.attributes.products[1].name}}'
      - state: "{{states.sensor.grocy_stock.attributes.products[1].available_amount | int(0) }}"```

But I get an error msg:
Invalid config for [template]: required key not provided @ data['binary_sensor'][0]['state']. Got None. 

But when I look at examples of other template-binary sensors, my code seems to be alright.
Is it just not possible to gain information out of the attribute this way?
marble jackal
#

remove the - before state

#

you are creating a second binary sensor now, and the first one is missing the state template

#

the second one is missing the name but that one is optional

#

you probably have a binary_sensor.template_1 or something simalar now

#

also, you are aware that you are creating binary sensors now right, so the state will be on or off

boreal pilot
#

@marble jackal Thanks, that solved it. The first template is always the most difficult one 😄
I thought a binary sensor would be good in my use case, but just checked it out and it wasnt. Changed it to a sensor and it shows now the data that I want.
I now have a working button that shows the information that I want 🙂
It calls a service, that does a manipulation on the data and after a delay, it shows the updated data.

Thanks for your help mate, much appreciated.

opaque wyvern
#

Basic template question. Is there anyone here?

jovial quail
#

“`
template:
{% for matter_device_entity in integration_entities('matter') -%}

  • binary_sensor:
    • name: "{{state_attr(matter_device_entity, 'friendly_name')}} Available"
      unique_id: "{{matter_device_entity}}_available"
      state: "{{ is_state('matter_device_entity', ['unavailable', 'unknown', 'none']) }}"
      {% endfor %}
      “`
      Hey, is there someone that knows how i could get something like this to work in homeassistant? I guess its not possible to use a for loop to define entities
mighty ledge
#

There is no way to "make it possible" either.

jovial quail
# mighty ledge There is no way to "make it possible" either.

I know that. My question was if i can achieve something that gets me a similar result a different way. My goal is basically to have an entry in influxDB where i can see when devices are available/unavailable. I can of course do all of this manually, but is there a more generic way to do it(doesn't need to be a template)?

mighty ledge
#

No, there's no way around this. You can't dynamically create entities

#

you can use yaml code to create the yaml and then paste it into your template file

#

that's the best option

#

You could create a custom integration that does this, but that would require integration creation knowledge and python knowledge

jovial quail
#

Thanks for the answer. I have also thought about making a costum integration, but that would just be overkill for my usecase.

young ridge
#

Struggling to get this template right, but I have a group of sensors in my freezers.... Sensors.freezer_sensors..... I'm to make a template sensor that will show the number of sensors greater than 10... Basically if any sensors are too hot.

I have expand | map(state) | map(float) | list.... And that works. But I can't seem to get the list to filter entries less than 10. Thoughts?

mighty ledge
young ridge
#

Thanks

#

I was trying map >

#

Is there a way to get the entity id of the ones instead of just the value?

marble jackal
#

not without a for loop

young ridge
#

👍

#

That's what I figured

lament dust
#

Not sure if this would fall under templates or not, but is there any way to create a button and have it associated to an existing device? For instance the android tv remote integration. Its a cool integration but out of the box doesnt have any buttions really. Id love to be able to add 2 or 3 buttons on the device that lets me open apps for instance

mighty ledge
#

you can't add items to devices in the devices page

#

but you can just make scripts or button helpers that aren't linked to the device

fast kettle
#

You have to create all the buttons yourself manually, it doesn't generate any by default at all.

lament dust
#

Well not devices to devices, but adding entities to devices. Like with a mqtt sensor I can make 4 sensor and associate them all to the same psueudo mqtt device

#

was just curious if there was a way to do that with other entities like add buttons that would run a script, etc..

mighty ledge
#

Yes, as I said, that's not possible

#

There's no way to add to existing devices. Helper entities can in some circumstances, but that's it. IIRC the only integration that does it is the switch as X integration.

lament dust
#

Interesting okay guess Ill just make a script for now then

fast kettle
#

The android TV remote creates a single remote entity and that's it.
You can create buttons that do whatever you want, but those aren't device entities on the remote, they're just buttons that call the remote service or scripts or whatever.

lament dust
mighty ledge
#

remotes in general need an overhaul

#

the way they are handled is pretty bad

lament dust
#

Got it, any idea why remote wouldnt even appear as a service for me?

mighty ledge
#

that means you don't have an integration that creates a remote

lament dust
#

Yeah seems because the tv was turned off when HA started it was giving an error. All fixed now though

mighty ledge
#

ouch, what integration for the tv?

#

@lament dust ^

lament dust
#

Yeah, the android tv remote. Its been super flaky for me in general. I had to reconnect it the other day

mighty ledge
#

ah

#

ok

willow wing
cursive ice
#

you have probably answered this 100 times already guys, but what do with my platform: template sensors now (tried searching forums but no joy_) fixed all the other stuff, removed skyq platform: but still get his error and not sure what to do ```The version platform for the sensor integration does not support platform setup.

Please remove it from your configuration and restart Home Assistant to fix this issue.``` do I just move all the sensors into command line and remove platform from them?

marble jackal
#

This is unrelated to template sensors

#

It's about your version sensor

cursive ice
#

I think I just found it Fes, restarting now, it was in my system monitor template

#

fingers crossed

marble jackal
#

It should be something with platform: version

cursive ice
#

found it, has not popped up on restart now, it was hidden in my system template, in-between two template sensors lol cheeky line of code

silent vector
#

Is there a way for a script to write a dictionary to an input text sensor or something? I want to write the last 10 script calls variables passed to it that cleans out every 3 seconds, to a template sensor somehow for memory. The goal would be if the script received the same set of variables in the last 2 seconds do nothing for example

marble jackal
#

not to an input text, that's always a string

#

you can write it to an template sensor attribute

silent vector
#

How would I write it to a template sensor attribute?

marble jackal
#

a trigger based template sensor with an event trigger

#

you can then send an event in the script, with the data you want to store

silent vector
#

Interesting. Any idea how I could make a template store up to 10 events only keep each one that comes in for 3 seconds? I assume I would also send a timestamp with the dictionary so that the template could filter them out when it's older than 3 seconds

#

Then the max of 10 wouldn't matter only events less than 3 seconds get to stay

marble jackal
#

you writ the wanted data and a timpestamp, and clear it up on every update, and on a 1 minute time interval

silent vector
#

Yeah that's what I thought. What's the service to call an event? I'm not seeing it.

#

Lol literally called fire event nevermind

#

It's saying it expected a dictionary for dictionary value for event data

"{{ { target_lights: lights_setting,'set_lights':set_lights,'timestamp':'foo' } }}"

Isn't that a dictionary ^?

marble jackal
#

you need to provide a key for the data

#
event: foo
event_data:
  bar: '{{ some data in a template }}"
silent vector
#

Oh 🤦‍♂️

marble jackal
#

you can also do this

event: foo
event_data:
  lights_setting: 
    set_lights: "{{ set_lights }}"
    timestamp: "{{ now().isoformat() }}"
silent vector
#

Good idea. In terms of the template trigger how should I go about adding the data so it's stored for 3 seconds. There could be 5 events within a few seconds of each other so a lot of data could come in at once and need to be stored. The goal of this is to dynamically reject some service calls to turn on/off lights. All my automations call this script to turn lights on. If someone hits the switch at the same time as my presence Detection turns the lights on they will end up turning them off lol. So rather than at each automation building something to stop that I figured I should do it here.

- trigger:
  - platform: event
    event_type: 'Master Lights Script Data'
  sensor:
    - name: "Maater Lights Script Memory"
      state: 'hello'
      attributes:
        memory: "{{ trigger.event.data }}"
#

This may or may not do what I want but still a good exercise I can keep for future reference.

marble jackal
#

You need to create a list with events and add each new event to the existing list using this.state

boreal panther
#

Hi all - I'm working on an automation, and HA is throwing the following error: Template variable error: 'dict object' has no attribute 'to_state' when rendering '{{ not (trigger.to_state.state in ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning', 'Tornado Watch', 'Severe Thunderstorm Watch', 'Flash Flood Warning', 'Excessive Heat Warning']) or (is_state('sensor.weatheralerts_1_alerts_are_active') == 'No') }}' The code that I'm using can be found at https://dpaste.org/hsfn8 - I could use a second pair of eyes to see where my wheels are falling off here. It seems to be working OK when I manually set the state for sensor.weatheralerts_1_alert_1_most_recent_active_alert, but evidently HA is having a kitten about it.

inner mesa
#

you didn't include the actual trigger, but that is usually caused by you just running the action of the automation and not letting it trigger

#

Or you didn't use a state trigger. Please include the whole thing when sharing code, rather than just the snippet you think is important

boreal panther
inner mesa
#

ok, so you have two triggers:

    trigger:
      - platform: state
        entity_id: sensor.weatheralerts_1_alert_1_most_recent_active_alert
      - platform: time_pattern
        seconds: '/3'
#

trigger.to_state will only be available when the first one fires

#

so every three seconds, any reference to trigger.to_state will fail in the way you described

boreal panther
#

I was wondering about that, TBH... I've had input from a few others helping me along with this, and I think that might have muddled things up. That said, to this totally n00b mind, it seems to me that if I have the sensor state defined under action, then I wouldn't need it under trigger, correct? Because I'm telling the automation to kick off every 3 seconds (which is making the light flash in red mode) and checking for the current status of that sensor.

inner mesa
#

yes

boreal panther
#

OK, I will take that statement out and see what happens.

inner mesa
#

the whole thing seems kinda fragile, though. You're running it every 3 seconds and you sometimes have a 2.5 second delay in there

boreal panther
#

It felt like this was a fairly straight-forward operation that I wanted to make happen, but it has been difficult to get just right.

boreal panther
inner mesa
#

I would use a state trigger and a repeat/while in the action

#

and maybe a second trigger for HA restart

#

or repeat/until

boreal panther
#

Essentially, a specific alert is issued by NWS. It either triggers flashing red, solid yellow, or solid green. Furthermore, IF the lights were at the flashing red or solid yellow state, and that particular alert has been cleared, it needs to go back to green.

inner mesa
#

yes, you could do that with what I suggested

#

and it wouldn't trigger every 3 seconds forever

boreal panther
#

The last time we had a warning, the lights went over to flashing red as they were supposed to, but never came out of that mode. The automation was still picking up on the "most recent active alert" and didn't pick up that there was no longer ANY active alert. That's a totally different sensor altogether, and what needs to be integrated into this as well.

inner mesa
#

ok

boreal panther
#

If I flow chart this in my head, I think the automation probably needs to check if that active alert sensor is set to Yes or No... If no, go about your day. If yes, then drop into the automation we've been looking at.

inner mesa
#

that's a trigger

boreal panther
#

So, that could be put up at the beginning of the automation, where I am taking out the current "platform: state"

#

And, in doing so, my new trigger would be a platform: template and then I'd follow that with a value_template: "{{ is_state('sensor.weatheralerts_1_alerts_are_active', 'Yes') }}

inner mesa
#

that's just a state trigger

#

you don' t need a template for taht

#
trigger:
  platform: state
  entity_id: sensor.weatheralerts_1_alerts_are_active
  to: 'Yes'
boreal panther
#

OK, I'm working on modifying the automation. I'm not going to address the time_pattern just yet, as I only want to tackle one issue at a time so as to not create more variables that could derail things. 🙂 I think the only other issue I have, is how to reset back to green when the "alerts_are_active" flips back to "No"... as it stands now, the automation will stay in either red or yellow, because there's nothing to tell it to go back to green when the alert clears. Which is what happened the last time, and how I fell into this rabbit hole. -- In my code, in the conditions field, could (or should) I add a condition where alerts_are_active is also set to yes?

#

Because if I do THAT, in the condition for green, I could tell the automation to check to see what the state is for alerts_are_active.

#

Thus, my condition for red, for example, would look something like this: conditions: "{{ is_state('sensor.weatheralerts_1_alert_1_most_recent_active_alert', ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning']) }}" and "{{ is_state('sensor.weatheralerts_1_alerts_are_active', ['Yes']) }}"

#

Hmmm.... except I'm not doing a list for alerts_are_active I'm only checking for a single state, so I need to change that.

#

I think all I need to do is take the [ ] out from around the Yes

inner mesa
#

yes, but that doesn't matter

boreal panther
#

(I really do appreciate your guidance on this, BTW... I'm trying to learn...)

inner mesa
#

a list of one item is the same as a single item not in a list in that case

boreal panther
#

OK - let me update the entire section and see what HA says....

#

HA is complaining about a "Bad indention" at my and statement.

#

OK, I've broken down the two sensors into two separate "condition: template" statements.

#

That seems to make HA happy.

inner mesa
#

this should be states(): state('sensor.weatheralerts_1_alert_1_most_recent_active_alert')

#

and you're still using templates where a "simpler" state condition would suffice, but that doesn't matter for functionality

#

and this will still blow up:

          - conditions: >
              {{ not (trigger.to_state.state in ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning', 'Tornado Watch', 'Severe Thunderstorm Watch', 'Flash Flood Warning', 'Excessive Heat Warning']) or (is_state('sensor.weatheralerts_1_alerts_are_active') == 'No') }}
#

for a couple of reasons. first, you have no state trigger. second, (is_state('sensor.weatheralerts_1_alerts_are_active') == 'No') is broken syntax

boreal panther
#

OK... I didn't touch that one this time around (yet), I only worked on the red & yellow. That was the example I was given by someone else when it broke last time, to try to fix it. 🙂 So I could make it like the red & yellow, but I have to admit, I'm still a little confused about the states vs templates. (Sorry....)

boreal panther
boreal panther
#

The logs show that I've pretty much got everything cleaned up to where HA is almost happy... I'm getting one error now with two different descriptions in the same error: Error in 'choose[0]' evaluation: In 'template' condition: UndefinedError: 'state' is undefined and Error in 'choose[0]' evaluation: In 'template' condition: TypeError: is_state() missing 1 required positional argument: 'state'

#

That's all it's telling me, so I'm assuming it's referring to my choose statement.

inner mesa
#

that's what I pointed out above

boreal panther
#

(Trying really hard to follow along here....) So, I'm checking for the value of two different sensors. Right now, I've got two condition: template statements, each followed by a value_template statement. However, you're saying that I should use states instead. I'm unclear how I would replace what I have with the proper "states" statement.

inner mesa
#

value_template: "{{ state('sensor.weatheralerts_1_alert_1_most_recent_active_alert') in ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning'] }}"

#

you have "state" where you need "states"

#

and you have is_state() somewhere without the second parameter

#

I don't see where, but clearly somewhere

boreal panther
boreal panther
inner mesa
#

no

#

it's quite simple, you're using the wrong function

boreal panther
inner mesa
#

value_template: "{{ states('sensor.weatheralerts_1_alert_1_most_recent_active_alert') in ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning'] }}"

#

you're missing an "s"

#

there are 10000 ways to do this and I don't care which you use, but you have to do one of them correctly 🙂

boreal panther
inner mesa
#

I hope it's clear, then

#

I did it for you

boreal panther
#

I do appreciate the help, and my apologies if I didn't seem to pick up the concept(s) quickly.

vast juniper
#

Hello, I was wondering if there is a way to retrieve yesterday's attribute massage from local calendar. Currently, I am using the following code:

cut_off_days_yesterday:
  unique_id: cut_off_days_yesterday
  friendly_name: "Cut Off Day Yesterday"
  icon_template: "{{ 'mdi:calendar-clock'}}" 
  value_template: "{{ states.calendar.cut_off_days.attributes.message if now().strftime('%H:%M') == '23:59' else states.sensor.cut_off_days_yesterday.state}}"```
However, I have noticed that after Home Assistant restarts, it displays as "unknown" status until it updates at the end of the day again. I was wondering if there might be a more reliable alternative.
cyan ingot
#

Hello everyone ! I have used HA for a lot of things but today I struggle with something because I don’t 100% grasp the method of programming in HA

I am making a program that make booking on a website, everything is managed in python, I just use HA as an interface to show info, or send command.

So basically I am running into a problem, I have 4 next reservation I want to show nicely. The problem is that I did it with webhook and sensor, but I did have a setup that was long (each user has 5 sensors), and it doesn’t look nice in the interface.

I just want a simple text for each user, I read that I can do that with markdown but couldn’t do it by myself…

#

Here is my code

template:

  • trigger:
    • platform: webhook
      webhook_id: cisjzbzje
      sensor:
    • name: "Booksite seat user1"
      state: "{{ trigger.json.seat }}"
    • name: "Booksite date user1"
      state: "{{ trigger.json.date }}"
    • name: "Booksite hour user1"
      state: "{{ trigger.json.hour }}"
    • name: "Booksite status user1"
      state: "{{ trigger.json.reservation_status }}"
    • name: "Booksite upcoming user1"
      state: "{{ trigger.json.upcoming }}"
#

The problem is that this code is duplicated for each user, if it were in python I would just have a dict or a list to manage this, but I don’t understand how to do it in HomeAssistant

#

My second problem is about the dropping list. I have a list of 4 next reservations I could send in a nice json to HomeAssistant, but I don’t want to store them in 4 different sensors for each user. Is it possible to store them in a list ?
If so, is it possible to have an id associated with each item ? The id will be received with the item in the webhook.

The id will serve if I want to manage the reservation in the drop list. I will select a future reservation from the list, it will select it by the id associated to it, then send a request to my server to do something with it.

I won’t go into details about my python program, but if I could just send an Id it will interpret it ok. But the id has to be the same as the one the program have sent to HomeAssistant… thank you for any help you could provide 🙏

sleek halo
#

Hey guys, was sent here from @integrations. I have a shelly h&t (temp sensor) that is integrated into HA. Im trying to set up a payload template to broker the temp-reading so that my NibePi (system i use to control my heat-pump).. Any1 care to explain what im supposed to do?

marble jackal
marble jackal
plain magnetBOT
#

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.

sacred sparrow
#
    - name: "NAS Status"
      icon: phu:nas-v2
      state: >
        {% if is_state('sensor.nas_volume_1_status', 'normal') or is_state('sensor.nas_volume_2_status', 'normal') or states('sensor.nas_upload_throughput')|float(0) > 0.1 or states('sensor.nas_download_throughput')|float(0) > 0.1  %}
          On
        {% elif states('sensor.nas_download_throughput')|float(0) > 1.9 %} 
          Powering Up  
        {% else %}
          Off
        {% endif %}```
ON and OFF work but not Powering up - What have I done wrong?
fickle sand
#

The if else code breaks on the place where it first renders true.
Powering Up will never be true first with this logic because > 0.1 was earlier in the statement rendered as true

sacred sparrow
#

I see what I've done

marble jackal
sacred sparrow
#

I have the wrong sensor in there haha

marble jackal
#

so it will be on

sacred sparrow
#
    - name: "NAS Status"
      icon: phu:nas-v2
      state: >
        {% if is_state('sensor.nas_volume_1_status', 'normal') or is_state('sensor.nas_volume_2_status', 'normal') or states('sensor.nas_upload_throughput')|float(0) > 0.1 or states('sensor.nas_download_throughput')|float(0) > 0.1 %}
          On
        {% elif states('sensor.nas_smartplug_watts')|float(0) > 1.9 %} 
          Powering Up  
        {% else %}
          Off
        {% endif %}``` is what it was meant to be. my laziness copy/paste got me
marble jackal
#

that makes more sense

sacred sparrow
#

thanks for the help guys!

sacred sparrow
#

one more thing from me

#
    - name: "NAS Total Throughput Status"
      state: >
        {% set throughput = states('sensor.nas_upload_throughput') | int + states('sensor.nas_download_throughput') | int %}
        {% if throughput > 1100  %}
          Transferring
        {% elif throughput > 300 %} 
          Streaming  
        {% elif throughput > 10 %} 
          Scanning
        {% elif throughput > 1 %} 
          Idle
        {% else %}
          Off
        {% endif %}```
#

I have this and it works but in my history I see:
Became unknown triggered by state of NAS Upload throughput changed to 3.256

#

why would it show as unknown?

#

I am thinking its because maybe states('sensor.nas_download_throughput') was not a number? is there a way to make it 0 if its not a number?

sacred sparrow
#

I am hoping there is something easier than: {% if states('sensor.nas_upload_throughput') | is_number -%} {{ states('sensor.nas_upload_throughput') | int }} {%- else -%} 0 {%- endif %} + {% if states('sensor.nas_download_throughput') | is_number -%} {{ states('sensor.nas_download_throughput') | int }} {%- else -%} 0 {%- endif %}

plain magnetBOT
#

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

marble jackal
#

but you can add default to the int filters to make it work with non numeric states

#

or add an availability filter

#

@dusky pike lights don't have a color attribute, I assume you mean the rgb_color attribute

#

and data_template has been depreciated for over 3 years now, you can just use data

dusky pike
#

ye i got it down to this

#

set_color: service: light.turn_on entity_id: light.bed_rgbw data: rgbw_color: - "{{ state_attr('light.bed_light_correction', 'rgb_color')[1]}}" - "{{ state_attr('light.bed_light_correction', 'rgb_color')[0]}}" - "{{ state_attr('light.bed_light_correction', 'rgb_color')[2]}}" - "{{ state_attr('light.bed_light_correction', 'brightness')}}"

#

But the problem is that i cant use the inside variables for it like {{ brightness }} for some reason...

#

i just want to pass the variables in diferent order but if i do it like this i get an error when the entity is off

#

but it works except the brightess param... strange.

#

rgb_color is working and rgbw to... but somehow the {{ state_attr('light.bed_light_correction', 'brightness')}} is returning a non int... wtf.

marble jackal
#

what does it return in developer tools > template

sacred sparrow
marble jackal
#

int(0) has 0 as it's default value

sacred sparrow
#

okay great - but why would I get Became unknown triggered by state of NAS Upload throughput changed to 3.256?

marble jackal
#

well, probably the other involved entity had a non numeric state

#

so the template was triggered by the state change of this entity, but ran into error because of the non numeric state of the other entity

sacred sparrow
#

ah yes so that means (0) should fix it

marble jackal
#

@dusky pike according to the template in the docs, I would suggest to use hue ans saturation for the color (which ara available as the variables h and s)

dusky pike
#

The problem is i need to switch the red and green. My leds are mosmatched with my led controler... @-@

sacred sparrow
#

this is still showing the same message:

#
    - name: "NAS Total Throughput Status"
      state: >
        {% set throughput = states('sensor.nas_upload_throughput')|int(0) + states('sensor.nas_download_throughput')|int(0) %}
        {% if throughput > 1100  %}
          Transferring
        {% elif throughput > 300 %} 
          Streaming  
        {% elif throughput > 10 %} 
          Scanning
        {% elif throughput > 1 %} 
          Idle
        {% else %}
          Off
        {% endif %}```
#

Became unknown triggered by state of NAS Upload throughput changed to 3.071

marble jackal
#

are you sure you reloaded the template entities after your change

sacred sparrow
#

yep

#

thats why im very confused

#

I even restarted HA

vast juniper
plain magnetBOT
#

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

lofty mason
#

don't think you should capitalize Sensor anywhere states('Sensor.second')

thorny snow
#

Also not working 😕

inner mesa
#

Yeah, you have capital letters all over the place that don't belong

#

And your indentation is wrong

#

At least inconsistent, and you're missing a :

#

Just review the docs and compare

#

Attention to detail is important, and that just looks tossed together

plain magnetBOT
#

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

thorny snow
#

But if I use only on eof the sensor as single value without any calculation or combination with other vlaues, it also returns "unknown"

inner mesa
#

Your as_timestamp() call has mismatched quotes

thorny snow
#

changing right now.

teal cedar
#

Hi all, I am trying to create what I thought would be really simple sensor to look at an attribute on an Abode Alarm sensor that returns True or False and just translate that to "Good" or "Low", but I am having a lot of trouble with that. Can anyone point me in the right direction? The below returns "Unavailable":
`template:

  • sensor:
    • name: "Alice Office Window Battery"
      value_template: >
      {% if is_state('binary_sensor.alice_office_window.attributes.battery_low', 'False') %}
      Good
      {% else %}
      Low
      {% endif %}
      device_class: battery
      unique_id: "RF:0328e410"`
inner mesa
#

you're not following the proper format

#

change value_template: to state:

#

sorry, didn't see that you were trying to test an attribute like that. That's wrong, too 🙂

#

{% if is_state_attr('binary_sensor.alice_office_window' 'battery_low', 'False') %}

#

you may need to remove the quotes around "False", depending on the actual type of the attribute

#

test it in devtools -> Templates

hollow vortex
#

I added the cpu temp to my configuration.yaml file. It outputs in C and even though my settings are for F, it is not being auto converted. How should I correct this?

hollow vortex
tepid onyx
#

what's it set to in the gui?

#

one of the appears to override the other so set them both. Probably the gui overrides the yaml. Then restart HA core

hollow vortex
tepid ice
#

Need help on template sensor. Following format doesn’t work. # platform: template
sensors:
salah_fajr:
friendly_name: "Fajr"
value_template: "{{ (as_timestamp(states('sensor.fajr_prayer')) - 60) | timestamp_custom('%Y-%m-%dT%H:%M:%S+00:00', false) }}"
device_class: timestamp

plain magnetBOT
#

@tepid ice 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
#

I think you want to do
{{ as_datetime(states('sensor.fajr_prayer') - timedelta(second=60) }}

lament dust
#

Is it possible to use a macro for creating multiple sensors via mqtt?

#

I made a simpleish macro that will take a bunch of params and then return alist item to use as a sensor rather then repeating a lot of the boiler plate: https://pastebin.com/d6KHghqj

Then trying to call it like so:

sensor:
  - {{shelly_ht_mqtt("Freezer HT Sensor Temperature C", "shelly-ht/freezer-ht-sensor/status/temperature:0", "value_json.tC", "°C", "temperature", "mdi:thermometer", "freezer_ht_ctemperature")}}

But getting a bunch of weird yaml errors

inner mesa
#

No, it is not

lyric comet
#

Another option could be to set all the other values as attributes of the primary sensor and use template sensors to convert any you need as sensors. This means everything can come up in one MQTT message.

thorny snow
#

I can post an example when HA restarted

#

States within developer tools displays

sensor.durchschnittlichetagesersparnis
average_daily_savings
 
sensor.tageseitinstallation
TageseitInstallation
 
sensor.tagesersparnis_2
Tagesersparnis
#

in Terminal I got

todaySaving
Tagesersparnis

daysSinceInstallation
TageseitInstallation

averageDailySavings
tägliche Durchschnittsersparnis
thorny snow
#

and even if I use the available entities, my calculation won't work.

{{states('sensor.gesamtersparnis_2') / states('sensor.tageseitinstallation') }}

if I use only one sensor, it works. So

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

and

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

give me the sensors value

inner mesa
#

States are always strings. You're trying to divide strings

thorny snow
#

ok, converting it to float and int worked. thanks

inner mesa
#

You dropped to the conversion to float and int for some reason

thorny snow
#

but can you tell me something regarding the "wrong" naming

inner mesa
#

Nope

thorny snow
#

too bad

#

maybe a restart helps after fixing that

teal cedar
#

Thanks @inner mesa ! I tried state: previously and different quotations around the False value but wound up with a similar errors. I didn't know there was a different way to test the attribute. That seems to get me a lot closer. I got a "Normal" value once, but now I just seem to be getting unknown. I've tired 'False' and False. Is there any way to do any additional debugging / testing? When I put the below IF statement into Dev Tools / Template, I get the anticipated response of "Good".
`template:

  • sensor:
    • name: "Alice Office Battery Test"
      state: >
      {% if is_state_attr('binary_sensor.alice_office_window', 'battery_low', False) %}
      Good
      {% else %}
      Low
      {% endif %}
      unique_id: "RF:0328e410"
      device_class: battery`
lament dust
lament dust
# inner mesa No, it is not

Damn, is it possible to split the mqtt file into sub files based on sensors/devices? Or any other suggestions to avoid repeating code. I basically have 8 of those sensors configured with very slightly changes, 2 for temp(c and F), 1 for battery, and one for humidity

nocturne chasm
#

Why does this list every one of my entities?
{{ states | selectattr('entity_id', 'search', '_round_trip_time') | selectattr('state', '>', '.150') | map(attribute='object_id') | map('replace', '_round_trip_time', '') | map('replace', '_', ' ') | map('title') | join(', ') }}

#

I think it is because it is a float and not an int?

#

but dont know how to do a float

inner mesa
#

it's because all states are strings always

nocturne chasm
#

this one seems to work though?
{{ states | selectattr('entity_id', 'search', '_rssi') | selectattr('state', '>', '-70') | map(attribute='object_id') | map('replace', '_rssi', '') | map('replace', '_', ' ') | map('title') | join(', ') }}

inner mesa
#

you can't compare a state with a number like that without a for loop

#

no, states are still always strings

#

maybe because of ascii math

#

it's not comparing numbers

nocturne chasm
#

so I have to do a template sensor?

inner mesa
#

what is that?

#

it's a template, but where you use it doesn't matter

nocturne chasm
#

mark down card

inner mesa
#

you have to use a for loop

#

it doesn't matter where you use it

nocturne chasm
#

just trying to check the rssi values and round trip times of zwave devices without making a group

inner mesa
#
{% set ns=namespace(names=[]) %}
{% for entity in states|selectattr('entity_id', 'search', '_rssi')|selectattr('state', 'is_number')|list %}
  {% if entity.state|float > 0.150 %}
    {% set ns.names = ns.names + [entity.object_id| map('replace', '_rssi', '') | map('replace', '_', ' ') | map('title')] %}
  {% endif %}
{% endfor %}
{{ ns.names|join(', ') }}
#

something likke that

nocturne chasm
#

float got invalid input 'unknown' when rendering template

#

auh, some of the states are unknown?

inner mesa
#

you have some states that aren't nmbers

#

yes

#

I fixed it, btw

nocturne chasm
#

ha, i was busy in dev_tools/templates trying to figure it out

#

that is doing something funky though

#

<generator object sync_do_map at 0x7fe517734740>, <generator object sync_do_map at 0x7fe517734940>,

inner mesa
#

yeah, you need to get rid of the map() calls

#
{% set ns=namespace(names=[]) %}
{% for entity in states|selectattr('entity_id', 'search', 'input_number')|selectattr('state', 'is_number')|list %}
  {% if entity.state|float > 0.150 %}
    {% set ns.names = ns.names + [entity.object_id.replace('_rssi', '').replace('_', ' ')|title] %}
  {% endif %}
{% endfor %}
{{ ns.names|join(', ') }}
#

I just copied what you had without thinking about it

#

I changed it a bit to work with my entities

nocturne chasm
#

still not working. it lists every entity.

inner mesa
#

not sure what to say, it works for me

#

0.150 is a pretty strange RSSI value

#

my guess is that that's wrong and you need to revisit your criteria

nocturne chasm
#

It is round trip time

#

I will play with it and figure it out.

inner mesa
#

You're using exactly the same entities as you did above for your actual RSSI comparison against -70

#

Which is a weak, but fine RSSI

nocturne chasm
#

dont know what to tell you. if i put {% if entity.state|float < 0.150 %} i dont get any entities, if i put {% if entity.state|float > 0.150 %} i get every entity

#

it is not respecting the float

#

same results if i change the 0.150 to 1

inner mesa
#

I think you're using the wrong entities

#

Because RTT is not RSSI

#

and I notice that I may have led you there

#

That looks better

#

Anyway, I don't think this is a logic issue

nocturne chasm
#

no, i corrected it on my end. anyway, when i test _rssi it works perfect

#

and i noticed one of my devices has a rssi of 83 dbm. thats terrible 😝

heavy crown
#

Hello, I am searching through a list of dates to get data of 'today'. The list of dates sometimes does not contain 'today' and my method crashes. How can I make this return a proper true or false?

#
{% set date = state_attr('sensor.school_lesson', 'date') %}
{% set search_date = now().strftime('%Y/%m/%d') %}
{{ date.index(search_date) }}
#

this returns: ValueError: '2023/06/11' is not in list

inner mesa
#

You just want true if the date is in the list and false if it isn't?

heavy crown
#

Yes please

#

then I can work from that

#

something like if exists ??

inner mesa
#

Easy

heavy crown
#

of course... only one coffee so far...maybe the cause

inner mesa
#

{{ search_date in date }}

heavy crown
#

aaarghhh...getting second coffee now THANKS !!!!

floral shuttle
#

So I made this custom_templates {% set batteries = states.sensor |selectattr('attributes.device_class','defined') |selectattr('attributes.device_class','eq','battery') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='entity_id')|list %} whihc allows me to do attributes: batteries: > {% from 'batteries.jinja' import batteries %} {{ batteries }} and return all batteries

#

I used to have a template sensor with that repeated selector in state and several other attributes, but this is much more efficient. theres a catch... a low_batteries attribute (using the this variable up to now):```
low_batteries: >
{%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %}
{%- set ns = namespace(batteries=[]) %}
{%- for s in expand(this.attributes.get('batteries'))
if s.state|int(default=0) < alert_level %}

        {%- set ns.batteries = ns.batteries + [' ' + s.entity_id] %}
        {%- endfor %}
        {{- ns.batteries|join(',')}}```
#

cant be replaced using import.. {%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {%- set ns = namespace(batt_low=[]) %} {%- for s in batteries if s.state|int(default=0) < alert_level %} {%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %} {%- endfor %} {{- ns.batt_low|join(',')}} returns UndefinedError: 'str object' has no attribute 'state'

#

aarghhh.... I missed the expand there....```
low_batteries: >
{%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %}
{% from 'batteries.jinja' import batteries %}
{%- set ns = namespace(batt_low=[]) %}
{%- for s in expand(batteries)
if s.state|int(default=0) < alert_level %}
{%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %}
{%- endfor %}
{{- ns.batt_low|join(',')}}

bronze tide
#

Hi there! I connect an input_boolean and a templated binary_sensor with 'and' to another templated binary_sensor called functionality_athome. Both sensors which are joined by 'and' are 'on' according to their states in the states and yet the resulting sensor functionality_athome is 'off'. I tried a few things so far and got stuck. Can you give me a hint?
Here is the code:

    functionality:
      name: My Functionality
- binary_sensor:
    - name: "Home: Uwe is here"
      unique_id: "at home uwe yn"
      state: >
        {{ is_state('person.uwe', 'home') }}
    - name: "functionality_athome"
      unique_id: "functionality_athome"
      state: >
        "{% if ((is_state('input_boolean.functionality', 'on')) and (is_state('binary_sensor.home_uwe_is_here', 'on'))) %}on{% endif %}"```
I think the stare of functionality_athome can be simplyfied by removing the if/endif resulting in a simple 'and'. But this how it is at the moment.
obtuse zephyr
#

I'd try changing it to {{ is_state('input_boolean.functionality', 'on') and is_state('binary_sensor.home_uwe_is_here', 'on') }} and see how that goes

#

Ah... you also don't need " when you're using the > syntax

#
- name: "functionality_athome"
  unique_id: "functionality_athome"
  state: >
    {{ is_state('input_boolean.functionality', 'on') and is_state('binary_sensor.home_uwe_is_here', 'on') }}
bronze tide
# obtuse zephyr I'd try changing it to `{{ is_state('input_boolean.functionality', 'on') and is_...

I simplified the expression and with the quotation marks gone like you suggested and the correct result showed up. I wonder why the quotation marks negate the result. Have you got some link where I can do some RTFM to dig for some explanation?
https://www.home-assistant.io/integrations/template/#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors shows the different how to use state: . The only difference I can see is that one liners with state: only need either single or double quotation marks, multi liners with 'state: >' do not need quotation marks. Hmmm...

lofty mason
#

The multiline thing probably escapes your quotation marks in the second line, so the template is never evaluated at all. It tries to just treat the whole string as the state, and since it does not match one of the strings for binary sensor to be on, it defaults to off.

bronze tide
inner mesa
#

There's a whole site for it

bronze tide
mental violet
#

Hi, I always wrote my sensors via:

configuration.yaml
sensors: include sensor.yaml

sensor.yaml

  • platform: template
    sensorname:
    etc...

Now I got a message that this is an old way to include template sensors. How do I translate them into the right way?

In addition I now need to write some mqtt sensors. How do I include them in the right way too?
Thanks for your help

slate fossil
#

Wondering if someone can help simplify this for me. Here's a portion of my template which works.yaml {% set charging_state = states('sensor.s22_ultra_charger_type') %} {% if charging_state == 'none' %} {% set charging = "" %} {% elif charging_state == 'ac' %} {% set charging = "charging-" %} {% elif charging_state == 'wireless' %} {% set charging ="charging-wireless-" %} {% endif %}

#

I tried to simplify it with this but I'm assuming because I use set on each line, only the last one actually works.yaml {% set charging = is_state('sensor.s22_ultra_charger_type', 'none') | iif("") %} {% set charging = is_state('sensor.s22_ultra_charger_type', 'ac') | iif("charging-") %} {% set charging = is_state('sensor.s22_ultra_charger_type', 'wireless') | iif("charging-wireless-") %}While the top code works, I would like something that is written a bit more efficiently. Any suggestions?

inner mesa
#
{% set map = {"none":"", "ac":"charging-", "wireless":"charging-wireless-"} %}
{% set charging = map[states('sensor.s22_ultra_charger_type')] %}
slate fossil
#

RobC That works perfectly. Thank you. I figured there had to be some way to use an array or something along those lines.

inner mesa
#

"dict" or "mapping"

slate fossil
#

Totally didn't even think about it. I use map in a Node-RED function to I wrote a while back ago to calculate Circadian levels. javascript function map(x, in_min, in_max, out_min, out_max) { return Math.round((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min); }

slow vine
#

in customize: is it possible to use templates (similar idea to customize_glob)? like a "customize_template" so all zwave switches in specific area(s) get specific icon.

inner mesa
#

No

slow vine
#

thanks.

floral shuttle
#

how odd, template sensor using custom_templates: - unique_id: alerts_notifying state: > {% from 'alerts.jinja' import alerts %} {{alerts|count}} name: > {% from 'alerts.jinja' import alerts %} {% set count = alerts|length %} {% set phrase = 'Alert' if count == 1 else 'Alerts' %} {{count}} {{phrase}} actief icon: > {% from 'alerts.jinja' import alerts %} {% set count = alerts|length %} mdi:numeric-{{count}}-box

#

returns 0 on all counts, while dev tools template {% from 'alerts.jinja' import alerts %} {{alerts}} {{alerts|count}} clearly shows thats not the case...

#

|count or |length dont make a difference in this case as can be seen

#

I moved to import that custom_template, because I had this expand:```
state: >
{% set alerts = state_attr('binary_sensor.alerts','entity_id') %}
{{expand(alerts)
|selectattr('state','eq','on')|map(attribute='entity_id')|list|count}}

#

this is my alerts.jinja:```
{% set alerts = expand(state_attr('binary_sensor.alerts','entity_id'))
|selectattr('state','eq','on')|map(attribute='name')|list %}

{% set hubs_offline = expand(state_attr('group.hub_device_trackers','entity_id'))
|selectattr('state','eq','not_home')|list %}

{% set critical_off = expand('switch.critical_switches')
|selectattr('state','eq','off')|list %}```

#

whats more, when pasting the full template config in the dev tools, it clearly shows its correct...

cerulean cipher
#

It's all Dutch to me

#

Actually, I understand more Dutch than templates 😂🤣

floral shuttle
floral shuttle
#

Btw my post above shows how it’s done 😉

marble jackal
#

What do you have in alerts.jinja?

#

oh, sorry, you already posted that

#

you dont't have to expand that attribute btw, you can expand the group directly

#

expand('binary_sensor.alerts')

lament dust
#

Is there a way to split up mqtt sensor files? Ideally Id like to do one file per device?

marble jackal
#

not templates related, but youy can do one include per domain.

#
mqtt:
  switch: !include dir_merge_list mqtt/switch
  light: !include dir_merge_list mqtt/light
lament dust
marble jackal
#

You can do that using packages

lament dust
icy jay
#

Hey,

ive got 12 entities with a certain value. I want to create an automation that compares all 12 of them and sends me a notification on the lowest 3 of them. How could i do this? Some ideas?

inner mesa
#

break it down into the parts that you need help with

icy jay
#
  • Find out what are the lowest 3 states (prices) out of 12 entities, all with the name sensor.x_diesel or if possible, from the integration tankerkoenig instead of the entity name

  • Output these 3 entities as a notification

inner mesa
#

so all of it 🙂

#

I suggest researching how you want to send the notification

#

there's no general solution for that

icy jay
#

the notification shouldnt be a problem when i get the 3 entities sorted out

fast kettle
#

It's just going to take you some serious time messing around with jinja.

inner mesa
#

it's a pain in the neck

#
{% set sensors = ['sensor.er_motion_sensor_battery', 'sensor.cr_left_window_battery', 'sensor.mbath_large_window_battery'] %}
{% set map = {sensors[0]:states(sensors[0]), sensors[1]:states(sensors[1]), sensors[2]:states(sensors[2])} %}
{{ (map.items()|sort(attribute='1')|map(attribute='0')|list)[0:3] }}
#

something like that would work. the first bit could use integration_entities() to form the list

#

But you have to built the dict. You could also do it with a for loop and namespace with a list, but that's more than I care to do right now 🙂

neat prairie
#

expand a group to build the dict?

icy jay
icy jay
inner mesa
#

better:

#
{% set sensors = ['sensor.er_motion_sensor_battery', 'sensor.cr_left_window_battery', 'sensor.mbath_large_window_battery'] %}
{% set ns = namespace(map={}) %}
{% for s in sensors %}
  {% set ns.map = dict(ns.map, **{s: states(s)}) %}
{% endfor %}
{{ (ns.map.items()|sort(attribute='1')|map(attribute='0')|list)[0:3] }}
#

dynamically generate the map

#

so...

#
{% set sensors = integration_entities('whatever') %}
{% set ns = namespace(map={}) %}
{% for s in sensors %}
  {% set ns.map = dict(ns.map, **{s: states(s)}) %}
{% endfor %}
{{ (ns.map.items()|sort(attribute='1')|map(attribute='0')|list)[0:3] }}
#

boom

icy jay
#

Damn that actually works

inner mesa
#

ye of little faith

icy jay
#

Thank you so much!

Soooo this spits out the „cheapest“ 3 sensors, so i only need to get them with value into a notification

But maaaaybe i can find that out by myself😅

inner mesa
#

you're on your own 🙂

#

I've done my good deed for the day

neat prairie
#

template sensor. then notify it's value. Or something like that 😉

inner mesa
#

grandma is going have to get across the street herself now

icy jay
#

First time somebody named me grandma:(

neat prairie
#
  - sensor:
    - name: "lowest3temperaturesensors"
      state: >
       {% set sensors = expand('group.temp_sensors')| sort( attribute='state') %}
       {% for s in sensors[0:3] %}
       {{ s.name }},
       {% endfor %}```
#

(yes, I'm just playing)

#

alternatively:

  - sensor:
    - name: "lowest3temperaturesensors"
      state: >
       {{ (expand('group.temp_sensors')| sort( attribute='state'))[0:3]|map(attribute='name')|join(",") }}```
#

Just needs a group with the sensors which you're interested in.

inner mesa
#

The problem with that is that states are strings, and it's generally frowned on to compare them as integers. It's an issue in my solution, too, but can be easily fixed with
{% set ns.map = dict(ns.map, **{s: states(s)|float}) %}

neat prairie
#

ahhh

inner mesa
#

I do wish that we had a way to transform a value in a filter before it's used in a comparison, but we (mostly petro) have been noodling on that for a long time without a good solution

neat prairie
#

That explains why you did it that way 🙂

inner mesa
#

well, I had a bug as well, and I didn't think of just keeping the state object 🙂

#

it's not a bad idea, and it will sometimes work and sometimes not

#

the problem is that you have to use map() to apply a transform, and you lose information when you do that

steel swift
#

Hello. I am trying to make a sensor. As my heating cables are on relay only I had an Idea to make a sensor measuring the time the relay is in on state. And from there do a calculation of kWh. I from there want to add this sensor in energy dashboard. Tried some things without any luck, but this one works though: `` {% set voltage = states('sensor.voltage_phase2_hjemme') | float %}
{% set resistance = 105 %}
{% set power = (voltage * voltage) / resistance %}
{{ (power / 1000) | round(2) }} ```

inner mesa
#

are you still looking for something?

icy jay
#

Im still stuck with the notification, im just not into templates.

Ive got the sensor now thats giving me
[‘sensor.x_diesel‘, ‘sensor.x_diesel‘, ‘sensor.x_diesel‘]

And i want to get a output like:

  • friendlyname1 value1
  • friendlyname2 value2
  • friendlyname3 value3
floral shuttle
marble jackal
#

You need to use jinja comments in a .jinja file

#

{# this is a comment #}

#
{#
  multi
  line
  comment
#}
floral shuttle
#

right... still, even without that the jinja editor is confused... guess my trusted BBedit does not have a .jinja translator

#

which is really nasty

#

and the templates arent colored at all in my vscode addon...which all of a sudden is using some silly modernish theme. aarrgghh

sacred sparrow
#

is the logbook changes dependant on device_class or type (binary sensor vs sensor)? For a binary sensor I get logbook for that entity saying:
Turned on triggered by state of NAS Upload throughput changed to 7.363

#

only history

silent vector
#

Is there an easy way to use a template to list all the attributes and their values? Without having to type each attribute key out in an automation variables section?

marble jackal
mighty ledge
silent vector
#

I mean something like this which would list out all attributes of the sensors for the automation to consume foo['attributeone']
foo: "{{ state_attr('sensor','attributes') }}"

mighty ledge
#

no, you need to use the state object, you can't use the state methods

silent vector
#

Awesome figured it out.

#

How would I access this?

dict_items([('master_bedroom_initial_temperature', []), ('master_bedroom_initial_humidity', []), ('master_bedroom_automation_action_time', []), ('friendly_name', 'HVAC Automation Memory')])

As in reference master_bedroom_initial_temperature for example.

marble jackal
#

what is your goal here?

silent vector
#

I'm going to store data in a template trigger sensor using the event stuff we talked about awhile ago. Then in an automation reference data for conditions by looking back at what changed during x time.

#

I'm looking for a clean way to reference attributes without having to define each one in the automation variables section. Or reference each one each time I want to use it.

#

The easiest is define each one in the variables section but I was wondering if there was a cleaner way.

marble jackal
#

and it looks like you are putting the code of a template switch in a card

hidden yacht
#

... cant even delete my message now :\

marble jackal
#

that doesn't belong there, it should be in configuration.yaml not in the dashboard code

#

I deleted it for you 🙂

hidden yacht
#

aye cause everything in examples is written in context of editing config.yaml and i cant convert it

sacred sparrow
#
    - name: "NAS Status"
      icon: phu:nas-v2
      device_class: enum
      state: >
        {% if states('sensor.nas_smartplug_watts')|float(0) < 1 %} 
          Off  
        {% elif ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_force_off', 'last_triggered')) |int(0) ) < 300 and ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_force_off', 'last_triggered')) |int(0) ) > 0
        and not ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_on', 'last_triggered')) |int(0) ) < 300 and ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_on', 'last_triggered')) |int(0) ) > 0 %}  
          Powering Down
        {% elif is_state('sensor.nas_volume_1_status', 'normal') or is_state('sensor.nas_volume_2_status', 'normal') or states('sensor.nas_upload_throughput')|float(0) > 0.1 or states('sensor.nas_download_throughput')|float(0) > 0.1 %}
          On
        {% elif states('sensor.nas_smartplug_watts')|float(0) > 1 and ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_on', 'last_triggered')) |int(0) ) < 300 and ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_on', 'last_triggered')) |int(0) ) > 0 %}  
          Powering Up
        {% endif %}```
marble jackal
sacred sparrow
#

oh sorry I thought you meant the entities that trigger it

marble jackal
#

try removing the device_class

sacred sparrow
#

the device class is new - I thought it would change it but still doesnt show without it

marble jackal
#

device classes are also for sensors with numeric states

#

did you exclude it from recorder (or forgot to include it)?

marble jackal
#

you can't template the entire attributes section though, so you need to assign a key (like source_sensor_attributes:) to it

sacred sparrow
mighty ledge
#

Just make an automation that logs it

#

and be done with it

sacred sparrow
#

I can see it in the logbook! but not in the entities log book (the pictures I posted before)

mighty ledge
#

it won't show in entities logbook unless it has a unique_id

marble jackal
#

ah!

#

🙂

mighty ledge
#

at least I'm pretty sure that's the case

sacred sparrow
#

and binary_sensors have a unique id?

marble jackal
#

if you add it

mighty ledge
#

depends on where it comes from

marble jackal
#

it's a template binary sensor right

sacred sparrow
#

sure is

marble jackal
#

(I assumed)

mighty ledge
#

do you have a unique_id in the configuration?

sacred sparrow
#
    - name: "NAS Data Transfer"
      icon: mdi:swap-horizontal
      delay_off:
        minutes: 1
      state: "{{ states('sensor.nas_upload_throughput')|int(0) + states('sensor.nas_download_throughput')|int(0) >= 15 }}"```
mighty ledge
#

well then that's not the case

sacred sparrow
mighty ledge
#

you don't

marble jackal
#

with your eyes 🙂

#
- binary_sensor:
    - name: "NAS Data Transfer"
      unique_id: this_is_a_unique_id_for_this_sensor
      icon: mdi:swap-horizontal
      delay_off:
        minutes: 1
      state: "{{ states('sensor.nas_upload_throughput')|int(0) + states('sensor.nas_download_throughput')|int(0) >= 15 }}"
#

this version has a unique_id

sacred sparrow
#

ah I was just showing you the binary that has logbook

#

I'll add it to the normal sensor

silent vector
mighty ledge
#

I don't think that will help based on what I've seen

mighty ledge
marble jackal
#

oh, sorry Dan 🙂

mighty ledge
#

You can see in the template editor

#

well well well, they are apparently

#

so that will work

#

they fixed that bug

silent vector
#

I was going to say hm then why does it look like a dictionary?? Lol

mighty ledge
#

don't get me wrong, it's not a dict

sacred sparrow
mighty ledge
#

it's just that the resolver handles the type now

silent vector
#

I put it in a variables section and ran the automation and it's not returning the variable at all under changed variables

mighty ledge
#

Just keep in mind that enums aren't translated in attributes, so it may be a string result.

#

i.e. if you're doing this with a light, it won't properly resolve a dictionary

#

because lights have 3 enums typically in attributes

silent vector
#

Interesting. Yeah this is just strings

#

But all I have is

context:
  id: 01H2T7JW35J4YKWSFRYP7608Q7
  parent_id: 01H2T7JW34DC6HKMQW9A2NBW2B
  user_id: null
#

When there should be the variable?

mighty ledge
#

changed variables only show up on when you aren't on a node

#

so make sure you're on the trigger

#

well, they do show up on variable nodes

#

but I'm assuming you put the variable in the main variables node/field

silent vector
#

That worked

hvac_automation_memory: >- dict_items([('master_bedroom_initial_temperature', []), ('master_bedroom_initial_humidity', []), ('hvac_turned_on_time', ''),
  ('hvac_turned_off_time', ''), ('master_bedroom_automation_action_time', []),
  ('friendly_name', 'HVAC Automation Memory')])
marble jackal
#

that looks like a string

mighty ledge
#

it is if the output is .items()

#

because thats the __str__ for the .items() object

silent vector
#

Should I use .items() for this or no?

mighty ledge
#

probably not because attributes resolves properly in the template editor as long as you don't have an attribute that's a complex object

#

it doesn't look like you do for whatever that is

silent vector
#

The only thing complex could be the timestamps. {{ now() | as_timestamp }} for the time attributes.

mighty ledge
#

datetimes will mess it up

silent vector
#

What should I do with that?

mighty ledge
#

you can test this crap yourself btw

marble jackal
#

probably not resource friendly, but I guess this should work {{ states.sensor.foo.attributes | to_json | from_json }} 😅

mighty ledge
#

that won't work for complex objects

#

because you can't serialize complex object if they don't have a serialize method

silent vector
# mighty ledge you can test this crap yourself btw

On the road to testing. Have been playing with getting the template trigger right for storing "memory" now I'm finally starting on the automation where I need these stored values. I went this route vs multiple input_text sensors

mighty ledge
silent vector
#

Worked

{{ { 'y': now() | as_timestamp } }}
marble jackal
#

a timestamp is just a number, not very complex 🙂

mighty ledge
#

I wouldn't use a as_timestamp personally

#

because it doesn't hold UTC

silent vector
#

So use string?

#

To store everything

mighty ledge
#

probably

#

only use as_timestamp if you understand the ramifications behind using it 😉

silent vector
#

The most this may be needed for is less than 12 hours

#

Then it would clear

#

So it's not as if this will be referencing something more than 24 hours ago.

#

No idea what the ramifications are. Is there googling I should do?

mighty ledge
#

Nope, just comes with experience

silent vector
#

Can you share some? Lol

mighty ledge
#

I mean, it's learn by doing

#

You have to hit the issues to see what they are to work past them

#

in HA, I only use datetimes as strings

#

in my own apps I use timestamps because I control the whole backend

silent vector
#

What apps do you write?

mighty ledge
#

stuff for work

#

applications for our production line

silent vector
#

Interesting. What do you do? Top secret stuff? Lol

mighty ledge
#

Nothing top secret

#

I manage production line equipment & software for making contact lenses

#

mainly focused on metrology. I.e. Making sure the lenses that we made are what we expect them to be

#

however, I'm a jack of all trades, so they have me make whatever they need software wise

silent vector
#

That's really cool stuff. I'm becoming the jack of all trades in Ansible lol for my team thanks to you guys over the past few years helping me along with Jinja.

mighty ledge
#

If you learn some python, you'll get even better

#

knowing python makes jinja a breeze

silent vector
#

That's what I'm beginning to realize and I'm starting to learn some python.

icy jay
#

Hey

Im still stuck with the notification, im just not into templates.

Ive got the sensor/ now thats giving me
[‘sensor.x_diesel‘, ‘sensor.x_diesel‘, ‘sensor.x_diesel‘]

And i want to get a output like:

  • friendlyname1 value1
  • friendlyname2 value2
  • friendlyname3 value3

Can somebody help pls?

floral shuttle
#

could this be further condensed:```
{% from 'media_players.jinja' import media_players_active %}
{% set rooms = media_players_active().split(',')
if media_players_active() != '' else [] %}
{% set count = rooms|count %}
{% set ns = namespace(speakers = '') %}
{% for i in range(count) %}
{% set d = ',' if ns.speakers|length > 0 else '' %}
{% if states('media_player.' ~ rooms[i]) not in ['unavailable','unknown'] %}
{% set ns.speakers = ns.speakers ~ d ~ 'media_player.' ~ rooms[i] %}
{% endif %}
{% endfor %}

        {% if count == 0 %} No active radio
        {% else %}
        {{ns.speakers}}
        {% endif %}```
#

if not 0 it takes the entity_id, and adds media_player in front of them, and then returns

#

Ive always found this a but frsgile: {% set ns.speakers = ns.speakers ~ d ~ 'media_player.' ~ rooms[i] %} so maybe it would be time to recheck that

mighty ledge
#

well it can because you're using an iterator which isn't needed.

#

you almost never need an iterator in jinja

floral shuttle
#

btw this it the custm_temnplate that is the base for it: {%- macro media_players_active() -%} {{- expand('group.media_players_active') |selectattr('state','eq','on') |map(attribute='object_id')|list|join(',') -}} {%- endmacro -%}

mighty ledge
#

for room in rooms

floral shuttle
#

just so you know why: i list the object_id's there because they are booleans I toggle

mighty ledge
#
            {% from 'media_players.jinja' import media_players_active %}
            {% set rooms = media_players_active().split(',') if media_players_active() else [] %}
            {% set ns = namespace(speakers = '') %}
            {% for room in rooms %}
              {% set d = ',' if ns.speakers|length > 0 else '' %}
              {% if states('media_player.' ~ room) not in ['unavailable','unknown'] %}
              {% set ns.speakers = ns.speakers ~ d ~ 'media_player.' ~ room %}
              {% endif %}
            {% endfor %}

            {% if rooms %} No active radio
            {% else %}
            {{ns.speakers}}
            {% endif %}
#

even further...

floral shuttle
#

hmm, the check on rooms fails...

mighty ledge
#
            {% from 'media_players.jinja' import media_players_active %}
            {% set rooms = media_players_active().split(',') if not media_players_active() else [] %}
            {% set ns = namespace(speakers = []) %}
            {% for room in rooms if ('media_player.' ~ room) | has_value %}
              {% set ns.speakers = ns.speakers + ['media_player.' ~ room] %}
            {% endfor %}
            {{ ns.speakers | join(',') if ns.speakers  else 'No active radio' }}
floral shuttle
#

same check fails... it returns 0,

mighty ledge
#

try again

floral shuttle
mighty ledge
#

unless media_players_active() doesn't return what it's supposed to

#
{% set rooms = media_players_active().split(',') | reject('eq', '') | list %}
#

use that instead

#

and if you want it to be optimal, that should just go in your for loop.

#
            {% from 'media_players.jinja' import media_players_active %}
            {% set ns = namespace(speakers = []) %}
            {% for room in media_players_active().split(',') | reject('eq', '') if ('media_player.' ~ room) | has_value %}
              {% set ns.speakers = ns.speakers + ['media_player.' ~ room] %}
            {% endfor %}
            {{ ns.speakers | join(',') if ns.speakers  else 'No active radio' }}
floral shuttle
#

yes, that works!

#

Inused this: {% set rooms = media_players_active().split(',') if media_players_active() != '' else [] %} on advice bt Taras in the community post, to prevent that splitting an empty list still counts 1

mighty ledge
#

right, but you can just reject the emtpy items in the generator

floral shuttle
#

nice, thx. this too:{% set ns.speakers = ns.speakers + ['media_player.' ~ room] %}

#

sweet and simple.

#

but here {% from 'media_players.jinja' import media_players_active %} {% set players = media_players_active().split(',') if media_players_active() != '' else [] %} {% set count = players|count %} {{count}} cant I use the reject?

#

this does wodk: {% from 'media_players.jinja' import media_players_active %} {% set players = media_players_active().split(',') %} {% set count = players|count if players != [''] else 0 %} {{count}}

mighty ledge
#

Why do you need count?