#templates-archived
1 messages Β· Page 23 of 1
can anyone help me with a mushroom template title card?
Id love to show the following when more then 1 persons are watching plex
But the following code doesnt work
{% if is_state("sensor.tautulli_watching", '>1') %}π¬{{ states.sensor.tautulli_watching.state }} persons are watching plex {% endif %}
{% set cnt = states("sensor.tautulli_watching") | int(0) %}{% if cnt >= 1 %}:clapper:{{ states.sensor.tautulli_watching.state }} person{{ 's are' if cnt > 1 else ' is' }} watching plex{% endif %}
hero! Thanks very very much
hey, i struggling a the state of an entity. I just want the state of an entity but in the same format like in a entity card.
If i use this: { states('switch.xxxxxx') }}
i get only "on" or "off". Is there a way to get the state back like "On" or "Off" and also the translation?
Not from a template.
translations are strictly front-end only at the moment
You can manually translate it yourself
is there a way to get the language and translate it in 2 languages?
Not sure if I know what you mean, but If you use lovelace-template-entity-row, it will translate to the current language.
"In evaluated templates the function _(<key>) (underscore) will localize the <key> to the current language. E.g. _(state.binary_sensor.motion.off) will be replaced with Clear if your language is set to English."
sorry i meant @mighty ledge
i had a quick look at template entity row but for me it is not clear how to use this my card is currenlty like this:
type: custom:mushroom-template-card primary: Fernseher secondary: '' icon: '{{ ''mdi:power-plug'' if is_state(entity, ''on'') else ''mdi:power-plug-off'' }}' icon_color: '{{ ''orange'' if is_state(entity, ''on'') else ''red'' }}' entity: switch.fernseher tap_action: action: toggle layout: vertical
and i want the state in the secondary field
You can't get translations
I can't say it enough
if you want to use the custom card boneheadfraggle mentioned, you have to completely use that card
otherwise, you cannot get translations
@dry lichen ^
thats what i understand from you petro. I understood that the first you wrote it
Yes, but you keep asking for it
if you just want the under the hood state for secondary,
secondary: "{{ states(entity) }}"
thank you for clarification
Is there a way to convert a sensor value that is a string currency -> a float / int?
E.g. the sensor value is Β£2.40 and I want to get it as a float so 2.40?
is the unit in the string?
Yes
if it's always the first character... float(value[1:])
Yes.
That works. Thank you
If the character moved around would there be another way to remove it?
May be regex?
You could also value.replace("Β£","") and cast to a float .
value_template: '{{ value | regex_findall("[0-9.]+") | first }}'
That's what I did just the other day with a gas price sensor
Are there any Utility Meter experts here? π I am tracking a device that can go negative. For example -20 one day. Does it start at 0 the day after or does it have to work from -20 if the following measurement is positive?
that'll work jumbers unless it gives you 3423.2342.324234 as a number
regex to find a safe number is lengthy
If it always has 2 decimals you can do
value | split | select ('is_number') | join | multiply(0.01) π
Sometimes the currency string wont have a trailing 0.
Thanks for all the help and tips everyonie!
boneheadfraggle lol
@glass veldt I converted your message into a file since it's above 15 lines :+1:
that is not a proper template
Sorry, I pasted that quickly
{% if states('sensor.water_room_offline', '1') %}
I am trying to change the color of temperature based on the offline sensor
{% if is_state('sensor.water_room_offline', '1') %}
you're also listing "red" twice?
not a very interesting template π
That is just to error catch. I can't get it to go red at all!
you're also not introducing a multiline template
I will change to different colours once it's working π
I'm a beginner, can you tell lol
I think I actually sent you a DM about this. Sorry about that.
color: "{{ iif(is_state('sensor.water_room_offline', '1'), 'red', 'blue') }}"
yeah, please just post in the forum
I saw that you did that
Won't happen again
no worries
Like this: card_mod:
style: |-
hui-generic-entity-row:
$: |
.text-content:not(.info) {
color: "{{ if(is_state('sensor.water_room_offline', '1'), 'red', 'blue') }}"
}
I'll reiterate that I don't use card_mod for this, so you'll probably get more help in #frontend-archived
the template is not the hard part here
"iif" not "if"
not a typo
oh wow, ok lol. Totally thought that was a typoi
It is possible, to get the name from the NFC-Tags based on the ID in the template?`(The name from NFC-Tags tab in Home Assistant under Settings)
Thanks for your time Rob. I will check in #frontend-archived
I have 2x datetime objects. Is there a way to find the difference between the two and represent them in another datetime-like format e.g. HH:MM:SS?
Sample data:
2022-12-29 20:15:38
{{ as_datetime("2022-12-29 20:15:38") - as_datetime("2022-12-29 19:55:52") }}
Thank you @solemn frost I didn't know you could do datetime addition / subtration like that.
If it's more than a day, it'll come out like this: 3 days, 0:19:46
it's a timedelta object
The template page in the dev tools will tell you it's a string, but yeah it's actually a timedelta
@turbid breach I converted your message into a file since it's above 15 lines :+1:
Tried but does not change :/
I expect that it's the previous state of the sensor, not the one that you're setting now
oh, and states are all strings, so it will never be 0
{% if this.state == '0' %}
but if you want to use the current state that you're setting in that definition, you'll need to replicate the logic in the "state" section
Oh thought I tried it but I just realized that the sensor info page actually works, and shows the current state, thanks a lot.
This is exactly what i did. Thank you!
Im wondering if templates are the best way to create a solution for this, but Im trying to create a multi state sensor to use in automations to determine if:
- Someone is asleep
- Everyone is asleep
- Nobody is asleep
To use for various lighting automation conditions. The biggest problem Im running into is the scalability of having checks which tell if multiple people are awake or asleep based on presence and phone charging status after a certain time. I want to factor presence in, as lighting automations need to fire even if the other person is out of town or something
My 'whiteboard solution' is something like this:
if (person x home and person y home) and (person x phone charging and person y phone chargin) everyone is asleep is true
if (person x home and person y not home) and (person x phone charging) everyone is asleep is true
if (person y home and person x not home) and (person y phone charging) everyone is asleep is true
If (person x home and person y home) and (person x phone charging or person y phone charging) someone is asleep is true
if (person x home and person y home) and (person x phone not charging and person y phone not charging) nobody is asleep.
But it really doesn't feel scalable if I need to add another person. Is there a cleaner way to scale it to multiple people, all of whom have their own devices attached to them?
good evening everyone
i want to get a list of every entity form the group group.battery_devices that has a state < 10
this is what i tried with no luck
https://pastebin.com/tSV5BFPY
Probably leveraging groups. You can create a group of "all people home", a group of "some people home", a group of "all phones charging", and a group of "some phones charging". Then adding new people is just adding them to the groups, and you don't touch the logic.
Though I'm not quite sure I follow the implication that anytime someone plugs in their phone they must be asleep, but π€·ββοΈ
Or actually I see you might need more than that. I would maybe create a per person sensor: "person is away or charging", and then make a group of those to use.
make a binary_sensor for every person first
then make a sensor/binary_sensor for the case
That's kind of a pain in the neck. I think you'd need to do something like this:
{% set group = "group.battery_devices" %}
{% set ns = namespace(low_batt=[]) %}
{% for entity in state_attr(group,'entity_id') %}
{% if states(entity)|float(0) < 10 %}
{% set ns.low_batt = ns.low_batt + [entity] %}
{% endif %}
{% endfor %}
{{ ns.low_batt }}
the problem with your code is that states are strings and can't be compared directly with numbers
ouch
checkin for unavailable entities is fairly easy
but numbers are hard
and you can't currently apply a filter to the incoming state without losing the entity_id
we desperately need a way to apply a filter to the incoming collection for selectattr and related filters
Grab this attribute, apply this filter, then use it with with the test & value
this seems to work, thanks alot
would have never figured that one out
I kinda hope that somebody else comes along with a more elegant solution...
Might've just found a bug (still on .12). state_attr seems to work as a filter in the dev tools template editor, but when I try it on a template sensor I get an error: No filter named 'state_attr'.
The fact that it errors I think lines up with the docs. I didn't think it would work, but then it did so I rolled with it. Either way, I'm pretty sure these should be consistent
π
same issue as the expand thing then?
It's still not working but I don't have any error message... juste the entity stay empty.
I would like to have in one entity the attributs starting with android.text* (like android.text_com.android.systemui or android.text_com.facebook.orca) from the mobile entity "sensor.a52s_active_notification_count" whne the value of these attribut are different from 'Bruit dΓ©tectΓ©' or 'avant pleine'
Maybe it's too complicated for home assistant ?
well, this was not clear from what you posted before
Should be possible, but currently I'm working, and this is quite complex
type: entity
entity: sensor.pool_cover_status_unsigned
state_color: false
value_template: '{{ states(''sensor.pool_cover_status_unsigned'') | float / 255 * 100 | float }}'
Id like to have that sensor display a value from 0-100%
The current values are 0-255, so I setup the value template, but it is somwhow not working. Any ideas?
it's not too complicated, but that attribute does not seem correct. Post your entities attributes as shown in HA's dev tools -> states page
that looks like a frontend card, which don't accept templates.
any ideas on how to do it otherwise?
make a template sensor
How would I do that since its a knx sensor?
I'm not following you
you simply create a template sensor and use that in your UI instead of the knx sensor
Sorry, im new to this.
I have a KNX sensor which gets the values from the bus - I need to convert them from 0-255 to 0-100. How would I create a template sensor that uses the knx values?
in yaml, you add a template sensor, which is a separate integration
check out the pins at the top of this channel
you already have the template that you posted above, you just need to add it
Made it work, thanks alot!
np
the | float at the end is not needed BTW
@rancid dagger I converted your message into a file since it's above 15 lines :+1:
for the second one, you can't use templates in a tap_action
use the template in your script itself
but my script might be called by different entities, I need to pass him the right entity too as a variable.. won't I get the same problem there ?
You can just use type: percent in this case for a knx sensor.
I just discovered this. Unreal.
Hey,
Iβm trying to make something that looks like a SWAKES Sensor counter, but I canβt figure it out by myself.
image
I want to count the number of entities within a group that I have and show also how many of them are in the βOnβ state
For example:
I have group.cameras with 3 entities of my cameras, 2 of them are βOnβ state and 1 is βOffβ state
So I want to show up in my dashboard 3/2 (3 is the total number of entities within the group, and 2 is the number of βOnβ devices within the group).
How do I do that? I want to count my lights and some devices I have.
Thanks for helping!
Something like this should give you that output
{{ group | count }}/{{ group | selectattr('state','eq','on') | list | count }}```
Thank you, it's working!
try to get the temperature from this in my sensor.yaml whats the mistake?
- platform: template
sensors:
climate.control_zo1
value_template: "{{ state_attr('climate.control_zo1', 'current_temperature') }}"
unit_of_measurement: 'Β°C'
friendly_name: 'Wohnraumtemperature'
state_class: measurement
device_class: temperature
Can this be written in a shorter version? I need a - before every item and each item should be on a new row:
{%- set doors = expand('binary_sensor.deuren_open') | selectattr('state', 'eq', 'on') | map(attribute='name') | list %}
{%- set data = namespace(entities=[]) -%}
{%- for state in doors -%}
{%- set data.entities = data.entities + ['- ' + state] -%}
{%- endfor -%}
{{ data.entities | join("\n") }}
When I do a join in teh first line then the first item doesn't has a - at the start
First : please paste your code staring with 3 backticks ` and als ending it. Second, this is the old way of using templates, it will work but better you migrate to the new way
template:
- sensor:
- name: "climate_control_zo1"
state: "{{ state_attr('climate.control_zo1', 'current_temperature') }}"
unit_of_measurement: "Β°C"
friendly_name: "Wohnraumtemperature"
you should be able to paste this 1-on-1 in Templates (under Development Tools) and see where it works/fails, I have no clue of your 'climate'
and seeing ou add 'measurement'...do you only want to have this show the temp?
I dm'ed you something about it, trying to track my temp sensors for example which has no 'on' / 'off' state, how do I do that? for example if 'sensor.temperature_humidity_sensor_humidity' is above 1% than it will consider it as on
you can use the same approach but instead of selectattr you use rejectattr
Oh wow expand doesn't work in template sensors either? How have I not run into this before
No clue if you are referring to something (not tracking all hist above) but I would not know why expand does not work
{{ expand('binary_sensor.deuren_open') | selectattr('state', 'eq', 'on') | map(attribute='name') | map('regex_replace','^','-') | join('\n') }}
``` should work
Invalid config for [sensor.template]: invalid template (TemplateAssertionError: No filter named 'expand'.)
Thanks that works!
It's not a filter
Yeah exactly. Well I mean it is in dev tools. That's what I Rob pointed out above
Seems to be a bug
How do i invert a input in YAML?
#dim Down
- conditions:
- "{{ command == 'down_press' }}"
sequence:
- service: light.turn_on
target: !input light
data:
** brightness_step_pct: !input dimmingIntervall**
transition: 1
this should be negative
* -1 ?
I know nothing about blueprints
or how to incorporate an !input into a template, which is probably what you need to do
we do have a channel for that: #blueprints-archived
how exactly?
https://www.home-assistant.io/docs/blueprint/schema/#blueprint-inputs-in-templates I haven't actually used blueprints and misunderstood your needs at first. This in the docs looks promising for you though.
So why not add your template? I (at least) cannot guess what you did/want π
I'm certain that it's this: https://github.com/home-assistant/core/pull/76006
As that's exactly the problem that I set out to fix...
ok...thanks then I step out as this is already on the next level π
You can provide variables in the data of the service call
So I'm just now coming back and revisiting a template I had for a sensor that stopped working awhile ago and see that there's now a new recommended syntax
I used to have, in my sensors.yaml:
- platform: template
sensors:
internet_in_mbps:
value_template: "{{ (state_attr('sensor.usg_wan_in_stats','change_rate')|float*0.25*(state_attr('sensor.usg_wan_in_stats', 'sampling_size')-1)/1000000)|round(2) }}"
unit_of_measurement: "MB/s"
entity_id: sensor.usg_wan_in_stats
and am now trying to move that into a new template.yaml:
sensor:
- name: internet_in_mbps
unit_of_measurement: "MB/s"
state: "{{ (state_attr('sensor.usg_wan_in_stats','change_rate')|float*0.25*(state_attr('sensor.usg_wan_in_stats', 'sampling_size')-1)/1000000)|round(2) }}"
YAMLKHAAAAAN shakes fist
all of the state_attr stuff can stay the same in the state: as it was in the value template before though?
You may want to set unique_id: internet_in_mbps and set the name to something friendly
Yes, you can leave that as is
Hmm, still showing unavailable after a reset. Any way I can find more detailed info about what's failing in it?
"Reset"? Do you mean reloading the templates?
Well, I restarted HA entirely.
And if you didn't have the templates.yaml file before your last restart you'd need to restart
Ah you did restart. You can just reload the template in developer tools now though, probably.
It's definitely reading in the templates.yaml file as it now shows the pretty name and the unique ID
Good
and I've verified that the sensor.usg_wan_in_stats sensor has data in it
Does sensor.usg_wan_in_stats exist?
Exists, and is populated with an integer value that refreshes/increases every 10 seconds
You may want to try:
state: >
{{ (state_attr('sensor.usg_wan_in_stats','change_rate') | float(0) * 0.25 * ( state_attr('sensor.usg_wan_in_stats', 'sampling_size') | int(0) - 1) / 1000000) | round(2) }}
Could it be you have a working sensor.internet_in_mbps_2?
Nope, I thought of that, and it did indeed create one, but that is unavailable as well.
(This is now passing defaults into the float, and making sure the sampling_size is an int with a default)
vscode is saying something about a missed comma between flow collection entries?
Does the template work in developer tools > template
It does not appear to. But this is helpful π
no error, it just returns -0.0 as the state
although that doesn't explain why the sensor is unavailable
Well that's due to the defaults
But in the dev tools try outputting just {{ state_attr('sensor.usg_wan_in_stats','change_rate') }}
And the same with sampling_size, to see which one(s) are empty
Yeah it's weird, it says "None" for both.
oh! I wonder if this has to do with the change I had to make to the sensor definition
Well that's your problem π
HASS complained that the statistics platform needed a state_characteristic attribute set
Maybe? It depends. But you can look at {{ states('sensor.usg_wan_in_stats') }} to make sure it has something
which it did not previously have or need
it definitely has something, if I output {{ states('sensor.usg_wan_in_stats') }} it outputs a number as expected
and updates every 10s
Good!
Open your Home Assistant instance and show your state developer tools
You can look into this to see which attributes are available
Those links never work for me, still not sure why.
Go to my.home-assistant.io and fix the address that's there π
ah, http/https issue. Thanks.
Do I now need to specify every state_characteristic I want a statistics sensor to have?
or should I be creating a separate statistics sensor for each characteristic?
What kind of sensor is this?
If it's a statistics one, then yes you need to add a sensor for each one you want π
Gotcha. Previously it was just a generic "statistics" sensor and I think it had ALL of them. A recent HA update made it so that was invalid config.
So that was perhaps something that changed semi-recently?
Not in my recent memory. But these attributes must be on a sensor that the statistics integration is using
What does your statistics YAML look like?
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.
http://pastie.org/p/5DudCbpU0kBiX4zxtycqNa this is what it was. I had put in a state_characteristic=mean just to get it to let me restart HA because it was complaining but I suspect that's what messed up the others
going to try creating multiple stat sensors for it
with change_sample and change_second
https://www.home-assistant.io/blog/2021/12/11/release-202112/
So the state_characteristic change happened about 13 months ago π
Don't update shame me. π
(it's possible that the change was made then but it was officially deprecated/started throwing errors recently?)
Well it was listed in the changes, if you get very behind it can be annoying but is definitely worth checking the breaking changes on every single update you need to do. They are always listed
It was an immediate change by the looks of it, but I didn't check the code to make sure
So the long story is that this whole thing broke a very long time ago not because of HA but because of my network. SNMP is not enabled by default on my new gateway so all my stats stopped working. I just manually installed SNMP on the new one and am trying to get it all working again but running into rabbit holes on multiple fronts π
Rabbit holes are my favourite way to learn and discover new things
Be warned: The Discord search is amazing, and excellent at providing new rabbit holes (which may lead to other dimensions π )
lol
I've gone down enough rabbit holes learning about SNMP OIDs today. π
and narrowing down what I want from the 57 interfaces on my router
lol
A mere 57? There are some in this server who would want at least a 0 on the end π€ͺ
This might actually simplify things quite a bit though
{{ states('sensor.usg_wan_in_change_rate') | float(0) / 1000000 }} this alone I think should do it
if I set state_characteristic: change_second
Nice!
Hey, thank you very much for your help and insights today @silent seal and also @marble jackal - much appreciated.
You're welcome! Happy automating!
`binary_sensor:
- name: "Has updates?"
state: >
{{is_state('update.home_assistant_core_update','on')}}`
I get missed comma between flor collection entries. Why?
I don't understand the question
I'm getting an error in VSCode and don't understand why. The message is the one above " missed comma between flor collection entries".
that just sounds like broken English
now I'm the one not understanding you
this is not an English sentence that makes any sense "missed comma between flor collection entries"
*flow instead of flor
anyway, it seems like you're trying to create a template binary_sensor without using the proper format
this is inside a templates.yaml file that came from template: !include templates.yaml
it's still not right
- binary_sensor:
- name: "Has updates?"
state: >-
{{ is_state('update.home_assistant_core_update','on') }}
you need a list
you had a map
Are there any ways to change an 'Unavailable' state for something like 'Idle'?
If it was from '0', for instance, it could be:
- name: "Sensor XXXX"
unique_id: sensor_xxxx
state: >-
{% if (states('sensor.XXXX') | float <= 0) %}
Idle
{% else %}
{{ states('sensor.XXXX') }}
{% endif %}
But for 'Unavailable'....
Should the order of things defined in your config ever matter? I have some template sensors that are defined as a static value (yes I know this could be done other ways) and if they are defined in my config after another template sensor that uses them then I get errors in my log
There's an availability template for the sensor to mark the sensor available/unavailable. Is that what you're looking for?
https://www.home-assistant.io/integrations/template/#availability
'Unavailable' is just a state
This seems like a bug. I've never heard of ordering mattering with any HA YAML configuration
Need to see an example
Order makes no difference at all as long as you follow the proper formatting
Here's the sensor:
- name: "Time Heater Seconds"
unique_id: time_heater_seconds
state: >
{{ (4.186*(80000*(60-states('sensor.temperature')|float(0)))/states('sensor.heater_watts')|float(0)) | round(0) }}
availability: "{{ states('sensor.heater_watts') | float(0) }}"
Keeping it terse just for the example but I can provide a fuller one:
- sensor:
- name: I use my sensor
state: >
{{
states('sensor.my_sensor')|float
}}
- sensor:
- name: My sensor
state: "1.23"
The availability solves the log's error caused when the 'sensor.heater_watts' is '0'
But then it becomes 'Unavailable', has it should.
I think it's blowing up on the float parsing specifically
that syntax isn't valid
The indenting is wrong there. The second -name is at the same level as sensor
your indentation is wrong
It's more of a aesthetic matter... I guess.
Ok sounds like you want a full example then lol
no, it's just wrong
I'm not getting indentation errors, though
I guess we need a real example π
not a broken one where we wave away the brokenness π
I made it more right if you want to take another look. I was leaving out that one level of sensor.
like i said, order makes absolutely no difference as long as the indentation and formatting are correct
ok, and what's wrong?
ValueError: Template error: float got invalid input 'unknown' when rendering template [...] but no default was specified
ValueError: Template error: float got invalid input 'unknown' when rendering template
If I define them in the other order then I don't get this
Your float doesn't have a default π
you'll probably get that when loading them because it's evaluating each one in turn
is it preventing the system from loading them?
Hm wait maybe I lied. I'm trying again and I'm still getting the errors
lol yeah well that's just a result of a issue before where it shouldn't be unknown
Never assume that something will not be "unknown" or "unavailable"
At some point the first entity will be created, and at another point the second one will be created. They don't happen all at the same time
this isn't a YAML thing at all, it's just the nature of a computer
I do kinda seem to get less errors though...
That's good practice, but I'm trying to get at another issue
And all it takes is someone making a typo when editing a file or renaming a sensor and the entity could vanish π
and I don't think it will prevent you from loading the templates at all, but instead give you an error, but then be fine later on
Ok so there's no guarantee on the order they will be evaluated? Like there's no dependency checking basically?
No
Ok good to know
A list by technical definition does not necessarily have an order.
is it just an error at startup/reloading?
In general each YAML file is loaded in in alphabetical order (whatever your system defines alphabetical as), but the contents of those are processed in whatever order makes most sense to the parser
lol I think it's a race condition. I move the template sensor that has dependencies to the bottom of the file and I don't get that error
But if there's no dependency checking then yeah I shouldn't rely on that and basically do what @silent seal was saying and check for things
It's not a race condition, it's just your template not failing gracefully π
I mean it is still a race condition lol
I run it multiple times with different results with the same input
Not saying it doesn't make sense if there's no guarantee of order though
- name: "Sensor XXXX B"
unique_id: sensor_xxxxb
state: >
{% if (is_state('sensor.xxxx','unavailable')) %}
Idle
{% else %}
{{ states('sensor.xxxx') }}
{% endif %}
You're right.
How should I go to add float <=0, so it would have the same behavior with '0' and negative values? I can't seem to get the template right.
Ugh... true. Was thinking of something else.
How can I convert a MQTT sensor which is currently an entity into MQTT device?
If I use
- service: light.turn_off
continue_on_error: true
target:
entity_id: |
{{ expand('light.alle_lampen')
| selectattr( 'state', 'eq', 'on')
| rejectattr( 'entity_id', 'eq', 'light.weihnachtskegel')
| rejectattr( 'entity_id', 'eq', 'light.galeriegelander')
| rejectattr( 'entity_id', 'eq', 'light.lichterkette')
| map(attribute='entity_id')
| join(', ') }}
and get sometimes (not always) Error for call_service at pos 3: Template rendered invalid entity IDs: without further information, what could be the reason and how to avoid this?
Unfortunately I have no output of this template for the error point in time either to see, what is perhaps wrong there.
No lights are on
Create a variable out of the template and first use that in a condition in an if
Use a condition above it
That's what I would do
- variables:
lights: >
{{ expand('light.alle_lampen')
| selectattr( 'state', 'eq', 'on')
| rejectattr( 'entity_id', 'in', ['light.weihnachtskegel', 'light.galeriegelander', 'light.lichterkette']
| map(attribute='entity_id')
| list }}
- if: "{{ lights | count > 0 }}"
then:
- service: light.turn_off
continue_on_error: true
target:
entity_id: "{{ lights }}"
Indentation is a bit off because I'm on mobile, but you get the idea Indentation fixed
Hi. Is it possible to create a template sensor which takes the value of another sensor but only at specific times? Eg. Right before midnight when the sensor resets. I haben't found any examples of this. πΆ
yes, create a trigger based template sensor, and use a time trigger just before midnight
Out of curiosity, what is your use case?
Yes, make a triggered template sensor. There's many examples of this in the documentation.
There are many use cases for this. I have one that updates at midnight every day and when HA restarts to specifically limit the number of times it calculates so that it does not alter an automation that uses it during the day.
I use it for seasonal calculations based on the current date. It's a heavy template and it really only needs to be available 100% of the time, but it should only calculate once a day because there's no need to run it more. If I were to remove the trigger, it would update once a minute, which is overkill.
In my case specifically I use a service which provides me with energy useage from yesterday, but it updates several times with preliminary numbers before giving me the real number.
In the history stats integration, I need a configuration that gives the duration of my last translation when it switches from off to on and after a certain period of time when it switches back to off. History stats came to mind as an integration, I am open to other options and suggestions... I would appreciate your help
{{ is_state('binary_sensor.pir_sensor_4', 'on') and (now() - states.binary_sensor.pir_sensor_4.last_changed).seconds < 900 }}
Can I keep the result of this sensor on the screen for 15 minutes? In other words, if we divide an hour from 15 minutes to 4, can I make it write true if there has been movement in the motion sensor in the last 15 minutes and false if not?
I'm not sure what the "dividing hours" has to do with it, but do you just want a sensor that shows "on" if that PIR sensor has been on w/in the last 15min? It's much simpler to just use delay_off: https://www.home-assistant.io/integrations/template/#delay_off
My goal is: If the sensor has been true in the last 15 minutes, it stays true for 15 minutes...The sensor configuration I have: the sensor detects motion and gives true and returns false again after 10 seconds...What I want is that if the pir sensor detects motion, it stays true for 15 minutes....Is there motion or not for the last 15 minutes?
Note: I don't want to do this from the pir sensor settings... It would be great if it is possible with templates or different systems
I'm sorry I didn't see the rest of your message... This is what I wanted "delay_off"... I will apply it, thank you very much
Is there a way to tell if I'm accessing the frontend from the mobile app vs a normal browser?
only with browser mod
the custom integration, and even then, it's painful to get the current browser mod entity that contains the user you care about
but it's all possible using that custom integration
just keep in mind, the logic to get which one you're using will still fail when you're logged into both a web browser and the app. Which will happen more than you anticipate.
it's there anyway I can make an entity from 1 attributes from another entity? my samsung tv state is on or off, but I want to get state for source of TV
yes, using a template sensor
thank you!
I'm having some trouble with this jinja statement and not sure why.
{{ state_attr('calendar.test', 'message') is not none | iif(state_attr('calendar.test', 'message').split(' ')[0], none) }}
Trying to make sure the split only happens when the 'message' is defined in the calendar sensor.
however the Dev Tools tempalte keeps giving me this error
UndefinedError: 'None' has no attribute 'split'
iif always renders both the true and false option
and you are apply the iif on none now
{{ state_attr('calendar.test', 'message').split(' ')[0] if state_attr('calendar.test', 'message') is not none }}
uh, the whole filter and beyond don't make sense
{{ states | state_attr('media_player.samsung_tv_remote', 'source') }} how can i tell to use only when TV is on ?
and when it's off to be null or something else?
Thank you. Didn't realise that was the case.
this template doesn't make any sense, what are you trying to do here?
{{ state_attr('media_player.samsung_tv_remote', 'source') if is_state('media_player.samsung_tv_remote', 'on') else 'off' }}
it's a media_player, they usually are not on, but playing, (or idle, or paused)
depends on the media player
that's perfect, thank you so much! @mighty ledge
it's a Samsung TV, I want to get the source as a state, to use in nodered
you can probably also do:
{{ state_attr('media_player.samsung_tv_remote', 'source') | default('off', true) }}
- name: "Samsung TV Source"
state: "{{ state_attr('media_player.samsung_tv_remote', 'source') if is_state('media_player.samsung_tv_remote', 'on') else 'off' }}"``` I added this to my template folder in a file sensors.yaml, I have this in configuration ```template: !include_dir_merge_named template``` , and after restart I don't see the entity, I do something wrong ?
!include_dir_merge_named is not correct
!include_dir_merge_list
thank you so much! it's working now
Hey all, I'm trying to create a tts message to let me know what my calendar events of the day are, but this does not seem to work as it keeps saying there are no calendar events today but there are 5 listed. Any idea what is wrong with this? thanks for your help.
{% set ns = namespace(events=[])%} {% set cals = states.calendar |
map(attribute='entity_id')| list %} {% for cal in expand(cals) |
selectattr('attributes.start_time', 'defined') |
sort(attribute='attributes.start_time') | map(attribute='entity_id') |
list %} {% if now() < state_attr(cal, 'start_time') | as_datetime |
as_local < today_at() + timedelta(days=1) %} {% set ns.events =
ns.events + [state_attr(cal, 'message')~" at "~ (state_attr(cal,
'start_time')|as_datetime|as_local).time()] %} {% endif %}{% endfor %}
{% set todays_events = ns.events %} {% set qty = todays_events | count
%} {% if qty != 0 %} There {{'is an' if qty==1 else 'are '~qty}}
event{{' ' if qty==1 else 's '-}} on the calendars for today. {{' and
'.join((todays_events|join(', ')).rsplit(', ', 1)) }}. {% else %} There
are no calendar events today. {% endif %}
today_at outputs midnight...
don't you want between midnight and now()?
right now you have the opposite
ah, missed the + 1 day
Between now and today at midnight + 1 day is how I read it
yes, it goes off in the morning
I suggest breaking it down and debugging the parts
well, it's simply never getting into that if statement
wouldn't you want to check the entire event?
i.e. the start and end?
if the start is before now, that check will fail
looking at my calendar data, it's outputting correctly
that is a good point, but if it past, then its not important, maybe?
that depends, the event is still occuring if the end time is after now
You should debug on your calendar
I should
Do you actually have events that match that logic?
most of my calendar entries are from google cal, if that matters
{% set t = now() %}
{% set ns = namespace(events=[])%}
{% set cals = states.calendar | map(attribute='entity_id')| list %}
{% for cal in expand(cals)
| selectattr('attributes.start_time', 'defined')
| sort(attribute='attributes.start_time')
| map(attribute='entity_id')
| list %}
{% set start = state_attr(cal, 'start_time') | as_datetime | as_local %}
{% set midnight = today_at() + timedelta(days=1) %}
{% set end = state_attr(cal, 'end_time') | as_datetime | as_local %}
{% if t < start < midnight or t < end < midnight %}
{% set ns.events = ns.events + [state_attr(cal, 'message')~" at "~ (state_attr(cal, 'start_time')|as_datetime|as_local).time()] %}
{% endif %}
{% endfor %}
{% set todays_events = ns.events %}
{% set qty = todays_events | count %}
{% if qty != 0 %}
There {{'is an' if qty==1 else 'are '~qty}} event{{' ' if qty==1 else 's '-}} on the calendars for today. {{' and'.join((todays_events|join(', ')).rsplit(', ', 1)) }}. {% else %} There
are no calendar events today.
{% endif %}
It's easier because you're already populating a bunch of intermediate variables
ok, if I put the block above as you pasted, i get there are no caledar entries....so it must be something to do with how the events input. For example, right now its 9 am, I have an entry at 10am and 4 all week events....still says there are no calendar entries.
i want to count how many of my state.climate entities currently have the attribute hvac_action set to heating.
My best guess till now was:
{{ states.climate | select('is_state_attr', 'hvac_action', "heating") | list | count }}
but this this fails:
AttributeError: 'TemplateState' object has no attribute 'lower'
Pointers anyone?
also keep in mind that calendars only show the next event
they do not show a list of events
yes all dat events...but I also have an 10 am appointment (in 1 hr)....and it didn't pick that one up
so, at most each calendar will produce 1 event
ok this sheds some light on the code, it may not pick up all day events that started yesterday and beyond
Everything that kinda like works with filtering/listing that I found in configuration/templating used arrays of entitiyIds
I thought the code would go beyond the first event...but that also explains that
also, looking at your template, you're doing a lot of... unnecessary conversions
oh, where?
well, it can be reduced to this
{% set t = now() %}
{% set ns = namespace(events=[])%}
{% for evt in states.calendar
| selectattr('attributes.start_time', 'defined')
| sort(attribute='attributes.start_time') %}
{% set start = evt.attributes.start_time | as_datetime | as_local %}
{% set midnight = today_at() + timedelta(days=1) %}
{% set end = evt.attributes.end_time | as_datetime | as_local %}
{% if t < start < midnight or t < end < midnight %}
{% set ns.events = ns.events + [evt.attributes.message ~" at "~ start.time()] %}
{% endif %}
{% endfor %}
{% set qty = ns.events | count %}
{% if qty != 0 %}
There {{'is an' if qty==1 else 'are '~qty}} event{{' ' if qty==1 else 's '-}} on the calendars for today. {{' and'.join((ns.events|join(', ')).rsplit(', ', 1)) }}.
{% else %}
There are no calendar events today.
{% endif %}
there's more oddness in your output line too, like you output a space or s with a space, but then remove the space after
just output nothing or s and remove the trailing whitespace remover
and you're adding an extra space on are
and you're missing a space on and at the end
when I run this code, it says its looking at the domain calendar, vs the older code, it specifically lists each calendar i have, which does clean that up as domain calendar means every calendar I presume
no, the space after the are is needed, my b
yes, the spacing is weird....I think it worked before but then the values were not spaced or something like that
so I added extra spaces
got it!
FYI that's why it's good practice to space out your operations so you can easily read your code
thank you! now I just have to figure out why my events are not showing up in this code
I promise, next time I will
attributes.hvac_action
I always wonder why people don't add them, it makes the code so unreadable. Like reading an entire book without paragraphs
sorry, i didn't finish my response, do this for me. Paste the output here
[
{%- for c in states.calendar %}
{
'entity_id': '{{ c.entity_id }}',
'attributes': {
'start_time': '{{ c.attributes.start_time }}',
'end_time': '{{ c.attributes.end_time }}',
'message': '{{ c.attributes.message }}'
},
},
{%- endfor %}
]
I don't get it.... attributesis not defined and I it is also no valid filter. How should I use this?
says this:
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'start_time'
sorry, this
[
{%- for c in states.calendar | selectattr('attributes.start_time','defined') %}
{
'entity_id': '{{ c.entity_id }}',
'attributes': {
'start_time': '{{ c.attributes.start_time }}',
'end_time': '{{ c.attributes.end_time }}',
'message': '{{ c.attributes.message }}'
},
},
{%- endfor %}
]
might be too long to paste BUT it is listing all the events!
{{ states.climate | selectattr('attributes.hvac_action', 'eq', 'heating') | list | count }}
here's one event
ok ill paste bin it now
and by current time i mean paste this here too
{{ now() }}
aaaahhhh! thank you!
now is last line
There are 3 events on the calendars for today. Tempo Christmas Break at 00:00:00, Garbage Cart at 00:00:00 and Epiphany at 00:00:00.
yes!
im an expert at copy-paste....let me send you a screen shot
@lilac folio I converted your message into a file since it's above 15 lines :+1:
can someone please help with this?
what's the output of states('sensor.fajr_prayer')
2023-01-06T06:42:00+00:00
trigger:
- platform: time
at: sensor.fajr_prayer
you don't need a template
@floral steeple you have all day events
i'm not sure why it's selecting the events, i'll look at it
the second event shouldn't be showing up
oh, because I added 7 days
give me a moment
For sure, thanks petro
ok, got it
{% set t = now() %}
{% set ns = namespace(events=[])%}
{% set events = states.calendar | selectattr('attributes.start_time', 'defined') | sort(attribute='attributes.start_time') | list %}
{% for evt in events %}
{% set start = evt.attributes.start_time | as_datetime | as_local %}
{% set midnight = today_at() %}
{% set midnight_tomorrow = midnight + timedelta(days=1) %}
{% set end = evt.attributes.end_time | as_datetime | as_local %}
{% if start <= midnight and midnight_tomorrow <= end or (midnight < start < midnight_tomorrow or midnight < end < midnight_tomorrow)%}
{% set ns.events = ns.events + [evt.attributes.message ~" at "~ start.time()] %}
{% endif %}
{% endfor %}
{% set qty = ns.events | count %}
{% if qty != 0 %}
There {{ 'is an' if qty == 1 else 'are ' ~ qty }} event{{ '' if qty == 1 else 's' }} on the calendars for today. {{ ' and '.join((ns.events|join(', ')).rsplit(', ', 1)) }}.
{% else %}
There are no calendar events today.
{% endif %}
``` @floral steeple
and if you want it to be alittle better...
bam! that was it, what was the issue?
how would i print the friendly names of the heated rooms? This fails again because of the missing lowerattribute:
{{ states.climate | selectattr('attributes.hvac_action', 'ne', 'heating') | list | map('state_attr', 'friendly_name') | list }}
you weren't accounting for all day events and the logic was wrong for start and end
anyways, this might be more what you're looking for
{{ states.climate | selectattr('attributes.hvac_action', 'ne', 'heating') | map(attribute='attributes.friendly_name') | list }}
{% set t = now() %}
{% set ns = namespace(events=[])%}
{% set events = states.calendar | selectattr('attributes.start_time', 'defined') | sort(attribute='attributes.start_time') | list %}
{% for evt in events %}
{% set start = evt.attributes.start_time | as_datetime | as_local %}
{% set midnight = today_at() %}
{% set midnight_tomorrow = midnight + timedelta(days=1) %}
{% set end = evt.attributes.end_time | as_datetime | as_local %}
{% if start <= midnight and midnight_tomorrow <= end or ()%}
{% set ns.events = ns.events + [evt.attributes.message ~" all day"] %}
{% elif t < start < midnight_tomorrow %}
{% set ns.events = ns.events + [evt.attributes.message ~" starts at " ~ start.time() ] %}
{% elif t < end < midnight_tomorrow %}
{% set ns.events = ns.events + [evt.attributes.message ~" ends at " ~ end.time() ] %}
{% endif %}
{% endfor %}
{% set qty = ns.events | count %}
{% if qty != 0 %}
There {{ 'is an' if qty == 1 else 'are ' ~ qty }} event{{ '' if qty == 1 else 's' }} on the calendars for today. {{ ' and '.join((ns.events|join(', ')).rsplit(', ', 1)) }}.
{% else %}
There are no calendar events today.
{% endif %}
``` @floral steeple
made an edit
anyways, it tells you when it starts or ends or if it's an all day event, i.e. no start/end
@mighty ledge thank you! this more cleaner now!!
works!
so the answer always seems to be "add attributes." π
But why is attributes. omitted in this example:
{{ ['binary_sensor.garage_door', 'binary_sensor.front_door'] | map('state_attr', 'friendly_name') | list }} ?
those aren't state objects, they're entity ids
you can do that now π
try it
in 2022.11 I added the ability to use state_attr as a filter, which means you can use it in map
state_attr is a filter, and it allows you to use it in map. state_attr grabs the attribute from the entity_id
Ah, makes sense.
Iβm an idiot, ignore my last reply, I didnβt see the context and read your comment wrong
π all good, yeah it definitely does work if you pass it an entity id though, which is awesome
Hi, I've a question regarding to template sensors. As I see the attributes of the template binary sensor is restored whenever HA restarts or templates are reloaded if template triggers are used. Is this a feature or is it just a side effect of something and it will may be changed in the future (in that case I won't use it)? If it is a feature why is it not working with simple (not binary) sensors? Maybe a bug? (sorry if wrong channel)
Is this a trigger based template sensor, or a state based template sensor?
State based template sensors are reloaded when the state of any of the entities used in the template sensor changes.
For a trigger based template sensor you control when it's rendered, based on the trigger
I'm currently using a template to return a light group from a switch name: yaml {{ states.light | selectattr('object_id','search','^group_') | selectattr('object_id','search',trigger.event.data.device | slugify) | map(attribute='entity_id') | list }}
How can I use this same criteria to determine if the light group is on or off? ```yaml
action:
- if:
- condition: template
value_template: "{{ is_state('light.group_backporch','on')}}"````
- condition: template
do you expect that to return one entity or many entities in a list?
I'm creating a single light group per switch, so one entity
that seems overly complicated. Can't you just generate the name based on the trigger data, rather than searching for the entity?
if the switch is called switch.foo and the light group is light.group_foo, then you can just build that
I guess so - I could append 'light.group_' to the trigger.event.data.device
sweet. I"m trying to avoid having to set up an automation for each switch. Once this works, I can automate creating a light group for each switch, and then all I have to do is add the light entity in the future
you can't really "automate creating a light group" π€
you can automate transforming a switch entity_id into the entity ID for the light group, as above
but you'll be creating the actual light group manually
hmm
{{ is_state('light.group_' ~ trigger.event.data.device|slugify, 'on') }} doesnt seem to be pulling the device. If I substitute 'trigger.event.data.device' with 'officeceiling', the state returned is ['unavailable']
I was just copying what you had above, which you said worked
where are you testing it?
it won't work as-is in the template dev tool, if that's what you're trying to do
in the templates developer page. yaml {% if is_state('light.group_' ~ 'officeceiling'|slugify, 'on') -%} The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago. {%- else -%} The sun will rise at {{ as_timestamp(state_attr("sun.sun", "next_rising")) | timestamp_local }}. {%- endif %}
correct, which is why I changed the trigger to what the trigger should be returning
unless the tilde is a special operator
yes. [<template TemplateState(<state light.group_officeceiling=on; supported_color_modes=[<ColorMode.RGB: 'rgb'>, <ColorMode.WHITE: 'white'>], color_mode=white, brightness=255, entity_id=['light.office_bulb_1', 'light.office_bulb_2'], icon=mdi:lightbulb-group, friendly_name=Office Ceiling, supported_features=LightEntityFeature.TRANSITION|FLASH @ 2023-01-06T16:27:16.702616-06:00>)>]
you're not actually outputting the state anywhere in that expression, so I don't know what you mean by this:
the state returned is ['unavailable']
the test should have output The sun rose {{ relative_time(states.sun.sun.last_changed) }} ago.
oh hell.
fricking ADD>
I was not looking at the right section
ahh, there's an issue. The trigger is no longer device, but now device_id
target:
entity_id: '{{ ''light.'' ~ trigger.event.data.device ~ ''_indicator_light''|slugify }}'```
should be returning 'light.Office_Ceiling_Indicator_light'.
Instead I"m getting the error `Error: Template rendered invalid entity IDs: light.Office Ceilingindicator_light`
First, that's an invalid entity_id anyway. They can't have capital letters
shouldn't slugify fix that?
Second, |slugify is only applied to _indicator_light there
ahh, the three are evaluated separately
Yes
Hello, I have sensor: !include sensors.yaml in my configuration.yaml then have this in my sensors.yaml restarted but not showing the sensor - platform: template sensors: test_Heat: value_template: "{{ is_state_attr('climate.wiser_test', 'hvac_action', 'heating') }}" friendly_name: test Heating On
I guess it's the capital H in test_Heat:
You can't use uppercase characters in object_ids
And I would suggest to make this a binary_sensor instead of a sensor
I have this I use for my Garage door, and it works fine, but how do i add the state_color: true (or just yellow) when the door is open?
state_color: true is for the UI only, so it's added when you place it in your UI
Looks like a mushroom template card, you can use the icon_color setting and use a similar template
mdi:garage
state_color: yellow
{% else %}
mdi:garage-open
{% endif %}
icon_color: >
{% if state_attr('binary_sensor.garageport_vibration_sensor_vibration', 'angle_y') | int(0) > 9 %}
yellow
{% else %}
blue
{% endif %}
@thorny snow I converted your message into a file since it's above 15 lines :+1:
@thorny snow I converted your message into a file since it's above 15 lines :+1:
Hey all ! Is there a good place with detailed tutorials ? The docs seems a bit scare sometimes for very newcomers like me
I would like to read up one example and adapt to my needs
For example , i guess very famous, setting a custom binary sensor for home presence based on my own inputs
@thorny snow you can't reduce open/close tags. 1 open/close tag per line of code
I need to manipulate the entity_id's in this list:```
{% set list =
expand('switch.z_wave_switches')|map(attribute='entity_id')|list +
expand('switch.shelly_switches')|map(attribute='entity_id')|list %}in such a way that I change the domain from switch to sensor, and add a suffix '_device_energy'. I seem to run into a silly oversight, because I keep getting
UndefinedError: 'str object' has no attribute 'entity_id'```
what am I not seeing?
In a next step I need to add the resulting sensor.*_device_energy entities to a kWh number and feed that to the utility meter...
that would be a separate add using states.sensor
right, {% set list = expand('switch.z_wave_switches','switch.shelly_switches')|map(attribute='entity_id')|list %}... sorry for that
expand('switch.z_wave_switches','switch.shelly_switches')|map(attribute='entity_id')|list %}
{% for s in mylist %}
{{s.entity_id}}
{% endfor %}``` results in the same error.
cause you're mapping the entity_id...
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{{s.entity_id}}
{% endfor %}
you're changing it from a list of state objects to a list of entity_ids
np
{%- set ns = namespace(energy=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_device_energy' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}
{{ns.energy}}```
can I directly manipulate that with |selectattr('state','is_number') |map(attribute='state') |map('float')|sum|round(2)}} or would it be best to create a second template sensor on that list
this seems to work: {%- set ns = namespace(energy=[]) %} {% set mylist = expand('switch.z_wave_switches','switch.shelly_switches') %} {% for s in mylist %} {% set switch = s.entity_id.replace('switch','sensor') + '_device_energy' %} {%- set ns.energy = ns.energy + [switch] %} {% endfor %} {{expand(ns.energy)|selectattr('state','is_number')|map(attribute='state') |map('float')|sum|round(2)}} though I dont understand the outcome yet.... have to fiddle some more with the result π
checking that, and understanding now.... can we sort this based on state:```
{%- set ns = namespace(energy=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_daily' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}
{% for s in expand(ns.energy) %}
{{s.name}}: {{s.state}}
{% endfor %}```?
You need to build a dict, and convert the states to float in that dict, then sort it and then output the sorted result
Or easier, build a list of tuples
{% set ns = namespace(sort=[]) %}
{% for s in expand(ns.energy) %}
{% set ns.sort = ns.sort + [(s.name, s.state | float)] %}
{% endfor %}
{% set sorted = ns.sort | sort(attribute='1') | list %}
What's the syntax for 'not equal' when evaluating state? Templating noob trying to create a template that outputs a count of open garage doors. Since there's several cover states I need count any door that's not equal to 'closed' instead of any door that's 'open'.
I've avoided it by using rejectattr instead of selectattr and got it working, but not sure it's the best way to do it. Here's my code:
{{ states.cover | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'garage') | rejectattr('state', 'eq', 'closed') | list | count }}
also, not sure how to paste code in here lol
duh, nevermind. != is what I was looking for.
< idiot
not that easy...```
{% set ns = namespace(energy=[]) %}
{% set ns = namespace(sort=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_daily' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}
{% for e in expand(ns.energy) %}
{% set ns.sort = ns.sort + [(e.name, e.state | float)] %}
{% endfor %}
{% set sorted = ns.sort | sort(attribute='1') | list %}errors with
UndefinedError: 'jinja2.utils.Namespace object' has no attribute 'energy'```
@floral shuttle You replaced ns.energy with ns.sort
{% set ns = namespace(energy=[], sort=[]) %}
ah yes, keen eye.```
{% set ns = namespace(energy=[], sort=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_daily' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}
{% for e in expand(ns.energy) %}
{% set ns.sort = ns.sort + [(e.name, e.state | float)] %}
{% endfor %}
{% set sorted = ns.sort | sort(attribute='1', reverse = True) %}
{{sorted}}```
now works, (note the final |list isnt necessary)
only thing now I have a nested list, and I want to list these without all of that :
like before:
Create the output based from the list with tuples in another for loop
{% for i ns.sort %}
{{ i[0] }}: {{i[1] }}
{% endfor %}
beat me to that, was building the full template like```
{% set ns = namespace(energy=[], sort=[]) %}
{% set mylist =
expand('switch.z_wave_switches','switch.shelly_switches') %}
{% for s in mylist %}
{% set switch = s.entity_id.replace('switch','sensor') + '_daily' %}
{%- set ns.energy = ns.energy + [switch] %}
{% endfor %}
{% for e in expand(ns.energy) %}
{% set ns.sort = ns.sort + [(e.name, e.state | float)] %}
{% endfor %}
{% set sorted = ns.sort | sort(attribute='1', reverse = True) %}
{% for u in sorted %}
{{u.0}} - {{u.1}}
{% endfor %}``` but you;re using an index arent you?
just so I start off on the right foot - i want to make a sensor that is 'on' if the value of an entity is <0 and 'off' if the same entity is >0
Is it a template binary sensor that I want to write ?
yes
Why does this code evaluate as False?
{{ 'a' in ['abc'] }}
But this one returns true.
{{ 'a' in 'abc' }}
A list would normally have many elements and you would want to see if a string is in a list of strings, so it wouldn't make sense for it to do partial matches
Is there a way to match a substring in a list? Or will only exact matches of a string item in a list work?
{{ ['abc']|select('search', 'a']|length > 0 }}
Is there documentation on search/match? I was looking for some earlier but couldnt find any. Of a mention of the search or match test/filter in the Jinja docs listed in Dev tools.
In the second link in the channel topic
Thank you. Love how helpful everyone on the template channel is. @inner mesa
Hey everyone! Hope you all are having a good weekend? π
I am fiddling with an idea that requires me to use templates to process some values.
Problem 1:
I have this template:
{{ (state_attr('sensor.nordpool_kwh_bergen_nok_5_096_025','today' ))}}
that returns this list: https://hastebin.com/evimapigaz.json
I want to calculate the average of all these values... Any hints on how to proceed?
|average
Problem 2:
I want to store the averaged value somehow, as the average for today, each month... These are electricity prices...
So for today I want to store the average value and have it overwritten on the same date next month
Too easy....
Feel free to try stuff π
I was reading the docs and expecting to have to use mapping... So... π€·ββοΈ
Any idea on Problem 2?
12 input_number entities
Each set based on an automation with a time trigger set to trigger each month
Construct the entity name based on the current month name or number
So go directly to monthly averages, don't go via daily? I don't need daily.
Does the energy dashboard not do what you're trying to accomplish with energy prices?
That's a strategy
Not at all.... Every day I am thinking that the energy dashboard has a ton of unused potential... Don't get me wrong, I am super happy with what it does, but it could do more....
As for this "project".... Here in Norway, due to the insane prices of electricity, the government has introduced a refund based on usage and the average price per kWh for a given month. They refund 80% of the price above the average. But identifying (and estimating) what the average value will end up at is hard. I still havent found anywhere to get that value, except for when the invoice comes. It would be great to have an idea earlier in the month....
Since I have all the data needed to calculate this I thought that would be easy enough....
And maybe it is... I could publish the day average to an MQTT sensor for storage, and use an automation maybe to add the next day average to the already published value...
As I see this is fixed here: https://github.com/home-assistant/core/pull/69344#discussion_r853960624 but never merged. @peak vector do you know anything about that commit why wasn't it merged?
It was merged
Okay that strange I can't reproduce the problem with some simple sensors only with complex ones. I'll try to reproduce the problem with a simpler example.
If I create a simple template sensor which returns the current minute:
template:
- sensor:
- name: sensor1
state: >-
{{ now().minute }}
Then I create another template sensor which calculates one of it attributes from it (in my original complex template there were multiple triggers and I only want to update specific attributes and keep the other ones based on the trigger.id):
- trigger:
- platform: state
entity_id: sensor.sensor1
id: sensor1_change
sensor:
- name: my template sensor
state: >-
{{ 0 }}
attributes:
my_attr: >-
{% if trigger.id == 'sensor1_change' and trigger.to_state.state|float("unknown")|is_number %}
{{ states('sensor.sensor1') }}
{% else %}
{{ state_attr("sensor.my_template_sensor", "my_attr") }}
{% endif %}
Next I reload templates and my_attr refreshed every minute. After that I modify the code of my template sensor to see if it restores the state (attributes):
- trigger:
- platform: state
entity_id: sensor.sensor1
id: sensor1_change
sensor:
- name: my template sensor
state: >-
{{ 0 }}
attributes:
my_attr: >-
{{ state_attr("sensor.my_template_sensor", "my_attr") }}
and I reload templates. The value of my_attr will be null.
If I use binary_sensor instead of sensor, the attributes are restored fine.
I have this template sensor which should take two values and perform a quick a - b = c but is doesnt seem to work (anymore)
What have I broken or not updated correctly?
` - name: Flow & Return Differential
unit_of_measurement: "Β°C"
state: >
{% set flow = states('sensor.flow_temperature') | float %}
{% set return = states('sensor.return_temperature') | float %}
{{ (flow - return) | round(1, default=0) }}`
'Doesn't seem to work'
it did work - but no more
What does it don't?
it says entity not available on the dash - however I just removed it and re-added it and it now says "on"
but its a temperature sensor
Can someone nudge me the right way to have a template sensor be ON if the value of an entity is <0 or off if its >0
is it possibly this one https://www.home-assistant.io/integrations/template/#state-based-sensor-with-multiline-template-with-an-if-test
What if the value is 0? Is that possible for whatever value you're trying to check?
Hello everyone,
trying to use an input_text to supply both auto-entities and a template.
So I need to work with wildcards for auto-entities but how do I make this compatible with templates?
input_text e.g. "*ENERGY Power"
{{ ['-- - --'] + states.sensor|selectattr('name', 'search', states('input_text.text_wildcards'))|map(attribute='name')|list }}
returns error: nothing to repeat at position 0
If I remove the "*" it works for template but not auto-entities.
Ideally I need the wildcards to also work in the template because it might also be something like "Shelly* Power*1"
A binary sensor expects a template that returns true/false for on/off, so {{ states('sensor.sensorname') | float < 0 }}
- name: Free Electric state: > {% if sensor.octopus_energy_electricity_current_rate < 0 %} on {% else %} off {% endif %}
so i need to add in | float after _current_rate by the looks of it
It should be states('sensor.octopus_energy_electricity_current_rate')
The whole thing would be
state: "{{ states('sensor.octopus_energy_electricity_current_rate') | float < 0 }}"
There's no need for the if, on/off, etc. The binary sensor just expects the template to return true or false, which the line above does
okay , so if the condition isnt met to make it on, it will be off
If it's -1 for example, the template will return true, which will set the sensor to on
thank you
its working - thats my trigger to turn on the electric water heater (instead of gas) when my electric is free from the grid
Aren't we supposed to provide default values now for float and int? As in | float(0) < 0 or | int(0) <> 77?
For a long time, and where needed
hey all, I have this automation that checks if any windows, doors or gates are open when my security is armed and when we leave home, problem is, it does not tell my which one is open. It would be great if this would tell me that via the actions/TTS. Any suggestions? http://pastie.org/p/2ykeoR1spg0nsJYfma3IvK
A template like this will give you a list of covers that are open in a comma separated list:
{{ states | selectattr('domain', 'eq', 'cover') | selectattr('state', 'eq', 'open') | map(attribute='name') | join(',') }}
Better to start with states.cover
{{ states.cover | selectattr('state', 'eq', 'open') | map(attribute='name') | join(',') }}
Templates using states are throttled to update only once per minute
Templates using states.<domain> are throttled to update once per second
probably a silly question but, I have a rest sensor that returns a float, however the UI shows the history as 500 differently colored blocks instead of a line graph
how do I make it show a line?
I looked at device classes but theres no class tha tmatches
this is my template currently:
value_template: "{{ value_json.result.cics[0].flowRate | float(default=0) | round(2) }}"
@stone imp See https://community.home-assistant.io/t/how-to-get-sensor-that-will-graph/260223/6
You'll need to pick an existing device class/unit_of_measurement.
Good Morning,
I have a problem with a Number Template. My KNX Number entity has a factor 10 that means 160 -> 16A. That I want to correct for the interface with an template. But I don't know that to enter to the set_value parameter:
- number:
- name: "Carport.Wallbox1.Stromaufnahme.maximal Laden"
state: "{{ (states('sensor.carport_wallbox1_stromaufnahme_maximal_laden_temp')|float(0)) / 10 }}"
set_value: "{{ value * 10 }}"
step: 0.1
min: 0
max: 16
availability: >-
{{
[ states('sensor.carport_wallbox1_stromaufnahme_maximal_laden_temp'),
] | map('is_number') | min
}}
ah ty!
set_value expects a (list of) action(s) to be taken when the value of the number entity is changed
Thank you. That was the info I need. Now it is working:
set_value:
service: number.set_value
data:
value: "{{ value * 10 }}"
target:
entity_id: number.carport_wallbox1_stromaufnahme_maximal_laden_temp
Is there a way to get the state last updated of all items in a dictionary and select the most recent? Such as outputting doorbell if doorbell was the most recent last updated.
status_sensor:
outdoor_2: 'binary_sensor.outdoor_2_notification_status'
doorbell: 'binary_sensor.doorbell_notification_status'
If I have a string with time/date, and want to use it's time only with current date, would that be possible? I have been trying with this, but no success yet; ```
{% set debug_night = '2023-01-07 23:34:00+01:00' %}
{% set d = now().date() %}
{% set t = (debug_night | as_datetime).time() %}
{% set dt = ??? %}
{{ dt }}```
What I'd like to do is create a string with the two and then convert into datetime
At times like this a filter as_text or as_string would have been handy to build the string more easily
I would like to setup the utility meter helper to track my energy consumption. Unfortunately my electric meter is analog without the posibilty to read out the values in any other way then writing them on a paper.
My electric meter has two counters for day and night so two different values to feed into the utility meter. Now what i do not understand is the setup process of the utility meter helper.
As input source it wants one sensor. But only one. So how would I track two different numbers?
{% set debug_night = '2023-01-07 23:34:00+01:00' %}
{% set dt = as_datetime(debug_night).replace(year=now().year, month=now().month, day=now().day) %}
{{ dt }}
WoW. Thank you! I have spent a good amount of time trying, much appreciated!
This will also work
{% set debug_night = '2023-01-07 23:34:00+01:00' %}
{% set dt = today_at(as_datetime(debug_night).strftime ('%H:%M')) %}
{{ dt }}
Really cool, thanks a lot!
@floral steeple Add those entities to a group like house_perimeter and then start with this template:
{{ expand('group.house_perimeter') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
It will need more tweaking to get the friendly_name rather than entity_id.
@hoary surge
"my electric meter is analog without the possibility to read out the values in any other way then writing them on a paper.
(the) meter has two counters for day and night so two different values to feed into the utility meter"
So you intend to record those on a daily basis and input the numbers manually and consistently into HA via an input_number or ??
"As input source it wants one sensor. But only one. So how would I track two different numbers?"
On first thought I was thinking via tariffs, but that won't work as you do not have a single constantly increasing value to break into tariffed usage.
I think 2 meters will be needed, one for day and one for night.
replace entity_id with name for the (friendly) name
As i do not want to go every day to the meter i would prefer an irregular schedule like once or twice per month. I do not want to use the utility meter in the energy dashboard but have it as a posibility of tracking
@hoary surge I am visualizing two (very spikey) utility meters then. Also, the input has to be a sensor so I'm thinking a "templated sensor of an input_number"?
@marble jackal @floral steepleDoh! Thanks! Probably will want to strip single quotes and braces from the output.
My test group gives me ['Kitchen occupancy', 'Office occupancy'].
Maybe change the comma + space to space & space too!
@stone imp Google is my best friend!
use join(', ') instead of list
['Kitchen occupancy', 'Office occupancy'] this is a list, not a string
What is wrong with this trigger please? ```
- platform: template
id: "set_light_on"
value_template: "{{ (as_timestamp(now()) > as_timestamp(states('input_datetime.christmas_lights_on') | as_datetime)) }}"```
template evaluates to true in dev-tools so should fire, right?
@silent vector Is there a way to get the state last updated of all items in a dictionary and select the most recent?
Have a look here: https://community.home-assistant.io/t/template-help-needed-convert-dictionary-to-list-so-i-can-take-first-x-entries/242646
Is it already true? A trigger will trigger when it changes from false to true
and the as_timetamp is not needed
what do you mean with state last_updated. Only an entity itself has last_updated, not attributes
Oh. My intention with writing it as is was to make it trigger whenever true, so I should add "from/to" ? So only state changes then...
@marble jackal @floral steeple
Almost perfect...Kitchen occupancyOffice occupancy.
join(', ') = Kitchen occupancy, Office occupancy
Adjust the (...) to what you want.
No, it will trigger when the current time changes from before the time set in your input_datetime, to after
today it's already after, so it won't trigger anymore today, It will trigger again tomorrow
well probably not, as you have a datetime input_datetime
Ah, that's why I felt it was failing. I expected it to trigger as it was true... Thanks for clarifying
when should it stop triggering then?
a trigger is always a single moment
not a period of time
Well, it just needs to trigger once
it then sets helpers with timestamps for on/off used elsewhere in my scripts
So that is why it will trigger when it becomes true, not when it is already true
@marble jackal @silent vector what do you mean with state last_updated. Only an entity itself has last_updated, not attributes
I think he was referring to a dictionary list of entities. Although the link I posted is manipulating attributes of an entity, I think it's a good starting point to play with sorting a dictionary list of entities and selecting the [0] item. There might be more relevant posts for what he wants...
Thank you but I actually moved away from that I'll be doing something a little different and will probably be back tomorrow morning to figure it out. I'm trying to create a frigate notification automation so that 1 notification can be used among 2-3 cameras with priority. Meaning phones would receive 1 that gets overwritten with new notifications as needed rather than 2-3 separate notifications.
@sonic sand I converted your message into a file since it's above 15 lines :+1:
Does anybody know if this can be done?
Use the same wildcard input I am using for dashboard cards as input for my automations?
e.g. *ENERGY*Power
I am guessing it would need to be somehow separated into multiple searches? One search per * wildcard?
@tidal meteor I converted your message into a file since it's above 15 lines :+1:
@barren umbra I converted your message into a file since it's above 15 lines :+1:
Did I miss a breaking change?
My notification is no longer telling me which device triggered the alarm.
action:
- service: notify.mobile_app_sm_g975f
data:
message: "Alert: {{ trigger.to_state.friendly_name }} DEAD"
friendly_name has never been a property of the state object. Either use 'name' or 'attributes.friendly_name'
I'm trying to integrate the play time of a media player into the energy dashboard, to approximate power consumption. Would this solution work or am I doing something stupid?
@tired pebble I converted your message into a file since it's above 15 lines :+1:
Will it count towards the the consumption even if the value is static and doesn't change?
Currently i do not have the readings of power consumption, so i can't hard code the value
You can also use the custom integration powercalc
It allows you to provide power consumption based on the state of an entity
O was about to use that, but they said they support switches and this is a media entity. Moreover, powercalc configuration still has to be done through the configuration yaml, so if i didn't mess up the logic in the code above, it should work, right? Or i just missed something really obvious. Because what i wrote seems way too simple to be true
Can templated variables be multiline within a script?
action_on: "{{ 'Turn On_' ~ context.id }}"
action_off: "{{ 'Turn Off_' ~ context.id }}"
temp: {% if states('sensor.adelynn_temp_temperature') >= '71' %}
Too High
{% elif states('sensor.adelynn_temp_temperature') <= '64' %}
Too Low
{% else %}
Just Fine
{% endif %}```
Returns the error Message malformed: invalid template (TemplateSyntaxError: expected token 'end of print statement', got 'sensor') for dictionary value @ data['sequence'][0]['variables']['temp']
not like that
lucky for you, there's an entire site: https://yaml-multiline.info/
also, you're doing string comparisons when you want to compare numbers
the template as written produces a string output in dev tools.
π€·
this doesn't do what you want:
if states('sensor.adelynn_temp_temperature') >= '71'
{{ states('sensor.adelynn_temp_temperature') }} Result type: number 63.5
temp: >-
{% if states('sensor.adelynn_temp_temperature')|float >= 71 %}
Too High
{% elif states('sensor.adelynn_temp_temperature')|float <= 64 %}
Too Low
{% else %}
Just Fine
{% endif %}
all states are strings all the time
so by putting '71' i'm converting it to string?
that is a string, yes
This is fabulous. My step dad bitching on me for charging my phone or even turning on my PC for 10 mins that it costs a fortune. Meanwhile his speaker setup that is sitting idle 24/7 in the living room consumes 6,4W even when no sound is produced
well shit. Okay, your code, as expected, works. i tried to pipe the output to float previously but for whatever reason it wouldn't give the expected output
Ok, tv goes from 130-270W depending on how bright the scene is. I used constant 200W average. That shit consumes more power than my pc
I did that, but the entity doesn't appear on the energy dashboard settings as an option to add
It needed some time to sample the data
Hi, hopefully this is the correct section to ask. I am trying to write an automation that triggers when a sensor changes (or if i run it manually then hoping it can get the information from the last time it would have ran). The aim is to send a load of information as part of a notification. I'm trying to get information about the last time a sensor was a value but the documentation to get the state object for the sensor seems to return null.
Last print ended: {{states('binary_sensor.octoprint_printing').last_changed}}
Is what I currently have inside message: but nothing is coming through
that's not how to do that
Last print ended: {{ states.binary_sensor.octoprint_printing.last_changed }}
Ok, I saw that way of doing it in the docuentation, but there is a warning https://www.home-assistant.io/docs/configuration/templating/ here to use the method I was using
you're confused
you're not getting the state there, you're getting a property of the state object
well, you were getting the state, and then trying to get the last_changed property from that, which doesn't make sense
states.xxx.xxx.state is indeed discouraged in favor of states('xxx.xx'), but that's not what you needed
Thanks, that's got me going again
@barren umbra @marble jackal awesome! thanks, this works well after making the perimeter group sensor:
{{ expand('binary_sensor.house_perimeter') | selectattr('state', 'eq', 'on') | map(attribute='name') | join(', ') }}
here's my updated automation.
only minor issue is a grammar one...if its one entity it will say "is open" but if its 2 or more...it will also say "is open"...but should be "are open"....Oh I sometimes I think I need meds for my OCD π
You could solve it the easy way by rewording it e.g. "Please check the following: <list>", or the more complicated way which would be to run a count and then use that number to select "is" vs. "are"
Personally I'd just reword it because that's simpler
message: >-
{% set open = expand('binary_sensor.house_perimeter') | selectattr('state',
'eq', 'on') | map(attribute='name') | list %}
You {{trigger.id}}, but {{
open | join(', ') }} {{ 'are' if open | count > 1 else 'is' }} open.
I"ve got an automation that uses ```yaml
if:
- condition: template
value_template: >-
{{ is_state(('light.group_' ~ trigger.event.data.device | slugify), 'on')
}}to decide whether to turn another entity on or off. The strings combine to makeentities: - light.group_office_ceiling```
However, the statement is always evaluated as false, even though the entity is on
Thanks very much! @marble jackal this is exactly how I wanted it in the first place....btw, great to know you more on Smart Home Junkie's video the other day!
Is it possible to display the current HA version with a template?
https://www.home-assistant.io/integrations/version/
That will create a sensor with the version that you can use in a template
service: notify.1204longhunterln
data_template:
message: >
"{{ input_text.slackmessage }}"
target: "#home automation"
How do I fix this? when I try to run it, i get: Error running action Error rendering data template: UndefinedError: 'input_text' is undefined
when I take out input_text. it saves, & runs, but notifys ""
{{ states('input_text.slackmessage') }}
just so I am sure I have this in the correct part of my config , is this a template binary sensor?
`- name: Flow & Return Differential
unit_of_measurement: "Β°C"
state: >
{% set flow = states('sensor.flow_temperature') | float %}
{% set return = states('sensor.return_temperature') | float %}
{{ (flow - return) | round(1, default=0) }}`
template:
- binary_sensor:
- name: "Has Unavailable States"
state: "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"
The above example is a binary sensor, it returns true or false. Since you're trying to store Β°C, that'd just be a sensor
so i tried dropping that into my sensor block - and HA refused to restart - is the formatting correct for a sensor?
It looks like your indenting is wrong
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.
This is the new template sensor format which belongs under template: and not under sensor:
So
template:
- sensor:
- name: ...
its just restarting - i cant remember what i just changed it to - lets see what the restart brings me!
so how do i add the template binary sensors in too;
http://pastie.org/p/56jCj7ls639OpPodwSgHkE
Thats what ive got and its not restarting because of the first line
What is the error?
Logger: homeassistant.config
Source: config.py:974
First occurred: 20:36:31 (1 occurrences)
Last logged: 20:36:31
Invalid config for [template]: [name] is an invalid option for [template]. Check: template->name. (See /config/configuration.yaml, line 447).
447 is the first line of that link above
Youre missing sensor
And you arenβt listing it
template:
- binary_sensor:
- name: β¦
Is what you pasted not what's in the config?
I didnβt read what he has in his config, Iβm just reading the error
The error sees:
template:
name:
The paste syntax is right, which is why I'm confused what happened
Maybe an old error and he doesnβt realize it?
"aren't actually using what they're posting" is always a possibility
From 20:36. Maybe old yeah
Oh, yeah, I just copied that from a reddit post...
the paste is direct from the config
What you pasted looks correct, so it doesn't line up with the error
just checked the log again - and this one is probably more likely the issue !
like you didn't reload
The system cannot restart because the configuration is not valid: Invalid config for [mqtt]: [state] is an invalid option for [mqtt]. Check: mqtt->mqtt->sensor->7->state. (See /config/configuration.yaml, line 57).
it wont let me reload
"restart" you mean
anyway, that's a completely different error
that looks like you put mqtt: in a file that you included from mqtt:
line 57
mqtt:
the only place i have mqtt: is on line 57
mqtt->mqtt->
when I add "mqtt:" to my "mqtt.yaml" file that's included from configuration.yaml, I get the same kind of thing:
2023-01-08 13:09:56.659 ERROR (MainThread) [homeassistant.components.homeassistant] The system cannot check_config because the configuration is not valid: Invalid config for [mqtt]: [mqtt] is an invalid option for [mqtt]. Check: mqtt->mqtt->mqtt. (See /config/configuration.yaml, line 101).
that's why I said: #templates-archived message
im getting a bit lost here - should I not have mqtt: at the start of my mqtt entities (the same way I have always had it for about 6 years)?
or should it be changed to mqtt->mqtt-> ?
Morning all. I have a template sensor that I want to be based on a number value, however this code gives me an unavailible return
kitchen_filter_days_remaining is based on helpers that determines days left before filter needs to be changed
and works 100%
The name of the sensor in states() isn't valid. What kind of helper is it?
I have 2 helpers, one datetime helper that sets the date I install the new filter, the second helper is a number helper that states 90days before the next filter change. I then have a sensor coded in yaml that subtracts these to determine the days remaining
sensors:
kitchen_filter_days_remaining:
friendly_name: Kitchen Water Filter Days Remaining
unit_of_measurement: days
icon_template: 'mdi:calendar-clock'
value_template: >-
{%- set inst = as_timestamp(states('input_datetime.kitchen_water_filter_installed')) -%}
{%- set dif = states('input_number.kitchen_filter_lifespan') | int * 86400 -%}
{%- set nt = as_timestamp(states('sensor.date')) -%}
{{ (((inst + dif) - nt) / 86400) | round(0) }}```
states('sensor.kitchen_filter_days_remaining')
You're also using the old format of template sensor
You can see the new format here
https://www.home-assistant.io/integrations/template/#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors
awesome thank you. I have quite a few that I will rework
Not urgent or anything, but best to follow the new format
I would love to know why this keeps being zero, (i'm new to templating)
{% set wv = 0 %}
{% for entity_id in states.group.thermostats.attributes.entity_id %}
{% if state_attr(entity_id, 'current_temperature') <= state_attr(entity_id, 'temperature') %}
{% set wv = wv + 10 %}
{% else %}
{% set wv = wv - 10 %}
{% endif%}
{% endfor %}
{{ wv }}
I see that HA enters the if statement
But wv is 0 the initial value at the end
because you need to use a namespace if you want to modify a variable in a loop and them use it outside the loop
{% set ns = namespace(wv=0) %}
thanks
then reference it as ns.wv
Thanks, yes that works
Would this be the place to ask about formatting a mqtt message in esphome? Trying to get values from mqtt into a variable for an nspanel but end up with values like \x8c\x85\xfe?.
Is templating the moon sensor broken for anyone else?
{{ states('sensor.moon') }}
Is outputting the enum string key instead of the value for me (waning_gibbous instead of "Waning Gibbous").
(This is the latest release, 2023.1.1)
Hmm. I get unknown
Well you'd need the moon integration enabled π
waning_gibbous with{{ states('sensor.moon_phase') }}
It's enabled, same here, mushroom chip doesnt display properly
Well at least I'm not alone!
Hello, I hope everyone is having a wondering day. I couldn't figure out if it's possible or how to do it, but for an automation with multiple triggers is there a way to see in with template code to see which trigger set off the automation? Thanks!
Yes, you have to set a trigger ID on the triggers, then you can use trigger ID as a condition
ahhh ok.
Thank you!
I'm getting the hang of templating and its amaaaaaaaaaaaazing!
You can also access the trigger data which has the entity_id, from_state, to_state, and some other things, but I can't find the doc on that at the moment. You can see the data in it via Traces though on the "Changed Variables" tab under trigger:
What I was looking for was {{ trigger.to_state.name }}
it doesn't do anything in the template development window but when putting it an action of the automation it tells you the name of the trigger that set off the automation.
Trying to pull a different device from an automation trigger: yaml service: light.toggle target: entity_id: >- {{ states.light | selectattr('entity_id','search','group_') | selectattr('entity_id','search',trigger.event.data.device | slugify) | map(attribute='entity_id') | list }}
In the template editor, if I replace 'trigger.event.data.device' with 'diningroom', the correct entity (light.group_diningroom) is returned. However, the automation trace says "TypeError: decoding to str: need a bytes-like object"
I'll bet that trigger.event.data.device is None or something like that
id: '0'
idx: '0'
alias: null
platform: event
event:
event_type: esphome.single
data:
device_id: diningroom
action: single_press
origin: LOCAL
time_fired: '2023-01-09T05:03:12.677551+00:00'
context:
id: 01GPAEJG95GM4W85DN53P3STZ2
parent_id: null
user_id: null
description: event 'esphome.single'```
ahh, shit
I did it again. 'device_id'
Hi,
https://ui-lovelace-minimalist.github.io/UI/usage/cards/card_room/#usage
Is the 'card_room.yaml' at the middle of the page template to the custom:card_room or a dashboard?
I want to add this card to my dashboard and getting some errors.
It's a copy of the card YAML from the dashboard
So if you want to paste it into the card YAML box, remove the - on the first line and outdent the whole template.
(I usually cheat by replacing the - with a space and then select the whole lot and shift tab)
I am struggling with that.. do you go on your dashboard to Raw Configuration or in the New View you do YAML edit mode?
Well for the cheat I mentioned, I do it in the card view YAML mode
Oh card view, I thought we were talking about Dashboard view
Do you create manual card and then edit or doesn't matter which card type?
@sonic sand I converted your message into a file since it's above 15 lines :+1:
It wouldn't matter which card type as you'd replace the whole YAML
I tried a manual card and got an error.
Sent you above if you don't mind help me
I'm on mobile so can't read the text files
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.
Getting the error that on the first line
My question is, How can I get that template (card_room) ? I assume I don't have the 2nd one too (red_no_state)
If you didn't install the card first then that would be your problem
I have Room Card installed already in HACS Frontend section
And you cleared your cache?
I did.
I'll have to look at the pastie later or maybe someone else can help, I've just spotted my missing electrician show up.
Thank you for helping tho'!
@sonic sand
I had a quick look...
Review the Configuration Templates section https://github.com/custom-cards/button-card#configuration-templates on github custom-cards / button-card.
Define your config template in the main Lovelace configuration and then use it in your button-card.
Those two templates need to be defined/added to the main Lovelace configuration outside the cards.
How you add that depends on which type of Lovelace dashboard you are using: managed or yaml which is mentioned in the section I linked to.
I believe that code is from https://ui-lovelace-minimalist.github.io/UI/usage/cards/card_room/ ?
At the bottom there is Template Code
Expand that and then add that yaml to your Lovelace via Raw Configuration Editor for your dashboard (managed) or ui-lovelace.yaml (yaml mode)
getting back to this, which is working fine as it is, showing me the ordered list in a Markdown, I had hoped to only show values that are > 0. so I entered that in the dev tools like: Per Switch: {%- for e in expand(ns.energy) %} {%- set ns.sort = ns.sort + [(e.name.split(': daily')[0], e.state | float)] %} {%- endfor %} {% set sorted = ns.sort | sort(attribute='1', reverse = True) %} {% for i in sorted if i[1] %} /* typing here */ {{- i[0]}}: {{i[1]}} {% endfor %}
and noticed I hadnt even added >0 after that, and it already filters the correct list π How does that work??
why dont I need {% for i in sorted if i[1] > 0 %}
@floral shuttle becasue 0 is considered false
so it's removed by if[1]]
{{ 'hi' if none else 'bye' }} # bye
{{ 'hi' if 0 else 'bye' }} # bye
{{ 'hi' if false else 'bye' }} # bye
{{ 'hi' if 'foo' else 'bye' }} # hi
{{ 'hi' if 1 else 'bye' }} # hi
{{ 'hi' if true else 'bye' }} # hi
Useful tips to save keystrokes!
right.... even if that would be 0.0 apparently
0.0 == 0
it can also work against you
{{ state_attr('media_player.whatever', 'volume_level') | default('not available', true) }} will also display not available when the volume is set to 0
I looked through the Jinja docs but could not find the correct filter.
Could someone help me split a string into parts based on a separator?
E.g. for every * create a new string?
*Energy*Power would result in Energy and Power
It would probably need to be an array, but I am not sure since I need to then filter the friendly name for each of the strings (that I can do, if I know how to get the partial strings π )
"this*is*a*string".split("*")
result: ["this", "is", "a", "string"]
Hi man thanks for that, I have added the template on the top part of the Raw Configuration Editor (above views:) and restarted HA, and empty the cache.
I still get the same error.
{{ "*Energy*Power".split("*") }} will result in ['', 'Energy', 'Power']
so you might want to use
{{ "*Energy*Power".split("*") | select() | list }}
(which will also filter out 0, false, none, but you will never have those when splitting a string)
That's what I feared also. Would probably need to perform a test if key is length >=1, correct?
Ah, perfect. I would have thought that would be more complicsted π
yes, it feels a bit hacky (didnt expect those 0.0 's to be numbers anyways so was preparing floating that and adding > 0.0), so I will keep the comparison in the template to be clear on what is happening without the deeper logic on the hi/bi
Does select only allow strings of length >=1?
Because the docs make it seem like I need to enter a filter criteria
no, the select() does the filtering
it filters out everything which is falsely (as also discussed above) It selects anything with is not considered falsely
empty strings/lists/dicts are also considered falsely
{{ 'hi' if '' else 'bye' }} # bye
{{ 'hi' if [] else 'bye' }} # bye
{{ 'hi' if {} else 'bye' }} # bye
they were converted to numbers to allow the sorting
Okay. Just wondering because true or false would be relative to the criteria. So I would have thought that empty would be ...
scratch that, you just clarified π
I will test and hopefully be able to use the list as search criteria.
Hey
is there a way to get the appointment name from a calendar entity? By default, you only get a feedback "on" and "off" whether an appointment is running or not.
same question on Spotify: can you show the song title instead of "running" and "paused"?
How would I get the most recent and oldest last updated if I had 3 last_updated attributes to compare? With 2 it's easier I just compare one against another but I'm not sure of a clean way to compare 3.
http://pastie.org/p/4X7hQvQqZRUUSNN3d1JJBD
I need help with the room card, I got the template on the Raw Configuration set up and still receiving this error (which is in the pastie on the first line).
Trying to create a card like that -
https://ui-lovelace-minimalist.github.io/UI/usage/cards/card_room/#usage
I'm trying to duplicate this. At first, the red_no_color template was missing. I found the code for that and now my addition in raw configuration editor is:
Sweet, but if it's missing why is it saying that room_card is missing at the first place?
@barren umbra I converted your message into a file since it's above 15 lines :+1:
is it the full code? because it ends with
state:
No, it's truncated...
ok let me try to add it, does it matter if it's on top of the room_card template on the raw config or no matter where
Okay, I placed it on top of everything, now getting another error:
button-card template 'ulm_translation_engine' is missing!
Ok, good, that's where I'm at too...
β ui_lovelace_minimalist find . -exec grep -l 'ulm_translation_engine:' {} ;
./lovelace/translations/default.yaml
β ui_lovelace_minimalist
Where should I place those 3 lines?
That's the output from me searching for the code!
It's in default.yaml (293 lines)...
if it's in default shouldn't it be automatically inserted into ANY template I have?
can't find anything online about this engine, weird isn't it?
No. UI Lovelace Minimalist expects you to be in yaml mode, not UI mode.
See https://ui-lovelace-minimalist.github.io/UI/setup/configuration/
I'm pretty sure this is a #frontend-archived discussion.
How come? It's a problem with the template I got.
Yes, you are correct, sorry!
@sonic sand Time to move the discussion...
Yes but it's a problem in the frontend not template sensors, automation templates, triggers etc.
It's not an HA templates issue, it's lovelace
Hope this is a template case
Thanks, will move!
Nope, it's frontend/lovelace
Oh ill fix
they are in the attributes of the calendar entity and media_player entity, so yes, you can get those
I'm sure there are more elegant variants, but this might get you started with Spotify:
{% set artist = state_attr("media_player.spotify_youraccount", "media_artist") %}
{% set song = state_attr("media_player.spotify_youraccount", "media_title") %}
{% set delimiter = 'by' %}
{% if song == 'unknown' %}
{% set song = '' %}
{% set delimiter = '' %}
{% endif %}
{% if artist == 'unknown' %}
{% set artist = '' %}
{% set delimiter = '' %}
{% endif %}
{{ song }} {{ delimiter }} {{ artist }}```
Is it possible to get a range of sensor values for a given time period in a template. I.e I have a start and end time, based on a binary sensor going On then Off, I want to get the average value of a different sensor during the time the sensor was on, so far I can only find the current value of the sensor, not its history. I have seen the sensor option which seems to let you average, but that seems to expect the amount of time to average over in advance, and the binary sensor I want to monitor can vary wildly (between 3 and 30 hours).
you can only get that information from the min/max integration
i.e. not templates
templates can't look at history
How would I get the most recent and oldest last updated if I had 3 last_updated attributes to compare? With 2 it's easier I just compare one against another but I'm not sure of a clean way to compare 3.
Also is there a variable for when a service was executed or can that be set? I can see it in trace but is that something a template can read?
Thanks, Ill have to find a different way to try to get what I need then
do you want to use it in that particular template sensor?
{{ this.attributes.items() | selectattr('1.last_updated', 'defined') | sort(attribute='1.last_updated') | map(attribute='0') | first }}
{{ this.attributes.items() | selectattr('1.last_updated', 'defined') | sort(attribute='1.last_updated', reverse=true) | map(attribute='0') | first }}
Trying to create a generic- room card, how can i make this select entities of device_class "humidity" ?
{{ expand(area_entities(area_id(entity))) | selectattr('humidity') }}
The above code yields "<generator object select_or_reject at 0x7f754a36f0>" ... (invalid result ...)
as soon as you start filtering, you'll get a selector
you need to add join or list or first or whatever to convert it to something meaningful
but anyway, you also need to adjust your filters
Yes I would use it in the template sensor.
Was that for me? adding | first or | list makes it invalid, I'm not even sure if its allowed to selectattr('humidity')
{{ expand(area_entities(area_id(entity))) | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', 'eq', 'humidity') | map('attribute='state') | map('float') | list }}
yes, that was for you, and what you did is indeed not allowed
try what I posted above, it will create a list of all states (converted to float) of the sensors
it's probably shorter to use the new filters
yep
{{ expand(area_entities(area_id(entity))) | selectattr('entity_id', 'is_state_attr', 'device_class', 'humidity') | map('attribute='state') | map('float') | list }}
{{ area_entities(area_id(entity)) | select('is_state_attr', 'device_class', 'humidity') | map('states') | map('float') | list }}
Is there a variable for when a service was executed or can that be set? I can see it in trace but is that something that available for a template?
thanks a ton both of you!
@marble jackal it's a pain to remember that we can use those after using selectattr for so long
you'll end up with a list, I don't know if you have any room with multiply humidity sensors
yeah, and I was racing to be faster than you, but forgot that there is no need to expand them with the new filters
π
while you're at it, is it possible to do arithmetic in the oneliner of the list? e.g take the avg of the values?
you can, but it will give an error on an empty list
{% set hum = area_entities(area_id(entity)) | select('is_state_attr', 'device_class', 'humidity') | map('states') | map('float') | list %}
{{ hum | average if hum else 'no data' }}
since when did Discord change the colors in the code BTW
you can do this to counter it
(hum or [0]) | average
but it'll be 0 as a result
or is powerful with empty items, use it!
I always forget about or (besides for usage in if statements)
yeah, its nice to have some fallback value, cheers!
sometimes it's just easier to use or than to sit there writing 893487392478328 lines of if else code
hehe
How can i set a text with variable value? i have my calendar, now i want an entity with the current Appointment name, how can i write this automatically in a text helper?
i mean, i need the syntax to extract the state of a string variable
and after that, how i can extract different attributes from the entity
create a template?
I have this from my calendar: "{{state_attr('calendar.bosstomming', 'description')}} i morgen!"
where description = Calendar entry
@mighty ledge I remember I first saw you could use or that way, and I asked if it would use the other if the first was falsely, and you made a very long post with examples
Which I said I would dig into, but never did, and when I wanted to check it, I couldn't find it anymore
How can I pull this into a variable?
Executed: January 9, 2023 at 8:00:36 AM
{% set variable = "Executed: January 9, 2023 at 8:00:36 AM" %} π But that is probably not what you mean here
Lol nope
I want to get the service execution time
I'm not sure if it's available or if it needs to be set right after the service is executed. Which would be off by a few seconds or something but better than nothing.
i know how to use numerical variables in notifications and other text realated things(f.e {{states("sensor.temperature_sensor_battery_sensor")}} ) but i dont know how's the syntax for string
if someone just scrolls past and uses this, add a "-" in the beginning after {% -> {%-
where do you get the string variable from? the "Executed: ..." ?
its from the calendar entity
please expand on your question here
are you referring to 'states', and 'float'? in the map?
and the goal is, that i can extract the name of the appointment and send it to me via telegram bot
This is from trace. I want to know the execution time of a specific service. I'm not sure if it's possible to retrieve or I need to do a workaround by setting a timestamp in a following service.
