#templates-archived
1 messages · Page 18 of 1
i think you want a utility meter sensor with your reimann sensor as it's input. https://www.home-assistant.io/integrations/utility_meter/
Oh i think you’re right. It should be Current Consumption template -> Reimann -> Utility. Forgot the last step! Thanks
service: light.turn_off
target:
entity_id: "{{ states.light | map(attribute='entity_id') | list }}"
Any ideas how to put an exclude in this template?
light.wled_christmas_tree_master
it turns off the wled master switch which we don't use
service: light.turn_off
target:
entity_id: "{{ states.light | map(attribute='entity_id') | reject('eq', 'light.wled_christmas_tree_master') | list }}"
yes, you can also use == or equalto
You changed the variable from sensor to people which broke it. You have to change the other sensor in that line to people as well.
I changed it back, using your default as posted and for some reason it fails on the condition. I'm now going through it line by line
@paper hazel I briefly scrolled through the posts above, do you have other anniversaries in the custom anniversaries integration besides birthdays?
I'm sure I made a mistake somewhere, but unsure where at this stage 😟
Yes, but they have different prefixes
Post the whole thing and I’ll look after my run
Thank you!
okay, you could also use
integration_entities('anniversaries') | select('search', 'birthday_') | list
instead of
states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list
oh wait, I see you also select on the state now
This part seems to render fine, it fails on the condition, which tests the variable items. But for the life of me I cant see why states.sensor| selectattr('entity_id', 'search', 'birthday_') | map(attribute='entity_id') | list
petro was kind enough to assist in the wee hours of this morning with this. My original implementation I was working towards was much longer and more complicated...
Veels geluk! Hoop dit is n mooi jaar... is this Afrikaans?
never realized you can use replace in map(). I always joined them, did the replace, and then split. I've been stupid 🙂
How to copy input temperature data from 1 thermostat to anotherr?
The docs really need to be revamped and split into tests, filters, and methods
or, revamped to cover each method and show them as tests, filters and methods
@paper hazel try changing
{% for sensor in sensors if config.get(sensor, False) %}
to
{% for sensor in sensors if config.get(sensor) is not none %}
and if you don't plan on using name, then....
- alias: Notify Birthday Message on Whatsapp
id: 'rtWpsuf0G8BVEviZK2aeGaM9wDRBWJOuttiDhWVvHX83koW2yWZsJ1LwdboEgLZl'
mode: queued
trigger:
- platform: time
at: "07:04:34"
variables:
config:
test_person: "2712345678@s.whatsapp.net"
people: >
{{ states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'birthday_', '') | list }}
items: >
{% set ns = namespace(ret = []) %}
{% for sensor in sensors if sensor in config %}
{% set ns.ret = ns.ret + [ config[sensor] ] %}
{% endfor %}
{{ ns.ret }}
condition:
- platform: template
value_template: "{{ items | length > 0 }}"
action:
- repeat:
for_each: "{{ items }}"
sequence:
- service: whatsapp.send_message
data:
clientId: default
to: "{{ repeat.item }}"
body:
text: "Veels geluk! Hoop dit is n mooi jaar..."
well, I knew that I could use filters in map(), so I should have known
@paper hazel another way to do items would be
items: >
{{ config.items() | list | selectattr('0', 'in', sensors) | map(attribute='1') | list }}
i'd probably go that route tbh
I don't know why I didn't think of it last night
probably because I assumed you wanted the name too
must have been the hangover 😛
maybe 🤣
where is sensors defined? Or do you mean people
I think you need to replace sensors with people in the for loop as well
or just name the variable sensors instead of people
Yip - Sorry for the delayed response, work interfered with my HA hobby 🙂
I copied this as is, and it still errored Invalid config for [automation]: Unexpected value for condition: 'None'. Expected and, device, not, numeric_state, or, state, sun, template, time, trigger, zone @ data['condition'][0]. Got None. (See ?, line ?).
lol, that's 100% unrelated to any of the code you've been posting
data['condition'][0] tells you the condition is failing
I see the error
{{ config.items() | selectattr('0', 'in', sensors) | map(attribute='1') | list }} this also works without the | list after items() BTW 🙂
condition:
- condition: template
value_template: "{{ items | length > 0 }}"
I couldn't remember, items doesn't return a list and sometimes jinja bitches about the objects that a dictionary returns for .keys(), .values(), and .items()
@paper hazel see my previous response with the condition change.
but anyway, sensors should be replaced with people
oh ffs, he changed that too? ok, yes
the variable is named people, not sensors
@paper hazel here's the changes, please don't change names of things 🤣
- alias: Notify Birthday Message on Whatsapp
id: 'rtWpsuf0G8BVEviZK2aeGaM9wDRBWJOuttiDhWVvHX83koW2yWZsJ1LwdboEgLZl'
mode: queued
trigger:
- platform: time
at: "07:04:34"
variables:
config:
test_person: "2712345678@s.whatsapp.net"
people: >
{{ states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'birthday_', '') | list }}
items: >
{{ config.items() | selectattr('0', 'in', people) | map(attribute='1') | list }}
condition:
- condition: template
value_template: "{{ items | length > 0 }}"
action:
- repeat:
for_each: "{{ items }}"
sequence:
- service: whatsapp.send_message
data:
clientId: default
to: "{{ repeat.item }}"
body:
text: "Veels geluk! Hoop dit is n mooi jaar..."
I'm still failing to see what was wrong with the condition BTW 😛
aaah crap
YEP
💩
yaml error, nothing to do with the template
would have been more obvious if they would have used trigger: template instead of platform: template
Oi! Well spotted...
and there it suddenly passes flawlessly....
Thank you both so much - kinda feel a bit stupid for not spotting it....
next time just share the error, it's something none of us would have spotted
but the error poitns right to where the issue is and we've helped enough people to know what each error means
Just a last question - Can I duplicate the automation, and split the people, depending on language and just alter the text? I believe it should work...
sure if you want... but...
- alias: Notify Birthday Message on Whatsapp
id: 'rtWpsuf0G8BVEviZK2aeGaM9wDRBWJOuttiDhWVvHX83koW2yWZsJ1LwdboEgLZl'
mode: queued
trigger:
- platform: time
at: "07:04:34"
variables:
config:
test_person:
whatsapp: "2712345678@s.whatsapp.net"
message: "Veels geluk! Hoop dit is n mooi jaar..."
people: >
{{ states.sensor | selectattr('object_id', 'search', '^birthday_') | selectattr('state','eq','0') | map(attribute='object_id') | map('replace', 'birthday_', '') | list }}
items: >
{{ config.items() | selectattr('0', 'in', people) | map(attribute='1') | list }}
condition:
- condition: template
value_template: "{{ items | length > 0 }}"
action:
- repeat:
for_each: "{{ items }}"
sequence:
- service: whatsapp.send_message
data:
clientId: default
to: "{{ repeat.item.whatsapp }}"
body:
text: "{{ repeat.item.message }}"
I understood from your explanation yesterday that this line should stop the process if no match is found under config. So duplicating it in its original form and splitting the lists should function as intended, or did I understand incorrectly.```
{% for sensor in sensors if config.get(sensor) is not none %}
right, but that old template isn't needed because you aren't creating or using the persons name, so all you need for items is
{{ config.items() | selectattr('0', 'in', people) | map(attribute='1') | list }}
which does the same thing
essentially
Is there a massive drawback using the original one vs the simpler one - Reason for asking, I have 110 people in the list, and to add those attributes is gonna be quite an admin task. There are only 13 exceptions currently which would use english vs Afrikaans.
Could probably get the attributes added in with notepad++, and I perhaps see the option to add more customised message per person...
There might be more value, for the current manually input needed...
Cool Stuff! Thank you for all your help - It has been a massive learning experience for me. Hopefully I pay it forward some time...
How to do this so it outputs ia properly:
{% set variable = 'ia' %}
{{ var' ~ variable ~ 'ble }}
{% set variable = 'ia' %} {{ 'var' + variable + 'ble' }}
the ~ was fine as well, that converts all the parts to a string
This will fail:
{% set variable = 123 %}
{{ 'var' + variable + 'ble' }}
This will work:
{% set variable = 123 %}
{{ 'var' ~ variable ~ 'ble' }}
Hello all! I have this on my front end UI the problem is when my sensor goes to a single digit it get's messed up. It's as if its comparing only the first digit when the sensor goes to say 9%, any ideas?
{% if states('sensor.processor_use') >= '35.' %} --paper-item-icon-color: #b81414;
you're comparing strings not numbers
strings work left to right when comparing
character by character
ahh!
so no matter what, '9' is always greater than '1' even if it's followed by a 0
So I would have to convert the string to a number first in order for it to work properly.
convert your state
This and @still plank just outputs variable
states(..) | float
I want ia
I'll look that up!
then just {{ variable }}
This doesn't work because you are missing a ' before var' and after 'ble
Yes its a simplified code of a much larger line, I want it like I wrote before "variable inside variable"
bro, you just said you want only ai after thefes gave you the right answer
I just wanted to explain why it's better to use ~ instead of +, that's why I changed it to 123
Yes but dont change it to 123, I want it to be ia to prove what Im trying to do
you mean you want to output the name of the variable, not the value of it?
I want the 2nd line to output ia
then just {{ ia }}
Im gonna copy whole code, sec
no he's just terrible at explaining, the answer he wants is just
{% set variable = 'ia' %}
{{ 'var' ~ variable ~ 'ble' }}
Im trying that and it outputs variable
@marble jackal already said that, but it wasn't what they wanted
Right but you've said 2 conflicting requests.
what do you want. To output just 'ia' or 'variable', because you've said you want both
it does because in that expression you are concatenating three strings - a literal 'var', the value of your variable and a literal 'ble'
Just ia
if you don't want 'var' and 'ble' parts then don't put them in the expression
Its a bad example, let me copy the real one.
ok, then that's simply just
{% set variable = 'ia' %}
{{ variable }}
if you're trying to concatenate a string to access a variable in the current namespace, that's not possible.
I think thats exactly what im trying to do
yep, that's not possible
I need to install discord on PC to copy code, sec
you can do it with a dictionary, but not with the items in the namespace
ok so this is the code:
{{ 'states.' ~ states.sensor.ramses_0_00.attributes.entity_id_climate ~ '.attributes.schema.schema' }}
{{ 'states.' ~ states.sensor.ramses_0_00.attributes.entity_id_climate ~ '.attributes.schema.actuators' }}
{% set sensor = 'states.' ~ states.sensor.ramses_0_00.attributes.entity_id_climate ~ '.attributes.schema.sensor' %}
{% set actuators = 'states.' ~ states.sensor.ramses_0_00.attributes.entity_id_climate ~ '.attributes.schema.actuators' %}
{% for x in actuators %}
{% if sensor is not in x %}
{{ sensor }}
{% else %}
{{ none }}
{% endif %}
{% endfor %}
the first two lines output the correct entity but in a string
where it errors is in 3rd and 4th lines (both set)
{% set stuff = { 'variable': 'some output' } %}
{{ stuff['var' ~ 'ia' ~ 'ble'] }}
its effectively the same as that previous simplified variable
{{ state_attr(state_attr('sensor.ramses_0_00', 'entity_id_climate'), 'schema').schema }}
while doing this Discord on PC, was also googling and I solved it by doing:
{% set sensor = states[states.sensor.ramses_0_00.attributes.entity_id_climate].attributes.schema.sensor %}
{% set actuators = states[states.sensor.ramses_0_00.attributes.entity_id_climate].attributes.schema.actuators %}
so putting [ ] instead of ' ~ ~ '
that would work for the first one
yes, but it's adviced to use state_attr() and not what you are doing now
yes thanks! I like this one much more then [ ]
{% set entity = state_attr('sensor.ramses_0_00', 'entity_id_climate') %}
{{ state_attr(entity, 'schema').sensor }}
but to be satisfied I want to know how to do this also, or is it not possible?
also good, thanks alot !
petro already answered that, not in the same namespace, only when using a dictionary like my example above
which one is a dictionary, can you reply to it?
{% set stuff = { 'variable': 'ia' } %}
{{ stuff['var' ~ stuff.variable ~ 'ble'] }}
that will output ia
i think i understand what you did there but its not the same I think, well whatever we solved the real one
😄
thanks again @marble jackal ! just wasted 2 hours for a simple thing and made an elephant out of a fly, atleast learned something new again !
No, it's not the same, but that is because what you wanted is not possible
Hello guys, Im wondering, how to get last datetime in my template for my door when was gone from locked to unlocked state? https://i.imgur.com/WA2EK56.png
"{{as_timestamp(states.binary_sensor.nuki_front_door_door_open.last_changed) | timestamp_custom('%A %d-%b-%y, %H:%M:%S')}}"
I created this template and it is correct, but Im missing only a condition for state, when was from "Locked" to "Unlocked" state.
Im not sure that I can put it here in this template?
that's not possible
if you want that, you'll have to make an automation that stores the datetime in an input_datetime
or use an SQL sensor to look into the database
How do I setup an availability_template that makes sure several different sensors are available?
For one sensor I've done this, right or wrong I'm not 100% sure?
availability_template: >
{{ states('sensor.electricity_price_osthammar') }}
Also how do you get the nice, color encoded code snippets? Three ` does not do the trick..
add "yaml" after the backticks
and assuming that you're using that with a legacy template format, which is where it's valid, that doesn't return "true" or "false" and won't work
it returns a string
@proud cradle I converted your message into a file since it's above 15 lines :+1:
did you make taht template or did you copy it
I made it
ok, then you should know how to make the availability_template return True or False then?
right now it just returns the state of your entity
so if you want it to be available, it needs to return true
So, I store in input_datetime and I create autonation to store that calue into input_datetime
Ahh oki, makes sense. What is this new template format? I presume I'm using the old.
it's just a new yaml format, nothing special. You don't need to switch to it
you store the time it changed to the state you care about
Do you know if there is any good documentation I can read which explains the new format and what has changed?
Aaahh, how do I convert an int to a string. It's nowhere in the docs.
yes, the docs
95% of this page: https://www.home-assistant.io/integrations/template/
yes it is 😉
| string
although any integration that has a state of "yEs" should be killed
Could you send me a link, I literally can't find it and thanks!
beat me to it
to be fair, nothing there says that 1|string is the right syntax
the Jinja docs are weird that way
I mean, it says "Convert an object to a string" 🤷♂️
Exactly! Never seen such notation before, I would have expected something like str(1) / string(1) or even ""+1 but 1|string is new to me.
And the jinja I found but that doesn't work in {{ ... }} these brackets right?
I ❤️ filters
filters are great, if you bother to learn them
not sure what you're saying here
this is the key bit in those docs: https://jinja.palletsprojects.com/en/3.1.x/templates/#filters
{{ }} -> outputs whats in the brackets
{% %} -> runs the line of code without outputting
Is there a way todo this without creating a separate group entity?
{% set sensors = ['sensor.electricity_price_total'] | list %}
{{ sensors
| rejectattr('state', 'in', ['unknown', 'unavailable', 'restored'])
| list | count > 0
}}
no need to tag me. I'm sure that Petro can help too 🙂
When I do {{string(10)}} is says it cant find string but the docs say string(value)
that's because the docs don't really show how you use them
for a filter, the first argument is always the incoming object/collection
if there are more arguments, then you do |filter(x, y, z)
That's my complaint! I've never worked with Jinja before, if the docs say string(value) I expect it to be a function. They could have written it as value | string that would have made sense to me a lot more!
e.g.
some_code(x, y, z) # As a function
x | some_code(y, z) # As a filter
Then you should read up on jinja
and stop assuming
we didn't make the language
it's not made by home assistant
it's made by some other nerds (not us, the HA nerds)
we just use it
I'm not complaining to you guys, you're awesome for helping idiots like me, I'm just complaining about the docs!
Sorry, but it's a short fuse with me because everyone and there mother complains to us, like we are going to fix it or change it
I'm answering my own question - but this seams to work fine to check that all sensors are available .
{% set sensors = expand(
'sensor.electricity_price_total',
'sensor.electricity_price_osthammar'
) | list %}
{{ sensors
| rejectattr('state', 'in', ['unknown', 'unavailable', 'restored'])
| list | count == sensors | count
}}
that's how I normally approach these things
i.e. put all things the template uses into a list, then ensure that they are all available
@analog leaf I converted your message into a file since it's above 15 lines :+1:
I'm currently trying to get https://community.home-assistant.io/t/wake-up-light-alarm-with-sunrise-effect/255193 to work but somehow it doesn't. sensor is my phone alarm.
sorry, that's too much to read
anyway, I hope #templates-archived message answers your question
I went with {{as_datetime(as_timestamp(states('sensor.date_time_iso')+ "+01:00" ))}} now as it seems to be a string and I can just add the timezone myself.
❤️
that's what I was getting at above
That works even better as I don't have to provide the timezone!
please have a look at https://community.home-assistant.io/t/how-to-record-the-duration-of-an-action-in-an-automation/495625 to help me out on the easiest template using input_datetime attributes?
not sure what type of input_datetime id use best for the ease of calculating the time spent between the 2 of them
Why don't you just set variables in your automation?
If I understand correctly you want the time that the switch was on
yes, indeed. we now have the time the action bolock takes, or even more precise, the time for the whole automation. Id love to narrow that down to the actual 'on' state for the switch
or the binary sensor?
no, the switch yes the binary.... sorry
oeh, that's nice, I didnt understand what you meant with variables, never used it like that before. It's what I do with the input_datetime (see my extra post in the community), but then way easier 😉 . Ill copy your full code in that same thread, unless you would like to do that? So our fellow commmunity members can see that too. (did it already now)
You’ve never used them like that before?
I just had a thought, this isn't taking into account day of the week is it? The tariffs are different on weekends
I'm not sure where the best place is to ask my question: I'm trying to build an automation that uses a counter helper. I want it to repeat till the counter is at it's maximum, and then stop.
I'm just struggling with how magical the templating seems to be
nope, guess I just never needed that. Or maybe I did, but fixed it differently. need to review my automations now 😉
Can someone help me figure out what is wrong with this?
- condition: numeric_state
entity_id: counter.tooth_seconds
value_template: "{{ state.state - state.attributes.Maximum }}"
below: 1
In 'numeric_state': In 'numeric_state' condition: template error: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'Maximum'
(I'm building a tooth brushing timer for my kids)
I notice this guy has it for weekdays etc, but he has the price in the template which we didn't do.
haha, it totally is, I'm reading various docs and only getting more and more confused.
I don't really know what you're doing there
well, it is mentioned https://www.home-assistant.io/docs/automation/trigger/#numeric-state-trigger
well, that's a trigger
yes, I can see that now
but it's also a thing for conditions
I'm building a new automation, I dont' have any triggers right now,
trigger: []
action:
- repeat:
until:
- condition: numeric_state
entity_id: counter.tooth_seconds
value_template: "{{ state.state - state.attributes.Maximum }}"
below: 1
that won't actually do anything
basically I want to repeat until the counter.tooth_seconds value (state?) reaches it's maximum
Yeah, I know that, I'm trying to explain what I want it to do. If it worked I wouldn't be here :p
lol
youd have to |float() it to be a number (numeric) though, https://www.home-assistant.io/docs/scripts/conditions/#numeric-state-condition
Imma need you to ELI5 here
won't that stop immedaitely?
had to google that ...;-)
Okay, I can figure out the math
perhaps you wanted "while"
anyway, does that entity have an attribute called "Maximum"?
Hey Rob, do you know much about the template I have been replying to, how to insert weekday vs weekend on it?
That's what i'm using
besides the point Rob makes, I do believe you need to make sure the template returns a number. Since all templates are strings, you would explicitly need to 'float' the result. Like the example in the docs. numeric expects a float
I don't have one, but I suspect that it's "maximum" and not "Maximum"
and yes, you need to convert at least the state to a number
yeah..
that was it
I think I saw some UI had capitalized it and it got stuck
editable: true
initial: 0
step: 1
minimum: 0
maximum: 120
icon: mdi:toothbrush-paste
friendly_name: tooth_seconds
This is what i get from the counter on the devtools
-> States is the definitive source of truth. Elsewhere, it gets translated and mangled
so, anything in that list will be on the state.attributes object then?
state.attributes is a dict, and those keys/values are all part of it
you can see that if you type {{ states.counter.tooth_seconds.attributes }} into
-> Templates
yes
man, I forgot about the templates thing
like my brain saw the word, and was like "nope, you don't need that"
Thank you
Templates are Life
condition: numeric_state
entity_id: counter.tooth_seconds
value_template: "{{ state.attributes.maximum - float(state.state) }}"
above: 0
I ended up with that
"{{ state.attributes.maximum - state.state|float(0) }}" would be better
What you did will work, but it's not typical of how you modify data in Jinja. You would normally use filters, which is what I did
and the (0) is specifying a default in case the state cannot be interpreted as a number. Otherwise, if that happens, the template render will just fail
so float() can cope with both methods of being called, but piping with a default is the recommended way?
yes
Thanks, any tips for dealing with WLED devices in an automation?
some filters are also functions, but most aren't
cause, dang the presets are a PITA
I don't use them and know nothing about them
okay, what the number.set_value service call
can any of those also take a value template?
- service: number.set_value
target:
entity_id: number.wled_intensity
data:
value: "69"
the docs will say
but in general, anything under data: or service: or target: can take a tempalte
I don't know what you're doing
I got it sorted
Anyone have any experience with light templates and effect lists? My template reports no errors when checking YAML, and I don't see any errors , but when I turn the light on there is no drop down list . I have values set for effect_list_template, effect_template, and set_effect. Am I missing something, or can someone recommend how to troubleshoot this?
effect_template: "{{ states('input_select.treeeffect')}}"
set_effect:
- service: input_select.select_option
target:
entity_id: input_select.treeeffect
data:
option: "{{ states('input_select.treeeffect')}}"```
whats the end goal? automation?
yeah, the end goal is to call the MQTT service to control the effects on the light. The entity doesn't natively support effects, but I can send effects via MQTT , so I was trying to create a single entity that consolidated both
Anyone able to do up a quick example for me. Trying to do a "if the data from the json = text" then condition is met for an automation. message: "{{ trigger.json.state }}"
ahh, thats above my paygrade
🤷♂️ I have everything working except the effects, no errors, no list... I'm at a loss
What kind of lights are you using?
Twinkly lights, powered by falcon player with the falcon player home assistant add-in
Oh yea cant help with that haven't used any of it.
the example in the documentation looks to be invalid , as it doesn't set an effect_template , but even with one set i can't get it to work
Link?
Oh though there was a specific one for the falcon add on. That is a messy light template lol.
If they are MQTT controlled I would have set them up as a MQTT Light https://www.home-assistant.io/integrations/light.mqtt/
the add-in brings it in as an MQTT auto discovered light
no effects..
but .. well... 💩 .... its a me problem.. i pasted in the sample code into my configuration and fixed the missing effect template... mine doesn't work the sample does
If it is auto discovered then it is telling it what it has.
so I messed something up lol
Yea have a look at the Flacon hass add in thing and see if you can get it to also add in the effects.
My MiLight hub has a list called 'Group state fields' where I have to check a box to say I want the effects list posted.
I made a manual list for WLED once, do you think that would help?
so i could go thru the list, like hit next and go to next effect
I'm not familiar with the lingo. I have roughly 30 smart switches installed. Is it possible to automatically add the physical switch to an automation if a related boolean switch is set to true?
I want to count the number of switches that are on given the entity_id starts with switch.zwater, alternatively count all switches that are on in two devices.. any help appreciated! I am currently at the following template {{ states.switch|selectattr('state','equalto','on')|list|length }}, but filtering the entities is my headache..
{{ states.switch | selectattr('state', 'equalto', 'on') | selectattr ('object_id', 'search', '^zwater') | list | length }}
Hey Fes, does that template you helped me with take into account weekdays vs weekends? (When you have time of course)
Beautiful.. I was close, but tried to use startswith for the object_id attribute, did not work. Can we find documentation for this or is it trial by error? Thanks anyway 🙂
search is mentioned in the jinja docs, and accepts regex
For the tariff?
Don't think so, can't remember you mentioned there was a difference
Yeah. Let me find a link to the tariff itself
It changes on weekends
There is no peak on weekends during summer and winter
Sure give me a couple
Hi!
I am very new writing templates and I am stuck at the following:
template: sensors: ampere_shelly_1a: friendly_name: Ampere Shelly EM1a unique_id: ampere_shelly_1a unit_of_measurement: A value_template: '{{ ((states("sensor.em1_1a_power")|float) / ((states("ssensor.em1_1a_power_factor")|float)*(states("sensor.em1_1a_voltage")|float)))|float|round(3) }}'
You are mixing the legacy and new format
state: >
{% set n = now() %}
{% set summer = [ 11, 12, 1, 2, 3] %}
{% set winter = [ 6, 7, 8 ] %}
{% if today_at('07:00') < n < today_at('22:00') %}
{% if (now().month in summer and today_at('14:00') < n < today_at('20:00'))
or (now().month in winter and today_at('17:00') < n < today_at('22:00'))
%}
peak
{% else %}
shoulder
{% endif %}
{% else %}
offpeak
{% endif %}
I tried adding a device_id to it as well, but failed.. any ideas?
{{ states.switch
| selectattr('state', 'equalto', 'on')
| selectattr ('object_id', 'search', '^zwater')
| selectattr ('device_id', 'equalto', '5f742531c9fd005cdbae69c2decbfd4d')
| list | length }}
The device_id is not in the state object
so Mon - Fri is fine during summer and winter months, just the weekends and non summer/winter work days, it only has shoulder from 7am-10pm and offpeak from 10pm-7am
{% set e = device_entities('5f742531c9fd005cdbae69c2decbfd4d') %}
{{ states.switch
| selectattr('state', 'equalto', 'on')
| selectattr ('object_id', 'search', '^zwater')
| selectattr ('entity_id', 'in', e)
| list | length }}
state: >
{% set n = now() %}
{% set summer = [ 11, 12, 1, 2, 3] %}
{% set winter = [ 6, 7, 8 ] %}
{% if today_at('07:00') < n < today_at('22:00') %}
{% if ((now().month in summer and today_at('14:00') < n < today_at('20:00'))
or (now().month in winter and today_at('17:00') < n < today_at('22:00'))) and now().isoweekday() < 6
%}
peak
{% else %}
shoulder
{% endif %}
{% else %}
offpeak
{% endif %}
that simple?
And trying to help another guy out in #energy-archived earlier today. His is peak 3pm-9pm on weekdays only, offpeak all other times, would this be the way for him to go?
state: >
{% set n = now() %}
{% if today_at('15:00') < n < today_at('21:00') %} and now().isoweekday() < 6 %}
peak
{% else %}
offpeak
{% endif %}
That would work
sweet, will let him know. thanks again Fes
Is there an "easy" template, jinja, etc. to get from a timestamp exactly this, what the frontend is doing: in 14 minutes, in one hour, tomorrow, etc, (and this of course 😉 best case in German language (as the frontend is able to do as well)).?
Hello, If I have a list of boolean values. How can I 'and' or 'or' them together to get out a single boolean value?
Any result of a jinja template based on locale will use the language set as locale on OS level, which will be English if you use HA OS. So there is no easy way
But there are probably posts on the community forum which do what you want
What is your goal here?
Will search for. But most probably then not that simple as a kind of makeuitext(states('sensor.timestamp')) what I of course hoped as HA is doing this already.
There is relative_time but it only works on datetimes in the past, and it will be in English
@formal ember I converted your message into a file since it's above 15 lines :+1:
so the guy i am helping has this as his automation for the dual tariff setup, but it is not changing. did i screw the template in the automation?
throwing it into the template in dev tools it returns UndefinedError: 'trigger' is undefined
he was, but then even when the time came around for him, it did not change
hes elaborated a bit on it here https://discordapp.com/channels/330944238910963714/872496321574088765/1047784392220745728
If you trigger it manually it won't work, as there is no trigger
it relies on the change of state of the sensor
does it work for you? Does your tariff change during the day?
yeah mine does 🙂 but its slightly different because of the third tariff
makes me wonder if i got it all right for him in the end?
my guess would be his template sensor with the current tariff type isn't named sensor.electricity_tariff
i will get him to double check all the entities
Not really template related but what we have been talking about, the utility_meter sesnor I made, it has the 3 tariffs in it which create tariff entities... is there a way to set a friendly name for those?
for the tarrifs itself? No, they are named based on the settings in Utlity Meter
utility_meter:
daily_energy:
source: sensor.energy
name: Daily Energy
cycle: daily
tariffs:
- Diamonds
- Peanuts
This would result in a select entity with Diamonds and Peanuts as options.
Logger: homeassistant.components.rest.sensor
Source: components/rest/sensor.py:170
Integration: RESTful (documentation, issues)
First occurred: 30. November 2022 um 16:29:33 (20622 occurrences)
Last logged: 13:58:33
JSON result was not a dictionary or list with 0th element a dictionary
Can Someone help me where to start with this Error?
Looks like you are performing some actions on the result of the rest query, which can't be processed if there is no result for example
Can this be fixed with something like a default Value if there is no result fro the Restsensor?
The thinks that are not getting Result are: 'layer_height' , 'object_height' and 'thumbnails'
I don't see those in the link you shared
Sorry, wrong Link.
That should be it, i cant seem to find a way to post my config because its to long for Discord
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
but this is fine as well
Thanks
what's the state of that sensor you use in the resource template when nothing is being printed
"sensor.3d_printer_state" is "standby" if nothing is printing
@green scaffold I converted your message into a file since it's above 15 lines :+1:
@green scaffold what's the problem, that looks like it should work
Trying to get all device_trackers which aren't assigned to an area. Any suggestions on how to do this? Particularly the filtering for entities without an area. Only thing I can think of is to manually specify each of my areas and then get a list of all device trackers and exclude the former list from that
templates
lol yes I mean that's why I'm here
plastics
That's not why I'm here 🙂
{% set ignore = states | map(attribute='entity_id') | map('area_id') | reject('none') | unique | map('area_entities') | sum(start=[]) | unique | sort %}
{{ states | map(attribute='entity_id') | reject('in', ignore) | list }}
Wow thanks, petro! You're really a master of templates
Wow, that right there is convoluted 🙂
I wouldn't have thought to go from entities to areas and back to entities in the same expression 🙂
lol
it's because we don't have a way to list areas
if we had a way to list areas, this would be less rediculous
I want a way to list areas so badly.
{{ states | map(attribute='entity_id') | map('area_id') | reject('none') | unique | list }}
{{ states | map(attribute='entity_id') | map('area_name') | reject('none') | unique | list }}
if you want something you can access at all times without redoing that template.................................
I mean that I'd like this to exist/work 😂
{{ areas }}
well, it would be areas()
I envision it to be like states.
Nope. As it is I was trying to do something via web sockets to provide me with a list as a sensor the other day. Then I got flu so I stopped work on it.
when I say possible, I mean it could be added
we could make an areas object and not make it callable
Do it! There's still time in this beta 🤓
Darn. But please add it. I'd love to use it!
Hi there, I'm getting "No Statistics found" in the History section of my template sensor. It is meant extract the power usage from my localtuya plug, which works live, but no history. Can anyone help at all?
` - platform: template
smart_plug_power:
friendly_name: "Living Room Power"
icon_template: mdi:flash
value_template: >-
{{ states.switch.living_room.attributes.current_consumption }}
unit_of_measurement: 'W'
use the new template format and add a state_class, device_class, and unit_of_measurement
also, power is not compatible with energy
energy is power over time, which is required for the energy panel
Is there documentation for this new template format?
yep, it's in template integration
Also as I understand it I use the integration function to convert to energy
- platform: integration source: sensor.smart_plug_2_power name: Living Room unit_prefix: k round: 2
yep
that's the sensor that needs the proper device_class, state_class, and unit_of_measurement
your power entity does not need that, so you could stick with the legacy format
But I want to see the power history, I had this before I moved to localtuya. This is a problem before I get to the integration part
then add the device_class, state_class, and unit_of_measurement to it using the new format
device_class, state_class, and unit_of_measurement control long term stats, that's what you need to see long term stats
the legacy template format does not support state_class
so you're forced to use the new format
Is there a way replicate Friendly name? My entity names are smart_plug_1 etc but friendly names had the locations. Doesn't look like it can be changed from UI
if you add an unique_id you can change stuff via the UI
Trying to get the color of a light to set the icon color in the Mushroom template card.
{{ state_attr('light.hue_lightstrip_02', 'rgb_color') | list | join(',') }}
Using this in the "Primary information" field just gives the rgb color without commas (2552555255), not (255,255,255)
Using it in the actual "Icon color" removes the icon entirely.
Using it in the template section in developer tools returns
Result type: list
[
255,
255,
255
]
you just want the literal text (255,255,255)?
Well i think i want it without the parenthesis? Since writing "255,255,255" in the Icon Color makes the icon white, but with parenthesis it does nothing
you're trying to template the icon color?
why are you putting the template in the primary field then?
I want the icon color to be the same color as a light
No. I just tried it in the primary field to visually see what it returns.
it already does that without templates though
Are you trying to use a the template card to display some other information on the light but you want the icon to be the color of the light?
anyways, usually these fields require rgb(255,255,255) as the output for them to work if it's an rgb color
Yes. I know the light card does that. But i want more information. This is a "room" card basically
This returns "rgb(255,255,255)" as a string (according to the template section in dev tools.) But in the icon color it does not work
{% set rgb = state_attr('light.hue_lightstrip_02', 'rgb_color') | list %}
{{ "rgb("+ rgb | join(',') + ")" }}
just needs to be rgb({{ state_attr('light.hue_lightstrip_02', 'rgb_color') | join(',') }})
if that's not working then the docs might help spell out what the requirements are
typing in what get's the color to change without a template?
Nope, does not work...
because based on what you said above... i.e. "255,255,255" paints it white, then all you'd really need is {{ state_attr('light.hue_lightstrip_02', 'rgb_color') | join(',') }}
Simply
"255,255,255"
or
"white"
can you post the field and the template when you use the template
i.e. post the whole line
or the whole config that you're trying
@spark tangle I converted your message into a file since it's above 15 lines :+1:
i don't see why that wouldn't work
I do find it odd that you're using |-
I'm guessing you just copied from someone else though
can the whole data: block of a service call be jinja generated?
Can someone assist me with some jinja syntax?
I want to filter an array of objects where object.datetime is in the >= now.
But I also want to preserve the other object properties.
I know how to do this in JS but not jinja
yes
needs to return dict
Give an example of the objects you have, but you'll be using the selectattr filter
if you can confirm they are always going to be datetimes, then you simply use selectattr like rosemary said
oh right, thanks
array_of_objects | selectattr('datetime', '>=', now())
yeah there will always be datetime
const data = [
{
datetime: '2022-12-01 20:00:00',
weather: 'snowy',
},
{
datetime: '2022-12-01 20:01:00',
weather: 'rainy',
},
].map((condition) => ({
...condition,
datetime: dateLibrary.convertToDateObj(condition.datetime)
}))
.filter(({ datetime }) => datetime >= currentDateTime())
that's roughly what i want to do (in JS)
Those look like strings to me
@tired sandal I converted your message into a file since it's above 15 lines :+1:
@mighty ledge Yes i know, I'm just using JS for an example because that's what I'm most familiar with
@marble jackal they are - I'm trying to convert date/times as strings into a proper datetime type, then filter the list by that
right, but what I'm saying is you can't convert types with any function in jinja, map can do it, but then it changes the object
right, i understand that
i wish there was a lambda func
i understand you can't use lambdas in jinja, but that's the rough approximation of what I'm trying to do
You can use strftime() on now() and do a string comparison
thanks!
well, the closest thing is select, reject, selectattr, rejectattr, and map
i don't want to do a string comparison
the first 4 will preserve the object
map will change the object into what you're mapping
maybe i should back up a bit
but you won't retain the original object with map
gotcha
Then you can rebuild the list in a for loop so it actually contains datetimes
@marble jackal oh right.
I want to look at the next 24 hours of weather (weather.home_hourly) and then decide if the next 24 hours are going to be <= freezing and if there's going to be any precipitation
or just use a forloop instead of filtering down
But a string comparison will be fine with this format
yep, that's what I do
is HA's hourly forecast >=now()?
format utcnow() to match the forecast values
or does it include < now()?
yes i understand that
without microseconds or the TZ
what I'm asking is - is the data in forecast present and future data or does it include historical data from earlier too?
...I don't care if it was freezing 3 hours ago, I DO care if it's going to be freezing tonight.
using string comparison works when you use utcnow().strftime("%Y-%m-%d %H:%M:%S")
Right
but my question (right now at least) is about the age of the data in forecast
right, so it's going to include things that are old.
...in other words - I am going to need to filter it
right
with string comparisons
your options are to use string comparisons and 1 loop, or transform then compare with 2 loops
yes.
which one do you think is optimal?
I'm still not entirely sure why I'm doing string comparison here
yes i know that, but jinja can convert ISO date strings into datetime objects, no?
(albeit in a loop)
sure you can
but what do you think is optimal?
making 24 datetime converstions and 24 datetime comparisons? Or 1 datetime to string conversion and 24 string comparisons?
I'm just not understanding how one would do date time math with string comparison
and is '2022-05-01' > '2022-06-01' ?
what about '2022-04-01T05:00' and '2022-04-01T08:00'
full circle, your wrenches won't work here
should've been T not +
this is python 101 my man, not js
this is ISO8601 my man, not python
You're welcome to continue to argue, but it's clear you don't understand string comparisons in python/jinja
I'm not arguing about string comparisons, I'm saying that,.....forget it.
You have an unalterable object that's in UTC fully fleshed out isoformat timestamp
you compare it to a fully fleshed out ISO formatted UTC timestamp and >, <, >=, and <= will work.
I know what you're asaying but youre complicating it for no reason
you have a hammer and you want to use it, I get it
but sometimes you have to act like you ahve other tools aside from your hammer
...no, I'm just trying to work out how the hell jinja works with strings
it goes character by character and evaluates each one
that's it
very simple
so if you keep the TZ the same, there's nothing to convert because those characters are negligible
and the good news is, the format of the string for forecast is already UTC
so you don't have to care about it when you have utcnow() that you can use
and actually, they use isoformatted strings
so you just need utcnow().isoformat()
Also, FYI if you're struggling with getting an hour of the day today in UTC, the code would be: {% set today = today_at("07:00").astimezone(utcnow().tzinfo) %} for 7am
then it would just be today.isoformat()
in the documentation i see the yaml for a state-based template binary sensor, but where do i put the code?
That seems overly complicated. I would just do {{ (now().replace(minutes=now().minutes()+1) - now()).seconds/60 }} (untested)
UndefinedError: 'datetime.datetime object' has no attribute 'minutes'
Something like that
this works in the dev tools template editor.
{% set t = now().replace(hour=1, minute=0, second=0, microsecond=0) %}
{% set r = ((t + timedelta(days=0) if now() > t else t) - now()).total_seconds() %}
{{ r | timestamp_custom('%-Hh %-Mm' if r > 3600 else '%-Mm', false) }}
i just can't figure out how to jam that into a sensor i can use.
yea sorry i had fixed that, pasted an older copy. i am also trying to get count down to other time vales with the same script too,
not sure it's the right place so please feel free to point me elsewhere. I am wondering if it's possible to display the value of a counter in esphome?
If you expose it as an entity, you would access it like any other entity
In an automation template (triggered by a sensor update), is there some reason to use trigger.to_state rather than states('sensor.whatever')?? (is the latter expected to be updated before the automation is called?)
cc @formal ember
You want to use trigger
It’s the information that caused the automation to trigger, which may not be what you get from the states method
for some reason his automation is not being triggered - @fickle kettle is the automation failing to trigger at all, or is it running and not changing the tariff?
It looks like it ran, but didn't change the tariff (and I didn't see it in traces).
it's triggered on a change in the tariff (top bar), and changes the price (bottom graph)
#energy-archived message
When I manually changed the tariff just now, it changed, and changed back OK
🤷♂️
actually.... I think I know the problem.
It probably ran perfectly at 9pm, but the value was already low, since the earlier job that should have set it to high failed, because there was some mistake in the value (extra %})
the manual test was OK (the up/down on the right), but let's see at 3pm 🙂
Then I might add it to energy dashboard. (don't want to break my previous solution, which works fine, until then)
bonus of having 3 tariffs is i get to find out sooner if things actually work 😄
but, will be interesting to see how the weekend tariffs go
I don't actually import any power at all from about 0700 to 1900 (solar), so although the price will swap, it won't have $$ impact.
thats so good. wish i had a system like that. what was the cost to install?
Full retail would have been about $25k I think, but with govt rebates and all that stuff, I think I paid about $8k
Actually, looking at emails. Was $8850 + $5k deposit that I paid
8.25kw inverter but really only get solar from 10am-5pm at the moment
still, that is amazing, how long ago?
six months?
!!!!
I've got 20kw inverter + panels.
Goodwe. I'm not suuuuuper happy with it - it's super noisy, and I'm trying to get the installer to move it outside (my workshop). But at least the HA integration is OK.
ah yep. I heard some can be noisy. ours is outside, Solaredge. Took a while (and a few visits from the installer) to get the monitoring right with visibility of import, export, consumption etc
I did all that myself, with HA integration via modbus, and ct-clamps on the wires etc (iotawatt)
if i were to do it again, i'd have optimisers or micro inverters installed at the panels because of the shading we get
But we're offtopic for here 🙂
back to #energy-archived you guys 😛
I am using a following template for binary_sensor template: value_template: "{{ states('sensor.openweathermap_temperature') | float()) > 1.5 and (states('sensor.openweathermap_wind_speed') | float()) < 7 and (states('sensor.outside_temperature') | float()) > 1 and (states('sensor.outside_wind_max_speed') | float()) < 5 }}"
Is there any way of making it still work when one of those sensor will be unavailable (so the template still renders based on the remaining ones)?
i want to have a sensor that shows me the electricity cost of just 1 smart plug. I understand I have to use history_stats platform, but i have no clue what the state of my sensor is. {{ states('sensor.tz3000_typdpbpg_ts011f_summation_delivered')}} returns a number
all the examples i can find are about on/off sensors
and a lot of unneeded parenthesis
Lots of Insidious Silly Parentheses
I mentioned that over use of parenthesis in math made it harder to read on Reddit the other day and got downvoted to hell and back
apparently people think parenthesis are easier to understand than pedmas
🤷♂️
Yeah it was those people who were downvoting me 🤣
Some guy even replied with lisp saying that he was a dev for it
thanks!
I'm not sure where to start with this one. I have a weather station and it has an built-in heater because when it gets cold, the wind readings become wrong, however, the heater also causes some local heating so the outdoor temperature can be inaccurate. For example, at -27oC true temperature, it can be off by 4oC, ie. it report a temperature of -23oC. Anybody know how to approach this and create a sensor based on this issue to compensate for the heater? It should only compensate for temperature when its below +5oC, and even then, it would be a "gradient" as the temperature gets colder, so (+5,0) and (-27, +4)...
assume a linear equation
I have this string and would like to calculate the minutes it is from now. Could someone point me in the right direction? 2022-12-02T19:00:00.000+01:00
Though this should have outputted the local time, but it still showed the same for some reason.
{{ state_attr('sensor.run_heater_when','heater')[0].startsAt|as_datetime|as_local }}
Output:
2022-12-02 19:00:00+01:00
what did you expect the offset to be?
it should reflect your local time. For me, that gives "2022-12-02 10:00:00-08:00`, which is correct for me
Very strange... that's 25min from now (when my heater will turn on) and let me tell you... it's not on! 🤣🥶
How would get the time difference in minutes between that string and now()?
{% if forecast[0].condition == "clear-night" %}
{% icon = "mdi:weather-night" %}
{% endif %}
{{ icon }}```
can someone help me debug my IF statement? I plan on putting this into a markdown card but when I add this into the card, the card goes blank which I assume the reason is a syntax error
as a sanity check, I've also done if "clear-night" == "clear-night" with no success
Which timezone are you in?
+01
then it's right!
Sorry guys I'm retarded... I forgot to filter out the values when the heater isn't running 🙈 Now it looks good, I just need to convert a formated datetime into minutes which I saw someone doing by adding lie ().minutes or something?
{%
set runTime = state_attr('sensor.run_heater_when','heater')
| rejectattr('value', 'in', [0])
| map(attribute='startsAt')
| sort
%}
{{ ((runTime[0]|as_datetime|as_local) - now()) }}```
```0:11:59.989734```
I would like just 11 or rounded to 12.
you would normally round a time like that by adding 30 seconds and then just taking the minute
Smart, unfortunately I don't know how todo that here.. I'm just an average php guy 😛
excellent
{{ ((("2022-12-02T20:23:42.000+01:00"|as_datetime|as_local - now()) + timedelta(seconds=30)).seconds/60)|int}}
😍
Where do you guys learn all this? I find the documentation a bit lacking when it comes to learning the language and its methods etc
Works perfectly btw, thanks a bunch @inner mesa 🙂
reading the docs and solving problems for you guys 🙂
Nice, then maybe you know if there is a function to either get the maximum value like max(-1, 0) and that should return 0 or if there is a way to do something like ifLessThanZero(-1,"return this") ?
Me mainly by asking questions here, in combination with the links in the pinned posts
[0, some_result ] | max
or
iif(some_result < 0, 0, some_result)
But I would go for the first one
That's brilliant! Thanks
Interesting -- the first suggestion from Rob inverted a negative number to positive when getting the delta in sec
I guess if the target date was less than 30s in the past
you can filter those out and don't do the math if that's going to be a problem
it sounds like an error condition based on your description
Yeap, this worked 🙂
{%
set runTime = state_attr('sensor.run_heater_when','heater')
| rejectattr('value', 'in', [0])
| rejectattr('startsAt', 'lt', now().timestamp() | timestamp_custom('%Y-%m-%dT%H:%M:%S.000%z'))
| map(attribute='startsAt')
| sort
%}
time to heater starts {{ [0, (((runTime[0]|as_datetime|as_local - now()) + timedelta(seconds=30)).seconds/60)|int] | max }} min```
Hi, I do have defined a sensor by mqtt with a state class of total increasing:
- name: "Garagenkraftwerk Arbeit Gesamt" state_topic: "solar/116175200790/0/yieldtotal" device_class: energy unit_of_measurement: kWh state_class: total_increasing unique_id: "GaragenkraftwerkArbeitGesamt"
Sometimes, maybe because of rounding errors, it startes new measurement cycles. Is there any way to prevent this?
Hi everyone, is there a way to obtain a localized state of an entity? {{ states('weather.myown') }} returns state in English.
Thanks petro! That's what I ended up doing.
hi, is there a value template for this to check if it has been true for 20sec?
- condition: numeric_state
entity_id: sensor.samsung_j3_ipcam_sound
above: '138'
Nope, you need to create a template binary sensor for that if you need it
and how do I do that ^^
{{ states('sensor.samsung_j3_ipcam_sound') > 138 }}
this will make the sensor turn on whenever it has passed that threshold right?
Correct
oh and it turns off if it goes downard of that value
and then I just use it as a condition with a time value attatched
thanks!
Correct again!
I would like to monitor when washing machine and dryer turn off, so someone can go rotate laundry. These machines (specifically the washing machine) has periods of "soaking" with very little energy usage for a few minutes, so a simple threshold trigger (probably?) wouldn't work.
Could I make a template binary_sensor that would go "on" when energy usage goes over 20W, and "off" when it has been under 20W for 2 minutes? Is there a better way to do this?
You can do that, but I "progress" my appliances through a list of states in an input_select based on their power usage. Only the end state notifies me. I based what I did on this: https://philhawthorne.com/making-dumb-dishwashers-and-washing-machines-smart-alerts-when-the-dishes-and-clothes-are-cleaned/
@dusty hawk I converted your message into a file since it's above 15 lines :+1:
Shoot. I'll try again
@paper hazel I converted your message into a file since it's above 15 lines :+1:
Figured it out...
Any idea if the keyword 'pop' (which is, Probability of Precipitation) is a HA template security-flagging parameter?
this:
{{ state_attr('sensor.openweather_report', 'daily')[0].pop }}
returns this:
SecurityError: access to attribute 'pop' of 'dict' object is unsafe.
All other parameters at that level work OK. Just this one fails.
WTH, a 2fer, this works: {{ state_attr('sensor.openweather_report', 'daily')[0]['pop'] }} Thanks, @inner mesa
what's special about 'pop'?
And, 'clouds' don't? What is pop in collection-speak?
It's a Python method
I wouldn't really call it 'escaping'. You're just indexing based on the string in such a way that it isn't misinterpreted
The dot notation for indexing is a Jinja thing that introduces ambiguity
Ahhh, I was thinking that pop might have been a variation of PEEK and POKE that would well be disallowed, but was a keyword a vendor choose, inartfully, perhaps. Maybe so, anyway.
It's just a Python method
And HA doesn't let you modify data structures once they're created
Hard to keep up as one who dives in as needed to javascript, Python, jinja, bash scripts, SQL, et al. I started with Fortran IV, and exited coding professionally after a loig tour through unix to about SQL Service Analysis Services writing Financial Services Multi-dimensional models. Thanks for helping.
It tells you what's wrong and what to do 🤷
you're right.
I just don't program YAML every day and the documentation and groups are full of depricated and il-advised methods
and I figure after an hour of mesisng and reading conflicting posts and documents, I to ask for help
Sorry about that
Here's a better question... Why does this work and return the right value in the templating sandbox?
value_template: "{{state_attr('weather.portland', 'temperature')}}"
It's the documentation
Ok?
I still don't understand what's what you're asking. Why does it work? It's correct and should work
In some of the documentation it says
`sensor:
- platform: template
sensors:
solar_angle:
friendly_name: "Sun angle"
unit_of_measurement: "degrees"
value_template: "{{ state_attr('sun.sun', 'elevation') }}"`
Not sure where the question is
and other places it says this:
- platform: template sensors: sensor name: friendly_name: "sensor friendly name" value_template: "{{ sensor value template }}"
I doubt that
stand by for the screenshot
I have no idea what you're asking. None
and maybe I mispoke when I said documentation
At all
the VScode drops the whole code block
Drops?
you type - platform: templ>>>>
Ignore it
Turn off code snippets
but the old and the new are hard to sift through
Ignore it. Get rid of it
gone
Don't let that confuse you
I'm old enough that I should know that I shouldn't assume things are "right"
so my bad
I'm tired
and cold
It's trying to help and it isn't. I turned all that crap off
I'm a hardware engineer, maybe that will explain my issues.
Anyways, thanks for the advice
i'm trying to create a sensor that stores a value based on the output of a template. it's saving the data as a string - is there a way to make a template output a value that's stored numerically (so I can graph it over time?)
i see mention of a number template but i've not been ble to find any examples of it.
my actual goal is to calculate a statistic and save that statistic as a value over time.
thinking making a sensor template would be the best way
doesn't pass yaml test
in "/config/configuration.yaml", line 175, column 9
expected <block end>, but found '<scalar>'
in "/config/configuration.yaml", line 177, column 28```
i think my code is identical to one of the examples
template:
- sensor:
- name: "Rainfall DarkSky"
unit_of_measurement: "in"
state: '{{ states('sensor.rainfall_over_last_48h_darksky')|float }}'
feel like it's identical to this: https://www.home-assistant.io/integrations/template#state-based-sensor-changing-the-unit-of-measurement-of-another-sensor
And I define that sensor as
sensor:
- platform: statistics
name: "Rainfall over last 48h - darksky"
entity_id: sensor.dark_sky_precip_intensity
max_age:
hours: 48
state_characteristic: sum
Your template uses the same type of quote inside and out
You are using the same quotes inside and outside the template
Oh, crap, apparently I wasn't at the bottom yet
Hi everyone.
Is it possible to generate a UUID from a template?
Why would you want that?
Hey I'm trying to make an automation trigger when I'm playing any game on steam.
I made this template sensor for it
steam_game_iisakki:
friendly_name: "Iisakki's steam game"
value_template: "{{ states.sensor.steam_76561199090611635.attributes.game }}"
The problem is that the resulting sensor has no value at all when I'm not playing a game. Is there a way to create a sensor that just returns "true" when playing any game and "false" when not playing?
The problem is that the attributes for the played game in the steam sensor disappears altogether when no game is played, instead of showing something like "not playing"
So I can't automate based on that.
What I'm trying to do is change settings for my wled strip behind monitor when I'm paying a game
@shrewd pilot {{ not state_attr('sensor.steam_76561199090611635', 'game') is none }}
This works, awsome, thank you a lot!
Hi, I am trying to get a value of the forecast of tomorrow 05:00 using standard weather sensor with hourly forecast. This is what I have now...it works but I would not be able to explain this (trial/error)
{% set x = state_attr('weather.home','forecast') | count %}
{% set pd = state_attr('weather.home','forecast') %}
{% for i in range(0,x) %}
{% if as_local(as_datetime(pd[i].datetime)) == now().replace(hour=5, minute=00, second=0, microsecond=0) + timedelta(days=1) %}
{{ pd[i].temperature }}
{% endif %}
{% endfor %}
any suggestions on this?
It's iterating through the list of forecast items looking for the one that has a timestamp of 5AM tomorrow
What did you want exactly?
It could be much shorter
{{ (state_attr('weather.home', 'forecast')|selectattr('datetime', 'eq', (utcnow().replace(hour=20,minute=0,second=0,microsecond=0)+timedelta(days=1)).isoformat())|list|first).temperature }}
Do you want 5:00 local time or 5:00 utc
doesn't look like anything template related
Ah shit sorry, over to integrations
@heavy crown If you want local time you can use
{{ (state_attr('weather.home', 'forecast')|selectattr('datetime', 'eq', (today_at('5:00').astimezone(utcnow().tzinfo) + timedelta (days=1)).isoformat())|list|first).temperature }}
I was trying and failing to work out this bit: (today_at('5:00').astimezone(utcnow().tzinfo)
was wishing for an |as_utc filter
I knew it had tzinfo in it, and that petro posted it recently 😉
hi. defined a template that listens 2 sensors, but i get the incorrect value, although individual sensors state is ok http://pastie.org/p/6b746AG0hbuG31aI9QCt8d
Is there a way to get a template to output a list of device trackers associated with a person entity?
i get the incorrect value
what value?
seems easy enough to debug
For context, specifically for the purposes of an automation that keeps track of the battery levels of all device trackers associated with me without me having to manually input the list of devices into the automation, so I don't ever have to update the automation if I add/remove devices.
you can easily get a list of all device_tracker entities, but I don't think there's a way to get the list of entities that are attached to a specific person, only the one that's currently supplying the location for that person
Dang, okay. Thanks anyway.
yup...simple math, but don't have an explanation 😦
each value is set to 1 according to state ...so 1+1 = 2...template should say "ok"
I got nothing:
{% set map = {0:"NOK", 1:"NOK", 2: "OK"} %}
{% set n = 1 if 'ok' == 'ok' else 0 %}
{% set z = 1 if 'ok' == 'ok' else 0 %}
{% set x = z + n %}
{{ map[x] if x in map.keys() else 'Error' }}
``` -> OK
again, this isn't rocket science. just check
probably the syntax is not correct , one day an idea will rise 🙂
🤷
syntax is fine
here
{{ states('sensor.nas_sam_smart_status_drive_0_1') }}
{{ states('sensor.nas_sam_smart_status_drive_0_2') }}
what does that say?
both OK
"OK" is not "ok"
hey maybe someone can help me 🙂
I have a Sensor which sends all 5 seconds the current time and I want to make a binary sensor which shows if the device send for more then 1 minute no new state, to indicate if the device is off or on
I know my code cant work this way .. but I should be something like this
binary_sensor:
- platform: template
sensors:
pc_on:
friendly_name: Zeigt an ob der PC im keller an ist
value_template: >-
{{ now() - state('sensor.desktop_lastactive_2') 60 }}
Hello, I am having a big problem with the template. I have a long configuration configuration and the sensors I added do not appear in the system...Can you help me?
It depends on the format of that sensor
maybe: {{ state('sensor.desktop_lastactive_2')|as_datetime < now() - timedelta(minutes=1) }}
perfect thank you 🙂
hey, my template sensor keeps failing the check configuration and can't figure out why!! driving my crazy
It always helps tremendously when you say how it's failing, not just that it fails
ive tinkered with it a few times now (7 actually) now im not sure which one is the latest error message 🤣
here are the error messages
Ok, so friendly_name is no longer allowed and you have weird quotes
value and value_template are coming from some other template
My guess is that you're mixing up the old and new style templates
oh that was it, i removed friendly name and it passes now
thank you very much!
also, I'd like for the sensor to be 1 decimal place. if I place "| round(1)" after float condition, it doesn't seem to round it to 1 decimal place. Where do I place the | round(1)
sensor yaml here
{% set temperature = states("sensor.temp") | float(0) | round(1) %}
The last three won't be rounded. They go on to do more math
guess I have to put it on every line?
Everywhere you want it rounded
got it!
http://pastie.org/p/1BR2oz6Fcf4fGXOuHnLPgl this is my master configuration. I'm trying to add a sensor here that I have the code for. File manager gives a green notch, I can't find an error, I save and update the template assets again, but this sensor does not appear in the system. Where should I add this sensor in this configuration? `template:
- sensor:
- name: combi_boiler_current_power_usage
unique_id: combi_boiler_current_power_usage
unit_of_measurement: W
device_class: power
state_class: measurement
state: >
{{ is_state('switch.combi_boiler_relay_switch', 'on') | iif(states('input_number.combi_boiler_power_usage'), 0) }} ` I'm having trouble pasting the code here properly. I'm still very new to this platform. I will learn this as soon as possible. I apologise for the visual pollution. Actually, the codes I want to apply are on this page: https://seanblanchfield.com/2022/02/virtual-energy-meters-with-powercalc
Sensor attributes last_changed and automation attributes last_triggered are not in my local time, but UTC by default. What is the easiest way to change it?
Actually I'm not sure it is UTC, but what it shows is equal to UTC.
They are actually in UTC, but the frontend shows it in your local time
You are mixing legacy template sensors and the new format under the template key
When I display it like this: {{ states.sensor.latest_hemr_occupancy_sensor_on.last_changed }} it gives me this: 2022-12-05 06:47:53.265064+00:00, which is not right, because my local time is one hour later.
template:
- platform: template
sensor:
- name: "Estimated Battery Depletion Time"
state: "{{ as_timestamp(states('input_datetime.estimated_battery_depletion_time')) | timestamp_custom('%-I:%M %p')}}"
icon: mdi:clock
- name: "Estimated Battery Depletion Time Countdown"
state: "{{ (as_timestamp(states('input_datetime.estimated_battery_depletion_time')) - as_timestamp(now())) | timestamp_custom('%H hr %M min', false)}}"
icon: mdi:timer-sand
move this part all the way to the bottom, remove the - platform: template line and add a - before sensor
Yes, so this is UTC
{{ states.sensor.latest_hemr_occupancy_sensor_on.last_changed | as_local }} will give you the local time
both are a correct representation of the time the sensor last changed, the timezone information is at the end (+00:00)
Yes, understood, thanks a lot!
sorry, was waiting for a reply for too long 🙂
I want to be able to change GUID on my phone companion app, as I use it to open garage door when I get home. But it offers no security and easy to clone and reuse.
The plan is for HA to generate new GUID and store in a helper. And automation will be comparing detected ble beacond GUID to that of a helper and actioning the automation if matched.
I can use Python script and call API from python, but thought it maybe easier just to do it on the fly
I have tried many different combinations. Even if I write according to the new system, the file manager does not give an error, but the home assistant gives an error...I am having difficulty solving the problem....I would be very grateful if you could specify in which section where I should put this sensor and with which indentations.
Well I started with this, but there is too much wrong in your config. Have a look at the documentation for the the template integration. The legacy format is at the bottom
Indentation is off for most of you legacy template sensors
And the new format is a different integration, it should not be placed under sensor:
I have a template sensor problem, which might be buried deep in HA, but which there might be a solution to: I have a group of mqtt-based sensors. When I restart HA the sensors themselves do not change but when I iterate through the group using expand and display the last_changed attribute of each sensor, the last_changed times are the time of the restart. Is there any solution to this?
Well, the state did change, from something like unavailable or unknown to the actual state
so that's why last_changed is updated
I recognized that reboot makes a few seconds of unknown state.
have a look at this thread, there is a solution based on mqtt sensors there, but also based on a trigger based template sensor.
https://community.home-assistant.io/t/persistent-version-of-last-changed-for-the-ui/467163
as I don't use mqtt myself, I've created the trigger based template one (https://community.home-assistant.io/t/persistent-version-of-last-changed-for-the-ui/467163/67?u=thefes)
Sure, I'll have a look at it. The strange thing is that when I look at the sensor itself in the history of the sensor, cannot see anything. Nor can I see this in the Dev Tools.
I think it filters these changes out for the frontend
where do you expect to see this in dev tools?
When I list the entity states, there somtimes is a last_changed attribute (second column: state) but isn't any.
At the top, I can see Last Updated and Last Changed.
Got it!
I'm gonna implement the trigger based template sensor you referenced. Would this work for mqtt?
It works for any entity
Is it enough if I apply it to the template sensor that works on the group of mqtt sensors, or I need to apply it on all individual mqtt sensor entities?
You need to add the individual entities to the trigger
All right!
what have I done to deserve this? https://imgur.com/g29ruMA
I can't even find where I created this sensor...
utility_meter perhaps?
had a look there and I cannot find it, just had a look at sensor.yaml and found this
- platform: integration
source: sensor.dehumidifier_smartplug_power
name: "Dehumidifier"
unique_id: 1da30564-1ac1-4d0a-b413-c858e1d5c949
unit_prefix: k
round: 2
What integration does the Related tab say created it?
No related items found.
And if you look in the entities list?
i think i need to scrap this and start again...
whats the best way to make a sensor for the energy dashboard based off a device that shows you how many watts it is using?
I said entities list, not states list 😉
ahh
just says integration
its like it turned on and just whacked 10kwh on to the sensor in one hit
That is weird. The only things I have with integration in the name of the integration are the Riemann Sum Integrals
aha!
That's exactly what the code above is
is this the right way to monitor a power source to put it in the dashboard?
Which is also the method to convert power usage in Energy
I can't see what im doing wrong with the following template im trying.
light.all_lights is a group (helper) that i created via the UI.
# This returns 3 (which is correct)
{{ expand(states.light.all_lights) | selectattr('state','eq', 'on') | map(attribute='entity_id') | list | count }}
# This returns 1 (there is a bit of extra formatting)
{% set ns = namespace(res=0) %}{% for switch in state_attr('light.all_lights', 'entity_id') if is_state(switch, 'on') %}{% set ns.res = ns.res + 1 %}{%endfor%}{{( ns.res | string + " ") | replace ("1 ", "1 ") }}
@plain veldt expand takes grouped entities and breaks them up into their individual entities. You're not using it in the second template.
it's recursive BTW, so you most likely have nested groups
recursive means it continues to dig deeper into the groups and return only the non-group entities
I've been trying to get rid of this error with this availability template, but I've misunderstood something as it still shows up at times.
TemplateError('TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'')
availability_template: >
{% set sensors = expand(
'sensor.electricity_price_total',
'sensor.tibber_prices',
'binary_sensor.run_heater'
) | list %}
{{ sensors
| rejectattr('state', 'in', [NoneType,'unknown','unavailable','restored'])
| list | count == sensors | count
}}
What shall I do to cover that case too?
Just add 'NoneType' to the list?
you're not adding anything in that so the error is coming somewhere else.
Yeah it's from my template, but I presume it's one of the sensors that doesn't hold a valid value?
it's not from that template.
I can 100% tell you, it's not from that template.
you are not adding in that template
@proud cradle I converted your message into a file since it's above 15 lines :+1:
That's the actual template
{% set prices = (state_attr('sensor.tibber_prices','today') + state_attr('sensor.tibber_prices','tomorrow'))
that line
and the heater line
Tomorrow is [] right now, shouldn't throw an error?
at startup, those attributes will return None
so you should add an availability template that checks for those attributes existing
or not being none
Right now:
{{ state_attr('sensor.tibber_prices','tomorrow') }}
[]
ahh thank you, will look into that!
yes but at startup it will be None
so when you restart, it will error and fail the sum. i.e. the + operator that your error is throwing
TemplateError('TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'')
So I need to add one more check in the attribute_templates that looks for, but not fails at the attribute?
it needs to check the attribute value for none
For some reason I find it difficult to find errors even when I browse... I've been in this system for about a year and a half... While the variety and doability is great, this yaml thing is really crazy... I'm still having trouble figuring it out. It needs a magic button. But it seems difficult in this process... Keep watching tutorial videos...
Any suggestion how I do that in a clean way?
state_attr(...) is not none
Ahh so it won't fail when trying to access a property that do not exist?
the attribute exists, but it's none
well, it might just be a byproduct of state_attr returning none if the attribute doesn't exist
regardless, do that
you could also just do this in your template
Nevermind, it complicates it. Just add the availability
well, maybe not
give me a moment
example:
sensor:
- platform: template
sensors:
adjust_slope_outside_temp_living_room:
friendly_name: adjust_slope_outside_temp_living_room
value_template: >
{%- set delta_slope = ((states('input_number.tado_max_slope')|float(default=16))-(states('input_number.tado_offset_slope')|float(default=16)))/12 -%}
{{(states('input_number.tado_offset_slope')|float(default=16)+((states('sensor.outdoor_temperature')|float(default=16))*delta_slope))|round(2)}}
- the object_id (
adjust_slope_outside_temp_living_room:in line457) and everything under it should be indented 2 spaces. - The same applies to the sensors after this one (lines
464-483) So basically lines 457 to 483 should be indented 2 spaces - The same applies to the sensors in line
521 - 542 - then on line
564you have a sensor with only a value template, no object_id - from lines
568 - 601you have template sensors using the new format, they should not be under thesensor:key, but under thetemplate:key - you have that
template:key on line606but you added an additional- platform: templateline which should not be included in the new format
{% set today = expand('sensor.tibber_prices') | selectattr('today', 'defined') | map(attribute='today') | first | default([]) %}
{% set tomorrow = expand('sensor.tibber_prices') | selectattr('tomorrow', 'defined') | map(attribute='tomorrow') | first | default([]) %}
{% set items = today + tomorrow %}
@proud cradle work off items from that point on and you won't need availability at all
it'll always have empty lists
so...
Ohhh that's soo clean, big thank you @mighty ledge
My home assistant system crashed last night:) I will recover it when I get home and apply what you say:))
i'm working on optmizing your code too
hold up
It goes to default now, something is up with how it selects the values I guess
[
{'total': 2.8995, 'startsAt': '2022-12-05T00:00:00.000+01:00', 'level': 'CHEAP'},
{'total': 2.7094, 'startsAt': '2022-12-05T01:00:00.000+01:00', 'level': 'CHEAP'}
]```
That's whats in the today & tomorrow properties.
ok
well your format is wrong
for the comparison
I'm not sure why these guys didn't use ISOFormat
For the date? I'm not sure their tech department is ran by the most experienced devs tbh given how much downtime and issues they have
ah, they added microsends milliseconds
yeah, but this will work
{% set currentPrice = states('sensor.electricity_price_total') | float %}
{% set gridFees = states('input_number.electricity_grid_fees') | float %}
{% set threshold = 0 %}
{% set onRate = 0.6 %}
{% set alwayOnBelow = 1 %}
{% set neverOnAbove = 6 %}
{% set ts = (now() - timedelta(hours=1)).replace(microsecond=0).isoformat("#", "milliseconds") %}
{% set today = expand('sensor.tibber_prices') | selectattr('today', 'defined') | map(attribute='today') | first | default([]) %}
{% set tomorrow = expand('sensor.tibber_prices') | selectattr('tomorrow', 'defined') | map(attribute='tomorrow') | first | default([]) %}
{% set items = (today + tomorrow) | rejectattr('startsAt', 'lt', ts) | list %}
{% set prices = items
| rejectattr('total', 'none')
| map(attribute='total')
| sort
%}
{% set threshold = prices[(prices | count * onRate) | int] + gridFees %}
{% set threshold = min(neverOnAbove,max(alwayOnBelow,threshold)) %}
{% set heater = items
| rejectattr('startsAt', 'lt', ts)
%}
{% set ns = namespace(vars = []) %}
{% for item in heater %}
{% if item.total + gridFees < threshold %}
{% set ns.vars = ns.vars + [{'value': 1, 'startsAt': item.startsAt}] %}
{% else %}
{% set ns.vars = ns.vars + [{'value': 0, 'startsAt': item.startsAt}] %}
{% endif %}
{% endfor %}
{{ ns.vars }}
I'm sure the ending could be optimized, but I didn't feel like it 🤣
🙂
UndefinedError: list object has no element 0
the integer selection you're doing is suspect too