#templates-archived

1 messages Β· Page 53 of 1

mighty ledge
#

line 1

acoustic arch
#

someone helped me with this a long tim ago

#

hehe. lemme template the first line solo.

mighty ledge
#

just remove the > 0 and make sure you use output jinja indicators and remove the if

acoustic arch
#

oof! that seems to work! haha. I got 10 in stead of 4 but when i remove count and just list them, i see some old sensors which should have been deleted...

#

so thats something to solve, but bingo!

#

thx !πŸ˜†

marble jackal
#

@acoustic arch to avoid that for the future, you could check on that using has_value

#
{% set tgtg_count = states.sensor
    | selectattr('entity_id', 'search', 'tgtg')
    | rejectattr('state', 'eq', '0')
    | map(attribute='entity_id')
    | select('has_value')
    | list
    | count 
%}
{{ (tgtg_count ~ ' beschikbaar') if tgtg_count > 0 else 'geen TGTG' }}
cerulean karma
#

I have a template class:

#
<template TemplateState(<state switch.pi_hole=on; icon=mdi:pi-hole, friendly_name=Pi-Hole @ 2023-09-10T21:36:30.766618+02:00>)>
#

I can print the state with {{ i.entity_id }} but how can I access the other attribues like "icon" or "friendly_name"?

#

I really don't get it atm 😦

mighty ledge
#

i.attributes.icon

#

see the state object documentation

cerulean karma
#

perfect, thanks

void flax
#

im using sms.incoming_sms as a trigger, is there a way to trigger if the text: contains a word to trigger and not exact

mighty ledge
#

with a template trigger

#

but we'd need more info

#

because sms.incoming_sms isn't something that normally exists in HA.

void flax
#

thank you lead me in the right direction was {{ 'Alarm' in trigger.event.data.text }}

mighty ledge
#

Ah, so it's an event trigger, with a template condition

#

makes more sense w/ sms.incoming_sms

cyan shale
#

Good morning. I need help with creating a template sensor. I have a water meter (ADC-SWM150) which has a flow sensor, which records in Liters per Min. My understanding is that I need to create a template sensor, which will take input from that original flow sensor, and create a mimic sensor that records in gallons per min. I am not an expert at this, and could really use some help in how to write that / create that. The original sensor that records in liters per minute is: sensor.smart_water_valve_meter_water_flow. And ofcourse this would be for US gallon.

mighty ledge
#

just multiply the value by 0.264172

#

in your template

cyan shale
#

Ok, how do I create this template πŸ™‚ .. Sorry, pretty novice here

lofty mason
#

If you have 2023.9, it's much easier in the UI template helper form.

cyan shale
#

Aha, ok, let me try that, thank you πŸ™‚

mighty ledge
#

just make sure you're using the value supplied above and not 1024

#

@cyan shale do you plan on using the energy tab?

cyan shale
#

yes, so I want to create this new sensor, which I'll use in a Consumption Sensor. I got the code for the consumption sensor from another HA user, who is using SWM-150 .. but he uses it as is in liters per min. I want to use it in gallons per min

mighty ledge
cyan shale
#

Ok, so sorry, but could you please point out where do I change that in the cog?

floral steeple
#

petro, can you add a value_template in the customize.yaml settings?

#

asking for Keith3

mighty ledge
floral steeple
#

ok, the he must create a second template sensor based on the reimann-sum sensor

#

having all the properties for the energy dashboard

cyan shale
#

Would this code work?

#

template:

  • sensor:
    • name: "Water Consumption"
      unit_of_measurement: "GPM"
      state: "{{ states('sensor.smart_water_valve_meter_water_flow')|float * 0.264172 }}"
      availability: "{{ is_number(states('sensor.smart_water_valve_meter_water_flow')) }}"
floral steeple
#
  device_class: water
  state_class: total_increasing

and add this, so it will work with the energy dashboard

cyan shale
#

Ok so three steps then?

plain magnetBOT
floral steeple
#

