#templates-archived

1 messages ยท Page 14 of 1

inner mesa
#

that's too complicated

#
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 }}
bronze prawn
#

Got it! Thanks for your help @inner mesa

wind flare
#

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.

inner mesa
#

The new format is under template:, so if you really want to put them under sensor:, yes, you need to use the old format

wind flare
#

Ah okay. Was just trying to be tidy. Thanks!

atomic blade
#

Why is this returning an empty array?
states|expand|rejectattr('device_class', 'undefined')|list

inner mesa
#

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

atomic blade
#

Oh huh. I was using it in another template I had as a filter

inner mesa
#

hmm

atomic blade
#

I guess I don't actually need expand in this case anyways it seems

inner mesa
#

that's true too

atomic blade
#

states|rejectattr('attributes.device_class', 'undefined') This seems to work

inner mesa
#

yes

inner mesa
atomic blade
#

That doesn't seem good if something works in the editor but not elsewhere

#

I am using it in a node red flow though

inner mesa
atomic blade
#

Nice looking PR

inner mesa
#

petro broke it, so need to fix the merge conflict this weekend ๐Ÿ™‚

atomic blade
#

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

inner mesa
#

not really

atomic blade
#

:/

round pecan
#

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.

marble jackal
marble jackal
round pecan
#

@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

rare linden
#

does this.entity_id not work on binary sensors?

mighty ledge
#

It works

marble jackal
#

Only in the new format maybe?

atomic python
#

anyone know how to extract the icon name from weather.home?
something like {{ state_attr('weather.home', 'icon') }} but that actually works

lone birch
#

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?

undone dagger
#

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?

marble jackal
#

You need to add a - before sensor

#

And before trigger as well

#
- sensor:
    - name:
      state:
    - name:
      state:
- trigger:
    - platform: bla
  sensor:
    - name:
      state:
undone dagger
#

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

vivid ridge
#

Right

hard topaz
#

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?

buoyant pine
#
{{ state_attr('climate.thermostat', 'current_temperature') }}
hard topaz
#

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.

hard topaz
#

I scrolled right past that section, as I assumed 'attirbute' would be it's own section, not directly under state.

buoyant pine
#

but yeah, lots on that page

hard topaz
#

ha! yeah, i scrolled right by that.... because... well, I'm not too bright.

#

but appreciate the point in the right direction.

plain magnetBOT
marble jackal
#

@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

thorny snow
#

Ok thx for that! Can legacy #3 be written as #2 then?

#

and can #4 be written in another way?

marble jackal
thorny snow
#

@marble jackal I am trying to rewrite #3 as #2 but I just don't get it to work.

  1. First of I had to manually use "space" on all lines instead of "tab", as the intendations would be wrong all of a sudden.
  2. on - name: "abc" it warns that it is "Missing property "state""
  3. on value_template: it now warns that "Property value_template is not allowed"
marble jackal
#

2 and 3 are both correct ๐Ÿ™‚

plain magnetBOT
marble jackal
#

Have a look at the documentation there

#

It's not as simple as just copying what you had under a new key

thorny snow
#

Ah.. ok seems like it is more legacy in the code then, thx

red rose
#

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"?

vocal agate
#

Good morning. I try to monitor the CPU of the server but every sensor is disabled by integration?

floral shuttle
#

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

marble jackal
#

So that timestamp from the integration is UTC?

floral shuttle
#

yes i believe so

marble jackal
#

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) }}

floral shuttle
#

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

marble jackal
#

When did it actually start? In NL time

floral shuttle
#

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 โ€ฆ.

marble jackal
#

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

floral shuttle
#

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 ?

marble jackal
#

Unless the timezone on the device is incorrect

floral shuttle
#

Exactly. But there probably is no way to set thatโ€ฆ

stark patrol
#

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.

inner mesa
#

first

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

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.

stark patrol
#

Ah yes.

inner mesa
#

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

stark patrol
inner mesa
#

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

stark patrol
#

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?

inner mesa
#

I don't understand the question

#

you need to quote strings, that's all

stark patrol
#

To be sure:

#

