#templates-archived

1 messages · Page 63 of 1

inner mesa
#

And pull out the entity_ids

summer arch
#

It gives me a state of []

#

I have no lights on atm and am looking to get 0

inner mesa
#

So add |length

#

See the links in the channel topic

summer arch
#

thank you 🙂

plain magnetBOT
#

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

fading spade
summer arch
#

Is there a way to check for the entity "type" ie I want to ignore all lighting groups as I only want to see the individual lights not the group controls

#

doesn't look like its an attribute

{
    'min_color_temp_kelvin': 2000, 
    'max_color_temp_kelvin': 6535, 
    'min_mireds': 153, 
    'max_mireds': 500, 
    'supported_color_modes': [<ColorMode.BRIGHTNESS: 'brightness'>, <ColorMode.COLOR_TEMP: 'color_temp'>], 
    'icon': 'mdi:lightbulb-group', 
    'friendly_name': 'Living Room Lights', 
    'supported_features': <LightEntityFeature: 0>
} 
#

Another solution would be to check if the name contains "Group" (I would change the light to reflect this). I can't see in the pinned link a contains

summer arch
marble jackal
#

With selectattr() you are using tests

summer arch
#

{{ states.light|rejectattr('name', 'contains', 'Group')|selectattr('state', 'equalto', 'on')|list|length }}

#

This seems to work

#

I would still like to know if I can test for the "type" as the helper ui calls it. That way its name agnostic and I just ignore all light groups

marble jackal
#

Are these light groups created in HA?

summer arch
#

Yes, from the HA helper tab

marble jackal
#

Check the 5th pinned message

summer arch
#

excelent, thanks. Can you give me a quick tldr on why rejectattr('attributes.entity_id', 'defined') rejects groups?

minor dune
#

Happy new year everyone!

i'm trying to create a condition for an automation that checks if 2 different entity value's are the same. (automatic cat feeding, check the required amount of food portions against the physically dispensed ones)

#

my guess would be that that is going to require a Template sensor, i have never done this before and using google really doesnt make it any more clear for me

fading spade
marble jackal
minor dune
#

most likely i do something wrong tho

#

ValueError: Template error: int got invalid input 'unknown' when rendering template '{{ states('<counter.bobo_benodigde_portie>') | int == states('<sensor.voerautomaat_bobo_portions_per_day>' | int) }}' but no default was specified

#

{{ states('<counter.bobo_benodigde_portie>') | int == states('<sensor.voerautomaat_bobo_portions_per_day>' | int) }}

summer arch
#

{{ states('counter.bobo_benodigde_portie') | int == states('sensor.voerautomaat_bobo_portions_per_day' | int) }}

minor dune
summer arch
#

Sorry I left a > in

minor dune
summer arch
#

I edited it

minor dune
#

oh lol

minor dune
# summer arch I edited it

ValueError: Template error: int got invalid input 'unknown' when rendering template '{{ states('counter.bobo_benodigde_portie') | int == states('sensor.voerautomaat_bobo_portions_per_day' | int) }}' but no default was specified still errors out

summer arch
#

This worked for me
{{ states('sensor.air_purifier_dust_level') | int == (states('sensor.air_purifier_fine_dust_level') | int) }}

#

I just used some sensors I had on hand

minor dune
#

hmm

summer arch
#

replace them with yours

minor dune
#

she works

minor dune
#

i need the output to be true if the value of the second entity is higher or equal to the first entity

#

😅

marble jackal
#

Use >= instead of ==

summer arch
# marble jackal Check the 5th pinned message

What about making a group with all lights that are in an area or all lights that exist?

Ie I add a new light to the living room and the living room group just inherits it and the houshold light group also inherits it? or is this sort of templating not valid in groups?

marble jackal
summer arch
#

Ok, I saw a forum post you can use all when calling the on and off service.

Can you target an area too?

minor dune
#

this helped me to go from 4 pages of node red to half a page with even more functionality 🙂 (For the automatic cat food dispensing)

marble jackal
exotic valve
#

For some reason, this template I got from this channel shows me 2 lights on when only 1 is on:

{{ states.light | selectattr('state', 'eq', 'on') | rejectattr('attributes.entity_id', 'defined') | map(attribute='entity_id') | list | count }}

This is still the correct way to filter out zigbee2mqtt groups, right?

marble jackal
#

No, Zigbee2MQTT groups don't have that entity_id attribute, so you won't be able to filter groups out like this

#

There is no way to determine if something is a Zigbee2MQTT group from the attributes of such a group

exotic valve
#

Ah okay, so I am supposed to make groups in a different way? Like is there a better option?

#

I think I found it, a group in the helpers menu. I'll try that.

Edit: that worked 🙂

marble jackal
#

That works, but you'll lose a lot of benefits Zigbee groups have

exotic valve
#

Dang it, like what? Sorry I'm super new to HA. I just wanted to have a counter for the lights so that I can always quickly see if any lights are on.

inner mesa
#

Like sending a single command to turn a bunch of lights on at once. I put 'group' in the name of my zigbee groups to make them easier to identify and filter on

halcyon owl
#

Can anyone help format a template so that the text stays on one line? I'm basically using this to send a notification to an led display but the android.text part sometimes overlaps onto a second line and then does not get display properly on the LED screen. So i am looking for whatever is extracted in the android.text part to kept on one line. Thjs is the current template - "text": "{{ state_attr('sensor.lenovo_tb_8704f_last_notification', 'android.title') }} , {{ state_attr('sensor.lenovo_tb_8704f_last_notification', 'android.text')

#

Example

{
"text": "Plymouth Argyle - Watford , 20' Goal: [1] - 1
Finn Azaz ",
"repeat": 2
}

#

The above is example of whats happening. The goalscorer is Finn Azaz and thats the part that doesnt get send to the led display properly as i take its becaise its on the next line instead of at the end of the line above it.

lyric comet
halcyon owl
#

to answer my own question, this did the job - "text": "{{ state_attr('sensor.lenovo_tb_8704f_last_notification', 'android.title') }}, {{ state_attr('sensor.lenovo_tb_8704f_last_notification', 'android.text') | replace('\n', ' ') }} "

summer arch
sacred flax
#

Th preview for my template shows unavailable . Does that mean I messed up?

#

Nvm. I had a bunch of mistakes

queen viper
#

Hello! I am actually not sure if this is better suited in "templates" or "automation"; but let me start here.
Our dog has a GPS Collar (Tractive). It works quite nice.

But what I would like to do is to create a sensor of "how long was doggos latest walk?"

The problem is; I want to explicitly look at "Time between leaving "home" to returning to "home", REGARDLESS of any zones doggo passes in the interval (and this is what I can not figure out. The reason for this requireiemtn is that doggo will on 5 walks out of 7 pass at least one other zone.

I also want the solution to be "restart proof", so just starting a timer does not fly either.

How should I tackle this? I have a feeling I am missing something very obvious?

marble jackal
#

what do you want the sensor to display while the dog is on it's walk?

#

the duration of the last walk before that, or that he's currently outside?

queen viper
marble jackal
#

You can create a trigger based template sensor which has two triggers:

  • device tracker leaving home
  • device tracker arriving home

When the device tracker leaves home, you update an attribute which stores the datetime when that trigger occurs. The state of the sensor will remain as it is (you can uste this.state for that)
When the device tracker arrives home again, you update the state of the template sensor, by calculating the difference between the time of that trigger, and the time stored in the attribute. That you can use to generate the sentence like you posted above

queen viper
#

@marble jackal Hm.. Yeah, that tracks. And if i want a template sensor with triggers. That still is a configuration.yaml thing-only, right? Because the UI template helper is just for triggerless?

marble jackal
#

Yes, the GUI doesn't support trigger based template sensors (yet)

queen viper
#

just need to filer the "arriving home" event to ignore changes from "unknown".. I guess?

marble jackal
#

does that happen?

#

I would use a state trigger. In that case you can use not_from: unknown

queen viper
#

Just for a backstory. We have a nice elderly couple that walks him during most days. HOWEVER, I feel fairly certain that they are not (out of personal pride) not really honest on how long he's been out some days. And if we know he's just gotten a quickie during lunch we can try to plan for getting home as soon as possible after lunch.

As for the "unknown/unavailable", @marble jackal , I am once again thinging on what happens during restarts of HA.

marble jackal
#

well, you can use not_from for that

queen viper
#

I have NO issue with doggo just getting a "five minute leg lift walk". But i'd like to know to be able to give hme a more proper evening walk 🙂

#

Now i look at the history of the tracker, which tells the story. But I'd just like to automate this to a push notice.. so to say.

marble jackal
#
template:
  - trigger:
      - platform: state
        entity_id: device_tracker.doggo
        from: home
        not_to: [ 'unavailable', 'unknown']
        id: walk_start
      - platform: state
        entity_id: device_tracker.doggo
        to: home
        not_from: [ 'unavailable', 'unknown']
        id: walk_end
      sensor:
        # sensor config here
queen viper
#

@marble jackal I think you have provided the "Least insane" way to do this. I thank you.

#