assuming your above code works (which I don't know) you can just add it to your template sensor, like this

sensor:
name: "Water Consumption"
    unit_of_measurement: "GPM"
    state: "{{ states('sensor.smart_water_valve_meter_water_flow')|float * 0.264172 }}"
    availability: "{{ is_number(states('sensor.smart_water_valve_meter_water_flow')) }}"
    device_class: water
    state_class: total_increasing
    unique_id: add a unique ID here
#

only 2 steps

cyan shale
#

Ahh ok, so in Step 1, would I use the source as this new sensor? How would I reference it? sensor.Water_Consumption?

#

Also, where you say unique id (in both steps)... is that specific to my device? Or I create a random one...

floral steeple
#
    availability: "{{ is_number(states('sensor.Water_Consumption')) }}"
#

you would call the state of the new sensor made in step 1

#

but it can be words too, not just numbers

lofty mason
#

What case am I thinking of where entity id becomes sensor.template_water_consumption?
Does template always append template_ to the name to get the entity_id? or is that only if you don't have a unique_id?

plain magnetBOT
#

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

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

floral steeple
cyan shale
#

Getting hte following error: "TemplateSyntaxError: expected token ',', got 'string'"

marsh cairn
#

You are missing a ' in your state template

cyan shale
#

Ahh ok...

#

Fixed that

#

now getting the following error

#

ValueError: Template error: float got invalid input 'unknown' when rendering template

#

I'm assuming I can't use the consumption sensor created in step 1, in step 2. I need to still use the original one ... sensor.smart_water_valve_meter_water_flow ?

marsh cairn
#

You can. But you cannot use the same unique_id for two different entities. That makes those not very unique.

cyan shale
#

Ohhhh, Ok so I need different IDs... let me try that first.

#

Done, and had to change the state and availability to the main sensor, it seems to be palssing in the developer section

marsh cairn
#

Have you done a full HA restart or just a quick reload?

cyan shale
#

Ok, so looks like I have to sort of reverse the steps...

#

'''# Template sensor to take SWM-150 Flow Sensor and convert it from Liters per minute to Gallons per minute, and then make it available in Energy Dashboard

sensor:
name: "GPM_Water_Consumption"
unit_of_measurement: "GPM"
state: "{{ states('sensor.smart_water_valve_meter_water_flow')|float * 0.264172 }}"
availability: "{{ is_number(states('sensor.smart_water_valve_meter_water_flow')) }}"
device_class: water
state_class: total_increasing
unique_id: 02fbc54d-1756-436d-b3e5-9632c242f76a'''

#

And then use this sensor in the consumption sensor

#

'''# Water Consumption Sensor in GPM using the Template Sensor Created above

  • platform: integration
    unique_id: eb817c0e-ea5d-416e-9278-b2e6b28b1bed
    source: sensor.GPM_Water_Consumption
    name: water_consumption_swm
    round: 2
    method: left'''
plain magnetBOT
#

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

marsh cairn
#

If the unit of measurement is "Galons per Minute" (flow rate), the state_class cannot be total_increasing (consumption).

cyan shale
marsh cairn
#

The integration platform needs a HA restart

cyan shale
#

Looks like I may still have errors here. Suggestions ? Reviews?

lofty mason
#

what's the error?

cyan shale
#

No syntax error anymore

#

I'm assuming based on Jorg's comment, that I have a logical error, that unit of measurement is GPM, and cannot be total increasing

lofty mason
#

GPM is a rate, it should be state_class: measurement.
Gallons is a volume, and that is what is total_increaseing

cyan shale
#

So I think the unit of measurement here should be just Gallons?

lofty mason
#

the flow rate sensor's unit is gallons per minute
The integration/riemann converts flow rate (gpm) to volume (gallons)

#

So gpm_water_consumption should be state_class: measurement

#

water_consumption_swm should be state_class: total_increasing

cyan shale
#

Ahhh... ok, let me re-write that... thanks...

plain magnetBOT
#

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

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

cyan shale
#

PS: trying to figure out how to paste code, and failing miserably.

plain magnetBOT
#

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

floral steeple
marsh cairn
#

The symbols used are backtics ` , not apostrophes '

#

And everything above 15 lines total should be shared via a code sharing site

cyan shale
#

Ok thank you

#

here is the final code, that I'm pasting in my yaml and then restarting HA

mighty ledge
#

why total_increasing?

cyan shale
#

Ok something is wrong in the formatting // I pasted it in my YAML // check config gives erros on different lines. So I'm assuming something is wrong with my formatting.

mighty ledge
#

those do not go in the same section

#

also, I'd expect your state_class on the integration sensor to be measurement

cyan shale
#

I'm confused then... sorry.

mighty ledge
#

I'm not even sure you need the integration platform either...

cyan shale
#

My goal is to take what Anto has done (it works for him) but have it show up in gallons not liters

mighty ledge
#

got a link to it again?

cyan shale
#

So I just need to add one extra step somewhere from his original code, which is here

#

FYI: this meter, SWM-150 reports flow in liters

floral steeple
#

yes, he's trying to convert a flow (l/m) to consumption (gallons)

mighty ledge
#

Ok, so...

#
template:
  - sensor:
    - name: "GPM_Water_Consumption"
      unit_of_measurement: gal/m
      state: "{{ states('sensor.smart_water_valve_meter_water_flow')|float * 0.264172 }}"
      availability: "{{ is_number(states('sensor.smart_water_valve_meter_water_flow')) }}"
      state_class: measurement
      unique_id: 02fbc54d-1756-436d-b3e5-9632c242f76a

sensor:
  - platform: integration
    unique_id: eb817c0e-ea5d-416e-9278-b2e6b28b1bed
    source: sensor.gpm_water_consumption
    name: Water Consumption
    unit_of_measurement: gal
    device_class: water
    state_class: measurement
    round: 2
    method: left
#

copy past that directly, unless you already have the template section and the sensor section. If you do have those sections, you'll need to adjust some things.

cyan shale
#

Ahhh, yes, I do have those sections... this is my current YAML

plain magnetBOT
mighty ledge
#

ok, then...

cyan shale
#

Thank you, ok trying it

#

Ok, getting this error
Invalid config for [sensor.integration]: [unit_of_measurement] is an invalid option for [sensor.integration]. Check: sensor.integration->unit_of_measurement. (See ?, line ?).

#

Does unit of measurement need to be in single quotes?

mighty ledge
cyan shale
mighty ledge
cyan shale
#

Ohhh... ok

lofty mason
#

yeah the riemann will try to come up with its own units, it doesn't let you give it one. it works great for power/energy, but it's pretty dumb for everything else, and will come up with gpmhours πŸ˜›

mighty ledge
#

sounds like we need an update to that integration

#

that should probably be in the UI anyways

#

(unless it already is)

#

it is!

lofty mason
#

Yes there's an integration/riemann helper in the UI, but it still doesn't do the units right for non-electric flows.

cyan shale
#

Ok that passed all the syntax

#

Going to cross my fingers and restart my HA

lofty mason
#

also I want to know who decided to name an integration integration 😦 πŸ˜›

floral steeple
#

lol that's good point, but I think in this case, it referring to integral

mighty ledge
#

yep

#

but they could have called it integral

lofty mason
#

yeah I get why... but it's just.... ugh

floral steeple
#

Keith run that water hard ...

mighty ledge
#

the derivative integration is called derivative, not derive

#

πŸ€·β€β™‚οΈ

floral steeple
#

maybe we should call all HA intergrations, integrals

cyan shale
#

I'm just taking a full backup / just in case it breaks.. and will restart then

marsh cairn
#

hassio integrals?

floral steeple
#

yeah, if it passes basic check, you should be fine less an error message in the logs if its not working

cyan shale
#

lol.. in hte last 3 months since I've been using HA, have had put so many devices, automations etc... don't want it not booting up

cyan shale
floral steeple
#

had did you get a SWM-150 without having ADC account?

#

know a dealer or something

cyan shale
floral steeple
#

got it.

#

makes sense

cyan shale
#

ok everything is back and up with new config

#

so when I go to energy dashboard to add, I get the following error

#

Oh no way to add a pic here... ok, i'll copy paste

floral steeple
#

did you run some water so that value us not 0 or unknown? check if the sensors are populating and adding

cyan shale
#

ohhhh, ok let me go run a faucet

#

ok did that, and that let me add it, but got another strange error

#

says
Last Reset Missing
The following entities have state class
'measurement' but 'last_reset' is missing:
. sensor.water_consumption

lofty mason
#

you're not supposed to add the measurement sensor to the energy dashboard

#

that only feeds the riemann.

#

you add the riemann to the dashboard

mighty ledge
#

that is the riemann

#

since when does riemann transform a measurement to total_increasing?

cyan shale
#

So under water source, I only see one sensor

lofty mason
#

why would a riemann sensor not be total_increasing? (or total)?

#

all of mine are

mighty ledge
#

because measurement is just a momentary measurement

#

it shouldn't need reset either

lofty mason
#

the flow rate is a measurement, the result of the integral is total_increasing

floral steeple
#

state_class: total_increasing

#

is what I have

mighty ledge
#

total_increasing means it never decreases

floral steeple
#

for my reimann

mighty ledge
#

integrals do not do that

lofty mason
#

they do if their inputs are always positive

#

are you returning water to the grid? πŸ˜›

mighty ledge
#

that makes absolutely no sense

floral steeple
#

lol it has a backflow preventor

#

he cannot return water

#

but good idea

mighty ledge
#

an integral is area under the curve

#

it's not total increasing

lofty mason
#

the integral of a water flow rate is "an amount of consumed water"

mighty ledge
#

are people really doing that, using integral to change it from momentary to total_increasing??? wtf

lofty mason
#

I really do not understand where your confusion is coming from.

cyan shale
mighty ledge
#

it's not confusion, it's just not how it should be done when the calcs can work off a momentary value, like energy

#

it's an extra step that's just not needed

#

that's the confusion

mighty ledge
lofty mason
#

measurement generates weird "min"/"max" statistics which make no sense for a total volume

cyan shale
#

oh ya, I saw that. The graph had min / max

#

I just changed it and rebooted it

mighty ledge
#

I've always wondered why people have been doing this

#

now I know, it's because we made a stupid decision

cyan shale
#

question, would I change state class "total_increasing" to both?

mighty ledge
#

no

#

just the gal one

cyan shale
#

Oh, just to line 21?

floral steeple
cyan shale
#

Yes my plumber pointed that out yesterday, and we added the expansion tank πŸ˜‰

cyan shale
floral steeple
lofty mason
#

I missed the start of this, why is your hot water tank exploding now?

floral steeple
#

the smart water valve has a back-flow preventor

#

my water system became closed once that was installed

cyan shale
#

Hahaha, I pointed it out to him that it has a backflow preventer, and he immediately said, we need to add an expansion tank

floral steeple
#

as you know, hot water expands when it heats, it used to push back on city water pressure before the valve was installed but after, it pushed back on the hot water tank pressure relief valve

lofty mason
#

ah I see

floral steeple
#

that why you need an expansion tank on the hot water tank

lofty mason
#

I thought all homes already had backflow preventers at the meter, but maybe that's just for irrigation water?

floral steeple
#

not here in Alberta

#

but they are changing that now

mighty ledge
#

it's to stop rainwanter from getting into your drinking water from the irrigation system

lofty mason
#

makes sense. I have one of those, and I'm pretty sure I don't have an expansion tank, and was just wondering why mine is not blowing up then

#

TIL

floral steeple
#

you should look into that

#

expansion tanks in general increase the logengvity of hot water tanks

#

because of this phenomenon

lofty mason
#

my hot water tank is currently like 28 years old πŸ˜›
I try not to even look at it lest it burst

floral steeple
#

lol maybe its made well so you are good

#

the new ones today are tin cans

mighty ledge
#

So, I'm going through my system and it seems that all my energy sensors changed from momentary to total increasing. I feel like I'm taking crazy pills

lofty mason
#

what integration creates the sensors?

mighty ledge
#

shelly

#

they were definitely momentary when this crap first came out

lofty mason
#

I assume you mean measurement not momentary

mighty ledge
#

and now they are definitely total increasing

#

yea yeah, same difference

#

it annoyed the ever loving shit out of me that I had momentary kWh sensors, but I rolled with it

#

at the time

#

now these shits are all total_increasing

cyan shale
#

Ok, it all seems to be working, except I noticed something off.... So that's an easy arithmatic fix.

#

The original sensor in HA reports liters per hour (not minute).

marsh cairn
#

Embrace the total increasing dark side SWPalp

cyan shale
#

So my math is taking liters per hour, and showing that as gallons per minute.. which is way off.

mighty ledge
#

never

mighty ledge
#

in the first template

#

just put a / 60

#

after the 0.2xxxx number

cyan shale
#

and reboot?

mighty ledge
#

Well, you'll aslo have to fix your statistics

#

you can just reload yaml

cyan shale
#

ahh ok

#

that did it !!! πŸ™‚

#

Ok, now, can I reset this sensor to zero? Meaning delete all its old values for past 60 mins?

mighty ledge
#

I'm not sure, I'm questioning everything about energy now because everything I set up originally is all different from what I remember.

cyan shale
#

Hey this is all working now πŸ™‚

#

Thank you all soooo much. this channel is amazing. I'm going to take all these learnings, and post it in the community forum thread if someone else is looking.

#

Ohhh wait, I've reached my first day limit of what I can post.....hahahah

#

@floral steeple , maybe you can post on the SWM150 thread :_

floral steeple
#

sure, but maybe you can edit your original post?

mighty ledge
#

I just bumped your trust level

#

so you can post now

cyan shale
#

Oh thank you, I'm giong to go ahead and post it. so excited about this. thank you again.

lean yacht
#

Hi there,
I'd like to use the current consumption of a smart plug as input to define a binary sensor...
My dryer is not connected but monitoring the current can tell me if it's running or not...
So I'm looking for a template that turns on the binary sensor if the current goes above 10Amps, and turns off if the current was below 0.1Amps for 10min...
I need the 10min delay because the end of the cycle goes through heat and cool periods so current is fluctuating.

Anyone has a ready made template that can do this ?

lofty mason
#

Ok, now, can I reset this sensor to zero? Meaning delete all its old values for past 60 mins?

I think the only way is to delete the riemann helper, then go to devtools/statistics and there should be a "Fix Issue" for that sensor that will ask you if you want to remove all long term statistics. Do that, and then you can recreate the riemann helper.

#

maybe throw in a recorder.purge_entities too for good measure, though I don't know if that's necessary

cyan shale
#

ahh ok, I'll play around with that next

uneven pendant
#

Command failed (with return code 255): ssh -i /config/.ssh/brendyn -o 'StrictHostKeyChecking=no' pizza@192.168.51.25 "type interactive.txt"

#

my cmd sensor says 'unknown'

#

when this command line sensor fails

#

is there a way to get a failure to show "False" or "off"

cyan shale
#

@mighty ledge and @floral steeple - ok quick results - something is off

  1. I had my sprinklers on from 1 pm to 1:13 pm -
  2. It reported accurately in the history graph for GPM_Water_Consumption
  3. I can see that it stayed at roughly 8 Gallons per minute during those 13 minutes, great

But on the home energy dashboard, where I'm using the Water Consumption sensor.
for that same time period 1 pm to 2 pm
Total consumed gallons is reporting as only 1.87 Gallons, which can't be right.
Since I was running approx 8 Gallons every minute for 13 minutes.

Another adjustment needed somewhere in the code?

mighty ledge
#

8 gallons per min seems high

lofty mason
#

I measured all my sprinkler zones at 9-14 gpm πŸ‡ΊπŸ‡Έ

cyan shale
#

So my Gallons used during that hour, should be very least at 104 Gallons totaling... So somwhere in the consumtion sensor, it is not doing the total correclty

mighty ledge
#

Well 13 * 8 / 60 is 1.733

#

You sure that we should have divided that value by 60? You sure your units are correct on the integration sensor? Iirc it defaults to hours

cyan shale
#

Ahhh, ok, so it defaults to hours.. yes... I

#

Hmm...

#

Dividing it shows correct GPM number, otherwise it will be Gallons per hour

#

Any way I can keep that ?? but in the consumption sensor, change it back?

#

If not, I can just remove the division by /60 ... and then change the nomenclature to say "gal/h"

lofty mason
#

If you want to keep the sensor in gpm, you need to delete and recreate the riemann with the correct time unit (minutes instead of hours)

#

well actually if you added it in yaml I'm not sure if you need to delete. If you added it in the UI you need to delete it. maybe you can just update the yaml

cyan shale
#

If I wasnted to keep having it in GPM (which is how it is now)... can I get my consumption sensor to multiply it back to 60? If that's too cloodgy, then I'll just keep it in GPH

lofty mason
#

what's in the past can't be modified

#

you can try to fix it going forward by adding the unit_time

cyan shale
#

Sorry, i meant going forward

lofty mason
#

what happens if you add unit_time: min and reload it, and test again

#

does it work?

cyan shale
#

Sorry, where do I add unit_time: min

#

Here is the code snippet again

lofty mason
#

in the integration settings:

  - platform: integration
    unique_id: [CREATE ONE FROM https://www.uuidgenerator.net]
    source: sensor.gpm_water_consumption
    name: Water Consumption
    round: 2
    method: left
    unit_time: min
cyan shale
#

Ahh ok, let me check...

#

and I suppose, I'll only be able to see the update in the next hour block? since energy dashboard has it for every hour, or is there a way to check that instantly? (Sorry for being a complete novice)

lofty mason
#

well you can see if the integration sensor increments by the correct value

#

if you consume 100 gals you should see it jump by 100

#

it won't show up in /energy till the next hour though

cyan shale
#

ok let me run some faucets ( I know they report correctly in my GPM template sensor). And then see how they populate in my energy meter

#

*energy dashboard

#

Ok running a test. Kitchen faucet at 2.2 GPM (I'm going to run it for a few minutes). And then I'll check my energy dashboard in 27 mins

cyan shale
#

It seems to have done the trick, but it was midway in the hour. So I'm going to test again for the full hour, and report back.
But seem like that may have done the trick πŸ™‚ πŸ™‚ ...

cyan shale
#

@lofty mason , that did it !!!!!!!! It works perfectly now... reporting the correct total gallons. ----- just had to add that unit_time: min

silver pewter
#

Hi all! Anyone knows how to add this "timestamp_custom('%H:%M')" to this: "{{ now() + timedelta(hours=6) | }} "
I only want Hour : Minutes πŸ˜›

fickle kettle
#

You want to format the time (in 6 hours) as hh:mm?

silver pewter
haughty breach
#
{{ (now() + timedelta(hours=6)).strftime('%H:%M') }}
silver pewter
fickle kettle
#

Hehe I had precisely the same, was just testing in developer tools πŸ™‚

silver pewter
#

Hehe, Thank you too lyricnz πŸ‘ πŸ™

fickle kettle
#

You can play with this too at /developer-tools/template
And read the two pages linked (jinja2 templates, and HA extensions to them)

silver pewter
#

Okok, thanks! πŸ™‚

fickle kettle
edgy wave
#

Is there a function to translate value (like "Fan high") from a input_select to a entity_id-friendly value (like "fan_high")?
I would like to do something like:
entity_id: scene.{{ convert(states('input_select.fan')) }}

marsh cairn
#

You could use |replace('Fan high','fan_high') or if, elif, else, endif.

marble jackal
#

"Fan high" | slugify

#

so in your case:

entity_id: scene.{{ states('input_select.fan') | slugify }}
marsh cairn
#

Sounds like a snail, but even better than replace. Learned something new πŸ‘

mighty ledge
#

it makes things into a 'slug'

edgy wave
#

Thanks @marble jackal that's perfect.

silent vector
#

How would I do an exact match from a list of dictionaries.

varfoo:
  - type: ['santa','eve']
    state: 'on'

If I did a select search ('s') I would end up matching ('santa') I want to match the entire string to avoid partial matches of even 1 character then map state

mighty ledge
#

selectattr

#

using in

#

or search

silent vector
#

varfoo | selectattr('type','in','santa') wouldn't work. Because type is a list.

#

But search does

#

Interesting the difference between select('search','santa') vs selectattr('type','search','santa')

marble jackal
#

use contains

#

varfoo | selectattr('type','contains','santa')

silent vector
#

What's the difference between that and search

marble jackal
#
{% set my_list = ['food', 'barbecue'] %}
{{ my_list is contains 'bar' }} # False
{{ my_list is search 'bar' }} # True
{{ my_list is contains 'food' }} # True
mighty ledge
#

FYI all of this won't exist in ansible πŸ˜‰

silent vector
mighty ledge
#

search won't for sure

plain magnetBOT
#

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

mighty ledge
#

because you always ask ansible questions, it doesn't take a rocket scientist to figure out when you're not asking about HA

thorny snow
silent vector
#

Is search does. I use it all the time. And selectattr search or select search.

I do ask some ha questions lol my most recent questions were ha related.

mighty ledge
#

although I do have a aerospace engineer degree, so maybe it does

#

the behavior of search in ansible will be different than HA

silent vector
#

Probably but it does work I never tried to test the differences in behavior between them and I didn't even realize contains would work in Ansible either.

mighty ledge
#

I would assume they are similiar, however they are completely different functions as both are implemented separately.

#

that goes for contains too

#

the HA extensions were built by HA, the ansible extensions are built by whoever made ansible

silent vector
mighty ledge
#

see what I just said

#

what @marble jackal is saying only applies to HA

#

@thorny snow most likely a UTC offset issue. use datetimes, don't use timestamps.

silent vector
#

I didn't try the is contains but I know I use is search all the time.

The difference he showed is the same behavior when doing selectattr('type','search','santa'
selectattr('type','contains','santa')

contains is exactly what I was looking for.

mighty ledge
#
{% set nr = state_attr('sun.sun','next_rising') | as_datetime | as_local %}
{% set ns = state_attr('sun.sun','next_setting') | as_datetime | as_local %}
{% set nr = nr - timedelta(days=1) if nr > ns else nr %}
{% set interval = 8 %}
{% set seconds = (ns - nr).total_seconds() / interval %}
{% set ns = namespace(items=[]) %}
{% for i in range(interval) %}
  {% set time = nr + i * timedelta(seconds=seconds) %}
  {% set ns.items = ns.items + [{'start': time - timedelta(hours=1), 'end': time + timedelta(hours=1)}] %}
{% endfor %}
{% set t = now() %}
{% set trigger = ns.items | selectattr('start', '<=', t) | selectattr('end', '>=', t) | list | first | default %}
Window Begin: {{ trigger.start }}
Window End:   {{ trigger.end }}
#

@thorny snow ^

#

had to make edit, forgot a character

#

you can probably also just use the loop to find the current interval as well.

#

It'd be nice if we had linspace, but alas

thorny snow
#

That's how I changed it now:

#
{% set nr = as_datetime(state_attr('sun.sun','next_rising')) | as_local %}
{% set ns = as_datetime(state_attr('sun.sun','next_setting')) | as_local %}
{% if nr > ns %}
  {% set nr = nr - timedelta(hours = 24) %} 
{% endif %}
{% set hours_difference = (ns - nr) %}
{% set interval_hours = hours_difference / 8 %}
{% set match = false %}
{% for i in range(8) %}
  {% set start_time = nr + (i * interval_hours) %}
  {% if ((start_time - timedelta(seconds=30)) <= now()) and (now() <= (start_time + timedelta(seconds=30))) %}
    {% set match = true %}
  {% endif %}
{% endfor %}
{{ match }}
#

Fingers crossed that it triggers

mighty ledge
#

So, just keep in mind that it will always be true

#

so it won't trigger

#

@thorny snow ^

#

ah, nevermind

thorny snow
#

It shouldn't be.

mighty ledge
#

you changed the timedelta

#

in the match

#

You may have to increate the timedelta to 1 minute

thorny snow
#

Match is false by default, and if the current time falls within a 60 second window of the interval time, it is changed to true.

mighty ledge
#

now() only updates once a minute on the minute

#

or 31 seconds

#

actually your code wont work

#

due to scoping

#

you have to use namespace

thorny snow
#

Like so?

{% set ns = as_datetime(state_attr('sun.sun','next_setting')) | as_local %}
{% if nr > ns %}
  {% set nr = nr - timedelta(hours = 24) %} 
{% endif %}
{% set hours_difference = (ns - nr) %}
{% set interval_hours = hours_difference / 8 %}
{% set ns = namespace(match = false) %}
{% for i in range(8) %}
  {% set start_time = nr + (i * interval_hours) %}
  {% if ((start_time - timedelta(seconds=30)) <= now()) and (now() <= (start_time + timedelta(seconds=30))) %}
    {% set ns.match = true %}
  {% endif %}
{% endfor %}
{{ ns.match }}```
#

Jinja is annoying.

mighty ledge
#

yeah that might work

#

this would def work

#
{% set nr = state_attr('sun.sun','next_rising') | as_datetime | as_local %}
{% set ns = state_attr('sun.sun','next_setting') | as_datetime | as_local %}
{% set nr = nr - timedelta(days=1) if nr > ns else nr %}
{% set interval = 8 %}
{% set seconds = (ns - nr).total_seconds() / interval %}
{% set ns = namespace(items=[]) %}
{% for i in range(interval) %}
  {% set ns.items = ns.items + [ (nr + i * timedelta(seconds=seconds)).replace(second=0, microsecond=0) ] %}
{% endfor %}
{{ now().replace(second=0, microsecond=0) in ns.items }}
#

and you can view the times by using {{ ns.items }} to see what minute it will trigger.

plain magnetBOT
honest wing
#

Issue resolved :)