"{{ (state_attr('sun.sun','next_rising')}}"
or
{{ (state_attr('sun.sun','next_rising')}}

inner mesa
#

it depends on whether you're building a single-line template or multiline

stark patrol
#

Riiiiight!

#

That explains why I keep seeing it in some and not others.

inner mesa
#

quote single line, don't quote multiline

stark patrol
#

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?

inner mesa
#

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

stark patrol
#

I've checked the quote mark errors, but it seems like it still isn't happy

inner mesa
#

keep looking ๐Ÿ™‚

stark patrol
#

Specifically the timestamp section, does that look accurate?

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

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.

stark patrol
#

If I can get this one right, I can fix all of them.

inner mesa
#

no, you're still using " inside and " outside

#

same thing I quoted earlier

stark patrol
#

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

inner mesa
#

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

stark patrol
#

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.

inner mesa
#

it's not specific to timestamp elements

#

it's a general rule

#

consider what the YAML parser will do with it otherwise

stark patrol
#

I don't know a lot about this, but this is a good way to learn.

inner mesa
#

"{{ "a" }}" is a mess

stark patrol
#

Thanks Rob!

dry narwhal
#

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?

inner mesa
#

if you use input_select.set_options, yes

dull burrow
#

What would be a use case for that?

inner mesa
#

I can see a use case to dynamically set the options in an input_select

dull burrow
thorny snow
buoyant pine
#

Remove sensor. from sensor.nibe_prio_state

thorny snow
earnest cedar
#

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)

dry narwhal
# dull burrow What would you use that for specifically?

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*).

dull burrow
dry narwhal
#

Yes, exactly

dull burrow
#

what would you use that dropdown for? just to add to a dashboard?

dry narwhal
#

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

dull burrow
dry narwhal
#

Yes, exactly.

#

Seems like sharing images is forbidden in this channel

dull burrow
#

you can pm me

dry narwhal
#

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

dry narwhal
dreamy sinew
#

