#templates-archived
1 messages Β· Page 53 of 1
someone helped me with this a long tim ago
hehe. lemme template the first line solo.
just remove the > 0 and make sure you use output jinja indicators and remove the if
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 !π
@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' }}
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 π¦
perfect, thanks
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
with a template trigger
but we'd need more info
because sms.incoming_sms isn't something that normally exists in HA.
thank you lead me in the right direction was {{ 'Alarm' in trigger.event.data.text }}
Ah, so it's an event trigger, with a template condition
makes more sense w/ sms.incoming_sms
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.
Ok, how do I create this template π .. Sorry, pretty novice here
I read and tried this: https://www.home-assistant.io/integrations/template/, but no luck
If you have 2023.9, it's much easier in the UI template helper form.
This example covers exactly what you need
Aha, ok, let me try that, thank you π
just make sure you're using the value supplied above and not 1024
@cyan shale do you plan on using the energy tab?
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
you should be able to chaneg the units in the cog
Ok, so sorry, but could you please point out where do I change that in the cog?
petro, can you add a value_template in the customize.yaml settings?
asking for Keith3
In the cog, there should be a units dropdown
No, not possible
ok, the he must create a second template sensor based on the reimann-sum sensor
having all the properties for the energy dashboard
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')) }}"
- name: "Water Consumption"
device_class: water
state_class: total_increasing
and add this, so it will work with the energy dashboard
Ok so three steps then?
@cyan shale I converted your message into a file since it's above 15 lines :+1:
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
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...
availability: "{{ is_number(states('sensor.Water_Consumption')) }}"
you would call the state of the new sensor made in step 1
you can greate a unique ID here
https://www.uuidgenerator.net/
but it can be words too, not just numbers
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?
@cyan shale I converted your message into a file since it's above 15 lines :+1:
@cyan shale Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
if the syntax is correct, give it try!
Getting hte following error: "TemplateSyntaxError: expected token ',', got 'string'"
You are missing a ' in your state template
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 ?
You can. But you cannot use the same unique_id for two different entities. That makes those not very unique.
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
Have you done a full HA restart or just a quick reload?
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'''
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.
If the unit of measurement is "Galons per Minute" (flow rate), the state_class cannot be total_increasing (consumption).
Not yet, I was testing it, to make sure no errors
The integration platform needs a HA restart
Oh, ok
Yep, i just wanted ot make sure there are no syntax errors or logical errors before I restarted.
Looks like I may still have errors here. Suggestions ? Reviews?
what's the error?
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
GPM is a rate, it should be state_class: measurement.
Gallons is a volume, and that is what is total_increaseing
So I think the unit of measurement here should be just Gallons?
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
Ahhh... ok, let me re-write that... thanks...
@cyan shale I converted your message into a file since it's above 15 lines :+1:
@cyan shale Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
PS: trying to figure out how to paste code, and failing miserably.
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.
try pastie.org for code pasting
The symbols used are backtics ` , not apostrophes '
And everything above 15 lines total should be shared via a code sharing site
Ok thank you
here is the final code, that I'm pasting in my yaml and then restarting HA
why total_increasing?
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.
those do not go in the same section
also, I'd expect your state_class on the integration sensor to be measurement
I'm confused then... sorry.
I'm not even sure you need the integration platform either...
My goal is to take what Anto has done (it works for him) but have it show up in gallons not liters
got a link to it again?
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
yes, he's trying to convert a flow (l/m) to consumption (gallons)
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.
Ahhh, yes, I do have those sections... this is my current YAML
@cyan shale I converted your message into a file since it's above 15 lines :+1:
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?
nope, apparently you'll need to do this...
meaning, add those single quotes?
Ohhh... ok
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 π
sounds like we need an update to that integration
that should probably be in the UI anyways
(unless it already is)
it is!
Yes there's an integration/riemann helper in the UI, but it still doesn't do the units right for non-electric flows.
also I want to know who decided to name an integration integration π¦ π
lol that's good point, but I think in this case, it referring to integral
yeah I get why... but it's just.... ugh
Keith run that water hard ...
maybe we should call all HA intergrations, integrals
I'm just taking a full backup / just in case it breaks.. and will restart then
hassio integrals?
smidge overkill huh?
yeah, if it passes basic check, you should be fine less an error message in the logs if its not working
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
ah, good to know. And just restarted
Yes, couple of online dealers that will sell it directly to you
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
did you run some water so that value us not 0 or unknown? check if the sensors are populating and adding
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
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
that is the riemann
since when does riemann transform a measurement to total_increasing?
So under water source, I only see one sensor
the flow rate is a measurement, the result of the integral is total_increasing
total_increasing means it never decreases
for my reimann
integrals do not do that
they do if their inputs are always positive
are you returning water to the grid? π
that makes absolutely no sense
https://developers.home-assistant.io/blog/2021/08/16/state_class_total/
total_increasing, a monotonically increasing total, e.g. an amount of consumed gas, water or energy.
the integral of a water flow rate is "an amount of consumed water"
are people really doing that, using integral to change it from momentary to total_increasing??? wtf
I really do not understand where your confusion is coming from.
So then does that mean in https://dpaste.org/nN5eu#L45, I change "measurement" to "total_increasing"
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
yes, apparently water requires that. Even though other areas do not.
measurement generates weird "min"/"max" statistics which make no sense for a total volume
sure, that may be the case, but that doesn't mean that we should force the user to make a total_increasing sensor to generate the value
I've always wondered why people have been doing this
now I know, it's because we made a stupid decision
question, would I change state class "total_increasing" to both?
Oh, just to line 21?
speaking of this, @cyan shale do you have a traditional hot water tank? and if so, do you have an expansion tank on it? you will need one now if you don't already have it.
Yes my plumber pointed that out yesterday, and we added the expansion tank π
Ahh got it
your plumber is sharper than mine. My tank was pissing water for a few seconds for about 2 weeks before I realized what the problem was and told him..... Imagine that, the hot water tank bouncing off the 150 psi pressure release valve after every shower/bath my family took for about 2 weeks π
I missed the start of this, why is your hot water tank exploding now?
the smart water valve has a back-flow preventor
my water system became closed once that was installed
Hahaha, I pointed it out to him that it has a backflow preventer, and he immediately said, we need to add an expansion tank
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
ah I see
that why you need an expansion tank on the hot water tank
I thought all homes already had backflow preventers at the meter, but maybe that's just for irrigation water?
typically just irrigation water.... at least in the states
it's to stop rainwanter from getting into your drinking water from the irrigation system
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
you should look into that
expansion tanks in general increase the logengvity of hot water tanks
because of this phenomenon
my hot water tank is currently like 28 years old π
I try not to even look at it lest it burst
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
what integration creates the sensors?
I assume you mean measurement not momentary
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
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).
Embrace the total increasing dark side 
So my math is taking liters per hour, and showing that as gallons per minute.. which is way off.
never
divide the result by 60
in the first template
just put a / 60
after the 0.2xxxx number
and reboot?
ahh ok
that did it !!! π
Ok, now, can I reset this sensor to zero? Meaning delete all its old values for past 60 mins?
I'm not sure, I'm questioning everything about energy now because everything I set up originally is all different from what I remember.
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 :_
sure, but maybe you can edit your original post?
Oh thank you, I'm giong to go ahead and post it. so excited about this. thank you again.
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 ?
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
ahh ok, I'll play around with that next
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"
@mighty ledge and @floral steeple - ok quick results - something is off
- I had my sprinklers on from 1 pm to 1:13 pm -
- It reported accurately in the history graph for GPM_Water_Consumption
- 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?
8 gallons per min seems high
I measured all my sprinkler zones at 9-14 gpm πΊπΈ
No that's accurate... I know that from my normal usage with an analog meter
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
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
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"
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
Yes, I added it in YAML.. per here. https://community.home-assistant.io/t/adc-swm150-smart-water-valve-with-meter/613460/14?u=keith3
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
what's in the past can't be modified
you can try to fix it going forward by adding the unit_time
Sorry, i meant going forward
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
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)
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
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
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 π π ...
@lofty mason , that did it !!!!!!!! It works perfectly now... reporting the correct total gallons. ----- just had to add that unit_time: min
Hi all! Anyone knows how to add this "timestamp_custom('%H:%M')" to this: "{{ now() + timedelta(hours=6) | }} "
I only want Hour : Minutes π
You want to format the time (in 6 hours) as hh:mm?
yes if possible! π
{{ (now() + timedelta(hours=6)).strftime('%H:%M') }}
Woho! Thank you so much π
Hehe I had precisely the same, was just testing in developer tools π
Hehe, Thank you too lyricnz π π
You can play with this too at /developer-tools/template
And read the two pages linked (jinja2 templates, and HA extensions to them)
Okok, thanks! π
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')) }}
You could use |replace('Fan high','fan_high') or if, elif, else, endif.
"Fan high" | slugify
so in your case:
entity_id: scene.{{ states('input_select.fan') | slugify }}
Sounds like a snail, but even better than replace. Learned something new π
it's a common term in coding
it makes things into a 'slug'
Thanks @marble jackal that's perfect.
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
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')
What's the difference between that and search
{% set my_list = ['food', 'barbecue'] %}
{{ my_list is contains 'bar' }} # False
{{ my_list is search 'bar' }} # True
{{ my_list is contains 'food' }} # True
FYI all of this won't exist in ansible π
Lol how did you know what it was for. It actually does exist though.
search won't for sure
@thorny snow I converted your message into a file since it's above 15 lines :+1:
because you always ask ansible questions, it doesn't take a rocket scientist to figure out when you're not asking about HA
Is there some intricacy about timestamps I don't understand? π
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.
although I do have a aerospace engineer degree, so maybe it does
the behavior of search in ansible will be different than HA
Actual ha question.
#templates-archived message
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.
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
This is a great example of the difference. I saved this for future reference.
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.
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.
{% 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
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
So, just keep in mind that it will always be true
so it won't trigger
@thorny snow ^
ah, nevermind
It shouldn't be.
you changed the timedelta
in the match
You may have to increate the timedelta to 1 minute
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.
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
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.
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.
@honest wing I converted your message into a file since it's above 15 lines :+1:
Issue resolved :)
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
Quick question:
https://www.home-assistant.io/docs/configuration/templating/#areas
list examples for area templates.
I would like to get a list of all area_name instead of area. But area_name requires a lookup value and I do not know a workaround (especially since some areas might not have anything assigned yet)
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
{{ 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 }}
Hi,
id like to create a template sensor, thats βonβ if theres any entities with βswitch.schedule_***β
How could i do this?
{{ states.switch|selectattr('object_id', 'match', 'schedule_')|list|length > 0 }}
Oh that works perfectly! Thank you so much!
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
{ '' }
}
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
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.
hey, I've had a similar issue with templates, someone helped me solve it like this
#frontend-archived message
maybe it'd help you
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" }}
something like that, but that does not work
You're after the immediate if, or iif
ah great, thanks π
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
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.
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:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
Thanks, here goes.
@cold canopy I converted your message into a file since it's above 15 lines :+1:
In what way does it not work?
do you have a sensor now with state: unknown?
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
if it remains unknown it doesn't trigger
if it is unavailble it did trigger, but the template failed
My apologies, its actually unavailable @marble jackal
should there be a final {% else %} clause?
it seems possible for that to exit with no value
that could be a cause yes
I was following the example from https://www.home-assistant.io/integrations/imap/
And in the Example: Keyword spotting - there is no final {% else %}
I am trying to figure out how to upload an image here...
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
okay i did that, reloaded yaml and now the sensor without a relevant email to the config, shows null value basically
@cold canopy I converted your message into a file since it's above 15 lines :+1:
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?
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
π€ hmm weird then. Why does it work now when before it did not?
not sure
impossible for me to say
HASS Goblin Magic?
Yes will try testing more.
THANK YOU SO MUCH - i appreciate you taking time out of your day to help me. π Thanks
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.
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!
the other parameters are defined in the docs
so, look at the docs to determine which fields you need and just place them at the same level as your state
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) }
all states are strings
But I am performing a mathematical operation, so JavaScript is treating them as numerical values. Would that not result in a numerical value?
it automatically converts from a string to a number?
seems doubtful
I always use parseFloat()
or whatever JS magic you need to convert
Well, it does calculate a number from the above template. So it seems to "convert" to a number and then subtract.
Hmmm. Strange. So maybe it is returning a time delta rather than a true number.
Yes, thank you. I wanted to edit above and post that it worked with Number() but you were faster π
BTW, this channel is for Jinja templating. Further JS/frontend-type questions should go to #frontend-archived
Even though it is Javascript templating and not really frontend layout stuff?
yes
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
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, π
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?
That is where I placed it, of course.
Well, I need to use Home Assistant's input_datetime. So I need to use whatever type I am getting from there, plus the type I am getting from HA as timestamp.
So unless I convert before the maths operation, I need to convert at the end.
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 π
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 }}
thanks man!
thx for guidance. I understand most of what I can learn from resources about the legacy format should be easily applicable to the new.
how on earth would i go to exclude/reject certain entites here?
{{expand(integration_entities('cast'))| map(attribute='entity_id') | reject('is_state',['unknown','unavailable','playing']) | rejectattr('entity_id','in',['media_player.utebod','media_player.klokke_hub'])| list }}
You're already rejecting some entities there
but they're still selected, so it aint right ...
Sorry why are you first expanding it, and then mapping it back to entity_ids so you had the result you started with
i was just playing around with the different ways (expand or is_state) to see if it made any difference
{{ 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
You need to keep track of whether you have a list of state objects or entity_ids at each point
okay, so its the order I had in my template that messed up
but that did exacly what I needed, TheFes, thank you again!
I suggest building it a step at a time in
-> Templates and pay attention to the output
yeah good point π
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'
full code here: https://www.toptal.com/developers/hastebin
because you didn't quote the seasons
it's comparing season against variables that aren't defined
As in βspringβ etc?
as in 'string'
state: >
{% set season = states('sensor.season_astronomical')|string %}
that's not at all what I said
How to use local vaiables in a template
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] }}
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 %}
Not without a target... π
this is amazing! thank you
@rustic agate try:
The battery level is {{ trigger.to_state.state }}%
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
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)
Yes, in the channel topic
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
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Β΄?
You can but you need to re set the value. Unique is an operation, it doesnβt alter existing memory
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.
sorry, I meant {% list(set ns.list = ns.list + [ item.entity_id ]) %}
Yeahβ¦ thatβs still not correct
I read that list(set()) removes duplicates from lists automatically
But youβre still using it wrong
Where would the unique go then? Because it cannot go inside the for item expression as the duplicates are created during ns.list filling
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
dev tools
<generator object do_unique at 0x7f821eace0>
Yes thatβs a generator
Thatβs what it returns, if you want a list you need to also use list after
π€¦
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 !!!
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
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
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
I will try the first one
The first one will only trigger on changes of the sonoff sensor, the second one will also trigger if you change the input number
Oh, i also like the thought of the second one now too π
@haughty breach thank you so much, this is awesome... Now to re-wite a bunch of automations π
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"
]
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.
That's a new requirement
Well, I would say that filtering by area means "only those in that area".
There's no area called 'undefined'
An undefined entity is not in that area.
That was a shot in the dark
That's just a word
Tried with an without quotes
then it's just a variable
What is the area_name of "no area"?
there isn't one, it just won't be in the list based on the template I gave
It will be. That'S the problem
it's only outputting a list of entities that are in that area
Nope
alright
In the area and undefined
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
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 π
Np, I figured it was something like that
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 π¦
You have to reject it
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.
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
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'.
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?
{{ ['sensor.sony_kd_75xf9005_naim_audio_av_energy_power_0'] | map('state_attr', 'friendly_name') | list }}
got it
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 }}
Interesting.
Does that work as simply the other way around?
So entity_id from friendly_name?
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
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
Since mine are unique, a list would be fine π
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 }}
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 π π π
it's just a common idiom
the same thing is used to find entities matching any number of criteria
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'
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. π
A trigger based template sensor which uses now() as it's state and triggers when your doorbell sensor turns on
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 π
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
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 π
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 π
So I would first need to split the exclude string into parts and then check for each part
That would me my approach - doesn't have to be the best one
I'm no templating expert
The problem is still that I would have
"create full_string | select(full_string, 'in', part)"
Would that work?
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
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
Just to keep it simple - don't your entity_ids also contain those string parts? Meaning sony and energy_power?
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
But as I said. One of the Ninjas might have a better solution.
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 }}
That is awesome, @haughty breach , thank you!
Works like a charm π
Out of curiosity, do you know why the final list has reversed order? I of course reversed it again with |reverse but I am curious to learn what causes it.
Reverse how? I don't see it being sorted anywhere
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
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)
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?
Probably a feature request since relative and absolute humidity are fairly different and only relative is currently supported
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?
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 }}
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....
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:
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
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.
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
No has_value takes an entity_id as input
You can use is_number if you're expecting a numeric state
ok, the current method isn't hard, just curious if that was actually added in under the radar
Canβt you use has_value(trigger.to_state.entity_id)
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
Ok good points!
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.
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
Hmmmm. I was on the track of using that value as a variable, but I guess I was thinking to complicated
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
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...
Template sensor is typically only usefull if you want to display the info in the dashboard
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.
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
Okay. I tried that, but I think I made a mistake in the remaining actions. Thx. Will try it again. You're the best!
Boooommmmmm. It worked.
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
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
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!
that guarentees that it exists but it still may be an empty dictionary
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'
you put the get on data
event is not a dictionary
data is
trigger.event.data.get('datetime')
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"
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()) }}
If it's always defined, you should be able to use
{{ (trigger.event.data.get('datetime', now())).isoformat() }}
all the rest that you're doing is non-needed fluff
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
holy smokes that worked
now I'm trying to recreate the 1-line version I had and find out why it didn't work
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
yes it does, I'm seeing that now
so your problem was most likely related to you trying to convert it to a datetime when you didn't need to
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()) }}
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 %}
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?
that makes sense. thanks
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
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'].
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.
argh I was looking in the wrong place. Missing a parenthesis
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 %}
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
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?
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 }}
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 %}
I don't follow you
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
yes, because your example show'd you creating an immutable list then iterating over it
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:
all you need to do is output a list of dictionaries with the correct fields
{% 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 }}
?
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?
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 π
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
I will read that tomorrow evening, when my wife is out of town π
May I ask one last thing before I do that?
sure
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.
Side question: Would me calling that "converting a list to a dictionary" be correct?
https://documentation.bloomreach.com/engagement/docs/datastructures
I'm not sure why you need both types?
the output specifically needs a list of dictionaires
so that's all you need
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).
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
Of course, you are right, I was going at it backwards. Please give me a few minutes to test
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 π π π
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).
yes but if you just post all the code I can just fix it
cheese and rice dude, overcomplicated much?
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.
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.
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"
yes it is
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 }}
sorry, i have to fix alot
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.
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?
Yes, it is. I mentioned above the folder entity row.
So conditional on the first include, the second is shown and so on. Same for the excludes.
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)
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.
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 π
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 "*"?
range in all languages starts at 0 and goes from there
yes, I kept the items as state objects because you were converting back and forth between state objects and entity_ids
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
what does the list look like before the excludes?
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
just take it one moment at a time, don't get ahead
Is there a way to get a list of disabled/not-configured integrations?
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}}
Was not trying to. Was just checking if the enity_id is extracted and it it.
Nope, outputs a list with all my entities
and what's in all your input texts?
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
{% 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
{% 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
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
literally seems to be all entities
Yeah, that's not possible unless you have output in the other input_texts
I'll just build safety into it then...
{% 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 }}
apexcharts_entity_exclude:
name: ''
icon: mdi:filter-remove-outline
max: 1000
min: 0
mode: text
initial: ''
Typo?
TemplateRuntimeError: No filter named 'name'.
try again, copy above
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"
]
alright, then it should be good
But what is the cause?
So that will also apply to excludes
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'
why do you keep doing this {% set area = states('input_select.apexcharts_dropdown_areas') %} {% if area
it makes it 1000% harder to read
that is from your re-work
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
I do too, but that is what HA does to a well formatted card. It reformats
cant you use {%- and -%} to get rid fo whitespace
{% 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 %}
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
That was the cause!
change both uniques to unique(attribute='entity_id')
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
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.
going to need to see output
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'
{% for item in ns.list %}
Was just about to say.
Why does {% set merged = namespace(items=[]) %}and {% set merged = namespace(list=[]) %}` return the same? Does it not matter here?
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
No worries, that was just a test for myself. I did not change anything else in the card. Still empty card though
please post whats in merged
{% set merged = namespace(items=[]) %}
{% for item in ns.list %}
{{ merged }}
{%- endfor %}
no
Result type: string
<Namespace {'items': []}>
<Namespace {'items': []}>
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 }}
I was not, I was just going through step by step and your would have been next
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
why is colors missing?
Removed it because it is not know in dev tools. Sorry, I did not mean to cause confusion
you should be able to copy/past that whole thing in dev tools
without removing anything
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
right but at this point, I don't see any additional errors
it's all outputting as it should
HEre is the output (including all the empty lines) when I just copy the entire card to dev tools
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
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
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:
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
not working:
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
(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
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)
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
And I feel dumb again... lol Gotta try harder on templates, thak you very much sir!
@dusky ore I converted your message into a file since it's above 15 lines :+1:
I have a sensor that combines the output of multiple calendar.list_event calls into a list of events and each event is a list of dictionaries (summary, location, start, end, etc.) A for loop iterates over the events, creating a list of new dictionaries- one for each event. How do I append these new dictionaries to the original list for each even?
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 }}
Thank you! This looks great from a content standpoint but the resulting datatype is a string- I'm no longer able to use [i] to select individual events. Is it a bracketing issue?
{% set events = state_attr('sensor.multi_cal_events_tomorrow','events') %}
{% set data = namespace(numbers=[]) %}
{% for i in events %}
{% set data.numbers = data.numbers +
[dict(i, **{'local_start': (i.start|as_datetime|as_local).strftime('%H:%M') })] %}
{% endfor %}
{{ data.numbers }}
Amazing, thank you!
Are you curious to know why the else failed to work?
@stark vale
3 things concerning your template you posted in #automations-archived
- It's
state_attr()notstates_attr() - The template won't work when the light is not
onas there will be nobrightnessattribute then - The template won't work when the brightness is already above 245, as the result will be above 255, which will cause an error
Did you figure it out?
thanks for the help
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?
π«£
that shouldn't have made a difference
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.
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?
It's most likely the card you're putting apex card into.
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?
For an entity with options, you should look at a select
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?
You're missing the surrounding {}. You can put it in any online JSON validator
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
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.
you commented out " at if value evaluation
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