patent finch
#

I am working on getting a sensor that tracks the max value of a moisture meter over the course of 24 hours

sensor:
  - platform: statistics
    name: Max_Soil_Moisture
    entity_id: sensor.soilsensor_moisture_wc
    state_characteristic: value_max
    max_age:
      hours: 24
    sampling_size: 2000```
#

but after letting this run for awhile i do not see this sensor getting created in developer tool stats page

dry narwhal
#

Is there a workaround or a way to make area() return the friendly names?

#

Already tried things like {{ areas() | map(attribute='name') | list }} with no success

marble jackal
#

{{ states | map(attribute='entity_id') | map('area_name') | unique | select() | list }}

#

Oh, this indeed only lists the areas with entities assigned

#

So this works
{{ areas() | map('area_name') | list }}

icy jay
#

Hi,

id like to create a template sensor, thats β€šonβ€˜ if theres any entities with β€šswitch.schedule_***β€˜

How could i do this?

inner mesa
#

{{ states.switch|selectattr('object_id', 'match', 'schedule_')|list|length > 0 }}

icy jay
#

Oh that works perfectly! Thank you so much!

dry narwhal
#

Oh no, I am messing up JS and Jinja again. πŸ˜“

#

I will never fully grasp where to use Jinja, Javascript and Python. Why even have all three πŸ˜„

#

Anyway, now I am stuck again converting, if even possible

      - area: |-       //would be working if I can convert the jinja expression for areas to JS (I think it is JS)
          ${ 
            if (states['input_select.dropdown_areas'].state == '-- - --')
              { '' }
            else
              { areas() | map('area_name') | select('ne', states['input_select.dropdown_areas'].state) | list }
            }
      - name: |-     //working syntax
          ${ 
            if (states['input_select.dropdown_wildcards'].state == 'Power')
              { '*Light*' }
            else
            { '' }
            }
inner mesa
#

yeah, that's quite a jumble of disparate things πŸ™‚

#

I don't know what syntax like { '*Light*' } is supposed to do, but while I'm sure you could rewrite some of that Jinja in JS, you may just be better writing a template sensor with the Jinja and using that entity in your JS

dry narwhal
#

I am using it in auto-entities with config-template card to create a filter.
So { '*Light*'} just returns the string *Light* to auto-entities, which then lists all entities with Light in their friendly_name.

I am trying to return a list of area names that do not match the input_select.dropdown_area and have those excluded.

#

Initially I used the include filter but I ran into the problem that entities that are not assigned to an area are not filtered (like in jinja).

#
                area: |-
                  ${ 
                      if (states['input_select.dropdown_areas'].state == '-- - --')
                        { '*' }
                      else
                        { states['input_select.dropdown_areas'].state }                   
                    }
#

I will also ask in auto-entities thread in the forum.
Maybe someone know if I can use a NOT in an exclusion template.

honest wing
cerulean karma
#

hey, what is the correct syntax to use a "if - elif - else" statement in a oneline print {{ }} ?

#
      {{ "yellow" if x=="b"
         "red"  elif x=="a"  
          else "grey" }}
cerulean karma
#

something like that, but that does not work

silent seal
#

You're after the immediate if, or iif

cerulean karma
#

ah great, thanks πŸ™‚

silver cape
#

Hi can someone help me on accessing the calendar events ? I can get a list for all my calendars but not for a specific one:

{{ states.calendar  | list }} --> works

{{ states.calendar.family_calender  | list }} --> does not work :(

How would I get the same for a specific one

cold canopy
#

Yikes, I am a new user and need help with a template sensor. Would it be okay to post here? I already created a forum item on the site but joined discord to see if i can get some assistance. Please πŸ™‚ ?

#

I am not sure if the gurus here will yell at me if its not the right spot for it. i am new here, plz advise.

plain magnetBOT
#

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

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

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

Thanks, here goes.

plain magnetBOT
#

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

lofty mason
#

In what way does it not work?

marble jackal
#

do you have a sensor now with state: unknown?

cold canopy
#

When i get new emails relevant to the config, sensor does not change state at all. Stays unavailble.

#

yes @marble jackal just stays unknown even when relevant emails coming through

marble jackal
#

if it remains unknown it doesn't trigger

#

if it is unavailble it did trigger, but the template failed

cold canopy
#

My apologies, its actually unavailable @marble jackal

lofty mason
#

should there be a final {% else %} clause?

#

it seems possible for that to exit with no value

marble jackal
#

that could be a cause yes

cold canopy
#

I am trying to figure out how to upload an image here...

lofty mason
#

it would be good for your debugging to have an else nonetheless, just set it to some string so you can know if that's what's happening or not

cold canopy
#

okay i did that, reloaded yaml and now the sensor without a relevant email to the config, shows null value basically

plain magnetBOT
cold canopy
#

OH, Amazing That worked somehow. the above code works. I changed the email to my email and sent relevant test to my inbox, and i can see the state changes

#

Weird how the example in the HASS documentation does not have that last {% else %}
But that seems to the issue here, Correct?

lofty mason
#

I don't think that would explain what you're seeing.

#

It doesn't need to have an else, that just allows you to return a value if it didn't match the first two conditions

cold canopy
#

πŸ€” hmm weird then. Why does it work now when before it did not?

lofty mason
#

not sure

cold canopy
#

i literally just changed that last else as you all suggested

#

nothing else changed

lofty mason
#

impossible for me to say

cold canopy
#

HASS Goblin Magic?

lofty mason
#

you could take it away and try the test again

#

or just leave it if you're happy

cold canopy
#

Yes will try testing more.

THANK YOU SO MUCH - i appreciate you taking time out of your day to help me. πŸ™ Thanks

uneven pendant
#

I have a command line sensor,
Command failed (with return code 255): ssh -i /config/.ssh/brendyn -o 'StrictHostKeyChecking=no' pizza@192.168.51.25 "type interactive.txt"

#

if the host it targets is offline, it produces that failure

#
command_line:
  - sensor:
        name: Brendyn PC Interactive
        command: ssh -i /config/.ssh/brendyn -o 'StrictHostKeyChecking=no' pizza@192.168.51.25 "type interactive.txt"
        scan_interval: 60
        value_template: >-
            {% if value == "yes" %}
            True
            {% else %}
            False
            {% endif %}
#

How can i get it to display FALSE instead of "unknown"

#

or unavailable (don't recall which)

#

which is what it shows now

#

I suppose my other option would be to just make a template sensor to parse this sensor and make "True" be on, and "unavailable" be off.

buoyant hare
#

Hi, before creating template sensors, can you help me understand if I should learn the new or the legacy format of defining template sensors in yaml ? The relevant page in HA docs https://www.home-assistant.io/integrations/template/ suggests that the platform (template) should be designated on the higher level of the yaml hierarchy, under which I list the sensors.
The other approach (listing sensors on a higher level of the yaml hierarchy and assigning the Template platform to each) is stated as legacy.
However, sample and tutorial on the new format is scarce. My focus currently is only calculating values from existing sensor values. I have successfully done that in the new format without any other parameters than what is in the samples but I am lost when I need to add other fields.
Thank you!

mighty ledge
#

so, look at the docs to determine which fields you need and just place them at the same level as your state

dry narwhal
#

I have a question on what config-template card returns when it is used in a frontend card.
So, I am subtracting two values (converted to timestamps) and I would like the returned value to be 1 but it is '1', so seemingly a string. Why is that and can I change that behavior?

{ ((states['sensor.timestamp'].state-states['input_datetime.start_datetime'].attributes.timestamp)/60/60).toFixed(2) }
inner mesa
#

all states are strings

dry narwhal
inner mesa
#

it automatically converts from a string to a number?

#

seems doubtful

#

I always use parseFloat()

#

or whatever JS magic you need to convert

dry narwhal
#

Well, it does calculate a number from the above template. So it seems to "convert" to a number and then subtract.

inner mesa
#

well, type seems to be your issue

#

you have my suggestion πŸ™‚

dry narwhal
#

Hmmm. Strange. So maybe it is returning a time delta rather than a true number.

dry narwhal
inner mesa
#

BTW, this channel is for Jinja templating. Further JS/frontend-type questions should go to #frontend-archived

dry narwhal
#

Even though it is Javascript templating and not really frontend layout stuff?

inner mesa
#

yes

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

dry narwhal
#

Okay, my bad.

#

I usually get sent here when I ask about templating.

inner mesa
#

I don't know where you put that Number() call, but it should have gone here: Number(states['sensor.timestamp'].state) or parseFloat(states['sensor.timestamp'].state)

#

point is, fix the type of the data you're using in the expression, rather than doing weird math and then forcing the result to a type

#

anyway, if it's working for you, πŸ‘

silent vector
#

If you can do listthing is search('foo|bar') is there a way to do an is search with an and instead of an or?

inner mesa
#

{{ "foobar" is search('(?=.*foo.*)(?=.*bar.*)') }}

dry narwhal
dry narwhal
upper basalt
#

how can i reject an entity based on rejectattr when listing entities in an integration? this doesnt work, as it doesnt reject entities that are playing ...

{{integration_entities('cast') | rejectattr('state','in',['unknown','unavailable','playing']) | list }}

Trying to make a smarter doorbell-automation that doesnt stop music that is playing πŸ˜›

marble jackal
#

You only have the entity_ids when using integration_entities()

#

So either use expand() or use the is_state test

#

like this

{{integration_entities('cast') | reject('is_state',['unknown','unavailable','playing']) | list }}
upper basalt
#

thanks man!

buoyant hare
upper basalt
inner mesa
#

You're already rejecting some entities there

upper basalt
marble jackal
#

Sorry why are you first expanding it, and then mapping it back to entity_ids so you had the result you started with

upper basalt
marble jackal
#

{{ integration_entities('cast') | reject('is_state',['unknown','unavailable','playing']) | reject('in',['media_player.utebod','media_player.klokke_hub'])| list }}

#

But when you map it back to entity_id, you don't have attributes anymore, so you can't use rejectattr()

#

You only have a list of entities, not state objects

inner mesa
#

You need to keep track of whether you have a list of state objects or entity_ids at each point

upper basalt
#

okay, so its the order I had in my template that messed up

#

but that did exacly what I needed, TheFes, thank you again!

inner mesa
#

I suggest building it a step at a time in devtools -> Templates and pay attention to the output

upper basalt
#

yeah good point πŸ™‚

sacred sparrow
#

is there a better way to do this for a binary sensor:

        {% set season = states('sensor.season_astronomical') %}
        {% if season == winter and states('sensor.living_room_feels_like_temperature')|float >= 23.0 or states('sensor.view_plus_feels_like_temperature')|float >= 24.0 %}
          on
        {% elif season == spring and states('sensor.living_room_feels_like_temperature')|float >= 23.0 or states('sensor.view_plus_feels_like_temperature')|float >= 24.0 %} 
          on 
        {% elif season == summer and states('sensor.living_room_feels_like_temperature')|float >= 23.0 or states('sensor.view_plus_feels_like_temperature')|float >= 24.0 %}
          on 
        {% elif season == autumn and states('sensor.living_room_feels_like_temperature')|float >= 23.0 or states('sensor.view_plus_feels_like_temperature')|float >= 24.0 %}
          on 
        {% else %}
          off
        {% endif %}```