|map(attribute="name')|list|join(', ')

#

to the thing that just went away ๐Ÿ˜ฆ

pastel crescent
#

Yes, I always find the answer immediately after asking

dreamy sinew
#

haha

#

rubber duck debugging

pastel crescent
#

Second question, is there a way to add a natural language "and" between the last and second-to-last elements of a list?

dreamy sinew
#

that gets wonkier

#

possible but rough

pastel crescent
#

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

dreamy sinew
#

can you post the full template again?

#

you can slice the list but you should assign it to a var

pastel crescent
#

{{ expand('group.openings') | selectattr("state", 'eq', 'on') | join(', ', attribute="name") }}

dreamy sinew
#
{{ "{} and {}".format(open_openings[:-1], open_openings[-1]) }}```
pastel crescent
#
{{ "{}, and {}".format(open_openings[:-1]|join(', '), open_openings[-1]) }}``` needed minor tweak
#

tysm

dreamy sinew
#

ah yes. good catch

dry narwhal
floral shuttle
#

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: input_select.select_option
            target:
              entity_id: input_select.mode
            data:
              option: '{{option}}'```
marble jackal
#

why combine a select with an input_select for this? Couldn't you do it all witth only the select

floral shuttle
#

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...

marble jackal
#

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

floral shuttle
#

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?

marble jackal
#

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

floral shuttle
#

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

dry narwhal
#

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.

marble jackal
#

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

marble jackal
#

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

plain magnetBOT
dry narwhal
#

So create the list of entities from a template and then apply them all as separate list items.

marble jackal
#

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

dry narwhal
marble jackal
#

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

dry narwhal
#

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)

marble jackal
#

But what do you want to happen when an option is selected?

distant plover
#

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

marble jackal
distant plover
#

Hmmm.... what does false do? ๐Ÿ˜„

woven lava
#

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.

distant plover
#

oh, Filter timestamp_custom(format_string, local=True, default)

woven lava
#

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

floral shuttle
#

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)}} ?

marble jackal
#

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) }}

floral shuttle
#

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?

marble jackal
#

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

floral shuttle
#

exactly. good point to make notice though. thks! will continue....

#

also, in that new format, we can use either [. ] or (. )

thorny snow
#

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

floral shuttle
#

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

dry narwhal
# marble jackal But what do you want to happen when an option is selected?

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 ๐Ÿ˜„

floral shuttle
#

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

thorny snow
#

Ok, thanks. Will make it an automation then

jagged dune
#

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.

jagged dune
#

Or do you perhaps know a better way to combine the 2 values?

inner mesa
#

You just provide a default for each state

jagged dune
#

So, |float(0)?

inner mesa
#

If you want zero to be the default in that case, yes

jagged dune
#

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

mighty ledge
#

you have to use it on both states() calls

#

and reload templates

jagged dune
#

Yes i did.
I forgot to change the entity in my dashboard to the correct one ๐Ÿคช

#

It is working, thanks a lot!

rare sage
#

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"

marble jackal
#

The second item is also today

#

If today is 1st of November (it's still 31st of October here)

rare sage
#

I know

#

That a schedule for tomorrow, I want to notify before it happed daily

marble jackal
#

I don't understand what you want to achieve

rare sage
#

I would only like to return the days for tomorrow

#

not the full list

marble jackal
#

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

rare sage
#

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

marble jackal
#
{%- 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
rare sage
#

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)?

marble jackal
#

For today it's

#
{%- set start = today_at().isoformat() %}
{%- set end = (today_at() + timedelta(days=1)).isoformat() %}
rare sage
#

How would i use this in a notification?

marble jackal
#
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 %}
rare sage
#

Thanks bro, just got it working... Your a legend!

#

One last question, How do I remove 30 minutes from the end time?

#

@marble jackal

marble jackal
#

(today_at() + timedelta(hours=47.5)).isoformat()

#

Oh wait, that's not what you mean

rare sage
#

Yeah was about to sayu

#

the schedule end_time says 7:30 but will come back on at 07:00

marble jackal
#

{{ (as_datetime(item.end_time) - timedelta(minutes=30)).strftime('%R') }}

#

Instead of what is there now in line before the last

rare sage
#

I found it

#

Thanks

#

Thats perfect

pine belfry
#

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

dry narwhal
# floral shuttle did you check the link to my Hue scenes setup? because thats exactly what that d...

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.

marble jackal
# rare sage Thats perfect

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?

plain magnetBOT
floral shuttle
#

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 ๐Ÿ˜‰

dry narwhal
#

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.

floral shuttle
#

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.

distant plover
marble jackal
#

what is the time in the input_datetime and what does now() return

distant plover
#

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.

marble jackal
#

oh, it's a time only input_datetime, that is good to know

distant plover
#

Ah, yes. ๐Ÿ™‚

#

It's set like this on line 21.: time: "{{ (now() - timedelta (minutes=5)).strftime('%H:%M:%S') }}"

marble jackal
#
{{ (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) }})

distant plover
#

Same here

marble jackal
#

So that's correct right?

distant plover
#

Yes.

#

But the notification I got showed 00:28:21

marble jackal
#

yes, but you didn't use the template I just provided at that time

#

so replace it ๐Ÿ™‚

distant plover
#

Hahah... I thought you just pasted what I had ๐Ÿ˜„

marble jackal
#

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?

distant plover
#

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

marble jackal
#

that timestamp is a timestamp of 9:03 on 1st of January 1970

#

so it will apply DST for that date

distant plover
#

I guess line 21 is a bit silly perhaps then?

marble jackal
#

I would use an input_datetime with date and time

distant plover
#

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.

marble jackal
#

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

dry narwhal
#
card:
  type: custom:auto-entities
  sort:
    method: state
    numeric: true
    reverse: true
  filter:
    include:
      - entity_id: ${ states['input_select.entity_dropdown'].state }
distant plover
#

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).

dry narwhal
#

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.

marble jackal
dry narwhal
#

Populate the dropdown rather than auto-entities populating apexcharts

floral shuttle
#

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

distant plover
dry narwhal
# floral shuttle or, trigger on another input_select:``` - platform: state entity_i...

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?

floral shuttle
#

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?

dry narwhal
floral shuttle
#

yo can use templates in auto-entities, but you need to create a valid jinja template and return a list

#

a, missed that , sorry

dry narwhal
#

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?

floral shuttle
#

but, that seems like a lot of work for simply returning 1 option of an input_select....

dry narwhal
#

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

floral shuttle
#

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 ...

dry narwhal
#

The wildcard expressions are only 4. So not a lot of work.

dry narwhal
#

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?

floral shuttle
#

well, its all there. I have 2 automation to auto populate the input_selects, based on the jinja templates.

dry narwhal
#

so it needs default รฒptions`

floral shuttle
#

the rest is all done in the frontend

floral shuttle
#

might I suggest you move this to the community, where it's way easier to share your code in 1 view

dry narwhal
#

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.

floral shuttle
#

return question: did you try ;-/

mighty ledge
#

or you make a select template, but the selection doesn't persist on restart like input_selects.

marble jackal
#

Yes, I noticed you also voted on my WTH about that

mighty ledge
#

yah, I assumed that the people who added the persistent state to templates did it for everything, they did not

marble jackal
#

I tried to convert it to a trigger based select, but even then no psersistant state

dry narwhal
unreal merlin
#

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?

dry narwhal
#

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 ๐Ÿ˜ฆ

inner mesa
#

EZPZ

dry narwhal
#

And I don't think can use selctattr because entity_id is not an attribute, or is it?

inner mesa
#

that's not what that means

dry narwhal
#

Ah, so it is not an attribute as shown in developer tools?

inner mesa
#

{{ 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

dry narwhal
#

Oh, match! I was trying 'eq' as in the examples from mariustHvdB

inner mesa
#

That would be 'equal'

dry narwhal
#

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

inner mesa
#

That would be 'in'

#

But it will match it anywhere in the string

dry narwhal
#

`Then what is the difference between 'in' and 'match'? Match is only the beginning of a string?

inner mesa
#

You said 'starting with'

#

Yes

#

It's in the docs

dry narwhal
#

Thank you for the explanation!

#

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

dry narwhal
#

This works
{{ states|selectattr('object_id', 'search', 'living')|map(attribute='entity_id')|list }}

#

Thank you very much for getting me there!!!!

inner mesa
#

That takes a regex. You can also use 'in', which just looks for a sub string

dry narwhal
#

{{ states|selectattr('object_id', 'in', 'living')|map(attribute='entity_id')|list }}does not list anything ๐Ÿ˜ฆ

inner mesa
#

Oh, yeah. That will be backward

dry narwhal
#

?

inner mesa
#

Backward

dry narwhal
#

backward?

inner mesa
#

Yes

#

It's testing if the whole object_id is in 'living', which is backward

dry narwhal
#

okay, understand! ๐Ÿ˜„

#

awesome, thank you very much! I will play some more with the possibilities ๐Ÿ™‚

ocean glade
#

Hi all.... Is it possible to access constants in templates, like HVACAction.HEATING instead of having to hard code the string "heating"?

plain magnetBOT
dry narwhal
#
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.

mighty ledge
#

it's going to replace the list. If you want it at the bottom, you need to build the code to handle that

dry narwhal
#

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?

mighty ledge
#

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.

dry narwhal
#

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?

mighty ledge
#

my man, you're over thinking this

#

just take the existing list and add (+) the next items

#

literally +

#

[ 'a','b','c' ] + ['d','e','f']

dry narwhal
#

So the existing list should be moved from the input_select to the automation. Okay, less code than reading it, but "same approach".

dry narwhal
glossy viper
#

hi. i wach developer tools and cannot explain why my template sensor doesn't show me value

inner mesa
#

You never outputted anything

#

You just have a bunch of logic there

#

Add {{ ns.hightemp }}

glossy viper
#

wanted that ns.hightemp calculated ๐Ÿ™‚

inner mesa
#

Then threw it away:)

