#templates-archived
1 messages ยท Page 15 of 1
cheers
so is https://github.com/thomasloven/lovelace-auto-entities something that is common use or is there support in a recent release? Don't want to go making things messy on the first day
but having a dynamic control center dashboard seems like something that would be doable
it's a custom card that fills another card with entities based on the criteria that you specify
and no, there's no "official" alternative
gotcha
clever workaround
ok so I'll throw that in and then I'll start banging my head again ๐
@inner mesa Is HACS recommended if I run HA in a container?
yeah ignore, see no point not to
yes. installation method doesn't matter
@inner mesa I tried to direct message you but couldn't. Just wanted to tell you that you've helped me on more than one occasion and you make a big difference in this community. Thanks again.
glad to be of service
Yes but I cannot find anything wrong in the code. HA does not give any error. It simply does not read the files at all.
This works:
utility_meter: !include utility_meter.yaml
This does not work:
utility_meter: !include_dir_merge_list utility_meters/
with the same file under that folder
I do not think that it should be
utility_meter: !include_dir_merge_name
(but have tried that to)
it's "named", not "name", but I don't do what you're doing and can't offer much more guidance
but I continue to contend that it's not expecting a list, and you shouldn't use directives that provide one
is this the chat channel to ask about sensor states?
oops i see energy i'll go there
thanks
Ok now it worked with "named" thx!
Is it possible to get a newline in a template to render in a dashboard? It shows up within the Template tester, but that's likely just because the output is in a pre block.
What does your whole template look like in the YAML?
Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.
As an example, https://pastebin.com/iVaE4iHh
Pastebin is not loading for me, and it can insert some arbitrary spacing too.
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.
Just make sure you share the full YAML of your template sensor.
That's the template... if you need the name... https://dpaste.org/UmJnL/slim
I needed the whole template, as I can see that's using state: > not state: >- which eliminates one reason why it would be removing line breaks
So both Doors and Locks are appearing on the same line?
Correct
I mean, I can think of a way around it, but I suspect that something is being overeager with the -%} tags.
Just stripped all of the -s out so there's a truckload of newlines... but they don't show up on an entity card
I think it's actually that line breaks in template sensor output are removed
What would you like to do with multiple lines long term?
Just find that formatting to be nicer instead of it being a runon string
So you want a nice list in say a frontend card?
Yup
You may want to try using templates to create groups instead, or putting the template in the markdown card
Gotcha, it does appear to render in a Markdown card. Don't think there's an Android widget for that though, could probably write the template out directly there instead possibly
Yeah I can give that a shot, thanks for the ideas
#android-archived may have suggestions too
Heh actually just using the Template widget and echoing out the template sensor brings back the line breaks
Perfect
I have a couple of timers related to my wake-up schedule / time, i want to show the next active timer on my dashboard.
I have created a template sensor
https://hastebin.com/ijisazavoj.coffeescript
If i try the code segment in the Developer tools / template i see the info i was expecting, but the sensor created by the template reports 'unavailable'
https://hastebin.com/kosalideve.php
What am i doing wrong ?
what you described doesn't really match that code
I see a few things -
- The namespace seems to be unused
- If any of the timers are active, it always picks the first one in your list of timers (not the next one, or not even an active one)
- You're returning a state object if any timers are active, as shown in the template dev tool, which probably isn't a valid state
Does anyone know how i can change the icon of the following? And how to show this state only when its before 0800 ?
โป๏ธ GFT is vandaag!
{% endif %}```
Can someone help me with an MQTT select command_template?
I have options like this: options:
- "0 - Schutzbetrieb" - "1 - Automatik" - "2 - Reduziert" - "3 - Komfort"
And I would like to get the value from the beginning to be used in the command_template.
I tried this {{this.state.split(' ')[0]}}, but it doesn't give the right result. It always revert to the current state of the select, not the new one.
How can we replace a substring in template conditions.
This is not working:-
{% set state = states('sensor.pantry_items') %}{{ state | states('sensor.pantry_items').replace("1: Canned Tomato", "") }}
You can either do {{ state | replace("1: Canned Tomato", "") }} or {{ state.replace("1: Canned Tomato", "") }}, but using the string result as a filter will not work
Not entirely clear on the result you're looking to get from that list, what are you looking to retrieve
Is it possible to make a icon a template like: {{ mdi:light }}
are you going to use a variable there? I think depending where you use it, you could output an icon
icon: >
{% if is_state("sensor.dar_today", 'gft') and now() < today_at("08:00") %}
mdi:recycle
{% else %}
mdi:calendar
{% endif %}
state: >
{% if is_state("sensor.dar_today", 'gft') and now() < today_at("08:00") %}
โป๏ธ GFT is vandaag!
{% endif %}
How can I make a last seen status out of {{states.binary_sensor.voron.last_updated}}
This one returns state as 2022-11-08 12:46:22.612422+00:00
You can make a simple template sensor with that, if you want to format the date and time: https://www.home-assistant.io/docs/configuration/templating/#time
And you can use a device_class of timestamp: https://developers.home-assistant.io/docs/core/entity/sensor?_highlight=device&_highlight=class#available-device-classes
(Though make sure not to format it if you set the device class, instead filter it as a timestamp)
So you'll probably want:
template:
- sensor:
- name: "Voron Last Updated"
unique_id: "voron_last_updated"
device_class: "timestamp"
state: >
{{ states.binary_sensor.voron.last_updated | as_timestamp }}
Or similar
Thank you so much.
But I am still confused how do I convert it to last see.
as {{ states.binary_sensor.voron.last_updated | as_timestamp }} returns 1667912032.622624
Yes, but by setting the device class of timestamp HA automatically interprets that correctly so when you add the template sensor you will see the date and time
a timestamp is in this case a unix timestamp, seconds since January 1st 1970
I am starting to understand
So if i want to make it to be time elapsed from last change I should do smth like now() - sensor.voron_last_updated? ?
You'll need to parse the last_updated into a datetime for that
Oh wait, that's your new sensor
If you just want time since it last updated, you could put that in the original template sensor. But if you just want to display it in the frontend, I'd put it in a Markdown card ๐
I want to use it in frontend in uptime-card
Thx very much for the time! Icon doesnt work within template ๐
cards:
- type: custom:mushroom-title-card
title: |2-
{%- if now().hour < 12 -%}Goedemorgen
{%- elif now().hour < 18 -%}Goedemiddag
{%- else -%}Goedeavond{%- endif -%}, {{user}}
subtitle: |-
{% if is_state("sensor.dar_today", 'gft') %}
โป๏ธ GFT is vandaag!
{% endif %}
๐ก {{ states.light
| rejectattr('attributes.entity_id', 'defined')
| selectattr('state', 'eq', 'on')
| list | count }} Lampen aan```
This is the card i use
But the uptime card just wants to to use sensor.voron from what I can see?
i want to change the GFT icon and light icon if possible
Both are emojis :p
Also like to use a plex emoticon
I want to use it as a title template
so title will show las time elapsed since last change
Well emojis aren't valid icons, which is why I used the mdi:recycle and so on ๐
template:
- sensor:
- name: "Voron Last Updated"
unique_id: "voron_last_updated"
state: >
{{ states.binary_sensor.voron.last_updated | as_datetime | relative_time }}
Yea i understand :p But when this doesnt work for me.. I might be doing something wrong
You're using a custom card I'm not familiar with rather than a template sensor
You should check the docs for the card to see what it says about icons, as you didn't actually define the icon
Based on the readme I found (https://github.com/piitaya/lovelace-mushroom/blob/main/docs/cards/title.md), you just define the title and the subtitle. There is no iconโexcept perhaps from an entity_id
If it is from an entity, you will need to customise the entity, and that's where the template:
icon: >
{% if is_state("sensor.dar_today", 'gft') and now() < today_at("08:00") %}
mdi:recycle
{% else %}
mdi:calendar
{% endif %}
Would come in
this one give me error in logs
TemplateError('TypeError: float() argument must be a string or a real number, not 'datetime.datetime'') while processing template 'Template("{{ states.binary_sensor.voron.last_updated | as_datetime | relative_time }}")' for attribute '_attr_native_value' in entity 'sensor.voron_last_updated'
Then you can remove | as_datetime, I forgot that's a valid date time
Thx for your help ๐ Is there any good practice to get gut at state attributes / templates?
Read the templating and the template docs, and use the search in this channel (you can add in:templates to any search to filter to the templates channel) to see what you find.
Most important of all though is to use states('domain.entity_id), along with state_attr(), is_state() and is_state_attr() whenever you can instead of states.domain.entity_id... (the exception being last_changed)
This is not working.
It is not replacing the substring.
Currently I am using the condition as:-
{% set state = states('sensor.pantry_items') %}{{ state.replace("Canned Tomato", "") }}
And state is:-
"state": "[Canned Tomato, Paper Towels, Tomato Sauce, Ketchup, Mayo, Sugar]",'
@prime kindle I converted your message into a file since it's above 15 lines :+1:
A wait_template is expecting an expression that returns true or false, not a list
Is there any solution for that, so that I can achieve replacing the substring?
but it doesn't make sense in that template
are you just trying to remove an item from a list?
That list will be in string format...so I am trying to remove the substring from a string
that's pretty weird
{{ "[Canned Tomato, Paper Towels, Tomato Sauce, Ketchup, Mayo, Sugar]"|replace('Canned Tomato, ', '') }} works fine for me
it looks like some broken, malformed JSON. Anyway, this also works:
{% set data = {"state": "[Canned Tomato, Paper Towels, Tomato Sauce, Ketchup, Mayo, Sugar]"} %} {{ data.state|replace('Canned Tomato, ', '') }}
Need to change the sensor state directly as anything can come inside the sensor state...
Based on MQTT msg payload, I have to remove a particular substring.
if you're getting that via MQTT, it's probably proper JSON there and is being turned into a mangled string when you make it the state of a sensor
it feels like you're approaching this in the wrong way
when it comes in via MQTT, make it an attribute and treat it as the JSON object & list that they are
In MQTT msg only a number will come and based on that number we have to remove a particular substring from the state of the sensor
ok, so I've shown you how to do that
@real sand I converted your message into a file since it's above 15 lines :+1:
I restarted my server and my template sensor is showing as "unknown"
- platform: time
at: "05:00:00"
id: 5am
- platform: state
entity_id: sensor.outside_home_temperature
sensor:
- name: "Outside Min Temp"
unique_id: outside_min_temp
availability: "{{ states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number }}"
unit_of_measurement: "ยฐC"
device_class: temperature
state: "{{ iif (trigger.id == '5am' or states('sensor.outside_home_feels_like_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_feels_like_temperature'), states('sensor.outside_min_temp')) }}"```
sensor.outside_home_temperature = 26.2
sensor.outside_home_feels_like_temperature = 25.9
and is there a way of if its showing up as unknown it just shows up as "-"
Can we write any condition in 'template condition' of the automation by which we can replace the state of a sensor?
You can not replace the state of a sensor in a condition. A condition is a check on a current state, it will not change anything.
Is there any other way by which I can replace the state of the sensor?
??
That really depends on the integration which created the sensor, there could be a service call provided by the integration to amend the values in the sensor
@flint wing I converted your message into a file since it's above 15 lines :+1:
After your advice to dive into the new syntax, I gave it a try and tried to convert my legacy format code.
Here is the previous code with legacy syntax:
sensor:
- platform: template
sensors:
duree_ecoulement_eau_principale:
friendly_name: Durรฉe d'รฉcoulement de l'eau principale
unit_of_measurement: "sec"
value_template: >
{% set t = this.state if states('input_boolean.eau_principale_on_off') == 'off' else now().timestamp() - states.input_boolean.eau_principale_on_off.last_changed.timestamp() %}
{{ t | round(2, 'common') }}
And here is the update code with new format?
template:
- sensor:
- name: Durรฉe d'รฉcoulement de l'eau principale TEST
unit_of_measurement: "sec"
state: >
{% set t = this.state if states('input_boolean.eau_principale_on_off') == 'off' else now().timestamp() - states.input_boolean.eau_principale_on_off.last_changed.timestamp() %}
{{ t | round(2, 'common') }}
Does it seems legit?
Yes. But a config check can tell you the same ๐
- HAOS
ha core check - Container uses
dockercommands - Core requires you to activate the venv first
anyone able to help me out with the above :)?
what does that show you in the Template Editor in Dev Tools?
UndefinedError: 'trigger' is undefined
That's probably your problem, your template runs in error when then second trigger triggers
As it has no trigger id
Oh no, wait that can't be it, it has an id by default, 1 in this case
Does anyone know if it's possible to add icons to templates? Right now I have this template, and I would love to change "Date:" with an icon..
{% set input = as_datetime(states('input_datetime.helper_dato_for_hjemmekontor')) %}
{% if now().date() < input.date() %}
Date: {{ input.strftime('%d %B') }}
{% endif %}
If I just add the mdi:someicon it will just show that text instead of an actual icon...
You can't directly, I believe there is some way to use mdi icons in strings, but it is easier to use emoji
You need to set the icon of the entity, but you can't do it in the same template as the state
How can I write 2 conditions back to back here, the following code is not working:-
service: mqtt.publish
data:
ย topic: pantry_items
ย payload_template: >-
ย ย {{ states("sensor.pantry_items") |
ย ย regex_replace(find="Canned Tomatoes,", replace="", ignorecase=False) }}
ย ย {{ states("sensor.pantry_items") |
ย ย regex_replace(find=states("sensor.pantry_items"), replace=states("sensor.pantry_items")+" Canned Tomatoes, ", ignorecase=False) }}
Weren't you asking about this yesterday? And is pantry_items an array or a malformed JSON string?
I have a whitelist of mac addresses stored in an attribute of a template sensor like this: ['11:11:11:11:11:11', '22:22:22:22:22:22', '33:33:33:33:33:33']. I then have an automation with a condition checking if a mac is in this whitelist. {% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %} {{ trigger.event.data.mac.upper() not in allowlist }}
Question is if I can structure the whitelist like so ['nameOfDevice1', 'mac1, 'nameOfDevice2', 'mac2' ...] and still check condition against the whitelist somehow. I need it so I can easier see what MAC address belongs to what device.
When I think of it, for this purpose I guess I can just make the whitelist exactly like that and it would still work. The condition would check against 'nameOfDevice1' which is not a valid mac address and just move on. But that's a bit silly.
Is there a different way I should store the list in order to keep both device name and mac together?
store the attribute...
[ {'name': 'nameOfDevice1', 'mac':'11:11:11:11:11:11'}, {'name': 'nameOfDevice2', 'mac':'11:11:11:11:11:11'} ]
Then
{% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %}
{% set name = allowlist | selectattr('mac', 'eq', trigger.event.data.mac.upper()) | map(attribute='name') | list | first | default %}
{{ name is not none }}
Nice! Perhaps a silly question but would it also be possible to skip the identificator like this [ { 'nameOfDevice1':'11:11:11:11:11:11'}, {'nameOfDevice2': '11:11:11:11:11:12'} ] and then somehow get just the mac by using something like trigger.event.data.mac.upper().[1]? If you understand what I mean... ๐
I mean like asking for the second part of each 'pair' ๐
yes
[ ('nameOfDevice1', '11:11:11:11:11:11'), ('nameOfDevice2','11:11:11:11:11:11') ]
and
{% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %}
{% set name = allowlist | selectattr('1', 'eq', trigger.event.data.mac.upper()) | map(attribute='0') | list | first | default %}
{{ name is not none }}
makes it harder to read though ๐
Lovely! Thanks! Harder to read perhaps, but easier to modify the whitelist ๐
not necessiarly
are you using yaml to create this list?
how are you creating the attribute?
Just modifying the attribute in file editor in yaml, yes
can you show me
template:
- sensor:
- name: AsusRouter Allowlist
unique_id: asusrouter_allowlist
state: True
attributes:
list: >
{{ ["11:11:11:11:11:11", ... }}```
You should be able to do...
- sensor:
- name: AsusRouter Allowlist
unique_id: asusrouter_allowlist
state: True
attributes:
list:
- name: abc
mac: 11:11:11:11
- name: xyz
mac: 11:11:11:11
where as if you made that a tuple
it would be
- sensor:
- name: AsusRouter Allowlist
unique_id: asusrouter_allowlist
state: True
attributes:
list:
- - abc
- 11:11:11:11
- - xyz
- 11:11:11:11
or you can go with the way you're doing it
Awesome ๐ Thanks again. I'll consider my options.
Next time I will, but validating from my favorite Jedi team brings so much joy to my heart ๐ ๐ ๐
@normal moat I converted your message into a file since it's above 15 lines :+1:
and it seems I need to learn how to write code on discord ๐ sorry about that (I dont use that feature very often)
{% set lowest = state_attr('sensor.nrgi_idag', 'prices') | selectattr('isLowestPrice', 'eq', True) | list | first | default %}
{% if lowest %}
{{ lowest.localTime }}
{% else %}
No lowest time
{% endif %}
Would it be possible to get a number of entities from a specific integration?
{{ integration_entities('zwave_js') | count }}
sweet, thanks :)
covered in the docs ๐
Thank you @mighty ledge
Any way to include an input_number state into an automation alias?
nope, not possible
was just wondering ๐
this is driving me crazy, why cant I apply a filter here? {{ states.binary_sensor
| selectattr('attributes.device_class', '==', 'window')
| list }}
Any idea why doesnt my state images work on 'picture-element'
type: picture-elements
elements:
- type: image
entity: binary_sensor.1compressor
image: https://portal.husdata.se/img/KompOnAnim.gif
state_image:
'on': https://portal.husdata.se/img/KompOnAnim.gif
'off': https://portal.husdata.se/img/KompOff.bmp
well, they disappeared after core and supervisor update
How about {{ states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', '==', 'window') | list}}
let me check
Entity ID [<template TemplateState(<state binary_sensor.ewelink_ds01_c29f1325_ias_zone=off; device_class=window is an invalid entity ID for dictionary value @ data['entities']
at least i get an error back now
i guess i need a map
finally
@obtuse zephyr thank you so much for pointing me to the right direction
You bet, np
guys, i'm beggig for help. Having such mqtt payload (json): https://pastebin.com/jvnwBLpe I'm trying to create separate sensors for every item in 'harmonogramy' list depending on value of $.harmonogramy[i].frakcja.id_frakcja I would like to pass $.harmonogramy[i].data to strptime. I guess selectattr and possibly | map | dict is way to go, but struggling to set this up. Any hint?
Last time I tried something like this I got errors that a template was expected
Or a string maybe, can't really remember
Hello,
I want to put a template condition which will check if some light from group of lights, or some media_player or swith from their respective groups is at least one turned on, to trigger automation
how can I do this
For examle I have script: "Goodbye Home" where I turn off everything in my house. the trigger is changing my zone from House to Away or other zone, so basically I want to trigger this automation only if there need to do (at least one light, or switch, or media_player is turned on)
So I tried that but I'm getting "UndefinedError: str object has no element 1" when testing in template
Perhaps because of the way I create the allowlist? - sensor: - name: AsusRouter Allowlist unique_id: asusrouter_allowlist state: True attributes: list: > [ ('name1','11:11:11:11:11:11'), ('name2','22:22:22:22:22:22'), ('name3','33:33:33:33:33:33')]
you might have to change the () to []
it depends on what the parser allows
well, no that works, so it's something else
make sure the attribute is not a string
I tested by doing this: {% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %} {% set name = allowlist | selectattr('1', 'eq', '11:11:11:11:11:11'.upper()) | map(attribute='0') | list | first | default %} {{ name is not none }}
How do I do that?
what does
{{ state_attr("sensor.asusrouter_allowlist", "list") }} return in the template editor?
The whole [ ('name1','11:11:11:11:11:11'), ('name2','11:11:11:11:11:12'), ('name3','11:11:11:11:11:13'), ('name4','11:11:11:11:11:14').... ] (macs swapped out )
then ya did something wrong
it should show up like
[
[
"name1",
"11:11:11:11:11:11"
],
]
FYI mac addresses aren't something that need to be hidden
I'm gonna try with " instead of '
that's not going to make a difference
you'r emost likely missing a quote
or some other character
I'll have a look
Hmm... some of my devices are named name1 [bedroom] ...Perhaps I need to treat those differently
Let me just try a bit more first... ๐
suit yourself, but I can tell you it's not related to your names
I cut it down to use the examples and now the value looks like you said [ [ "name1", "11:11:11:11:11:11" ],
But I still get UndefinedError: str object has no element 1 on ```{% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %}
{% set name = allowlist | selectattr('1', 'eq', '11:11:11:11:11:11') | map(attribute='0') | list | first | default %}
{{ name is not none }}
|| MAC addresses aren't sensitive info btw ||
Hi, i could really do with some help here, I have a binary sensor, but i want to check 2 states, and the both must be TRUE before setting ON state, i dont know how to and and AND between the two IF's
{% if state_attr("sensor.dallas_mavericks", "opponent_name") == "Grizzlies" %}
{% if states("sensor.dallas_mavericks") != 'PRE' %}
Off
{% else %}
On
{% endif %}
{% endif %}
'and'
{% if is_state_attr("sensor.dallas_mavericks", "opponent_name", "Grizzlies") and not is_state("sensor.dallas_mavericks", 'PRE') %}
Be careful there, you're mixing quotes too. Some are " and some are '
'I'll take overthinking for $100, Alex'
๐ true true
So I did {% set mylist = [('name1','bla1'),('name2','bla2'),('name3','bla3') ] and ```{% set mylist2 = state_attr('sensor.asusrouter_allowlist', 'list') %}
But you can simplify it even further:
{{ if is_state_attr("sensor.dallas_mavericks", "opponent_name", "Grizzlies") and not is_state("sensor.dallas_mavericks", 'PRE') }}
When you say "Identical" do you mean that you see exactly that in your developer tools?
Because it looks like malformed JSON to me.
Both show [ [ "name1", "bla1" ], [ "name2", "bla2" ], [ "name3", "bla3" ] ]
The first one works, and i understand it now, the second one, i am a little lost with it, but once i get the first one in place i can play with the second one, thank you so very much
Those are arrays of arrays, not arrays of objects. I think because the mylist one you posted is using round brackets those are being interpreted as objects in the array
The second one just says "output the result of these two" which will output True or False. Assuming you're using a binary sensor, it will translate that into "On" and "Off" for you ๐
Here is my yaml in configuration: - sensor: - name: AsusRouter Allowlist unique_id: asusrouter_allowlist state: True attributes: list: "[('name1','bla1'), ('name2','bla2'), ('name3','bla3')]"
Question: Why are you defining this in YAML like that?
Second question: Why is the JSON both malformed and in a string?
Third question: What are you trying to do?
The third is probably the most important question here
Haha. I'm trying to create a whitelist to compare an event to but because of the error I'm trying to break it down. I wanted a nice list of "device name, mac address" that could be easily edited when I needed to.
I'd highly recommend putting that in a database somewhere and looking it up rather than storing it as attributes in a template
You could get creative and use an #integrations-archived for your router even perhaps
Initially I had it one line for each device but just to make sure the issue wasn't a multiline issue I put it on one line
I do use an integration. I use an event that integration has for devices connecting but want to compare it to a whitelist. A template sensor seems nice. ๐
If you really want it in HA, look at using the MQTT sensors: https://www.home-assistant.io/integrations/sensor.mqtt/
But another way:
- sensor:
- name: AsusRouter Allowlist
unique_id: asusrouter_allowlist
state: True
attributes:
name1: 'bla1'
name2: 'bla2'
name3: 'bla3'
Or nest those names under list, something like that.
that's not correct
you have to use yaml, or json
or a template
you're making it a string, which will always fail
remove the outside quotes, or put it in a template, or make it into json
Petro is very good at templates, so I'd recommend listening to him ๐
File editor says "missed comma between flow collection entries (257:33)" when I remove the " "
well, you refuse to actually show what you're putting in that field, so I can't help
i've said it multiple times that you're messing something up
post it and I'll show you
What I pasted IS what I have now. I removed all the real stuff and now use just 3 lines.
none of it is sensitive information, so i'm not sure why you're reluctant
and what you pasted is not correct
lose the outsize quotes
254 | unique_id: asusrouter_allowlist
255 | state: True
256 | attributes:
257 | list: [('name1','bla1'), ('name2','bla2'), ('name3',' ...
---------------------------------------^
258 | ```
or keep the outside quotes and add the {{ }}
Maybe a bug in File editor?
- sensor:
- name: AsusRouter Allowlist
unique_id: asusrouter_allowlist
state: True
attributes:
list: [{'name1','bla1'}, {'name2','bla2')}, {'name3','bla3'}]
is my guess at what you should be doing. But if you put an apostrophe in a device name...
Why tuples? He was trying to look up the bla1 by name1 just now ๐คช
๐คทโโ๏ธ that's what he wanted
I stand corrected, he was trying to look it up by index.
Which makes no sense to me either to be honest.
it's possible what thefes said earlier is also true, attributes might require templates and nothing else
Yup, that would make sense. I'd go for an API call to look this up myself.
I'm on holiday right now, so I can't really test it, but I ran into that in the past
it would just be the config validation, which TBH shouldn't be a restriction
I just got back from holiday
spooling up my devbox
It's a bit inconvenient to create a test template sensor in mobile
Ended up using your second one, it is a little back to front False being ON and True being OFF, but it is only for 5 cards, so its all good, Thank you again and thank you for such a speedy response.
Maybe the easiest way is to create it on GitHub and then pull it to my config
Well if you want to swap it around...
{{ if not is_state_attr("sensor.dallas_mavericks", "opponent_name", "Grizzlies") and is_state("sensor.dallas_mavericks", 'PRE') }}
I'm just cooking, but will pull out my iPad shortly
Stupid kitchen having limited counter space ๐
just checked, needs to be a template
or single value
can't be a complex object
odd restriction, it's only the validation.
So, MQTT sensor?
nope, he just needs {{ }}
Gotcha
Yes, since you can create the object in a template
attributes:
bar: "{{ [('a', 'b'), ('c', 'd')] }}"
Well that seems to have helped yes, but it's not working properly for {% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %} {% set name = allowlist | selectattr('1', 'eq', 'bla1'.upper()) | map(attribute='0') | list | first | default %} {{ name is not none }} It's returning True with both 'bla1' and 'asdadas'.
Ah, so it probably works but not when I replace it with a string in dev tools?
If I understand you correctly
This post here, the logic is checking if the trigger event is in the allow list. That's what this new template does as well.
Ok. I just expected it to return False if MAC was in allow list and True if not.
remove the not
Yeah, that's ok, but I still don't understand how it can return True with both 'bla1' and 'asdasdad'. But I'll put it as a condition and see how it goes. ๐
I have a template entity with some if statements, can I include a โforโ
Example right now itโs if x>7 and switch = on, then Ok
Can I write it so that it means
If x>7 for 30 seconds and switch = on?
Or do I need to make a helper variable and an automation that flips/sets the helper variable for me and then base off that helper?
you should create a trigger-based binary_sensor with a numeric_state trigger and a for: and base it off of that
Is there a way to get the non-domain portion of an entity_id?
Like an attribute I'm not aware of or something
I have something like this and I'm trying to get the notification id (which is the part after the .)
{{
states
| selectattr('domain', 'eq', 'persistent_notification')
| map(attribute='entity_id')
| list
}}
Otherwise I'll just use a regex I suppose
Ah perfect thanks, cuz I was failing at the regex part. Just to educate myself, how would that actually work using a regex? regex_findall seemed like it might be but it doesn't seem to be working as I expected
I think really I want to use a map there, because I'm trying to modify the data. I'm kinda at a loss though
map('replace', 'persistent_notification.', '')
Though I was kinda hoping for a more generic solution using a regex. Something like [^.]*, but replace just takes a substring
Look into regex_replace
Cool, thanks for the help rob
Think I got my full NR flow to clear persistent notifications based on message
I'm trying to turn a list of entity ids into their device names. I thought I could do:
my_list | device_attr("name_by_user")
but apparently device_attr is not a filter. Any suggested alternatives?
This lists all device names that have an entity with a state that's unavailable or unknown. Maybe use it as inspiration?
{{ states | selectattr("state", "in", ["unavailable", "unknown"]) | map(attribute="name") | list | join(", ") }}
Is there a way using a template to extract a configuration parameter/value of a Z-Wave device?
does anybody know if there is any convenient way to debug value_template j2 templates based on 'mocked' or real values that come from mqtt topic? Developer tools/template is not way to go in this case
i tried to {% set var = value %} but it's not the same as the var is of type str not json
Thanks, but if I understand this correctly it lists entities, not devices
Hi smart peoples... I want to create a template so that I can create card on my dashboard... It is for my Solar inverter's battery state of charge, anyways what I need to do is the state of charge shows as a percentage.. What I want to die is show the state of charge time to 35% from one hundred percent and also vise versa? I have no clue of to do this
what are you trying to do, device_attr gets device attributes. Are you trying to get a list of name_by_users from device_ids?
You'd need to know how long it takes for each %. Without that, it's not possible.
{% set value_json = "<copy_topic_contents_here>" | from_json %}
{{ Test your MQTT code for value_template here }}
Thank You!!
Yes, list of name_by_users from device or entity ids (device_attr can handle both as input, but is not available as a filter)
BTW I think you can simply this template. For example, the map, list, and join can all be consolidated to join(',', attribute="name")
It sure works fine. Thanks
you'd have to use namespace to generate the list as they aren't filters
{% set ns = namespace(names=[]) %}
{% for e in mylist %}
{% set ns.names = ns.names + [ device_attr(e, 'name_by_user') ] %}
{% endfor %}
{{ ns.names }}
baah ๐ฆ Do you happen to know if it's intentionally not a filter or just an omission?
LOL
just missing functionality
just wondering if it's as simple as a PR that adds
self.filters["device_attr"] = pass_context(self.globals["device_attr"])
yep, that would be about it
but you're still using it wrong in jinja
if it was a filter, this would be the correct way.
{{ mylist | map('device_attr', 'name_by_user') | list }}
cool. Why is it better than the direct way? I use filters like that all the time
it's not better, the method only acccepts a single string as an input
so if it was a filter, it would still only accept a single string as the first argument
first_argument | filter(second_argument)
is functionality the same as
filter(first_arugment, second_argument)
that's the only difference between a filter and a function/method
but filters can be used in map and other functions
and device_attr does not accept a list, therefor you'd have to use map.
but map itself is a filter with arguments, why is it needed?
because device_attr's 1st argument doesn't accept a list
ah, got it
np
I have a pending PR for that...
what's up with your PRs taking years for reviews?
I'd expect 1 - 2 months max
You tell me
There are a bunch of 'can't be used as filters' functions that I want to fix
got a list? I know some will get rejected BTW unless you can show the use case in your description.
BTW, feel free to ping me, IDC about pings
and let me know if you don't like pings, i'll stop. However I ping tink on purpose now ๐คฃ
Not offhand, but it's the ones around devices and integrations
I love filters, and it just seemed a weird omission
when they are rejected, it's mainly because it doesn't make sense code-wise
unless you can show a usecase for it
like when using select or selectattr
I don't see why you'd want a function without a filter that can act on an iterator
for example, states as a filter was rejected at one point
my guess is that they aren't thinking about generators
In any case, I have a PR for device_attr, I think. Will look at others
It's a pattern
I'd lump all device ones together and all integration ones together
tests and filters
Have you switched to #449717345808547842 yet?
||I switched to your mom||

Hello, template math type question. I want to divide 2 entities.
Does this look correct?
template:
- sensor:
- name: "Percent Covered"
unit_of_measurement: "W"
state: "{{ states('sensor.envoy_20221x_lifetime_energy_consumption') / states('sensor.envoy_20221x_lifetime_energy_production') }}"
- name: "Percent Covered"
you need to convert both to floats
{{ states('sensor.envoy_20221x_lifetime_energy_consumption') | float(1) / states('sensor.envoy_20221x_lifetime_energy_production') | float(1) }}
``` replace the `1` with whatever a reasonable default value is for those sensors in the event that one or both of them are unavailable
Ok, I have to read up on float. Let me give that a try.
All states are strings, so you need to convert them to numbers first before doing math with them
That worked perfect. | round(2) }} at the end should work, no?
I assume you want to rond the result, in that case you need to add parenthesis around the formula
I only rond so many results, most of the time I rund them
First you unga, then you bunga
||I did. Sshhhh...||

It was surprisingly easy and seamless. I realized that all the addons I was running were simply to allow access to HA OS, and then I had my VM mysteriously just shut down twice in a few days. Once it was making my install less stable, I bailed
HA Container is nice. docker-compose is also so easy to use it feels like I'm using a UI
I do like YAML though, so that helps I suppose
I wrote a small shell script to update HA, so still easy to update with a button
I have some aliases set up and an updater script
I also collapsed all my (many) independent containers into a single docker-compose.yaml, and I'm somewhat less enthused about that
updating isn't really a one-size-fits-all exercise, and I found yesterday that a single failure broke everything. I've been slowly putting most stuff in a separate profile to allow starting/updating independently
@mighty ledge I created a PR based on our discussion: https://github.com/home-assistant/core/pull/81924
just read the conversation and saw that @inner mesa you might have one too? Mine is for device_attr and is_device_attr
did that work as-is? I have one in progress that builds on another PR I have open: https://github.com/home-assistant/core/pull/79903/files
I found it to be more complicated than just allowing it to be called as a filter
hmm, it worked for me
you can ignore a bunch of that, as it's related to the other PR
is_device_attr needs to be a test for it to work with select
oh, I actually didn't test it with select - just assumed it works
I'll chang the description
yeah, well you assumed wrong ๐
ok, I updated the PR description to something I did test
Hi guys, i scraped some date of Internet ' Thursday 10 November 2022' this current string in it, how can i cant it to date? Thanks
When I was working on that PR, I had expected that filters would be called separately for each item in the incoming list, but it seemed like they just get called with the whole thing, requiring the filter to iterate. That's why it seemed more complicated. Did I just misunderstand what was going on there?
yeah, that's what @mighty ledge clarified for me above - you should use it with map()
and then it doesn't have to work on a collection, just a single item
let's hope it gets picked up
{% set date = 'Thursday 10 November 2022' %}
{{ strptime(date, '%A %d %B %Y') }}
Thanks and how would i to this if that string is in the senor.bin_collection?
you can update things independently even if they're in the same docker-compose file
docker-compose up {service_name}
I know, it's just more typing
some things I want to update together, some things separately. profiles can help with that
makes sense
makes sense
I just don't have a consistent system in place yet
{{ strptime(states('sensor.bin_collection'), '%A %d %B %Y') }}
Thanks alot, it finally works ๐
Im trying to create a template sensor with an attribute that is supposed to be a list of objects, {date, value}. I can only seem to get to be a string, and not a real list, that I can use in my frontend for charts and stuff. Any way to do this correct?
From what I understand, a template sensor returns only a single value
yes, a list will also be a single value, and an attribute can be a list. It will just turn into a string when I use an object
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.
Share what you have now @proven needle
anyone familiar with scraping data from a local hosted website ? - im trying to scrape some data in a sensor, but having some issues with getting the correct css selector. If anyone could spare a few tips, please feel free to write me a message privately
I have changed it a bit now, so I just return a tuple with a timestamp, and my value, and not an object. This works fine for me ๐
I normally use a chrome extension "Copy CSS Selector" and that works pretty well for me so far...
yeah, im working with that as well. But im probably not understanding the way it works well enough. I've created a sensor. But get the error in the logs, thats stating - index '0' not found in sensor.xxxx. Any idea what the issue is ?
resource: https://www.gasbuddy.com/home?search=68154&fuel=1&stationId=38&maxAge=0&method=all
scan_interval: 3600
name: GasBuddy-Costco
select: 'div#root div:nth-child(1) > span.text__lg___1S7OO.text__bold___1C6Z_.text__left___1iOw3.PriceTrends-module__priceHeader___fB9X9'
try that and see if that helps you understand why yours isn't working... or post your code...
- platform: scrape
name: Storj Bandwith
resource: http:// removed....
select: "#app > div > div.scrollable > div.content-overflow > div > div.info-area > section:nth-child(3) > div > p > b"
have you tried the select with ' '
I'm certainly no expert. I don't have any local scrapes, mine are all on public sites... but I have 4 and once I got them right I left them alone. I'll wait until someone more knowledgeable can respond.
fair enough - thanks for your input anyway ๐
very welcome
Are there others errors in your log
None other than the one Mentoined. Index 0 not found in Sensor.sensorname no
Your local page doesn't have auth or SSL or anything on it?
No, not That I know off
No login required
It's a local dashboard from a storj node if your familiar with storj
Gotcha, I'm not, I just know a lot of (obviously, not all) local things require some type of credentials before letting you browse the first time
You'll get more help if you post in the proper channel. #integrations-archived
this channel is for jinja templates
Didn't realize that. Thought it was all templates. Not an integration I'm using
it is all templates, but what you're asking about isn't a template
Yes it is?
A template sensor
Using scrape function as the template
Or am I missing something
I've yet to see you post any template
you're asking about the scrape integration selectors
and the configuration for scrape
a template will start with {{ }} or {% %}
and it will contain jinja code
e.g. template
{% set abc = states('sesnor.something') | float(0) %}
{{ abc + 4 }}
that's jinja
i.e. a template
Ahh I see thanks for clearing that up
I'll try in integrations
I got jinja code covered. Just didn't know that was what it was called
FYI, you can read the channel description for each channel, it will clear up any doubts about where to post.
and if you're still unsure, just post in #general-archived first
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
and maybe add the html via one of the code share options
http://pastie.org/p/7o0BTUraok6Uh2wR7szoug
Using this for gathering the total power my lighting circuits use. I throw it into the energy dashboard and some days it is showing 500 kwh per day usage. what have I done wrong? all entitles it is pulling the state from are in kWh
what's wrong
you mean you duplicated them
bathroom is in there twice
you also have others in there twice
FYI, the way you are managing that isn't very nice
{% set entities = (
'sensor.ensuite_ceiling_energy',
'sensor.ensuite_vanity_energy',
'sensor.toilet_ceiling_energy',
'sensor.bathroom_ceiling_energy',
'sensor.bathroom_fan_energy',
'sensor.underhouse_storage_energy',
'sensor.workshop_energy',
'sensor.toilet_fan_energy',
'sensor.entrance_chandelier_energy',
) %}
{{ entities | map('states') | map('float') | sum | round(2) }}
does the same thing you're doing
and then your availability would be
lots of multiples
{% set entities = (
'sensor.ensuite_ceiling_energy',
'sensor.ensuite_vanity_energy',
'sensor.toilet_ceiling_energy',
'sensor.bathroom_ceiling_energy',
'sensor.bathroom_fan_energy',
'sensor.underhouse_storage_energy',
'sensor.workshop_energy',
'sensor.toilet_fan_energy',
'sensor.entrance_chandelier_energy',
) %}
{{ entities | map('states') | reject('is_number') | list | count > 0 }}
what is the difference between the two?
first is you sum
second is availability
just keep in mind that if any sensor drops out, the entire sensor drops out
which might not be what you want
if you want it to always have a value, omit the availability template and just have your state as
{% set entities = (
'sensor.ensuite_ceiling_energy',
'sensor.ensuite_vanity_energy',
'sensor.toilet_ceiling_energy',
'sensor.bathroom_ceiling_energy',
'sensor.bathroom_fan_energy',
'sensor.underhouse_storage_energy',
'sensor.workshop_energy',
'sensor.toilet_fan_energy',
'sensor.entrance_chandelier_energy',
) %}
{{ entities | map('states') | map('float', 0) | sum | round(2) }}
oh cool. that makes sense if one of them goes offline
keep in mind, you'll get jumps in your data when you restart. There's a trade off
what would petro do?
petro doesn't restart
(have not had one go offline - if one goes offline they all go offline)
how tf do u do updates?
I do them once and a great while
and I ignore the data from that day
or I use an availability template
with the one listed above
all or nothing
roll of the dice, flip of the coin
how would what you suggested fit into the sensor? is it just after state: >-?
just replace your 2 templates with what I wrote above
make sure you add in the spaces for each
@formal ember I converted your message into a file since it's above 15 lines :+1:
yeah i am
then you should simply get a sum
fk i know why. i commented out the old stuff, but its still picking it up!
you can't comment out anything in templates
now i know ๐
I'm trying to change the color of an icon based on the temperature of a room vs the temperature the thermostat is set to, so I can quickly see if a specific room is too hot or too cold. And was hoping you smart folks might be able to help me logic this out, because I think I might be approaching it in a sub-optimal way.
Currently doing temp_diff = (thermostat_temp) - (room_temp) and then if temp_diff is -X degrees or lower a light blue color. If it's between these temps return a darker blue color, if it's between an 'optimal' range return white, if it's too high, yellow, orange, red, etc. And that has been working great for when the AC is on. Because when you set the AC on, you want it to be that temperature.
But now that I've switched over to heat, the logic doesn't really work anymore. It's not that cold outside yet, so heat's not even running. T-stat is set to 68ยบ F so the heat kicks on when it's actually cold at night, but some rooms are floating around 72-74ยบ during the day which is great. But my sensors are showing RED because it's more than a 5ยบ temp_diff
any thoughts?
Maybe have a condition check to have different ranges/thresholds based on climate mode of your thermostat
Yeah, that's what I was thinking originally. Just wasn't sure if there was a more elegant solution that I hadn't thought of
I'm attempting my first template for a lovelace card, and I'm a little over my head with formating
Charley's next important date is {{ (state_attr("calendar.charley","start_time")) }} results in Charley's next important date is 2022-12-02 14:00:00 but I'd ultimately like Charley's next important date is on 12-02-2022 at 2:00pm
You'll need to format it, the templating docs have some pointers: https://www.home-assistant.io/docs/configuration/templating/#time
{{ state_attr('automation.alarm_armed', 'last_triggered').strftime("%-m-%-d-%-Y at %-I:%M%p") }}
-> 11-11-2022 at 6:56AM
https://strftime.org/ to the rescue, as always
Grrr, I was just completing this:
{{ now().strftime('%d-%M-%Y at %I:%M %p') }}
I have a syntax error
| relative_time another nice one to use
I'm on mobile, so I needed to come back here to copy and combine it
{{ (state_attr('calendar.charley','start_time')).strftime("%-m-%-d-%-Y at %-I:%M%p") }}
UndefinedError: 'str object' has no attribute 'strftime'
What is the error that you get?
Ok, that's easy enough
{{ (state_attr('calendar.charley','start_time')) | as_datetime | strftime("%-m-%-d-%-Y at %-I:%M%p") }}
*easy enough for me
Almost:
{{ ((state_attr('calendar.charley','start_time')) | as_datetime).strftime("%-m-%-d-%-Y at %-I:%M%p") }}
You can't use strftime() as a filter
Darn, I always forget that one
if I ever start typing a complex template on my phone and see somebody smarter than me typing, I just erase and move on ๐
okay it works! now I gotta look through the linked document and figure out what I can learn
and then, how to get that into a lovelace card
thanks!
The markdown card will be a good helper to start with ๐
Well, I would not consider this complex. I had to look at strftime.org though for the 12hr clock format
one persons simple is definitely my complex ๐
anything that requires me to repeatedly switch between alpha and two different sets of symbols on my phone is "complex" ๐
Ah, right, that's true.. adding code tags is almost complex then. That backtick is hidden in a deep dungeon of the Android keyboard
it's less about the difficulty of coming up with it than the challenge in testing it and typing the thing in the first place
Thanks for everyones help
I got everything looking how I wanted
Hi Everyone! I am looking for some help with a template sensor. For the life of me, I can't figure out why the template sensor is "unknown". I have a boiler that has an API and it exposes data about the current state of the boiler. The detailed data comes across in state attributes of the entity sensor.ibc_boiler. Here are the attributes: http://pastie.org/p/6iZ8pakEYJHGcIr04EzGv7
I am using template sensors to break out the attributes into their own entities. I am able to get SupplyT and ReturnT, for example, just fine however Errors and Warnings are always unknown
I can't quite figure out why, when in developer tools I can see the data for both is None
Here is my template sensor
state: "{{ state_attr('sensor.ibc_boiler', 'Errors') }}"```
'None' is special
Oh man....๐
three hours of troubleshooting to find out 'None' is a reserved word
lol
Is it possible to evaluate for none and change the message in the template sensor?
Yes
Awesome!
Probably don't need the True
you do need the , True
hey @inner mesa can you tell me a little more about what you mean?
'None' (note the quotes) would be fine
I'm not so sure
None is its own data type though (NoneType)
matt@server:~$ python3
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type('None')
<class 'str'>
Still not sure that translates back to the state that way.
I'm pretty sure I've had that issue
Interesting. To be fair, it's probably best to avoid anyway
I was still curious
But yeah, if you've had issues with it before, still probably just best to avoid
I recall that the problem was returning that as a state of a template sensor
On Template page there is this example:
- binary_sensor:
- name: "Has Unavailable States"
state: "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"```
It appears none and unknown might be the same thing so does it all resolve back to unknown?
not sure
so...
state: "None" gives a "None" state
state: "{{ 'None' }}" returns "unknown"
as does state: '{{ "None" }}'
So if you just use a string, you're good. If you return it from a template, it's converted into the type
Interesting
Is it possible to create sensors/binary sensors in a loop in the configuration.yaml. Instead of a sensor configuration per room, I would love to create the same sensors in a loop to reduce duplication.
Hi, you entered this too in the forum and I 'guess' I know what you want but was not enticed to join any comms ...maybe explain a bit what you want to achieve without (immediately) looking for a tehcnical solution
Ah ok, so that's what was happening... the state was "{{ 'None' }}" so it was returning "unknown". I just ended up evaluating for 'None' and returning 'Clear'
Now I'm good to go!
Thanks again!
{% if states['sensor.anyfanon'].attributes.[variables.attri] > 0 %} show {% else %} hide {% endif %}
what I'm doing wrong ?+
you have an extra "."
compare: states['sensor.anyfanon'] to attributes.[variables.attri]
that whole construct isn't ideal
{{ iif(state_attr('sensor.anyfanon', variables.attri) > 0, 'show', 'hide') }}
keep looking, I guess. works for me
{% if state_attr('sensor.anyfanon', '[variables.areazone]') > 0 %}
show
{% else %}
hide
{% endif %}
still can't get it to work
I have many sensors and binary sensors for things like detection if motion was recently detected in a certain room, performing of counts of certain actions per minute in various rooms. Theres a sensor for each room which runs a certain piece of logic, with time/date comparisons inside and other checks. The only difference between the sensors is the name and an entity id checked inside. So I want to automatically generate sensors, with the contents of the template for each sensor being parameterized.
That looks nothing like what I gave you
Good luck
What you gave didnt work
So tried something else
Did Rob have square brackets in the state_attr()
I tried also without square brackets
Random musings
{% if state_attr('sensor.anyfanon', variables.areazone) > 0 %}
show
{% else %}
hide
{% endif %}
Are you sure you don't need areazone instead of variables.areazone?
If you defined them under variables: you don't need it
Unless you did
variables:
variables:
areazone: "foo"
Variables:
areazone: "pczone"
Can templates be used in device select_option blocks, it seems not, unless I'm doing it wrong, ie the following string is being passed literally to my device, not the value of the rendered block of template.
device_id: a1f2.....
domain: select
entity_id: select.harmony_hub_activities
type: select_option
option: "{{ states('input_text.desired_harmony_option') }}"
sorry i'm lost in here
{% if state_attr('sensor.anyfanon', areazone) > 0 %}
show
{% else %}
hide
{% endif %}
still nothing
No, but you can use the select.select_option service call and use templates there
there is a template concept of integration_entities(arg) where you pass in an integration 'key' to get a list of items within it
Thank you @marble jackal !
but how do you iterate on integrations?
Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.
Share the complete code of the script/automation
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.
I meant that bot message
Do you mean know what the integration key is or ...?
You want to iterate over every integration in your system, without knowing what they are?
it's a button template card
I mean, the system knows
why should I copy paste data that's just going to fall out of date
The XY problem is asking about your attempted solution rather than your actual problem.
you may want to explain your goal here, it'll help people help you
I want to assign area on entities based on other aspects of them... names or inheretence tree or things like that
I mean, at the core of this
You can't do that programmatically
dang
cause there's no way to bulk set area in the ui either
you have to do it one thing at a time
so if I have large numbers it's... miserable
I don't think that card is aware of those variables
Hey. I have a big list of ping entities of iot devices, all ending ttheir name with _status. How can i template them as trigger going to off state, in a way so i can notify my mobile the one that went offline?
else i have to select them all and keep track of them whenever i make a new one
like this but then smart:
entity_id:
- binary_sensor.camera_achtertuin_status
- binary_sensor.otgw_status
to: "off"
for:
hours: 0
minutes: 10
seconds: 0```
@bronze dune I converted your message into a file since it's above 15 lines :+1:
On the right channel this time ๐
Hello, Can anyone help me out with this? i need to create a new "sensor" that shows the difference between 2 sensors, this is what i got but something is wrong.
template:
- sensor:
- name: "Solar Total Energy"
unit_of_measurement: "KWh"
state: >- {{ states('sensor.solar_energy_total_energy') - ('sensor.house_energy_total_energy') }}
- name: "Solar Total Energy"
state: "{{ states('sensor.solar_energy_total_energy')|float(0) - states('sensor.house_energy_total_energy')|float(0) }}"
you forgot the second states ๐
so you need states for every sensor right?
Correcting the formatting.
Hi - I'm hoping someone could point me in the right direction.
I am attempting to create a template sensor entity that contains a list of entity_ids from other devices. But, the senor state results in unknown. The same code works in the dev tools template section.
http://pastie.org/p/7oSBDYelMl22rJ9ueszabM
Hi Team, This may be a weird question but going to ask anyway.
I have a sensor the has a value anything between 1 and 100.
I am trying to set a helper to the closes lower "10" of the number of the sensor.
eg. if the sensor is 18 then I want to set my helper to 10. if its 55 the I want to set it to 50.
I looked at "round" and a few other but cant get it to give me the rounded number to 10.
Can anyone of help give me an idea on how to get this working please?
{% for person in ns.persons %}
<img src="/local/{{ ns.persons[{{loop.index-1}}] }}.jpg" width="50%">
{% endfor %}
How do i put a loop index inside my namespace?
{% for person in ns.persons %}
<img src="/local/{{ ns.persons[0] }}.jpg" width="50%">
{% endfor %}
This works but I want the for loop to iterate through my namespace indexes as I got different images
You are nesting templates
For the first one you should remove the curly brackets around loop.index -1
If anyone else runs into this type of problem.. the state of the sensor can't store the volume of the data.. my work around was to make state an int and create an underlying attribute for the entity_id array.
http://pastie.org/p/0ZyvTXUSoZCLhGzDp7gq5T
Your template is really overcomplicated
{{ 58 | round(-1, 'floor') }} returns 50
OMG, thanks @marble jackal works. should have come here earlier. ๐คฆโโ๏ธ
I was about to help, but looks like you've got it sorted ๐
@lime shell did someone help you yet?
Yes it's working
Excellent
@marble jackal Firstly, extreme thank you - I'll study this and improve how I make things.
Question: The |unique throws an error in the template? <generator object do_unique at 0x7f7ca4e8f0>
Can you post you template code somewhere so we can look? Probably unique is getting a None or something. Would need to see full error
Hi it is this code from TheFes - I took the block from entity_id and tossed it in the template editor in HA and got that error
http://pastie.org/p/78u63yOkjFaHCydB0F34HX
sorry I have to go to my grandkid birthday now, no time to help. Maybe when I get back in ~6 hours
try breaking down that final expression, and printing the bits. I bet one is None or something like that
afk
I'm back. Did you get solution @marble jackal ?
It's not an error, but I forgot to add | list
{{ (lightsOn + lightsOff) | unique | list }} was what it should have been
Ahh.. ok thanks! That works
Good good
Has anyone got a good tip on how to create reusable calculation modules for use in templates ?
I have some calculations that i need to do in multiple places but based on different input values and i would very much like to create these as "functions" that i can use in any template that needs that calculation, so that i don't have to include the full template code in every place i want to perform the calculation. This makes things very complex to maintain.
I have seen suggestion to use yaml anchors on reuable templates code but i cannot see a way to parse one or more parameters to a piece of anchored template code.
You can use trigger based template sensor and add the input as trigger variabeles
Hi,
Anyone give me some pointers on making an entity from an existing entity?
I'm trying to make a new entity from media_player.spotify_home_assistant
The code I have is below, but I'm unsure what platform I would need..
platform: spotify_song: friendly_name: "Spotify Song" value_template: "{{ state_attr('media_player.spotify_home_assistant', 'media_title') }}"
Hello Everyone. I want to build a card for all my rooms. Is there a way to template this ro will i have to create individual yamls for each?
platform: template, but that is the legacy format, and your indentation also seems off
yeah, indent is due to Discord
I literally just figured it out about 3 seconds before the bing noise XD
Thank you though
What would be the difference with the newer format? The only things I can find is older code, so updating to latest format would be advantagious
oh... I think I understand this!
Newer code supports state_class and self referencing using this
I think I may have cracked it! Let me test
maybe not...
maybe I'm just a complete moron XD
it would be helpful if I referenced the templates files and folder correctly!
... and that works gloriously with the new format
thank you
is there a list of variables I can see for an entity? I have media_artist and media_track, but can I also pull duration, album art etc?
Is there something wrong with this:
type: picture-elements
elements:
- type: image
entity: binary_sensor.1compressor
image: https://portal.husdata.se/img/KompOnAnim.gif
state_image:
'on': https://portal.husdata.se/img/KompOnAnim.gif
'off': https://portal.husdata.se/img/KompOff.bmp
style:
top: 57.8%
left: 40%
scale: 0.7
Or why it does not show "compressor" image on that picture element?
You wanted #frontend-archived
Developer Tools > State
But most attributes for a media player are only available while playing something
Thank you
is there a function that could show a delta of a sensors value over a period of time and be "live"? for example I have a sensor that reports every 10 seconds, is it possible to have a 6hr % change sensor?
Templates are only in live data
But you could use an SQL sensor to get the value from six hours ago out of the database
Hello, I am trying to write a template that sifts thorugh states.sensor and in the end sorts by state, something like {{ states.sensor | filter1 | filter2 | sort('state') }}. The problem is that homeassistant stores the values as strings, and lexicographical order & numerical order are not the same thing. In my case, the state is a float, and I would like to convert it before sorting happens. I could not find any way to do that in jinja, nor it seems to be possible through homeassistant in some way. Is there any way to solve this problem?
For some context, the result of this is needed within a notify call, to advise the user about what power sensor is reporting the highest consumption.
I would like to convert it before sorting happens.
|map('float')
Yep the problem is that map('float') does not work on the list of entities. I can extract the state but then I lose the friendly_name, which I want to keep instead - the final idea is to produce a notification like "Currently the $friendly_name is consuming $state W" where both the name and the consumption are extracted from states.sensor
Ideally I would need something like map('float', attribute='state') if that makes sense
@wary moon You need to use a for loop with a namespace to create a list with the thing you want (the friendly name for example) and the state as a float, and then use that to sort it. At least, that is what I would do
{%- set ns = namespace(sort = []) %}
{%- for item in states.sensor | selectattr('state', 'is_number') %}
{%- set ns.sort = ns.sort + [ dict(name=item.name, state=item.state | float) ] %}
{%- endfor %}
{{ ns.sort | sort(attribute='state') }}
{{ states.binary_sensor|map(attribute='entity_id') |list }} How can i select all entities ending with a certain string? _status in my case
selectattr, though I'm not sure it works with a regex.
is there another way to select only a couple based on some parameter?
i have ping sensors for iot devices. I dont want to keep track of the list but scoop them all up in one smart template
| selectattr('entity_id', 'search', '._status$')
You always solve my problems. Thanks for that! Now I can go rework lots of templates ๐
my syntax is ehhhh broken.
as per usual ๐
i get ALL info on the ping sensors not just the entity name to use in as a trigger
You'll need to map the entity id ๐
You removed the map()?
ye didnt work
{{ states.binary_sensor| selectattr('entity_id', 'search', '._status$') | list }}
this gives me ALL info
Yes, that's because you removed the map()
nvm... got it lol
{{ states.binary_sensor| selectattr('entity_id', 'search', '._status$')| map(attribute='entity_id') | list }}
๐
thx! saves me keeping track of all sensors
well.... im not out of the woods yet. i need a template trigger: If any of these mapped entities go to off
Well, that's a bit trickier, because the state trigger doesn't let you input a template.
{{ states.binary_sensor | selectattr('entity_id', 'search', '._status$') | map(attribute='entity_id') == 'off' }}
i cooked up this
it shows false now. which is correct, but yet to pull one ping device offline
The problem is you're checking if the list of entity_ids equals off.
So if [sensor.1, sensor.2] == 'off'
so you want to fill the state trigger a full array as entities
then you can even pass the bad one to notify
No, you can't do that, the state trigger doesn't take templates
{{ states.binary_sensor | selectattr('entity_id', 'search', '._status$') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list | count > 0 }}
That's a guess, I'm not sure that'll work. Because if you have one offline device you won't get another trigger
that gives a trigger
thats not a problem cuz ill go and find it straight away. But the bad entity is no known
But, if you use a condition instead of the > 0, and save the count of offline devices to an input_number, or something I'm sure you can manage it
But what are you trying to accomplish here?
its fancy to get a notify of it but not really needed
notify me of the entity name going offline
like bad wifi or whatever
But why?
If something is offline due to bad wifi, then it will be "unavailable", not "off"
And if the network is down, the notify won't work
the ping binary sensor will be off though
i have cameras as well
not integrated into HA
Like Rosemary said, you will only get a trigger if it goes from 0 to 1, but not if a second device fails
thats better then my girlfriend yelling this or that isnt working ๐
you can use the template you had to get the entity_id of the device which caused it
replace entity_id with name to get the friendly name
and jou can use join(', ') instead of list to get a string instead of a list
I'd do the join, maybe sort the list first to be sure, and save it to an input text.
Then you can compare it to the input text for changes.
If you want a trigger for the second/third/etc device as well, I would createa a template sensor with a count of the devices which are offline, and a list of the devices which are offline in an attribute
then trigger on a state change of that template sensor, check if the value increased in a condition
hahaha its becoming wayyyy overkill ๐ i like that.
Ooh, much better idea
an compare the new value of the attribute with the old to see which one caused it
all stuff is working pretty well with 4 APs in the house, but i like it
Of course, if one device goes offline as another comes online then you might not get a trigger ๐
it has to be within one second, as states[domain] templates are rendered once per second
is the outgoing ping in sych for all
?
i can do differenct intervals for all ping sensors
120 sec 118sec 116 sec etc
if you would put them in a group (which you can do dynamically using group.set) and use expand on the group, you have instant updates
or, if they are the same 4 devices always, just add them in a binary_sensor group
its like 20 wifi iots
removing and adding as i please/is needed
hence the ping binary sensor so i only need to keep track of that yaml file
and a trigger with entities ending with _status
that was my novice idea anyway ๐คท๐ผโโ๏ธ
Well, what I would do:
- on startup of HA, and reload of ping sensors, create a group with all these binary sensors
- create a template sensor with the count of the group members which are
offand the names in an attribute - use that sensor for the automation
thank you for your effort! both of you. Im going to re-read this tomorrow and hopefully i can cook something up
๐๐ผ
Hello everyone,
I am trying to create a list of sensors matching two criterias. One is part of the name and one is the area.
I cannot figure out the area filtering.
{{ area_entities(states('input_select.dropdown_areas')) }}
{{ states.sensor|selectattr('object_id', 'match', 'xiaomi_humidity')|map(attribute='name')|list }}
The first returns all entities in the area (but as entity_id rather than the wanted friendly_name)
The second gives me the result I want but not filtered for area
{% set entity_list = area_entities(states('input_select.dropdown_areas')) %}
{{ states.sensor | selectattr('object_id', 'match', 'xiaomi_humidity') | selectattr('entity_id', 'in', entity_list) |map(attribute='name') | list }}
Or something like that. I'm guesstimating as I'm on mobile.
Thank you! That works perfectly!
I kept trying an integrated one liner version and kept failing ๐
And then merged
{{ states.sensor | selectattr('object_id', 'match', 'xiaomi_humidity') | selectattr('entity_id', 'in', area_entities(states('input_select.dropdown_areas'))) |map(attribute='name') | list }}
{{ area_entities(states('input_select.dropdown_areas')) | selectattr('domain', 'eq', 'sensor') | selectattr('object_id', 'match', 'xiaomi_humidity') | selectattr('entity_id', 'in', entity_list) |map(attribute='name') | list }}
Would have been my guess, but that works too
I can't seem to figure out how to match foo "OR" bar in i.e. {%- if 'espressif' OR 'ESPHome' in manufacturer -%} Is it possible?
You'd need to do: if 'espressif' in manufacturer or 'ESPHome' in manufacturer
Or use set-logic
don't know what set-logic is yet ๐ but this worked {%- if 'ESPHome' in manufacturer or 'espressif' in manufacturer -%}
I'm looking at https://jinja.palletsprojects.com/en/latest/templates/#logic now...
{% if manufactuer in ['ESPHome', 'espressif'] %}
Or you could do:
if {'ESPHome', 'espressif'} & manufacturer
I tried that but I had it reversed... ๐คฆ
its a string.
OK use what rob wrote. I assumed it was a list/set because you were using "in" on it
I'm trying to filter for entities that don't have an "alarms" attribute OR a "timers" attribute. Of course I can't just add one before or after the other since then they would already have been excluded. This is what I have to filter one of them, but how would I do filter for one or the other?
...
|rejectattr('attributes.alarms', 'undefined')
...
I don't see why you can't just use two |rejectattr()
Well because which ever comes first will filter out entities before the next one can even get to them, no?
Say I have a bunch of entities that have one of the following: only an alarms attribute, only a timers attribute, or neither. If I filter for entities with the alarms attribute then filter for entities with the timers attribute, those that actually have the timers attribute will already have been rejected by the first filter because they don't have an alarms attribute.
Perhaps I'm missing something, but when you say "don't have an 'alarms' or 'timers' attribute", it sounds like you're looking for entities that have neither
so reject both attributes
reverse the order...
filter with timers attributes, reject alarms. If you're trying to remove both, just reject both in any order.
I have a helper, which counts the impulses of my gasmeter.
I also have a template that represents the total gss consumption in mยณ.
I want to have ab other template, that calulates the Gas consumption per h, per day, per week.
How can I access the timestamps to do this.
use utility meter integration
or use the energy tab
if you don't want entities
thanks!
for me to learn:
If I want fo aggregate values of a timeserie, can this be expressed in a template too?
I'd suggest for anything like that you should look at InfluxDB (and optionally Grafana for pretty charts)
You can, but templates don't have access to history.
i.e. there's no point to investigate it because you can't get to it.
Thanks.
Iยดll try this out
An other issue:
I have wrong data for the helper, on one day in the past, where I setted it up.
This disturbse now all statistics.
How can I get rid of the helpers historical data for one day in the past.
Then you have the same issue
I'm trying to select both.
I'm not sure how else I can put it
You said rejectโฆ
so you want all enties which:
- don't have an alarm attribute
- do have a timer attribute
Reject undefined was the code snippet.
create 2 lists and combine them
Do have one or the other
So are we supposed to read minds then?
No you're supposed to read the code snippet
Yes and it had rejectโฆโฆโฆโฆโฆ..
But it was confusing how I was using a double negative, I agree
Isn't rejecting undefined the same as selecting it being present?
{% set no_alarms = states.sensor | selectattr('attributes.alarms', 'undefined') | list %}
{% set timer = states.sensor | selectattr('attributes.timer', 'defined') | list %}
{{ no_alarm + timer }}
Yes this is actually what I ended up doing lol
I was looking for a solution in a single filter though
that's not possible for the reason you already stated, you filter out entities you need
Well I didn't think it was possible, but also I'm sure there are better templaters in here
Also that first undefined should be a defined
I wanted it with one or the other
whatever, your descriptions were very unclear
Rereading my first sentence I think it could have been better:
I'm trying to filter for entities that don't have an "alarms" attribute OR a "timers" attribute
I should have said "out" instead of "for"
Also didn't specify if the "don't" applies to the second clause
if you're trying to filter them out, then that's sipmly reject attr
this is what you aren't understanding
so you have a fundamental incorrect thinking on what filter means.
when you filter something out, you remove it
meaning you'd be left with all sensors that DO NOT HAVE alarms or timers
Yes, and at the time I had double negative logic, so I was looking to filter out what I wasn't looking for
not "I only want a list with alarms or timers"
if you want to filter out entities then you just use rejectattr, i feel like we are going in circles here
{% set no_alarms = states.sensor | selectattr('attributes.alarms', 'defined') | list %}
{% set timer = states.sensor | selectattr('attributes.timer', 'defined') | list %}
{{ no_alarm + timer }}
This was the solution
AND THATS NOT FILTERING OUT
that's selecting ๐
When you say "I want this" in a filter you're also saying you don't want everything else
Filtering is the |
"I want to filter down to a list of alarms or timers"
I already said I worded my first sentence poorly
right, but you've reworded it wrongly every time you've said it
I was using the word filter in the technical aspect like Rosemary said
You need to be clear if you mean a filter function or filtering a list of somethings.
Well my example had the |
It's often best to describe your problem as simply as you can:
I want to get a list of the sensors which have an attribute "alarms", or an attribute "timer"
I agree I didn't word it very well initially. Fes was able to figure it out without too much fuss though
And then you can include your example after that, but the simple explanation at the start is really critical ๐
I wasn't because I used undefined instead of defined (and named the variable no_alarms)
lol true
Incorrectly named variables are one of the banes of my existence ๐
That's why I try to do everything in a single filter, don't need variables ๐
Oneliners sound good, but it makes re-using things harder.
It's a script kiddy approach usually.
(I say that as a former script kiddy ๐)
Maybe I should have given a code example of how to accomplish it
...
.filter(foo -> foo.attributes.includes('timers') || foo.attributes.includes('alarms')
...
Haha well I'm certainly not a script kiddy. They just read easier for me. You're just applying rules one step at a time
{{ states.sensor | rejectattr('entity_id', 'in', states.sensor | rejectattr('attributes.timers', 'defined') | rejectattr('attributes.alarms', 'defined') | map(attribute='entity_id') | list) | list }}
there's your oneliner
Aaah, that looks easy on the eye!
Haha tbf I was kidding about always using only filters. I think with some formatting that would be easier to read though
That's the first thing I started doing when he pasted that
Hm I'm not sure this actually works
Also since in most cases I prefer filters, I try to figure it out that way first because it helps me get better with them
it works perfectly fine if your goal is to get a list of entities that have alarms or timers attributes
Let me take a look over it again. I think I understood what you had there but maybe not.
Here's an alternate solution sort of along the lines of what you had:
Here's an alternate solution
{{
states.sensor
| selectattr('entity_id', 'in',
states.sensor | selectattr('attributes.alarms', 'defined') | map(attribute='entity_id') | list
+
states.sensor | selectattr('attributes.timers', 'defined') | map(attribute='entity_id') | list
)
| map(attribute='entity_id')
| list
}}
yep, but you're iterating the state machine 3 times vs 2
True
Much less efficient, and long term that adds up
Ok actually now I'm getting correct results when I run what you had. Weird
Ah ok I see, you're inner filter is getting a list of everything excluding entities that have either attribute, then you're excluding that from the total list to get the inverse
It still should be possible to iterating it once though...
it'll never be possible, these aren't lambda functions
How do they differ?
They seem the same fundamentally. You're telling it to do some operation on each element in the list
select, selectattr, reject, and rejectattr only allow 1 attribute at a time. That's a limitation of those BUILT-IN jinja functions. You can't get around it.
Well they allow one argument, specifically right?
those generators work on 1 item in the list at a time, and selectattr/rejectattr require 1 attribute as an argument.
Couldn't that one attribute be the attributes list? Just spitballing
no, it's a BUILT-IN jinja filter
Oh sorry, yeah I mean for select/reject
we would need a new test that accepts a list
and even then, you can't check for defined
Well you could do another in() on that list to see if the attribute is there
But yes you're right about the test
no you couldn't unless you made the new test accept tests
Ok I see
I'm still not sure jinja template filters are fundamentally different from lambas though. It's just that you have a limited number of lambda functions you can call
I think that's why it's a bit difficult for me to see the limitations
they are different as in they are constrained by what you can use. It's not a developed set of rules like lambdas where you can map things and retain the original object.
I understand and agree with the first sentence, not sure about the second. But my experience with this is more in java (streams) than python
But I assume the underlying concepts are still the same. In a stream you run into this same problem where you only have what made it past the last map() or filter()
In jinja it seems like the select and rejects are like filters, but like you said they're just constrained
I mean like I get it, just saying that fundamentally they are the same so it's kinda hard to see where the limits are
Like saying, write some program, but you can't use the letter 'i' lol
what you aren't understanding is that it only runs functions, filters, and tests. It's not built into the language, so you can't use built in keywords like or and and while expecting them to maintain the proper order of operation.
well, you can expect the proper order of operation, but it's order of operation is arguments first, then function/filter/tests. Where lambdas execute the code with their own set of rules for order of operation
lambdas you're also defining a function to execute at that moment in time
where as jinja, everything is pre-defined
it's really apples and oranges.
Is it possible to make a icon a template like: {{ mdi:light }} - its for a lovelace card
@merry delta I converted your message into a file since it's above 15 lines :+1:
Did I post my code or question incorrectly? I'm not good on dicord
Hiw do I post a template that's above 15 lines and ask for help? I was told to goto discord for help? Sorry I am old and dumb
is the "if" statement in value_template working as you expect?
I don't know what phu: is, but I'm guessing some third-party icon library
I suggest putting the template in
-> Templates, seeing if it evaluates as you expect there, and debugging
there's nothing wrong with the syntax
The templates work in developer except I don't think it can debug the icons, and yes it's 3rd party icons but I also have tried with mdi
It only matters that it outputs the correct string
Well it's only putting out the else string I dunno why
Then it's not working ๐
The first and second templates are identical, so are both working or not?
Check the states in
-> States
It very well could be a problem with these binary_sensors. They say clear even when I am triggering them. So that what I need to figure out.
