#templates-archived
1 messages ยท Page 14 of 1
trigger:
- platform: template
value_template: >-
{% set entities = ['sensor.front_window', 'sensor.gabrielle_window', 'sensor.laundry_door', 'sensor.master_window', 'sensor.patio_door', 'sensor.front_door'] %}
{{ expand(entities) | selectattr('state','eq','open') | list | length > 0 }}
Got it! Thanks for your help @inner mesa
If I want to move my sensors to sensors.yaml do I have to use the legacy configuration format? I keep getting
Invalid config for [sensor]: required key not provided @ data['platform']. Got None.
The new format is under template:, so if you really want to put them under sensor:, yes, you need to use the old format
Ah okay. Was just trying to be tidy. Thanks!
Why is this returning an empty array?
states|expand|rejectattr('device_class', 'undefined')|list
expand as a filter doesn't work properly
I truly wish it did, but they'd have to pick up my PR
also, you need attributes.device_class
Oh huh. I was using it in another template I had as a filter
hmm
I guess I don't actually need expand in this case anyways it seems
that's true too
states|rejectattr('attributes.device_class', 'undefined') This seems to work
yes
My guess is that you were testing in
-> Templates. It works there, but not in an actual sensor definition or automation or script or...
That doesn't seem good if something works in the editor but not elsewhere
I am using it in a node red flow though
Nice looking PR
petro broke it, so need to fix the merge conflict this weekend ๐
Speaking of which, is there a way to get more attention to a PR? There's a pretty straightforward one for an issue I reported, but it's already been passed over for about 3 releases now
It's this one: https://github.com/home-assistant/core/pull/74822
not really
:/
I have a sensor that have a attribute that returns a dictionary like this
{'dictkey1': {'date': 1667033190, 'status': 'done'}, 'dictkey2': {'date': 1667033190, 'status': 'ongoing'}}
I trying to use filters to get how many that have status done. But don't manage. Been googeling so now trying here.
I could come to this
{% set test = {'dictkey1': {'date': 1667033190, 'status': 'done'}, 'dictkey2': {'date': 1667033190, 'status': 'ongoing'}} %}
{% set ns = namespace(count=0) %}
{% for key in test %}
{% if test[key].status == 'done' %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{% endfor %}
{{ ns.count }}
Wait, this is much better
{% set test = {'dictkey1': {'date': 1667033190, 'status': 'done'}, 'dictkey2': {'date': 1667033190, 'status': 'ongoing'}} %}
{{ test.values() | selectattr('status', 'eq', 'done') | list | count }}
@marble jackal THANK YOU. Used state_attr('xx', 'xx') and did not manage to get the values I tried and used like "| values" as a filter but it was that simple as ".values()". So easy when you wrote it. Thanks again
does this.entity_id not work on binary sensors?
It works
Only in the new format maybe?
anyone know how to extract the icon name from weather.home?
something like {{ state_attr('weather.home', 'icon') }} but that actually works
this is more of a general "code style" question. I am creating a one sensor that signals the period where electricity is the cheapest of every day (or what's remaining of the day). Something that would hold values like "between 2PM and 5PM". Would you create a single sensor that contains that information in a single state like 14-17 or would you rather create two sensors (being and end of the cheap period), each of them containing a Date?
I'm trying to set up a template sensor which triggers updates every 30 seconds but can't figure out how write the yaml structure. In configuration.yaml I have template: !include template.yml , and in template.yml I had up to now just a sensor: top level element and then - name: <blahblah> etc, working fine.
My thought then was to also add a trigger: at 0 indentation at the bottom of the file and add trigger-based template sensors under there but I can't work out how to do it.
so the question is, how, from the perspective of the top level of my template.yml file, do I start writing a trigger-based sensor?
You need to add a - before sensor
And before trigger as well
- sensor:
- name:
state:
- name:
state:
- trigger:
- platform: bla
sensor:
- name:
state:
gotcha, will try that out, thank you
(yaml baffles me sometimes)
that appears to do it, thanks a lot
I had been throwing stuff at the wall for a while for that one
Right
All, I've got a zigbee thermostat with one state, but like 15 attributes. My assumption is the attributes stay the same regardless of the state.
If I have a template like this: {{ states('sensor.mytempsensor') }}
that pulls the current temp of the room, whats the equivalent for pulling the attibute for : Current_Temperature
or is there a way I can turn that Current_Temperature attribute into a sensor?
{{ state_attr('climate.thermostat', 'current_temperature') }}
I assume it's done in the template, but the doc doesn't seem to have a section for pulling data from an attribute.
thanks, I'll give that a whirl.
I scrolled right past that section, as I assumed 'attirbute' would be it's own section, not directly under state.
ha! yeah, i scrolled right by that.... because... well, I'm not too bright.
but appreciate the point in the right direction.
@thorny snow I converted your message into a file since it's above 15 lines :+1:
@thorny snow template expect a list, and not a dictionary. 1 will only work with one item (HA will see it as a list item then). As soon as you add a second key it will fail. So 2 is the correct one.
3 is the legacy template format
4 is a sensor provided by an integration
Ok thx for that! Can legacy #3 be written as #2 then?
and can #4 be written in another way?
3 can be converted to 2, there is no alternative for 4, unless the integration starts using the config flow (then no YAML confrontation is needed anymore)
@marble jackal I am trying to rewrite #3 as #2 but I just don't get it to work.
- First of I had to manually use "space" on all lines instead of "tab", as the intendations would be wrong all of a sudden.
- on - name: "abc" it warns that it is "Missing property "state""
- on value_template: it now warns that "Property value_template is not allowed"
2 and 3 are both correct ๐
Have a look at the documentation there
It's not as simple as just copying what you had under a new key
Ah.. ok seems like it is more legacy in the code then, thx
Hi, how can i alter a sensor state from numerical to aphabetical? Im am getting states from my cyberpower USV via snmp Integration. consumption e.g. is numerical int. The state has to be divided by 10 to get the actual correct measurement. This works via value_template in the sensor configuration itself. Now i want to get the state of the usv which returns 1 for on mains and 2 for on battery. How can i "1" and "2" to actual values "an Mains" and "on Battery"?
Good morning. I try to monitor the CPU of the server but every sensor is disabled by integration?
grr here we go again. My water sensor returns 2022-10-30T13:43:45Z as startup time. my mqtt value template sensor``` - unique_id: watermeter_smart_gateways_startup_time
state_topic: watermeter/smart_gateways/startup_time
name: Watermeter startup time
value_template: >
{{value.split('Z')[0]|as_timestamp|timestamp_local}}
the manufacturer says its correct. and wont change the format. so I am forced to repair this in HA. but. how?
because it actually is {{now(0)}}, returning 2022-10-30 12:53:40.025288+01:00
So that timestamp from the integration is UTC?
yes i believe so
If I just use as_datetime on it, is seems to be working
However, that is still in the future
{{ '2022-10-30T13:43:45Z' | as_datetime - timedelta(hours=2) }}
yes, and it was in the past. it simply is 1 hour behind
but let me try your format in the sensor
nope, its even worse..it now seems 2 hours off```
- unique_id: watermeter_smart_gateways_startup_time
state_topic: watermeter/smart_gateways/startup_time
name: Watermeter startup time
value_template: >
{{value.split('Z')[0]|as_timestamp|timestamp_local}}
- unique_id: watermeter_smart_gateways_startup_time_alt
state_topic: watermeter/smart_gateways/startup_time
name: Watermeter startup time datetime local
value_template: >
{{value|as_datetime|as_local}}``` now show as
which is also odd, because before, the top template would also show 'in 1 hour' as relative time (see screenshot above) . Adding this second sensor now changes that to the actual state
When did it actually start? In NL time
Just rebooted the device
14:35 our local time, device says 15:35Z
And front end does
Top my original, middle your format bottom raw value
Itโs maddening โฆ.
It looks like it doesn't take into account that DST ended last night
But Z in am the timestamp should indicatie it's UTC, which it obviously isn't
{{ value | as_datetime - timedelta(hours=2) }}
Basically the timestamp is off with 2 hours
Because you stripped the timezone info ('Z') and then treated it as local time, it worked with DST
But now it doesn't anymore, as the time difference is only one hour
You can convert it to local time as well, but that doesn't matter for the dashboard
Thing is, it seems the raw data isnโt correct in the first place ? So how can we reliably fix the template for that, taking into account the dst changes..
Quoting the author of the device and code (pardon its in dutch )
โde ntp time is de utc time. Je mag dit zelf terugrekenen naar je eigen timezone. โ
If that were true (utc time) , shouldnโt we simply be able to convert that as he suggests ?
But it isn't UTC time, otherwise you are restarting the device in the future
Unless the timezone on the device is incorrect
Exactly. But there probably is no way to set thatโฆ
Anyone mind looking at my template? I am banging my head against a brick wall here. It works fine in the dev tools but I am getting errors when I try to restart.
All of the problems are the custom timestamps. It absolutely hates them but I'm mainly copying and pasting from the forum and these are more experienced people's examples.
But I'm putting colons all over the darn place and I can't see where it's meant to be.
first
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Ah yes.
second, remove the quotes surrounding the template in the first one
third, you're using the same type of quote both inside and outside some of your templates. that can't be parsed
you just have a lot of quote issues
review all of them
like this:
:%M", false) }}""
you can't use " inside and " outside, and you have two of them at the end
Okay yeah that's really helpful. I keep forgetting HA puts two quotes in when you type one.
Simple qn, do states for templated need to be in quote marks?
To be sure:
"{{ (state_attr('sun.sun','next_rising')}}"
or
{{ (state_attr('sun.sun','next_rising')}}
it depends on whether you're building a single-line template or multiline
And multiline is only for clarity of the reader, it doesn't make a different to the code?
Or are there times when you NEED to use multiline?
single line templates without quotes look like JSON to the parser and it will fail
there are some esoteric differences in how they work, but for the most part it's just readability
I've checked the quote mark errors, but it seems like it still isn't happy
keep looking ๐
Specifically the timestamp section, does that look accurate?
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
But when I check this with the templater on the dev tools, it needs the quote marks surrounding the custom time stamp
I tried removing them and it errors.
I can use single quote marks tho
I guess I'll give that a shot
it's very simple
state: "{{ (state_attr('sun.sun','next_rising') |as_timestamp - now()|as_timestamp) | timestamp_custom('%-H:%M', false)}}"
you cannot use the same quotes both inside the template and surrounding it. that cannot be parsed
you did it right the first two times and wrong the third
Got it, timestamp elements must still be quoted but cannot be the same type of quotation mark as used surrounding the entire code for the state.
it's not specific to timestamp elements
it's a general rule
consider what the YAML parser will do with it otherwise
I don't know a lot about this, but this is a good way to learn.
"{{ "a" }}" is a mess
Thanks Rob!
Hey everyone
NFL commercial break and I was wondering: input_select supports templating, correct?
Can this be used to create a list of entity names as options?
if you use input_select.set_options, yes
What would be a use case for that?
I can see a use case to dynamically set the options in an input_select
What would you use that for specifically?
anyone here who can probably answer a really easy question? I have a template Iยดd like to change number states to text information but Iยดm getting template error. I have no idea whats is wrong with the template.
The code http://pastie.org/p/3eaIIQJypYP4oAaqnJHJ7j
The Error http://pastie.org/p/2rXvBcPZX2Kuf2JNC35Oex
Thanks for any help i can get ๐
Remove sensor. from sensor.nibe_prio_state
Thank you! ๐ worked ๐
Hello! I have an (poorly) mqtt-connected alarm that creates an alarm control panel for each zone that can be armed and one for the global arm. I (think I) would like to create a template alarm panel that merges down these entities into a single alarm, so that I can have presets for arming and disarming multiple zones at once and also have just one alarm card on my dashboard. Is it possible? How?
One more thing: non of the alarm entities that I now have require a pin in order to arm/disarm. It would be nice to have it (I know it would not add any real security, but it would prevent arming/disarming by mistake, and create a little more complication to anyone who might get their hand on my family's phones)
I am using input_select dropdown lists to select which entities to show in a chart.
So it would be pretty cool if I could have the input_select automatically create the list of all available entities for a specific template.
E.g. all entities that belong to climate or all entities that belong to my thermometers (sensor.xiaomi_temperature*).
that way as you buy more devices you dont have to hardcode each one into an automation/card/etc?
Yes, exactly
what would you use that dropdown for? just to add to a dashboard?
Right now I am feeding a wildcard expression directly into auto-entities in an apexchart.
That gives me all entities matching a template.
But I would also like a dropdown that then allows me to select one of those.
One second, I will take a snap
using this card with auto entities? https://github.com/RomRider/apexcharts-card
you can pm me
I have it all working. Only thing missing is the correct syntax to get input_select to create a list according to a wildcarded entity_id
done
Yes, I always find the answer immediately after asking
Second question, is there a way to add a natural language "and" between the last and second-to-last elements of a list?
pop off the last element, push "and", then push back on the last element?
or prepend "and " to the last element .. if count(list) > 1
can you post the full template again?
you can slice the list but you should assign it to a var
{{ expand('group.openings') | selectattr("state", 'eq', 'on') | join(', ', attribute="name") }}
{{ "{} and {}".format(open_openings[:-1], open_openings[-1]) }}```
{{ "{}, and {}".format(open_openings[:-1]|join(', '), open_openings[-1]) }}``` needed minor tweak
tysm
ah yes. good catch
Anybody know a solution, please?
did you checkout the template: select? ```template:
- select:
- name: Mode selector
unique_id: mode_selector
icon: mdi:sync-circle
state: >
{{states('input_select.mode')}}
options: >{{state_attr('input_select.mode','options')}}
select_option:- service: script.turn_on
target:
entity_id: script.scene_{{option|slugify}}```
- service: script.turn_on
- name: Mode selector
- service: input_select.select_option
target:
entity_id: input_select.mode
data:
option: '{{option}}'```
or check here for some more extensive use of those selects, and automatic creation of entities/options https://community.home-assistant.io/t/select-activate-hue-scenes-in-new-v2-api-setup/356057/42?u=mariusthvdb using templates
why combine a select with an input_select for this? Couldn't you do it all witth only the select
uhm, I didnt check at that time tbh. At that time, the template select was new to me, and I merely experimented.... will check now to see how that could be further improved upon though. always a challenge when you're around ๐ the input_select is deeply involved in my system, so it would mean at least some further overhaul...
basically now you just replaced an automation with the select. You could replace both the input_select and the automation with this select
You only need to add the options in the select itself, instead of taking them from the input_select
hmm, wait, the state template brings some challenges there
it was indeed the exercise to replace the automation. I didnt look further at that time.
maybe we can use the this variable for state?
this works, but shows unknown after a restart or template reload
select:
- name: Mode selector
unique_id: mode_selector
icon: mdi:sync-circle
state: "{{ option }}"
optimistic: true
options: "{{ [ 'Mode 1', 'Mode 2', 'Mode 3'] }}"
select_option:
- service: script.turn_on
target:
entity_id: script.scene_{{ option | slugify }}
It would be nice if the select would return to the previous state after restart/reload
maybe we can ask Erik to fix that, just like he did on the other template formats. restore state did the trick on template trigger
also, I created the input_select via the UI, which means we dont have to write yaml for that entity. Using it in the above method would require editing the yaml for the options list, and reload templates after that edit.
not that those options will change often (as a matter of fact, these are the longest standing options in my system...), but just saying, for comparisons sake
Most useful things break UI support ๐คฃ
I will need to check select out then.
@marble jackal , the docs for select are basically non existent and the thread is cool use cases, but not the individual keys.
You define options: and then also select_option.
Do you need both?
select:
- name: Mode selector
state: "{{ option }}"
options: sensor.xiaomi_{{ 'humidity' | slugify }}
Looks wrong to me.
yes, you need both. options provides the options you can choose from. select_option provides the actions taken when you select one of these options
yes, that's a benefit from the GUI created input_select, you can easily change the options
it looks like state restore also only works on trigger based template sensors. Tried with a trigger based template select, but that also doesn't work
@marble jackal I converted your message into a file since it's above 15 lines :+1:
But the options are supposed to be created by the template and there is no action.
It is supposed to be used in an entities card as a dropdown.
So create the list of entities from a template and then apply them all as separate list items.
options needs a template in which a list with options is returned. That can be anything you want.
select_option is what happens when you select an option, it uses the variable option. It expects a sequence of actions, just like action in an automation or sequence in a script
As it is still October, I created a WTH for it https://community.home-assistant.io/t/wth-is-the-state-of-select-and-number-template-entities-not-restored/482170
Then what would be the advantage of select over input_select in my case? Or does input_select simply do not allow me to create a template-equivalent of wildcards?
For an input_select you can use input_select.set_options to set the options, you can use templates there
for the select you can simply use the template in the options field
But the select, you said, needs an action. What would be my action then as I do not want to "do" anything except pass it on?
More precisely:
not actively pass it on.
I do not want to push it to the destination, I want a card to pull the information from the source (select, input_select or whatever else)
But what do you want to happen when an option is selected?
I have automations notifying me when appliances are done and how long the run took. After the daylight saving time change yesterday, the notification is 1 hour off. Ideas? https://pastebin.com/rgdx4qrX
yes, add false to the timestamp_custom filter
{{ (now().timestamp() - state_attr('input_datetime.oppvaskmaskin_startet', 'timestamp')) | timestamp_custom('%H:%M:%S', false, default=none) }}
Hmmm.... what does false do? ๐
How can I make a working automation from a blueprint i have downloaded. When I click save it doesn't save my changes and the fact that it is still in blueprints suggests it is not even running.
oh, Filter timestamp_custom(format_string, local=True, default)
Sry, i just figured out it gets saved to automations but stays in blueprints. That makes sense just the 'save' button is confusing
Should be called publish or something like that
heck, I am still fighting to understand the new templating options for filters and tests of https://github.com/home-assistant/core/pull/79473. could this be using those: {{expand('sensor.teller_1_terug','sensor.teller_2_terug') |selectattr('state','is_number') |map(attribute='state') |map('float')|sum|round(2)}} ?
yes
{{ ['sensor.teller_1_terug','sensor.teller_2_terug'] | map('states') | select('is_number') | map('float') | sum | round(2) }}
or this: {{ ('sensor.teller_1_terug','sensor.teller_2_terug') | map('states') | map('float', 0) | sum | round(2) }}
thanks!, I was close, but forgot the map to states... i did meet the default error also. Defaulting to 0 seems less reliable (correct), than is_number, which simply excludes it if it isnt?
sure, but for a sum it doesn't really matter if you default to 0 or leave it out
for average it's different
then you should leave them out
exactly. good point to make notice though. thks! will continue....
also, in that new format, we can use either [. ] or (. )
Does someone here know if there is an equivalent to "delay_on" that exists for binary_sensor for a regular sensor? I made a template that looks at lux, but I don't want to update sensor until the value has been fulfilled for 5 minutes
there s really no alternative in the integration itself, other than an automation using the for: option on the state change, trigger or condition
or maybe a trigger template: with that for: option
I do not want to select something and then have something happen.
I want to enter a template in the select_input and then, when I click the dropdown in my entities card, see all entities that matched that template.
Basically I want to see a list of entities in a dropdown menu without having to enter all the entities manually.
something something
options:
- sensor.xiaomi_humidity*
- sensor.xiaomi_temperature*
- sensor.eq3_temperature*
And in the dropdown I would then see the 27 entities matching that wildcard.
Basically auto-entities for a dropdown menu ๐
did you check the link to my Hue scenes setup? because thats exactly what that does. I've added a Gif showing what it does
Ok, thanks. Will make it an automation then
I'm struggling with 2 solar panel inverters.
I have then combined in a template.
- sensor:
- name: Solar Production Today (total)
unit_of_measurement: "kWh"
state: >-
{% set links = states('sensor.today_generation_links')|float %}
{% set rechts = states('sensor.today_s_pv_generation')|float %}
{{ (links + rechts) | round(2) }}
But whenever one becomes unavailable, the whole template becomes unavailable.
Does anyone know how to prevent this?
They become unavailable when there's no sun on the panels.
Thanks. So do i do that at the 2 separate sets?
Or do you perhaps know a better way to combine the 2 values?
You just provide a default for each state
So, |float(0)?
If you want zero to be the default in that case, yes
Thanks! Let me try it
Does that mean if either or both become unavailable, they return a value of 0?
Cause it still states unavailable
Yes i did.
I forgot to change the entity in my dashboard to the correct one ๐คช
It is working, thanks a lot!
Good Day, Anyone know how one would be able to only return the dates = to today?
"[{'start_time': '2022-11-01T05:00:00+00:00', 'end_time': '2022-11-01T07:30:00+00:00'}, {'start_time': '2022-11-01T13:00:00+00:00', 'end_time': '2022-11-01T15:30:00+00:00'}, {'start_time': '2022-11-02T13:00:00+00:00', 'end_time': '2022-11-02T15:30:00+00:00'}, {'start_time': '2022-11-02T21:00:00+00:00', 'end_time': '2022-11-02T23:30:00+00:00'}, {'start_time': '2022-11-03T21:00:00+00:00', 'end_time': '2022-11-03T23:30:00+00:00'}, {'start_time': '2022-11-04T05:00:00+00:00', 'end_time': '2022-11-04T07:30:00+00:00'}, {'start_time': '2022-11-05T03:00:00+00:00', 'end_time': '2022-11-05T05:30:00+00:00'}, {'start_time': '2022-11-05T11:00:00+00:00', 'end_time': '2022-11-05T13:30:00+00:00'}, {'start_time': '2022-11-06T11:00:00+00:00', 'end_time': '2022-11-06T13:30:00+00:00'}, {'start_time': '2022-11-06T19:00:00+00:00', 'end_time': '2022-11-06T21:30:00+00:00'}, {'start_time': '2022-11-07T19:00:00+00:00', 'end_time': '2022-11-07T21:30:00+00:00'}]"
Would like it returnsomthing like this:
start_time: 2022-11-01 05:00:00
end_time: 2022-11-01 07:30:00
or "2022-11-01 05:00:00 - 2022-11-01 07:30:00"
The second item is also today
If today is 1st of November (it's still 31st of October here)
I don't understand what you want to achieve
Yes, but there are two items which match tomorrow, the first starts at 5:00 and ends 7:30, and the second one starts 13:00 and ends 15:30
correct so tomorrow our power will be off between 05:00 and 07:30 then again 13:00 - 15:30. So i want to send a notification:
2022-11-01
05:00 - 07:30
13:00 - 15:00
example
{%- set data = [{'start_time': '2022-11-01T05:00:00+00:00', 'end_time': '2022-11-01T07:30:00+00:00'}, {'start_time': '2022-11-01T13:00:00+00:00', 'end_time': '2022-11-01T15:30:00+00:00'}, {'start_time': '2022-11-02T13:00:00+00:00', 'end_time': '2022-11-02T15:30:00+00:00'}, {'start_time': '2022-11-02T21:00:00+00:00', 'end_time': '2022-11-02T23:30:00+00:00'}, {'start_time': '2022-11-03T21:00:00+00:00', 'end_time': '2022-11-03T23:30:00+00:00'}, {'start_time': '2022-11-04T05:00:00+00:00', 'end_time': '2022-11-04T07:30:00+00:00'}, {'start_time': '2022-11-05T03:00:00+00:00', 'end_time': '2022-11-05T05:30:00+00:00'}, {'start_time': '2022-11-05T11:00:00+00:00', 'end_time': '2022-11-05T13:30:00+00:00'}, {'start_time': '2022-11-06T11:00:00+00:00', 'end_time': '2022-11-06T13:30:00+00:00'}, {'start_time': '2022-11-06T19:00:00+00:00', 'end_time': '2022-11-06T21:30:00+00:00'}, {'start_time': '2022-11-07T19:00:00+00:00', 'end_time': '2022-11-07T21:30:00+00:00'}] %}
{%- set start = (today_at() + timedelta(days=1)).isoformat() %}
{%- set end = (today_at() + timedelta(days=2)).isoformat() %}
{%- set data_tomorrow = data | selectattr('start_time', '>=', start) | selectattr('end_time', '<', end) | list %}
{{ as_datetime(start).date() }}
{%- for item in data_tomorrow %}
{{ as_datetime(item.start_time).strftime('%R') }} - {{ as_datetime(item.end_time).strftime('%R') }}
{%- endfor %}
result:
2022-11-01
05:00 - 07:30
13:00 - 15:30
Would i use: states.sensor.load_shedding_middelburg.attributes.start_time / (state_attr("sensor.load_shedding_middelburg", "schedule"))
(state_attr("sensor.load_shedding_middelburg", "schedule")) where do i add
Got it
So if i would want it to run for today if the schedule was too change?
timedelta(days=2) > timedelta(days=1)?
For today it's
{%- set start = today_at().isoformat() %}
{%- set end = (today_at() + timedelta(days=1)).isoformat() %}
How would i use this in a notification?
message: |
Power outage schedule tomorrow:
{%- set data = state_attr("sensor.load_shedding_middelburg", "schedule") %}
{%- set start = (today_at() + timedelta(days=1)).isoformat() %}
{%- set end = (today_at() + timedelta(days=2)).isoformat() %}
{%- set data_tomorrow = data | selectattr('start_time', '>=', start) | selectattr('end_time', '<', end) | list %}
{{ as_datetime(start).date() }}
{%- for item in data_tomorrow %}
{{ as_datetime(item.start_time).strftime('%R') }} - {{ as_datetime(item.end_time).strftime('%R') }}
{%- endfor %}
Thanks bro, just got it working... Your a legend!
One last question, How do I remove 30 minutes from the end time?
@marble jackal
(today_at() + timedelta(hours=47.5)).isoformat()
Oh wait, that's not what you mean
{{ (as_datetime(item.end_time) - timedelta(minutes=30)).strftime('%R') }}
Instead of what is there now in line before the last
Hello, do you know if the templating engine works with transliterated ids? area_devices('Meterkast') works but area_devices('kathistiko') doesnโt
Second id was transliterated from a Greek label
I will check it out with fresh eyes again tomorrow, but when I checked the first time, it created a list in an entities card from a value supplied by the dropdown.
I want the dropdown itself to be auto-populated.
Making an entities card auto populate itself does not even need templating. You can simply pass the string "sensor.xiaomi*" directly to an auto-entities card.
But I want to have a dropdown that is auto populated so I can select a single entity from there.
But as I said, maybe I overlooked something. The git at least looks like it does what I just said.
What I realized when I was already in my bed, the timestamps are in UTC time, so so are the times in your message. I suppose you want those in local time right?
@floral shuttle I converted your message into a file since it's above 15 lines :+1:
archhh.... main point being action: service: input_select.set_options target: entity_id: input_select.hue_group data: options: > {{expand(integration_entities('Philips Hue 1')) |selectattr('attributes.is_hue_group','defined') |selectattr('attributes.is_hue_group','eq',true) |map(attribute='name')|list}}
run at startup
or, trigger on another input_select: - platform: state entity_id: input_select.hue_group action: service: input_select.set_options target: entity_id: input_select.hue_dynamic_scene data: options: > {% set hue_group = states('input_select.hue_group') %} {{states.scene |selectattr('attributes.group_name','defined') |selectattr('attributes.group_name','eq',hue_group) |selectattr('attributes.is_dynamic','eq',true) |map(attribute='name')|list}}
so yes, its all in there ๐
But if I understand correctly, you need multiple entities/scripts/automations instead of just one?
I am not trying to be difficult, btw, I am trying to optimize my dashboards and at the same time minimize the amount of entities/helpers/scripts etc. needed.
So to me, in theory, only one input_select would be needed without any other calls, IF the input_select directly populates the dropdown it "is" in an entities card.
The entities card only "sees" the list the input_select passes on to it. That list should be auto-created by the input_select itself.
Just like auto-entities passes on the final list to the host card.
well, dont know how to help you, if you only state what you want, and oppose to all we suggest to you... why dont you start by showing us your current config, and let us help you optimize that.
Hmm... I did that and now the time is 1 hour off in the other direction. Before the appliance took 3 hours, now it takes 1 hour but it should take 2 hours. ๐
what is the time in the input_datetime and what does now() return
input_datetime = 09:03 and now() says 2022-11-01 10:36:19.687141+01:00
The hours above were a simplification. I got a notification saying it was done after 28 minutes but it was really done after 1 hour 28 minutes.
oh, it's a time only input_datetime, that is good to know
Ah, yes. ๐
It's set like this on line 21.: time: "{{ (now() - timedelta (minutes=5)).strftime('%H:%M:%S') }}"
{{ (now() - today_at(states('input_datetime.oppvaskmaskin_startet'))).seconds | timestamp_custom('%H:%M', false) }}
This gives 1:33 for me now
using the input you provided
({{ (as_datetime('2022-11-01 10:36:19.687141+01:00') - today_at('09:03')).seconds | timestamp_custom('%H:%M', false) }})
Same here
So that's correct right?
yes, but you didn't use the template I just provided at that time
so replace it ๐
Hahah... I thought you just pasted what I had ๐
but this is based on your old template, and it also gives me 1:33
{{ (as_datetime('2022-11-01 10:36:19.687141+01:00').timestamp() - today_at('09:03').timestamp()) | timestamp_custom('%H:%M', false) }}
what is the value of that timestamp attribute?
Yeah, that gives me 1:33 as well. But {{ (now().timestamp() - state_attr('input_datetime.oppvaskmaskin_startet', 'timestamp')) | timestamp_custom('%H:%M:%S',false,default=none) }}. gives 00:41:20 still.
{{ state_attr('input_datetime.oppvaskmaskin_startet', 'timestamp') }} = 32633
that timestamp is a timestamp of 9:03 on 1st of January 1970
so it will apply DST for that date
I guess line 21 is a bit silly perhaps then?
I would use an input_datetime with date and time
I can't remember why I set a timestamp with just hh:mm. I don't use it for anything else than these automations with notifications.
so you also use the correct date
or use the template I just gave you instead of the one you are using now
because using the timestamp will cause issues with DST
Sorry, I meant no offsense. I just wanted to describe what I am trying to do and what I am trying to avoid.
input_select:
entity_dropdown:
name: entity_dropdown
options:
- sensor.xiaomi_temperature*
- sensor.xiaomi_humidity*
- sensor.eq3_temperature*
- sensor.eq3_valve*
This goes to an auto-entities card which goes to an apexcharts card.
card:
type: custom:auto-entities
sort:
method: state
numeric: true
reverse: true
filter:
include:
- entity_id: ${ states['input_select.entity_dropdown'].state }
If you can help me with setting the input_datetime correctly (minus 5 minutes) I think I prefer that. That would perhaps also work if I turn on the appliance just before midnight (which I really shouldn't do anyways).
So as you can see, I am feeding a string to auto-entities which interprets this as a wildcard expression.
I would like to create a similar entity_dropdown where instead of the auto-entities creating the list for the following apexcharts, the input_select creates a list for me to select one single entity from.
Why not just use this template for your message:
{{ (now() - today_at(states('input_datetime.oppvaskmaskin_startet'))).seconds | timestamp_custom('%H:%M', false) }}
Populate the dropdown rather than auto-entities populating apexcharts
sure, and you do that by creating that input_select as I showed you? (set_options and then the template )
because as far as I understand it, thats the only way to have the input_select be created without explicitly stating all options verbosely
No real reason. I'll use that. Thanks. ๐
Using this to then have one input_select create the list for another, correct?
I am probably not getting how it works. Because you have
input_select.hue_group which is probably what you then use to trigger the list creation.
input_select.hue_dynamic_scene which is where the list is being created and which you are adding to the entities card.
Do I understand that correctly?
upon selecting a hue_group, the input_select is populated with dynamic scenes belonging to tht group yes
btw, not sure what youre doing here: filter: include: - entity_id: ${ states['input_select.input_select.entity_dropdown'].state } because that doesnt work?
Yes, it does ๐
I am of course using config-template-card also. Sorry, did not mention that
yo can use templates in auto-entities, but you need to create a valid jinja template and return a list
a, missed that , sorry
No, my mistake for not mentioning it
I am feeling very thick right now, sorry.
The hue_group itself is already an input_select, is it not?
So you are using
2 input_select helpers plus one state?
but, that seems like a lot of work for simply returning 1 option of an input_select....
I feed the wildcard string when I want to see them all. I then want to be able to feed a single entity_id when I want to follow up on just one of them.
And since the single entities are more than 20, I dont want to create that list manually
I believe you need to step down, and break things up itnto smaller and working bits. Also, move to the correct channel, because this it about Jinja templates, and all your asking is #frontend-archived ...
The wildcard expressions are only 4. So not a lot of work.
#frontend-archived would be the part in the card. I have that working.
I need to create an input_select with automated list. That is the missing part.
Your approach would create that, but with 3(?) different components (2*input_select + 1 state)
Btw, what do the two input_selects then look like? The code you posted was only the state. The input_select need some kind of content?
No, sorry, one state and one input_select. You only labeled the state as input_select.
Because input_select.hue_dynamic_sceneneeds to exist before setting it, does it not?
well, its all there. I have 2 automation to auto populate the input_selects, based on the jinja templates.
so it needs default รฒptions`
the rest is all done in the frontend
yes, thats the only caveat. you need to create an input_select, with 1 default option. hard coded. And then you overwrite that with the automation. It needs to 'exist'.
might I suggest you move this to the community, where it's way easier to share your code in 1 view
One final question before I potentially move it to the community:
Is it possible to append to the existing list of entities instead of replacing it? Then I would append it to my wildcard list and only have one dropdown.
return question: did you try ;-/
what marius described is what you do to get what you want...
or you make a select template, but the selection doesn't persist on restart like input_selects.
Yes, I noticed you also voted on my WTH about that
yah, I assumed that the people who added the persistent state to templates did it for everything, they did not
I tried to convert it to a trigger based select, but even then no psersistant state
I admit, in this case, I asked off of your description because my wife decided that me time is over ๐คฃ
I will try it asap ๐
Howdy ๐
I'm trying to get a template binary_sensor in place that flags whether or not my plex server is needed (I push it down to sleep if not).
state: >
{% if expand(integration_entities('plex'))|selectattr('state', 'in', ['paused', 'playing'])|list|count > 0 %}
on
{% else %}
off
{%endif%}
Now this seems to be working up to a few hours, and then it keeps reporting off for seemingly no good reason.
My best guess is that when the plex integration goes unavailable (as I'm suspending the plex server), this template goes titsup and won't recover - can that be?
I have been trying to make my so simple idea work and somehow simply find all entities starting with "sensor.xiaomi", but I failed miserably to find an example in the Templating docs or derive it from the community.
I did find a way to list all entities:
{%- for state in states -%}
{{"\n"}}- {{state.entity_id}}
{%- endfor -%}
But that does not help me filter that list yet ๐ฆ
Jinja is a mistery to me with few forums really discussing it ๐ฆ
EZPZ
And I don't think can use selctattr because entity_id is not an attribute, or is it?
that's not what that means
Ah, so it is not an attribute as shown in developer tools?
{{ states.sensor|selectattr('object_id', 'match', 'xiaomi')|map(attribute='entity_id')|list }}
I'm saying that 'attr' doesn't mean 'attribute' in the HA context
Oh, match! I was trying 'eq' as in the examples from mariustHvdB
That would be 'equal'
But the rest was wrong also, so....
Yes, but I thought it would maybe be equal as in contains. Because I was looking for contains
`Then what is the difference between 'in' and 'match'? Match is only the beginning of a string?
Thank you for the explanation!
Now that I know, I can find it here https://www.home-assistant.io/docs/configuration/templating/#regular-expressions
But even there I would not know how to place it then correctly.
Your search explicitly looks in sensors only, correct? So I could replace sensor with anything else. But if I only use {{ states|selectattr... it does not search in all kinds of entities. How would I achieve that then?
Or is the rest wrong. Wanted to test with the 'in' to make it look everywhere.
{{ states.sensor|selectattr('object_id', 'in', 'living')|map(attribute='entity_id')|list }}
Should show me all sensors containing the string living but ends up being empty ๐ณ
e.g. sensor.eq3_temperature_living_room
I think this is searchand not in. Could that be?
This works
{{ states|selectattr('object_id', 'search', 'living')|map(attribute='entity_id')|list }}
Thank you very much for getting me there!!!!
That takes a regex. You can also use 'in', which just looks for a sub string
{{ states|selectattr('object_id', 'in', 'living')|map(attribute='entity_id')|list }}does not list anything ๐ฆ
Oh, yeah. That will be backward
?
Backward
backward?
okay, understand! ๐
awesome, thank you very much! I will play some more with the possibilities ๐
Hi all.... Is it possible to access constants in templates, like HVACAction.HEATING instead of having to hard code the string "heating"?
@dry narwhal I converted your message into a file since it's above 15 lines :+1:
input_select:
dropdown_climate:
name: dropdown_climate
options:
- sensor.xiaomi_temperature*
- sensor.xiaomi_humidity*
- sensor.eq3_temperature*
- sensor.eq3_valve*
These entries are then no longer available.
Sidenote: automation does not run on restart, but does replace the list when I run it manually from UI.
it's going to replace the list. If you want it at the bottom, you need to build the code to handle that
But that's what I asked earlier and you both told me off because "that is what it does". ๐
Then I repeat my question: how do I not replace but append?
you take the existing list and then add your items at the end
by writing the code in a way that does that. The code you wrote overwrites it ๐
So my answer is still the same.
I would think that the action needs to include the append, correct?
If not, the options could only append if I first read the current list and then merge the two lists.
But home assistant does not support an append action. So either template the action or read and merge the list?
my man, you're over thinking this
just take the existing list and add (+) the next items
literally +
[ 'a','b','c' ] + ['d','e','f']
So the existing list should be moved from the input_select to the automation. Okay, less code than reading it, but "same approach".
That usually happens when I have a clean idea of what I would like to achieve and what the most elegant way of doing so is in my head ๐
hi. i wach developer tools and cannot explain why my template sensor doesn't show me value
but put in whole picture, the value of max forecast temp appears: http://pastie.org/p/7ae1uAz4pK4EGmIaHBxdan
You never outputted anything
You just have a bunch of logic there
Add {{ ns.hightemp }}
wanted that ns.hightemp calculated ๐
Then threw it away:)
omg..amazing discovery.... thank you for help
FYI, you don't need a for loop there. {{ state_attr('weather.home', 'forecast')[:16] | map(attribute='temperature') | list | max }}
so no need to template highest value ๐
Hi, I have this as a trigger but for some reason it didn't trigger:
>=
as_local(as_datetime(state_attr('calendar.holidays','end_time')))
+ timedelta(hours = 0, minutes = 30)
and(
now()
<=
as_local(as_datetime(state_attr('calendar.holidays','end_time')))
+ timedelta(hours = 0, minutes = 30,seconds = 10))
}}```
theres was an event that had an end time
Assume the end time is 23:00 and the current time is 22:55. The template will do 22:55 > 23:30 which is false
Now it becomes 23:01, which is after the end time. So the calendar entry isn't relevant anymore for the calendar, and the next event ends tomorrow at 10:00
The template will do 23:01 (today) > 10:30 (tomorrow) which will be false
So checking for a time after the end time will never be true
ahh
I have it trigger when the calendar shows a holiday which it works
but I want it to trigger again when the there isnt a holiday that day
Trigger for on I am using is:
>=
as_local(as_datetime(state_attr('calendar.holidays','start_time')))
- timedelta(hours = 3, minutes = 1)
and(
now()
<=
as_local(as_datetime(state_attr('calendar.holidays','start_time')))
- timedelta(hours = 3, minutes = 0, seconds = 55))
}}```
that turns triggers the automation no problems
I just can't see to trigger an automation with the code I first pasted - what would be the best way?
Sorry, I don't understand what you are trying to achieve here
I want a template to be true my end_time is not today
the problem is the end time is normally 12am which is technically the next day
Btw it looks like you are using very short time windows in these triggers, 5 or 10 seconds
templates with now() are only rendered once per minute (or on state change of one is the other entities) so you might miss that time window
good tip - I didn't know that
My next holiday is
start_time: 2022-12-25 00:00:00
end_time: 2022-12-26 00:00:00
this triggers the start time
at 3 hours before the event
so just before 9pm - which works
Okay
it turns input_select.holiday_status to ON
when that event finishes I want it to turn input_select.holiday_status to OFF
so this is the trigger I was using which you said will never be true
so I need a template to be true when that event ends
But why 30 minutes after the event?
because 26/12/22 is a holiday as well
I don't want it to turn off straight away because it would just turn straight back on
I thought if I give it 30 minutes it will give the next event enough time to load in
if there is a better way I am all ears as I know I am making it complex
Just trigger on the calendar going to off. I assume it will not go to that state is the next day is also a holiday, but you can hold the state for a short amount of time to be sure
- platform: state
entity_id: calendar.holidays
from: "on"
to: "off"
for:
seconds: 10
I found an edge case in this template that causes it to throw an error which creates several downstream issues. The point of the template it to evaluate the two groups of calendars, find the next event in each and then return the earliest event of the two. I am filtering out "all day" events. The other day I had a situation where "event1" did not have any scheduled events and this resulted in an "empty" list. Is there a way that can code this so if the list is empty, I can avoid that issue?
http://pastie.org/p/0LH8OQtokQfJBQJK65r9X7
{{ value_json }}```
I am trying to get the value inside data
How should I do that?
When I did value.json[0], i got the { instead
ah nvm, i shudnt have '' the json value
I am trying to build a rest command that returns it response in a sensor.
scan_interval: 5
resource_template: https://api.checkwx.com/metar/{{states('input_text.airportcode')}}?x-api-key=33d3d20d73f54ddasdsasdasd
sensor:
- name: "METAR Raw Data"
unique_id: metar_raw_data
value_template: "{{ value_json.data[0] }}"```
Basically I want to be able to key in the Airport Code (WSSS) of the dedicated. Doesnt seem to be working
Yeah the API Call is working but doesnt seem to be updating when I change the value of the input_text
odd. been a while since i've messed with that
its giving me an unknown
Oh its finally working
Is there anyway that I can request when I click on a button? I dont want to use scan interval as it is gonna blow my API Limit
You can set the scan_interval
Yeah I know that
But I want to only send 1 request when I have to
Else I will blow my daily limit very quick
The alternative is to use a command or python script which are only called when you click it, and those could set something like an input_text, but that's an integration question not templates ๐
and if I got to wait 30seconds for my METAR and TAF values, google is better.
Ah I see
thanks
I got an idea, I will set the scan interval to 5
then create another input_text to store the api key
and when a button is pressed, it will change the value of the input_text to the api to call the value for 60 seconds and then change the value to null, so it doesnt blow my limit
I only have 2000 calls a day
probably better to use some other integration instead
if I go 5s, im blowing it in an hour
The scan interval defaults to 15 minutes, you could easily set it longer than that
because you would still be hitting their api
TAF and METAR Values are On demand
15 mins interval will give me inaccurate data
I will check for an integration
Well you need to figure out what problem you're solving. But I've suggested 2 integrations already
Most of the community made integrations gives me basic data. I couldnt find one that gives me Raw Data.
data similar to this: TAF WSSS 012300Z 0200/0306 32006KT 9999 FEW015 BKN020 TEMPO 0200/0203 3000 TSRA FEW012CB BKN015
Hence, api call was the way to go. But thanks for all the help so far!
there are other generic integrations that can be used
I know about rest_command
Where I can call the service
But thats more like for Post and put right
from an automation or a script
I cant GET a response back?
ah, looks like it will log the response but doesn't return it
Yeah, if only I could get the response back in a stdout format or something
Would be nice
That way I wouldnt necessarily have to waste API Calls, just 1 api call on demand will do the job perfectly for me
That's why I suggested the python script #integrations-archived
Does anyone have thoughts on my earlier post? #templates-archived message
You need to provide defaults of a kind.
But you have to decide what you want to happen when one list is empty.
{% if event1_min and event2_min %}
{{ [event1_min,event2_min] | min | timestamp_custom('%Y-%m-%d %H:%M:%S') }}
{% endif %}
Is simple enough
I figured out how to set a default. I set it to an impossibly late date (2099-12-31). This does prevent the error but is it "bad code" is there a better way?
http://pastie.org/p/1ltp4snU5ZKwFQ4U6xhvQT
Good morning everyone,
I am trying to read the value of an input select as the matching criteria. The individual parts work, but I have tried different things and cannot get the combination to work.
{{ states.input_select|selectattr('object_id', 'match', 'dropdown_climate')|map(attribute='state')|list }}
{{ states.sensor|selectattr('name', 'match', 'Xiaomi Humidity')|map(attribute='name')|list }}
{{ states.sensor|selectattr('name', 'match', states.input_select|selectattr('object_id', 'match', 'dropdown_climate')|map(attribute='state')|list)|map(attribute='name')|list }}
I think it is because I am producing a list instead of a string. But |string is not valid.
Is the first list always one item?
The first input_select has multiple options but the state is only one string.
Is that first template meant to return the state of input_select.dropdown_climate?
Yes.
Output is
['sensor.xiaomi_temperature*']
['Xiaomi Humidity Dining Room', 'Xiaomi Humidity Kitchen', 'Xiaomi Humidity Living Room', 'Xiaomi Humidity Master Bathroom', 'Xiaomi Humidity Master Bedroom', 'Xiaomi Humidity Office', 'Xiaomi Humidity Walk-In']
So the state of the dropdown_climate at the top (one entry) and the output of the second is the list of sensors matching Xiaomi Humidity
For the merged I get TypeError: unhashable type: 'list'
Just use states('input_select.dropdown_climate') instead of that complicated template you have now
{{ states[states('input_select.dropdown_climate')].name }}
That's all you need to get the name of the sensor from the dropdown
This one seems to cause issues.
TemplateError: str: Invalid domain name 'Xiaomi Temperature'
But the original one with the smart approach works
{{ states.sensor|selectattr('name', 'match', states('input_select.dropdown_wildcards'))|map(attribute='name')|list }}
Oh, I thought the options of the input select were entity_ids
But it's has a *, I missed that
No problem. I now switched a bit of the syntax in the input_selects anyway now ๐
Trying to switch to friendly_names instead of entity_id.
Now I just need to template in the frontend to automatically select one of the two input_selects depending on their state.
Ah, no, I have to take it back. One more template problem.
The dropdown has a wildcard for entity_ids right
We talked yesterday about adding a manual entry.
I just tried with ['Test']+{{ ...}}
But this produces two lists. So the dropdown will not work anymore because options are only allowed to be one list.
Used to, yes.
Now it only has the friendly_name and I add the wildcard feature in the frontend.
That way the 'match' does not cause any issues. (Probably could replace the "*", but that is the more complicated approach)
Sorry, nevermind the list issue. I should have simply placed the first list inside the {{}}
You have to add it inside the code indicators
Thank you, but see above you post ๐
Figured it out myself ๐
I'm including a directory of templates. Can you only have one binary sensor per file? I had to put it inline with - platform to stop an error over having 2 spaces back which is what I had when I was not using a directory.
Invalid config for [template]: [binary_sensor] is an invalid option for [template]. Check: template->binary_sensor. (See ?, line ?).
it needs to be in line with trigger.
you're probably using the wrong include as well
take a look at how I include things in my repo for templates.
I only think that I have to use a template for this
I try to choose one or more entetys for Music assistant, based on 2 input_booleans.
current train of thought is that I can have a list for media_player.play
an tip for me where to start
I'm using
!include_dir_list /config/include/templates/
What's the difference between that and !include_dir_merge_list
It looks like you are adding multiple sensors here, with statische m separate triggers per sensor
All of them need to be a separate list item
And if you want to include them in one file, you need dir_merge_list
!include_dir_merge_list
Allows
- trigger:
vs
trigger:
That one combines lists, dir_list combines items into a list
Is that right? ^
Yes, and multiple items in a file
I see. Makes sense. I'll switch it to that then.
As it already expects a list
Thank you. I'll take note of that
You need to build your file like this
- trigger:
- some trigger
binary_sensor:
- name: some sensor
state: "{{}}"
- name: another sensor using the same trigger
state: "{{}}"
- trigger:
- another trigger
binary_sensor:
- name: another sensor using a different trigger
state: "{{}}"
Yes, that's why I said check my config. I already have examples of exactly what you're looking for
it's linked in my profile
I use the other include, with separate files per sensor
Yep that's what I did. @mighty ledge
Right, but dan wants multiple per file
if you don't want multiple per file, then you'd use the other merge
I switched to !include_dir_merge_list and reformatted
To multiple lists.
Should work now thank you guys. Always saving the day lol.
It worked.
Not completely sure why I use that include BTW, the other one is more versatile. You can still have one item per file, but you also have the option to add more
That's fine, l will switch to the other one. I drew the inspiration to use it in the first place from you months ago.
For the following template where "event1" is a list of calendars, do I have the right code for a default value if all of the calendars are filtered out? It works, just making sure it is correct:
{% set event1_min = as_timestamp(expand(event1) | selectattr('attributes.all_day', 'defined') | selectattr('attributes.all_day', 'false') | selectattr('attributes.start_time', 'defined') | map(attribute='attributes.start_time') | min | default('2099-12-31')) %}
@marble jackal I need your help again... ๐ฆ
Just post your question, and please don't ping me, there are more smart people here who can help you
How does one create a calendar from a sensors attributes?
starts_in: 1684
next_stage: 1
next_start_time: '2022-11-04T13:00:00+00:00'
next_end_time: '2022-11-04T15:30:00+00:00'
forecast:
- stage: 1
start_time: '2022-11-04T13:00:00+00:00'
end_time: '2022-11-04T15:30:00+00:00'
last_update: '2022-11-03T08:26:32+00:00'
icon: mdi:calendar
friendly_name: Load Shedding Schedule
I don't think there is something as a template calendar
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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
How do i extract this? "forecast:
- stage: 1
start_time: '2022-11-04T13:00:00+00:00'
end_time: '2022-11-04T15:30:00+00:00'"
please see the message from the bot regarding formatting of code
but this is teh same as the next_start_time and next_end_time attribute
or do you want it for all items in that forecast attribute?
'''forecast:
- stage: 1
start_time: '2022-11-04T13:00:00+00:00'
end_time: '2022-11-04T15:30:00+00:00''''
'''
forecast:
- stage: 1
start_time: '2022-11-04T13:00:00+00:00'
end_time: '2022-11-04T15:30:00+00:00'
'''
please also see the last line of the the bot message!
you can copy the right backticks from the bot message if you need
Thanks, So you helped me with this code:
example:
Loadshedding {{(state_attr("sensor.load_shedding_middelburg",
"schedule_stage"))}} Schedule Tomorrow:
{%- set data = state_attr("sensor.load_shedding_middelburg", "schedule") %}
{%- set start = (today_at() + timedelta(days=1)).isoformat() %}
{%- set end = (today_at() + timedelta(days=2)).isoformat() %}
{%- set data_tomorrow = data | selectattr('start_time', '>=', start) | selectattr('end_time', '<', end) | list %}
{{ as_datetime(start).date() }}
{%- for item in data_tomorrow %}
{{ as_datetime(item.start_time).strftime('%R') }} - {{ (as_datetime(item.end_time) - timedelta(minutes=30)).strftime('%R') }}
{%- endfor %}
Would like to do the same with the above with each stage forcast:
example:
stage: 1
start_time: 2022-11-03T03:00:20.345543+00:00
end_time: 2022-11-03T14:00:00+00:00
ends_in: 265
starts_in: 265
next_stage: 2
next_start_time: 2022-11-03T14:00:00+00:00
next_end_time: 2022-11-04T03:00:00+00:00
forecast:
- stage: 1
start_time: '2022-11-03T03:00:20.345543+00:00'
end_time: '2022-11-03T14:00:00+00:00'
- stage: 2
start_time: '2022-11-03T14:00:00+00:00'
end_time: '2022-11-04T03:00:00+00:00'
- stage: 1
start_time: '2022-11-04T03:00:00+00:00'
end_time: '2022-11-04T14:00:00+00:00'
- stage: 2
start_time: '2022-11-04T14:00:00+00:00'
end_time: '2022-11-05T03:00:00+00:00'
last_update: 2022-11-03T08:26:32+00:00
icon: mdi:lightning-bolt-outline
friendly_name: Load Shedding Eskom Stage
Could you please put some effort in actually using the right code tag
copy paste it if you really need
Figured it out sorry
{%- set data = state_attr("sensor.load_shedding_middelburg", "schedule") %} should be {%- set data = state_attr("sensor.the_sensor_of_which_you_sent_the_data", "forecast") %}
of course replace "sensor.the_sensor_of_which_you_sent_the_data" with the actual sensor
Yeah but i cannot get the result to look as follows:
Example:
Loadshedding Stage 1
2022/11/03
07:00 - 09:00
Loadshedding Stage 2
2022/11/03
16:00-23:00
But you never said that it should look like that ๐
also, the same comment here as for your previous template. These timestamps are UTC, do you want the UTC times, or local time?
Hehe should have indicated that sooner. You deal with alot of requests a day ๐
LocalTime Prefered
{%- for item in state_attr("sensor.the_sensor_of_which_you_sent_the_data", "forecast") %}
{%- set start = as_local(as_datetime(item.start_time)) %}
{%- set end = as_local(as_datetime(item.end_time)) %}
Loadshedding Stage {{ item.stage }}
{{ start.date() }}
{{ start.strftime('%R') }} - {{ end.strftime('%R') }}
{% endfor %}
Thanks looks good, BUt the end time is that same as the start time ๐ฆ
Results:
Loadshedding Stage 1
2022-11-03
05:00 - 05:00
Loadshedding Stage 2
2022-11-03
16:00 - 16:00
Loadshedding Stage 1
2022-11-04
05:00 - 05:00
Loadshedding Stage 2
2022-11-04
16:00 - 16:00
fixed
Your a GOD! Thanks!
I read my Gas consumption via ESPHome and an impulse counter in cubic meters. What is the best way to display this in kWh?
I have all the values of my gas supplier that I need for the transformation. Can I create another sensor that does the transformation on the fly?
Yes, I would just create a template sensor that does the math
hey guys, i have a templating question that i can't quite get my head around
i'm trying to make a voice interface to navigate my tv, and am trying to get it to move up/down/left/right n number of times, where n is given from the voice command. the only issue is that n can be blank, so sometimes the value for n is ''.
here's the code i have so far: http://pastie.org/p/6PebXPAzWSJeWe7AwOauM5
the control and input_repeat are given from the voice command, and since input_repeat can be empty i have a variable called repeat that i want to be equal to input_repeat if it's a number or 1 if it's empty
i tried making it a service but that doesn't work, and now i'm a little stuck on what i should be choosing instead?
variables:
control: "{{ trigger.event.data.action }}"
repeat: "{{ trigger.event.data.number | int(1) }}"
Remove your current lines 11 and 12
And your service call for the script can just be:
- service: "script.tv_{{ control }}"
oh wow, that's cool!
there's one slight issue though - when i send an input with a number it works flawlessly, but when i don't, it doesn't trigger for some reason
like with trigger.event.data.number=''
wait, no, i fixed it sorry
that was on the voice command's end
that's worked so well, thanks!
hi, im asking the question here because i was told in general that is probable template related: i want an automation which is triggered through an dropdown helper. I want the automation to be triggered when that helper changes and to use service light.turn_on to activate a scene with the same name stored in the dropdown helper to be activated. i am having a template which returns the string of the helper, but i dont know ho to integrate that into the service call correctly
{{ states('input_select.nanoleaf_effects') }} this template returns the right string in developer tools
call service requires to put a string after effect:
but my template doesnt work here
got it working now, i was on the right path, but somehow devtools threw an error, dont know why
https://snipboard.io/VwZtCq.jpg this works
good to hear, for future reference, don't post images of code
If I would want to help you make a correction, I would have to type it all over, instead of simply using copy/paste
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
hey guys, i have another question
here's my code: http://pastie.org/p/5x6drGqo5bb3UmBCxCQoWK
i want the value of text to be "Opened {{ tv_source }}" when tv_source != "home" - how would i go about doing that? i can't quite figure out how to best if/else things in these situations?
what should it be if tv_source == "home"
oh, should have mentioned - if tv_source == "home", i want it to be blank and not say anything
{{ iif(tv_source == "home", "whatever you want", "Opened "~tv_source) }}
is one of the possible solutions
ah, so i can do if statements there, that's good to know
what's the ~ do between "Opened " and tv_source?
a concatenation
a + would also work here, but the ~ 'force' implicit conversion to strings, in case your are concatenating integer for instance
Is there an equivalent to
{%- for state in states -%}
{{"\n"}}- {{state.entity_id}}
{%- endfor -%}
to create a list of areas? In the templating docs I only found ways of getting the area_id of an entity, but not how to just find all available areas.
I was able to do this, but it seems overly complicated
{{ states | selectattr('state', 'defined')
| map(attribute='entity_id')
| map('area_id') | unique | reject('none') | list }}
That's what I was going to suggest. I don't know what the first selectattr is doing for you, though
Actually, I was hoping that {{ states|map(attribute='entity_id')|area_name }} would work, but it does not
I have a PR waiting for a similar issue
Filters should always act on iterators, IMHO
I tried without the selectattr but could not get it to work without. That's why I also needed the unique.
every entity has a state
I just tried your template and it worked, then removed |selectattr('state', 'defined') and the result didn't change
for me as well
I do remember seeing a similar issue here before
@dry narwhal what does this return (out of curiosisty)
{{ states | rejectattr('state', 'defined') | list }}
empty list []
Then it should work without the selectattr
My mistake, indeed it does. Must have forgotten to remove the | before. -.-
Is it possible to nest an if statement inside a template?
I would like to exclude all entities containing Light unless selected in the dropdown.
{{ states.sensor|selectattr('name', 'search', states('input_select.dropdown_wildcards')) | selectattr('name', 'search', ' Power') |
{% if states('input_select.dropdown_wildcards') != 'Light' %} rejectattr('name', 'search', 'Light') {% endif %} | map(attribute='name')|list }}```
I could put it around the entire template, but if I could place it inside it would shorten the code.
How do I make a value_template a percentage?
I try this but it's rejected as invalid:
value_template: '{{ ((value | int) / 2300.00 )) | int}}'
Where is value defined?
@icy marsh remove the last )
I figured that out but now it is reading 0%
Is there any way to read the raw value in Home assistant?
If I comment out unit_of_measurement & value_template it is reading 1725 as expected
My goal is to get it showing 75% based on 1725 รท 2300
I try to follow the bad documentation with no examples
I end up with: value_template: '{{ value / 2300 }}'
Which throws an error:
TypeError: unsupported operand type(s) for /: 'str' and 'int'
'{{ (value | int) / 2300 }}' works but it gives a value of 0.0%
binary_sensor:
- name: Camera Car Front
state_topic: "frigate/front_door/car"
device_class: motion
availability_topic: "frigate/available"
unique_id: "camera_car_front"
payload_on: true
payload_off: false
value_template: '{{ value | int > 0 }}'```
I feel like I am missing something so obvious.. but this sensor will not appear for love nor money
No errors to be found anywhere
Is something publishing to that topic?
Yes, but should I be expecting the sensor would not appear until something publishes to that topic?
Well, I'm assuming that you've restarted/reloaded your config since adding the device
Yes!
And you've looked for it in the entities list?
It would be binary_sensor.camera_car_front
Yup, straight up doesnt exist
place the payload_on and payload_off values in quotes as well
no change ๐ข
binary_sensor:
- name: "Camera_Car_Front"
state_topic: "frigate/front_door/car"
value_template: '{{ value | int > 0 }}'
- name: "Camera_Person_Front"
state_topic: "frigate/front_door/person"
value_template: '{{ value | int > 0 }}'```
Simplified, because really I just wanna see the sensor turn up
How do I make value_template return a value based on the input?
Example input value = -3 output = Ok/Good/Whatever
For multiple choices...
What is the value template on?
snmp sensor
Something simple like:
value_template: >-
{% if value == -3 %}
Ok
{% elif value == 1 %}
Good
{% else %}
Whatever
{% endif %}
That sounds right. They really need to expand the documentation with common sense real world examples
There are plenty of examples in the templates and templating documentation, but you are expected to extrapolate from the examples and provide more when you feel that the examples are lacking
I just looked there are 0 in templating doc for "if value"
Could someone please have a peek what is wrong with this template:
{{ ( ( states.sensor.outside_wind_max_speed.state | int > 6 ) and ( ( ( ( as_timestamp(strptime(states.sensor.date_time.state, '%Y-%m-%d, %H:%M') ) - as_timestamp(states.sensor.outside_wind_max_speed.last_updated) ) / 60) | int ) >= 2 ) ) or ( ( states.sensor.outside_temperature.state | int < 1 ) and ( ( ( ( as_timestamp(strptime(states.sensor.date_time.state, '%Y-%m-%d, %H:%M') ) - as_timestamp(states.sensor.outside_temperature.last_updated) ) / 60) | int ) >= 2 ) ) or ( ( states.sensor.openweathermap_wind_speed.state | int > 8 ) and ( ( ( ( as_timestamp(strptime(states.sensor.date_time.state, '%Y-%m-%d, %H:%M') ) - as_timestamp(states.sensor.openweathermap_wind_speed.last_updated) ) / 60) | int ) >= 2 ) ) or ( ( states.sensor.openweathermap_temperature.state | int < 1 ) and ( ( ( ( as_timestamp(strptime(states.sensor.date_time.state, '%Y-%m-%d, %H:%M') ) - as_timestamp(states.sensor.openweathermap_temperature.last_updated) ) / 60) | int ) >= 2 ) ) }}
It errors:
ValueError: Template error: int got invalid input 'unknown' when rendering template (...)' but no default was specified
Sure, but I shouldn't be expected to learn an entire programming language and the docs should cover basic usage
ok
That's because as I said, you're supposed to extrapolate. https://www.home-assistant.io/docs/configuration/templating/#processing-incoming-data
And the very first example on that page shows how to do an if and output some text.
you should use states('sensor.foo') instead of states.sensor.foo.state
and one of these sensors on which you are using the int filter doesn't have a numeric state (probably it's unavailable) and as you did not provide a default for your filter, it fails
https://www.home-assistant.io/docs/configuration/templating/#states Explains the why behind what Fes just said
Thanks for explaining!
Hello, I've created a template that controls a device state and power consumption, this works OK, and is stored in is own yaml file, that latter is included in Home Assistant. All works as intended! The problem is that now I have to replicate this like 50 times. To other devices! It will be a pain to copy and replace this, and a bigger pain if in the future I need to change something! Is there a faster way to do this? Like a pre config generator that changes generates the code based on a Prรฉ diffined pathern? Similar to the Hass-lovelace_gen, but for the config! Thank you.
What does the template look like?
It's a binary_sensor trigger based! That contains the logic. But the information would be easily replicated by a for loop, that would loop the entity names and create the entities
Ok, but what does it look like? As in, the code.
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
I'm not in the pc now! But is that relevant? Is there any kind of generator that does that?
It's relevant because without knowing what kind of device this is coming from and the logic involved, I can't tell you if you're trying to put diesel in a unicycle, or if you will have to copy and paste/generate the YAML using code.
The template creates a entity that is used to harvest information from several entities and then I send it to influxdb to latter use in grafana!
That still doesn't help me figure out what it is actually do. Imagine you're trying to explain gravity inside a gas giant to someone from the the 1300s. Except it's more like you're speaking Esperanto to someone fluent in several of its base languages.
You're using keywords which sound like the right things, but you might still be trying to fly to the moon on that diesel powered unicycle ๐
When I get home latter, I'll copy the sensor yaml code
Sounds like you could use a generator outside of HA, to generate a yaml file, then just !include it in your config.
Then if you change the code, change the "generator".
Like a jinja template (python) or golang template or whatever you're comfortable with.
approach systematically. cut it down, bit by bit, until it works. what you just removed was the problem
grid_export_power:
device_class: power
friendly_name: "Power Sold"
unit_of_measurement: "W"
value_template: "{{ [0 - states('sensor.solarnet_power_grid')|float, 0]|max }}"```
whats the best way to get rid of any decimal places for this sensor template?
im sure there is a round in the line near the float, just not sure how to put it in
for anyone wondering or for future Spaldo, this is what I ended up with:
device_class: power
friendly_name: "Power Sold"
unit_of_measurement: "W"
value_template: "{{ [0 - states('sensor.solarnet_power_grid')|float, 0]|max|round(0) }}"```
hopefully it is correct ๐
Is it correct that I can't use {{ now() }} in my yaml configuration? I need to use a service in a component config with the current time, but this seems not possible?
If templates are allowed that is explicitly stated in the relevant documentation.
How can I write regular expression in condition of the automation??
If want to write the regular expression for state.
in a template condition probably. What are you trying to achieve?
@marble jackal Suppose an IP is coming in a MQTT message and then in condition I want to write that if the IP is in particular range then send a MQTT MSG
Any solution for it ?? @marble jackal
is it only the last part of the ip you want to check on?
{% set ip = trigger.payload %}
{{ ip.split(':')[-1] in range(100,150) }}
I want to check starting part of the IP...
if the IP is 10.xx.xx.xx or not?? @marble jackal
Please stop tagging me
Okay sorry
{% set ip = trigger.payload %}
{{ ip.split(':')[0] == '10' }}
It's not working if I write this condition directly in state.
@prime kindle I converted your message into a file since it's above 15 lines :+1:
@marble jackal Pls help...
Sorry for the tagging...but I need help in urgent
it was meant as a condition, not as a trigger
and I'm at work, so I can't help at the spot
condition:
- condition: template
value_template: >
{% set ip = trigger.payload %}
{{ ip.split(':')[0] == '10' }}
but this will only work on the mqtt trigger
you didn't say before there is also a state trigger
No this is state trigger
Hey All - Fairly new to HA (been using it about 3 weeks) and slowly getting to grips with it. I need a bit of guidance on a template though.
I've made a web scraper which checks my councils website and retrieves one piece of info "bin type & date of next collection". I'm saving the output into a sensor then displaying that sensor in an entities card on the dashboard. All works well, but the text on the entities card doesn't read nice, it looks like this:
RECYCLING + FOOD WASTE Thursday 10
November
when I'd like to read:
RECYCLING + FOOD WASTE
Thursday 10 November
I believe the correct thing to do is add a value template to the sensor which manipulates the string and inserts a line break after the word "waste" (waste will always appear in the same place every scrape). Is that about right? If so, where to start?
Thanks in advance!
{% set txt= "RECYCLING + FOOD WASTE Thursday 10
November" %}
{{txt | regex_replace("\n"," ") | regex_replace("WASTE ","WASTE\n")}}
it will remove the first carriage return, and add a new one after WASTE
Hey guys so with the new History function in 2022.11 min,max,mean are we now possible to create a sensor for like min as example temperature daily,monthly etc.?
You started your question by stating it was from an incoming MQTT message, so that sounds like an MQTT trigger
Yeah...after this trigger I have to write a condition that the state should come like this
So basically I have to make changes in condition state
Thanks, I'll give it a go
I am trying to make an automation that gives me notifications if someone makes a temp change on home assistant and who did it, and to make a notification if someone changes it from the thermostat without the userrname.
I got the notifications working for the physical thermostat changes but if you change the min/max set temp from Home Assistant it doesnt trigger.
@slender plaza I converted your message into a file since it's above 15 lines :+1:
@slender plaza change your triggers to numeric_state https://www.home-assistant.io/docs/automation/trigger/#numeric-state-trigger
It was a above and below value, I dont want that. I want it to trigger on any change for this.
I think I know what I need now, how do I make the climate/thermostat card trigger when the high setpoint or low setpoint is changed from the card?
@slender plaza you're right, my apologies for that. ๐
Your next question is more #frontend-archived but this looks like it will expose the setpoints https://github.com/nervetattoo/simple-thermostat
what problems?
Im trying to make a template sensor that references it's own state as part of the template, but the issue I'm running into is that the state of the template entity itself is unkown for a couple seconds at startup, so it can never reference itself again, since its state is unkown.
Is this fundamentally how it should work and am I out of luck? Or can I maybe force the sensor to update x seconds after boot? Or make it retain it's value after a restart?
You should be using is_state to get the state, then it will fail gracefully. That combined with a default should do it
https://www.home-assistant.io/docs/configuration/templating#states
The warning box tells you about using is_state, default is also mentioned on that page
I am using is_state, and I cant use a default because I want the default to variable itself. So if it defaults to unkown, it can never reference itself again
What is it exactly that you're trying to do?
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
I have a total_solar_today sensor, that goes unavailable at night, since the inverter doesn't get power at night. So I'm using a template sensor to keep displaying the total_solar_today until the sun rises again
so the template state is either the original sensor, or the last value of the template sensor itself
Try looking at mqtt sensors to accumulate the data
oh that might work
Or that, better idea Fes ๐
trigger:
- platform: state
entity_id: sensor.total_solar_today
not_to: unavailable
sensor:
- unique_id: template_sensor_whatever
name: whatever
state: "{{ trigger.to_state.state }}"
Something like that
thanks! thats a lot shorter than I was brewing up before
Hi, I am trying to write a wait template that waits until a binary_sensor changed to a state for a certain time (e.g. 2 minutes). Can someone help me with the template?
There's an example in the docs, it's 10 minutes not 2, but I'm sure you can figure it out
I have read this page 20 times and have never seen the example. I am sorry and thanks so much! ๐
Ah wait, I am using this in a script so I think I cannot use the "wait for trigger" as I do not have the entity as a trigger in this context
It's a trigger, not the trigger
wait_for_trigger:
- platform: state
entity_id: binary_sensor.your_sensor_name_here
to: "on"
for: 2
But the documentation says "This action can use the same triggers that are available in an automationโs trigger section." and I think I have tried it before and it didn't work when I used any trigger.
can use the same triggers, not must
I will give it another try. ๐
And it may not have worked before because if you edited automations before the 2022.11 update then it reloaded all your automations/scripts which would have cancelled any waits or delays
Thanks a lot!
As far as I know this will be 2 seconds, not 2 minutes
Whoops, yup. But you can indent minutes beneath the for and specify it there instead ๐
I have an automation that notifies if the setpoint is changed, however we also get a notification when the setpoint is changed by a preset (home/away). How do I go about stopping the automation if the setpoint is changed by the preset?
@slender plaza I converted your message into a file since it's above 15 lines :+1:
hey guys, i have a templating question - here's my code so far: http://pastie.org/p/7pMVwPunhyba2uvEsampN6
i've got some code that i'm running to navigate my tv with voice commands, and i want to say something like "go up 2 and right 4", but i might not have the second part of the command (i might just say "go up 2", and when that happens then command2 == ''
how can i get the repeat to run only when command2 != ''?
oh wait, i can make another variable to check if command=='', and if so, do an iif statement to either spit out repeat2 or 0, depending what it is - and if command2=='', then the repeat count will be 0 which means it won't run, right? is that a good way to do things or is there a better way i should be using?
Is there any way (and is it expected) to expand a group if its entities are unavailable? For example, if Z2M is offline or the device is unavailable, I just get an empty array for expanding a group in the template editor.
If it matters, it's a light group
The state of entities in a light group should have no bearing on your ability to expand it
That's what I'd think
Do they still show up in the attributes of the light group?
In states, no. But they still show up in group options
Likely connected state_attr('light.living_room','entity_id') in that scenario returns None
If you don't see them in
-> States, yes. I wouldn't have expected that to be dynamic
In any case, I confirmed that the state of the entities doesn't matter
If they literally disappear, I don't know
Yeah, seems weird, I'm not sure what else to try to figure out the actual issue though if the unavailability shouldn't be the thing causing this
You keep 'unavailability', but that implies a state, which doesn't matter
I found a template on reddit that allows me to find all the devices in my house that haven't updated in X hours, is there a way to limit it to only a certain integration?
It also implies that an entity exists
Right ... again, that was my initial assumption causing this, but you're saying it doesn't. If that's not the cause, I'm stumped as to what would be the cause as the unavailability seems to be the trigger that causes this. If they become available again, everything is ๐
Probably with expand(integration_entities())
Are the entities themselves disappearing?
They're still in states w/ a state of unavailable
And they appear and disappear from the entity_id attribute in your light group?
Yup
Ok
I manually set a state of a light and it did not, but ๐คท
But I don't use that integration
https://imgur.com/a/JHoe2kk screenshot of the 2 states, if it helps
Likely something w/ the MQTT integration that causes it. I tried a binary sensor group as well w/ the same result
Eh... same thing happes w/ ZWave JS looks like though
Looks like it was reported a while ago w/ no traffic: https://github.com/home-assistant/core/issues/77511
It occurred to me that changing the state isn't the same as the availability property changing, so that's probably why I didn't see it
Ah, gotcha
It's probably considered a feature that only available entities are listed
Well that's not entirely true either... all entities are listed as long as there's >0 available entities
Seems like less of a feature and more of not writing the entity_ids attribute when the group is unavailable
how can I check if all lights in some group are turned off? I need condition if at least one light or more turned on to keep with automation
Hi guys, can someone help me? Im stuck with a template problem. I have a mqtt topic with 5 sensors inside the same topic. I dont know how to get those inside HA with templating.
The device keep rewriting on the topic with the 5 sensors updates, just like that:
05/11/2022 15:28:53
{"variable":"EPT_C", "value":1.38,"unit":"kWh"}
05/11/2022 15:28:53(-0 seconds)
{"variable":"EPT_G", "value":19.65,"unit":"kWh"}
05/11/2022 15:28:53(-0 seconds)
{"variable":"IA", "value":18.50,"unit":"A"}
05/11/2022 15:28:53(-0.05 seconds)
{"variable":"UA", "value":239.28,"unit":"V"}
05/11/2022 15:28:53(-0.06 seconds)
{"variable":"PA", "value":-4451.24,"unit":"W"}
Hi there, I have around a hundred Shelly units and the updates for them show up nicely in Home Assistant. But right now I still have to update them one by one. Does anyone know how I could use a template with the update.install service to update all shelly update entities at once?
Hey guys so with the new History function in 2022.11 min,max,mean are we now possible to create a sensor for like min as example temperature daily,monthly etc.?
template:
- button:
- name: Update Shellies
unique_id: button_update_all_shellies
device_class: update
press:
- service: update.install
target:
entity_id: "{{ expand(integration_entities('shelly')) | selectattr('domain', 'eq', 'update') | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}"
@severe hatch I converted your message into a file since it's above 15 lines :+1:
@severe hatch this is not related to templates, better ask in #energy-archived
oke, thx!
You are my hero! Thanks a million!
hey, im trying to debug an integration for a developer and the instructions are to "set debug-level logs for home assistant.components.lametric and demetriek"...how exactly do I do this? I presume it goes into my config.yaml, somehere?
how can I check if all lights in some group are turned off? I need condition if at least one light or more turned on to keep with automation
Hi! How would I write a single template entry to use 'current_temperature' attribute from all available climate entities and create a sensor from it?
Redirected here from #automations-archived, attempting to streamline presence based automation with ESPresence, suggested to use a template sensor to track # of devices with the proper state, linking to here: https://www.home-assistant.io/integrations/template#state-based-template-binary-sensors-buttons-numbers-selects-and-sensors
I'm new to templates in general, how can I apply this to my usecase?
Take a look at the examples under https://www.home-assistant.io/integrations/template#rate-limiting-updates, those show a way of counting entities in a certain state. Should be under the sensor map though, not binary_sensor.
- name: tesal-model-x-rated-range
unique_id: 3a33104e-42d7-4e4e-b705-38437556520c
unit_of_measurement: Km
state_class: measurement
state: >-
{{ ((states('sensor.tesla_rated_battery_range_km') | float - states('sensor.tesla_battery_level')) * 100) | round }}
can some help me this ttemplate does not work
You didn't convert the second state to a float
- name: tesal-model-x-rated-range
unique_id: 3a33104e-42d7-4e4e-b705-38437556520c
unit_of_measurement: Km
state_class: measurement
state: >-
{{ ((states('sensor.tesla_rated_battery_range_km') | float - states('sensor.tesla_battery_level')) | float * 100) | round }}
this still does not work
you still didn't convert the second state to a float
how do I do that
no I don't see it
ok
I got it thank you for your help๐
Hi, semi new to templates and got something I can't figure out. How do I get just the day value out of a date? And even better can it be convert to the 1st, 2nd, 3rd, 4th, form of the number?
@tropic hill I converted your message into a file since it's above 15 lines :+1:
Anyone know why this not working?
{% if is_state('sensor.living_room_humidity', '0') %}
Off
{% elif is_state('sensor.living_room_humidity', '<50') %}
Good
{% elif is_state('sensor.living_room_humidity', '>50') %}
Very Good
{% endif %}
is_state calculates equivalence, not comparison
{% if is_state('sensor.living_room_humidity', '0') %}
Off
{% elif state('sensor.living_room_humidity') | int(0) < 50 %}
Good
{% elif state('sensor.living_room_humidity') | int(0) > 50 %}
Very Good
{% endif %}
Thank you, I pasted it in HomeAssistant but only the code is shown in the card.
Well that's because it's a template, so you'd make a template sensor and show the sensor in the card
Okay, so what would I need to change to get the sensor recognized?
No, you make a template sensor
I unterstand. Is this right?:
template:
- binary_sensor:
- name: "Sensor"
state: "{% if is_state('sensor.living_room_humidity', '0') %}
Off
{% elif state('sensor.living_room_humidity') | int(0) < 50 %}
Good
{% elif state('sensor.living_room_humidity') | int(0) > 50 %}
Very Good
{% endif %}"
- name: "Sensor"
states()
Not quite:
template:
- binary_sensor:
- name: "Sensor"
state: >-
{% if is_state('sensor.living_room_humidity', '0') %}
Off
{% elif states'sensor.living_room_humidity') | int(0) < 50 %}
Good
{% elif states('sensor.living_room_humidity') | int(0) > 50 %}
Very Good
{% endif %}"
Yeah, that's my fault on the state/states messup, I typoed ๐คช
it won't be obvious what binary_sensor.sensor is, though
Very trye
Shouldn't that be a standard sensor, as it has > 2 states?
Hello everyone, is there any reason why this template sensor would not be created by Home Assistant after restarting if it has been inserted inside configuration.yaml?
- platform: template
sensors:
duree_ecoulement_eau_principale:
friendly_name: Durรฉe d'รฉcoulement de l'eau principale
unit_of_measurement: "sec"
value_template: >
{% set t = this.state if states('input_boolean.eau_principale_on_off') == 'off' else now().timestamp() - states.input_boolean.eau_principale_on_off.last_changed.timestamp() %}
{{ t | round(2, 'common') }}
Thanks
I have used a value_template in the past to combine several states into one combined state, however the method of doing it has changed. I cannot make sense of the documentation, what platform would something like this fall under? state?
That link has an example
you can still use the old ones?
yes
- platform: template
sensors:
friendly_name: "Total Light Energy Spent"
unit_of_measurement: "kWh"
value_template: "{{ ( states('sensor.ensuite_ceiling_energy')|float + states(`sensor.ensuite_vanity_energy`)|float + states('semsor.toilet_ceiling_energy')|float ) }}"
that should work?
I don't see why not
Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: unexpected char '`' at 60) for dictionary value @ data['sensors']['total_light_energy_spent']['value_template']. Got "{{ ( states('sensor.ensuite_ceiling_energy')|float + states(`sensor.ensuite_vanity_energy`)|float + states('semsor.toilet_ceiling_energy')|float ) }}". (See ?, line ?).
Invalid config for [sensor.template]: expected dictionary for dictionary value @ data['sensors']. Got None. (See ?, line ?).
bummer
whoops, used ` instead of '
I'm trying to help someone but can't figure out what he did wrong.
Have a look at this picture: https://community.home-assistant.io/t/using-esphome-to-build-a-water-flow-rate-meter/119380/178?u=donparlor
Is there a problem with his configuration.yaml file?
Yes
There's no sensor:, as in the docs
That's why I asked, and gave you a pointer to the docs
After looking at your pointer in the docs, I tried correcting the syntax and form, does it look better like this:
sensor:
- platform: template
sensors:
duree_ecoulement_eau_principale:
friendly_name: Durรฉe d'รฉcoulement de l'eau principale
unit_of_measurement: "sec"
value_template: >
{% set t = this.state if states('input_boolean.eau_principale_on_off') == 'off' else now().timestamp() - states.input_boolean.eau_principale_on_off.last_changed.timestamp() %}
{{ t | round(2, 'common') }}
This is using the legacy syntax, I'd recommend moving to the new format. https://www.home-assistant.io/integrations/template/#legacy-sensor-configuration-format
Hello everyone, how can I set up a serial port reader (serial:) that sends a single data each time, to an all-in-one sensor. the serial object is working, it's reading very very fast tho. and I wonder how can I template every data into a single sensor. (after parsing)
#- platform: serial
# name: USBTeleInfo
# serial_port: /dev/ttyUSB0
# baudrate: 1200
# bytesize: 7
# parity: E
# stopbits: 1
# xonxoff: false```
works, very fast, and the data is a raw string that needs to be trimmed/split whatsoever
hmmmm, should I use AppDaemon maybe?
anyone know why this not working?
template:
- binary_sensor:
- name: "Luftfeutigkeit"
state: >-
{% if is_state('sensor.living_room_humidity', '0') %}
Off
{% elif states'sensor.living_room_humidity') | int(0) < 60 %}
Nicht optimal
{% elif states('sensor.living_room_humidity') | int(0) > 60 %}
Optimal
{% endif %}"
- name: "Luftfeutigkeit"
missing a ( on your first elif. You should take a look at the error in the log
also... should be under the sensor map not binary_sensor
Not working
Code:
template:
- sensor:
- name: "Luftfeutigkeit"
state: >-
{% if is_state('sensor.living_room_humidity'), '0') %}
Off
{% elif states'sensor.living_room_humidity') | int(0) < 60 %}
Nicht optimal
{% elif states('sensor.living_room_humidity') | int(0) > 60 %}
Optimal
{% endif %}"
- name: "Luftfeutigkeit"
Error:
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got '{% if is_state('sensor.living_room_humidity'), '0') %}\n Off\n{% elif states'sensor.living_room_humidity') | int(0) < 60 %}\n Nicht optimal\n{% elif states('sensor.living_room_humidity') | int(0) > 60 %}\n Optimal\n{% endif %}"'. (See /config/configuration.yaml, line 17).
Iยดm sorry. Fixed. It is possible to reload the file without restarting HA?
File... no. Template entities specifically, yes. Dev Tools-> under YAML configuration reloading, hit Template Entities
Add a default? int(0)
unavailable can't be cast as an int
You probably have an error in your template that's making it unavailable
log
@obtuse zephyr iยดm sry. I have one question it is possible to change the code that the Text is optimal if the temperatur from the sensor is between 17-20 C? I have tried a few things, I do not know what to do right now.
{% elif states('sensor.living_room_humidity') | int(0) > 60 %}
Optimal
I can't say I completely follow... you only want optimal to be displayed if the humidity is > 60 and the temp is between 17 and 20 C?
I want to display "Optimal" if the Humidity is under 60% and the Temperature between 17-25C. And "Nich Optimal" if the Humidity over 60% or the Temperature over 25C or under 17C. I hope you can follow me.
I do... I think you've got your operators confused
< is less than
and > is greater than
If you've got a separate entity for temp, something like {% if states('sensor.living_room_humidity') | int(0) < 60 and states('sensor.living_room_temperature') | int(0) >= 17 and states('sensor.living_room_temperature') | int(0) <= 25 %} could work for your optimal condition
might wanna pull the temp/humidity out into their own variables for cleanliness, too
{% if is_state('sensor.living_room_humidity'), '0') %}
Off
{% elif states('sensor.living_room_humidity') | int(0) < 60 and states('sensor.living_room_temperature') | int(0) >= 17 and states('sensor.living_room_temperature') | int(0) <= 25 %}
Optimal
{% else %}
Nicht optimal
{% endif %}
Hi guys,
Can someone help me with a template for when the phone is not in_vehicle for a specific amount of time? I'd like to use it as an automation trigger
I've gotten this far but don't know how to specify for a period of time
{{ states.sensor.rani_f3app_detected_activity.state != "in_vehicle" }}
Thanks Rob
The problem is that the app changes between many states (on foot, still etc) very frequently. So I can't set the trigger as "if state changes from in_vehicle to any the other state.
That just leads to the automation triggering way too often.
Instead, I'd like to specify that if the state hasn't changed to in_vehicle for 10 minutes, then it's safe to assume that I'm not at a traffic light
You can add a not, it's referenced in the docs Rob linked
https://www.home-assistant.io/docs/automation/trigger/#state-trigger: not_from and not_to
I have a problem with !include_dir_merge_list in configuration.yaml for utility meters.
#configuration.yaml
utility_meter:
test_power_um_hourly:
source: sensor.test_power
name: Test energi dag
cycle: hourly
(above works)
however putting this in configuration.yaml does not work:
#configuration.yaml
utility_meter: !include_dir_merge_list /utility_meters/
I've found a thread with same problem:
https://community.home-assistant.io/t/can-not-include-utility-meter-in-dir/348286
however the fix was to use !include_dir_MERGE_list, which I already do
anyone knows about this?
it doesn't look like it expects a list
I suspect you want !include_dir_merge_named instead
Great, thank you.
Can I also apply this in conditions somehow?
condition: state entity_id: sensor.rani_f3app_detected_activity for: hours: 0 minutes: 3 seconds: 0 state: In_vehicle
So basically, the trigger is if state doesn't change to in_vehicle for X period of time, and the condition that I was in fact driving within the last 3 minutes. Then perform the action
Apologies if I'm not making sense, I'm struggling to put automation together
Dunno the difference but I tested "named" also and it didn't work either. No utility meters show up
Described in the docs: https://www.home-assistant.io/docs/configuration/splitting_configuration/#advanced-usage
it determines whether you need a list or a dict
"doesn't show up" just means that you need to run a config check
Hello,
I want to put a template condition which will check if some light from group of lights, or some media_player or swith from their respective groups is at least one turned on, to trigger automation
how can I do this
For examle I have script: "Goodbye Home" where I turn off everything in my house. the trigger is changing my zone from House to Away or other zone, so basically I want to trigger this automation only if there need to do (at least one light, or switch, or media_player is turned on)
similar to Stefans request, I'm trying to do something I assumed would be simple but alas. I have a card on my dashboard which lists lights that are turned on, allowing me a quick overview. Using state_filters this all works great. The issue is that I now manually hardcode each light.<name> to the filter card config.
A quick google led me to lovelace-auto-entities but it seems a bit overkill to intall a addon
just to iterate over a json-collection
alias: ForEachTest
sequence:
- repeat:
for_each: >-
{{states.input_boolean | selectattr('entity_id', 'search', 'missed') | map(attribute='name') | list}}
sequence:
- service: input_boolean.turn_off
data: {}
target:
entity_id: {{ repeat.item }}
mode: single
Just trying to figure out syntax to run this for each script.
Message malformed: not a valid value for dictionary value @ data['sequence'][0]['repeat']['sequence'][0]['target']['entity_id']
when I attempt to test it.
you want entity_id and not name
ahhh
still doesn't like it.
same message
Message malformed: not a valid value for dictionary value @ data['sequence'][0]['repeat']['sequence'][0]['target']['entity_id']
alias: ForEachTest
sequence:
- repeat:
for_each: >-
{{states.input_boolean | selectattr('entity_id', 'search', 'missed') | map(attribute='entity_id') | list}}
sequence:
- service: input_boolean.turn_off
data: {}
target:
entity_id: {{ repeat.item }}
mode: single
is the problem that I can't do loops in filter card scripts or why is it I can't easily just iterate over a filtered array?
you're trying to do this in a frontend card?
that's a script. it doesn't go in a card
so just call the script
Rob, i just realized you may not have been talking to me.
do you recommend I install the lovelace addon?
oh, sorry
@uneven pendant he was ๐ He is helping both of us
I'm using half my brain to talk to two different people and it's not going well
Well you were first so i'll be patient.
honestly I think you where... and we're lucky to both have RobC here tonight
so I'll wait my turn... politeness on the interwebz....that was a long time ago ๐
@inner mesa Should I just manually add all entity_ids, try to link from the frontend-card to a script or install https://github.com/thomasloven/lovelace-auto-entities ?
You need quotes around that single line template
seems those are my three options here
oh, ok, lemme try
entity_id: "{{ repeat.item }}"
yeah, that too
That did it.
Thank you guys.
now i don't have to edit all this every time I add an input boolean entity
and wth is lovelace cards anyway? Can't find any card type with that name.
"Lovelace" is the former name of the dashboard