glossy viper
#

omg..amazing discovery.... thank you for help

mighty ledge
glossy viper
#

so no need to template highest value ๐Ÿ™‚

sacred sparrow
#

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

marble jackal
#

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

marble jackal
sacred sparrow
#

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?

marble jackal
#

Sorry, I don't understand what you are trying to achieve here

sacred sparrow
#

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

marble jackal
#

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

sacred sparrow
#

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

sacred sparrow
#

at 3 hours before the event

#

so just before 9pm - which works

marble jackal
#

Okay

sacred sparrow
#

it turns input_select.holiday_status to ON

#

when that event finishes I want it to turn input_select.holiday_status to OFF

sacred sparrow
#

so I need a template to be true when that event ends

marble jackal
#

But why 30 minutes after the event?

sacred sparrow
#

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

marble jackal
#

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
sacred sparrow
#

oh of course

#

Don't know why I didnt think of that

#

thank you

spiral imp
#

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

obsidian lintel
#

{{ 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

obsidian lintel
#

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
dreamy sinew
#

that should work

#

assuming the api call is working

obsidian lintel
#

Yeah the API Call is working but doesnt seem to be updating when I change the value of the input_text

dreamy sinew
#

it might not trigger immediately

#

does it go on the next poll?

obsidian lintel
#

Nope

#

I will try again hold on

dreamy sinew
#

odd. been a while since i've messed with that

obsidian lintel
#

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

silent seal
#

You can set the scan_interval

obsidian lintel
#

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

silent seal
#

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 ๐Ÿ™‚

obsidian lintel
#

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

silent seal
#

Or use a secret

obsidian lintel
#

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

dreamy sinew
#

probably better to use some other integration instead

obsidian lintel
#

if I go 5s, im blowing it in an hour

silent seal
#

The scan interval defaults to 15 minutes, you could easily set it longer than that

dreamy sinew
#

because you would still be hitting their api

obsidian lintel
#

TAF and METAR Values are On demand

#

15 mins interval will give me inaccurate data

#

I will check for an integration

silent seal
#

Well you need to figure out what problem you're solving. But I've suggested 2 integrations already

obsidian lintel
#

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!

dreamy sinew
#

there are other generic integrations that can be used

obsidian lintel
#

I know about rest_command

#

Where I can call the service

#

But thats more like for Post and put right

dreamy sinew
#

from an automation or a script

obsidian lintel
#

I cant GET a response back?

dreamy sinew
#

ah, looks like it will log the response but doesn't return it

obsidian lintel
#

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

silent seal
spiral imp
silent seal
#

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

spiral imp
dry narwhal
#

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.

marble jackal
#

Is the first list always one item?

dry narwhal
#

The first input_select has multiple options but the state is only one string.

marble jackal
#

Is that first template meant to return the state of input_select.dropdown_climate?

dry narwhal
#

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'

marble jackal
#

Just use states('input_select.dropdown_climate') instead of that complicated template you have now

dry narwhal
#

๐Ÿคฆโ€โ™‚๏ธ

#

So stupid!

marble jackal
#

{{ states[states('input_select.dropdown_climate')].name }}

#

That's all you need to get the name of the sensor from the dropdown

dry narwhal
#

But the original one with the smart approach works
{{ states.sensor|selectattr('name', 'match', states('input_select.dropdown_wildcards'))|map(attribute='name')|list }}

marble jackal
#

Oh, I thought the options of the input select were entity_ids

#

But it's has a *, I missed that

dry narwhal
#

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.

marble jackal
#

The dropdown has a wildcard for entity_ids right

dry narwhal
#

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.

dry narwhal
#

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 {{}}

mighty ledge
dry narwhal
#

Thank you, but see above you post ๐Ÿ™‚
Figured it out myself ๐Ÿ™‚

silent vector
#

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 ?).

https://dpaste.org/aKSWc

mighty ledge
#

you're probably using the wrong include as well

#

take a look at how I include things in my repo for templates.

thorny snow
#

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

silent vector
#

What's the difference between that and !include_dir_merge_list

marble jackal
#

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

silent vector
#

!include_dir_merge_list

Allows

- trigger:

vs

trigger:
marble jackal
#

That one combines lists, dir_list combines items into a list

silent vector
#

Is that right? ^

marble jackal
#

Yes, and multiple items in a file

silent vector
#

I see. Makes sense. I'll switch it to that then.

marble jackal
#

As it already expects a list

silent vector
#

Thank you. I'll take note of that

marble jackal
#

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: "{{}}"
mighty ledge
#

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

marble jackal
#

I use the other include, with separate files per sensor

silent vector
#

Yep that's what I did. @mighty ledge

mighty ledge
#

Right, but dan wants multiple per file

#

if you don't want multiple per file, then you'd use the other merge

silent vector
#

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.

marble jackal
#

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

silent vector
#

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.

spiral imp
#

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'))  %}
rare sage
#

@marble jackal I need your help again... ๐Ÿ˜ฆ

marble jackal
#

Just post your question, and please don't ping me, there are more smart people here who can help you

rare sage
#

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
marble jackal
#

I don't think there is something as a template calendar

plain magnetBOT
#

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.

rare sage
#

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'"
marble jackal
#

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?

rare sage
#

'''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'
    '''
marble jackal
#

please also see the last line of the the bot message!

#

you can copy the right backticks from the bot message if you need

rare sage
#

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
marble jackal
#

Could you please put some effort in actually using the right code tag

#

copy paste it if you really need

rare sage
#

Figured it out sorry

marble jackal
#

{%- 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

rare sage
#

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

marble jackal
#

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?

rare sage
#

Hehe should have indicated that sooner. You deal with alot of requests a day ๐Ÿ™‚

marble jackal
#
{%- 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 %}
rare sage
#

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

marble jackal
#

fixed

rare sage
#

Your a GOD! Thanks!

acoustic urchin
#

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?

deft timber
#

Yes, I would just create a template sensor that does the math

clear mist
#

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?

marble jackal
#
  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 }}"