(and another possible reason for "unknown/unavailable" is of course "You forgot to charge the tracker, stoopid" 😉

marble jackal
#

If you need help with the sensor config, let me know 🙂

plain magnetBOT
#

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

queen viper
#

@marble jackal I'll give it a go based on the EV-template-thing i found and didnt think before i pasted in the channel 😉

marble jackal
#

This looks like a good start

queen viper
#

@marble jackal We'll see. I'm using the person entity and not the device tracker.. but that should be the same. Let's just wait for the real walk to happen as to not mess up my history with overriding in dev tools 🙂

night sandal
#

Is there an "easy" way to support templates in custom cards or do we have to go the button-card way and implement our custom templating system as well?

marble jackal
queen viper
#

@marble jackal Oooh.. Doogo is off and the sensor is increasing. Let us hope that he passes into an adjacant zone. 🙂

marble jackal
#

Can you share the code, curious to see what you came up with

queen viper
marble jackal
#

you could let it output the full sentence instead of only the number of seconds

queen viper
#

@marble jackal Yeah, fur sure. But, hey a quick test never hurt someone. Besides, I will probably end up formatting this sensor data differently in different notifications. So "raw value" should be fine for the sensor itself.

marble jackal
#

👍

#

it will never reach the else part of the if statement in the state value, it only updates when it's triggered, so there is no way it will get to that

#

never mind, you added a time patter trigger

#

you should recalculate it on the else part.

#

scrap all that, looks good!

queen viper
#

@marble jackal Thanks. Again, i yanked that part pretty much verbatim from someone who had done a EV-charge time sensor. 🙂

marble jackal
#

small improvement

        start: >
          {% if trigger.id == "walk_start" %}
            {{ now().timestamp() }}
          {% elif trigger.id == "trigger_time_pattern" and this.attributes.start | is_number %}
            {{ this.attributes.start }}
          {% else %}
            Idle
          {% endif %}
queen viper
#

@marble jackal What Am i not seeing as to different operation?

#

@marble jackal AAAh!

#

Human readable date attribute

marble jackal
#

You were returning Idle twice, once in an elif, once in the else

#

I removed the need for the elif

queen viper
#

Funny. Really funny. I was just now thinking "Right, next to increase readability".

Oh.. You are right about that as well... Thank you.

willow wing
#

is there a way to add in the new sensor template format a friendly name (Name without _)?

  - name: wohnzimmer_comet_dect_current_temperature
    unique_id: "Wohnzimmer Comet DECT Current Temperature"
    unit_of_measurement: "°C"
    device_class: temperature
    state: "{{ state_attr('climate.wohnzimmer_comet_dect', 'current_temperature' ) }}"```
marble jackal
#

name will be the friendly name, you can use spaces and capital letter there

#

that will be slugified to the entity_id

willow wing
#

i have tried it, he makes _, maybe i delete it before?

marble jackal
#

so:
name: Wohnzimmer Comet Dect Current Temperature will result in sensor.wohnzimmer_comet_dect_current_temperature

willow wing
#

and the freindly name also have the _?

marble jackal
#

no, if you do this, the friendly_name will not have _

  #Comet DECT Current Temperature
  - name: "Wohnzimmer Comet DECT Current Temperature"
    unique_id: "Wohnzimmer Comet DECT Current Temperature"
    unit_of_measurement: "°C"
    device_class: temperature
    state: "{{ state_attr('climate.wohnzimmer_comet_dect', 'current_temperature' ) }}"
willow wing
#

ah unique no need _ too, thanks i will try

marble jackal
#

unique_id is only for storing it in the database, it has no effect on the name or entity_id

#

unless you don't provide a name

willow wing
#

so it would be better too give the unique a name with underscore or what you personally prefer? (so i have not problems when i forget a name?)

marble jackal
#

That post refers to the behavious that the entity_id is now created based on the name, they want to be able to set the entity_id and name separately. They are now linked to each other

#

it doesn't have anything to do with underscores in the friendly name

willow wing
#

ah ok, what can be the problem than?

marble jackal
#

What is your current code?

willow wing
#
   - name: "Küche Comet DECT Current Temperature"
    unique_id: "Küche Comet DECT Current Temperature"
    unit_of_measurement: "°C"
    device_class: temperature
    state: "{{ state_attr('climate.kuche_comet_dect', 'current_temperature' ) }}```
marble jackal
#

okay, did you reload template entities after making this change?

willow wing
#

i have delte the existing sensor and let it create with them new

#

one moment, now its correct

#

after 3-5 minutes

marble jackal
#

then you most probably have a sensor.kuche_comet_dect_current_temperature_2 now

#

or maybe not (based on your last comment)

willow wing
#

so i change all names now, thank you thefes for help

floral shuttle
#
     {% from 'easy_time.jinja' import big_relative_time %}
          {% set year = now().year +1 %}
          {% set new_year = year~'-01-01 00:00:00' %}
          {{big_relative_time(new_year,language='nl')}}``` stopped counting the days?
#

seem to remember it did work ok before... (only thing of importance was updating to 2024.1.0b04...)

#

time since new year does work: {% from 'easy_time.jinja' import big_time %} {{big_time(now().replace(month=1,day=1,hour=0,minute=0,second=0,microsecond=0), language='nl')}}

marble jackal
#

hmm, strange

#

I'm looking in the code, but all macros are using other macros, and before I figured this out, petro probably fixed it himself

#

at least relative time plus works 🙂

willow wing
# marble jackal or maybe not (based on your last comment)

hmm, i tried these template and the friendly_name is again with underscore. something wrong? (HA reboot i do too)

    unique_id: "Feiertag Beginn"
    state: >
      {{ as_timestamp(state_attr('sensor.ics_2', 'start'), default=0) | timestamp_custom('%d.%m.%Y') }}
marble jackal
#

can you show this entity looks in developer tools > states

#

post a screenshot using imgur or similar

plain magnetBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

willow wing
marble jackal
#

I don't know why it does that, that's not normal behavior

mighty ledge
#

I'll have to look at the code, they changed something

#

No, nothign changed, just a bug for dates in the future

nimble palm
#

Hi guys.. is there a way to convert decimal to hex without using format?

mighty ledge
#

why don't you want to use format?

nimble palm
#

so I tried it on the template editor where it is working but it ain't working with the rest integration

mighty ledge
#

can't help without any context.

nimble palm
#

so my phillips wiz bulb gives me rgb values in an array.. I convert it to hex and format it because I want to pass it to an api

{{ '%02x%02x%02x' | format(state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[0], state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[1], state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[2]) }}

#

working with template editor

#

`sensor:

  • platform: rest
    name: Bulb Color
    resource_template: https://www.thecolorapi.com/id?hex={{ '%02x%02x%02x' | format(state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[0], state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[1], state_attr('light.wiz_rgbw_tunable_c0dd69', 'rgb_color')[2]) }}

    value_template: "{{ state_attr('light.wiz_rgbw_tunable_c0dd69', 'effect') or value_json.name.value }}"

    value_template: "{{ value_json.name.value }}"`
#

I add it as part of this and it throws me an error - %x format: an integer is required, not LoggingUndefined

#

I just started this templating so please bear with me if this is a dumb error

floral shuttle
mighty ledge
#

You most likely need the #

mighty ledge
nimble palm
#

yes

#

i hardcoded the value to check

#

it works

floral shuttle
#

Top ‘over 1 week’ etc uses that same template

dry narwhal
#

Hello @mighty ledge ,
I am sure you remember working your magic on my apexcharts-card filter template 🙂
I have run into a problem and cannot find the mistake.

mighty ledge
dry narwhal
#

For some reason the exclude part only uses the first exclude word and ignores the others.

#
    {% for i in range(1, 6) %}
      {% set post = '' if i == 1 else '_' ~ i %}
      {% if states('input_text.apexcharts_entity_exclude' ~ post) %}
        {% set excluded = states('input_text.apexcharts_entity_exclude') | replace(', ', '|') %}
        {% set ns.list = ns.list 
          | selectattr('attributes.friendly_name', 'defined')
          | rejectattr('attributes.friendly_name', 'search', excluded, ignorecase=True)
          | reverse | list %}
      {% endif %}
    {% endfor %}
nimble palm
mighty ledge
#

rest entities

#

you can force a poll by using homeassistant.update_entity

dry narwhal
#

Found it.

#

{% set excluded = states('input_text.apexcharts_entity_exclude') | replace(', ', '|') %} was missing the ~ post

#

Thanks for listening 🙂

jolly crest
#

Anyone have a template that outputs the last sunday of the month?

floral shuttle
# mighty ledge No, nothign changed, just a bug for dates in the future

could it be the leap year causing an issue? just checked the 'old' template and that is still correct {%- set values = [phrase('week',60*60*24*7),phrase('day',60*60*24,7),phrase('hour',60*60,24), phrase('min',60),phrase('sec',1,60)]|select('!=','')|list %} {{values[:-1]|join(', ') ~ ' and ' ~ values[-1] if values|length > 1 else values|first}}

mighty ledge
#

I doubt it, it's probably just some bug I overlooked

floral shuttle
#

do you need an issue for it?

#

still, dont get why 1 week ago this worked just fine and now behaves like this

mighty ledge
#

That's time, it's a pain in the ass

lucid thicket
# jolly crest Anyone have a template that outputs the last sunday of the month?
{% set some_datetime = now() %}
{% set last_day_of_month = today_at().replace(year=some_datetime.year, month=(some_datetime.month + 1) % 12, day=1) + timedelta(days=-1) %}
{% set last_sunday_of_month = last_day_of_month - timedelta(days=(last_day_of_month.weekday() + 1 ) % 7) %}
{{ last_sunday_of_month }}

Leaving this here to start ideas flowing, but as noted by @marble jackal this doesn’t work correctly.

craggy iron
#

Guys - I've got a whole bunch of device_trackers for fuel stations, with their longtitude and latitude. Perhaps Im thick, probably, but is there not an easy way to dynamically find the closest fuel station to a given entity? In this case, another device tracker, a phone. The idea is it will ping the phone the cloest fuel station when phone bluetooths to the car. The fuel stations have dynamic names i.e. asda_postcode so it would need to be asda*, esso* etc. (device_tracker.esso*).

#

I've messed around, battled with some chatGPT answers, but it seems way to difficult.

marble jackal
lucid thicket
#

Crap you’re right

inner mesa
#

dates and times are the devil's handiwork

lucid thicket
#

I’ll have to chew on that one some more when I get time. Happy if anyone else wants to take a crack.

marble jackal
#
{% set some_date = now().date() %}
{% set last_day_of_month = (some_date.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1) %}
{{ last_day_of_month - timedelta(days=last_day_of_month.isoweekday() % 7) }}
marble jackal
#

@lucid thicket this will work

lucid thicket
steep raven
#

i m using this template {{ state_attr("switch.auto_meter", "current_consumption" ) }} but i need to have the , placed one number to the left how can i do this?

#

its now reporting 73,8kW but it needs to be 7,38kW

marsh cairn
steep raven
#

yes thats exactly what i needed

#

ty

floral shuttle
mighty ledge
#

Yes, not surprised

#

there's most likely an issue with the transition between years

floral shuttle
#

yes, and my next alarm also had that. since no alarm was set it defaulted to beginning epoch, which is January first......

#

using .day..... {{(now()+timedelta(days=1)).day == (states('sensor.next_alarm_timestamp')|as_datetime()).day}}

#

flukes beause of {{(states('sensor.next_alarm_timestamp')|as_datetime())}} being 1970-01-01 00:00:00+00:00

#

fixing for now with {% set next = states('sensor.next_alarm_timestamp')|as_datetime() %} {{(now()+timedelta(days=1)).day == next.day and next.year != 1970}}

jolly crest
craggy iron
#

The Petrol Stations are just map objects, not zones unfortunately. The list updates dynamically via the Fuel Prices add-in in HACS.

mighty ledge
#

if they have lat/lon, just use the distance function

mighty ledge
craggy iron
#

I have about 50 to choose from, and I want it to pick the "closest"

#

Sorry, HA is new to me, just in the midst of learning all the great features.

marble jackal
#

There is also a closest() function

mighty ledge
#

closest is always the closest to home, so if you want it closest to you, you'd need to use distance.

lucid thicket
# craggy iron I have about 50 to choose from, and I want it to pick the "closest"

I would break up your problem into pieces. First step is to get a list of all your stations. Focus on that first. Once you can get those entity_id’s in a list, you can then figure out how to loop through that list calculating distance to each one. During the loop you can save the distance and entity_id associated with the closest one.

Don’t try to ask for the whole solution in one bite.

craggy iron
#

Thanks - that is helpful. Let me start working on the first part, getting a list of all stations.

lusty ermine
#

petro, is there a way to have easy time display the worded date from a date time("2023-11-02 22:00:00") as "November 2nd 10PM"? or does it have to be built manually? like using custom time where you can say which parts of the date time to display.

plain forge
lusty ermine
#

ok so it would be: as_datetime("2023-11-02 22:00:00").strftime("%B %-d, %-I%p")

November 2, 10PM

celest tinsel
#

Need some help conceptualizing a solution. I have a dozen temperature vakue entities and corresponding expected value entities. I want to generate an alert whenever the difference between any tuple > 2. I also want to ignore the difference if the expected value is > 100 (purposedly set high).
I have the jinja to test for those conditions and find the difference. Soinds like I need to iterate over the whole list and find any offending temps. And how to turn that into a list, then alert if the list isn't empty.
Does that sound like the right approach?

stuck dock
#

@thorny steeple this section will help with templates

final mulch
#

Hi
I've some problems with a REST template sensor.
Root of the problem is a buggy API of my washing-machine. Nothing I can change easy. So I have to deal with that.

I want to read out the endtime. If I request over HTTP I can get:

  • no answer
  • json ".error"
  • json "valid output" -> machine inactive = true
  • json "valid output" -> machine inactive = false

Only the last state is relevant as for all others I do not have an endtime.

So I did a "availabiliy" statement in the REST sensoe like:
availability: "{{ value_json.Inactive == 'false' }}"

But I can still see errors in my log because it failed to render the sensor itself. Any ideas why this happens?

summer arch
#

Are you able to get what integration an entity or device was created with?

final mulch
fading bone
#

hey, I need some help or guidance, I have GPS tracking on my car that i can access via a web service.
currently, i have inputs for lat and long, but it isnt a device tracker, so does not show on the map
Can someone please help me with a device tracker template where i can then use device_tracker.see to update?

mighty ledge
#

otherwise you can make an automation using device_tracker.see service to create a device_tracker that mirrors your sensor.

fading bone
#

the automation part is fine. going to use Node-Red for that

mighty ledge
#

Well then you need to come up with a way to do that in node red

#

the service call is simple

fading bone
#

do you create the entity using device_tracker.see?

#

cause the call looks simple

summer arch
#

Why does 100 evaluate to true for le

{{ ((states.sensor | selectattr('entity_id', 'search', "_battery$")))|selectattr('state', 'le', '20')|map(attribute='state')|list }}
{{ ((states.sensor | selectattr('entity_id', 'search', "_battery$")))|map(attribute='state')|list }}
['100', '100']
['100', '100', '86', '94']
mighty ledge
#

it is simple, it just creates a device tracker

mighty ledge
#

with a string 100 is less than 20 because 1 is less than 2 when evaluating characters left to right.

summer arch
#

or is it impossible 😦

mighty ledge
#

map the value to a float

#

| map(attribute='state') | map('float')

#

then do | select('le', 20)

#

but keep in mind, you'll lose the link to your state object.

#

i.e. you won't be able to get the name from it.

summer arch
#

TemplateRuntimeError: No test named 20.

mighty ledge
#

you used selectattr when it should be select

#

you no longer need to use selectattr after you map the generator to the attribute state

fading bone
summer arch
#

Unfortunate I can't get the name anymore though. Was hoping that I could get a sensor with a list of bad batteries and a total count for icon templating

mighty ledge
#

you can use namespace to keep the references but it makes it so you can't use a 1 liner

summer arch
#

that would be fine by me, I am in the yaml anyway

lunar crater
#

Hi, i am having some trouble with my energy dashboard using helper entities for daily reset metering as those entities somehow do not inherit the correct device class from the parent

lofty mason
#

I think I've sometimes seen that too.... I just fix it with customize

lunar crater
#

customize?

lofty mason
#

you can add device_class to your helper if it's not correct

void quiver
#

where can I find help with Ian Richardsons 'Config Template Card Card'?

lunar crater
celest tinsel
inner mesa
#

Sounds fine

plain forge
#

Hey all, I know it is possible with a template to check if an automation was triggered in the last X hours but is it also possible to check when it last performed an action? So the last time the automation was triggered and all set conditions returned true.

inner mesa
#

I don't think it counts as triggered unless it gets through the conditions

mighty ledge
#

last triggered is the last time it ran

#

not the last time it triggered

plain forge
#

Ok cool. Thanks!

fringe remnant
fringe remnant
fringe remnant
#

Okay, second question! I am trying to make an automatic list of cheapest hours of electricity.

{{ state_attr('sensor.nordpool_kwh_fi_eur_3_10_024', 'raw_today') }} returns the following list: https://hastebin.com/share/hugujejixe.css

How do I return the list sorted based on ascending 'value'?

#

Actually nvm, I think I got it

mighty ledge
#

You can install it via HACS

fringe remnant
boreal solar
#

Any dashboard templates?

mighty ledge
opaque star
#

Guys is it possible to use a template in the entity filed?
I want to implement this gallery card, but i want too change the folder everyday.

entities:
  - path: media-source://media_source/local/Cameras/Porteiro/2024/01/04
    include_video: false```

Would be something like: 
```media_source/local/Cameras/Porteiro/{{ now().year }}/{{ now().month }}/{{ now().day }}```
#

But i think its not possible, anyone knows another solution for this?

stoic cedar
#

I have a space heater that has a rest api that allows me control. It seems like the fan template (https://www.home-assistant.io/integrations/fan.template/) is a good fit for functionality but it does not have a temperature control. Is there a way to incorporate the temperature into that template or would I need to make another entity like a template sensor on input to get this functionality?

obtuse zephyr
stoic cedar
#

thank you for the pointer

plain magnetBOT
#

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

mighty ledge
#

@lone galleon the frontend doesn't support templating

#

You can make a script that has your templates and call that instead

wintry ether
#

Hi all. A Template Sensor I made that subtracts one sensor from another is getting the maths wrong!

template:

  • sensor:

  • name: "Total Electricity Used Today"

unit_of_measurement: "kWh"

state: >

{{ states('sensor.ems2234025_grid_import_power_today') | int - states('sensor.ems2234025_grid_export_power_today') | int | round(2)}}

Currently the two sesnors have a read of 43.8 and 0.1, but the template is giving 43.0 as the answer. What do I need to change?

mighty ledge
#

you're only rounding the second sensor

#

if you want to round the whole result, put the equation in parenthesis

wintry ether
#

{{ states('sensor.ems2234025_grid_import_power_today') | int | round(2) - states('sensor.ems2234025_grid_export_power_today') | int | round(2)}}

#

That still gets the result wrong

mighty ledge
#

... that's not what I said to do

wintry ether
#

Sorry, I'm quite new to this

#

Can you edit this to be correct?

mighty ledge
#

(x + y) | round

#

remove the | int's too

#

or change them to | float

wintry ether
#

I'm sorry. Can you edit the template so I can understand what you mean

#

I've tried a number of combinations of what you have suggested but it either gives me an error or the same result

#

I'm obviosly not getting the order right

fickle sand
#
state: >
  {{ (states('sensor.ems2234025_grid_import_power_today') | float  - states('sensor.ems2234025_grid_export_power_today') | float) | round(2)}}
wintry ether
#

That has worked, kind of. I now get the answer - 43.699999999999996

#

Also, I had to remove the ) from after the second float.

mighty ledge
#

you should have copied and pasted his result exactly

fickle sand
#

You need that ) together with the ( I put in front of your template

mighty ledge
#

the 2nd ) is needed, you clearly omitted the first (

wintry ether
#

Bingo! Sorry, I missed the first one. That's working now. Thanks both.

inner needle
#

Hi guys, I am doing some cleanup of my HA installation and I have a few errors in my system log related to templates that I am unable to fix
e.g. this one here:

Template variable error: 'None' has no attribute 'split' when rendering '{% if state_attr('sensor.office_lights', 'friendly_name') is defined %} {% for word in state_attr('sensor.office_lights', 'friendly_name').split() %} {% if loop.index > 1 %} {{ word }} {% endif %} {%- endfor %} {% else %} {{ 'sensor.office_lights' }} {% endif %}'
Template variable error: 'None' has no attribute 'split' when rendering '{% if state_attr('binary_sensor.fensterkontakt_arbeitszimmer_rechts_state', 'friendly_name') is defined %} Fenster {% for word in state_attr('binary_sensor.fensterkontakt_arbeitszimmer_rechts_state', 'friendly_name').split() %} {% if loop.index > 1 %} {{ word }} {% endif %} {%- endfor %} {% endif %}'
Template variable error: 'None' has no attribute 'split' when rendering '{% if state_attr('binary_sensor.fensterkontakt_arbeitszimmer_links_state', 'friendly_name') is defined %} Fenster {% for word in state_attr('binary_sensor.fensterkontakt_arbeitszimmer_links_state', 'friendly_name').split() %} {% if loop.index > 1 %} {{ word }} {% endif %} {%- endfor %} {% endif %}'
Template variable error: 'value_json' is undefined when rendering '{{ value_json.state }}'```

I am unable to find where this is coming from, I don't understandy why it is happening, but I also don't understand where it is coming from. Is there any way to narrow it down?
mighty ledge
#

search your configuration for those templates

#

the syntax isn't correct either. You're using is defined for something that will always be defined. You should change that to is not none, that should fix the issues.

inner needle
inner needle
mighty ledge
inner needle
#

Just did a grep on the whole config folder for "is defined" and the only thing I can find is in the log

#

Any other place I could check?

mighty ledge
mighty ledge
inner needle
#

Could you please be a bit more specific? 🙂

mighty ledge
#

there's no way to be more specific

#

I have no idea what you use

inner needle
#

xD

mighty ledge
#

but if you have MQTT devices, and they were auto discovered, then the MQTT discovery can contain templates.

inner needle
#

Ah ok I see, I have a bunch of auto discovered MQTT devices, where can I check for the templates?

#

The thing is, I have a templates in my dashboard that looks very similar to the onces with the erros

mighty ledge
#

that depends on the device

#

or their origin

inner needle
#
name: |
  {% if state_attr('this.entity_id', 'friendly_name') is not none %}
    {% for word in state_attr('this.entity_id', 'friendly_name').split() %}
      {% if loop.index > 1 %}
        {{ word }}
      {% endif %}
    {%- endfor %}
  {% else %}
    {{ 'this.entity_id' }}
  {% endif %}

e.g. this one, I was getting the error regarding none and the .split and I tried to fix it by checking for "is not none" before that

mighty ledge
#

that whole template is just wrong

inner needle
#

Ok?

mighty ledge
#

'this.entity_id' should be this.entity_id

#

in all cases

#

and the is not none will stop the split from failing

inner needle
#

Yeah that is what I though, funny thing is it worked before (without the outer most if)... is there somehwere a template cache or something I can / need to clean?

mighty ledge
#

there's no way it worked with 'this.entity_id' wrapped in quotes

inner needle
#

I mean the output was as I expected 😄

mighty ledge
#

literally impossible for it to work that way

inner needle
#

It stripped the first word fromt the friendly name...

mighty ledge
#

Not sure what to tell you, this.entity_id is a variable and you're treating it like the literal string 'this.entity_id' which is not going to be an entity on your system

inner needle
#

I am using it in the frontend in an filter card, if this makes any difference

mighty ledge
#

If the filter card put in some bullshit to transform the 'this.entity_id' from a string into your actual entity_id, then it would work

#

I don't use that card so I wouldn't know

inner needle
#

Yeah that might be the case I guess, in the error you also only see the replaced names

#

I dont get it, Just as a test I removed all tempaltes that make any use of ".split" and restarted my HA. Still I am getting the error

mighty ledge
#

clear your cache and refresh the page

inner needle
#

You mean the log page?

#

Or might this error also be caused by another client that is still running an older verison of the dashboard?

mighty ledge
#

yes that's possible w/ frontend cards

inner needle
#

I assumed it happend server-side, but could it also be triggered by a client?

#

uff, Ok, this might explain it, have quite a few clients running

#

will try to close them all and try again

#

Wow... that was it...

slate ermine
#

Dumb question: How can I search for a string in a message?
I'm trying to find the string SRSP - AF - dataRequestExt after 6000ms and SRSP - ZDO - mgmtPermitJoinReq after 6000ms in a MQTT automation, this is what I have so far (mainly for testing):

platform: mqtt
topic: zigbee2mqtt/bridge/logging
payload: "on"
value_template: '{{ "on" if value_json["level"] == "debug" else "off"}}'
mighty ledge
#

'abc' in some_value or 'xyz' in some_value

inner needle
#

I am left with one last template error: Template variable error: 'value_json' is undefined when rendering '{{ value_json.state }}'
I could imagine that this is more likely related to some mqtt device... question is where to search for that. The string "value_json.state" is not used in my frontend or any config.

What are the places to check for, for the templates related to the auto discovered MQTT entities?

mighty ledge
#

that's from z2m, wait for an update

inner needle
#

Ahh, this is a known issue?

mighty ledge
#

yes, from the 2024.1

inner needle
#

Ah ok, great 👍

marble jackal
#

it's comging from the devices set to legacy

inner needle
#

Set to legacy where? in z2m?

dark rock
#

Hi guys. Looking forward for help with a yaml template multi line sensor. The idea is to have a sensor that translates a Height into a text:

      {% set height = states('sensor.desk_2995_height') | float(0) %}
      {% if height < 0.9 %} Sitting
      {% elif  height < 1.15  %} Standing
      {% elif  height > 1.15  %} Walking Pad
      {% endif %}

This works in developer platform, so logic is supposed to be ok, but not sure how to put into the configuration.yaml file. Right now is like this:

sensor:

  • platform: template
    sensors:
    Standing_status:
    friendly_Name:"Standing Status"
    value_template:
    {% set height = states('sensor.desk_2995_height') | float(0) %}
    {% if height < 0.9 %} Sitting
    {% elif height < 1.15 %} Standing
    {% elif height > 1.15 %} Walking Pad
    {% endif %}

but i got an indentation error. Pastebin of the yaml: https://pastebin.com/Z2fkA0dw

inner needle
#

Ah nevermind, in your pastebin it looks ok 😄

dark rock
inner needle
#

Thank you @mighty ledge for your help!

inner needle
marble jackal
#

yeah, I think so

#

not completely sure

inner needle
#

Yeah that seems to be it! Thank you

#

Now I am almost error / warning free, but the rest is not related to templates and most of them need fixes by the developers xD

wooden raven
#

Using this to send notification of door open duration. It works, but often reports duration from an "opening" ago. That is to say, the door opens (A) and reports proper time. Door closes. Door opens again (B) and reports time from (A) using the following code. Any advice on a better duration template?

service: notify.mobile_app_dab
data:
message: >-
{{ trigger.from_state.attributes.friendly_name }} has been open for: {{
(now() - trigger.from_state.last_changed).total_seconds() | int // 60 }}
minutes.

mighty ledge
#

you're only using the trigger entity, which will be the triggering entity only, i.e. it will only report what triggers, it will never caculate based on a non-triggering entity

dry narwhal
#

Is it possible to access the items of a todo list using jinja? I want to get the list and use it in a template sensor to randomly pick an item. But for that I somehow need to access the list.

#
template:
- trigger:
  - platform: time_pattern
    hours: '/1'
  sensor:
  - name: random_meal
    state: >
        {{ states('todo.meals') | random }}
#

statesis of correct false as the state is the number of items. But tried other approaches and all I could find were service calls.

mighty ledge
#

Yes, this is covered in the docs

dry narwhal
#

Only the state issue I already mentioned. Did not see anything on direct accessing using templating.

mighty ledge
#

There is no direct access using tempaltes

#

you have to call a service to get the returned data, just like forcast

#

if you want it in a template sensor, then you need to use the new action: section for template sensors with a paired trigger.

dry narwhal
wooden raven
wooden raven
mighty ledge
wooden raven
karmic sapphire
#

Is there a way I can make this work for auto entities?

type: custom:mushroom-template-card
primary: |-
  {% set entityname = (entity) %}
  {{state_attr(entityname, 'friendly_name')}}
secondary: |-
{{ state.attributes.last_triggered.timestamp() | timestamp_custom('%H:%M') }} : {{ state.name }}
icon: null
icon_color: green
multiline_secondary: true
#

for the secondary line to show last triggered on an automation

mighty ledge
#

that should just work assuming that your entity is set to an automation

shy sun
#

Can somebody tell me how I can use the repeat for_each with the values I get from state_attr()?

(for example, I want to send a message for every attribute of a sensor. How could I do this?)

dry narwhal
#

which apparently creates the variable according to traces

plain magnetBOT
#

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

dry narwhal
#

but dev tools report UndefinedError: 'mymeals' is undefined

#

{{ mymeals['todo.meals']['items'] | list | string }}

inner mesa
#

Variables aren't system-global

mighty ledge
#

you have to build your template inside your automation where mymeals exists

dry narwhal
#

Do you by any chance know if I can use a template to set the value of an input_text in an automation?

  - service: input_text.set_value
    data: {{ mymeals['todo.meals']['items'] | list | string | random }}
    target:
      entity_id: input_text.meals_1 
#

Home Assistant seems unpleased with my approach

Error loading /config/configuration.yaml: while scanning for the next token
found character '|' that cannot start any token
  in "/config/packages/frontend/meals_automation.yaml", line 13, column 45
#

My template was supposed to create a list and then randomly pick one of the items.

#

after defining the variable

  - service: todo.get_items
    target:
      entity_id: todo.meals
    response_variable: mymeals
#

Thought maybe I need to specify it as a template, but that was not it.

  - service: input_text.set_value
    data: 
      template: {{ mymeals['todo.meals']['items'] | list | string | random }}
inner mesa
#

Yes, but you need to follow the docs for setting the value of an input_text

#

Seems you're trying random things

dry narwhal
#

I am using this in another automation

    action:
      - service: input_datetime.set_datetime
        target:
          entity_id: input_datetime.start_datetime
        data:
          timestamp: >
            {{ (states['input_datetime.end_datetime'].attributes.timestamp-86400)|float }}  
#

And merely adapted for the new one

inner mesa
#

Not really

plain magnetBOT
inner mesa
#

You stuck a template right after data:, then made up the 'template' key

dry narwhal
#

I am pretty sure I used the template key before, but seemingly not for this.

inner mesa
#

There's even an example of exactly what you want

dry narwhal
#

And I missed the "

inner mesa
#

Many things

dry narwhal
#

Just the two, I hop

#

e

inner mesa
#

template: is only valid to introduce a block of template entities

gritty umbra
#

Hello, I'm new with home assistant, and facing an issue creating a statistics sensor.
My configuration.yaml contains this;
sensor: !include_dir_list sensors/

in sensors/ i have (currently one) sensors file containing this;
- platform: statistics name: Eloverblik Monthly Statistics entity_id: sensor.eloverblik_energy_total sampling_size: 50 state_characteristic: mean max_age: days: 30

On load i get this error;
Invalid config for 'sensor' at sensors/eloverblik.yaml, line 1: expected a dictionary '', got [{'platform': 'statistics', 'entity_id': 'sensor.eloverblik_energy_total', 'name': 'Eloverblik Monthly Statistics', 'sampling_size': 50, 'state_characteristic': 'mean', 'max_age': {'days': 30}}], please check the docs

What am i missing ?

inner mesa
#

include_dir_list takes a bunch of files and concatenates their contents into a set of list items. My guess is that you need to remove the leading - and move everything 2 spaces to the left

gritty umbra
#

Thanks @inner mesa that was excactly the issue - now the sensor loads as it should!

dry narwhal
#

Is there a way to make variables temporarily global?
I find it a bit difficult to test my template without being able to modify it "live".

#
value: "{{ mymeals['todo.meals']['items'] | map(attribute='summary') | rejectattr('summary', 'search', states(input_text.meals_1)) | list | random }}"
#

I am simply trying to exlude any value that has already been written to the input_text.meals_1 so I don't create duplicates in the next service call

inner mesa
#

To start, you're missing quotes around the entity_id

dry narwhal
#

darn it

inner mesa
#

The way to do what you're asking is to execute the service call in the dev tool and then assign the result to a variable in the template dev tool for use in your template

#

And no, you can't ever make a variable global in that way

hearty verge
#

Is home assistant's location (lat/lon) availabe in templtes in the latest release?

lofty mason
#

zone.home has always had lat/lon. Can that be assumed to be the same thing as "home assistant's location" ?

hearty verge
#

awesome 🙂

lofty mason
#

I see zone.home does follow homeassistant.set_location too. So that's probably good to use.

dry narwhal
#

I wanted to check for the existence of a file before using it but my code always returns true.
Does anybody know if there is a detail wrong or if this is generally not possible?

#
{% if '/local/images/test.jpg' -%}
  true
{% else -%}
  false
{% endif -%}
sleek apex
#

Is there a simple way to build a template that creates a ternary (binary but 3) entity for security— green for all good and disarmed, yellow for potential problems, and red for armed? Right now, I’m just imagining a ton of and/or statements sandwiched between a few if/elses, and that seems wrong. There’s about a dozen entities (sensors and locks) in the mix to determine the security status.
Or is this better suited for a different solution?

obtuse zephyr
#

Doesn't seem wrong to me... kind of depends on the specifics, but you're not going to get around 2 conditions and an else

lucid thicket
sleek apex
#

Thank you!
And @obtuse zephyr , that was my thinking too. Hoping mekaneck's suggestion simplifies things a little.

limpid osprey
#

anyone please help with why this label: "[[[ return variables.ulm_translation_state + ' - ' + relative_time(states['lock.kwikset'].last_changed)]]]"
keeps showing reference error. Im just trying to convert the last_changed UTC time to relative time

#

dashboard returns ButtonCardJSTemplateError: ReferenceError: relative_time is not defined in 'return variables.ulm_translation_state + ' - ' + relative_time(states['lock.kwikset'].last_changed)'

inner mesa
#

You're confusing JavaScript and Jinja

crimson lichen
#

Create a sensor template then add states to that.

inner mesa
#

That's also one way

#

Do the whole thing in a template sensor and then just return the state in JS, or maybe JS has an equivalent to relative_time 🤷

lucid thicket
dry narwhal
neon lodge
#

Hi.
I`m looking for a way to count open doors & windows in rooms.

Is there a way to use a helper for counting windows in a room with open state, or do i need to create a template to solve this ?

marble jackal
#

You can do that using a template helper

dry narwhal
#

MAybe a template wiz knows a smart approach that I could try to create myself.
I am trying to create 5 random entries for 5 input_text helpers. But I want to make sure that they are all unique, i.e. no input_text is the same.
Can anybody think of a way of doing that without manually rejecting each of the other input_texts?

#

My basic approach for two would be

      - service: input_text.set_value
        data: 
          value: "{{ mymeals['todo.meals']['items'] | map(attribute='summary') | list | random }}"
        target:
          entity_id: input_text.meals_1
      - service: input_text.set_value
        data: 
          value: "{{ mymeals['todo.meals']['items'] | map(attribute='summary') | reject('equalto', states('input_text.meals_1')) | list | random }}"
        target:
          entity_id: input_text.meals_2
    mode: single
#

But I would like to create 5 and not repeat the reject(). But I am a bit stuck, creatively

dry narwhal
dry narwhal
#

Is there a way to reset all todo list items at once?

      - service: todo.get_items
        target:
          entity_id: todo.meals
        data:
          status: needs_action
        response_variable: mymeals    
      - service: todo.update_item
        target:
          entity_id: todo.meals
        data:
          item: "{{ mymeals['todo.meals']['items'] | map(attribute='summary') | list }}"
          status: "completed" 
#

My attempt failed and I am not sure if maybe there is a simpler solution that is not in the docs

formal ember
#

hey template gurus, i have an entity that gives me the current grid consumption for my electricity. this goes negative when I am feeding into the grid and its positive when I am using grid energy. I am trying to set up automations thru a blueprint to use my excess solar for certain entites. this blueprint needs an entity for the export power and one for load. can I at least get the export power out of this entity via a template sensor? still trying to figure out the load one...

dry narwhal
#

Can't you just check if your grid consumption entity goes negative? And then trigger the automation? Then you would not need to create new sensors.
Or maybe I misunderstood your approach, sorry

neon lodge
modern sluice
#

Hi, can somebody help me with my template? Following the instructions https://www.home-assistant.io/docs/configuration/templating/, I got most of the way there but I'm just having trouble with the time. Here's the working template: due_datetime: "{{ now() + timedelta(days = 15) }}" I need this same thing but always make the time 12:00PM. I'm trying to convert this template for use in the todo.list without making weird and wonky times. I tried sending just the due date but I get errors: Error running action Could not parse date for dictionary value @ data['due_date']. Got None I also tried just overwriting the time in a subjequent step but I saw no way to send time only without a date.

inner mesa
#

I would just change now() to today_at('12:00')

modern sluice
hot flax
#

I'm trying to get current week. It seems as jinja doens't have a week property as it eg year {{ now().year }} have. Any suggestion to week? {{ now().week }}

hot flax
rich anvil
hot flax
#

awesome, thank you

rich anvil
#

So you can use any of the datatime functions on it

dry narwhal
#

Also possible to use elif instead or in addition to else

#

If you don't want to use true and false you can also perform something using {{ do something }}

stuck sedge
#

how do i get the previous event from a calendar?

fierce imp
#

I want to take some JSON that comes in via a webhook (from woocomerce) and parse out some info to create todo items. I generally know how to do this, but I'm stuck on one thing, the json will contain a field called line_items, if there is just one item they will be under line_items[0], if two items, there will be line_items[0] and line_items[1] and so on depending on the number of items. Whats the best way to handle this field? (this is what it looks like in JSON Path Finder: https://imgur.com/a/7Q543uc )

formal ember
fierce imp
marble jackal
marble jackal
# stuck sedge how do i get the previous event from a calendar?

You need to use the calendar.list_events service call. Use something like this to get the events which ended the last 2 days

service: calendar.list_events
target:
  entity_id:
    - calendar.your_calendar
data:
  end_date_time: "{{ now() }}"
  start_date_time: "{{ now() - timedelta(days=2) }}"
formal ember
#
- sensor:
  - name: Grid Consumption Reversed
    unit_of_measurement: kW
    unique_id: 89c413f0-4e46-4ff1-862b-cd8946d917b0
    state: >
      {% set value = - (states('sensor.grid_consumption')  |float)  %}
      {{ value }} 

I have this sensor which shows my electricity grid consumption reversed. This shows a positive number if I am generating solar and exporting to the grid, and a negative number if I am importing from the grid. Is it possible to create another sensor off this to show exactly what I am exporting (i.e. a sensor that only shows the existing sensor from 0 and above?)

obtuse zephyr
#
  {% set value = states('sensor.grid_consumption') |float %}
  {{ value if value > 0 else 0 }} 
#

Something like that should do that

rich anvil
#

Or {{ [0, value] | max }}, although the if version is easier to read.

floral steeple
#

Hello all, I have a curl request that sends a request to another computer in my network to create an image. I'd like to automate this in HA and base the prompt (there are two that have to be the same) based on the state of a sensor, namely weather forecast.

#

This should generate a different image based on the weather forecast once a day which I then plan to create a pictures card in ha to display it

floral steeple
#

How do I create it such that the prompt field is modified on each request?

floral steeple
#

an example prompt could be:

a house in the mountains on a {{ state_attr('weather.forecast_home', 'forecast')[0].condition }} day, in the style of light maroon and sky-blue, poetcore, light gray and light brown, 32k uhd, light yellow and navy, consumer culture critique
#

I guess I can simply change the prompt to the above

#

in both fields

#

so the above definitly seems to work, if I inject that prompt with the state attribute, it comes out as

"positive_prompt": "a house in the mountains on a cloudy day, in the style of light maroon and sky-blue, poetcore, light gray and light brown, 32k uhd, light yellow and navy, consumer culture critique
",
spark vortex
#

- trigger: - platform: state entity_id: binary_sensor.alarm_sensorbb0003 to: "on" id: "on" - platform: state entity_id: binary_sensor.something001 to: "on" id: "off" binary_sensor: - name: my_sensor state: "{{ trigger.id }}"

if I have a tempalte sensor trigger based like this, but I want to turn it "on" only if a condition is matched (another sensor is true), can I add this condition only on the first platform: state and make sure that this condition is not considered if the second platform: state happens?

marble jackal
#

You can use a template trigger

quiet lagoon
#

Hello. I run into trouble as I don't find the error.... 😦 May you maybe help me out here?

#
  - sensor:
    - name: Heizung_COP
      state: >
            {% set q = states('sensor.mqtt_heizung_heizleistung') | float %}
            {% set w = states('sensor.shelly_heizung_total_active_power') | float / 1000 %}
            {% if w <= 0.5 or q <= 0 %}
              0
            {% else %}
            {{ (q / w) | round(2) }}
            {% endif %}
      availability: >
          {{
            is_number(states('sensor.mqtt_heizung_heizleistung')) and
            is_number(states('sensor.shelly_heizung_total_active_power')) 
          }}```
royal tree
#

Hi, is there a way to calculate my monthly cost for something, I have a sensor of current wattage of a charger and then I have another sensor of my cost per kwh

fickle sand
#

Else your are trying to divide a string by a number that will not work

quiet lagoon
#

you sir, are a hero. thank you very much.

lucid thicket
# royal tree Hi, is there a way to calculate my monthly cost for something, I have a sensor o...

You need to perform an integral on your kW sensor to calculate kWh, see the Riemann sum integration. Once you have that, you can use a template sensor to calculate kWh times $/kWh. You’ll also need to consider when to reset the sensor else it will just continue to increase (or maybe that is what you want)
Edit: take the Riemann sum sensor, then feed it into a utility_meter sensor that resets monthly

inner mesa
quiet lagoon
#

I was not even able to see what is wrong. So, how could I?

inner mesa
#

I would normally just ignore such a request

quiet lagoon
#

oh you mean: "no output"

inner mesa
#

well, clearly something wasn't working

quiet lagoon
#

sorry, understood.

royal tree
#

What isn't it doing, that it should be doing

#

I work in IT, I say that about 605054 times a day

hot flax
#

I'm trying to have some logic for a dashboard variable. The counter prints the jinja text {{ 2 % 2 }} . I want it to return 0 (only an example).

      - type: "custom:button-card"
        template:
          - custom_card_garbage_collection
        variables:
          label: test label
          counter: >
            {{ 2 % 2 }}
        entity: input_boolean.garbage_collection_collected
inner mesa
#

custom button card uses JavaScript, not Jinja

plain magnetBOT
#
The topic of this channel is:

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

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

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

floral shuttle
#

other than using Spooks repairs entity, can we somehow find the repairs in HA states? asking because I need the repairs number and preferably with only core functionality

#

using this now {% set issues = states('sensor.active_issues')|int(default=0) %} {% set updates = states.update | selectattr('state','eq','on') | list | count %} {{issues + updates}} and use that for the notifications number on the configuration menu item

spark vortex
marble jackal
#

trigger based temlate (binary) sensors don't support conditions

spark vortex
#

so how can I do it?

marble jackal
#

you can do something like this:

- trigger:
    - platform: state
      entity_id: binary_sensor.alarm_sensorbb0003
      to: "on"
      id: "on"
    - platform: state
      entity_id: binary_sensor.something001
      to: "on"
      id: "off"
  binary_sensor:
    - name: my_sensor
      state: "{{ trigger.id if is_state('binary_sensor.some_other_sensor', 'on') else false }}"
#

or

- trigger:
    - platform: template
      value_template: "{{ is_state('binary_sensor.alarm_sensorbb0003', 'on') and is_state('binary_sensor.some_other_sensor', 'on') }}"
      id: "on"
    - platform: state
      entity_id: binary_sensor.something001
      to: "on"
      id: "off"
  binary_sensor:
    - name: my_sensor
      state: "{{ trigger.id }}"
spark vortex
#

ah ok, clear, thanks

ember saffron
#

is there a way to get the state of a YAML configured input_boolean to be persistant after a HA reboot?

marble jackal
spark vortex
#

is there a reliable way to manually change a binary_sensor state? via API is still the right way?

rich anvil
#

What's the right way to mark a template sensor as unavailable? I'd like for a template sensor I've written to go unavailable when the sensor it depends on goes unavailable.

#

I've currently got {{ states('sensor.living_room_tv_power') | int > 10 }} but that errors in the logs when living_room_tv_power goes unavailable.

fickle sand
#

Or specify a default value in the int filter -> | int(0) to always get a number as state

formal ember
#

"{{ (states('sensor.solaredge_i1_ac_power'+'sensor.solaredge_i2_ac_power')|int(0) ) }}"

#

would this be the correct way to combine two sensors into one?

#

or can you put a , instead of the +?

obtuse zephyr
#

No, the states function takes 1 entity id

#

"{{ states('sensor.solaredge_i1_ac_power') | int(0) + states('sensor.solaredge_i2_ac_power') | int(0) }}"

formal ember
#

awesome thanks!

#
-template:
  - sensor:
    - name: Modbus Load
      unit_of_measurement: W
        friendly_name: "Load"
        device_class: power
        state_class: measurement
      unique_id: fd32c3b4-8eec-4c41-a2ca-d96627e4257f
      state: "{{ ((states('sensor.solaredge_i1_ac_power')|int(0) + states('sensor.solaredge_i2_ac_power')|int(0)) 
                        - states('sensor.solaredge_m1_ac_power')|int(0))}}"

Does this look right in its entirity?

#

just not sure how friendly name, device and state class are supposed to be formatted

#

the docs aren't very clear on this

obtuse zephyr
#

they should be aligned with the other properties

#
template:
  - sensor:
    - name: Modbus Load
      unit_of_measurement: W
      friendly_name: "Load"
      device_class: power
      state_class: measurement
      unique_id: fd32c3b4-8eec-4c41-a2ca-d96627e4257f
      state: "{{ ((states('sensor.solaredge_i1_ac_power')|int(0) + states('sensor.solaredge_i2_ac_power')|int(0)) 
                        - states('sensor.solaredge_m1_ac_power')|int(0))}}"

formal ember
#

ok, when I do that, the sensor does not work (disappears from HA)

obtuse zephyr
#

What's your log say? Do you have the template integration configured more than once?

formal ember
#

I have a template.yaml file, this has multiple instances of

- sensor:
  - name:
    ...
- sensor:
  - name:
    ...
#

if that makes sense...

obtuse zephyr
#

sure... and this entry is just a single one in there then?

#

without the template: at the top

#

(If not, that's where it should go)

formal ember
#

correct

#

fwiw i have other sensors with the correct formatting that you showed me and they work fine

obtuse zephyr
#

Sure, that's why I mentioned checking the log... if you've got everything configured correctly, that will tell you what failed to set up

formal ember
#

awesome, thanks, will take a look

floral steeple
inner mesa
floral steeple
#

thanks, Rob. But when would you want to use a RESTful Command vs Sensor? Does it have to do with refreshing it? for example, to refresh the command, I just need to call a service, but the sensor has its own interval....does that make sense?

inner mesa
#

If you want a sensor, use the sensor

#

If you just need a service, use the service

#

You can call a service whenever you want, like in an automation. Giving a service a refresh interval doesn't make sense

floral steeple
#

ok so this setup:

sensor:
  - platform: rest
    name: InvokeAI Last Image
    resource: http://192.168.1.195:9090/api/v1/images/?is_intermediate=false&board_id=none&offset=0&limit=1
    method: GET
    unique_id: 13b8afba-1f27-4d0b-a1d8-0fc24a9d1f1d
    headers:
      accept: 'application/json, text/html'
    content_type:  'application/json; charset=utf-8'
    data_template:
      json_attributes: true
      value_template: "{{ value_json.items[0].image_url }}"
#

should parse out the url from the API output here:

#
{"limit":1,"offset":0,"total":11,"items":[{"image_name":"c16db7b3-6866-43c1-aa34-6a35dbb20736.png","image_url":"api/v1/images/i/c16db7b3-6866-43c1-aa34-6a35dbb20736.png/full","thumbnail_url":"api/v1/images/i/c16db7b3-6866-43c1-aa34-6a35dbb20736.png/thumbnail","image_origin":"internal","image_category":"general","width":384,"height":384,"created_at":"2024-01-08 06:00:02.276","updated_at":"2024-01-08 06:00:02.330","deleted_at":null,"is_intermediate":false,"session_id":"5f17cb52-25f9-45b0-b989-00fbe9e98bc2","node_id":"5bdc4138-e8f9-4682-bc3c-8fafcb3dd324","starred":false,"has_workflow":false,"board_id":null}]}
#

and how often does it update?

opaque creek
#

Heya! Whats wrong with this code? Trying to make a template switch with 2 services on both on and off. But it doesnt show up after restart:
https://dpaste.org/dTpD0
Thank you!

inner mesa
opaque creek
inner mesa
#

You can't just put it there

#

You have to do it the way the docs show

#

It's not optional

opaque creek
wary yew
#

can someone help me with the syntax example to add a mdi icon in a template? I want an icon in the secondary information.

type: custom:mushroom-template-card
primary: '{{ states(entity) | capitalize }}'
secondary: ''
plain magnetBOT
#

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

rich anvil
#

You seem to be missing the preset_modes array at the very least

#

I don't think you can avoid having a "turn off", it's required by the template fan integration

main nova
rich anvil
#

ChatGPT has truly hallucinated most of that automation. Give me a second and I'll try tidying it up

main nova
rich anvil
#

So is switch.sonoff_100053c64c the medium and switch.sonoff_10004e540a the high?

main nova
#

yes, correct

#

see first two comment lines

rich anvil
#

Sorry missed that haha

main nova
#

No worries. So the preset_mode array would define what's visible in the UI?

rich anvil
rich anvil
#

I'm not 100% sure you can leave turn_on and turn_off empty like I did. If not, you could try putting an empty delay in them:

turn_on:
  - delay: 0
main nova
#

Excellent, I'll give this a whirl.

#

Thanks a lot!

#

Hmm, not quite, I'm getting the following check errors:

#

Invalid config for 'template' from integration 'fan' at configuration.yaml, line 170: 'condition' is an invalid option for 'fan.template', check: fans->ventilation_fan->set_preset_mode->0->choose->0->condition
Invalid config for 'template' from integration 'fan' at configuration.yaml, line 170: required key 'conditions' not provided
Invalid config for 'template' from integration 'fan' at configuration.yaml, line 171: 'value_template' is an invalid option for 'fan.template', check: fans->ventilation_fan->set_preset_mode->0->choose->0->value_template

#

My 170 is your 18

#

is it just a matter of adding the s to conditions? 😄

rich anvil
#

Sadly a bit more than that

#

I initially used if and switched to choice but the structure is abit diff

#

Also just noticed some odd quoting on the templates. The YAML formatter I used did that so not sure if it's right

main nova
#

great, thanks so much again, I'll try this in a bit

main nova
#

Unfortunately, even more screaming:

Invalid config for 'template' from integration 'fan' at configuration.yaml, line 170: Unable to determine action 'fans->ventilation_fan->set_preset_mode->1', got {'conditions': [{'condition': 'template', 'value_template': "{{ preset_mode == 'high' }}", 'sequence': [{'service': 'switch.turn_on', 'target': {'entity_id': 'switch.sonoff_10004e540a'}}, {'service': 'switch.turn_off', 'target': {'entity_id': 'switch.sonoff_100053c64c'}}]}]}
Invalid config for 'template' from integration 'fan' at configuration.yaml, line 180: Unable to determine action 'fans->ventilation_fan->set_preset_mode->2', got {'conditions': [{'condition': 'template', 'value_template': "{{ preset_mode == 'medium' }}", 'sequence': [{'service': 'switch.turn_off', 'target': {'entity_id': 'switch.sonoff_10004e540a'}}, {'service': 'switch.turn_on', 'target': {'entity_id': 'switch.sonoff_100053c64c'}}]}], 'default': [{'service': 'switch.turn_off', 'target': {'entity_id': 'switch.sonoff_10004e540a'}}, {'service': 'switch.turn_off', 'target': {'entity_id': 'switch.sonoff_100053c64c'}}]}

#

Unfortunately I don't understand enough about Jinja2 to even spot quoting issues

#

@rich anvil 👋

#

The template sections look ok in my file editor.

inner mesa
#

share what you're using

main nova
#

Me? The standard file editor in HA.

inner mesa
#

the code

main nova
inner mesa
#

the important thing is what you're using

plain magnetBOT
#

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

inner mesa
#

it checks just fine for me

#

my guess is that you put all that under template:

#

or in templates.yaml or something

main nova
#

no, it's in my configuration.yaml just under fan:. I have switch: right above and cover: underneath and both work fine.

inner mesa
#

I just pasted that whole thing as-is in my configuration.yaml and it checked fine and restarted without errors

main nova
#

that's interesting

#

I'm restarting in case something is lingering

#

nope, same issues after restart

inner mesa
#

your indentation is off

#

you need to indent everything in the choose: block

#

that's why it's important to see what you are using

#

I successfully copied and pasted it right out of the gist

main nova
#

Great, got it to check out, thank you! (Studio Code it is from now on)

#

@rich anvil it works! 🥳 Albeit with an on/off and separate presets, was hoping for a 3 level slider, but maybe this isn't an option in my case.

spiral imp
#

I am attempting to create a template binary sensor that is "on" if any entities that contain media_player.emby_ipad* or media_player.emby_iphone* are "playing" or "paused". I have gotten this to work which accurately counts any Emby players that are "playing". Not sure how to add "paused" or specify multiple entities.
{{ states | selectattr('entity_id', 'search', 'media_player.emby_*') | selectattr('state','eq','playing') | list | count }}

inner mesa
#

Use 'in', ['playing', 'paused']

spiral imp
#

is there something similar for the first selectattr so that I can specifiy media_player.emby_ipad* and media_player.emby_iphone* etc?

inner mesa
#

Not beyond what you already did

#

Wildcard matching is different from string matching

spiral imp
#

ok, I think I can make what I need work with the wildcard at the emby* level

#

thanks for the help

spiral imp
#

So the template I am using updates immediately in Template Editor. I created a binary sensor and the state does not change when I start to play media. It only changes if I go back to the template editor. Do I need to change something?
{{ states | selectattr('entity_id', 'search', 'media_player.emby*') | selectattr('state','in', ['playing', 'paused']) | list | count > 0 }}

inner mesa
#

states updates once per minute. Change it to states.media_player

shadow vale
#

I have a Template inside an automation question so I'm not sure which is best to post. I have a 4 button remote and want one automation to control all of them, instead of 4 individual automations. I'm capturing the trigger data but cannot get the template to read and compare. The evaluation comes back false. I've tried every combination I can think of and just can't get it working.

  - condition: template
    value_template: "{{ 'endpoint_id=2' in trigger }}"
then:
  - type: turn_on
    device_id: xxx
    entity_id: xxx
    domain: light
    brightness_pct: 99
enabled: true```
The value of "trigger" is:
```    <Event zha_event[L]: device_ieee=xxx,
    unique_id=xxx:0x0006,
    device_id=xxx, endpoint_id=2, cluster_id=6,
    command=on, args=[], params=>```
inner mesa
#

"trigger" isn't enough

#

in your case, you would use value_template: "{{ trigger.event.data.endpoint_id == 2 }}"

floral steeple
#

Anybody know what is the equivalent of "data" is in the RESTFul Command? is it Payload?

#

I'm trying to use "data" in a RESTful command but its does not seem like an option (according to the docs): does the data need to be in the payload below?

#
rest_command:
  get_LocalAI_image:
    - name: "Parse Image URL"
      resource: http://localhost:8080/v1/images/generations
      method: POST
      headers:
        Content-Type: application/json
      data:
        prompt: "a prompt"
        model: "dreamlike-photoreal"
        size: "512x512"
      value_template: "{{ value_json.data[0].url }}"
      payload: "{{ value_json }}"
inner mesa
#

payload is what you need to send

#

you're treating it as though you're receiving it

#

and it seems like you're still using rest_command, when you should be using a rest sensor

floral steeple
#

This is where I get confused: I need to send and receive.

#

Send a request to generate an image

inner mesa
#

that's what that does

floral steeple
#

Receive to to tell me where it is

inner mesa
#

you send a command and get a response

floral steeple
#

So, rest command is correct?

inner mesa
#

no

#

I keep saying...

floral steeple
#

Lol

inner mesa
#

one last time

#

read the whole page

#

top to bottom

#

don't skip anything

floral steeple
#

OK I will do that again and post a revised yaml oh my lol

floral steeple
#

Here's the scenrio:

  1. Send a curl request to an image generating AI machine once a day at 4 am which based on weather sensor (i.e. weather forcast) - so the prompt will be different all the time
  2. Wait upto 2 minutes for image to be generated and responce back
  3. Get image URL from the responce and place it it glaces picture card (or perhaps image entity)
#

it basically needs to be a service

#

called upon by an automation

inner mesa
#

ok

#

there's no way to get a response from a service like that

#

I still don't see why a REST sensor isn't what you want, but it's your thing

floral steeple
#

but is the sensor going to hit the machine on every update?

inner mesa
#

you can update however often you want

floral steeple
#

make the update interval once a day...could work

inner mesa
#

you control it

#

I'm sure they'll get rid of scan_interval one day and make this less hacky

floral steeple
#

ok, I could put this in:
scan_interval: 86400

#

what about restarts of HA?

#

it will likely force a refresh (i,e, and send a request) then

inner mesa
#

I don't know what happens on a restart

floral steeple
#

maybe sending a another command via command line to tell me what the last created file was in the images folder
ls -lat | head -2 | tail -1 | awk '{print $9}'
this gives me the file name

#
command_line:
  - sensor:
      name: LocalAI Last Image Created
      command: "ssh name@192.168.1.195:8080/generated-images/ ls -lat | head -2 | tail -1 | awk '{print $9}'"
      scan_interval: 3600
      unique_id: e23e13a6-9354-4de5-8a7c-86fd3b2d0a9e
      value_template: "{{ string | filename image entity?? }}"
summer arch
#

Would this template sensor keep a list of everytime that this device goes offline?

- trigger:
  - device_id: 3bc4bd9d1403a66c4fac7126026bfd55
    domain: zha
    platform: device
    type: device_offline
    subtype: device_offline
  sensor:
    - name: "zha Unavailable"
      unique_id: zha_dead
      state: >
        {% set time_list = (states('sensor.zha_dead') | list) %}
        {{ time_list.append(now()) }}
        {{ time_list }}
#

and what triggers taht? I am trying to catch zha going into "initialising" in which every entity is "Unknown" or "Unavailable"

#

It doesn't work...

fickle sand
#

If you test the template in dev-tools you will see an important warning

summer arch
#

I didn't put it in there because I expected the trigger to not be readable in it

inner mesa
#

There's no trigger mentioned in the template...

marble jackal
#

There are a couple of things wrong here.

  • | list doesn't make a list out of a json string, you need to use from_json for that
  • .append doesn't work in jinja
  • the entity_id of your sensor will be sensor.zha_unavailable (unless you change it). But you could also refer to this.state to avoid issues with the naming
  • this will soon exceed the 255 character limit for states

If you want to do something like this, put in in an attribute, not in the state. You can store lists in attributes.

summer arch
# marble jackal There are a couple of things wrong here. * `| list` doesn't make a list out of ...

.append doesn't work in jinja
I found multiple stack overflow for jinja .append. I thought templating was in jinja?
https://stackoverflow.com/questions/49619445/how-to-append-to-a-list-in-jinja2-for-ansible

the entity_id of your sensor will be sensor.zha_unavailable (unless you change it). But you could also refer to this.state to avoid issues with the naming
Didn't know they had object knowledge, cool

marble jackal
#

it's not supported in HA

summer arch
marble jackal
#

it's all in the documentation

plain magnetBOT
marble jackal
#

and you can add items to a list, but not by using append

{% set some_list = [ 'a', 'b', 'c' ] %}
{% set new_list = some_list + [ 'd' ] %}
{{ new_list }}
[
  "a",
  "b",
  "c",
  "d"
]
summer arch
#

Ok, so taking all of the suggestions, I have come up with this.

- sensor:
  - unique_id: zha_errors
    state: >
      {{ this.attributes.failures | length }}
    attributes:
      failures: >
        {% set old_list = this.attributes.failures | default('[]') %}
        {% set new_list = old_list + [ now() ] %}
        {{ new_list }}
#

state should be the length of the list, attribute will be the list of failures?

#

I didn't add the trigger

#

That's coming

marble jackal
#

You need the trigger for it to be persistent after a restart

summer arch
#
- trigger:
  - device_id: 3bc4bd9d1403a66c4fac7126026bfd55
    domain: zha
    platform: device
    type: device_offline
    subtype: device_offline
marble jackal
#

And after you add the trigger, this will be the state object at the time of the trigger. So with the templates like this, the state will be 1 lower than the the actual number of items in the list

summer arch
#

I pulled this one from an automation, are they the same?

marble jackal
#

Yes, the triggers are exactly the same as for automations

#

Also, the first time it triggers, the attribute won't exist

summer arch
#
- trigger:
  - device_id: 3bc4bd9d1403a66c4fac7126026bfd55
    domain: zha
    platform: device
    type: device_offline
    subtype: device_offline
  sensor:
  - unique_id: zha_errors
    state: >
      {{ 1 + (this.attributes.failures | default([]) | length) }}
    attributes:
      failures: >
        {% set old_list = this.attributes.failures | default([]) %}
        {% set new_list = old_list + [ now().isoformat() ] %}
        {{ new_list }}
marble jackal
#

You need a default there as well

summer arch
marble jackal
#

The default is at the wrong place

summer arch
marble jackal
#

And if you want the state to match the number of items in the list, you need to add 1

#

The default needs to be before the length filter

summer arch
#

Edited to match those two suggestions

marble jackal
#

And remove the quotes around [] for both default filters

#

You want it to be an empty list, not a string

summer arch
#

ok, edited again 😛 hahaha

#

Did I finally get it right

marble jackal
#

This looks okay to me

summer arch
#

cool, thanks for your help. I will slap it in and unplug the dongle to see what happens

marble jackal
#

Oh wait

#

You need to convert now() to a string

#

Use now().isoformat()

summer arch
#

ok, now it looks good?

marble jackal
#

👍

summer arch
#

I unplugged the dongle and the sensor still just shows "unknown"

marble jackal
#

check the log if there are warnings/errors

#

and maybe create an automation with the same trigger, and see if that triggers when you unplug the dongle

#

to check if your trigger is correct

hollow peak
#

I have to adjust my wind speed sensor and multiply by 1.5. This works in the developer tools template but when I add it to my yaml, no sensor show up after restart of HA. What am I missing - sensor:
friendly_name: "Wind 1.5"
unit_of_measurement: "mph" # Adjust this based on the unit of your original entity
value_template: "{{ states('sensor.tempest_wind_speed') | float * 1.5 }}"

mighty ledge
#

are you pasting all of that into the UI helper?

#

if yes, that's the problem.

hollow peak
#

Thats from my config.yaml

mighty ledge
#

what section did you put that in?

hollow peak
#

under template:

mighty ledge
#

You're mixing legacy templates with modern templates

#

friendly_name and value_template are not usable in modern template yaml

#

name and state

#

Also, in-line comments will cause problems

#

with yaml

hollow peak
#

I used chatgpt to make it

mighty ledge
#

well chatgpt isn't great for reasons like this

hollow peak
#

I see that now

mighty ledge
#

now you see why it's use is banned (for helping others)

lofty mason
#

Might just want to make a Template Helper in the UI, a lot easier.

hollow peak
#

I tired that, I probablly didnt do it correctly

#

Got it

#
  • sensor:
    - name: "Wind 1.5"
    unit_of_measurement: "mph" # Adjust this based on the unit of your original entity
    state: "{{ states('sensor.tempest_wind_speed') | float * 1.5 }}"
#

Thx for the advice!

#

One more quickie, If I wanted the output value to be lets say 3.25 instead of 3.253, how can I add that to the line? Basically round to the 10th

mighty ledge
#

Just add {{ (what you had inside other curly brackets) | round(2) }}

hollow peak
#

Thx

neon lodge
#

Hi.
I have custom:button-card to toggle my garage door.
The door gives open and close states, but is it possible to add "closing/opening" states from when i push the button and until its actually open by a sensor?

quiet lagoon
#

hello. how many "or" can I write into one "if" statement? like e.g.: {% if w <= 0.5 or q <= 0 or q > 10.0 %}

#

would that be possible?

inner mesa
#

as many as you want

quiet lagoon
#

hassio is stealing my life. i could invest so many hours into it. it's so much fun. - Thanks RobC!

#

no irony!

carmine hearth
#

Suddenly my flic button is not working and apparently I have to make it only accessible from the local network, as per a warning in my HA settings page.

It tells me to click the gear icon beside the Webhook ID but there is no gear icon so I do not know what to do. I would attach images but there is no option. This might help https://community.home-assistant.io/t/update-webhook-trigger-issue/669961

plain magnetBOT
#

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

urban moat
#

However I have the syntax wrong and I can't find in the docs how I should correct it.

#

The error given when I try to save that is Message malformed: expected dictionary @ data['action'][0]['default'][0]

inner mesa
#

you can't template service calls like that

#

you need to use script syntax to iterate over a list like that

urban moat
#
actions:
  repeat:
    foreach:
      {{ sensors }}
    sequence:
      - service: todoist.new_task
        data:
          content: Replace {{ repeat.item }} battery
#

Like that?

#

Apologies for my severly lacking YAML-fu

inner mesa
#

you need for_each: "{{ sensors }}", assuming that sensors is a list

#

I don't use blueprints, so there's some syntax around that that I'm not familiar with

urban moat
#

Thanks! I'll take it over to blueprints and see if they can get me the last mile.

devout dragon
#

i have a shellyplug and i want to pull the status from it (the full status message) in a template sensor, how would i do that? 🙂

spark vortex
#

in a template trigger sensor the return of trigger.to_state.state is a string, right? so I can do something like: {% if trigger.to_state.state == 'stop' %} ?

marble jackal
#

All states are strings, so trigger.to_state.state will also be a string

plain magnetBOT
#

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

spark vortex
#

it seems that the trigger to 'off' is not made for some reason, but it is made if I reaload the yaml

marble jackal
#

Is the binary sensor a template entity itself?

spark vortex
#

yes

#

- binary_sensor: - name: "Forno state" delay_off: minutes: 1 state: > {{ states('sensor.forno_power')|float(0) > 60.0 }}

#

but it happens also with other sensors that are not templte, but from an integration

#

it seems that the if statement is not triggered

spark vortex
#

@marble jackal any clue why this is happening?

#

I have a guess

#

the number input_number.forno_energy_per_cycle is updated by an automation, so I guess that the automation will be triggered after the sensor template trigger, so the value inside the input_number.forno_energy_per_cycle could be not updated yet at time of sensor template trigger

#

how can I make sure that the trigger template is updated always after the automation?

#

or I can probably update the sensor directly from the automation?

obtuse zephyr
#

Why not then trigger on input_number.forno_energy_per_cycle changes?

spark vortex
#

because it changes 2 times: when the oven starts and when it ends, I just need the (end - start) value

#

service: input_number.set_value data: value: >- {{ ((states('sensor.forno_energy') | float) - (states('input_number.forno_energy_per_cycle') | float)) | round(4) }} target: entity_id: input_number.forno_energy_per_cycle
this is what I have in the automation when it stops

#

probably I should use a temporary input_number for it instead of using always input_number.forno_energy_per_cycle ?

marble jackal
#

All template entities will go to unknown when you do that

spark vortex
#

yes, but it works because at time of restart, the input_number.forno_energy_per_cycle contains the right value

#

how can I update a sensor from an automation directly?

#

or make sure that an automation is ended before to update a template sensor

#

I could probably add some delay, but it could be not reliable always

#

for example, I want to run this
state: > {% set forno_state = trigger.to_state.state %} {% if forno_state == 'off' %} {{ (float(states('input_number.forno_energy_per_cycle')) * float(states('input_number.price_per_kwh'))) | round(2) }} {% else %} {{ -1 | float(0) }} {% endif %}
only if the automation X finished

#

uhm, if I add multiple triggers they will be in AND or OR?

obtuse zephyr
#

triggers are always OR

spark vortex
#

can't make them in AND?

obtuse zephyr
#

Combine them into one... only 1 trigger ever actually triggers something

spark vortex
#

uhm?

obtuse zephyr
#

State your specific need and we can help out with the best way to structure it

spark vortex
#

ok, I will put on a pastebin to make it clear

#

these are my automations and sensors https://pastebin.com/MUbK9SY7 , the problem is that the template sensor will contain a wrong value, my guess is that because the tempalte tirgger is triggered before the automation STOP ends, so it will use the input_number.forno_energy_per_cycle updated in the START and not in the STOP automation

#

so a probably solution can be to add sort of delay in the template sensor after the trigger and before it set the state, is it possible?

drowsy vigil
#

Hi,
I have a question about a template.

The goal is that I get a value from the gas meter, where a certain value e.g. 700 is subtracted and that the value is then output in the unit of the gas meter. I have the following template:

  • name: "gasconsumption"
    state: >
    {% set gasconsumption1 = states('sensor.gasconsumption') %}
    {{ ( gasconsumption1 | float - 700 ) | round(2) }}

However, only the value is output here - without the unit.

If I use the following template, I get an error message because the calculation does not work, as the unit is included in the calculation.

{% set gasconsumption = states('sensor.gasconsumption', with_unit=True ) %}
{{ ( gasconsumption | float - 700 ) | round(2) }}

Can anyone help me?

spark vortex
#

@obtuse zephyr ok, found a better solution based on your suggestion (thanks):

- trigger: - platform: state entity_id: input_number.asciugatrice_energy_per_cycle not_to: - unavailable - unknown sensor: - name: Asciugatrice cycle cost unit_of_measurement: "€" state: > {% if states('sensor.asciugatrice_dryer_machine_state') == 'stop' %} {{ (float(states('input_number.asciugatrice_energy_per_cycle')) * float(states('input_number.price_per_kwh'))) | round(2) }} {% else %} {{ 0 | float(0) }} {% endif %}

obtuse zephyr
floral shuttle
#
homeassistant.util.yaml.objects.NodeStrClass object' has no attribute 'data' when rendering ```
#

would appreciate a pair of eyes to help me out why this happens unlike the one for persistent notifications

obtuse zephyr
#

Your history attribute is always looking at trigger.event.data, and it's indicating that that attribute doesn't exist on the event

#

Your repairs attribute is checking differently, as it's using an empty list of the trigger.id is start

#

If that's suitable for the history attr, you could mimic that

floral shuttle
#

thanks for having a look. yes I figured that too, otoh, the failing history should take the else on HA start, so not use the trigger.event.data at all?

#

besides, the pers noti template does the exact same thing, unless my eyes deceive me now, why would that be different

#

wait, maybe I should add a check for trigger.event.data first? like {% if trigger.event.data and trigger.event.data.action == 'create' %} ?

marble jackal
floral shuttle
#

or add an id to the update trigger? and check for that

marble jackal
#

on the Home Assitant start event you wont't have trigger.event.data.action

#

just do the same as for the repairs attribute

#

first check if it triggered on the start trigger

#
            {% set rprs = this.attributes.get('repairs',[]) %}
            {% if trigger.id == 'start' %}
#

not sure why you have that trigger though

#

oh wait, repairs probably have been fixed due to the restart

floral shuttle
#

ok let me try that (had just clicked restart with the trigger.id for update, so next cycle... 😉

#

now see you both suggested the same thing...

#

yes this works too {% if trigger.id == 'update' and trigger.event.data.action == 'create' %}

marble jackal
#

that would work as well

floral shuttle
#

which would basically be the same I guess, checking if it was actually updated. which btw isnt bad, as I noticed upon restarting just now, it is triggered twice

marble jackal
#

assuming you added that id to the trigger

floral shuttle
#

first for restart, and few moments later, apparently for event

#

yes, I have this now:```

  • trigger:
    • platform: homeassistant
      event: start
      id: start
    • platform: event
      event_type: repairs_issue_registry_updated
      id: update```
#

so, given the fact the repairs_issue_registry_updated is happening on each restart, I could just aswell leave out that HA start trigger?

marble jackal
#

well, I don't know how it works for repairs like the restart required for a HACS update

#

I can imagine they are not cleared on startup, but just not created again

#

so if you don't clear the list on startup, they might stay in the list forever

floral shuttle
#

yes, that was why I kept it in. Otoh, there are also persistent repairs on purpose, (see that service in dev tools) which I now clear in the state... I suppose that is not good. hmm

#

no, its needs to be cleared, because otherwise HA clears them (if theyre non persistent at least, and the sensor goes out if sync). too bad we can not see the Severity and Persistent in the data. and the Domain is just false.

silent flicker
#
{{ state_attr('media_player.media_group_all_google', 'entity_id') | select ('is_state','off') | list }}

i am currently using this to find all devices where the state is off. is there a way i can rewrite this to display the list of devices that have a State attribute called friendly_name that contains the word kitchen? so for example, return a list of all kitchen media players because they have kitchen in their name

mighty ledge
silent flicker
#

oh snap thats a lot more complicated than i thought it would be

silent flicker
#

okay i think i figured out a better way to do it, but i cant get the IF working. any thoughts?

plain magnetBOT
#

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

silent flicker
#

line 7

#

value_template: "\"{{ repeat.item == 'media_player.aarons_room_display' }}\""

#

wait i think i just got it. a quote issue. NVM 🙂

silent flicker
#

yeah too many

mighty ledge
#

              value_template: "{{ repeat.item == 'media_player.aarons_room_display' }}"
silent flicker
#

that fixed it once i saw them in the raw editor

mighty ledge
#

the loop is pointless though

#

unless you're going to add an else to that if statement

silent flicker
#

it was just a small snip

#

im changing the volume on all my media devices if they are OFF and im adding extra IFs to set different ones to different volumes

#

a daily "reset" of the volume in case people change them to make them too quiet to hear anything

carmine hearth
#

Suddenly my flic button is not working and apparently I have to make it only accessible from the local network, as per a warning in my HA settings page.

It tells me to click the gear icon beside the Webhook ID but there is no gear icon so I do not know what to do. I would attach images but there is no option. This might help https://community.home-assistant.io/t/update-webhook-trigger-issue/669961

inner mesa
#

please don't crosspost

#

that has nothign to do with templates

dry narwhal
#

Trying to create a small batch addition script for To-Do Lists but my code only work in dev tools. In my script the counting does not work.

  meals_batch_addition:
    alias: Meals Batch Addition
    sequence:
      - repeat:
          count: "{% set items = ["1","2","3"] %}{% set item_count = items | length %}"
          sequence:
            - service: todo.add_item
              data:
                item: "{{['items'][repeat.index-1]}}"
              target:
                entity_id: todo.meals    
    mode: single
#

Error: invalid literal for int() with base 10: '""'

marble jackal
#

You are not outputting anything for the count

dry narwhal
#

Oh, I just see that I am setting the item_count and not returning it. I need to add {{ item_count }}

#

Op, nope, not quite.
count: "{% set items = ["1","2","3"] %}{% set item_count = items | length %}{{ item_count }}"
Leads to
expected <block end>, but found '<scalar>'

#

Apologies, I used double quotes inside the array and for the template 🤦‍♂️

#

Still stuck 😦
Error: length of value must be at least 1 for dictionary value @ data['item']

#
  meals_batch_addition:
    alias: Meals Batch Addition
    sequence:
      - repeat:
          count: "{% set items = [1, 2, 3] %}{% set item_count = items | length %}{{item_count}}"
          sequence:
            - service: todo.add_item
              data:
                item: "{% set items = [1, 2, 3] %}{{['items'][repeat.index-1]}}"
              target:
                entity_id: todo.meals    
    mode: single 
#

Tried with and without single quotes inside the arrays

mighty ledge
#

the whole mess in todo items is... a mess

#

"{% set items = [1, 2, 3] %}{{items[repeat.index-1]}}"

dry narwhal
#

Okay, found one issue: it must be `{{ items[repeat]}

mighty ledge
#

assuming you're doing that oddness

dry narwhal
#

Why oddness?

#

I tried not re-setting items but it seems it does not get the items from the count.

mighty ledge
#

cause you made a 1 item list ['items'] and tried to get indexes beyond it's size

#

Also, you can probably do this w/ for_each and alot less jinja.

#

e.g.

- repeat:
    for_each: "{{ [1,2,3] }}"
    sequence:
            - service: todo.add_item
              data:
                item: "{{ repeat.item }}"
              target:
                entity_id: todo.meals
floral steeple
#

hi! can you use scan_interval for a resful sensor setup?

sensor:
  - platform: rest
    name: "Image URL Sensor"
    resource: http://192.168.1.195:8080/v1/images/generations
    method: POST
    scan_interval: 43200
    timeout: 180 
    headers:
      Content-Type: application/json
    payload: '{"prompt": "Ultra high resolution 3D, {{ state_attr('weather.forecast_home', 'forecast')[0].condition }} day on midwestern hay field in late fall. vivid landscape colors, Shot with Nikon D780 with Nikon AF-S NIKKOR 24-70mm f/2.8G ED lens, resolution 45.7 megapixels, ISO sensitivity: 100, Shutter speed 1/250 second, 12k resolution, award winning photography, trending", "size": "512x512", "model": "dreamlike-photoreal" }'
    value_template: "{{ value_json.data[0].url }}"
floral steeple
inner mesa
#

I never argue with the dragon

floral steeple
#

😁

#

Having said that setting up as a sensor is the only east way I could do this short of an integration. If it hits the API on every restart is not a big deal cuz I don't often restart

winged thistle
#

Gosh. Anyone running Shelly 1 PM Mini with MQTT? I'm using it to monitor my solar power production however with the new devices Shelly also seem to have switched to a single "RPC" topic called shellypmmini/events/rpc which sometimes include the JSON parameter containing the power, sometimes it's outputting completely different stuff on the same topic. Then I am getting Template variable error: 'dict object' has no attribute (......) errors. According to what I found online that could be solved using availability but I couldn't wrap my head around it yet

floral steeple
#

does not seem to like the formatting for this sensor,
http://pastie.org/p/0lmsTrdyYUnEwzPCg2lMew
it seem to be complaining about bad indentatoin of the {{ state_attr('weather.forecast_home', 'forecast')[0].condition }} part, but I don't think that the case?

obtuse zephyr
#

You have a multi line value without using a multi line indicator. Mixing tabs & spaces in YAML is also asking for a bad time

#

if you made payload: -> payload: >, removed the leading and trailing ', and fixed the mixed whitespace, you should be good

urban moat
#

I asked this over in #blueprints-archived and got redirected back here. Is it possible to set a variable with results from a service call or to be able to make a service call from within a template? Related to my previous question in #automations-archived (#automations-archived message), the blueprint/automation finds all entities that have low batteries and I create a todo task (via Todoist) for each sensor needing a replacement. I would like to check if a todo already exists (via the todo.get_items service call) to exclude those entities so as not to make duplicate todos for ones that already have a todo. For reference, my blueprint is at https://gist.github.com/tteggelit/ff200972645b0d1f203605df10e6eb2a

#

Also, the automation I've currently created on this blueprint looks like the following.

floral steeple
#

If the state of that sensor is a url to a local image, should I now make an image entity based on this entity so that I could view the image in a picture card?

slow vine
#

I know I can use templates in a shell_command. Is there a way for that template to have the trigger information from an automation?
For example I want to echo {{ trigger.event.data.tag_id }} >> tags_scanned.log' when a rfid card is scanned.

haughty breach
slow vine
#

I tried something similar and it was not working so I was wondering if there is a templating problem, I am trying it a little differently (than I originally did) now, I'll see if its working.

#
shell_command:
  write_card: "/bin/bash -c 'echo Scanned {{ tag }} >> /config/cards.txt' "

automation:
  - id: "writecard"
    alias: Write Card to File
    trigger:
      platform: event
      event_type: tag_scanned
    condition: []
    action:
      - service: shell_command.write_card
        data:
          tag: >-
            {{ trigger.event.data.tag_id }}
#

now its working.

floral steeple
graceful sphinx
#

Can you include the "lock.open" action to a template lock? The Nuki Matter integration doesn't expose lock.open as a supported feature, so the usual lovelace cards don't show the option anymore so I'd like to fix that with a template lock.

marble jackal
#

there is no lock.open service call

#

there is lock.lock and lock.unlock

#

oh wait, there is lock.open

#

sorry

#

but I don't see it in the template lock documentation, only lock: and unlock:

graceful sphinx
#

yeah seems like it's not implemented in the template lock

#

it is within ESPHome though, so I'm just using an existing ESPHome device in my network to accomplish this

plain magnetBOT
#

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

graceful sphinx
#

would be great to have this integrated within the lock template 🙂

marble jackal
#

the keys are lock: and unlock:. Not lock_action: and unlock_action:

#

you could try if open: works as well, and maybe just isn't documented

graceful sphinx
#

the code above is from ESPHome

marble jackal
#

ah

#

I missed the ESPHome part (only looked at the code)

cinder lotus
#

I'd like to use the Mushroom number card with the slider to change the volume of a media player.
There is no volume entity by default in HA.
I created below template:

      - name: keuken volume
        unique_id: keuken_volume
        state: "{{state_attr('media_player.harman_kardon','volume_level')}}"```
Restarted HA but still no volume entity to use the Dashboard card.
graceful sphinx
#

doesn't this just create a sensor with volume_level as state?

cinder lotus
#

It seems I should create another type of sensor. I can't select the sensor in the Mushroom number card

graceful sphinx
#

maybe create a number template instead of a sensor? With that you can also define min/max and set_value

cinder lotus
#

I'll figure out how to do that

graceful sphinx
#
  - number:
      - name: keuken volume
        unique_id: keuken_volume
        state: "{{state_attr('media_player.harman_kardon','volume_level') * 100 | int }}"
        min: 0
        max: 100
        optimistic: false
        step: 1
        set_value:
          service: media_player.volume_set
          target:
            entity_id: "media_player.harman_kardon"
          data:
            volume_level: "{{ value | float / 100) }}"
#

this could work 😄

#

It won't though, volume_level is float

marble jackal
#

the qoutes around the template are missing

cinder lotus
#

I do get: The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: invalid key: "{"((states('number.keuken_volume') | int) / 100)": None}" in "/config/template.yaml", line 14, column 0

marble jackal
#
 volume_level: "{{ states('number.keuken_volume') | int / 100 }}"
graceful sphinx
#

also

state: "{{state_attr('media_player.harman_kardon','volume_level') * 100 | int }}"
marble jackal
#

yes, but you already had qoutes there

graceful sphinx
#

yeah but it would've spat out a float between 0 and 1

marble jackal
#

oh, right

#

I didn't see what you changed

graceful sphinx
#

volume_level will also spit out a string which doesn't work

marble jackal
#

no, that's already a float

#

btw, you can use:

        set_value:
          service: media_player.volume_set
          target:
            entity_id: "media_player.harman_kardon"
          data:
            volume_level: "{{ value | int / 100 }}"
graceful sphinx
#

hmm I think we need to turn it back to a float for media_player.volume_set

#

I've adjusted my code above

#

my number entity spat out a string so better be safe

volume_level: "{{ value | float / 100) }}"
cinder lotus
#

Hi, this created a sensor number.keuken_volume. Can select this entity in the Mushroom number card but the slider doesn't work to change the volume....

graceful sphinx
#

hmm okay

#

does the slider actually change the value of number.keuken_volume?

cinder lotus
#

No, when I play with the slider the volume changes to 0

graceful sphinx
#

so it does something at least

#

I could help troubleshoot with Teamviewer or something, just shoot me a DM if you want

cinder lotus
#

Sent you my ID and password

maiden magnet
#

hi, I try to create a template entity which if an entity has the state "dnd" or "online" then the state "1" and otherwise "0" gets. I have the following code. Since I want to create many such variables, I wanted to use variables, but I can not address these variables in the template so far, how do I do that? {% set user = states('sensor.user') %} {% if {{user}} == "dnd" or {{user}} == "online" %}1{% else %}0{% endif %}

urban moat
#

@maiden magnet I don't beleive you need {{user}} in Jinja code. I think you can just write {% if user == ...

marble jackal
#

it won't have a volume_level then

marble jackal
#

use user like shingle suggests

urban moat
mighty ledge
#

either it's a simple answer, or i'm not understandign what you're asking

#

simple answer: todo.get_items is a service call that responds with data and you just set the response_variable

urban moat
#

Let me first see if I can figure out what a response_variable is and if that is my solution. If not, I'll more thoroughly explain what I'm trying to do (and how I'm currently trying to do it, which may be completely the wrong way).

maiden magnet
sullen osprey
#

Hi guys, im trying to create a sensor with a attribute of a sensor but i got a error. what wrong on thaht : - sensors: iphone_alex_zone: friendly_name: Iphone Alex Zone value_template: '{{states.sensor.iphone_53_geocoded_location.attributes.zones}}'

urban moat
mighty ledge
#

it's done in the sequence section for scripts or the action section for automations and template entities

marble jackal
plain magnetBOT
#

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

marble jackal
#

also you should use state_attr() instead of states[].attributes[]

sullen osprey
#

You right ! i miss indentation ! i just try it but they dont get the value. Also i try this in devtools/templates : {{ state_attr("sensor.iphone_53_geocoded_location", "zones") }} and they return None. But if i go on States and look the attribute zones i have a value

merry furnace
#

I wanted to use different services if boolean true and others if not true. Then a final service in any case. See code below.
This doesn't work and I have the feeling that this is because it should first give back an enter after the sequence.
Is what I try to do possible in such a way?
For now I have solved it with simply using a group, but the question remains.

#
  sequence: >
    {% if states('input_boolean.vacuum_once_a__day') == 'on' %}
      - service: vacuum.return_home
        entity_id: vacuum.antracii
      - service: vacuum.return_home
        entity_id: vacuum.silvii
    {% else %}
      - service: vacuum.start
        entity_id: vacuum.antracii
      - service: vacuum.start
        entity_id: vacuum.silvii
    {% endif %} 
    - service: input_boolean.toggle
      entity_id: input_boolean.vacuum_once_a_day```
marble jackal
sullen osprey
marble jackal
fickle sand
#

That means that the attribute doesn’t exist or that the key name is wrong

marble jackal
#

either the entity_id or the attribute is wrong

#

check in devtools > states

sullen osprey
marble jackal
#

your attribute is Zones, not zones

sullen osprey
#

Oh ! Capital sensitive !

marble jackal
#

use state_attr('sensor.iphone_53_geocoded_location', 'Zones')

merry furnace
marble jackal
#

that's because you were not using target

merry furnace
#

True I tried target and later data, but probably made some other mistake there.

#

I'll try it again.
I see btw that I tried it different than you are proposing. Your's is cleaner!

sullen osprey
fickle sand
sullen osprey
marble jackal
#

okay

#

I guess you placed it under template:

#

but you were using the legacy format, which should be under sensor:

#

for the legacy format it should be:

sensor:
  - platform: template
    sensors:
      iphone_alex_zone:
        friendly_name: Iphone Alex Zone
        value_template: '{{state_attr('sensor.iphone_53_geocoded_location', 'Zones')}}'
merry furnace
#

I made the mistake @TheFes, I had -entity_id: xyz under targget, instead of just listing the -xyz.
Thanks for your help again!
I'm going to make other scripts cleaner based on your suggestion as well.

marble jackal