#templates-archived
1 messages · Page 42 of 1
it's not a hunch, you're just recreating the same logic
it's happening because of your settings
if you aren't waiting long enough, then you'll get oddness
For me it was a hunch - since I am not as efficient in scripting templates, so assumed it would give the same result.
e.g. door opens and updates in 0.5 seconds. gate opens and updates in 3 seconds
if you toggle the cover between 0.5 and 3 seconds, you're going to have oddness
Fair, but I don't.
I am not at home - drive up to my gate and call up Google to open both.
It asks for PIN and receives it.
Then it opens one but not the other
So there is no way for any additional toggles in the interim
I'd love for it to be this simple!
It's a group from the UI, so how can there be spelling errors.
there's nothing else to it other than your binary sensor not reporting the correct state
They are selected from the drop down menu
in your original cover template
Looking into it now.
Wait, if the original template works OK for each gate separately, then there can't be a spelling error, since the group is selected from the UI.
Am I missing something?
if they work separately, and they don't work in the group, then it's a hardware problem
do they come from the same hardware?
the momentary switches?
ok, are you sure that device can except 2 signals at the same time?
because HA is extremely fast
Both integrated in exactly the same way with a nearly identical magnetic sensor for open/close detection
wait, but are they separate hardware or the same hardware?
2 covers being actuated via a Satel alarm system which has magnetic sensor for closure detection
Different motors, and everything obviouslyt
You may be on to something that the Satel central unit receives two requests two quickly
There's nothing else it can be
It may not handle any queues hence the request no.2 gets discarded, but how to know that is... tricky
you'll have to add a delay between the two calls
and you can't use thefes's templates
if you want to get fancy, you could use your home/away state to open the gate first then the garage and vice versa
I live in a larger city and sometimes pass by my house on my way to the kid's school, so having things open on their own is a bit too much for my taste.
No you're not understanding
I'm saying, when you press the button, if you are home it opens in x order, otherwise it opens in y order
Thanks for the clarification. This said, I wouldn't need more than one order of opening things
Just so that it opens both, which seemed super simple, but it isn't
I'll have to search the web for some example templates with entities having a delay between actions.
I'll need to have it so it's 'wife-safe' as well...
you don't need templates...
Having things not work while I am out is a quick way to an Armageddon... lolz
the turn_on section is an action section
identical to automation action sections
just put a normal delay in it
Fair point!
between 2 turn on calls
0 templates
- service: switch.turn_on
target:
entity_id: switch.a
- delay:
seconds: 1
- service: switch.turn_on
target:
entity_id: switch.b
But then if it's just a button with an action having a delay, I'll probably get myself into a pickle with the flip-flopping effect I discussed with @marble jackal .
If one gate is open and the other closed, it will start flip-flopping.
Unless you use and in your value_tempalte for the cover
and requires both to be on to be on
I understand it must be frustrating, having it all laid out in your head, trying to explain it. Sorry for being less than quick in catching what you mean.
you can also use chooses to conditionally choose which one should turn on if it's not.
But then wouldn't this go into a template cover?
I am sure I can, but it's beyond my current skill set. I'll look around for examples.
Do you know how to make a choose in an automation?
You seem to think this requires templates, but it does not
you already have your template
maybe you're confused about the name of the channel and the integration you're using
you're using the template integration to create a template cover
the word template does not refer to the templates in this channel
this channel is for jinja templates
which the template integration uses
this is a template {{ ... }} or {% ... %}
everything else is yaml
So, a choose is simply yaml. You can build the yaml in the automation editor and then just copy/paste it into your turn_on or turn_off section
Not at this time, but later today I will. 😉
the problem is that all actiosn (open, close, stop) use the same switch.turn_on action
that's a momentary switch
it's basically a button press, which initiates an action based on the current state
That is exactly true!
All my garages are binary_sensors w/ momentary switches
I do not have his problem
he has some hardware thing going on causing the confusion
I've been thinking of getting the gates out of Satel and putting some Shelly or other in there to get them to be smarter, but still, the garage door doesn't have an up/down - only a momentary switch in itself.
I have a group of garage doors with template covers and they work great without delays and I have a similar setup to the template you created @marble jackal
I'll check inside the Satel software if there is some queue handling there.
I don't have a garage nor gate 😛
Happy man!.... lol...
Do you own a car? Or even need one?
#JealousOfEUTransportation
Yes, you are corrects I mix up what it means to have something as a template (integration) and needing a template inside the 'action' .
which you don't
you only need a template for value_template
I do own a car 🙂
all the rest can be done w/ normal actions
So within the cover template created by @marble jackal I'll need to find a way to add a delay between the actions called.
Or am I still confusing things?
no...
I am so sorry, I don't get it!
choose
How do I go from a momentary switch integrated into HA to an operating cover???
I always assumed I need a template_cover
my man, can you please go to the automation editor and look at choose in the action section
turn_on:
- action 1
- action_2
those actions are exactly the same as the action sequence in an automation
I already have him the example above 🙂
here
he just needs to use a choose for each of those if he wants them to always be in sync
with an added normal condition checking the binary sensor state
I had it on my to do list to add a hyphen in the docs for all template entities in those sequences, because it's unclear now that it can be a list
yes, but people still don't know what the hyphen means so it's a moot point
true
or someone uses scripts in the action to make the config smaller
really annoyed by the examples in general
Within choose I'd go about and list all 4 options, with both closed, one open, the other open and both open, correct?
Actually, that won't work, because this doesn't take into account what the intention is – to open all or close all.
@undone jungle I converted your message into a file since it's above 15 lines :+1:
@mighty ledge not sure if this is what you meant.
I would have made 2 separate chooses with a delay in between
the first choose would look at main_gate and only turn on the switch if it was not on
the second choose would do the same for garage_door
Then you'd apply the same logic to the close_cover section, but with 'off'
e.g. if door not open then open, wait 2 seconds, if second door not open then open
OK - working on it
@undone jungle I converted your message into a file since it's above 15 lines :+1:
yes, but not together like that
your open_cover will only do the turn on stuff
your close_cover will only do the turn_off stuff
It's not together now. It's only the turn_on (i.e. open).
it is
you have it in 1 action section
so how do you plan to put that in the open_cover action section?
Nevermind, I didn't save something... sorry!
@undone jungle I converted your message into a file since it's above 15 lines :+1:
Is that what your meant?
yes
after you add them to your open_cover section and close_cover section, make sure to change the or in your value_template to and
also, when coping from that code, don't include the word action:
The open_cover and close_cover will accept the hyphen list?
I just saw you two discussing it but wanted to confirm it pertains to covers as well
it pertains to all 'action' sections
I wish they never supported the non dashed list
How would I handle the stop in this scenario?
Since I want it to indiscriminately send another switch, making both covers stop moving
It doesn't like this syntax:
stop_cover:
service: switch.turn_on
target:
entity_id:
- switch.main_gate
- delay:
hours: 0
minutes: 0
seconds: 2
milliseconds: 0
- switch.garage_door
here
So annoying, this channel doesn't convert longer code into files (or I am to think to figure it out).
I arrived at this
your icon template is using or,swap it to and and it should be good to go
I am still confused as to why the choose would even be necessary if there is no choice of any kind
It's a list of operations one after the other.
If the condition is met, the operation takes place
you still have or in the icon template
I did correct it before pushing it out.
because you said you want to keep the covers in sync
Unfortunately they don't.
if one door is open and the other door is closed, your actions will keep them in sync
I just opened them and they both opened as planned
But I tried stopping them since it's an important safety feature
When I initiated the stop the garage door closed while the main gate remained open because it didn't finish opening.
I think this will always be the case since there is no way for both to know what the other one is doing
that means your binary sensors do not output the states the way you described
There is no running parameter
right
then it relies on the binary_sensors state
hence why you have all those 'choose's in there
if you stop it and the system thinks 1 is open and the other is closed, you're going to have oddness
I need to read up on the choose. I understand it is needed, but the naming is just confusing, since there is no actual choice taking place
At least in my head it should be sufficient to give a condition of if off, open and if on, close
But it seems like this is wrapped inside the choose action
there is a choice though
you're choosing to only do the action if it's a specific state
it's doing nothing if it's not that specific state
Makes sense.
The problem is you only know when it's closed (when the magnetic sensor makes contact)
When it doesn't, you don't know if it is opening, closing or open
So that leaves you in the dark for the stop action, which should only be performed when it's closing or opening
And not when it's fully open, because then it will close again
yes, but with momentary switches, that doesn't matter
the only thing that matters at that point is how each binary_sensor retains state
if he stops half way and 1 binary sensor says "on", the other "off", then that's the problem
they both need to report the same way, i.e. contact sensors that only report state when fully closed or vice versa
if one reports fully closed, the other reports fully open, keeping them in sync will be a pita
Oh yeah, one other wrench is the behavior of the motors
My garage doors do not continue their action after stopping. They reverse.
so when I stop half way, my next 'monetary switch' that is pressed will reverse what was just done
Both of his hardware would have to act this way
I'd wager that's an issue he's running into. 1 reverses the other continues forward
@undone jungle ^
Yup, that is exactly what I realized when discussing it with @mighty ledge a few lines above. It's the lack of running state that is the issue mostly.
That is what sometimes will happen for two reasons. The garage door opens first so it will finish first and hence will be able to close if 'stopped'
Second, the gate closes on it's own from a timer (since this is the basic functioning of such gates)
Third, one can actuate both by other means - i.e. Wall pannel
If that would be an option sure - but I don't have enough lines in the ground any more ( between the intercoms, power, etc. I ran out of cable pairs in a multistrand put in by the general contractor)
I bought the house with it in place so would have to tear up the driveway
I believe most such devices do that and both of mine do to. If you actuate them they'll continue the reversed action when actuated next
Nope the both reversed
My issue is the length of time it takes to run each from close to open and the fact one closes on it's own, finally it's also that they are actuated from other places
I accept these oddities
I've been able for the first time today drive home and call up Google to get them both open.
I call this a success and need to just add the device_class so that they ask for a code beforehand
Currently it's a free for all and I don't like it
If I am not mistaken device classes gate, door and garage are 'controlled' correct?
?
Because I don't see an option to indicate to Google which device to ask for a code and which not
device_class only determines the icon for covers
and potentially how they are exposed to other apis
Yup, the latter part is what I care about
I would assume both require a code
Probably Google recognizes barriers as 'controlled'
Without a device class it doesn't so I need to choose one of the once that do
Hello, I do not have so much experience.
I need a counter that indicates how many entities have either the state "abc" or "def". I have from all entities the Ids.
Entity 1: abc
Entity 1: xyz
Entity 1: def
-> here the counter should give 2
How would I do this?
template:
- sensor:
- name: State Count
state: >-
{% set entities = ['sensor.entity_1', 'sensor.entity_2'] %}
{{ entities|select('is_state', ['abc', 'def'])|list|length }}
I don't know if is_state does tricks like that
well now my response looks dumb
Mission: Accomplished
pretty sure it does
Thanks. will try that 🙂
it does
just checked
that was added pretty recently too
in the last year or so
I don't really do any of that fancy stuff in my install, so my exposure to it is posts here and testing them
works perfectly. Thank you
Set it to Garage and it works like a charm. Thank you so very much @marble jackal and @mighty ledge for all your patience and assistance
Hey guys, i have 2 helpers that has a date/time value...I want to show the time past between then...the format is: 2023-06-05 00:00:00
helpers is called start and slut
{{ now() - states('input_datetime.date_test')|as_datetime|as_local }} -> 287 days, 2:57:24.654919
{{ states('input_datetime.rengoring_start') - states('input_datetime.rengoring_slut')|as_datetime|as_local }}
??
same thing ?
yes
I dont understand
{{ states('input_datetime.rengoring_start')|as_datetime|as_local - states('input_datetime.rengoring_slut')|as_datetime|as_local }}
yes
if it put it in a button card it doesn't work
No visual editor available for type 'custom:button-card {{ states('input_datetime.rengoring_start')|as_datetime|as_local - states('input_datetime.rengoring_slut')|as_datetime|as_local }}'.
custom button card uses javascript, not Jinja
I don't know how to do that in JS
other than creating a template sensor
arh okay...
template:
- sensor:
- name: renoeringstid
state: >
{{ states('input_datetime.rengoring_start')|as_datetime|as_local - states('input_datetime.rengoring_slut')|as_datetime|as_local }}
Hi, maybe someone can help me. I want to check if two bits from a json value are set. With a single bit it's work as mqtt switch with this: value_template: "{{value_json.infobt| int // (2**27)%2}}"
check out these:
Filter value_one|bitwise_and(value_two) perform a bitwise and(&) operation with two values.
Filter value_one|bitwise_or(value_two) perform a bitwise or(|) operation with two values.
the first one, in your case
This will not work value_template: "{{value_json.infobt| int // (227)%2 and value_json.infobt| int // (230)%2}}" or should i use & ?
what?
you create a bitmask with your two bits and then use bitwise_and
{{ 0x06|bitwise_and(0x03 * 2**1) == 0x06 }} -> True
Ok now i check how to Bitwise &
Thanks a lot!
- sensor: unique_id: total_house_power name: total_house_power device_class: power state_class: measurement unit_of_measurement: 'W' state: >- {% set gridpower = states('sensor.gridpower') | float(unknown) %} {% set pvpower = states('sensor.pvpower') | float(unknown) %} {{ (gridpower+pvpower) | round() }}
With this template I get two different value updates at the same second. I feel template is triggered both on gridpower change and pvpower change. How can I make sure it triggers only once?
What's the complete sensor code (the YAML)
gridpower and pvpower is updated every minute at the same time, or atleast in within few milliseconds. Is there a delay to wait if all inputs are settled in and then I can calculate template value?
As you are using the new format, you can use a template trigger which compares both last_changed values and triggers when the difference is less than eg 5 seconds
Your current template will return errors btw, if the value for one of the sensors is non-numeric it will fail because you didn't add quotes around unknown. It will search for a variable unknown
And if you add the quotes you will get an error because you'll end up with
('unknown' + 'unknown') | round()
You should use an availability template here
Thanks, got it working with "state trigger". Not sure if I need to use "template trigger" instead
Time condition for serial template trigger sensor
Hey all. I'm taking my first leap into date/time in templates and it's giving me a real headache. I'd like to convert the current ISO date time into a simple HH:MM display.
I have this code but it seems convoluted, how can I simplify it?
{{ states('sensor.date_time_iso') | as_datetime() | as_timestamp() | timestamp_custom('%H:%M', local=true) }}
(yes I know there is a sensor.time sensor - this is more for my learning)
{{ (states('sensor.date_time_iso') | as_datetime).strftime('%H:%M') }}
and if the iso is UTC, then you'd need an extra
{{ (states('sensor.date_time_iso') | as_datetime | as_local).strftime('%H:%M') }}
Perfect, thanks a lot 🙂
does that just output the current time?
if yes, then...
{{ now().strftime('%H:%M') }}
all that extra datetime fluff is because state's are strings and you need to convert the string to a datetime object
please let me get back on this generic templating question: what would be most efficient: have template sensors use a |round() to limit state changes on many decimals in the DB (as we all did before) opposed to the now available rounding in the frontend.
seems the round on all of those template sensors is an extra template step in itself, so it might be just as powerhungry for the system, albeit mayby not for the DB
The operation is so small that it doesn't really matter
Personally, when I write code, I don't round things until I display them.
its just that on an entity with 10 decimals, there are huge amounts of state changes all of the time, written to the DB
I.E. leave it to the frontend
yeah thats what I do now too
If you want a smaller database, by all means, round it
I do not give two shits about my database size
well, no, size doesnt matter.... it's the effort that counts 😉
I'm at just over a gig for 40 days of history
and now with everything moving towards LTS, I'm not even sure I need 40 days
bottom line would be: round (is costly in templates) and have fewer state changes, or dont round (costly in DB writes) and require additional Frontend power
only yesterday did I re-migrate to SQLite and have a 10 day retain. might be even better to lower that, and have better graphs on the more-info. and no have those statistics blur the historic truth
can we somehow escape the ! in {% set datum = !secret vj_marijn %}?
or use secret like this at all
that's not possible
never has been
the best you can do is set it to a variable in an automation or attribute on a sensor. But remember, you won't be able to use this if you set it to an attribute as it will always be 1 state behind. But that probably won't matter if it's just your birthday.
yeah that is what I am trying to do.As you witnessed yesterday, I rewrote all of my sensors to be verbose, and ditch the this.variable. But mainly because it causes trouble when using them as trigger template. set an attribute, and use that in state, and the state breaks. As regular template (but I dont want that, I want it to be limited to once a day) there is no issue at all
Why not just put your dates in a macro
custom_macros\birthdates.jinja
{% set vj_marijn = '1901-10-04' %}
then in your template
{% from 'birthdates.jinja' import vj_marijn %}
{% set datum = vj_marijn %}
it's basically the same as secrets
hell, you can set them as datetime objects too...
{% set vj_marijn = '1901-10-04' | as_datetime | as_local %}
they will maintain their object
- unique_id: marijn_verjaardag
state: >
{% set event = this.attributes.secret|as_datetime|as_local %}
{% set year = 1 if event.month < now().month or
(event.month == now().month and event.day < now().day)
else 0 %}
{% from 'easy_time.jinja' import count_the_days %}
{{count_the_days(event.replace(year=now().year + year)) }}
attributes:
secret: !secret vj_marijn
but no that breaks the state when used as trigger template
not sure how it does
nor am I, but it does, ive tested this extensively . with or without defaults
or the .get() format
you're importing a mcro already, there's no way importing a second macro will break triggers.
from what Ive been able to establish, is we can use this.state in attributes just fine, but when any of the main config options refers to a this.attrbutes.xxx, it breaks when used as a trigger template
oh you're still talkinga bout that, not the macro
just use the macro
not to mention, it's more optimized
let me try.
when I do: {% from 'feestdata_macros.jinja' import vj_marijn %} {{vj_marijn}} an error is returned: expected token 'name', got 'end of statement block'
while this is in that file: {% macro %}{% set vj_marijn = '1910-05-27' | as_datetime | as_local %}{% endmacro %}
no you don't need a macro
literally just this line in the file
{% set vj_marijn = '1910-05-27' | as_datetime | as_local %}
@floral shuttle ^
ah yes, that helps. though, setting that on an attribute with datum: > {% from 'feestdata.jinja' import vj_marijn %} {{vj_marijn}} shows Datum 27 mei 1910 om 00:00:00 where using datum: '1964-05-17' reveals the neater:Datum 17 mei 1964
Sure, but then you can't use it without converting all the time
do you really need 'datum' to be friendly?
if yes, just make a separate attribute
but TBH, it's pointless if you're just using it for notifications and you'll be translating it anyways.
well no, I was surprised the frontend did that, and ofc, next one gets used to that 😉
the frontend knows how to handle datetime objects
that's why everything should be datetime objects, let the frontend display it and the user should choose how they want it displayed
So user A could have a different display from user B
just to give you an idea why all of this is done. And all of those attributes need that date...
Yah, but for me, I wouldn't have any of those attributes.
I'd make a set of template sensors with 1 calc
1 for age, 1 for days away
days away would be used for an automation for notifications
age would be for display in the UI
my frontend is made with these card: type: custom:template-entity-row entity: '[[entity]]' state: > {{states(config.entity)}} {{'dag' if states(config.entity)|int(default=-1) == 1 else 'dagen'}} secondary: > {% set event = state_attr(config.entity,'datum')|as_datetime %} {{state_attr(config.entity,'type')}}: {{event.strftime('%d-%m-%Y')}} and automation is using state = 1 or 0
wrap-up so instead of converting that date string 6 times per template sensor like: {% set event = '1964-08-27'|as_datetime|as_local %} {{(now() - event).days}}
I'd be better of importing those from custom_templates?
yes, that
{% from 'feestdata.jinja' import vj_marijn %}
{% set event = vj_marijn %}
{{(now() - event).days}}```
If i use a media selector ... how do i do a trigger on the state change of the media player...
I have this block:
trigger_variables:
media: !input media
player: "{{ media.entity_id }}"
Do i need to use a template trigger if i want to access that player?
When i try to use "{{player}}" as an entity_id in a state trigger
Before I post, how do I paste code so it's nicely formatted and blocked like above?
Triple backticks (`)
Are you posting an answer for me!
make it a entity selector, not a target selector. Then use !input media on your trigger entity: field.
@solar star I converted your message into a file since it's above 15 lines :+1:
So whats the point of the media selector?
ah
so you have to get aroudn that limitation
so i need to select an entity and then also would use media to select the same entity + the media i want to play
that means the output of your !input needs to be able to go directly into the field without needing a template
well, you could just not use the media selector at all
I need a local file as well to play
Turning my fireplace scripts into a blueprint:
If fireplace on + no sound on sonos - play user selected "fireplace sounds"
so you need to select fireplace + a media_player + a sound
Then you'll need both
lol that you need a sound system to make your fireplace sound like a fireplace
this is why we have technology
Yup... although I'd really like them to close out my PR to allow cloud control for the unit ... its unfortunately more reliable than local
I still need a trigger_variable right and then a template trigger?
oh nevermind
looks like i can use !input in the platform state
you can use !input in any field as long as the output of the input matches what the field requires
!input is just a glorified secret
or yaml anchor
@royal vector I converted your message into a file since it's above 15 lines :+1:
@royal vector No, the template sensor is not required, it used to be back in the day based on the intentions of the code. It baiscally was made to get the switches previous state. In the past, you weren't able to self reference in a template. Now you can with this.state.
i didnt think so, but i cant find a way to get just the cover config referencing the state of the binary sensor to work as i expect it to. heres is my config that i was using
@royal vector I converted your message into a file since it's above 15 lines :+1:
Hi, how do I express this as a template value?
V = dT x Q
V = Volume (L)
dT = delta Time (h)
Q = Volume flow rate (L/h)
dT= last time stamp - (last time stamp before that)
?
@royal vector, you don't even need those conditions in the open_cover or close_cover because you're using switch.toggle
do you have Q?
if the answer is no, then you're at an impasse
unless you're looking for Q
and you have V
TLDR, wtf are you looking for and what data do you have
Mmm...algebra
remember when I said all that crap about the config helper in VSCode? this just popped up when I started it at my house 🤣
I just configured it once and good to go
well apparently I installed it and then never did anythng with it @ my home PC
lol I have a water meter that only reports instant flow rate for example, 0 L/h or whatever x L/h. I want to calculate total consumption from this based on the time.
it updates everytime the flow rate changes
no flow = 0 L/h
does it have a device_class and state_class?
if yes, just use the energy tab
it does it for you
really, from a rate it can calculate that?
Yes, all you need is the rate and you can calculate V for any timeperiod
fantastic! then I just have to create a template sensor with the device_class and state_class
ah ha...im readig about it now
https://www.home-assistant.io/docs/configuration/customizing-devices/
just confirm, if I made a customize.yaml !inlcude file (under homeassistant: in my configuration.yaml)
the sensor should have this state and device class
device_class: water
state_class: 'total_increasing'
unfortunatly, even with the settings above and correct class, it won't allow me to use it as a water consumptions sensor because the units are L/h not, L, gallons, etc. So, it seems it does not accept rate unless I did something wrong
I'd guess you need a riemann sum on top of the rate to get an accumulated value
how do I get it to drop the time unit though? I have ~~divide ~~ multiply by dT
V = dT x Q
can anybody give me a hint how to calculate the difference between {{ now().time() }} and a input_datetime helper with time only? I want to find out whether the time in the input_datetime helper is not yet reached.
I would do something like:
{{ now() > today_at(states('input_datetime.test2')) }}
hi. how can i display the volume level of my media player in the frontend ui?
media_player.home_assistant_speakers
attribute is called; volume_level:
Why Does this not work?
Thanks Rob! I while doing some RTFM I came across today_at, but did not get that this is my solution at all.
Good evening all, trying to grasp still all the possibilities of templates in HA.
I have a sensor that provides me with a lot of data via its Attributes.
In these attributes I find item A, item B, Item C and so on.
I would like to create automatically for each item a button(image) that shows me some information gained from within these attributes and when clicked calls a service.
I am already fiddling around under developer tools -> template.
Is this possible? Or should I create each button manually.
Just trying to get a headstart, quick learner here 🙂
This is what I currently have in the template editor:
http://pastie.org/p/4lH2HRoPmUIe5F78Di5pzX
It allows me to get the necessary values, but I cant seem to get them working as sensors of some sort. My modifications to the configuration.yaml dont create them as actual sensors, so I am kinda stuck.
You can't dynamically create template sensors by looping through a set of attributes. For each attribute of interest, you'll need to explicitly define a template sensor. But you already have quite a lot of what should go into the state: of each template sensor.
Follow the format in the template sensor docs closely.
With clever use of YAML anchors you can maybe simplify the code, but you can't template the entire YAML code for your config
it might look valid in the template checker, but that doesn't check for valid YAML
if you really want it dynamically, put all the data in a attribute, although if you have a lot of items, it might get too big to store it in your database
It is already in an attribute, but with loads of other stuff in there too:
http://pastie.org/p/499EILoQKddbpXWP5Ex3Rk
Seeing that I want for each item only 2 lines of information each...
or is that exactly what u mean, gather for each of the items the 2 lines of info that I need, add them in a new attribute and use that one.
that's what I mean, create one new template sensor with a state of just ok or whatever, and take the 2 values you need and put those in an attriubte
however, if it is for displaying it on a dashboard, you won't gain anything in that way
You might be better of using a Markdown card, which accepts templates
The goal is to create a separate button for each item on the dashboard, each button includes an image and the info gained from the 2 lines.
I wonder, what is the most used or best way to check if "2023-06-07T08:00:00+00:00" is today. Most probably an often-used step, but I was not able to find examples in the community. Or I searched in a wrong way. Any example or proposal would be appreciated.
as_datetime("2023-06-07T08:00:00+00:00").date() == now().date() is what I would do
In that case you can look into custom:auto-entities
#frontend-archived can probably help you with that
it can dynamically create cards based on templates
@marble jackal Thanks, I'll have a look 🙂
Trying it in a different way as well, just to see if I can create one sensor.
- binary_sensor:
- name: Ice Tea + '{{states.sensor.grocy_stock.attributes.products[1].name}}'
- state: "{{states.sensor.grocy_stock.attributes.products[1].available_amount | int(0) }}"```
But I get an error msg:
Invalid config for [template]: required key not provided @ data['binary_sensor'][0]['state']. Got None.
But when I look at examples of other template-binary sensors, my code seems to be alright.
Is it just not possible to gain information out of the attribute this way?
remove the - before state
you are creating a second binary sensor now, and the first one is missing the state template
the second one is missing the name but that one is optional
you probably have a binary_sensor.template_1 or something simalar now
also, you are aware that you are creating binary sensors now right, so the state will be on or off
@marble jackal Thanks, that solved it. The first template is always the most difficult one 😄
I thought a binary sensor would be good in my use case, but just checked it out and it wasnt. Changed it to a sensor and it shows now the data that I want.
I now have a working button that shows the information that I want 🙂
It calls a service, that does a manipulation on the data and after a delay, it shows the updated data.
Thanks for your help mate, much appreciated.
Basic template question. Is there anyone here?
“`
template:
{% for matter_device_entity in integration_entities('matter') -%}
- binary_sensor:
- name: "{{state_attr(matter_device_entity, 'friendly_name')}} Available"
unique_id: "{{matter_device_entity}}_available"
state: "{{ is_state('matter_device_entity', ['unavailable', 'unknown', 'none']) }}"
{% endfor %}
“`
Hey, is there someone that knows how i could get something like this to work in homeassistant? I guess its not possible to use a for loop to define entities
- name: "{{state_attr(matter_device_entity, 'friendly_name')}} Available"
that's not possible.
There is no way to "make it possible" either.
I know that. My question was if i can achieve something that gets me a similar result a different way. My goal is basically to have an entry in influxDB where i can see when devices are available/unavailable. I can of course do all of this manually, but is there a more generic way to do it(doesn't need to be a template)?
No, there's no way around this. You can't dynamically create entities
you can use yaml code to create the yaml and then paste it into your template file
that's the best option
You could create a custom integration that does this, but that would require integration creation knowledge and python knowledge
Thanks for the answer. I have also thought about making a costum integration, but that would just be overkill for my usecase.
Struggling to get this template right, but I have a group of sensors in my freezers.... Sensors.freezer_sensors..... I'm to make a template sensor that will show the number of sensors greater than 10... Basically if any sensors are too hot.
I have expand | map(state) | map(float) | list.... And that works. But I can't seem to get the list to filter entries less than 10. Thoughts?
map('states') | select('is_number') | map('float') | select('>', 10) | list | count
Thanks
I was trying map >
Is there a way to get the entity id of the ones instead of just the value?
not without a for loop
Not sure if this would fall under templates or not, but is there any way to create a button and have it associated to an existing device? For instance the android tv remote integration. Its a cool integration but out of the box doesnt have any buttions really. Id love to be able to add 2 or 3 buttons on the device that lets me open apps for instance
you can't add items to devices in the devices page
but you can just make scripts or button helpers that aren't linked to the device
you can definitely create dashboard buttons or whatever that can call the remote.turn_on service with custom options, ie to open specific apps. https://www.home-assistant.io/integrations/androidtv_remote/
You have to create all the buttons yourself manually, it doesn't generate any by default at all.
Well not devices to devices, but adding entities to devices. Like with a mqtt sensor I can make 4 sensor and associate them all to the same psueudo mqtt device
was just curious if there was a way to do that with other entities like add buttons that would run a script, etc..
Yes, as I said, that's not possible
There's no way to add to existing devices. Helper entities can in some circumstances, but that's it. IIRC the only integration that does it is the switch as X integration.
Interesting okay guess Ill just make a script for now then
The android TV remote creates a single remote entity and that's it.
You can create buttons that do whatever you want, but those aren't device entities on the remote, they're just buttons that call the remote service or scripts or whatever.
Yup, was just hoping there was a way to associate them so when I look up the remote I can actually see the buttons sort of like quick actions on the device itself
Got it, any idea why remote wouldnt even appear as a service for me?
that means you don't have an integration that creates a remote
Yeah seems because the tv was turned off when HA started it was giving an error. All fixed now though
Yeah, the android tv remote. Its been super flaky for me in general. I had to reconnect it the other day
When i have a rest_command like that
Klimaanlage_Buero_SwingH:
url: http://192.168.178.50/cm?cmnd=IRhvac{"Vendor":"PANASONIC_AC","Model":3,"Mode":"Auto","Power":"On","Celsius":"On","Temp":18,"FanSpeed":"High","SwingV":"High","SwingH":"Left","Quiet":"Off","Turbo":"On","Econo":"Off","Light":"Off","Filter":"Off","Clean":"Off","Beep":"Off","Sleep":-1}
how can i say that the command for Power or Temp should use a entitiy state from homeassitant?
you have probably answered this 100 times already guys, but what do with my platform: template sensors now (tried searching forums but no joy_) fixed all the other stuff, removed skyq platform: but still get his error and not sure what to do ```The version platform for the sensor integration does not support platform setup.
Please remove it from your configuration and restart Home Assistant to fix this issue.``` do I just move all the sensors into command line and remove platform from them?
I think I just found it Fes, restarting now, it was in my system monitor template
fingers crossed
It should be something with platform: version
found it, has not popped up on restart now, it was hidden in my system template, in-between two template sensors lol cheeky line of code
Is there a way for a script to write a dictionary to an input text sensor or something? I want to write the last 10 script calls variables passed to it that cleans out every 3 seconds, to a template sensor somehow for memory. The goal would be if the script received the same set of variables in the last 2 seconds do nothing for example
not to an input text, that's always a string
you can write it to an template sensor attribute
How would I write it to a template sensor attribute?
a trigger based template sensor with an event trigger
you can then send an event in the script, with the data you want to store
Interesting. Any idea how I could make a template store up to 10 events only keep each one that comes in for 3 seconds? I assume I would also send a timestamp with the dictionary so that the template could filter them out when it's older than 3 seconds
Then the max of 10 wouldn't matter only events less than 3 seconds get to stay
you writ the wanted data and a timpestamp, and clear it up on every update, and on a 1 minute time interval
Yeah that's what I thought. What's the service to call an event? I'm not seeing it.
Lol literally called fire event nevermind
It's saying it expected a dictionary for dictionary value for event data
"{{ { target_lights: lights_setting,'set_lights':set_lights,'timestamp':'foo' } }}"
Isn't that a dictionary ^?
you need to provide a key for the data
event: foo
event_data:
bar: '{{ some data in a template }}"
Oh 🤦♂️
you can also do this
event: foo
event_data:
lights_setting:
set_lights: "{{ set_lights }}"
timestamp: "{{ now().isoformat() }}"
Good idea. In terms of the template trigger how should I go about adding the data so it's stored for 3 seconds. There could be 5 events within a few seconds of each other so a lot of data could come in at once and need to be stored. The goal of this is to dynamically reject some service calls to turn on/off lights. All my automations call this script to turn lights on. If someone hits the switch at the same time as my presence Detection turns the lights on they will end up turning them off lol. So rather than at each automation building something to stop that I figured I should do it here.
- trigger:
- platform: event
event_type: 'Master Lights Script Data'
sensor:
- name: "Maater Lights Script Memory"
state: 'hello'
attributes:
memory: "{{ trigger.event.data }}"
This may or may not do what I want but still a good exercise I can keep for future reference.
You need to create a list with events and add each new event to the existing list using this.state
Hi all - I'm working on an automation, and HA is throwing the following error: Template variable error: 'dict object' has no attribute 'to_state' when rendering '{{ not (trigger.to_state.state in ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning', 'Tornado Watch', 'Severe Thunderstorm Watch', 'Flash Flood Warning', 'Excessive Heat Warning']) or (is_state('sensor.weatheralerts_1_alerts_are_active') == 'No') }}' The code that I'm using can be found at https://dpaste.org/hsfn8 - I could use a second pair of eyes to see where my wheels are falling off here. It seems to be working OK when I manually set the state for sensor.weatheralerts_1_alert_1_most_recent_active_alert, but evidently HA is having a kitten about it.
you didn't include the actual trigger, but that is usually caused by you just running the action of the automation and not letting it trigger
Or you didn't use a state trigger. Please include the whole thing when sharing code, rather than just the snippet you think is important
Here's the entire automation: https://dpaste.org/DiaLt
ok, so you have two triggers:
trigger:
- platform: state
entity_id: sensor.weatheralerts_1_alert_1_most_recent_active_alert
- platform: time_pattern
seconds: '/3'
trigger.to_state will only be available when the first one fires
so every three seconds, any reference to trigger.to_state will fail in the way you described
I was wondering about that, TBH... I've had input from a few others helping me along with this, and I think that might have muddled things up. That said, to this totally n00b mind, it seems to me that if I have the sensor state defined under action, then I wouldn't need it under trigger, correct? Because I'm telling the automation to kick off every 3 seconds (which is making the light flash in red mode) and checking for the current status of that sensor.
yes
OK, I will take that statement out and see what happens.
the whole thing seems kinda fragile, though. You're running it every 3 seconds and you sometimes have a 2.5 second delay in there
It felt like this was a fairly straight-forward operation that I wanted to make happen, but it has been difficult to get just right.
Eh, it could be somewhat fragile.... but I'm going to admit that I'm still learning, and I'm 100% sure there are better ways to handle this.
I would use a state trigger and a repeat/while in the action
and maybe a second trigger for HA restart
or repeat/until
Essentially, a specific alert is issued by NWS. It either triggers flashing red, solid yellow, or solid green. Furthermore, IF the lights were at the flashing red or solid yellow state, and that particular alert has been cleared, it needs to go back to green.
yes, you could do that with what I suggested
and it wouldn't trigger every 3 seconds forever
The last time we had a warning, the lights went over to flashing red as they were supposed to, but never came out of that mode. The automation was still picking up on the "most recent active alert" and didn't pick up that there was no longer ANY active alert. That's a totally different sensor altogether, and what needs to be integrated into this as well.
ok
If I flow chart this in my head, I think the automation probably needs to check if that active alert sensor is set to Yes or No... If no, go about your day. If yes, then drop into the automation we've been looking at.
that's a trigger
So, that could be put up at the beginning of the automation, where I am taking out the current "platform: state"
And, in doing so, my new trigger would be a platform: template and then I'd follow that with a value_template: "{{ is_state('sensor.weatheralerts_1_alerts_are_active', 'Yes') }}
that's just a state trigger
you don' t need a template for taht
trigger:
platform: state
entity_id: sensor.weatheralerts_1_alerts_are_active
to: 'Yes'
OK, I'm working on modifying the automation. I'm not going to address the time_pattern just yet, as I only want to tackle one issue at a time so as to not create more variables that could derail things. 🙂 I think the only other issue I have, is how to reset back to green when the "alerts_are_active" flips back to "No"... as it stands now, the automation will stay in either red or yellow, because there's nothing to tell it to go back to green when the alert clears. Which is what happened the last time, and how I fell into this rabbit hole. -- In my code, in the conditions field, could (or should) I add a condition where alerts_are_active is also set to yes?
Because if I do THAT, in the condition for green, I could tell the automation to check to see what the state is for alerts_are_active.
Thus, my condition for red, for example, would look something like this: conditions: "{{ is_state('sensor.weatheralerts_1_alert_1_most_recent_active_alert', ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning']) }}" and "{{ is_state('sensor.weatheralerts_1_alerts_are_active', ['Yes']) }}"
Hmmm.... except I'm not doing a list for alerts_are_active I'm only checking for a single state, so I need to change that.
I think all I need to do is take the [ ] out from around the Yes
yes, but that doesn't matter
(I really do appreciate your guidance on this, BTW... I'm trying to learn...)
a list of one item is the same as a single item not in a list in that case
OK - let me update the entire section and see what HA says....
HA is complaining about a "Bad indention" at my and statement.
OK, I've broken down the two sensors into two separate "condition: template" statements.
That seems to make HA happy.
Here's the current code: https://dpaste.org/TYoBx
this should be states(): state('sensor.weatheralerts_1_alert_1_most_recent_active_alert')
and you're still using templates where a "simpler" state condition would suffice, but that doesn't matter for functionality
and this will still blow up:
- conditions: >
{{ not (trigger.to_state.state in ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning', 'Tornado Watch', 'Severe Thunderstorm Watch', 'Flash Flood Warning', 'Excessive Heat Warning']) or (is_state('sensor.weatheralerts_1_alerts_are_active') == 'No') }}
for a couple of reasons. first, you have no state trigger. second, (is_state('sensor.weatheralerts_1_alerts_are_active') == 'No') is broken syntax
OK... I didn't touch that one this time around (yet), I only worked on the red & yellow. That was the example I was given by someone else when it broke last time, to try to fix it. 🙂 So I could make it like the red & yellow, but I have to admit, I'm still a little confused about the states vs templates. (Sorry....)
OK, here's the code modified for the green condition: https://dpaste.org/cUT3T
The logs show that I've pretty much got everything cleaned up to where HA is almost happy... I'm getting one error now with two different descriptions in the same error: Error in 'choose[0]' evaluation: In 'template' condition: UndefinedError: 'state' is undefined and Error in 'choose[0]' evaluation: In 'template' condition: TypeError: is_state() missing 1 required positional argument: 'state'
That's all it's telling me, so I'm assuming it's referring to my choose statement.
(Trying really hard to follow along here....) So, I'm checking for the value of two different sensors. Right now, I've got two condition: template statements, each followed by a value_template statement. However, you're saying that I should use states instead. I'm unclear how I would replace what I have with the proper "states" statement.
value_template: "{{ state('sensor.weatheralerts_1_alert_1_most_recent_active_alert') in ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning'] }}"
you have "state" where you need "states"
and you have is_state() somewhere without the second parameter
I don't see where, but clearly somewhere
OK, I'll investigate that deeper...
So I would replace all of my is_state with states in those multiple type lines.... (Also trying to follow along in the Templating document.)
Dang it...
value_template: "{{ states('sensor.weatheralerts_1_alert_1_most_recent_active_alert') in ['Tornado Warning', 'Severe Thunderstorm Warning', 'High Wind Warning', 'Extreme High Wind Warning', 'Ice Storm Warning'] }}"
you're missing an "s"
there are 10000 ways to do this and I don't care which you use, but you have to do one of them correctly 🙂
I want to use the way that works. 🙂
I do appreciate the help, and my apologies if I didn't seem to pick up the concept(s) quickly.
Hello, I was wondering if there is a way to retrieve yesterday's attribute massage from local calendar. Currently, I am using the following code:
cut_off_days_yesterday:
unique_id: cut_off_days_yesterday
friendly_name: "Cut Off Day Yesterday"
icon_template: "{{ 'mdi:calendar-clock'}}"
value_template: "{{ states.calendar.cut_off_days.attributes.message if now().strftime('%H:%M') == '23:59' else states.sensor.cut_off_days_yesterday.state}}"```
However, I have noticed that after Home Assistant restarts, it displays as "unknown" status until it updates at the end of the day again. I was wondering if there might be a more reliable alternative.
Hello everyone ! I have used HA for a lot of things but today I struggle with something because I don’t 100% grasp the method of programming in HA
I am making a program that make booking on a website, everything is managed in python, I just use HA as an interface to show info, or send command.
So basically I am running into a problem, I have 4 next reservation I want to show nicely. The problem is that I did it with webhook and sensor, but I did have a setup that was long (each user has 5 sensors), and it doesn’t look nice in the interface.
I just want a simple text for each user, I read that I can do that with markdown but couldn’t do it by myself…
Here is my code
template:
- trigger:
- platform: webhook
webhook_id: cisjzbzje
sensor: - name: "Booksite seat user1"
state: "{{ trigger.json.seat }}" - name: "Booksite date user1"
state: "{{ trigger.json.date }}" - name: "Booksite hour user1"
state: "{{ trigger.json.hour }}" - name: "Booksite status user1"
state: "{{ trigger.json.reservation_status }}" - name: "Booksite upcoming user1"
state: "{{ trigger.json.upcoming }}"
- platform: webhook
The problem is that this code is duplicated for each user, if it were in python I would just have a dict or a list to manage this, but I don’t understand how to do it in HomeAssistant
My second problem is about the dropping list. I have a list of 4 next reservations I could send in a nice json to HomeAssistant, but I don’t want to store them in 4 different sensors for each user. Is it possible to store them in a list ?
If so, is it possible to have an id associated with each item ? The id will be received with the item in the webhook.
The id will serve if I want to manage the reservation in the drop list. I will select a future reservation from the list, it will select it by the id associated to it, then send a request to my server to do something with it.
I won’t go into details about my python program, but if I could just send an Id it will interpret it ok. But the id has to be the same as the one the program have sent to HomeAssistant… thank you for any help you could provide 🙏
Hey guys, was sent here from @integrations. I have a shelly h&t (temp sensor) that is integrated into HA. Im trying to set up a payload template to broker the temp-reading so that my NibePi (system i use to control my heat-pump).. Any1 care to explain what im supposed to do?
use a trigger based template sensor (new format, you are using the legacy format here) and a time trigger.
Trigger based template sensors resore their state after a restart
please format your code as code
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.
- name: "NAS Status"
icon: phu:nas-v2
state: >
{% if is_state('sensor.nas_volume_1_status', 'normal') or is_state('sensor.nas_volume_2_status', 'normal') or states('sensor.nas_upload_throughput')|float(0) > 0.1 or states('sensor.nas_download_throughput')|float(0) > 0.1 %}
On
{% elif states('sensor.nas_download_throughput')|float(0) > 1.9 %}
Powering Up
{% else %}
Off
{% endif %}```
ON and OFF work but not Powering up - What have I done wrong?
The if else code breaks on the place where it first renders true.
Powering Up will never be true first with this logic because > 0.1 was earlier in the statement rendered as true
I see what I've done
it will never reach that part of the if statement.
if states('sensor.nas_download_throughput')|float(0) > 1.9 is true, then states('sensor.nas_download_throughput')|float(0) > 0.1 this is also true
I have the wrong sensor in there haha
so it will be on
- name: "NAS Status"
icon: phu:nas-v2
state: >
{% if is_state('sensor.nas_volume_1_status', 'normal') or is_state('sensor.nas_volume_2_status', 'normal') or states('sensor.nas_upload_throughput')|float(0) > 0.1 or states('sensor.nas_download_throughput')|float(0) > 0.1 %}
On
{% elif states('sensor.nas_smartplug_watts')|float(0) > 1.9 %}
Powering Up
{% else %}
Off
{% endif %}``` is what it was meant to be. my laziness copy/paste got me
that makes more sense
thanks for the help guys!
one more thing from me
- name: "NAS Total Throughput Status"
state: >
{% set throughput = states('sensor.nas_upload_throughput') | int + states('sensor.nas_download_throughput') | int %}
{% if throughput > 1100 %}
Transferring
{% elif throughput > 300 %}
Streaming
{% elif throughput > 10 %}
Scanning
{% elif throughput > 1 %}
Idle
{% else %}
Off
{% endif %}```
I have this and it works but in my history I see:
Became unknown triggered by state of NAS Upload throughput changed to 3.256
why would it show as unknown?
I am thinking its because maybe states('sensor.nas_download_throughput') was not a number? is there a way to make it 0 if its not a number?
I am hoping there is something easier than: {% if states('sensor.nas_upload_throughput') | is_number -%} {{ states('sensor.nas_upload_throughput') | int }} {%- else -%} 0 {%- endif %} + {% if states('sensor.nas_download_throughput') | is_number -%} {{ states('sensor.nas_download_throughput') | int }} {%- else -%} 0 {%- endif %}
@dusky pike I converted your message into a file since it's above 15 lines :+1:
that's clearly not the case, becasue the message mentions the state was 3.256
but you can add default to the int filters to make it work with non numeric states
or add an availability filter
@dusky pike lights don't have a color attribute, I assume you mean the rgb_color attribute
and data_template has been depreciated for over 3 years now, you can just use data
ye i got it down to this
set_color: service: light.turn_on entity_id: light.bed_rgbw data: rgbw_color: - "{{ state_attr('light.bed_light_correction', 'rgb_color')[1]}}" - "{{ state_attr('light.bed_light_correction', 'rgb_color')[0]}}" - "{{ state_attr('light.bed_light_correction', 'rgb_color')[2]}}" - "{{ state_attr('light.bed_light_correction', 'brightness')}}"
But the problem is that i cant use the inside variables for it like {{ brightness }} for some reason...
i just want to pass the variables in diferent order but if i do it like this i get an error when the entity is off
but it works except the brightess param... strange.
rgb_color is working and rgbw to... but somehow the {{ state_attr('light.bed_light_correction', 'brightness')}} is returning a non int... wtf.
what does it return in developer tools > template
how so?
and if not that - then what could cause that? 🙂
you were doing that before on your float filters
int(0) has 0 as it's default value
okay great - but why would I get Became unknown triggered by state of NAS Upload throughput changed to 3.256?
well, probably the other involved entity had a non numeric state
so the template was triggered by the state change of this entity, but ran into error because of the non numeric state of the other entity
ah yes so that means (0) should fix it
@dusky pike according to the template in the docs, I would suggest to use hue ans saturation for the color (which ara available as the variables h and s)
The problem is i need to switch the red and green. My leds are mosmatched with my led controler... @-@
this is still showing the same message:
- name: "NAS Total Throughput Status"
state: >
{% set throughput = states('sensor.nas_upload_throughput')|int(0) + states('sensor.nas_download_throughput')|int(0) %}
{% if throughput > 1100 %}
Transferring
{% elif throughput > 300 %}
Streaming
{% elif throughput > 10 %}
Scanning
{% elif throughput > 1 %}
Idle
{% else %}
Off
{% endif %}```
Became unknown triggered by state of NAS Upload throughput changed to 3.071
are you sure you reloaded the template entities after your change
Thanks i will give a go tonight 😉
@thorny snow I converted your message into a file since it's above 15 lines :+1:
don't think you should capitalize Sensor anywhere states('Sensor.second')
Also not working 😕
Yeah, you have capital letters all over the place that don't belong
And your indentation is wrong
At least inconsistent, and you're missing a :
Just review the docs and compare
Attention to detail is important, and that just looks tossed together
@thorny snow I converted your message into a file since it's above 15 lines :+1:
But if I use only on eof the sensor as single value without any calculation or combination with other vlaues, it also returns "unknown"
Your as_timestamp() call has mismatched quotes
changing right now.
Hi all, I am trying to create what I thought would be really simple sensor to look at an attribute on an Abode Alarm sensor that returns True or False and just translate that to "Good" or "Low", but I am having a lot of trouble with that. Can anyone point me in the right direction? The below returns "Unavailable":
`template:
- sensor:
- name: "Alice Office Window Battery"
value_template: >
{% if is_state('binary_sensor.alice_office_window.attributes.battery_low', 'False') %}
Good
{% else %}
Low
{% endif %}
device_class: battery
unique_id: "RF:0328e410"`
- name: "Alice Office Window Battery"
you're not following the proper format
change value_template: to state:
sorry, didn't see that you were trying to test an attribute like that. That's wrong, too 🙂
{% if is_state_attr('binary_sensor.alice_office_window' 'battery_low', 'False') %}
you may need to remove the quotes around "False", depending on the actual type of the attribute
test it in
-> Templates
I added the cpu temp to my configuration.yaml file. It outputs in C and even though my settings are for F, it is not being auto converted. How should I correct this?
Not really a templates question but:
https://www.home-assistant.io/docs/configuration/basic/
Look at unit_system
or through the GUI in https://yourha.instance:8123/config/general
My unit is set to F/Lbs already
what's it set to in the gui?
https://www.home-assistant.io/integrations/systemmonitor/
says: The unit of measurement (Celsius vs. Fahrenheit) will be chosen based on the system configuration.
one of the appears to override the other so set them both. Probably the gui overrides the yaml. Then restart HA core
The gui is set to fahrenheit. Restarting the entire system, the cpu temp still displays as celsius
Need help on template sensor. Following format doesn’t work. # platform: template
sensors:
salah_fajr:
friendly_name: "Fajr"
value_template: "{{ (as_timestamp(states('sensor.fajr_prayer')) - 60) | timestamp_custom('%Y-%m-%dT%H:%M:%S+00:00', false) }}"
device_class: timestamp
@tepid ice To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
I think you want to do
{{ as_datetime(states('sensor.fajr_prayer') - timedelta(second=60) }}
Is it possible to use a macro for creating multiple sensors via mqtt?
I made a simpleish macro that will take a bunch of params and then return alist item to use as a sensor rather then repeating a lot of the boiler plate: https://pastebin.com/d6KHghqj
Then trying to call it like so:
sensor:
- {{shelly_ht_mqtt("Freezer HT Sensor Temperature C", "shelly-ht/freezer-ht-sensor/status/temperature:0", "value_json.tC", "°C", "temperature", "mdi:thermometer", "freezer_ht_ctemperature")}}
But getting a bunch of weird yaml errors
No, it is not
Another option could be to set all the other values as attributes of the primary sensor and use template sensors to convert any you need as sensors. This means everything can come up in one MQTT message.
It seems, that renamed sensors are nopt properly updated. At leas it remarks, that an entity is not available under the new name. But in the states and entetiy menu it is available under it's old one.
How do I solve this?
I can post an example when HA restarted
States within developer tools displays
sensor.durchschnittlichetagesersparnis
average_daily_savings
sensor.tageseitinstallation
TageseitInstallation
sensor.tagesersparnis_2
Tagesersparnis
in Terminal I got
todaySaving
Tagesersparnis
daysSinceInstallation
TageseitInstallation
averageDailySavings
tägliche Durchschnittsersparnis
and even if I use the available entities, my calculation won't work.
{{states('sensor.gesamtersparnis_2') / states('sensor.tageseitinstallation') }}
if I use only one sensor, it works. So
{{states('sensor.gesamtersparnis_2') }}
and
{{ states('sensor.tageseitinstallation') }}
give me the sensors value
States are always strings. You're trying to divide strings
ok, converting it to float and int worked. thanks
You dropped to the conversion to float and int for some reason
but can you tell me something regarding the "wrong" naming
Nope
Thanks @inner mesa ! I tried state: previously and different quotations around the False value but wound up with a similar errors. I didn't know there was a different way to test the attribute. That seems to get me a lot closer. I got a "Normal" value once, but now I just seem to be getting unknown. I've tired 'False' and False. Is there any way to do any additional debugging / testing? When I put the below IF statement into Dev Tools / Template, I get the anticipated response of "Good".
`template:
- sensor:
- name: "Alice Office Battery Test"
state: >
{% if is_state_attr('binary_sensor.alice_office_window', 'battery_low', False) %}
Good
{% else %}
Low
{% endif %}
unique_id: "RF:0328e410"
device_class: battery`
- name: "Alice Office Battery Test"
I dont controll the mqtt messages sadly
Damn, is it possible to split the mqtt file into sub files based on sensors/devices? Or any other suggestions to avoid repeating code. I basically have 8 of those sensors configured with very slightly changes, 2 for temp(c and F), 1 for battery, and one for humidity
Why does this list every one of my entities?
{{ states | selectattr('entity_id', 'search', '_round_trip_time') | selectattr('state', '>', '.150') | map(attribute='object_id') | map('replace', '_round_trip_time', '') | map('replace', '_', ' ') | map('title') | join(', ') }}
I think it is because it is a float and not an int?
but dont know how to do a float
it's because all states are strings always
this one seems to work though?
{{ states | selectattr('entity_id', 'search', '_rssi') | selectattr('state', '>', '-70') | map(attribute='object_id') | map('replace', '_rssi', '') | map('replace', '_', ' ') | map('title') | join(', ') }}
you can't compare a state with a number like that without a for loop
no, states are still always strings
maybe because of ascii math
it's not comparing numbers
so I have to do a template sensor?
mark down card
just trying to check the rssi values and round trip times of zwave devices without making a group
{% set ns=namespace(names=[]) %}
{% for entity in states|selectattr('entity_id', 'search', '_rssi')|selectattr('state', 'is_number')|list %}
{% if entity.state|float > 0.150 %}
{% set ns.names = ns.names + [entity.object_id| map('replace', '_rssi', '') | map('replace', '_', ' ') | map('title')] %}
{% endif %}
{% endfor %}
{{ ns.names|join(', ') }}
something likke that
float got invalid input 'unknown' when rendering template
auh, some of the states are unknown?
ha, i was busy in dev_tools/templates trying to figure it out
that is doing something funky though
<generator object sync_do_map at 0x7fe517734740>, <generator object sync_do_map at 0x7fe517734940>,
yeah, you need to get rid of the map() calls
{% set ns=namespace(names=[]) %}
{% for entity in states|selectattr('entity_id', 'search', 'input_number')|selectattr('state', 'is_number')|list %}
{% if entity.state|float > 0.150 %}
{% set ns.names = ns.names + [entity.object_id.replace('_rssi', '').replace('_', ' ')|title] %}
{% endif %}
{% endfor %}
{{ ns.names|join(', ') }}
I just copied what you had without thinking about it
I changed it a bit to work with my entities
still not working. it lists every entity.
not sure what to say, it works for me
0.150 is a pretty strange RSSI value
my guess is that that's wrong and you need to revisit your criteria
You're using exactly the same entities as you did above for your actual RSSI comparison against -70
Which is a weak, but fine RSSI
dont know what to tell you. if i put {% if entity.state|float < 0.150 %} i dont get any entities, if i put {% if entity.state|float > 0.150 %} i get every entity
it is not respecting the float
same results if i change the 0.150 to 1
I think you're using the wrong entities
Because RTT is not RSSI
and I notice that I may have led you there
That looks better
Anyway, I don't think this is a logic issue
no, i corrected it on my end. anyway, when i test _rssi it works perfect
and i noticed one of my devices has a rssi of 83 dbm. thats terrible 😝
Hello, I am searching through a list of dates to get data of 'today'. The list of dates sometimes does not contain 'today' and my method crashes. How can I make this return a proper true or false?
{% set date = state_attr('sensor.school_lesson', 'date') %}
{% set search_date = now().strftime('%Y/%m/%d') %}
{{ date.index(search_date) }}
this returns: ValueError: '2023/06/11' is not in list
You just want true if the date is in the list and false if it isn't?
Easy
of course... only one coffee so far...maybe the cause
{{ search_date in date }}
aaarghhh...getting second coffee now THANKS !!!!
So I made this custom_templates {% set batteries = states.sensor |selectattr('attributes.device_class','defined') |selectattr('attributes.device_class','eq','battery') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='entity_id')|list %} whihc allows me to do attributes: batteries: > {% from 'batteries.jinja' import batteries %} {{ batteries }} and return all batteries
I used to have a template sensor with that repeated selector in state and several other attributes, but this is much more efficient. theres a catch... a low_batteries attribute (using the this variable up to now):```
low_batteries: >
{%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %}
{%- set ns = namespace(batteries=[]) %}
{%- for s in expand(this.attributes.get('batteries'))
if s.state|int(default=0) < alert_level %}
{%- set ns.batteries = ns.batteries + [' ' + s.entity_id] %}
{%- endfor %}
{{- ns.batteries|join(',')}}```
cant be replaced using import.. {%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {%- set ns = namespace(batt_low=[]) %} {%- for s in batteries if s.state|int(default=0) < alert_level %} {%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %} {%- endfor %} {{- ns.batt_low|join(',')}} returns UndefinedError: 'str object' has no attribute 'state'
aarghhh.... I missed the expand there....```
low_batteries: >
{%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %}
{% from 'batteries.jinja' import batteries %}
{%- set ns = namespace(batt_low=[]) %}
{%- for s in expand(batteries)
if s.state|int(default=0) < alert_level %}
{%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %}
{%- endfor %}
{{- ns.batt_low|join(',')}}
Hi there! I connect an input_boolean and a templated binary_sensor with 'and' to another templated binary_sensor called functionality_athome. Both sensors which are joined by 'and' are 'on' according to their states in the states and yet the resulting sensor functionality_athome is 'off'. I tried a few things so far and got stuck. Can you give me a hint?
Here is the code:
functionality:
name: My Functionality
- binary_sensor:
- name: "Home: Uwe is here"
unique_id: "at home uwe yn"
state: >
{{ is_state('person.uwe', 'home') }}
- name: "functionality_athome"
unique_id: "functionality_athome"
state: >
"{% if ((is_state('input_boolean.functionality', 'on')) and (is_state('binary_sensor.home_uwe_is_here', 'on'))) %}on{% endif %}"```
I think the stare of functionality_athome can be simplyfied by removing the if/endif resulting in a simple 'and'. But this how it is at the moment.
I'd try changing it to {{ is_state('input_boolean.functionality', 'on') and is_state('binary_sensor.home_uwe_is_here', 'on') }} and see how that goes
Ah... you also don't need " when you're using the > syntax
- name: "functionality_athome"
unique_id: "functionality_athome"
state: >
{{ is_state('input_boolean.functionality', 'on') and is_state('binary_sensor.home_uwe_is_here', 'on') }}
I simplified the expression and with the quotation marks gone like you suggested and the correct result showed up. I wonder why the quotation marks negate the result. Have you got some link where I can do some RTFM to dig for some explanation?
https://www.home-assistant.io/integrations/template/#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors shows the different how to use state: . The only difference I can see is that one liners with state: only need either single or double quotation marks, multi liners with 'state: >' do not need quotation marks. Hmmm...
The multiline thing probably escapes your quotation marks in the second line, so the template is never evaluated at all. It tries to just treat the whole string as the state, and since it does not match one of the strings for binary sensor to be on, it defaults to off.
A pity that it is not well documented. I came across the template sensors where examples look different (with quotation marks or the greater than sign) without mentioning why this is so. Documentation could be better in this case...
Thanks for the link. I will do some RTFM there. 👍
Hi, I always wrote my sensors via:
configuration.yaml
sensors: include sensor.yaml
sensor.yaml
- platform: template
sensorname:
etc...
Now I got a message that this is an old way to include template sensors. How do I translate them into the right way?
In addition I now need to write some mqtt sensors. How do I include them in the right way too?
Thanks for your help
Wondering if someone can help simplify this for me. Here's a portion of my template which works.yaml {% set charging_state = states('sensor.s22_ultra_charger_type') %} {% if charging_state == 'none' %} {% set charging = "" %} {% elif charging_state == 'ac' %} {% set charging = "charging-" %} {% elif charging_state == 'wireless' %} {% set charging ="charging-wireless-" %} {% endif %}
I tried to simplify it with this but I'm assuming because I use set on each line, only the last one actually works.yaml {% set charging = is_state('sensor.s22_ultra_charger_type', 'none') | iif("") %} {% set charging = is_state('sensor.s22_ultra_charger_type', 'ac') | iif("charging-") %} {% set charging = is_state('sensor.s22_ultra_charger_type', 'wireless') | iif("charging-wireless-") %}While the top code works, I would like something that is written a bit more efficiently. Any suggestions?
{% set map = {"none":"", "ac":"charging-", "wireless":"charging-wireless-"} %}
{% set charging = map[states('sensor.s22_ultra_charger_type')] %}
RobC That works perfectly. Thank you. I figured there had to be some way to use an array or something along those lines.
"dict" or "mapping"
Totally didn't even think about it. I use map in a Node-RED function to I wrote a while back ago to calculate Circadian levels. javascript function map(x, in_min, in_max, out_min, out_max) { return Math.round((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min); }
in customize: is it possible to use templates (similar idea to customize_glob)? like a "customize_template" so all zwave switches in specific area(s) get specific icon.
No
thanks.
how odd, template sensor using custom_templates: - unique_id: alerts_notifying state: > {% from 'alerts.jinja' import alerts %} {{alerts|count}} name: > {% from 'alerts.jinja' import alerts %} {% set count = alerts|length %} {% set phrase = 'Alert' if count == 1 else 'Alerts' %} {{count}} {{phrase}} actief icon: > {% from 'alerts.jinja' import alerts %} {% set count = alerts|length %} mdi:numeric-{{count}}-box
returns 0 on all counts, while dev tools template {% from 'alerts.jinja' import alerts %} {{alerts}} {{alerts|count}} clearly shows thats not the case...
|count or |length dont make a difference in this case as can be seen
I moved to import that custom_template, because I had this expand:```
state: >
{% set alerts = state_attr('binary_sensor.alerts','entity_id') %}
{{expand(alerts)
|selectattr('state','eq','on')|map(attribute='entity_id')|list|count}}
this is my alerts.jinja:```
{% set alerts = expand(state_attr('binary_sensor.alerts','entity_id'))
|selectattr('state','eq','on')|map(attribute='name')|list %}
{% set hubs_offline = expand(state_attr('group.hub_device_trackers','entity_id'))
|selectattr('state','eq','not_home')|list %}
{% set critical_off = expand('switch.critical_switches')
|selectattr('state','eq','off')|list %}```
whats more, when pasting the full template config in the dev tools, it clearly shows its correct...
here's a link to a communit post which might be easier https://community.home-assistant.io/t/template-with-custom-templates-import-does-not-update-correctly/581120
Can anyone help?
Did you check the template: documentation ? Its all there. Share what you did and we can have a look
Btw my post above shows how it’s done 😉
What do you have in alerts.jinja?
oh, sorry, you already posted that
you dont't have to expand that attribute btw, you can expand the group directly
expand('binary_sensor.alerts')
Is there a way to split up mqtt sensor files? Ideally Id like to do one file per device?
not templates related, but youy can do one include per domain.
mqtt:
switch: !include dir_merge_list mqtt/switch
light: !include dir_merge_list mqtt/light
Hmm yeah wouldnt help much in my case. I have 8 sensors, 4 per shelly ht, and its a lot of boilerplate code. From posting in here before, its not possible to use macros so I was hoping to do one file per device to keep things a bit cleaner
You can do that using packages
Any example or guide on how to do that?
Hey,
ive got 12 entities with a certain value. I want to create an automation that compares all 12 of them and sends me a notification on the lowest 3 of them. How could i do this? Some ideas?
break it down into the parts that you need help with
-
Find out what are the lowest 3 states (prices) out of 12 entities, all with the name sensor.x_diesel or if possible, from the integration tankerkoenig instead of the entity name
-
Output these 3 entities as a notification
so all of it 🙂
I suggest researching how you want to send the notification
there's no general solution for that
the notification shouldnt be a problem when i get the 3 entities sorted out
It's just going to take you some serious time messing around with jinja.
it's a pain in the neck
{% set sensors = ['sensor.er_motion_sensor_battery', 'sensor.cr_left_window_battery', 'sensor.mbath_large_window_battery'] %}
{% set map = {sensors[0]:states(sensors[0]), sensors[1]:states(sensors[1]), sensors[2]:states(sensors[2])} %}
{{ (map.items()|sort(attribute='1')|map(attribute='0')|list)[0:3] }}
something like that would work. the first bit could use integration_entities() to form the list
But you have to built the dict. You could also do it with a for loop and namespace with a list, but that's more than I care to do right now 🙂
ill give my best to understand it and give it a try😅 Thanks a lot!
Ill take a look right now, thx!
better:
{% set sensors = ['sensor.er_motion_sensor_battery', 'sensor.cr_left_window_battery', 'sensor.mbath_large_window_battery'] %}
{% set ns = namespace(map={}) %}
{% for s in sensors %}
{% set ns.map = dict(ns.map, **{s: states(s)}) %}
{% endfor %}
{{ (ns.map.items()|sort(attribute='1')|map(attribute='0')|list)[0:3] }}
dynamically generate the map
so...
{% set sensors = integration_entities('whatever') %}
{% set ns = namespace(map={}) %}
{% for s in sensors %}
{% set ns.map = dict(ns.map, **{s: states(s)}) %}
{% endfor %}
{{ (ns.map.items()|sort(attribute='1')|map(attribute='0')|list)[0:3] }}
boom
Damn that actually works
ye of little faith
Thank you so much!
Soooo this spits out the „cheapest“ 3 sensors, so i only need to get them with value into a notification
But maaaaybe i can find that out by myself😅
template sensor. then notify it's value. Or something like that 😉
grandma is going have to get across the street herself now
First time somebody named me grandma:(
- sensor:
- name: "lowest3temperaturesensors"
state: >
{% set sensors = expand('group.temp_sensors')| sort( attribute='state') %}
{% for s in sensors[0:3] %}
{{ s.name }},
{% endfor %}```
(yes, I'm just playing)
alternatively:
- sensor:
- name: "lowest3temperaturesensors"
state: >
{{ (expand('group.temp_sensors')| sort( attribute='state'))[0:3]|map(attribute='name')|join(",") }}```
Just needs a group with the sensors which you're interested in.
The problem with that is that states are strings, and it's generally frowned on to compare them as integers. It's an issue in my solution, too, but can be easily fixed with
{% set ns.map = dict(ns.map, **{s: states(s)|float}) %}
ahhh
I do wish that we had a way to transform a value in a filter before it's used in a comparison, but we (mostly petro) have been noodling on that for a long time without a good solution
That explains why you did it that way 🙂
well, I had a bug as well, and I didn't think of just keeping the state object 🙂
it's not a bad idea, and it will sometimes work and sometimes not
the problem is that you have to use map() to apply a transform, and you lose information when you do that
Hello. I am trying to make a sensor. As my heating cables are on relay only I had an Idea to make a sensor measuring the time the relay is in on state. And from there do a calculation of kWh. I from there want to add this sensor in energy dashboard. Tried some things without any luck, but this one works though: `` {% set voltage = states('sensor.voltage_phase2_hjemme') | float %}
{% set resistance = 105 %}
{% set power = (voltage * voltage) / resistance %}
{{ (power / 1000) | round(2) }} ```
are you still looking for something?
Im still stuck with the notification, im just not into templates.
Ive got the sensor now thats giving me
[‘sensor.x_diesel‘, ‘sensor.x_diesel‘, ‘sensor.x_diesel‘]
And i want to get a output like:
- friendlyname1 value1
- friendlyname2 value2
- friendlyname3 value3
thx, In wasnt sure if it would have any influence, but tested that for 3 of these domains (binary_sensor (helper UI group), group (manual) and switch (helper UI group), and thats indeed seems ok 😉 btw editing these custom_templates files (.jinja) is not very nice in an external editor.... tbh, I am not even sure these comments will actually be commented
You need to use jinja comments in a .jinja file
{# this is a comment #}
{#
multi
line
comment
#}
right... still, even without that the jinja editor is confused... guess my trusted BBedit does not have a .jinja translator
which is really nasty
and the templates arent colored at all in my vscode addon...which all of a sudden is using some silly modernish theme. aarrgghh
is the logbook changes dependant on device_class or type (binary sensor vs sensor)? For a binary sensor I get logbook for that entity saying:
Turned on triggered by state of NAS Upload throughput changed to 7.363
but with my normal sensor I get no logbook changes:
https://imgur.com/a/jsBZHS9
only history
Is there an easy way to use a template to list all the attributes and their values? Without having to type each attribute key out in an automation variables section?
Entities with a unit of measurement don't appear in the logbook, because they are prone to frequent changes which will flood the log
.items() on the attributes object on the state object
Install a jinja extension
I mean something like this which would list out all attributes of the sensors for the automation to consume foo['attributeone']
foo: "{{ state_attr('sensor','attributes') }}"
no, you need to use the state object, you can't use the state methods
Awesome figured it out.
How would I access this?
dict_items([('master_bedroom_initial_temperature', []), ('master_bedroom_initial_humidity', []), ('master_bedroom_automation_action_time', []), ('friendly_name', 'HVAC Automation Memory')])
As in reference master_bedroom_initial_temperature for example.
what is your goal here?
I'm going to store data in a template trigger sensor using the event stuff we talked about awhile ago. Then in an automation reference data for conditions by looking back at what changed during x time.
I'm looking for a clean way to reference attributes without having to define each one in the automation variables section. Or reference each one each time I want to use it.
The easiest is define each one in the variables section but I was wondering if there was a cleaner way.
cards are for #frontend-archived 🙂
and it looks like you are putting the code of a template switch in a card
... cant even delete my message now :\
that doesn't belong there, it should be in configuration.yaml not in the dashboard code
I deleted it for you 🙂
aye cause everything in examples is written in context of editing config.yaml and i cant convert it
The binary sensor also has unit of measurment and that shows logbook - so theres no way around it? the template is:
- name: "NAS Status"
icon: phu:nas-v2
device_class: enum
state: >
{% if states('sensor.nas_smartplug_watts')|float(0) < 1 %}
Off
{% elif ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_force_off', 'last_triggered')) |int(0) ) < 300 and ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_force_off', 'last_triggered')) |int(0) ) > 0
and not ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_on', 'last_triggered')) |int(0) ) < 300 and ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_on', 'last_triggered')) |int(0) ) > 0 %}
Powering Down
{% elif is_state('sensor.nas_volume_1_status', 'normal') or is_state('sensor.nas_volume_2_status', 'normal') or states('sensor.nas_upload_throughput')|float(0) > 0.1 or states('sensor.nas_download_throughput')|float(0) > 0.1 %}
On
{% elif states('sensor.nas_smartplug_watts')|float(0) > 1 and ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_on', 'last_triggered')) |int(0) ) < 300 and ( as_timestamp(now()) - as_timestamp(state_attr('script.nas_on', 'last_triggered')) |int(0) ) > 0 %}
Powering Up
{% endif %}```
I binary sensor doesn't have a unit of measurement. I doesn't have a numeric state, it's either on or off
oh sorry I thought you meant the entities that trigger it
try removing the device_class
the device class is new - I thought it would change it but still doesnt show without it
device classes are also for sensors with numeric states
did you exclude it from recorder (or forgot to include it)?
it you don't add items() you get a dict with all the attriubtes, which you can use for the attribute
you can't template the entire attributes section though, so you need to assign a key (like source_sensor_attributes:) to it
I only have excluding and its not there - but good idea haha I thought I might of exluded it
I can see it in the logbook! but not in the entities log book (the pictures I posted before)
it won't show in entities logbook unless it has a unique_id
at least I'm pretty sure that's the case
and binary_sensors have a unique id?
if you add it
depends on where it comes from
it's a template binary sensor right
sure is
(I assumed)
do you have a unique_id in the configuration?
- name: "NAS Data Transfer"
icon: mdi:swap-horizontal
delay_off:
minutes: 1
state: "{{ states('sensor.nas_upload_throughput')|int(0) + states('sensor.nas_download_throughput')|int(0) >= 15 }}"```
well then that's not the case
how can I check that?
you don't
with your eyes 🙂
- binary_sensor:
- name: "NAS Data Transfer"
unique_id: this_is_a_unique_id_for_this_sensor
icon: mdi:swap-horizontal
delay_off:
minutes: 1
state: "{{ states('sensor.nas_upload_throughput')|int(0) + states('sensor.nas_download_throughput')|int(0) >= 15 }}"
this version has a unique_id
ah I was just showing you the binary that has logbook
I'll add it to the normal sensor
Something like?
variables:
hvac_automation_memory: "{{ states.sensor.hvac_automation_memory.attributes }}"
I don't think that will help based on what I've seen
that won't work as attributes are not a dictionary
oh, sorry Dan 🙂
You can see in the template editor
well well well, they are apparently
so that will work
they fixed that bug
I was going to say hm then why does it look like a dictionary?? Lol
don't get me wrong, it's not a dict
- name: "NAS Status"
unique_id: nas_status
icon: phu:nas-v2
state: >```
youre right - it didn't work
it's just that the resolver handles the type now
I put it in a variables section and ran the automation and it's not returning the variable at all under changed variables
Just keep in mind that enums aren't translated in attributes, so it may be a string result.
i.e. if you're doing this with a light, it won't properly resolve a dictionary
because lights have 3 enums typically in attributes
Interesting. Yeah this is just strings
But all I have is
context:
id: 01H2T7JW35J4YKWSFRYP7608Q7
parent_id: 01H2T7JW34DC6HKMQW9A2NBW2B
user_id: null
When there should be the variable?
That I defined
changed variables only show up on when you aren't on a node
so make sure you're on the trigger
well, they do show up on variable nodes
but I'm assuming you put the variable in the main variables node/field
That worked
hvac_automation_memory: >- dict_items([('master_bedroom_initial_temperature', []), ('master_bedroom_initial_humidity', []), ('hvac_turned_on_time', ''),
('hvac_turned_off_time', ''), ('master_bedroom_automation_action_time', []),
('friendly_name', 'HVAC Automation Memory')])
that looks like a string
Should I use .items() for this or no?
probably not because attributes resolves properly in the template editor as long as you don't have an attribute that's a complex object
it doesn't look like you do for whatever that is
The only thing complex could be the timestamps. {{ now() | as_timestamp }} for the time attributes.
datetimes will mess it up
What should I do with that?
you can test this crap yourself btw
probably not resource friendly, but I guess this should work {{ states.sensor.foo.attributes | to_json | from_json }} 😅
that won't work for complex objects
because you can't serialize complex object if they don't have a serialize method
On the road to testing. Have been playing with getting the template trigger right for storing "memory" now I'm finally starting on the automation where I need these stored values. I went this route vs multiple input_text sensors
Worked
{{ { 'y': now() | as_timestamp } }}
a timestamp is just a number, not very complex 🙂
probably
only use as_timestamp if you understand the ramifications behind using it 😉
The most this may be needed for is less than 12 hours
Then it would clear
So it's not as if this will be referencing something more than 24 hours ago.
No idea what the ramifications are. Is there googling I should do?
Nope, just comes with experience
Can you share some? Lol
I mean, it's learn by doing
You have to hit the issues to see what they are to work past them
in HA, I only use datetimes as strings
in my own apps I use timestamps because I control the whole backend
What apps do you write?
Interesting. What do you do? Top secret stuff? Lol
Nothing top secret
I manage production line equipment & software for making contact lenses
mainly focused on metrology. I.e. Making sure the lenses that we made are what we expect them to be
however, I'm a jack of all trades, so they have me make whatever they need software wise
That's really cool stuff. I'm becoming the jack of all trades in Ansible lol for my team thanks to you guys over the past few years helping me along with Jinja.
If you learn some python, you'll get even better
knowing python makes jinja a breeze
That's what I'm beginning to realize and I'm starting to learn some python.
Hey
Im still stuck with the notification, im just not into templates.
Ive got the sensor/ now thats giving me
[‘sensor.x_diesel‘, ‘sensor.x_diesel‘, ‘sensor.x_diesel‘]
And i want to get a output like:
- friendlyname1 value1
- friendlyname2 value2
- friendlyname3 value3
Can somebody help pls?
could this be further condensed:```
{% from 'media_players.jinja' import media_players_active %}
{% set rooms = media_players_active().split(',')
if media_players_active() != '' else [] %}
{% set count = rooms|count %}
{% set ns = namespace(speakers = '') %}
{% for i in range(count) %}
{% set d = ',' if ns.speakers|length > 0 else '' %}
{% if states('media_player.' ~ rooms[i]) not in ['unavailable','unknown'] %}
{% set ns.speakers = ns.speakers ~ d ~ 'media_player.' ~ rooms[i] %}
{% endif %}
{% endfor %}
{% if count == 0 %} No active radio
{% else %}
{{ns.speakers}}
{% endif %}```
if not 0 it takes the entity_id, and adds media_player in front of them, and then returns
Ive always found this a but frsgile: {% set ns.speakers = ns.speakers ~ d ~ 'media_player.' ~ rooms[i] %} so maybe it would be time to recheck that
well it can because you're using an iterator which isn't needed.
you almost never need an iterator in jinja
btw this it the custm_temnplate that is the base for it: {%- macro media_players_active() -%} {{- expand('group.media_players_active') |selectattr('state','eq','on') |map(attribute='object_id')|list|join(',') -}} {%- endmacro -%}
for room in rooms
just so you know why: i list the object_id's there because they are booleans I toggle
{% from 'media_players.jinja' import media_players_active %}
{% set rooms = media_players_active().split(',') if media_players_active() else [] %}
{% set ns = namespace(speakers = '') %}
{% for room in rooms %}
{% set d = ',' if ns.speakers|length > 0 else '' %}
{% if states('media_player.' ~ room) not in ['unavailable','unknown'] %}
{% set ns.speakers = ns.speakers ~ d ~ 'media_player.' ~ room %}
{% endif %}
{% endfor %}
{% if rooms %} No active radio
{% else %}
{{ns.speakers}}
{% endif %}
even further...
hmm, the check on rooms fails...
{% from 'media_players.jinja' import media_players_active %}
{% set rooms = media_players_active().split(',') if not media_players_active() else [] %}
{% set ns = namespace(speakers = []) %}
{% for room in rooms if ('media_player.' ~ room) | has_value %}
{% set ns.speakers = ns.speakers + ['media_player.' ~ room] %}
{% endfor %}
{{ ns.speakers | join(',') if ns.speakers else 'No active radio' }}
same check fails... it returns 0,
try again
unless media_players_active() doesn't return what it's supposed to
{% set rooms = media_players_active().split(',') | reject('eq', '') | list %}
use that instead
and if you want it to be optimal, that should just go in your for loop.
{% from 'media_players.jinja' import media_players_active %}
{% set ns = namespace(speakers = []) %}
{% for room in media_players_active().split(',') | reject('eq', '') if ('media_player.' ~ room) | has_value %}
{% set ns.speakers = ns.speakers + ['media_player.' ~ room] %}
{% endfor %}
{{ ns.speakers | join(',') if ns.speakers else 'No active radio' }}
yes, that works!
Inused this: {% set rooms = media_players_active().split(',') if media_players_active() != '' else [] %} on advice bt Taras in the community post, to prevent that splitting an empty list still counts 1
right, but you can just reject the emtpy items in the generator
nice, thx. this too:{% set ns.speakers = ns.speakers + ['media_player.' ~ room] %}
sweet and simple.
but here {% from 'media_players.jinja' import media_players_active %} {% set players = media_players_active().split(',') if media_players_active() != '' else [] %} {% set count = players|count %} {{count}} cant I use the reject?
this does wodk: {% from 'media_players.jinja' import media_players_active %} {% set players = media_players_active().split(',') %} {% set count = players|count if players != [''] else 0 %} {{count}}
Why do you need count?