clear mist
#

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!

red rose
#

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

marble jackal
#

what is your current template?

#

did you try to add a screenshot maybe?

red rose
#

got it working now, i was on the right path, but somehow devtools threw an error, dont know why

marble jackal
#

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

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

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.

clear mist
#

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?

marble jackal
#

what should it be if tv_source == "home"

clear mist
#

oh, should have mentioned - if tv_source == "home", i want it to be blank and not say anything

deft timber
#

{{ iif(tv_source == "home", "whatever you want", "Opened "~tv_source) }}

#

is one of the possible solutions

clear mist
#

ah, so i can do if statements there, that's good to know

#

what's the ~ do between "Opened " and tv_source?

deft timber
#

a concatenation

#

a + would also work here, but the ~ 'force' implicit conversion to strings, in case your are concatenating integer for instance

clear mist
#

ah, thought so but just wanted to double check

#

perfect, thanks!

dry narwhal
#

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 }}
inner mesa
#

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

dry narwhal
#

I tried without the selectattr but could not get it to work without. That's why I also needed the unique.

inner mesa
#

every entity has a state

#

I just tried your template and it worked, then removed |selectattr('state', 'defined') and the result didn't change

marble jackal
#

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 }}

marble jackal
#

Then it should work without the selectattr

dry narwhal
#

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.