#

for some reason its showing the information for {% elif season == spring and states('sensor.living_room_feels_like_temperature')|float >= 23.0 or states('sensor.view_plus_feels_like_temperature')|float >= 24.0 %} even though sensor.season_astronomical is 'winter'

inner mesa
#

because you didn't quote the seasons

#

it's comparing season against variables that aren't defined

sacred sparrow
#

As in β€˜spring’ etc?

inner mesa
#

as in 'string'

sacred sparrow
#

state: >
{% set season = states('sensor.season_astronomical')|string %}

inner mesa
#

that's not at all what I said

storm cloud
#

How to use local vaiables in a template

haughty breach
# sacred sparrow is there a better way to do this for a binary sensor: ``` state: > ...

One way to do it that is less repetitive would be to set up a few variables and use a dictionary:

  {% set l = states('sensor.living_room_feels_like_temperature')|float %}
  {% set v = states('sensor.view_plus_feels_like_temperature')|float %} #}
  {% set season = states('sensor.season_astronomical') %}
  {% set l_v_mapper = {"winter": [23,24], "spring": [23,24], "summer": [23,24], "autumn": [23,24] } %}
  {% set temps = l_v_mapper.get(season) %}  
  {{ l >= temps[0] or v >= temps[1] }}
torpid crag
#

Hi All, Just checking... will this work as expected?
service: input_text.set_value data: value: > {% if trigger.id == 'peak' %} Weekday Peak {% elif trigger.id == 'offpeak' %} Weekday Off Peak {% elif trigger.id == 'weekend' %} Weekend Off Peak {% else %} None {% endif %}

haughty breach
#

Not without a target... πŸ™ƒ

lucid thicket
#

@rustic agate try:
The battery level is {{ trigger.to_state.state }}%

rustic agate
#

Doesnt work :/

#

I'll research i later i'm tiredd but thanks for that, it does tell me i dont need to make a template i can use that in the message at least i think

cedar turret
#

is there any documentation on the available functions/variables/etc?
I could only find https://www.home-assistant.io/docs/scripts/#variables which seems to only have examples, which happen to contain is_state, wait.completed, and states
However, I want to find the attribute (specifically a lightbulb temperature)

inner mesa
#

Yes, in the channel topic

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

dry narwhal
#

Good morning everyone πŸ™‚
I am stuck in a little Jinja problem.
I would like to use nested for loops to create a list of entities.

#
{% for ENTITY_ID in states.sensor | selectattr('name','search',states['input_text.text_wildcards'].state) | map(attribute='entity_id') | list -%}
    {% if states['input_text.text_wildcards_2'].state != '' %}
      {% for ENTITY_ID_2 in states.sensor | selectattr('name','search',states['input_text.text_wildcards_2'].state) | map(attribute='entity_id') | list -%}
        {% set ENTITY_ID = ENTITY_ID + '\n' + ENTITY_ID_2 %}
      {%- endfor %}
    {% endif %}
{{ ENTITY_ID }}
{%- endfor %}
#

(and more input_texts will follow once it works as wanted)

#

My problem is, that the ENTITY_ID is appended inside the IF expressions but the final ENTITY_ID only has the outer for loop ENTITY_ID.

#
sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0    // inner for if
sensor.schenker_vision_16_pro_energy_power    // inner for if
    
    
    
      
sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0 //out for
      
        sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1    // inner for if
sensor.schenker_vision_16_pro_energy_power    // inner for if
    
    
    
      
sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1 //outer for
#

Do I need some kind of return statement to make the inner information available to the outside?

#

...or maybe namespace....

#

Okay, namespace is the key.
Why can't I remove duplicates from the ns.list with `| uniqueΒ΄?

mighty ledge
#

You can but you need to re set the value. Unique is an operation, it doesn’t alter existing memory

dry narwhal
#

Is there a way to filter the final ns.list then?

#

Tried set(ns.list) without success

mighty ledge
#

Yes, just output the value from unique or set it again

#

That’s not how set works

#

See your other examples of set

#

On mobile, can’t write the code.

dry narwhal
#

sorry, I meant {% list(set ns.list = ns.list + [ item.entity_id ]) %}

mighty ledge
#

Yeah… that’s still not correct

dry narwhal
#

I read that list(set()) removes duplicates from lists automatically

mighty ledge
#

But you’re still using it wrong

dry narwhal
#

Where would the unique go then? Because it cannot go inside the for item expression as the duplicates are created during ns.list filling

mighty ledge
#

And I’m not sure if set in jinja is the same as set in python

#

It’s a filter, it goes at the end

dry narwhal
#

I know, but the end of where?

#

{{ ns.list |unique }} does not work

mighty ledge
#

That will work

#

If it’s not,it doesn’t do what you think it does

dry narwhal
#

dev tools

<generator object do_unique at 0x7f821eace0>
mighty ledge
#

Yes that’s a generator

#

That’s what it returns, if you want a list you need to also use list after

dry narwhal
#

🀦

#

Now lets see if I can feed my card with that or if I need a different final output, like strings with line break or something.

#

I need to convert to strings 😦

#

Strings with line breaks, probably

#

Nope, worked by just looping through items in ns.list.

#

Thank you @mighty ledge !!!

keen swan
#

