#templates-archived
1 messages · Page 156 of 1
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
Just in case 😄
Hehe, the problem is complicated.
I have a script where people to resume Google Home Speakers after they have been interrupted
They can provide any service call in it which will be performed, and after that the previous stream (spotiy, tunin will be resumed)
For one specific case I replace the target with another one. That works fine, but it could be that the actual target has been provided under data.
So for that specific case I want to remove entity_id, area_id and/or device_id from data
Well, not so complicated in the end
I could possibly do something like:
{% set ns = namespace(s={}) %}
{% for item in service_call.get('data', {}).items() | list %}
{% if not item[0] in [ 'entity_id', 'device_id', 'area_id' ] %}
{% set add = { item[0]: item[1] } %}
{% set ns.s = dict(ns.s, **add) %}
{% endif %}
{% endfor %}
{{ ns.s }}
Jep, that works
Figured out how to do it with a filter as well:
{% set example = { 'a': 1, 'b': [2, 5], 'c': {'d': 4} } %}
{% set test = example.items() | rejectattr('0', 'eq', 'a') | list %}
{{ dict(test) }}
Hey everyone, I'm looking for assistance regarding a TTS automation. I currently have a sensor that tracks my sleep time and lists the state as 6:53 for example but when read it says 6 53 hours. Is there a template i could use to get it to read 6 hours 53 minutes instead?
without knowing where it's getting the "hours" from, I would do this:
{% set time = states('sensor.whatever').split(':') %}
{{ time[0] ~ " hours " ~ time[1] ~ " minutes" }}
Thanks very much Rob I appreciate that
That's come up with 6 hours 53 hours minutes, is there a way to remove the second hours mention?
no idea where it's coming from
Ah I see the issue. The problem was my original template i used to convert 413 minutes into hours, I removed the hours mention in that so your template only picks up the numerical values and its working now. Thanks again
@naive swan posted a code wall, it is moved here --> https://hastebin.com/onocujuser
Ugh i hit 15 lines only due to including the surrounding context 😄
What is the current state of your Fitbit sleep hours sensor in Dev Tools > States?
6:53, the template i used got it close to what i wanted then used robs to separate it into hours and minutes
What the error seems to be indicating is that when you split the Fitbit sleep hours state by : , the resulting list doesn't have an element in the 1th position.
This could happen if say the state is 'unavailable'
Are you getting the error now, when the state is 6:53?
Last even log showed the warning 13 minutes ago.
It looks to be that it's falling into an unknown state for a very brief time every so often
There's no drop outs on the original sensor its referencing so I'm unsure what's causing the template to do so
guys
is it possibly to somehow get which light toggled on a group
with a template ?
Yes, how would you like to use this information?
You can create an automation or trigger based sensor with the group turning on as the trigger. Then use a template to expand the group and determine which entities are on
When they are all on, the group itself was turned on, and not a single entity
i use the mushroom card, and i want to know which light in the specific group has turned on the light and show that on a card
Okay, so you want to use it in a template card?
If you need to know which entity turned the group on, I would suggest to create the trigger based template sensor.
You need to know the information at the time of the state change, not at the current moment, so you need to store it somewhere.
If you need to have it survive a HA reboot or a template reload, store it in an input_text using an automation.
Display the state of the sensor or the input_text in your card
Maybe trigger on the group turning on and off
The template can then be something like:
{% set group = 'light.your_light_group` %}
{% set member_count = expand(group) | list | count %}
{% set members_on = expand(group) | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') | list %}
{% if trigger.to_state.state == 'off' %}
Group is off
{% elif members_on | count == members_count %}
Group itself
{% else %}
{{ members_on | join(', ') }}
{% endif %}
@fallow ruin disclaimer: typed on mobile without testing
thnx i'm giong to try that
UndefinedError: 'trigger' is undefined
i'm really bad with templating @marble jackal
@fallow ruin The template relies on a trigger, it will only work when there is a trigger, and will therefore not work in the template editor.
You can add {% set trigger = { 'to_state': { 'state': 'on' } } %} at the top of the template editor to mimic it
@fallow ruin Or change the template to:
{% set group = 'light.your_light_group` %}
{% set member_count = expand(group) | list | count %}
{% set members_on = expand(group) | selectattr('state', 'eq', 'on') | map(attribute='attributes.friendly_name') | list %}
{% if is_state(group, 'off') %}
Group is off
{% elif members_on | count == members_count %}
Group itself
{% else %}
{{ members_on | join(', ') }}
{% endif %}
this works great, your a template king 😉
I get a Config error for this, however yaml-wise it is correct according to Yamllint. How should I create a templated open_cover: in my Template Cover?
open_cover: >
{% if is_state('cover.garage','closed') %}
- service: mqtt.publish
data:
topic: automation/xx
payload: garage
retain: false
{% endif %}```
```Invalid config for [cover.template]: expected dictionary @ data['covers']['garage']['open_cover'][0]. Got '{'. (See ?, line ?).```
Are there only 2 states possible? Is it ever unavailable or unknown?
Solved by creating a script, which includes a Choose action, and this script is used for open_cover:.
You can not put yaml in a template like that
Use a choose for something like this
Ah, should have read all posts
How do I check if a condition has ran in the past 5 minutes? My bedroom curtains are opening because my living_room curtains are opening, it detects motion because of this and that will trigger to open the bedroom curtains.
value_template: "{{ (as_timestamp(now()) - 60) < as_timestamp(state_attr('automation.open_curtains_living_room_right', 'last_triggered' )) }}?
Yep, that works!
That will be the last minute though, not 5
Yeh, used it to test it 🙂
What do you actually need to put into a template condition?
It right now gives me this error while testing: template value should be a string for dictionary value @ data['value_template']. Got None
The template is just this one line: {{ as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off"].last_updated) > as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off_2"].last_updated) }}
That line works fine in the Dev Tools template editor.
Random question. Can you do an if statement based on who the current user is?
You probably just need to surround it in quotes, but would otherwise need to see the whole thing
I can't seem to post screenshots here, but surrounding it in quotes makes no difference.
It's just a simple Condition, with Condition type set to Template, and the exact string up there in the Value template field
You could describe it, or actually post it
The text is the one above
Oh well
I don't understand what you're asking from me, sorry
{{ as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off"].last_updated) > as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off_2"].last_updated) }} is the text of the template
Post the whole damn thing. As text
heh
What whole damn thing? I'm making this script via the visual editor.
If there is a plain text representation of it, I don't know how to get it to show it to me.
Ah, seems like when I try to run it once, it shows up in the "Show Trace" section...
It's too long for Discord to let me send it, so here's a pastebin: https://bpa.st/UGNQ
Seems like the "Test" button is just straight up broken. The script seems to work fine.
as_timestamp(states.light.3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off.last_updated) ?
Can't do that because of the leading number
use single quotes?
It makes no difference. I tested that line in the Template-Editor in dev tools. I'm pretty confident it works fine.
The script also runs and behaves like I'd expect, so it seems to be working fine as well.
Just the "Test" button throws an error.
I wasn't aware you could rename them at that level? I gave them useful names in the UI
ah, you sure can... yeah, that sure makes things easier
pretty sure you can
Yeah, I never noticed that the Entity ID field was editable. I took them as device given
Press the 3 dots at the top right in the GUI, switch to YAML view and share the complete condition
Ahhh, that's good to know. Thanks
Just the condition out of it is:
- condition: template
value_template: >-
{{
as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off"].last_updated)
<
as_timestamp(states.light["3a_smart_home_de_lxn_2s27lx1_0_6ede69fe_level_on_off_2"].last_updated)
}}
The whole thing is what I already pasted on bpaste
Don't see any issues with it, besides that they are both datetime object which you can perfectly compare with each other without converting them to a timestamp
ah, that makes it quite a bit nicer
yeah, the whole script also works from what I can tell
Just the Test button doesn't like it. Or really anything I put in there
I think the Button just broken
I made this install literally today, so I couldn't tell :D
A popup error box with template value should be a string for dictionary value @ data['value_template']. Got None in it
Hmm, maybe a bug in that check button then indeed
At least this slight mess of a script seems to work. One button blinds control, yay
how do I get the area an entity is in? Sorry, derp, it's right in the docs
Ok, so I can pull a list of entities in my kitchen in, and I can get their friendly names and states, but how do I get their domain? ``` {% for foo in area_entities('Kitchen') %}
{{ state_attr(foo, 'friendly_name') ~ ' ' ~ states(foo) }}
{% endfor %}
from the entities
area_entities() returns complete entity_ids, including their domains
as just a string though, right?
I can parse the string, but thought there might be a cleaner way
entitied_ids are strings, yes
an entity_id like switch.fr_table_lamp is just a string
{{ "switch.fr_table_lamp".split('.')[0] }}
I'll give that a shot, thanks
Basically, I'm trying to make a template that for a given area will output a light icon if any lights in that area are "on", a door icon if any doors are "on" and a lock icon if any locks are "unlocked". Could I just do that with some kind of select?
those are three different things to output, but yes, that's much easier
{{ states.light|selectattr('state', 'eq', 'on')|list|count > 0 }}
or in your case, {{ area_entities('Family Room')|expand|selectattr('domain', 'eq', 'light')|selectattr('state', 'eq', 'on')|list|count > 0 }}
thanks!
that returns true if any lights in that area are on
selectattr is great.
it is
Why doesn't states.light|selectattr('area_name', 'eq', 'Kitchen')|list return anything? When I use states.light|selectattr('state', 'eq', 'on')|list I get a list that includes:
It shows as area_name as an attribute, but looks like I can't select for it
Got it! states.light|selectattr('attributes.area_name', 'eq', 'Kitchen')|list
Hi guys! I am using this in my scripts to define a few variables; all_lights: "{{ area_entities('Bathroom') | expand | selectattr('domain', 'eq', 'light') | map(attribute='entity_id') | list }}" lights_on: "{{ area_entities('Bathroom') | expand | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}" number_of_lights_on: "{{ lights_on | length }}"
they check out fine in dev_tools, but I get this error in the gui when the scripts are called;Invalid config for [script]: invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['variables']['all_lights']. Got None invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['variables']['lights_on']. Got None. (See /config/configuration.yaml, line 15). Invalid config for [script]: invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['variables']['lights_on']. Got None. (See /config/configuration.yaml, line 15).
I can't seem to find the issue. It complains on the 'expand' filter/command which is needed... What can I do?
No idea at all?
If what I have written above is not correct, can these values be retrieved in a better way, so that it don't generate an error when actually run?
Use expand(something) instead of something | expand
expand can not be used as a filter
Ah... Explains the error. Was confused because 'ha core check' found no issue, nor the 'check config', but will try this, thanks! 🙂
Yes, I did that, and in that it worked nicely, just not in the script later...
Btw, you can use your all_lights variable in all_lights_on
Hmm, indeed, that's strange
It does accept it in the template checker
Yes, but all in all, there's a lot that works really nicely these days, so I wouldn't complain... 🙂
I will have a further look and might create an issue if I get the same result
Great! Thanks for the help!
hi everyone! I have a little D1 mini with an ultrasonic sensor attached to measure the salt in my water softener. I am using update_interval: 3600s on the D1 but im wondering if there is a way for me to get the D1 to report every an average of say 10 consecutive measurements (maybe every 1s) to eliminate any errors?
not sure if this is a problem for a template?
ESPHome is a system to control your ESP8266/ESP32, with a native integration for Home Assistant.
You can find their documentation here, and get help with ESPHome itself here in the #diy-archived channel (#integrations-archived for the Home Assistant side integration with it). They also have their own Discord server too.
trying to do away with as many rest sensors to the instance /api as possible, (some historic background on this in https://community.home-assistant.io/t/template-to-display-loaded-components-on-ha-instance/114402/13) I was looking for a way to find the installed components (integrations) and checked https://next.home-assistant.io/docs/configuration/templating/#integrations. that doesnt seem to help yet though.
replacing my python script which does components = hass.states.get('sensor.ha_rpi4_config').attributes['components'] built on ```
- platform: rest
name: Ha Rpi4 config
resource: !secret resource_ha_rpi4_config
value_template: > #components|list|count}}
{{value_json.version}}
json_attributes:- components
- unit_system
- config_dir
can we not do this yet with the new integrations template options? or what am I missing. ;-/
Trying to create a template that checks if everyone is in bed. Got all the bed sensors in group.bed_presence and want to compare that to zone.home. so If 1 person is at home and 1 or more are in bed the sensor should be true. However if 0 people at home and 0 people in bed it should not be true.
I think i got the first part figured out, but not sure about the last part.
i got this now:
{{ states.group.bed_presence|expand|selectattr('state', 'eq', 'on')|list|count|int >= states('zone.home') | float }}
Any suggestions / ideas?
I spot something I did wrong too, 'expand' cannot be used as a filter (but does indeed work in the template checker). Have a look here #templates-archived message
add and states('zone.home') != '0'?
That works! {{ expand(states.group.bed_presence)|selectattr('state', 'eq', 'on')|list|count|int >= states('zone.home') | float and states('zone.home') != '0'}}
Thanks 🙂
help
Month:
value_template: {% if now().month() in (0,) %}Janeiro{% elif now().month() in (1,) %}Fevereiro{% elif now().month() in (2,) %}Março{% elif now().month() in (3,) %}Abril{% elif now().month() in (4,) %}Maio{% elif now().month() in (5,) %}Junho{% elif now().month() in (6,)%}Julho{% elif now().month() in (7,)%}Agosto{% elif now().month() in (8,)%}Setembro{% elif now().month() in (9,)%}Outubro{% elif now().month() in (10,)%}Novembro{% elif now().month() in (11,)%}Dezembro{% endif %}
now().month() counts from 1 to 12, not from 0 to 11
You could also do it like this:
{% set months = [ 'January', 'February', 'March', 'April' ] %}
{{ months[ now().month() - 1 ] }}
Add all the months of course, don't stop at April
You could also try {{ now().strftime('%B') }}
The latter was neat... Is there anything to consider when choosing method, or are they equally good?
Well, the list with month names always gives the same result, the latter depends on language settings
**{{- d[0]}}:**
{% for i in d[1] if i.state in ['unavailable','unknown'] -%}
> {{i.name}}: *{{i.state}}*
{% endfor %}
{%- endfor -%}``` give me a nice ordered list of domains and their entities. It does however show the domain when there is no entity to list. Ive tried to set a count !=0 and even exclude some domains completely (if d not in ['alert','media_player','zone'], but that wont make a difference. Would appreciate some help to figure this out
wait, another go made this work: {%- for d in states|groupby('domain') if d[0] not in [ 'alert','media_player','zone'] %} so I only need to be able to check for 0 entities in a domain and deselect that domain
What if you used:
{%- for d in states|groupby('domain') if states[d[0]] | list | count > 0 %}
Or something like that
Well, that won't work for domains with only entities with state unknown or unavailable
Hi,
Have several sensors that measure outdoor weather, have a template that takes avarage.
The issue is that if one sensor is unavaliable then the average is wrong (in case of 2 sensors it will be just half of the real number).
What is the best approach to solve this issue, ofcourse I could do 'if then', but when there are a lot of sensors construction can get pretty big. Please advise. Thanks!
value_template: >-
{{ (( (states('sensor.filtered_outdoor_humidity_1') | float) +
(states('sensor.filtered_outdoor_humidity_2') | float)
) / 2) | round(0)
}}
thanks
@marble jackal posted a code wall, it is moved here --> https://hastebin.com/xafiqasiqe
Whoops, copied in the original post and forgot to remove it. This is what I wanted to post
I don't think that won't solve the issue.
This might:
{% set sensors = 'sensor.filtered_outdoor_humidity_1, sensor.filtered_outdoor_humidity_2' %}
{{ expand(sensors) | map(attribute='state') | select('is_number') | map('float') | average }}
Copying part of a message is a pita on discord mobile
Maybe combined with an availlibility template that at least one sensor should be available
I'm trying to add a condition to an automation like this:
condition: template
value_template: '{{ states.person|selectattr("state","equalto","home")|list|length > 0 }}'
but i am getting: template value should be a string for dictionary value @ data['value_template']. Got None
I also tried:
condition: template
value_template: '{% states.person|selectattr("state","equalto","home")|list|length > 0 %}'
but that gives me: invalid template (TemplateSyntaxError: Encountered unknown tag 'states'.) for dictionary value @ data['value_template']
Could someone help me out?
the second doesn't output anything, so it won't work. the first looks fine, and I suspect that the UI editor is hosing it up somehow
I am using the "edit as yaml" function if that matters here
I also tried
condition: template
value_template: >-
{{ states("sensor.schlafzimmer_sensor_temperature") | float >
states("sensor.openweathermap_temperature") | float }}
which i need for another automation, but i still get
template value should be a string for dictionary value @ data['value_template']. Got None
hey, how do i update a dict entry?
{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'märz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
i want to update the month of mai with 110 in this example
you can't directly. you have to create a new dict with a different key/value
I give up. I can't figure out how to do that in Jinja. Perhaps somebody smarter will come along...
I have an NFC tag and i want only the device that scans it to get the notification. Is there a way to do that?
right now, the "notify" trigger is sent to a specific device.
so you have a bunch of android devices and you need a template to divine which one of those been scanned
description: ''
trigger:
- platform: tag
tag_id: 80520be9-7d5d-490e-98ff-e08e878ae5d8
condition: []
action:
- service: notify.mobile_app_schwiingmobile_s22
data:
message: command_activity
data:
channel: com.google.android.deskclock
group: >-
android.intent.extra.alarm.LENGTH:2700,android.intent.extra.alarm.SKIP_UI:true
tag: android.intent.action.SET_TIMER
mode: single
This is my automation thus far.
@odd crystal posted a code wall, it is moved here --> https://hastebin.com/ijubaqayut
However, this says that regardless who scans my tag, it'll notify schwiingmobile_s22
i want it to notify phone_that_scanned_my_tag
hmm maybe you could do it with a helper as well, but I believe a template would be the cleanest looking way (which I don't know)
never used templates before. i wouldnt know where to start
something like a condition?
via a helper, you'd have to set it to choose from a list of devices
from a dropdown list
how do you use helpers in automations?
it's like any other sensor basically
is it a condition? action?
only you change the value manually (or via automation)
no, it's an entity
which changes value based on what you give it
sorry, what category is it under in the automations UI
ah, not automations. separate "helpers" i see.
it would even be OK if i had 2 automations
one for each device
"if android_ONE, do X"
"if android_TWO, do Y"
i just dont know how to set that condition
you can have a lot more, there's no shortage of space or computing for autos afaik
huh?
ok, so at this point no one has answered us, you could ask for the template again tomorrow
we go back to #automations-archived sorry for the run around
np
I am cross posting this with #frontend-archived because I am not sure it belongs there or in templates
I have an attribute with a datetime in it, which I want to display on a markdown card. The attribute looks like this timestamp: '2022-04-04T03:20:00+00:00' I want to display it in local time and don't need anything other than the date, time is not needed. Currently in the markdown card it has "The last update was at {{package.timestamp}}" But of course that displays the whole ugly thing in UTC. I have pored over the template docs for quite some time and can't seem to get it right.
{{ ("2022-04-04T03:20:00+00:00"|as_datetime|as_local).date() }}
-> 2022-04-03 for me
might not need the as_datetime if it's already a datetime
why does state_attr yield additional brackets and hypens in the result when there are none. I have an attribute on a sensor that gives me a url but it spits that result in ['/some/url']
maybe it's really a list of 1 item
it is, but I don't know why it's doing that
was an easy fix but took me forever to catch it lol
Thank you, you certainly pointed me in the right direction. I ended up with {{(package.timestamp|as_local).date()}}
it was a custom addon to the IMAP, maybe cause it just adds to the existing rather than replacing it is why the additional attributes was list
Just an additional question if you have time. Where is .date documented?
it's a python method for a datetime: https://docs.python.org/3/library/datetime.html
Jinja uses Python data structures and you can use their methods
🙂 thought it was probably something like that!
And now I have made it even better with strftime, you made my day!
You can do it like this. It will also keep the months in order:
{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'märz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
{% set ns = namespace(paid={}) %}
{% for item in paid.items() | list %}
{% if item[0] == month %}
{% set ns.paid = dict(ns.paid, **{ month: x }) %}
{% else %}
{% set ns.paid = dict(ns.paid, **{item[0]: item [1] }) %}
{% endif %}
{% endfor %}
{{ ns.paid }}```
Well, yeah :). I wasn't going anywhere near that 🙂
thanks alot 🙏
hey how would I take a template from a history_state and multiply it by a constant to get a sensor registering a kWh unit_of_measurement?
the history_state is 1h over a duration of 365.25 days
right now I have:
- platfrom: energy
id: heating_oil_usage
unit_of_measurement: 'kWh'
value_template: {{ states('sensor.hourly_furnace_runtime') * 33.410107 }}
states are always strings, so you need to cast it to a float and you need to place quotes around your template if you use a single line
so {{ states('sensor.hourly_furnace_runtime') | float * 33.410107 }}
And quotes around it
or {{ parseFloat(states('sensor.hourly_furnace_runtime')) * 33.410107 }}
I'm getting: 2022-04-11 01:36:48 ERROR (MainThread) [homeassistant.bootstrap] Failed to parse configuration.yaml: invalid key: "OrderedDict([("float(states('sensor.hourly_furnace_runtime')) * 33.410107", None)])"
it seems to be casting my float back to a string...
What is the complete code you gave now for this sensor
BTW, you could also use this more simple version which will put the month (mai) at the end of the dict
{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'märz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
{{ dict(paid.items() | rejectattr('0', 'eq', month) | list, **{ month: x }) }}
Scratch all that, this works and keeps the order intact
{% set month = 'mai' %}
{% set x = 110 %}
{% set paid = {'januar': 85,'februar': 85,'märz': 85,'april': 85,'mai': 0,'juni': 0,'juli': 0,'august': 0,'september': 0,'oktober': 85,'november': 85,'dezember': 85} %}
{{ dict(paid, **{ month: x }) }}
any Idea for the energy sensor? I just tried {{ float(parseFloat(states('sensor.hourly_furnace_runtime')) * 33.410107) }} and its still going into safemode
I told you 2 times now that you need to place quotes around your template
quotes outside the curly braces?
- platfrom: energy
id: heating_oil_usage
unit_of_measurement: 'kWh'
value_template: "{{ float(states('sensor.hourly_furnace_runtime')) * 33.410107 }}"
Yes
Otherwise it will treat it as a dict
thanks, I didn't register that when you said quotes I thought you meant around the float method
Or use the multi line format as you did in the other template (using >-)
@marble jackal do you know why the id / entity_id does not appear in developer tools under states?
maybe it should be entity_id
Can't find any docs on this platform energy sensor
thanks, this is getting closer (added the counter to check if that works as expected): {%- for d in states|groupby('domain') if d[0] not in ['alarm_control_panel','alert','automation', 'counter','media_player','proximity','scene','zone'] %} **{{- d[0]}}:** *({{states[d[0]] |selectattr('state','in',['unavailable','unknown']) |list|count}})* {% for i in d[1] if i.state in ['unavailable','unknown'] -%} > {{i.name}}: *{{i.state}}* {% endfor %} {%- endfor -%} but yes, it still lists the domains with count 0
btw, this is the markdown version hence the **, * and > and specific whitespace killers
content: >
{%- for d in states|groupby('domain') if
d[0] not in ['alarm_control_panel','alert','automation','button',
'counter','media_player','proximity','scene','zone'] and
states[d[0]]|selectattr('state','in',['unavailable','unknown'])|list|count != 0 %}
**{{- d[0]}}:** *({{states[d[0]]
|selectattr('state','in',['unavailable','unknown'])
|list|count}})*
{% for i in d[1] if i.state in ['unavailable','unknown'] -%}
> {{i.name}}: *{{i.state}}*
{% endfor %}
{%- endfor -%}``` does the job 😉
tidied that up a bit:```
{% set x = ['unavailable','unknown'] %}
{% set exclude_domains = ['alarm_control_panel','alert','automation','button',
'counter','media_player','proximity','scene'] %}
{%- for d in states|groupby('domain') if d[0] not in exclude_domains and
states[d[0]]|selectattr('state','in',x)|list|count != 0 %}
**{{- d[0]}}:** *({{states[d[0]]
|selectattr('state','in',x)
|list|count}})*
{% for i in d[1] if i.state in x -%}
> {{i.name}}: *{{i.state}}*
{% endfor %}
{%- endfor -%}```
can you explain what **{{- d[0]}}:** does ?
more specifically the asterix
as I said above, thats a markdown code , see https://www.markdownguide.org/cheat-sheet/
missed that...thanks
but there's 1 spot in the template I can leave the [0] out I guess, in d not in exclude_domains. no, thats not true, need that for the domain filter too..
yeah, you can do very nice things with that, but this is my default markdown toolset, bold, italic and paragraph. Most other things I tend to use card-mod for, although one can also use the # header options with good result
and you need to test it in the frontend, because dev template only creates the correct template result, but not the formatting...
sweet 👍
yeah, sweet indeed, what isnt so sweet though, is when editing these heavier templates in dev tools and during editing the interpreter tries to create an output, my Ping sensors always go down. and because there is a flaw in that integration, if 1 goes down they all go down... and set off all kinds of alarms in the home, checking to see if my essential hubs are down 😭
as for the d[0] functionality, it takes the first item in the list of the domain object, you can see for yourself when you do {%- for d in states|groupby('domain') %} {{- d}} {% endfor %} instead.
'{{ iif(states.input_number.volume_level.context.user_id) }}'
I used this in a condition til now to only make an automation trigger when that input is changed manually by me
but what if I needed the opposite
for the input to only trigger when changed automatically by automation?
Easiest way is to flip an input boolean as the first service of your action. Then you can use the input boolean in the condition of other automations. Then when it makes sense, turn the input boolean off
I get notifications when my thermostat mode and temp change, but only if changed manually, not by an automation.
cheers
I will experiment with this
but isn't there also a template
like to change context.user_id to something denoting an auto action
i.e. not by user
'{{ not iif(states.input_number.volume_level.context.user_id) }}'
Or '{{ iif(states.input_number.volume_level.context.user_id, false, true) }}'
cheers
I have a template binary_sensor that is based on two template sensors. I'm having trouble getting the binary_sensor to reevaluate when I change the templates for the template sensors and then reload template entities.
when I run the template in developer tools, it's showing the expected value. So it must just be something missing from the triggers on the template binary_sensor.
remove the trigger from the binary_sensor
then it will be state based
Not sure if you need triggers for the other ones as well
I need the triggers on the binary sensor because I want it to trigger at the time seen in the other two sensors. There will not be a state change at that time.
Unless there's another way to do that?
that template will only update when you change the state of your entities, when the time occurs, and restart
if you want it to update on a period in relation to now, you need to add a time_pattern trigger
I added a every 5 seconds time trigger and that works just fine, but that's less than ideal.
remove tht trigger completely, you don't need it
a template like that, with removed triggers, will only update once per minute
shouldn't this pick up the reload of the template entities:
- platform: event
event_type: event_template_reloaded
@mighty ledge because of the now() it'll update every minute?
I guess that's wasteful, but, better than it not updating at all.
your updating options are: Triggers or entities inside the template without the triggers
right. I was trying to fine tune the triggers to cover all the cases where it should update. But, catching the reload of template entities themselves seems to be the issue.
the template reload occurs before the templates reload
so, it never effects template sensors itself
ugh.
This should work fine as well https://www.codepile.net/pile/2g5Nn6eQ
I'll be honest, I don't get your templates for the out_front_lighting_start and end
I just tried that, and it does work... right now? But my worry is that this part will be missed:
# - platform: time
# at: sensor.out_front_lighting_start
# - platform: time
# at: sensor.out_front_lighting_end
But I guess it'll trigger within a minute according to @mighty ledge, so that's probably good enough.
what's this trying to do?
the whole setup
just have a 2 hour period before and after sunset that's on for 2 hours?
set a lighting window for outdoor lighting. 2 hours before sunrise through 2 hours after sunset. But also with literal max/min times. So... if two hours before sunset is 8am, then it still starts at 6am.
I want the lights on during the "dark" times when people are awake, but also late enough/early enough that it ALWAYS includes the times we typically leave the house or get home.
ok
you can change
{%- set window_start_max = (next_rising.year|string + '-' + next_rising.month|string
+ '-' + next_rising.day|string + ' ' + '06:00:00')|as_datetime|as_local
-%}
to
{%- set window_start_max = today_at('06:00') %}
unless it's tomorrow
no but you could still change it
{%- set window_start_max = next_rising.date() ~ ' 06:00:00')|as_datetime|as_local -%}
what does the "~" do?
adds 2 objects together and ensures both sides of the addition are strings
I still think there's room for improvement in that, but I just woke up and I'm not thinking straight
without the triggers, all three of these are evaluating every minute (since they all include now()). So I can probably get rid of this block now too:
{%- if now() + timedelta(days=1) < window_start -%}
{%- set window_start = window_start - timedelta(days=1) -%}
{%- endif -%}
if you get rid of now that template won't resolve every minute
.... blink.... blink.... of course. it's early for me too....
SO, you're just trying to make a binary sensor that is on or off for your timeperiod?
yes.
okay. thank you!
So to clarify, you're trying to show a window between todays current rising and falling? You remove the day when it falls into tomorrow because it's past that point in time?
Basically, looking at that code, it should never have tomorrows date even when next rising is tomorrow
I had to remove the day because if it evaluated after the sun set, but before the window elapsed, next_setting was tomorrow.
ok
so to reiterate, your goal is to always have a timestamp for today, and you really don't care about tomorrow
endgoal is to just have an on/off for todays timespan
correct. IDEALLY as soon as the window elapsed the values would be set to to tomorrows information. But, if that happens at midnight, that's fine too.
yes.
right, but
"window elapsed the values would be set to to tomorrows information"
doesn't really need to happen
as long as it happens before the next window starts, it's fine.
ok
yeah. that part doesn't mater, I don't think, if it's evaluating every minute.
though... maybe it still does. sun.sun will show tomorrows times as soon as the rising/setting event for today has passed. If it evaluates every minute, then on the next evaluation after sunset, both rising and setting times will be tomorrow and the current time will no longer be "in the window" even though I would still want it "on".
subtracting the day brings it back to today's times (though, technically, not 100% accurate since sun rise/set times are slightly different every day... but it's close enough for this purpose. I imagine there might be some weird case around start/end of daylight savings time but, that's fine).
If I didn't care about the 06:00 and 21:30 max/min times, how would I create a sensor that was always set to 2 hours after today's sunset? Because, if I can make that, I can use another template sensor to handle the min/max cases based on the time produced by that.
so this is what I would do
- binary_sensor:
- name: past_rising
state: >
{%- set next_rising = state_attr('sun.sun', 'next_rising')|as_datetime|as_local - timedelta(hours=2) -%}
{%- set offset = timedelta(days=1) %}
{%- set next_rising = next_rising - offset if next_rising > today_at() + offset else next_rising %}
{{ now() > min(next_rising, today_at("06:00")) }}
- name: before_falling
state: >
{%- set next_setting = state_attr('sun.sun', 'next_setting')|as_datetime|as_local + timedelta(hours=2) -%}
{%- set offset = timedelta(days=1) %}
{%- set next_setting = next_setting - offset if next_setting > today_at() + offset else next_setting %}
{{ now() < max(next_setting, today_at("21:30")) }}
- name: out_front_lighting
state: >
{{ expand('binary_sensor.past_rising', 'binary_sensor.before_falling') | selectattr('state','eq','on') | list | length == 2 }}
that would resolve properly at all times, including reload
00:00:00
so, the only thing is, it wouldn't fire perfectly at 2 hours before next setting etc
it'll be on the minute
so if the setting falls at like 24 seconds, it'll turn on at the following 0
yeah. that's good enough for this case.
this is better, because at least only two of them evaluate every minute, where, my version had all three going every minute.
you could easily turn it into 1 template
yeah. but it'd be the same amount of "work" for HA every minute, right? I'd still need all the same computation to happen.
- binary_sensor:
- name: out_front_lighting
state: >
{%- set offset = timedelta(days=1) %}
{%- set next_rising = state_attr('sun.sun', 'next_rising')|as_datetime|as_local - timedelta(hours=2) -%}
{%- set next_rising = next_rising - offset if next_rising > today_at() + offset else next_rising %}
{%- set next_setting = state_attr('sun.sun', 'next_setting')|as_datetime|as_local + timedelta(hours=2) -%}
{%- set next_setting = next_setting - offset if next_setting > today_at() + offset else next_setting %}
{{ min(next_rising, today_at("06:00")) <= now() <= max(next_setting, today_at("21:30")) }}
I have plenty of CPU to throw at it. So it shouldn't be an issue. I just like to optimize as much as I can upfront because once it's working, I'll forget about it.
right.
it's up to you
I personally make everything an 'on/off'
or I make everything an event
on/off is what I aim for too, usually. In this case, I made timestamp sensors because it helped me to see the values for debugging.
So, have you used this all year?
because I see potential issues with this and your old template
I've not used it at all. I am currently doing this same thing using an entirely different method (pyscript code) and I'm trying to move it into something more standard just to see if I can.
so you haven't ran into an issue when the days are shrinking in your pyscript?
no.
so........ the days shrink by 3 minutes
so you could have a scenario where you turn on, then immediately turn off after next rising changes to tomorrow, and then it'll turn on again
trying to see that corner case myself in this. I think I don't have that issue with the pyscript code because I'm computing rise/set using the astral package instead of relying on data from sun.sun.
yep
ahhh. i see the issue with shrinking days now. grrr.
the only way around it that I can see (and I don't like it) is to use two input_datetimes and an automation that triggers at midnight. In that automation, set the datetimes to the rise/set times in sun.sun at that exact moment. Then use those input_datetimes for all the computations in this.
If I use two template sensors that trigger at midnight, when I reload template entities, they will be "unknown" until midnight occurs, right?
yeah. but... even then, how would you cover everyone's weird use cases? lol. Does resetting the values in sun.sun only at midnight work for everyone? what about people with really long days and/or really long nights?
by separating todays rising and tomorrows rising
oooh. yeah. that would do it.
it's done in sun2, a custom integration
looking at that now.
which is also more accurate
Is there and advantage of using {{ expand('binary_sensor.past_rising', 'binary_sensor.before_falling') | selectattr('state','eq','on') | list | length == 2 }} instead of {{ is_state('binary_sensor.past_rising', 'on') and is_state('binary_sensor.before_falling', 'on') }}
the biggest advantage, at least for me, is that I learned something new in jinja templates. 🙂
expand a really nice function 🙂
okay. now I have sun2. this should make it a lot easier.
Yeah, sun2 is nice and it's more accurate. Although there was changes that made sun.sun as accurate as sun2
awhile back
just having the today/yesterday/tomorrow bits is helping a lot here.
does today_at() in a template sensor cause evaluation every minute?
petro 👍
2022-04-11T12:51:07+00:00 this is the actual state for the entity im trying to automate. This is the template im using: {{ ( now() - states('sensor.thegoat420_lastactive') | as_datetime).total_seconds() >= 9 }}
it doesn't trigger, condition comes back as false
the last active sensor is a user input sensor for windows10
it resets each time I move the mouse
in dev tools the stamp shows as above, but in the UI it looks clean, always shows how many seconds from the last time I moved the mouse or whatever
presumably, when it updates, it's set the the current time. which would be the same as now(). Since the condition only evaluates after the trigger, it will always be == 0
You could make this template be the trigger, but, templates with now() are only evaluated every minute, so, it wouldn't trigger at exactly 9 seconds.
instead, you should set "mode" to "restart" and add a 9 second delay to the top of the action.
if you use the delay I mentioned, it'll happen exactly 9 seconds after thegoat420_lastactive is updated.
hi guys i hope i write in the right place..
can some one explain me how to configure a switch as a light from .yaml?
my configuration is working whit no problem but i would love to have it set as a light instead as a switch
I dont know from yaml but you can use the helpers tab
i know that but if its possbile from yaml that will be amazing 🙂
mostly. you don't need the condition at all any more.
it triggers, yes. But the bathroom_fan doesn't toggle because 9 seconds haven't elapsed before it triggers again.
just for the record, the 9 seconds and the switch are just there until I can see it working then I can change the timing and device
it's not a "simple" yaml to make a switch look like a light. Using the helper does all the work for you. But, if you want to go down that road anyway, you're going to need a "light" template.
if you want to keep it from triggering, you can do this instead:
trigger:
- platform: state
entity_id: sensor.thegoat420_lastactive
for: 9
and then get rid of the delay (and leave the condition or get rid of it, it won't matter)
no, the point of making the automation is I want it to work
haha. no. I mean... it will work with the "for".
ok Im trying but just so you know what you said last time did happen, the fan did turn on
you have a sensor that basically updates CONSTANTLY when it's being used, and doesn't update at all when the thing isn't being used. So, with the trigger above, you're just waiting for it to stop updating for 9 seconds. I think that does what you want.
the fan turned on, after 9 seconds, right?
lemme check
if you do the "trigger" with "for" like above, you don't need the condition, the delay, or the mode: restart. You're just going to wait for it to stop changing for 9 seconds. This assumes that it changes constantly (at least once every 9 seconds) when it is in use.
trigger:
- platform: state
entity_id: sensor.thegoat420_lastactive
for: 9
action:
- service: switch.toggle
data:
entity_id: switch.bathroom_fan
This means, wait for the state of thegoat420_lastactive to change and KEEP THAT VALUE for 9 seconds, then toggle the fan.
do you know wehre i can find an example?
if the value changes after 5 seconds, say, then then it doesn't trigger.
the only thing I know of is the light.template docs https://www.home-assistant.io/integrations/light.template/
your "turn_on" will be "switch.turn_on". your turn_off will be "switch.turn_off". you can do nothing with set_temperature, set_color, set_white_value, etc... since you don't actually have a light. value_template wil have to look at the state of the switch, etc, etc.
In an old post from petro, there is this:
light:
- platform: switch
name: Light Name
entity_id: switch.name_switch
- platform: switch
name: Light Name 2
entity_id: switch.name_switch_2
Not sure if this syntax still works, but you could try it.
Hi, I want to put a service in an automation which turns on input_booleans with a specific entity_id and a specific state.
data: {}
target:
entity_id:
{{states.input_boolean |selectattr('object_id', 'search', 'is_fixkosten')|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}
``` like this, but what is the right synstax?
is "is_fixkosten" part of an entity_id?
yes
change "object_id" to "entity_id", I think. and it works?
{{states.input_boolean |selectattr('object_id', 'search', 'is_fixkosten')|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list }}
this gives me the right entity_ids I want to change. But I dont know how to put this statement into a service call
service: input_boolean.turn_on
data:
entity_id: "{{ blah blah blah|list }}"
thank you 😄
you can probably do it with "target" too... I'm just not sure because I rarely use it.
target works as well
just not:
service: input_boolean.turn_on
entity_id: "{{ blah blah blah|list }}"
That field doesn't accept templates
Hey guys, im have some hard times with one of the param of a template cover. Im using shelly for controlling my covers, and im trying to do a template cover, where the original cover entitys position 1-25% is defined as 1% in the template cover, and the 26-100 percent is the other 99. I need that because the shelly calibration is don't take in consideration the roller blinds holes (between the bars) that take some time to close.
So, my problem is that the set_cover position not working properly. With that config (in the next message) the slider (or simply call the service) act as the original cover. How should i change that to work with the positions i set in the template?
@acoustic fox posted a code wall, it is moved here --> https://hastebin.com/xolozagine
Is there/does someone have an example for a template sensor, which solves the same requirements, where I would use state for x minutes in an automation or delay_on in an binary template sensor? I want to set a state only when another criteria is in a certain state for x minutes.
You can use triggers with templates
Yes. Thanks. Perhaps my intention was not clear. I know this, could also use an automation or helper or variable, etc.
I was more interested in, how such things could be solved within a template. To learn and play around.
Maybe you aren't understanding me, you can use triggers with template sensors
Templates are limited to current information only. So you can only do so much with timing in templates
at one point I had a duration on one of those triggers but removed it in favor of something else
Otherwise you have to calc it yourself and hope your state didn't change over the duration you're checking against
Hi, is there a filter for this expression:
selectattr('state','eq','on') for 2 mins
? Thank you^^
hello, i have this template for a restful sensor
value_template: "{{ state_attr('sensor.cmi', 'Outputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join }} "
now some of these Value.Value are binary
i try do get the number 1 or 0 and make it a word, on/off
value_template: "{{ 'On' if is_state('sensor.cmi_xxx', '1') else 'Off' }}"
The second value template would work, however i dont want two sensors.
How would i combine the second template into the first one? I dont understand the jinja2 expressions, prob very easy if you know how.
Thanks
No, you will have to compare the last_changedobject of the entity with the current time as well
This should work | selectattr('state','eq','on') | selectattr('last_changed', '<', now() - timedelta(minutes = 2))
so i did some experimenting and came to this:
value_template: "{{ state_attr('sensor.cmi', 'Outputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join | replace('1', 'On') | replace('0', 'Off') }} "
Not pretty but functional, maybe someone can me give me something how to solve it different and more correct, for me to learn. Thanks 🙂
value_template: "{{ 'On' if state_attr('sensor.cmi', 'Outputs') | selectattr('Number', 'eq', 1) | map(attribute='Value.Value') | join == '1' else 'Off' }}"
thanks 👍
I'm trying to create variables in a script with the context id included, but i'm getting:
UndefinedError: 'context' is undefined
That's my code for the variables:
variables:
action_yes: '{{ ''YES_'' ~ context.id }}'
action_no: '{{ ''NO_'' ~ context.id }}'
Okay i found the problem
Quick question: I had this working last week, but I'm not sure if between updating to 2022.4 or me tinkering with the dashboard, something got tweaked somewhere.
I have an automation that calls a shell script that posts a sensor state to a slack channel:
service: shell_command.slack_topic
data: {{ states('sensor.weekly_special') }}
however, when I click Run Actions and view the trace, it's being replaced with
service: shell_command.slack_topic
data:
'[object Object]': null
Has anyone seen this before?
You need to surround the template in quotes
updated to
service: shell_command.slack_topic
data: "{{ states('sensor.weekly_special') }}"
which is then 'autocorrected' to
service: shell_command.slack_topic
data: '{{ states(''sensor.weekly_special'') }}'
and says "Error: Error rendering data template: Result is not a Dictionary"
Tried via yaml editor in the HA interface as well as editing via nano
Also, getting the right output via the template debugger under Developer Tools
Is there a template that would work to make a sensor showing how many minutes an entity has been in its current state?
Oh, you're also missing an actual key. And I don't think you can even do that. There's no indication in the docs
which docs are you looking at, perchance? It usedto work, I know that much. But it was probably somewhat hacked together at the time lol
data: is not a key, it's a dict, which contains key/value pairs
and it wouldn't be indented like that in any case
Hi all, struggling to create a value template for a sensor. the sensor scrapes a value from the web, and gets something like "Next Collection: 8 days from now on Thursday, 21 April 2022"
In the template editor in dev tools, I have:
{% set text = states.sensor.blackbin.state %}
{{ text.split(', ')[-1].strip() if ',' in text else text.strip() }}
which outputs the date part as a string. Im really struggling to understand how to convert this to a date in a value template
What is the output you're getting, and what are you trying to do with the result?
https://www.home-assistant.io/docs/configuration/templating/#time and strptime is likely what you want
the output from the template editor is a string, "21 April 2022". However, if I use that code as a value template in configuration.yaml, its empty
the result should be able to be referenced by an automation to remind me to put the bin out, so a date comparison
What's the full YAML for the template sensor
- platform: scrape
name: blackbin
resource: https://www.n-kesteven.org.uk/bins/display?uprnXXXXXXXXXXXX
select: "#content > div > div > div.bin-dates > div.bg-black.text-white.bin-black-next.bins-next.position-relative > p:nth-child(2) > strong"
value_template: >-
{% set text = states.sensor.blackbin.state %}
{{ text.split(', ')[-1].strip() if ',' in text else text.strip() }}
You are referring to the same sensor right? That won't work
Yes, Im finding this all a bit confusing! Not great with templates, and I found the docs didnt seem to help me understand it much 😦
Guys, my goal is to use 2 conditional cards to show either "Switch on server using WoL" if off, or "Show server stats from mqtt json" if on. Issue is how to determine "is on". My thoughts were that since I include the date time stamp in my sent mqtt json, I could do an "If now() > last received json (MyServer/timestamp + 10 minutes), then the server is off" Time stamp is in the format now.strftime("%Y-%m-%d %H:%M:%S"). Anyone want to point me in the direction of the jinja to put that into a template binary sensor?
Remove the {% set text %} part and replace text with value
Assuming the part after select: is correct
I have this now
value_template: >-
{{ value.split(', ')[-1].strip() if ',' in text else text.strip() }}
which gives me a state of "unknown"
oops typo.. i ll try again
ok, I now have a state of "Next Collection: 8 days from now on Thursday, 21 April 2022"
using
sensor:
- platform: scrape
name: blackbin
resource: https://www.n-kesteven.org.uk/bins/display?uprn=XXXXXXXXXXX
select: "#content > div > div > div.bin-dates > div.bg-black.text-white.bin-black-next.bins-next.position-relative > p:nth-child(2) > strong"
value_template: >-
{{ value.split(', ')[-1].strip() if ',' in text else value.strip() }}
scan_interval: 86400
right, missed a "test" in the middle, its now returning a state of "21 April 2022"
That was the idea right?
I need to have a device class of timestamp somehow
customize.yaml
could you expand on that please? I now have a sensor, with a state that is a string containing the date, how do I convert that to a timestamp?
By default, all of your devices will be visible and have a default icon determined by their domain. See customizing devices for how to change that.
see manual customization in that link
that link does not explain how to change from a string to a timestamp
How can I use a template in a payload for an MQTT switch? This, for example, is just sending the literal string rather than interpolating the payload:
payload_off: >-
{"value": {{ 1 if is_state('switch.charger', 'on') else 4 } }}
Your closing curly brackets do not match the opening brackets
Sorry, typo in my white-spacing
Should be:
payload_off: >-
{"value": {{ 1 if is_state('switch.charger', 'on') else 4 }} }
That looks better already
Well, maybe, but it doesn't work 🙂
What's the format of your time string then?
"21 April 2022"
Does it work in
> template?
You have to use strptime to convert that to a datetime https://www.strftime.org
Have tried:
{{strptime(states('sensor.blackbin'), '%d/%m/%Y')}}
which still returns a string of 21 April 2022
I though %m would change April to 04
do you have / in your string "21 April 2002"?
||you don't||
No, I also tried
{{ strptime(states('sensor.blackbin'), "%d %m %Y") }} which gives the same output
Are you doing this in the scrape sensor itself?
at the moment, Im doing it in Devtools - Template
OK, and what does https://strftime.org say for converting something to April?
so the scrape sensor alread has the value 21 April 2022 as the state
%m 09 Month as a zero-padded decimal number.
and is the word April 04?
the word is just april, I thought it would change it to 04
so what %<letter> gets you the word April?
you're converting your String to a datetime object
%Better use something else then
strptime takes the string and format and uses the format to convert the string
so you're saying convert a 04 month when you're providing a word month
ah ha! {{ strptime(states('sensor.blackbin'), "%d %B %Y") }} now give me 2022-04-21 00:00:00
🎉
just need to figure out how to add that to the value tmplate, thanks guys 🙂
np
always helps to understand what strptime and strftime does
strptime takes a string and converts it to a datetime
strftime takes a datetime and converts it to a string
Yep, this is a whole new world to me
if it's any consolation, this is the hardest aspect of templates
20 years ago I would have been all over this. These days, the old grey matter is a little slow
You can replace the state_attr part with the current template, or create a variable using the current template and use the variable
No, I couldn't get it to recognize templates at all. I just rewrote it as a couple of binary sensors and template switches calling the mqtt.publish service and it works
ok sounds like I want to create a variable and use that
That would be easier to read
So basically:
{% set date = current_template %}
{{ strptime(date, format) }}
so like:
value_template: >-
{{ value.split(', ')[-1].strip() if ',' in value else value.strip() }}
{% set date = current_template %}
{{ strptime(sensor.blackbin, "%d %B %Y") }}
Nope
{% set date = value.split(', ')[-1].strip() if ',' in value else value.strip() %}
{{ strptime(date, "%d %B %Y") }}
Like that
Awesome, thanks 🙂
BTW, that whole if is not needed, you can just split something by , . It will do nothing if there is no , in it besides making it a list
{% set date = value.split(', ')[-1].strip() %}
{{ strptime(date, "%d %B %Y") }}
I have several occupancy sensors that appear as binary sensors, and the states are either "on" or "off". How can I make a text field show "Occupied" or "Unoccupied" based on that?
change the device_class to occupancy
you should be able to do that through the UI on the entity itself
Then in the UI, they will have the state Occupied or whatever the opposite is.
in the backend it will always be on/off
Ok so in Configuration > Devices & Services > Entities it's set to show as Occupancy, but when i set a Mushroom template card's text field to {{ states('binary_sensor.music_room_occupancy') }} it shows on/off
yes, because that's a template
templates access the raw, untranslated states
So not so good at templating, but trying to get better. Need som ehelp as I try t transition away from nodered. In nodered I had a function: msg.payload = msg.payload.split(" "); var index = msg.payload.indexOf('in'); // get index if value found otherwise -1 msg.payload.splice(index); msg.payload = msg.payload.join(" "); return msg;
I am basically trying to convert this into a template. Basically the task is to take a long sentence, find the word in, and splice it off from there. It seems jinja doesnt have a splice function? Right now I am basically at this:
{% set string = states('sensor.pixel_5_last_notification').split(" ") %} {% set index = string.index("in") %}
and unsure of how to chop off from index on before joining the remaining words back up.
any help would be appreciated
You want the part after "in"?
nah the part before.
I think I got it. Took a long time but this is the end state and seems to work:
service: tts.google data: entity_id: media_player.home_group message: >- {% set string = states('sensor.pixel_5_last_notification').split(" ") %} {% set index = string.index("in") %} {% set string = string[:index] %} {{ "Attention " + string|join(" ") }}
Yes, I thought after, so I was about to suggest this :)
{% set index = string.index('in') if 'in' in string else 0 %}
{{ string[index:] | join(' ') }}
ah that may still help make it cleaner though! Basically get notifications from my cmmmunities app when someone checks in, and same boilerplate
The if statement for index is to avoid errors in case there is no in in the string
Good thinking
and like the string[:index]|join.... wasnt sure how to join those two expressions
But you need to replace the 0 in that statement now, because you need the first part. However, if you replace it with -1 it will remove the last word
oh in should always be in there
You could do it like this:
{% set index = string.index('in') if 'in' in string %}
{{ ( string[:index] if 'in' in string else string) | join(' ') }}
figured with 0 there it means their whole notification boilerplate changed and would need to recheck it
oh I see
In all your notifications?
Ah okay
but better safe than sorry
strings come out like ['person', 'arrived', 'in', 'the', 'community', 'and', 'was', 'verified', 'and', 'entry', 'granted.', 'Please', 'note', 'that', 'guests', 'can', 'be', 'approved', 'on', 'multiple', 'accounts', 'and', 'may', 'be', 'here', 'to', 'see', 'another', 'resident.']
so i basically aim for google to say Attention person arrived
could someone explain what's wrong with how i'm using the "float" in this template? Everything calculates correctly in the developer tools templates, i get proper data in the sensor within HA. But I receive a warning in the log "Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.1"
value_template: >-
{{ (states('sensor.plug1_office_powerbar_current') | float) + (states('sensor.plug2_office_powerbar_current') | float) + (states('sensor.plug3_office_powerbar_current') | float) }}
i seem to have problems with so much of my templates revolving around floats
You need to specify a default value which will be used if the entity you're using the float filter on isn't available.
| float(0)
``` for example
Have you had any internet battles you’d like to talk about?
I hope you know, I have a million ips
"I own all the IP addresses in existence"
Careful though. He might be watching 
I am become Google
Nooo
{{ all_ipaddresses|random|torment(tediore) }}
Lol
to, ya know, bring it back around to the topic
Currently 'torment' will return 'me', however this template will fail to render in Home Assistant core 2022.1
I know, wtf man
I do find it funny/sad that this is how they've decided to use their time
To prove...that they can use a VPN? I guess?
Thanks! Will give that a go.
Has this topic been an ongoing thing for @buoyant pine ?
Thankfully not
Ok .. I thought I might have hit on a touchy subject 😛
Some troll got upset the other day and decided to take it out on me in the lamest way imaginable
Ahh .. so it was just purely coincidental that was asked after my inquiry …
I thought my question about floats was triggering haha
Haha, yeah sorry! Completely unrelated
No worries 🙂
trying to cut the template evaluation as much as possible in the system, I seem to have forgotten how we can prevent daily (or longer) templates to be calculated each minute... things like {{now().day}} ... what was it again please?
Templates with now() in it will be evaluated every minute
As now() will update every minute
yes, thats why I asked.... I have quite a few of those, that don't need that. Maybe its not such a huge burden on the system, but hey, the devil is in the details
I am trying to create three sensor
Invalid config for [sensor.template]: required key not provided @ data['sensors']. Got None. (See ?, line ?).
Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See ?, line ?).
getting this error
Check your indentation carefully. Error in line 2.
a specific reason you dont use the template: format, but the 'legacy style' platform: template?
you mean it should be ```
- platform: template
sensors:
template_grid_feed_in:
none, only I was trying to copy some old code
give the new style a try, its very nice
template:
- sensor:
- unique_id: new_years_day_countdown
name: New years day countdown
state: >
icon: >
check the config options in the docs. no more value_template, new is state: no more friendly_name, new is name:. and use a unique_id, so you can edit in the UI. Its all in the docs..... https://www.home-assistant.io/integrations/template/#configuration-variables
and don't place this in your sensor.yaml, place it in configuration.yaml or in a separate template.yaml for which you have to create an include in configuration.yaml
yes, considering he has utility_meter on the same level, that should be ok here though
I am including it in configration.yaml
I believe it was a simple as https://next.home-assistant.io/integrations/template/#trigger-based-template-sensors, and add the daystart trigger
yep, that was it, rate-limiting and updating on```
template:
- trigger:
- platform: time_pattern
This will update every night
hours: 0
minutes: 0 - platform: event
event_type: homeassistant_start - platform: event
event_type: event_template_reloaded``` beautifully
- platform: time_pattern
I do believe I found an issue because this template: state: > {{states('sensor.dag')}} {{states('sensor.current_day')}} {{states('sensor.maand')}} {{states('sensor.year')}} of which the second and last nested templates also use the same trigger base show 'unavailable'. see: https://github.com/home-assistant/core/issues/70036
Are you sure sensor.current_day and sensor.year actually exist? Maybe they _2 has been added for some reason (old version still existed when you updated the unique_id or something)
How it should be?
yes they are there, and show up correctly as individual sensors, its really surprising
one other problem template: ```
- unique_id: christmas_time
name: Christmas time
state: >
{% set today = now().day %}
{% set month = now().month %}
{{month == 12 and today >= 24 or month == 1 and today <= 2}}
somehow the nesting causes havoc
thats because you dont use the correct indenting, see #templates-archived message and sensors: should become - sensor: Be precise!
where i am doing it wrong?
- sensor:
template_grid_feed_in:
name: "Solar 2 Grid"
unit_of_measurement: 'W'
device_class: power
state: >
{% if states('sensor.grid_active_power') | int > 0 %}
{{ states('sensor.grid_active_power') }}
{% else -%}
0
{% endif %}
```?
try again:```
template:
- sensor:
- unique_id: template_grid_feed_in
name: Solar 2 Grid
state:
etc....
- unique_id: template_grid_feed_in
- sensor:
- unique_id: grid_feed_in
name: Solar 2 Grid
unit_of_measurement: 'W'
device_class: power
state: >
{% if states('sensor.grid_active_power') | int > 0 %}
{{ states('sensor.grid_active_power') }}
{% else -%}
0
{% endif %}
is this correct now?
looks fine
how to format the next two?
still
Source: config.py:454
First occurred: 2:20:18 PM (6 occurrences)
Last logged: 2:50:01 PM
Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 147). Please check the docs at https://www.home-assistant.io/integrations/sensor
Invalid config for [template]: [template_grid_consumption] is an invalid option for [template]. Check: template->template_grid_consumption. (See /config/configuration.yaml, line 161).
Invalid config for [template]: [unique_id:curent_solar_consumption] is an invalid option for [template]. Check: template->sensor->0->unique_id:curent_solar_consumption. (See /config/configuration.yaml, line 174).
Invalid config for [template]: [unique_id:curent_solar_consumption] is an invalid option for [template]. Check: template->sensor->0->unique_id:curent_solar_consumption. (See /config/configuration.yaml, line 175).
add a space after the :, remove the : at the end
unique_id: curent_solar_consumption
Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 147). Please check the docs at https://www.home-assistant.io/integrations/sensor this is about something else you didn't share in your codepile
Could also be about something in sensor.yaml
back to legacy format
you're quite accomplished in not following advise here.... I mean even the first one still has indents differently from what we suggested and what is in the docs..
btw, the 'next two' should be indentically formatted below the first one
What is wrong with these conditions?
- conditions:
- condition: or
conditions:
- condition: state
entity_id: binary_sensor.home_occupied
state: 'on'
- condition: and
conditions:
- condition: state
entity_id: binary_sensor.home_occupied
state: 'off'
- condition: trigger
id: door
I basically want it to be true only if home is occupied or (home is not occupied and the door got opened), but it triggers even if the home is occupied when the door is open
it looks exactly like this example in the documentation but with reversed or and and conditions
that's what you've told it to do
the first part of the "or" condition will allow the automation to proceed if you're home regardless of the state of the door
it won't even bother to look
oooh gotcha!
stupid me... 😆
thanks!
I think I'm gonna have to find a better way of creating automations because mixing triggers and actions make them sometimes very complex (maybe not much this one, but...)
might be easier to sort out in a choose:. There are several ways to handle conditions
- platform: event
event_type: homeassistant_start
Is there a way to tiggger x minutes after start?
And where is the difference between platform event with event_type homeassistant_start and platform homeassistant with event start?
trigger on start and add a delay?
Possible with a trigger template sensor? Didn't see this there, only in automations.
No, not possible for template sensor
You could add an uptime sensor, and trigger x minutes after the datetime in that sensor
Will try this. Thank you. Good idea, if not possible directly in a trigger. Or I will switch to an automation.
To be honest, currently I'm not seeing the benefit of a trigger template sensor compared to an automation. Is there any, so that has been intrupoduced recently?
a trigger-based template sensor returns a value that can be used elsewhere, where an automation can do a bunch of things based on a trigger & condition, but doesn't have a state other than enabled/disabled
template sensors don't do anything other than define their own state

Yes and (currently, until I perhaps get it) no. I compare it against a helper or a custom variable (instead of the template sensor), have the triggers as here and set the value via the different set_value services. Then it is the same, isn't it? But then with more options, like steps and delays before finally setting the value, log, and esp. trace.
Yes, you can emulate the functionality of a trigger-based template sensor with an automation & helper
And because of this my question above, where the benefit of the trigger based template is and so it has been introduced, if I have only limited options compared to the other way?
it's simpler and doesn't require another entity?
you should use what makes sense for you and your situation
Advantage of a helper is that it is persistent and will survive a reboot
I have this action
entity_id: media_player.shop
data:
message: The shop is now open.
Could I template the message? The reason is based on the time of day, would like to say good morning, afternoon, or evening. Just thinking out loud, is there not a sensor for that?
Event streams are really the only reason to use a template trigger sensor.
Yes, you can template anything in a data: block, and no there's no sensor for the wording that you're looking for
it's easy enough to write a template for that based on now().hour, though
Longtime I couldn’t find a usecase either, but next to the event capturing, rate limiting really is a true benefit.
What helper would i use if i want it to represent a true/false template?
The following template used to work, any idea what changed?
{{ state_attr('sensor.recycleapp_restafval', 'Days-until') }}
The state of the entity is here: 19 Apr
check for the various HA type events https://www.home-assistant.io/docs/configuration/events/#homeassistant_start-homeassistant_started and https://www.home-assistant.io/docs/automation/trigger/#home-assistant-trigger, and, tbh, I dont understand the difference either 😉 I only noticed the homeassistant_started (not _start) event yesterday.. what I did noticed was that my trigger based templates didnt update on the platform: event, homeassistant_start event, but did on the home-assistant-trigger. might be because of 123's deduction here: https://community.home-assistant.io/t/enhance-trigger-based-template-sensors/308037 ?
Check
> states if that attribute exists
Maybe they changed it to lowercase
input_boolean
Only over yaml tho, right?
That question doesn’t make sense.
I mean you can’t configure it from the ui
You can’t configure template sensors from the ui
yeah,but why is that different form the others, specifically homeassistant_started?
they're all core events, why cant we use those platform: events ?
One is fired from the event bus the other is probably handles before
They are 2 different integrations
tbh, I feel some sort of short explanation should be provided in the docs to explain the difference, and when to use which
Just use home assistant start
The other is an event
Use the event when you want 1 trigger and to parse through separate events
yes, and events are valid triggers, so should also be valid for trigger based templates ?
Yes
but they arent....
I briefly saw Arganto mention that (its gone now), and it is what I described in my issue
not sure I understand what you ask. when I used the platform: event on homeassistant_start, the trigger based sensor didnt work, using the platform: homeassistant, event: start, it works fine
I now see that homeassistant_start is too early in the process, and maybe should use homeassistant_started
And you’re 100% sure this event is real?
I would hope so ;-=) my system did startup ...?
Yes but that doesn’t mean that HA creates that event
yes, and thats why I hope some explanation will be offered on the whens and whys
its not very silly to expect an event homeassistant_started to be created on homeassistant start is it? If that cant be used, it should really be indicated as such, and what we Can use it for
exactly, as I quoted in my Community post, and yet we can not use it for the trigger based template
yes, it says we recommend
thats not the same as you can not use these events, nor does it explain why.
You probably don’t need to know why because it’s not meant for you to use
ah but there you go, I always want to know why....
Well how about just use what everyone tells you to use
i dont like to be told I dont need to know 😉
Read the code then
yes, I started to do that indeed, but couldnt find the definitive answer yet
It probably happens before templates are loaded therefor templates dont trigger off it
Because there probably is no definitive answer. The loading process is complicated. Homeassistant event triggers are ensured to work
So use them
yes, That was my conclusion too as reason for why nested templates in the trigger based templates remain unavailable. And ofc I did change to the platform: homeassistant after that. np. Its just that I dont grasp why the events are there in the first place
Otherwise read the code
I moved it over to #automations-archived to be not that o.t. here. But I'm with you. Even if it is recommended in the docs (what I read before) to use the other, it is not written, that the others don't work. A recommendation is for me the opposite from a must. Comparable to sufficient vs. necessary.
The others do work, but it's meant for integrations and the backend. The automation engine is not running when the event is fired, same with templates.
I just confirmed. so, use the other.
need some help with a template sensor. i'd like to make one show the difference between a static number, and a different sensor. so say {{ 100 vs (current sensor) = (+ or - value) }} . so 100 vs (current sensor at 50) = -50. or the opposite at 100 vs (current sensor at 150) = +50. hope this makes some sense lol. TIA
Umm why not just do {{ states('sensor.xxx') | int(0) - 100 }}?
cuase i was way over thinking it and trying to do it oposite lol
Is it critical to have the + if the difference is positive?
no
what does the int(0) define?
how do you link text in the black box to show correct format
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
Ensure that the value from the sensor is cast to an int. (0) is the default if the sensor's state can't be cast to int, eg. If sensor is unavailable.
or single backticks
- sensor:
- name: "titanoinvestment"
state: >
{{
( states('sensor.titano') | int(0) - 14000 )
}}
unit_of_measurement: "$"
oh nice
does that look ok in my template.yaml
Throw the {{...}} into Dev Tools > Template and see if any errors pop up. But looks legit from here.
Yes
Check
-> States for the list of attributes
You're probably looking for something like
{{ state_attr('sensor.smartdry','Humidity') }}
If this doesn't belong here, please advise.
Input Number Slider Question: I have a slider with a min/max/step of 0/70/1. I want the slider to show value in percent, where 0=0% and 70=100%, is this possible? if so, how?
Hmmm...
Out of all trigger based entities binary_sensor is the only one that retains it's state between reloads and restarts.
sensor|number|select defaults to unknown state and requires special handling.
Interesting, hope one day all will be able to retain state.
soon.... the PR;s for that are almost ready....
Hey folks. My old automation for forwarding persistent notifications to my phone hasn’t worked properly in a number of months. I can see that they are all listed in states.persistent_notification, but I need help fishing the details out. Does anyone have a template (or combination of templates) for grabbing the title and message for the most recent persistent notification?
what would be the wait template for my sensor so it doesn't move on to the next step of the automation until nothing on the cover has been triggered for 5 seconds? {{ is_state('cover.living_room_blinds_', '.........
the lag in web api for my blinds can be up to 10 seconds and sometimes the values arent sent to HA before the wait template has had a chance to see the new values
You can't use a wait_template for that
You would want wait_for_trigger with a state trigger with no to or from and a for:
Assuming that it is actually changing state and you want it to settle on a value
The 'nothing on the cover has been triggered for 5 seconds' is a little confusing
Can't you adda tag to each notification and track them using the tag?
im trying to count how many lights are on but somehow i can't get it to work
im using this code and did put ut in my sensor.yaml file
count_lights_on:
friendly_name: "# Lights on"
unit_of_measurement: 'on'
value_template: "{{ states.light | selectattr('state', 'eq', 'on') | list | count }}". ```
- platform: template
sensors:
count_lights_on:
friendly_name: "# Lights on"
unit_of_measurement: 'on'
value_template: "{{ states.light | selectattr('state', 'eq', 'on') | list | count }}"
Or using the new template integration:```
template:
- sensor:
- name: "# Lights on"
unit_of_measurement: 'on'
state: "{{ states.light | selectattr('state', 'eq', 'on') | list | count }}"
- name: "# Lights on"
(That goes in your configuration.yaml file, not sensors.yaml)
am trying it right now
such a hero
it works!
i see it also counts groups
can i also only count the lights
i created a light group in helpers
I don't think so. The light group creates a light entity. There's no way to distinguish it from other lights. I could be wrong. Petro or Fez might know a way.
To count lights which are on, and exclude light groups, note that groups have an attribute entity_id You can exclude the lights who have this attribute defined.
This attribute entity_id contains the members of the group
template:
- sensor:
- name: "# Lights on"
unit_of_measurement: 'on'
state: "{{ states.light | rejectattr('attributes.entity_id', 'defined') | selectattr('state', 'eq', 'on') | list | count }}"
or, if you use hue_groups or deconz_groups and want to exclude them as well
template:
- sensor:
- name: "# Lights on"
unit_of_measurement: 'on'
state: "{{ states.light | rejectattr('attributes.entity_id', 'defined') | rejectattr('attributes.is_deconz_group') | rejectattr('attributes.is_hue_group') | selectattr('state', 'eq', 'on') | list | count }}"
There is a missing pipe (|) between selectattr and rejectattr filter
Already fixed, nvm
I’m talking about the system generated notifications, like the discovery of a new device or an integration that needs to be reconfigured, etc.
i tried your code and it works perfectly! Thank you!😄
Having trouble understanding the regular expressions to get contains in a template. The state of a media player allows me to trigger based on song, artist, or album. The problem with this is it must be exact and so many artists/songs/albums have collabs in their names it's difficult to build effective triggers. Can somebody help me with a template that triggers when a song CONTAINS media_artist: Nicki Minaj
so it will still fire even if media_artist: Nicki Minaj feat. Drake, Lil Wayne & Chris Brown please?
"{{ 'Nicki Minaj' in state_attr('media_player.whatever', 'media_artist') }}"
You would
Wut?
This worked perfectly and now I've buried a ridiculous lighting easter egg deep within my HA. I was able to figure out the 'not' template to change everything back at song end
Hello, I'm new to templates and just wanted to know how I would get this value out of this sensor: https://imgur.com/Lab2IxN
it's hard to tell if your big yellow outline has obscured something
I don't think it has but here is the screenshot without: https://imgur.com/3F0LfCN
but {{ state_attr('sensor.xxx', 'entries')[0].content[0].value }}
ok, well, try that in
-> Templates
That worked perfectly thank you very much for your help!
What is the best way to dynamically create entities? Basically, I want to consume this api (https://api.ebongo.org/prediction?stopid=0245) and create an sensor.prediction_* for each prediction in predictions.
I have a pretty crude rest sensor that I'm using right now that just uses a single entity but I'd like to actually create different entities for each prediction. I also want to expand this to get the location of each vehicle from another endpoint.
hmm, might be able to do it with pyscript and hass.states.set(..., ..., ...)
Hello, i used a vibration sensor to try to "smartify" my dryer, problem is, i cannot figure out how to make an accurate template, this is what it looks like when it's on vs when off https://prnt.sc/tyqnNcdtKRJb
it fluctuates so much when working i cannot use it to create an automation, any idea how can i solve it?
yeah it turn on at 8:48ish
yeah but one sec is off and next sec on
https://prnt.sc/v3SA0fNYlm0X a close up of the actual sensor not the helper
just check when it's been off for >2 min
trying to make a script that changes defined hue light targets to a random color. dunno where to put random. could've swore it used to work as effect/light effect, but it doesn't.
Use service: light.turn_on with rgb_color: "{{ [ range(0,256) | random, range(0,256) | random, range(0,256) | random] }}"
Heyho. So I am trying to combine my automations into one right now. But its not really working how I thought it would work. The trigger is a template and the entity_id that triggered the automation should be used in the action. https://pastebin.com/d2jcLfry
As you use a template trigger, there is no trigger.entity_id variable
So is there a way to go about that?
Yes, add a trigger id and use the entity is there
Or add any other trigger variable as introduced in 2022.4
- platform: template
id: climate.comet_dect_3_wohnzimmer
value_template: >-
{{ state_attr('climate.comet_dect_3_wohnzimmer','current_temperature') | int(default=0) > 21 }}
Then use trigger.id instead of trigger.entity_id
Or, with these templates you can just use numeric_state triggers and then you can use trigger.entity_id
No template trigger needed
So just for my understanding for the next time I am doing something like that. First variant is just sending an id with it so it what triggered it. Second variant would be something like this?
- platform: numeric_state
entity_id: climate.comet_dect_3_wohnzimmer
attribute: current_temperature
above: 21```
trying to use the chat integration to let people know if they are free, dnd or busy based on the RGB Lites example:
rgb_color:
- "{% if color == 'red' %}255{% else %}0{% endif %}"
- "{% if color == 'green' %}255{% else %}0{% endif %}"
- "{% if color == 'blue' %}255{% else %}0{% endif %}" ```
changed it to
data:
option:
- "{% if roomstate == 'dnd' %}'DND'{% endif %}"
- "{% if roomstate == 'vrij' %}'Vrij'{% endif %}"
- "{% if roomstate == 'bezet' %}'Bezet'{% endif %}"
But that fails
Correct
.share the whole thing
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
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.
error is: Received invalid slot info for kamer: value should be a string for dictionary value @ data['option']
one of those three indeed
That's not how that works
When i set it to :
option: "{{roomstate}}" , it works, but i have to type the correct state
option: >
{% if roomstate == 'dnd' %}
DND
{% elif roomstate == 'vrij' %}
Vrij
{% else %}
Bezet
{% endif %}
let me try that!
i was searching for that indeed, but couldnt find much info in the google chat bot and passing the slots except the light example
worked ! ty
If it helps, here is an example of the output:
[<template TemplateState(<state persistent_notification.config_entry_reconfigure=notifying; message=At least one of your integrations requires reconfiguration to continue functioning. [Check it out](/config/integrations)., title=Integration requires reconfiguration, friendly_name=Integration requires reconfiguration @ 2022-04-13T21:11:02.077940-03:00>)>]
Never mind. I managed to piece it together myself. I guess I’m starting to figure this stuff out after all.
I use a markdown card that uses ```
| {{ states.sensor.updater_core.attributes.current_version }}
Not sure how I can pull just the version number into my markdown card.
Tried | HassOS | {{ state.sensor.home_assistant_operating_system_version }} and this does not work
it's not what the docs say
{{ states('sensor.home_assistant_operating_system_version') }}
suggest reading that link
You should add .state if you want to use this (which is advised against)
Rob's answer worked. I had tried using states.sensor.home_assistant_operating_system_version and it was not working.
right, because it's not correct. you're missing .state, as TheFes mentioned
At the end?
the link explains
Got it. Thanks.
data:
rgb_color: {{ [ range(0,256) | random, range(0,256) | random, ]range(0,256) | random]
}}
target:
entity_id:
- light.go_mini_lamp
- light.hue_go_1
- light.hue_go_2
- light.lightstrip
Message malformed: template value should be a string for dictionary value @ data['sequence'][0]['data']
still not working
same error?
try rgb_color: "{{ [ range(0,256) | random, range(0,256) | random, range(0,256) | random ] }}"
that works, ty. 🙂
Ah, there did that closing square bracket go while copy pasting on mobile 😎😅
Hi, referred here from #automations-archived . I have an issue with calling lights with a list of strings; https://paste.debian.net/hidden/830ca0a1/ I can't seem to get the syntax right. Can someone please help?
You'll need a loop to add light. to each entity in your variable, which seems a bit much for this
That could work. But in the description for entity_id, it says a string, or a list of strings as input?
and yes, this is a proof of concept script to learn this, so may seem a bit too much like this
Howdy ya'll!
I got stuck with this one 😦
{% if is_state('sensor.washer', 'off') %}
Standby
{% else %}
Time Remaining: {{% state_attr('sensor.washer', 'remain_time') %}}
{% endif %}
basically trying to have the dishwasher say "Standby" if its off, or show Time Remaining when its on
anyone know how to do this? #templates-archived message Why is the docs talking of "list of strings" as value for 'entity_id' if some kind of loop is still needed?
Remove the % in the opening and closing of the template for time remaining
variables:
light: ['light.rgb', 'light.roof']
This would make your variable a list of strings, and would be the same as:
variables:
light:
- light.rgb
- light.roof
To make a list of light entities out of your current variable, you would need something like
{% set ns = namespace(lights = []) %}
{% for item in light %}
{% set ns.lights = ns.lights + [ 'light.' ~ item ] %}
{% endfor %}
{{ ns.lights }}
Awesome! Than you, will try this 🙂
WoW. Finally got it working as I need. Thanks much @marble jackal !
I'm using {{ states("binary_sensor.window_contact") }} to display on my dashboard the state of the window sensor, but if shows on/off. Is there any method/function to use to display open/closed as it does if I use a entity or button card ? So I don't need to write if else statemant, or is that the only way?
There's no way to access the translated values via a template
hi guys. i am trying figure out how to count lights sensors on within groups.
i got this sensor who counts all light
sensor:
- platform: template
sensors:
count_lights:
friendly_name: "Count Of Lights"
value_template: >-
{{ states.light | list | count }}
but how do i create sensor that will count lights on
{{ states.light | selectattr('state', 'eq', 'on') | list | count }}
ok thanks that works but if i have a light.group let's say kitchen how do i point to that?
{{ expand(state_attr('light.kitchen', 'entity_id'))|selectattr('state', 'eq', 'on')|list|count }}
or maybe you can now just directly expand the light group? I don't have any and don't know
thanks alot guys i got this now
You can expand light groups directly
{{ expand('light.kitchen')|selectattr('state', 'eq', 'on')|list|count }}
is there a way to track the history of a template sensor? i'd like to see what the value was say 24hrs ago. heres my sensor: ```
- sensor:
- name: "thor"
state: >
{{
( states('input_number.thor_daily_increase') | float | round(2)) *
( states('sensor.cryptoinfo_price_thor_usd') | float | round(2))
}}
attributes:
number: >
{{ ( states('input_number.thor_daily_increase') | float | round (2)) }}
unit_of_measurement: "$"
- name: "thor"
I have a automation that triggers on all available motion and door/window sensors when I am not at home and send me a notification. For various reasons I am not interested in the entities name or friendly name that triggered the automation, but in the area the entity id is related to. However I am struggling to find the correct template to find the area name assigned. So far I tried {{ area_name ('trigger.entity_id') }} and also {{ area_name ('trigger.to_state.name') }} but both return 'None'. It seems that the copied trigger entity does not belong to the area of the originating entity.
Remove the single quotes around trigger.entity_id
🙈 Always these little things . Thanks. I'll give it a try :)
Templates are designed to frustrate you
@mighty ledge is there a way to do this? or do i need to use a different sensor
The state of 24h ago should be stored in your database
what database
The one of Home Assistant, unless you excluded this sensor from the recorder
i have not. could i set that as a attribute? how would i enter that?
Templates only work with the actual data at the current moment, if you want to retrieve something out of your database, you'll need a SQL sensor https://www.home-assistant.io/integrations/sql/
I can't help you with the code to get it out though, I don't know much SQL
tyvm its a start
Hi everyone, I need some help with a template to count the number of lights that are on in my house. I currently have this one :
{{ states.light|selectattr('state', 'eq', 'on') | list | length }}
It was okay until I added lights group through the UI, because they are created in the light domain
I think the only difference between a proper light and a light group is that the latter has an entity_id attribute
How could I exclude these?
Is it possible to create a template switch? I'd like to make a switch that turns on/off multiple entities as one. Do I need to make it manually or is there a format that will just take the entity names and be done?
what are the advantages?
It groups entities together to control them together, which sounds like what you asked for
yes it looks like a better option
template switches seem to be powerful, but yes a group makes more sense
when I put ```
switch:
- platform: group
name: "T1 All Clip Fans"
entities:- switch.t1_clip_fans
- switch.t1_clipfan_upper```
into groups.yaml
I get: Invalid config for [group]: value should be a string for dictionary value @ data['group']['switch']['entities']. Got None. (See /config/configuration.yaml, line 8).
groups.yaml is in config.yaml as a group - is this why ?
that doesn't belong in groups.yaml
it's a switch
it's probably easier for you to just create it in the UI
groups.yaml contains the YAML configuration of the group integration. What you had belongs to the switch integration.
The first line shows that
ok I got it from the wiki directly on the groups integration
So since the new release (2022.4) it is possible to 'hide' entities. Does anyone know if it is possible to filter entities when they are hidden?
I actually don't think this is possible because 'Hidden' (or 'Disabled' for that matter) is not an attribute of the entity.
Hey all. Have created two sensors to convert MB to GB, but they end up showing as KB....
- sensor:
- name: "NBN Download GB"
unit_of_measurement: "GB"
state: >-
{{ (states('sensor.nbn_downloaded') | filesizeformat(GB)) }}
- sensor:
- name: "NBN Upload GB"
unit_of_measurement: "GB"
state: >-
{{ (states('sensor.nbn_uploaded') | filesizeformat(GB)) }}
Any ideas why it would do that?
If I'm understanding the Jinja docs for the filesizeformat filter, you can't force it to report the filesize in a certain order of magnitude. It will report it to the order of magnitude that makes the most sense from a human readability POV.
Yup. Only takes the filesize value and whether you want the true binary size.
If you specifically want it in GB, just math it?
Yeah I guess I’ll have to!
Thanks a lot! Alas it doesn’t work apparently, I get 0 all the time.
Edit: my bad… mixed attributes.entity_id with only entity_id
hey guys.
I was thinking of starting with light groups, but realized thats gonna mess up this template:
'{{ states.light|selectattr("state", "equalto", "on")|list|length }}'<
does anyone have an idea on how to subtract the number of turned on light groups to get the right number of turned on lights? 😄
Immediately above your post
Seems to be quite popular to count the number of lights which are on
Pinned
Awesome. Thanks @inner mesa
Granted that’s not very useful, but when I only put the icon my wife says it’s not very visible, and I figured the number of lights would be the most interesting information next to the icon.
@young jacinth posted a code wall, it is moved here --> https://hastebin.com/mayeqomafu