icy marsh
#

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}}'

silent seal
#

Where is value defined?

slim elk
#

@icy marsh remove the last )

icy marsh
#

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%

edgy yarrow
#
  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

silent seal
#

Is something publishing to that topic?

edgy yarrow
#

Yes, but should I be expecting the sensor would not appear until something publishes to that topic?

silent seal
#

Well, I'm assuming that you've restarted/reloaded your config since adding the device

edgy yarrow
#

Yes!

silent seal
#

And you've looked for it in the entities list?

#

It would be binary_sensor.camera_car_front

edgy yarrow
#

Yup, straight up doesnt exist

slim elk
#

place the payload_on and payload_off values in quotes as well

edgy yarrow
#
  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

icy marsh
#

How do I make value_template return a value based on the input?

#

Example input value = -3 output = Ok/Good/Whatever

#

For multiple choices...

silent seal
#

What is the value template on?

icy marsh
#

snmp sensor

silent seal
#

Something simple like:

value_template: >-
  {% if value == -3 %}
    Ok
  {% elif value == 1 %}
    Good
  {% else %}
    Whatever
  {% endif %}
icy marsh
#

That sounds right. They really need to expand the documentation with common sense real world examples

silent seal
#

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

icy marsh
#

I just looked there are 0 in templating doc for "if value"

inner mesa
#

that's just basic Jinja, not an HA extension

elder moon
#

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

icy marsh
#

Sure, but I shouldn't be expected to learn an entire programming language and the docs should cover basic usage

inner mesa
#

ok

silent seal
#

And the very first example on that page shows how to do an if and output some text.

marble jackal
#

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

silent seal
hollow girder
#

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.

silent seal
#

What does the template look like?

hollow girder
#

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

silent seal
#

Ok, but what does it look like? As in, the code.

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

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.

hollow girder
#

I'm not in the pc now! But is that relevant? Is there any kind of generator that does that?

silent seal
#

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.

hollow girder
#

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!

silent seal
#

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 ๐Ÿ˜‰