Hi all, really hop[e some can help,
I want have a helper that i can set to say 19 Helper is input.number
So want to set a trigger in an automation that will only trigger if there value is 0.5 above my helper number
I have something like this, but it is not working, and i dont understand the "value_template"

platform: numeric_state
entity_id: sensor.sonoff_b09203993_temperature
above: "{{ (states('input_number.office_temp_cool_target') | float +0.5) }}"
id: Above Cool Temp

Please help

marble jackal
#

You need to either use a value_template in your numeric_state trigger, or a template trigger.
You can't use templates in the above field

haughty breach
#
platform: numeric_state
entity_id: sensor.sonoff_b09203993_temperature
above:  0.5
value_template: "{{ state.state|float(0) - states('input_number.office_temp_cool_target')|float(0) }}"
id: Above Cool Temp

Or, use a template trigger:

platform: template
value_template: |
  {{states('sensor.sonoff_b09203993_temperature')|float(0) >
  (states('input_number.office_temp_cool_target')|float(0) + 0.5)}}
id: Above Cool Temp
marble jackal
#

The first one will only trigger on changes of the sonoff sensor, the second one will also trigger if you change the input number

keen swan
#

@haughty breach thank you so much, this is awesome... Now to re-wite a bunch of automations πŸ™‚

dry narwhal
#

Does anybody know how to filter a namespace list by area?
I think they no longer have properties like entity_id, so I cannot use the classical |selectattr('entity_id', 'in', area_entities('Bedroom'))

#

Line I would like to apply the filter in:
{% set ns.list = ns.list | unique | list %}

#
Result type: list
[
  "sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0",
  "sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1",
  "sensor.schenker_vision_16_pro_energy_power"
]
inner mesa
#

just use select()

#

{{ ns.list|select('in', area_entities('Bedroom'))|list }}

dry narwhal
#

Thank you RobC, but that does not filter out entities without an assigned area.

#

Tried adding
| reject('in', area_entities('undefined')) but that also does not filter out entities without an area assignment

#

P.S.: 'equalto' instead of 'in' also does not work.
Somehow I need to reject entities that are not assigned to an area.

inner mesa
#

That's a new requirement

dry narwhal
#

Well, I would say that filtering by area means "only those in that area".

inner mesa
#

There's no area called 'undefined'

dry narwhal
#

An undefined entity is not in that area.

dry narwhal
inner mesa
#

That's just a word

dry narwhal
#

Tried with an without quotes

inner mesa
#

then it's just a variable

dry narwhal
#

What is the area_name of "no area"?

inner mesa
#

there isn't one, it just won't be in the list based on the template I gave

dry narwhal
#

It will be. That'S the problem

inner mesa
#

it's only outputting a list of entities that are in that area

dry narwhal
#

Nope

inner mesa
#

alright

dry narwhal
#

In the area and undefined

inner mesa
#

that is not true

#

it's literally only select entities from that list that are in the "bedroom" area

#

it's a very simple template

#

I can only conclude that you did something else

dry narwhal
#

I will re-check the rest of the template immediately. Because rejecting entities in that area worked. But selecting only in did not.

#

I will double check everything

#

I sincerely apologize. I found a placement mistake that led to another iteration of a loop re-adding the one entity that was not assigned to an area 😟

inner mesa
#

Np, I figured it was something like that

dry narwhal
#

It is tricky to stay on top of templating in cards without comments etc.
Is there any way of commenting in the frontend?
I tried ## and {# ... #} but both broke the card.

#

Also, why is
{% set ns.list = ns.list.remove(states['input_text.apexcharts_entity_exclude'].state) %}
unsafe?
I just wanted to remove the entry matching that input_text from the namespace list 😦

inner mesa
#

You have to reject it

dry narwhal
#

But then I need a property to reject, don't I?
I can't just | reject(states['input_text.apexcharts_entity_exclude'].state) because that is not a known property of the list.

inner mesa
#

Then what did you want with remove?

#

A list has no keys

dry narwhal
#

The namespace list contains a bunch of entity_ids as strings.
I want to remove the string in that list that matches the string of states['input_text.apexcharts_entity_exclude'].state

inner mesa
#

Right, reject it

#

This is the same thing you already did

dry narwhal
#

I thought so, but I am overlooking something.
{% set ns.list = ns.list | reject(states['input_text.apexcharts_entity_exclude'].state) | list %}
returns
TemplateRuntimeError: No test named 'Sony KD-75XF9005_Naim Audio AV ENERGY Power 1'.

inner mesa
#

You didn't provide a test

#

You need 'eq'

dry narwhal
#

So simple 😦

#

MAybe I should go to bed soon πŸ˜‰

#

Is it easy to get the friendly_name of an entity_id? Or should I not even try that as my final task of the day?

inner mesa
#

It's an attribute

#

So, easy

dry narwhal
#

{{ ['sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0'] | map('state_attr', 'friendly_name') | list }}

#

got it

inner mesa
#

if that's really all you wanted, then that's a pretty complicated way of saying {{ state_attr('sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0', 'friendly_name') }}

#

or the better version: {{ states.sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0.name }}

dry narwhal
#

Interesting.
Does that work as simply the other way around?
So entity_id from friendly_name?

inner mesa
#

friendly_name is just an attribute that some (but not all) entities have and isn't unique

#

guessing at what you really mean, you can get a list of entity_ids that have a friendly_name that matches some string

dry narwhal
#

I mean that if I have a friendly_name, can I find out the matching entity_id?
(these do not work, but maybe show what I mean)

    {{ ns.list | selectattr('entity_id','search',states['input_text.apexcharts_entity_exclude'].state) |list }}

    {{ states['input_text.apexcharts_entity_exclude'].state.entity_id }}

with
states['input_text.apexcharts_entity_exclude'].state = Sony KD-75XF9005_Naim Audio AV ENERGY Power 0

inner mesa
#

like I said, they're not unique

#

so the best that you can get is a list

dry narwhal
#

Since mine are unique, a list would be fine πŸ™‚

inner mesa
#

so, again, it's just an attribute

#

an exhausitve search is easy

#

{{ states|selectattr('attributes.friendly_name', 'defined')|selectattr('attributes.friendly_name', 'eq', 'whatever')|map(attribute='entity_id')|list }}

dry narwhal
#

Ah, never in a million years!
But I understand what you did there. You first got all friendly names from all states that have a friendly_name as an attribute and then search those for the entity_id string and map them ....

#

I/we must seem like monkeys to you πŸ˜„ πŸ˜„ πŸ˜„

inner mesa
#

it's just a common idiom

#

the same thing is used to find entities matching any number of criteria

dry narwhal
#

Things seem clear when I see them, but then I try to combine things I know and things I learned and then I get 90 % of where I need to go and then the smallest details derail the process.

I spent the last 20 min in dev tools trying to insert this

states|selectattr('attributes.friendly_name', 'defined')|selectattr('attributes.friendly_name', 'eq', states['input_text.apexcharts_entity_exclude'].state)|map(attribute='entity_id')|list
#

here

{% set ns.list = ns.list | reject('eq', 'insert here') | list %}

to filter out strings from the ns.list that match the entity_id I derived from a friendly_name.
I don't know if it fails because I am searching for a list in a list or if I simply have a different mistake.

{% set ns.list = ns.list | reject('eq', states|selectattr('attributes.friendly_name', 'defined')|selectattr('attributes.friendly_name', 'eq', states['input_text.apexcharts_entity_exclude'].state)|map(attribute='entity_id')|list) | list %}
#

Because

{{ ns.list }}
{% set ns.list = ns.list | reject('eq', states|selectattr('attributes.friendly_name', 'defined')|selectattr('attributes.friendly_name', 'eq', states['input_text.apexcharts_entity_exclude'].state)|map(attribute='entity_id')|list) | list %}
{{ns.list}}

{{ states|selectattr('attributes.friendly_name', 'defined')|selectattr('attributes.friendly_name', 'eq', states['input_text.apexcharts_entity_exclude'].state)|map(attribute='entity_id')|list }}

returns

['sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0', 'sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1', 'sensor.office_energy_power', 'sensor.lightswitch_office_energy_power_0', 'sensor.lightswitch_office_energy_power_1']

['sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0', 'sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1', 'sensor.office_energy_power', 'sensor.lightswitch_office_energy_power_0', 'sensor.lightswitch_office_energy_power_1']

['sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1']
#

So the entity_id is found from the friendly_name but it is not removed from the ns.list. The filtered ns.list still matches the initial one.

#

It was the 'eq' !
I needed to search 'in' 😭

#

I am going to be now. Finally.

In case anybody has a sleepless night I would be curious what the syntax would need to be for this:

{% set ns.list = ns.list | reject('in', states|selectattr('attributes.friendly_name', 'defined')|selectattr('attributes.friendly_name', 'in', states['input_text.apexcharts_entity_exclude'].state)|map(attribute='entity_id')|list) | list %}

to also work for partial matches of states['input_text.apexcharts_entity_exclude'].state of the friendly_name.

So, e.g. if the real friendly_name is Sony KD-75XF9005_Naim Audio AV ENERGY Power 1
but states['input_text.apexcharts_entity_exclude'].state = 'Sony.*ENERGY Power 1'

boreal oasis
#

Hi, I have a binary sensor (ESPhome) called "Doorbell Sound Level" which turns to "on" if the sound sensor detects sound on the door. I have several automations for it. But I want to see the last "doorbell time" in the dashboard. I asked ChatGPT and nothing works very well. I can use a template which shows ANY change (off and unknown too), but I only want to see the last datetime for "on". Could you help me? I'm sure someone have a snippet in his own HA. Thanks. πŸ™‚

marble jackal
#

A trigger based template sensor which uses now() as it's state and triggers when your doorbell sensor turns on

dry narwhal
#

Good morning everyone
is it possible to check if a complete string is a reverse match for the incomplete string containing wildcards?

So I have Sony.*ENERGY Power.* and want to check if "Sony KDXF Energy Power 1" would be a match for that search string.

It sounds backwards, but that is the way the data is available πŸ™‚

plain magnetBOT
#

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

dry narwhal
#

The final if is supposed to remove entities the user wants to exclude out of the generated list.
So for instance if the search was for all power sensors but the user wants to exclude the one with "useless" in the name πŸ™‚

marsh cairn
#

I would think about something like

|selectattr('entity_id', 'search', 'energy_power')```
That should also be possible with the friendly name (not sure if name or attributes.name would be needed).
But one of our Ninjas might have a better idea πŸ˜†
dry narwhal
#

So I would first need to split the exclude string into parts and then check for each part

marsh cairn
#

That would me my approach - doesn't have to be the best one

#

I'm no templating expert

dry narwhal
#

The problem is still that I would have
"create full_string | select(full_string, 'in', part)"
Would that work?

marsh cairn
#

You shouldn't need to have to manipulate the name string

#

The first selectaddr looks for everything containing sony and the second one selects the remaining ones containing energy_power

#

At least, if I got you right

dry narwhal
#

The problem is that the user inputs the friendly name and the ns.list contains entity_ids.
So I first need to convert the ns.list to a list of friendly_names and then reject the exclude_string from that friendly_name list.

#

Do you know if it is possible to have an if expression inside a pipe(?) ?
{{ states | select() | if (something) then reject() | map() | list }}

#

So only if the condition is met the rejection is performed. And it not, that part will be ignored and it will continue with the mapping

marsh cairn
#

Just to keep it simple - don't your entity_ids also contain those string parts? Meaning sony and energy_power?

dry narwhal
#

Yes, but in different case. Or will that not matter?

#

But I could split into parts on space and then convert to lower...

#

good idea @marsh cairn

marsh cairn
#

But as I said. One of the Ninjas might have a better solution.

haughty breach
# dry narwhal So only if the condition is met the rejection is performed. And it not, that par...

What about something like:

{% set ent_list = states.sensor | selectattr('name','search', states('input_text.apexcharts_entity_wildcard')) | map(attribute='entity_id')| unique | list %}

{% if states('input_select.apexcharts_dropdown_areas') != '-- - --' %}
  {% set area_list = area_entities(states('input_select.apexcharts_dropdown_areas'))%}
  {% set ent_list = ent_list | unique | select('in', area_list) | list %}
{%- endif %}

{% if states('input_text.apexcharts_entity_exclude') != '' %}
  {% set excluded = (states('input_text.apexcharts_entity_exclude'))|replace(', ', '|') %}
  {% set ent_list = expand(ent_list) 
  | selectattr('attributes.friendly_name', 'defined')
  | rejectattr('attributes.friendly_name', 'search', excluded, ignorecase=True)
  | map(attribute='entity_id')|list %}
{%- endif %}
{{ ent_list }}
dry narwhal
marble jackal
#

Reverse how? I don't see it being sorted anywhere

plain magnetBOT
#

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

dry narwhal
#

The "sorting" is done by the user who has multiple input_text fields and the result should be in the order that he enters the search strings.
(I had left out input_text.wildcard2-5 because it would have just made the code even longer with zero benefit)

open flower
#

I have a bug when creating a template sensors from the UI. Error message is: 'g/mΒ³' is not a valid unit for device class 'humidity'; expected '%'. But air humidity can also be expressed in gramms of watervapour per cubic meter of air ...

#

Where should I report this bug?

compact rune
#

Probably a feature request since relative and absolute humidity are fairly different and only relative is currently supported

lucid thicket
#

if I'm checking whether a key exists in a nested dictionary, is there a way to check several layers deep without having to check each layer one at a time?

#

For example:

{% set mydict = {"nest1":"val1"} %}
{{ mydict.nest1.nest2 is defined }}

results in false as expected. But what I'm wanting is the following to result in false:

{% set mydict = {"nest1":"val1"} %}
{{ mydict.nest1.nest2.nest3 is defined }}

But it results in an error: 'str object' has no attribute 'nest2'. I understand why, but is there a way to avoid it without multiple is defined checks?

marble jackal
#

You can use .get() and let it return an empty dict as default

#
{% set mydict = {"nest1":"val1"} %}
{{ mydict.get('nest1', {}).get('nest2', {}).nest3 is defined }}
lucid thicket
#

I think that should work. It doesn't work in that example because nest1 has a string as its value, but I think that was just a poorly dumbed-down example. I'll play with this, thank you!

#

to be clear, I'm the one who did a poor job of dumbing it down....

dry narwhal
#

I have a bit of a templating syntax problem for an output I am trying to create.

#

I would like to turn this output

type: custom:apexcharts-card
series:
  entity: entity1

type: custom:apexcharts-card
series:
  - entity: entity2

into

type: custom:apexcharts-card
series:
  - entity: entity1
  - entity: entity2
#

in the else statement of this code:

plain magnetBOT
dry narwhal
#

That would let the user create either multiple cards with one entity each (current if statement works like that) into one card with multiple entities (the else statement, which does not work yet because I do not know how to change the output in the mentioned, desired way.

bitter atlas
#

Can we use trigger.to_state.state in has_value? I found a post from 2022 that indicates you cannot not finding anything that states that you can since 2023.4.

#

guess maybe this question might belong in automations

#

but then trigger templates also use it

marble jackal
#

No has_value takes an entity_id as input

#

You can use is_number if you're expecting a numeric state

bitter atlas
#

ok, the current method isn't hard, just curious if that was actually added in under the radar

lucid thicket
#

Can’t you use has_value(trigger.to_state.entity_id)

mighty ledge
#

yes, but that's not the same

#

you already have the state with trigger.to_state.state, there's no reason to quiery the state machine again using has_value

#

not to mention, there's a chance the state changes from your current triggered automation to when you access it

lucid thicket
#

Ok good points!

deep marsh
#

Hi!
Is there a way to use the state of a trigger action template sensor in a blueprint? So, let's say I want to use the precipitation of a weather entity in a calculation in a blueprint.

I want to define the trigger template within the blueprint and use the outcome of that template as a value to calculate something else.

marble jackal
#

Why not ask for the weather entity in the input values for the blueprint, and run the weather.get_forecast service call in the automation?

#

I don't see a need to do that in a template sensor

deep marsh
#

Hmmmm. I was on the track of using that value as a variable, but I guess I was thinking to complicated

mighty ledge
#

personally, I try to simplify all inputs on blueprints down to a few options

#

when you get too complex, it becomes a pain to manage and it's easier for users to make mistakes

#

keep the complexity in your variables, away from the users

deep marsh
#

Yes, I agree. I only wanted to ask for the weather entity indeed and then do the magic, but I was on the wrong track thinking about a template sensor...

mighty ledge
#

Template sensor is typically only usefull if you want to display the info in the dashboard

deep marsh
#

Okay, I'm a step further.
So now, my result is stored in a response_variable which works fine. I can use that response variable in the next action of the automation.

But I want something more. I want to use the value of the response variable to calculate a new value and store that new value in a variable that I can use in multiple actions that follow after the response_variable is filled with data. This must be simple, but I cannot find an explanation that I understand.

#

It doesn't make sense to me to do the same calculation multiple times for each action in an automation.

mighty ledge
#

like this

#
action:
  - service: weather.get_forecast
    target:
      entity_id: !input weather
    data:
      type: hourly
    response_variable: current
  - variables:
      something_you_want: >
        {{ current.forecast | .... }}
#

then acces something_you_want in all the remaining variables

deep marsh
#

Okay. I tried that, but I think I made a mistake in the remaining actions. Thx. Will try it again. You're the best!

deep marsh
lucid thicket
#

is there a better (simpler, without the if/else clause) way to determine if the event object has a specific key in the data dictionary, or whether data is even provided with the event at all? I am trying to create a trigger-based template sensor using events, and I'd like it to work whether or not event_data is provided when the event is fired

#
  - trigger:
      - platform: event
        event_type:
          - air_filter_changed
    sensor:
      - name: "Air Filter Last Changed"
        state: >-
          {% if trigger.event.data.datetime is defined %}
            {{ (trigger.event.data.datetime | as_datetime | default(now(), true)).isoformat() }}
          {% else %}
            {{ now().isoformat() }}
          {% endif %}
        unique_id: airfilterlastchangedtemplatesensor123
        device_class: timestamp
mighty ledge
#

is defined, which you're already using

#

if you're talking about the whole event data object

#

then is defined and is not none

#

i.e. trigger.event.data is defined and trigger.event.data is not none

deep marsh
#

Thank you @mighty ledge and @marble jackal for your help. This get_forecast service and the decision to remove the forecast attribute from the weather entity helped me a lot in learning new stuff!

mighty ledge
#

that guarentees that it exists but it still may be an empty dictionary

lucid thicket
#

yes I'm taking care of the empty dictionary with the default filter. I was hoping to use the .get() method so I could supply a default if the key doesn't exist, but it doesn't work on the event itself, e.g. trigger.event.get('data', {}) results in an error: 'homeassistant.core.Event object' has no attribute 'get'

mighty ledge
#

you put the get on data

#

event is not a dictionary

#

data is

#

trigger.event.data.get('datetime')

lucid thicket
#

what I'm looking for is the most compact way to say "if the event doesn't have data, or if it has data but the key datetime isn't defined, then default to now() otherwise use the value supplied by datetime"

mighty ledge
#

there's really no compact way of doing that

#

data should always be defined as an empty dict

#

you can always test it if you want

#

as for your template sensor, the most compact you'd need would just be {{ trigger.event.data.get('datetime', now()) }}

marble jackal
#

If it's always defined, you should be able to use
{{ (trigger.event.data.get('datetime', now())).isoformat() }}

mighty ledge
#

all the rest that you're doing is non-needed fluff

marble jackal
#

You're right

#

Even isoformat is fluff

mighty ledge
#

isoformat isn't needed anymore and it'll cause the template to complain (maybe)

#

I have to double check that

#

Acutally, it won't cause it to complain, it is just fluff

lucid thicket
#

holy smokes that worked

#

now I'm trying to recreate the 1-line version I had and find out why it didn't work

mighty ledge
#

well, you did have a | as_datetime

#

if you do now() | as_datetime, I'm pretty sure that would fail

#

which is dumb, but I think it does

#

Yes, it does

lucid thicket
#

yes it does, I'm seeing that now

mighty ledge
#

so your problem was most likely related to you trying to convert it to a datetime when you didn't need to

lucid thicket
#

so if I take TheFes' answer and I wanted to catch errors if the provided datetime key wasn't in the right format, how could I do that? Since now() is in the correct format, but I don't know whether datetime is, and I can't send it to the as_datetime filter

#

actually, using your answer without isoformat, i.e. {{ trigger.event.data.get('datetime', now()) }}

mighty ledge
#

well, you'd need to use set in that case

#

if the datetime format is wrong, then don't default it to anything

#
{% set t = trigger.event.data.get('datetime') %}
{% if t is not none %}
  ....
{% else %}
  {{ now() }}
{% endif %}
lucid thicket
#

thanks. so no simple 1-liner in that scenario. My own automations are going to be the only thing creating those events, so I think the best answer is to not try to error-handle my own stupidity. It makes the code balloon.

#

is there a general best practice in that regard? Handle any feasible input gracefully versus assume the input is correct, when you have control over both input and output?

mighty ledge
#

I let it error

#

so I can fix it on what's generating it

lucid thicket
#

that makes sense. thanks

marble jackal
#

I assume this is a custom event?

#

You could use
{{ t | as_datetime if t is not none and t | as_datetime is not none else now() }}

#

As as_datetime returns none on invalid input

lucid thicket
#

yes it is a custom event

#

that makes my head spin but it would work! That's good to know but I think I'm going to let the errors happen, that probably makes more sense so I can fix them

#

I think I'm almost at a solution but I'm having one last error I can't seem to squash

#

invalid template (TemplateSyntaxError: expected token ',', got ':') for dictionary value @ data['sensor'][0]['attributes']['history'].

dry narwhal
#

Does anybody have any good experience with an AI I could try to fix my Jinja code? Tried Bing AI with no luck.
I "know" where I am going wrong and I think I know why, I just don't know how to fix it.

lucid thicket
dry narwhal
#

I need to have the for loop inside the print statement.

{% set ns = namespace(list=['entity1', 'entity2']) %}

{{ {'type': 'custom:apexcharts-card',
      'series': [{
            {% for item in ns.list -%}   
            {{      
               'entity': item, }]
   }
}}
{%- endfor %}
mighty ledge
#

you should never need tht

#

if you need to create a list before outputting it, then use namespace and add to the list

#

then output the list after all additions are complete

dry narwhal
#

I did create a namespace with all the entities.
Now I need to have the typeand series part only once but one 'entity:' item per ns.list item.

#

So do I need to create a second namespace with all the 'entity:' item in it?

mighty ledge
#

no, you just do it in 1 namespace

#

you're not using namespace correctly

#

in your example above

#

you're just using it as a normal immutable list.

#

namespace is specifically designed for you to mutate complex objects

#
{% set ns = namespace(items=[]) %}
{% for item in ['entity1', 'entity2'] %}
  {% set ns.items = ns.items + [{'entity': item}] %}
{% endfor %}
{{ ns.items }}
dry narwhal
#

I wanted to try on a simplified version where I manually entered the test values.

#

This is part of the original one (which contains more includes and excludes):

    {% set ns = namespace(list=[]) %}    {% for item in states.sensor |
    selectattr('name','search',states['input_text.apexcharts_entity_include'].state,
    ignorecase=True) -%}
        {% set ns.list = ns.list + [ item.entity_id ] %}
    {%- endfor %}   
mighty ledge
#

I don't follow you

dry narwhal
#

I create a namespace with the list of entities I want to pass to the card with that code.
So I did not create a list by hand like in the ['entity1', 'entity2'] example. Was that not what you meant with me using namespace incorrectly?

#

And if I understand you correctly,

#

I should now modify the namespace I already created and essentially add 'entity:' in front of each of the ns.items

mighty ledge
dry narwhal
#

Sorry, I was trying to create a simplified example that could be tested without actually having to populate with own sensors. 😦

#

So your example would be this (implemented and with ns.list instead of ns.items:

mighty ledge
#

all you need to do is output a list of dictionaries with the correct fields

dry narwhal
#
    {% set ns = namespace(list=[]) %}    
    {% for item in states.sensor |
    selectattr('name','search',states['input_text.apexcharts_entity_include'].state,
    ignorecase=True) -%}
        {% set ns.list = ns.list + [ item.entity_id ] %}
    {%- endfor %}   
    {% for item in ns.list -%}
      {% set ns.list = ns.list + [{'entity': item.entity_id}] %}
  {% endfor %}
  {{ ns.list }}
#

?

mighty ledge
#

you don't need to do that twice

#

just do it in the first for loop

#

as a sidebar, do you understand object oriented languages?

dry narwhal
#

Trying to learn how they work.
I have observed that
[{ something }] used in a card configuration will create the - something version, so with the leading dash.

Yeah yeah, I know I sound stupid, but I assure you I am not πŸ˜„

mighty ledge
#

you really need to spend 10 minutes learning yaml

#

Look up some tutorials on JSON

#

then look up some tutorials on YAML

#

then look up how you can use JSON in YAML

#

then you'll understand what the dashes do, what objects to return

dry narwhal
#

I will read that tomorrow evening, when my wife is out of town πŸ™‚

#

May I ask one last thing before I do that?

mighty ledge
#

sure

dry narwhal
#

If I already created a namespace list created like this:

{% set ns.list = ns.list + [ item.entity_id ] %}

(a list with only values?)
and want to turn it into this type:

{% set ns.list = ns.list + [{ 'entity': item.entity_id }] %}

(an object with property and key?).
Is that easily achievable?
Because I need both types on list and ideally I create the first one and then transform it into the second one.

mighty ledge
#

the output specifically needs a list of dictionaires

#

so that's all you need

dry narwhal
#

This output, yes.
But I am trying to create a grid card that you can switch from "multiple charts with one entity per chart" (needs the list) to "one chart card with multiple entities" (needs the dictionary).

mighty ledge
#

then you just make the list of dictionaries

#

and map the value to get a list of entity_ids for the other list

#

map(attribute='entity') | list

#

that's why I asked you if you understood object orientation earlier

#

if you have a list of objects, you can generate a list of information based on those objects as long as they all have a common property, or you can filter down to a common property

dry narwhal
#

Of course, you are right, I was going at it backwards. Please give me a few minutes to test

dry narwhal
#

Oh, I hate this day so much -.-
I had one of the two version ready and then tried to get the second one working and broke the first.

And now I can't get it working again -.-
My problem, I know, but sooo frustrating. And you think this is all so easy πŸ˜„ πŸ˜„ πŸ˜„

mighty ledge
#

justpost the whole template

dry narwhal
# mighty ledge justpost the whole template

Okay, but here it is still with the list instead of dict because I had it working and now lost it again. Even when downscaling (i.e. removing all the additional includes, excludes).

mighty ledge
#

yes but if you just post all the code I can just fix it

dry narwhal
#

This is what it looks like for input_boolean == 'on'

mighty ledge
#

cheese and rice dude, overcomplicated much?

dry narwhal
#

Looks complicated but a lot is copy & paste.

#

Ah, I can't post a picture here....

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.

dry narwhal
#

That is the version with the boolean turned on (so one card per entity).
On the right all the input helpers. include up to five wildcard includes and 5 wildcard includes plus area filter.

#

Hidden/shown with entity-fold-row

#

I can of course also post the helpers, if that makes anything easier.

mighty ledge
#

what is sensor.timestamp?

#

is that now() as a timestamp?

dry narwhal
#
sensor:
  - platform: time_date
    display_options:
      - 'date_time_iso'

template:
  - sensor:
    - name: timestamp
      state: "{{ as_timestamp(states('sensor.date_time_iso')) }}"
      icon: "mdi:calendar-clock"
mighty ledge
#

yes it is

dry narwhal
#

Yes πŸ™‚

#
automation:
  - alias: Apexcharts Dropdown Areas
    id: apexcharts_dropdown_areas
    mode: single
    trigger:
      platform: homeassistant
      event: start
    action:
      - service: input_select.set_options
        target:
          entity_id: input_select.apexcharts_dropdown_areas
        data:
          options: >
            {{ ['-- - --'] + states | map(attribute='entity_id') | map('area_name') | unique | reject('none') | list }}
mighty ledge
#

sorry, i have to fix alot

dry narwhal
#

Oh no 😦
But it was working for case a. Does case a also need a lot of fixing or is it due to the change from list to dictionary?

Is it possible that a namespace template I still had in dev tools may have interfered with one of my test steps? I think namespaces in dev tools - templates are available through HA, right? So a card "sees" those also?
Just wondering because I had to restart HA because it started to lag.

mighty ledge
#

just bare with me for a bit

#

I have to reformat everythign to reduce redundancy

#

so why are you checking apexcharts_entity_include 1 through 5?

#

your UI only shows 1

#

is that hidden in the down arrow?

dry narwhal
#

You can see it on the second picture I had shared.
There I opened the dropdown for you to see (only one include and one exclude as an example)

mighty ledge
#

ok, so you have that large if statement at the bottom, you're trying to fix which one?

#

they both appear to be using the same crap. A list of dictionaries

#

@dry narwhal ^

#

anyways, I'm assuming ou want something like this.

dry narwhal
#

Sorry, dinner with my wife πŸ™‚

#

They are using the same crap and that's the reason why
a) I tried decluttering card despite it using yaml instead of jinja (hoping to somehow bridge that)
b) I was trying to make it work without a second full config else and instead just have a different list passed into the same config.

Unfortunately, all that crap is needed to make the card look nice...and I have not even pimped all of it yet πŸ˜„

dry narwhal
# mighty ledge <https://dpaste.org/7D6Qa>

Thank you so very much!
I am trying it now. It is not yet showing anything (empty card without error) so I will look through the code and try to understand and check what is specific to me that might be breaking it.

I have a question or two to learn πŸ™‚

  • You iterate include and exclude from i=1 to 6. Is that one larger than initially on purpose?

  • I tested the namespace code in the dev tools and I see that ns.list returns a huge string list with seemingly all entities and all of their attributes.

#
[<template TemplateState(<state sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0=24; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Sony KD-75XF9005_Naim Audio AV ENERGY Power 0 @ 2023-09-18T20:41:16.477710+02:00>)>, <template TemplateState(<state sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1=2; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Sony KD-75XF9005_Naim Audio AV ENERGY Power 1 @ 2023-09-18T20:43:46.456028+02:00>)>, <template TemplateState(<state 
.....
#

Is maybe an empty input_text being interpreted by the filter as "*"?

mighty ledge
#

yes, I kept the items as state objects because you were converting back and forth between state objects and entity_ids

dry narwhal
#

Alright. So maybe the filtering is the problem, because

    {% for item in ns.list -%}
    {{ item.entity_id }}
    {%-endfor%}

returns a looong list of entity_ids that does not match the filters.

#

Entered include string is Sony.*ENERGY Power.*

#

all other includes and all excludes are empty

mighty ledge
#

what does the list look like before the excludes?

dry narwhal
#

I am trying to go through it bit by bit.
So

    {% set ns = namespace(list=[]) %} {% for i in range(1, 6) %}
      {% set post = '' if i == 1 else '_' ~ i %}
      {% for item in states.sensor | selectattr('name', 'search', states('input_text.apexcharts_entity_include' ~ post), ignorecase=True) %}
        {% set ns.list = ns.list + [ item ] %}
      {% endfor %}
    {% endfor %}
    {{ns.list}}
#

returns

Result type: string
[<template TemplateState(<state sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0=24; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Sony KD-75XF9005_Naim Audio AV ENERGY Power 0 @ 2023-09-18T20:41:16.477710+02:00>)>, <template TemplateState(<state sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1=2; state_class=measurement, unit_of_measurement=W, device_class=power, friendly_name=Sony KD-75XF9005_Naim Audio AV ENERGY Power 1 @ 2023-09-18T20:43:46.456028+02:00>)>, <template TemplateState(<state sensor.fixed_value_consumers_energy_total=24310.832; state_class=total, source=sensor.fixed_value_consumers_energy_power, unit_of_measurement=Wh, icon=mdi:chart-histogram, friendly_name=Fixed Value Consumers ENERGY Total @ 2023-09-18T18:41:13.626674+02:00>)>, <template TemplateState(<state sensor.date_time_iso=2023-09-18T21:15:00; icon=mdi:calendar-clock, friendly_name=Date & Time (ISO) @ 2023-09-18T21:15:00.001070+02:00>)>, <template TemplateState(<state sensor.shelly_high_temperature=[]; friendly_name=Shelly High Temperature @ 2023-09-
#

and much much more of that.

#

All output now for the include string Sony.*ENERGY Power.*

#

And then the item.entity_id

    {% set ns = namespace(list=[]) %} {% for i in range(1, 6) %}
      {% set post = '' if i == 1 else '_' ~ i %}
      {% for item in states.sensor | selectattr('name', 'search', states('input_text.apexcharts_entity_include' ~ post), ignorecase=True) %}
        {% set ns.list = ns.list + [ item ] %}
      {% endfor %}
    {% endfor %}

    {% if is_state('input_boolean.apexcharts_merge_split', 'on') %}
      {% for item in ns.list -%}
      {{ item.entity_id }}
      {%- endfor %}
    {% endif %}
#
Result type: string
sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0sensor.sony_kd_75xf9005_naim_audio_av_energy_power_1sensor.fixed_value_consumers_energy_totalsensor.date_time_isosensor.shelly_high_temperaturesensor.timestampsensor.fixed_value_consumers_energy_todaysensor.fixed_value_consumers_energy_powersensor.sun_next_dawnsensor.sun_next_dusksensor.sun_next_midnightsensor.sun_next_noonsensor.sun_next_risingsensor.sun_next_settingsensor.home_assistant_v2_db_sizesensor.pn532_r

and so on

mighty ledge
#

just take it one moment at a time, don't get ahead

hearty verge
#

Is there a way to get a list of disabled/not-configured integrations?

mighty ledge
#

this here should only output a list with your sony serahc in it

    {% set ns = namespace(list=[]) %} {% for i in range(1, 6) %}
      {% set post = '' if i == 1 else '_' ~ i %}
      {% for item in states.sensor | selectattr('name', 'search', states('input_text.apexcharts_entity_include' ~ post), ignorecase=True) %}
        {% set ns.list = ns.list + [ item ] %}
      {% endfor %}
    {% endfor %}
    {{ns.list}}
dry narwhal
dry narwhal
mighty ledge
#

and what's in all your input texts?

dry narwhal
#

they are all empty except for the first one

#

To test I tried the original

    {% set ns = namespace(list=[]) %}    {% for item in states.sensor |
    selectattr('name','search',states['input_text.apexcharts_entity_include'].state,
    ignorecase=True) -%}
        {% set ns.list = ns.list + [ item.entity_id ] %}
    {%- endfor %} 
    {{ns.list}}

and it only gives the two entities I am looking for

mighty ledge
#
    {% set ns = namespace(list=[]) %}
    {% for i in range(1, 6) %}
      {% set post = '' if i == 1 else '_' ~ i %}
      {% for item in states.sensor | selectattr('name', 'search', states('input_text.apexcharts_entity_include' ~ post), ignorecase=True) %}
        {% set ns.list = ns.list + [ item ] %}
      {% endfor %}
    {% endfor %}
    {{ns.list | map('name') | list }}
#

post the full results

dry narwhal
#

TemplateRuntimeError: No filter named 'name'.

#

I guess that was not the plan πŸ˜„

mighty ledge
#
    {% set ns = namespace(list=[]) %}
    {% for i in range(1, 6) %}
      {% set post = '' if i == 1 else '_' ~ i %}
      {% for item in states.sensor | selectattr('name', 'search', states('input_text.apexcharts_entity_include' ~ post), ignorecase=True) %}
        {% set ns.list = ns.list + [ item ] %}
      {% endfor %}
    {% endfor %}
    {{ns.list | map(attribute='name') | list }}
#

sorry that

plain magnetBOT
#

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

dry narwhal
#

literally seems to be all entities

mighty ledge
#

Yeah, that's not possible unless you have output in the other input_texts

#

I'll just build safety into it then...

dry narwhal
#

They are initially ''

#

So not undefined, if I am not mistaken

mighty ledge
#
    {% set ns = namespace(list=[]) %}
    {% for i in range(1, 6) %}
      {% set post = '' if i == 1 else '_' ~ i %}
      {% set find = states('input_text.apexcharts_entity_include' ~ post).strip() %}
      {% if find %}
        {% for item in states.sensor | selectattr('name', 'search', find, ignorecase=True) %}
          {% set ns.list = ns.list + [ item ] %}
        {% endfor %}
      {% endif %}
    {% endfor %}
    {{ns.list | map(attribute='name') | list }}
dry narwhal
#
  apexcharts_entity_exclude:
    name: ''
    icon: mdi:filter-remove-outline
    max: 1000
    min: 0
    mode: text
    initial: ''
dry narwhal
#

TemplateRuntimeError: No filter named 'name'.

mighty ledge
#

try again, copy above

dry narwhal
#

Jup, that looks good

#
Result type: list
[
  "Sony KD-75XF9005_Naim Audio AV ENERGY Power 0",
  "Sony KD-75XF9005_Naim Audio AV ENERGY Power 1"
]
mighty ledge
#

alright, then it should be good

dry narwhal
#

But what is the cause?

mighty ledge
#

you probably have a space in those fields

#

so it was finding things with a space

dry narwhal
#

So that will also apply to excludes

mighty ledge
#

no

#

because that already had an if statement

#

just try it

dry narwhal
#

still empty card, that's why i asked

#

I will do the next step in dev tools

#

The area section

    {% set area = states('input_select.apexcharts_dropdown_areas') %} {% if area
    == '-- - --' %}
      {% set ns.list = ns.list | unique | list %} 
    {% else %}
      {% set ns.list = ns.list | unique | selectattr('entity_id', 'in', area_entities(area)) | list %}
    {%- endif %}
#

is causing
TypeError: unhashable type: 'TemplateState'

mighty ledge
#

why do you keep doing this {% set area = states('input_select.apexcharts_dropdown_areas') %} {% if area

#

it makes it 1000% harder to read

dry narwhal
#

that is from your re-work

mighty ledge
#

it is not

#

I keep my if statements at the start of a line

dry narwhal
#

Oh, you mean that.
That's the frontend πŸ˜‰

#

I asked if thtere is a way from keeping HA from messing it up but apparently there is not

dry narwhal
hearty verge
#

cant you use {%- and -%} to get rid fo whitespace

dry narwhal
#
    {% set area = states('input_select.apexcharts_dropdown_areas') %} 
    {% if area == '-- - --' %}
      {% set ns.list = ns.list | unique | list %} 
    {% else %}
      {% set ns.list = ns.list | unique | selectattr('entity_id', 'in', area_entities(area)) | list %}
    {%- endif %}
mighty ledge
#

you shouldn't be gettin any error in that part

#

unless unique cannot handle that

#

then just remove the unique and deal with it at the end

dry narwhal
dry narwhal
mighty ledge
#

change both uniques to unique(attribute='entity_id')

dry narwhal
#

Did I overlook something during our debugging or were you always creating a list of friendly_names instead of entitiy_ids?

#

I think a step to convert friendly_name to entity_id is needed

mighty ledge
#

it is not

#

it's a list of state objects

dry narwhal
#

My mistake, I had one more map in there that caused the problem.

#

So, it is working until the first if, so multiple cards with one entity each. But the else leaves me with an empty card.

mighty ledge
#

going to need to see output

dry narwhal
#

working on it, bare with me

#

Hope I did not overlook a vital test piece with all that config "crap" πŸ˜‰

#
    {% set ns = namespace(list=[]) %} 
    {% for i in range(1, 6) %}
      {% set post = '' if i == 1 else '_' ~ i %}
      {% set find = states('input_text.apexcharts_entity_include' ~ post).strip() %}
      {% if find %}
        {% for item in states.sensor | selectattr('name', 'search', find, ignorecase=True) %}
          {% set ns.list = ns.list + [ item ] %}
        {% endfor %}
      {% endif %}
    {% endfor %}

      {% set merged = namespace(items=[]) %}
      {% for item in ns.items %}
      {{ item.entity_id }}
      {%- endfor %}
#

'jinja2.utils.Namespace object' has no attribute 'items'

mighty ledge
#

{% for item in ns.list %}

dry narwhal
#

Was just about to say.

#

Why does {% set merged = namespace(items=[]) %}and {% set merged = namespace(list=[]) %}` return the same? Does it not matter here?

mighty ledge
#

what?

#

merged is a new namespace object

#

don't change what's on that, literally only change {% for item in ns.items %} to {% for item in ns.list %}

#

nothing else

dry narwhal
#

No worries, that was just a test for myself. I did not change anything else in the card. Still empty card though

mighty ledge
#

please post whats in merged

dry narwhal
#
      {% set merged = namespace(items=[]) %}
      {% for item in ns.list %}
      {{ merged }}
      {%- endfor %}
mighty ledge
#

no

dry narwhal
#
Result type: string
<Namespace {'items': []}>
      <Namespace {'items': []}>
mighty ledge
#

why are you changing things?

#

afterr this

      {% set merged = namespace(items=[]) %}
      {% for item in ns.items %}
        {% set merged.items = merged.items + [
          {
            "entity": item.entity_id,
            "yaxis_id": "first",
            "color": colors[loop.index0],
            "show": {
              "in_chart": true,
              "in_brush": true
            }
          }
        ] %}
#

put this

#

{{ merged.items }}

dry narwhal
#

I was not, I was just going through step by step and your would have been next

plain magnetBOT
#

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

mighty ledge
#

why is colors missing?

dry narwhal
#

Removed it because it is not know in dev tools. Sorry, I did not mean to cause confusion

mighty ledge
#

you should be able to copy/past that whole thing in dev tools

#

without removing anything

plain magnetBOT
#

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

mighty ledge
#

right but at this point, I don't see any additional errors

#

it's all outputting as it should

dry narwhal
#

HEre is the output (including all the empty lines) when I just copy the entire card to dev tools

plain magnetBOT
#

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

mighty ledge
#

if it's outputting it should just work. I based it off your yaml. So if your yaml was not correct for the multiple entities in the series item, then it won't work

dry narwhal
#

I apologize, I just got called to support a friend in an emotioanl crisis. I need to abort.
I truly apologize and thank you so very much for everything so far!

I will continue as soon as I get back from work tomorrow.

Last thing I did before the call was to convert the dict to yaml using https://paji-toolset.net/py-dict-to-yaml-converter
and then copied the yaml directly to an empty card.
That worked.

#

But as soon as I add it to the auto-entities & grid portion, it no longer works.

#

Working:

plain magnetBOT
#

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

dry narwhal
#

not working:

plain magnetBOT
dry narwhal
#

(had to remove graph_span line due to 2000 chars limit)

#

Sorry, ignore my last post, it was in the template part, that cannot work

snow folio
#

Guys, any ideas on why

"{{{states.binary_sensor.puerta_principal_sala.last_changed.strftime('%H:%M') }}"

is giving me the wrong time? (4 hours ahead) (all my TimeZone and locals are ok even the HA logs is showing me the correct time)

inner mesa
#

it's in UTC

#

if you want local time, you need {{ (states.binary_sensor.puerta_principal_sala.last_changed|as_local).strftime('%H:%M') }}

#

you also had an extra { in there

snow folio
#

And I feel dumb again... lol Gotta try harder on templates, thak you very much sir!

plain magnetBOT
dusky ore
rose scroll
# dusky ore I have a sensor that combines the output of multiple calendar.list_event calls i...

I think you'd need to reconstruct a new list containing dicts referencing the data from the two lists of dicts you've made. Assuming you've declared events as above and assigned data_numbers to the variable start_times:

{% set output = namespace(list = []) %}
{% for i in range(0, start_times | length) %}
  {% set output.list = output.list + [{ 'start': events[i]['start'],
                                        ...
                                        'calendar': events[i]['calendar'],
                                        'local_start': start_times[i]['local_start']}] %}
{% endfor %}
{{ output.list }}
dusky ore
haughty breach
dusky ore
#

Amazing, thank you!

dry narwhal
marble jackal
#

@stark vale
3 things concerning your template you posted in #automations-archived

  1. It's state_attr() not states_attr()
  2. The template won't work when the light is not on as there will be no brightness attribute then
  3. The template won't work when the brightness is already above 245, as the result will be above 255, which will cause an error
mighty ledge
dry narwhal
# mighty ledge Did you figure it out?

I tested around early this morning because it was bugging me and both seemed to work after converting dict to yaml when I used the yaml for a standalone card.
And then I spotted it 🫣

#

not working:

            "offset": SPAN_OFFSET
          }
        }
      }}
    {% endif %}