hollow girder
#

When I get home latter, I'll copy the sensor yaml code

fickle kettle
#

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.

fickle kettle
steel marsh
#
      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

steel marsh
#

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 ๐Ÿ˜‰
timid badger
#

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?

charred dagger
#

If templates are allowed that is explicitly stated in the relevant documentation.

prime kindle
#

How can I write regular expression in condition of the automation??

If want to write the regular expression for state.

marble jackal
#

in a template condition probably. What are you trying to achieve?

prime kindle
#

@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

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) }}
prime kindle
#

I want to check starting part of the IP...
if the IP is 10.xx.xx.xx or not?? @marble jackal

marble jackal
#

Please stop tagging me

prime kindle
#

Okay sorry

marble jackal
#
{% set ip = trigger.payload %}
{{ ip.split(':')[0] == '10' }}
prime kindle
#

It's not working if I write this condition directly in state.

plain magnetBOT
prime kindle
#

@marble jackal Pls help...
Sorry for the tagging...but I need help in urgent

marble jackal
#

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

prime kindle
#

No this is state trigger

chilly dagger
#

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!

deft timber
#
{% 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

plush fractal
#

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.?

marble jackal
prime kindle
#

So basically I have to make changes in condition state

elder moon
#

pardon?

#

๐Ÿ™‚

slender plaza
#

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.

plain magnetBOT
slim elk
slender plaza
slim elk
inner mesa
#

what problems?

leaden perch
#

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?

silent seal
#

You should be using is_state to get the state, then it will fail gracefully. That combined with a default should do it

leaden perch
#

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

silent seal
#

What is it exactly that you're trying to do?

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

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.

leaden perch
#

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

silent seal
#

Try looking at mqtt sensors to accumulate the data

marble jackal
#

Use a trigger based template sensor for that

#

Hehe

leaden perch
silent seal
#

Or that, better idea Fes ๐Ÿ˜„

marble jackal
#
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

leaden perch
#

thanks! thats a lot shorter than I was brewing up before

strong idol
#

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?

silent seal
#

There's an example in the docs, it's 10 minutes not 2, but I'm sure you can figure it out

strong idol
#

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

silent seal
#

It's a trigger, not the trigger

#
wait_for_trigger:
  - platform: state
    entity_id: binary_sensor.your_sensor_name_here
    to: "on"
    for: 2
strong idol
#

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.

silent seal
#

can use the same triggers, not must

strong idol
#

I will give it another try. ๐Ÿ™‚

silent seal
#

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

strong idol
#

Thanks a lot!

marble jackal
silent seal
#

Whoops, yup. But you can indent minutes beneath the for and specify it there instead ๐Ÿ˜„

slender plaza
#

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?

plain magnetBOT
clear mist
#

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?

obtuse zephyr
#

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

inner mesa
#

The state of entities in a light group should have no bearing on your ability to expand it

obtuse zephyr
#

That's what I'd think

inner mesa
#

Do they still show up in the attributes of the light group?

obtuse zephyr
#

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

inner mesa
#

If you don't see them in devtools -> 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

obtuse zephyr
#

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

inner mesa
#

You keep 'unavailability', but that implies a state, which doesn't matter

hard topaz
#

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?

inner mesa
#

It also implies that an entity exists

obtuse zephyr
#

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 ๐Ÿ‘

inner mesa
inner mesa
obtuse zephyr
#

They're still in states w/ a state of unavailable

inner mesa
#

And they appear and disappear from the entity_id attribute in your light group?

obtuse zephyr
#

Yup

inner mesa
#

Ok

#

I manually set a state of a light and it did not, but ๐Ÿคท

#

But I don't use that integration

obtuse zephyr
#

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

inner mesa
#

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

obtuse zephyr
#

Ah, gotcha

inner mesa
#

It's probably considered a feature that only available entities are listed

obtuse zephyr
#

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

sonic nimbus
#

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

burnt lion
#

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"}

regal temple
#

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?

plush fractal
#

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.?

marble jackal
plain magnetBOT
marble jackal
regal temple
floral steeple
#

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?

sonic nimbus
#

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

tropic breach
#

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?

little salmon
obtuse zephyr
wild pumice
#
      - 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

inner mesa
#

You didn't convert the second state to a float

wild pumice
#
      - 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

inner mesa
#

you still didn't convert the second state to a float

wild pumice
#

how do I do that

inner mesa
#

sigh

#

you just put it in the wrong place

#

compare the first to the second

wild pumice
#

no I don't see it

inner mesa
#

ok

wild pumice
#

I got it thank you for your help๐Ÿ˜‘

proper wave
#

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?

plain magnetBOT
strong pier
#

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 %}