#

working:

            "offset": SPAN_OFFSET
          }
        }
      }},
    {% endif %}
#

do you see it?

#

🫣

mighty ledge
#

that shouldn't have made a difference

dry narwhal
#

weeelll, I do not know why or how, but it made it work.

#

I was wondering if it was linked to the grid card rather than the apexcharts card

#

But again, no idea why because I would have thought that no comma is needed since it is the end of the block and only one card is created.

#

Is it possible that the template creates a line break or something at the end which the card then cannot handle? So the comma would allow a new (although be it empty) line to follow?

Just a stab in the dark.

fierce hawk
#

Hi guys, I need a bit of help. I recently got a new pool electrical box and it can be controlled through MQTT. However it has its own MQTT so I created a bridge between the box and HA. It works and I can see everything in MQTT explorer
Now I am trying to add the entities and I successully added the lights control. However I'd like as well to add the pump speed. the state is in topic xx/reported/$value and to publish a command it's in xx/desired/$value
Currently 3 values that can be published is 129,130 and 131 (that are low, standard and high speed)
Any idea how to integrate this? Should it be switch template?

mighty ledge
dry narwhal
#

Stock grid, in this case. But I also tested with vertical-stack. That's why I was thinking about new line/line breaks being the issue.
The cards maybe expected a second card due to a line break or new line.
Would that be possible to test, i.e. is it possible to prevent line breaks at the end of a printout or a block?