silent seal
#

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 %}
strong pier
silent seal
#

Well that's because it's a template, so you'd make a template sensor and show the sensor in the card

strong pier
silent seal
#

No, you make a template sensor

plain magnetBOT
strong pier
# silent seal 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 %}"
inner mesa
#

states()

silent seal
#

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 ๐Ÿคช

inner mesa
#

it won't be obvious what binary_sensor.sensor is, though

silent seal
#

Very trye

obtuse zephyr
#

Shouldn't that be a standard sensor, as it has > 2 states?

inner mesa
#

that too

#

and it would be sensor.sensor, which is even better

flint wing
#

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

inner mesa
#

where did you insert it in configuration.yaml?

formal ember
#

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?

inner mesa
#

That link has an example

formal ember
#

you can still use the old ones?

inner mesa
#

yes

formal ember
#
- 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?

inner mesa
#

I don't see why not

formal ember
#
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 '

flint wing
inner mesa
#

Yes

#

There's no sensor:, as in the docs

#

That's why I asked, and gave you a pointer to the docs

flint wing
# inner mesa Yes

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') }}
hoary ether
#

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

hoary ether
#

hmmmm, should I use AppDaemon maybe?

strong pier
#

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 %}"
obtuse zephyr
#

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

strong pier
# obtuse zephyr 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 %}"

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).

obtuse zephyr
#

You didn't fix your missing paren

#

Test your template in Dev Tools -> Template

strong pier
obtuse zephyr
#

File... no. Template entities specifically, yes. Dev Tools-> under YAML configuration reloading, hit Template Entities

obtuse zephyr
#

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

strong pier
#

@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

obtuse zephyr
#

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?

strong pier
obtuse zephyr
#

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 %}
lime olive
#

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" }}

inner mesa
#

you don't need a template for that

#

second example there

lime olive
# inner mesa you don't need a template for that

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

silent seal
#

You can add a not, it's referenced in the docs Rob linked

thorny snow
#

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/

#

however the fix was to use !include_dir_MERGE_list, which I already do

#

anyone knows about this?

inner mesa
#

it doesn't look like it expects a list

#

I suspect you want !include_dir_merge_named instead

lime olive
#

Apologies if I'm not making sense, I'm struggling to put automation together

thorny snow
inner mesa
#

it determines whether you need a list or a dict

#

"doesn't show up" just means that you need to run a config check

sonic nimbus
#

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)

gray skiff
#

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

uneven pendant
#
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.

inner mesa
#

you want entity_id and not name

uneven pendant
#

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
gray skiff
#

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?

inner mesa
#

you're trying to do this in a frontend card?

gray skiff
#

sigh

#

I see

#

yes

#

so templates have full jinja2 support

inner mesa
#

that's a script. it doesn't go in a card

gray skiff
#

frontend-cards are just formatting

#

yeah... shit

inner mesa
#

so just call the script

uneven pendant
#

Rob, i just realized you may not have been talking to me.

gray skiff
#

do you recommend I install the lovelace addon?

inner mesa
#

oh, sorry

gray skiff
#

@uneven pendant he was ๐Ÿ™‚ He is helping both of us

inner mesa
#

I'm using half my brain to talk to two different people and it's not going well

uneven pendant
#

Well you were first so i'll be patient.

gray skiff
#

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 ๐Ÿ™‚

marble jackal
gray skiff
#

seems those are my three options here

uneven pendant
#

oh, ok, lemme try

marble jackal
#

entity_id: "{{ repeat.item }}"

inner mesa
#

yeah, that too

uneven pendant
#

That did it.

#

Thank you guys.

#

now i don't have to edit all this every time I add an input boolean entity

gray skiff
#

and wth is lovelace cards anyway? Can't find any card type with that name.

inner mesa
#

"Lovelace" is the former name of the dashboard