dry narwhal
#

I started to read up on the json syntax and wanted to convert

      value_template: >
        {% if value_json.Result == "ok" %}
          {{ value_json.temp }}
        {% else %}
          {{ states('sensor.eq3_temperature_living_room') }}
        {% endif %}

into a dictionary.

#

However, neither the literal (using line breaks)

    "value_template": "{% if value_json.Result == \"ok\" %}\n  {{ value_json.temp }}\n{% else %}\n  {{ states('sensor.eq3_temperature_living_room') }}\n{% endif %}\n",
#

nor the smiplified

"value_template": "{% if value_json.Result == 'ok' %}{{ value_json.temp }}{% else %}{{ states('sensor.eq3_temperature_dining_room') }}{% endif %}",
#

seem to work.
I validated by just using "value_template": "{{ value_json.temp }", which leads to an updating sensor.

#

Where am I going wrong?

inner mesa
#

You're missing the surrounding {}. You can put it in any online JSON validator

plain magnetBOT
#

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

dry narwhal
#

Grrr, these automatic conversions. That's why I try to only post the really relevant piece of code 🫣

#

All validators seem to think that the version with line breaks is correct.
But HA does not seem to think so.
HA shows that entity as unavailable if I use MQTT Auto discovery with that syntax.
But the sensor updates without the if expression.

jagged obsidian
#

you commented out " at if value evaluation

fierce hawk
# lucid thicket For an entity with options, you should look at a `select` https://www.home-assi...

thanks for insights. I have tried a bit but somehow lacks bit on jinja understanding: select:
```- name: "CCEI Pump Speed"
unique_id: "CCEI Pump Speed"
state_topic: "anteavs_XX/u8_w/filt_speed/info/reported"
options:
- "Off"
- Level1
- Level2
- Level3
value_template: >
{% if value_json.svalue1 == "0"} Off
{% elif value_json.svalue1 == "119"} Level1
{% elif value_json.svalue1 == "120"} Level2
{% elif value_json.svalue1 == "131"} Level3
{% endif %}

This fails with incorrect data key
For now just trying to read the data, once it works i will do the state command