#templates-archived

1 messages · Page 73 of 1

fickle sand
#

me neither. Reload does sort of imply that the integration/platform must been added to hass on beforehand. Which is done by a restart

fickle sand
#

Just tested it with a mock sensor. The reload all yaml configurations seems to work after you've setup at least one sensor with the filter platform. @silent vector

marble jackal
#

ah, I was just rebooting

#

I inititially placed my test sensor in the wrong folder, so it was under template

fickle sand
#

Haha even experts can sometimes be confused with a sensor platform and the template integration😛

mighty ledge
#

Assuming the integration/platform supports reloading

marble jackal
#

but all yaml configuration is a bit misleading in that sense, it's all yaml config which for which at least one config entry was already loaded, and which supports reloading 😉

mighty ledge
#

Yep, its been missleading like that from day 1 though

#

You guys weren't involved in HA when that reload service & page was implemented

#

But that was a "big todo" back in the day

#

"todo" as in, people were all pissed that it didn't reload everything

marble jackal
#

but after finally adding a test config the right way, it does show in the list

#

Well, the all yaml config button is rather new right? It used to be only the individual reload options

mighty ledge
#

no, it's always been there

#

what's new is that it reloads only the pieces that need reloading

marble jackal
#

ah okay

mighty ledge
#

new as in "about a year old now"

#

before, that button would reload it all

#

regardless if things changed or not

marble jackal
#

maybe I'm confused with the option being added under the restart menu

#

the quick reload option

mighty ledge
#

I just restart because my restart time is ~10 to 30 seconds

#

reloading comes with issues

#

especially integrations that don't have unique_id

#

you get duplicate entities

#

the only integration I reload are ones with unique_id

fickle sand
#

Could HA not require to set a unique_id to newly setup entities? Which already is for core integrations that are at least silver on the quality scale

mighty ledge
#

first there was yaml, then there was the UI, then there was yaml reloading, then there was unique_id for yaml (to adjust in the UI)

#

there are many integrations still stuck in the first there was yaml stage

#

all it takes is the integration to get abandoned at any stage, HA still has to support every rendition

#

Mind you, these stages occured over 8 years

#

I doubt we will ever have all integrations move from stage 1

#

unless someone with some gusto goes through and updates old integrations. Which @sleek trail has been doing.

fickle sand
#

Okay but it should be doable to require it for everything that supports reloading

mighty ledge
#

it is a requirement

sleek trail
#

but sometimes youre at the point where you need the actual devices to be able to continue

mighty ledge
#

Yep

#

it's a catch 22

#

we want things to be up-to-date, but there's only so much crap you can do

#

so we have really old yaml only integrations that are abandoned, with some things ham-fisted into them.

#

like reload services

fickle sand
#

And if the code-owner or someone else with the knowledge to do so doesn't have that device or services it will be in that state until the core-team decides to break it

mighty ledge
#

well it won't be broken

#

but you're making an assumption that all integrations have code-owners

#

there are many dead integrations that still just work because nothing has changed

#

the core team manages the linkings to HA core

#

so the integration will still be supported, even though it's abandoned

#

but then you end up with situations like reloading causes duplicate entities

#

because it's running off an old framework

silent vector
#

Well this was all very insightful as to how the reload option works.

silent vector
#

I do see the filter entities option now

mighty ledge
sleek trail
#

yep

mighty ledge
#

OOF

#

that's a fucking huge body of work

sleek trail
#

for what

mighty ledge
#

to remove -platform loading

sleek trail
#

oh but this is every integration

#

also config flow

#

this just means that it has that platform

mighty ledge
#

oh, so it's not actually meaning "platform loading"

sleek trail
#

doesn't mention if it uses CONFIG_SCHEMA or PLATFORM_SCHEMA

mighty ledge
#

that's pretty important info, seeing that it's what greatly effects reloading & restart speed

sleek trail
#

Could add that as well

mighty ledge
#

meh

fickle sand
#

`more than half of the integrations don't have a config flowmindblown

sleek trail
#

Also take in mind the system ones

fickle sand
#

Yeah okay minus the default config and some others

mighty ledge
sleek trail
#

Hmm, why didn't it update

sleek trail
#

ffs petro

#

I now found a new integration to migrate

#

I can't test it tho, so that means I have to do it well, or break it and get testers via github

inner mesa
#

You should do it well 🙂

mighty ledge
sleek trail
#

KEF

#

I don't know any of it, but it looks doable and the services that it provides can easily be number and select entities at this point

mighty ledge
#

All 55 people will be upset that you removed yaml

sleek trail
#

I can handle that

#

fight me

#

I mean

mighty ledge
#

DO yamaha

sleek trail
#

I was checking with Martin about wake on lan last weekend

mighty ledge
#

I can help with yamaha

sleek trail
#

he was upset we removed the discovery integration

mighty ledge
#

The downside of that is you'll end up removing source naming

#

but I can live with that

sleek trail
#

What kind of discovery do they do

mighty ledge
#

what do you mean?

#

I would assume the discovery would be one of the main types

#

it used to be in discovery

sleek trail
#

oh lol

mighty ledge
#

meeting brb

sleek trail
#

it uses SSDP

agile patrol
marble jackal
sleek trail
#

so

#

(55/80*100)/30*100

marble jackal
#

80% of 30%

last shale
#

Hey All, I have a script with a bunch of conditions that are all iterations of
- condition: numeric_state entity_id: sensor.kw13_temperature above: 29.9 below: 40 sequence: - service: light.turn_on metadata: {} data: color_name: darkblue brightness: 100 transition: 5 target: entity_id: light.master_light_on_off
The only thing that changes in each condition section is the above/blow and color_name values. Is there a way to have a variable called "color". Do the temp comparisons and set "color" based on the correct range then at the end call the light on method with "color" as the color_name value?

brazen ember
#

Well I waited until the last minute and now I need to convert my weather entities to the new format. I have several template sensors that pull various weather related data for automations but can't seem to get the new format working. I understand I need to first call the weather.get_forecasts service and create the sensor from there but the trigger sensor is not working. I have followed the examples and searched endlessly but can't seem to get it working. I keep getting the error "end of the stream or a document separator is expected". What am I missing? I'm using a templates.yaml file with this inserted directly as the first line.

- trigger: - platform: time_pattern hours: /1 action: - service: weather.get_forecasts data: type: hourly target: entity_id: weather.forecast_home response_variable: hourly sensor: - name: "Temperature in 2 hours" unit_of_measurement: "°F" state: "{{ hourly['weather.forecast_home'].forecast[2].temperature }}"

lofty mason
#

does /1 need quotes around it maybe?

marble jackal
brazen ember
marble jackal
#

so in you configuration.yaml you have template: !include templates.yaml and the code above is placed in that file?

brazen ember
marble jackal
#

is the indentation the same?

last shale
brazen ember
# marble jackal is the indentation the same?

I've tried all types of different indentations and mirrored examples online. I assume it's related to that but can't determine what.

I've also considered it's because it is it's own entry when everything else is nested under sensor: or binary_sensor: but couldn't find an answer. I've read that trigger is a list so I put the code block in brackets as well but still nothing.

marble jackal
#

can you share your entire templates.yaml?

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.

floral shuttle
sleek trail
floral shuttle
#

moving to UI?

marble jackal
sleek trail
floral shuttle
#

ah. so can at least set some properties in the UI, nice

sleek trail
#

no I closed it

#

as in, didn't merge

#

we don't allow that if it doesn't have a config flow

floral shuttle
#

heck., thats what I figured, hence my responce for the UI...

#

well, you know what to do next then 😉

sleek trail
#

graduate

floral shuttle
#

heheh

#

yep that too

last shale
mighty ledge
#

before

last shale
#

Does it go:
`- conditions:
condition: ...
condition: ...
variables: ...
sequence

  • service: ...`
mighty ledge
#

if you do it inside the loop, they are only available inside the loop

last shale
#

Hard for me to know since the gui doesn't like the variables there but studio code editor accepts it

floral shuttle
#

having this attribute template using an old style group tekst: > {% set last = as_local(states.group.media_players_device_trackers.last_changed) .strftime('%D %X') %} {% if this.state|int(-1) != 0 %} {% set count = this.state %} Tracked: {{count}} -- {{this.attributes.get('home')}} {% else %} Nothing tracked: {{last}} {% endif %} which I want to replace with the label_entities('speler_tracker')

last shale
#

Or, does it go directly under actions: before - Choose:?

mighty ledge
#

you can't instantiate variables in the condition section

#

and that's your problem

last shale
#

Ah, yeah, I just moved it out under Action: and gui seems much happier

floral shuttle
#

am in a bit of trouble as the former entity of the last_changed was the group.... what would be the most efficient way to check the last changed if the label entities?

last shale
#

Thanks, @mighty ledge

floral shuttle
mighty ledge
#
{% set last = (label_entities('label') | expand | map(attribute='last_changed') | map('as_local') | first | default(now())).strftime('%D %X') %}
floral shuttle
#

perfect! thanks a lot. 1 2 groupS down 😉

floral shuttle
#

too bad the auto-entities card using the include for label is reallly slow..... need to add those in the yaml dashboard as the UI editor just wont surface... Hope that will be fixed some time soon on auto-entities

mighty ledge
#

just use a template

#

no different

#

filter:
template: "{{ label_entities('label') }}"

#

I don't even bother using anything but template for auto-entities

#

just way too much control with templates instead of multiple filters

floral shuttle
#

sure, but templates filter needs some careful crafting if you want 'options'. that's where the simplicity of the include shines.

mighty ledge
#

you can still use options with template filter

#

as long as card_param is not card

floral shuttle
#

and yes, the template option is as fast as before, (relying on the core templating engine), so its definitely an auto-entities card thingy for now

magic moss
#

I am trying to send an email with the sensor value, I have tested with the following:
{{ states('sensor.apollo_air_1_ce7424_co2.state') }}

I am still getting the following error: expected dict for dictionary value @ data['data']. Got None

lofty mason
magic moss
#

Is this correct? the following gives the same error:
{{ states('sensor.apollo_air_1_ce7424_co2') }}

thorny snow
#

sorry for replying back late. What confuses me, is that when I go into that automation that template code is entered as a line in the visual editor instead of being an actual template like so: https://i.imgur.com/naJCKUP.png
so that leads me to think I'm not entering the template code properly.

mighty ledge
#

and make sure you delete the contents of those fields if you filled them out

magic moss
#

That worked, thanks!

#

CO2 is above 1000ppm: 1089

worldly plank
#

I used the template helper so I don’t think it puts anything into the yaml file, right? Should I create the sensor manually instead?

mighty ledge
#
{{state_attr('climate.heat_pump', 'target_temp_high') or this.state | default(0, True)}}
worldly plank
#

I changed it to this last night and it looks better but I need to see if there are any more bad values in the states table
{% if state_attr('climate.heat_pump', 'target_temp_high') %}{{state_attr('climate.heat_pump', 'target_temp_high')}}{% endif %}

#

I wasn’t sure if returning nothing would do the same as returning bad values

mighty ledge
#

nothing == unavailable

worldly plank
#

Does unavailable cause gaps in the chart?

#

I was getting gaps before

mighty ledge
#

yes

worldly plank
#

Ok

#

I will take a closer look later, thanks

brazen ember
mighty ledge
#

no

#

to the guy who deleted

limpid moss
#

Thanks , I found the answer ! And it works

atomic oak
#

I'd like to make a template sensor of desired climate temp based on outside temp and presence. I was thinking of adding an attribute for mode=cool or heat but it looks like you can't do an attribute template for GUI-created sensors. Would it make sense to have a second sensor which is just the mode, or is there a better way to accomplish this other than doing it in the yaml file?

mighty ledge
#

you can add attributes via yaml

thorny snow
mighty ledge
#

Yes

#

I do about 9 races a year

thorny snow
#

damn! Nice, I've only done 3. In my dotage I've wanted to do more but I've got some minor injuries that make it doubtful

#

keep on going!

mighty ledge
#

what injuries? Just barrel through them!

#

I have my first ultra of the year in 3 weeks

#

Not looking forward to that one, but I am looking forward to all the other races 🤣

thorny snow
#

I've only ever done the first stage of the races. Compressed disc was the first one, it's better but I've got a back/hip problem that's chronic, now i've got a shoulder issue, and my right leg is ... weird to say the least. I've been lifting weights for a long time and cycling through various injuries. It's very tempting, the race is a lot of fun though!

mighty ledge
#

oh yeah, that makes sense

#

leg issues are not great for the races

#

If you can't trail run, then you shouldn't spartan race

#

if you can trail run, then you can definitely do the races, just take it slow

atomic oak
#

Could I get help with syntax on this? {{ state_attr('climate.family_room', 'temperature') | default('76.0') }} (hoping to get 76.0, instead gettign None)

thorny snow
inner mesa
quick stag
#

will give that a crack, cheers!

#

hrmm. Invalid config for 'template' at configuration.yaml, line 234: 'entity_picture_template' is an invalid option for 'template', check: sensor->3->entity_picture_template

#

i wonder if that's why i originally had it under the sensor integration

bronze prawn
#

I'm using a restapi call that returns:

  - joke: Why do bees have sticky hair? Because they use a honeycomb.```

If I do  ```{{ joke_response['content'] }}``` I get back ```[{'joke': 'My toddler is refusing to nap. He’s guilty of resisting a rest.'}]```

But if I do  ```{{ joke_response['content']['joke'] }}```  I get nothing
#

How do I pull the joke portion out?

lofty mason
#

The outer [] indicate an array I believe.

bronze prawn
#

That's it! So you are selecting the first element ("0") and then within you are selecting the value associated with joke. I thought I was already getting back that element but I get it. Thanks for showing me this

bronze prawn
#

{{ now() - states.sensor.tabletmaster_browser_path.last_changed }}

I'd like to see if the browser path has changed in the last twenty seconds. I know that in the Dev tools->Template area these are not evaluated quickly enough to show this. My question is can I use this reliably in an if statement or is the evaluation time also delayed. Not sure if that makes sense.

#

Or maybe I should think about this a different way and ask a different question. This is what I want to do in an automation:

  • store the last changed time of states.sensor.tabletmaster_browser_path.last_changed in a variable
  • wait for 20 seconds
  • check the current time against the variable stored time above
  • If they match then change to a different page, if they don't, then do nothing.

So the question is now does that last_changed value change immediately on state change and I can do what I'm talking about above with confidence?

#
[[[ WAIT HERE 20 SECONDS ]]]
{% if changed == states.sensor.tabletmaster_browser_path.last_changed %}True
{% else %}False
{% endif %}
inner mesa
#

Just use a state trigger in an automation with a for:

bronze prawn
#

I'm not understanding.

bronze prawn
inner mesa
#

A state trigger triggers when the state changes. If you just want to know whether a state didn't change for 20s, use a for: block

#

Whatever you're trying to do with this calculation seems like a hack for something simpler

bronze prawn
#

Agreed. I'm still finding my way on most of this.

#

Right now I have an automation that checks to see if the display device has changed views AND if the display device is in normal mode. It then waits 20 seconds and then switches the view back to a predefined view (clock). BUT, what can happen is that a user makes an assist call for a different thing and the display changes during that 20 second wait. The new view is shown BUT the wait time elapses and it switches back to the predefined view (clock). This makes the new view show for a time much shorter than desired especially if the wait time is about to elapse.

#

So that's where this comes in. After the wait I want to check to make sure that view has not changed while the wait is active. If the view has not changed then go back to clock. If the view has changed, don't go back to the clock until 20 seconds has passed.

#
    - condition: state
      entity_id: states.sensor.tabletmaster_browser_path.last_changed
      for:
        seconds: 20

I don't think this is right?

quick stag
#

sorted it - seems you can just put the template code into 'picture' now. Thanks for your help!

template:
  - sensor:
      - name: testbin
        state: >
          {% set is_after_thu = today_at().isoweekday() > 4 %}
          {% set is_odd_weeknumber = bool(today_at().isocalendar()[1] % 2) %}
          {{ 'Recycling' if (is_after_thu == is_odd_weeknumber) else 'Garden' }}
        picture: >
          /local/images/{{ 'bin_yellow.png' if is_state(this.entity_id, 'Recycling') else 'bin_green.png' }}
inner mesa
bronze prawn
#
    - condition: state
      entity_id: sensor.tabletmaster_browser_path
      for:
        seconds: 20

I need to remove the 'states.' part in the front too right? This will be true when the state of that entity has not changed for 20 seconds, correct?

marble jackal
#

Correct

rocky crypt
#

Hey there. I have a YAML formating question for Templates... I was trying to clean up my templates part of my configuration and would like to change the configuration.yaml to:

template: !include templates.yaml

so that way my templates are in a separate file. I was able to do this and it worked for my sensors and my binary_sensor area... But I can't figure out how to format it for a trigger template...

#

So in my template.yaml, I have

sensor:
      - name: "My Sensor 1"
        state: "My State 1 Template"
      - name: "My Sensor 2"
        state: "My State 2 Template"

etc... But not sure how to do the trigger template.

rocky crypt
#

I tried doing this....

trigger:
  - platform: time_pattern
    ...
action:
  - service: weather.get_forecasts
    ...
sensor:
  - unique_id: c1a120b6-f065-4cd4-ac83-5b09c62e3e02
    name: Daily Weather Forecast
    ...

But that casuses an error saying there is a duplicate for "sensor"

marble jackal
#

@rocky crypt template expects a list

#

So it should be:

# templates.yaml
- sensor: 
    - name: ...
    - name: ...
- trigger: 
    - platform: ...
  action: 
    - service: ...
  sensor:
    - name: ...
- binary_sensor: 
    - name: ...
rocky crypt
#

Ahh! Ok. That appears to work! 🙂

#

Thank you!

hoary wing
#

Does anyone know how to only let this template trigger when the outside temperature was higher before then inside?

platform: numeric_state
entity_id:
  - weather.buienradar
attribute: temperature
id: "Buiten koeler dan binnen"
below: sensor.gemiddelde_temperatuur
alias: "Buiten koeler dan binnen "
#

now it randomly triggers during the day 😦

fickle sand
hoary wing
#

Thanks very much

stable vortex
#

Does anybody know how I can use the new labels in a template to check the state of any of the entities marked with a label similar to a group, i.e. {{ is_state(label_entities('kitchen_light'),'on') }} gives an error msg TypeError: unhashable type: 'list'

mighty ledge
#

{{ label_entities('kitchen_light') | select('is_state', 'on') | list }}

#

@stable vortex ^

stable vortex
#

thank you

inner pagoda
#

if you want to get a boolean "are there any on?" instead of a list of the ones that are on, the easiest way is probably to add | length > 0 to the end of that.

bronze prawn
#

https://dpaste.org/Y6F1G

Still at this. It's becoming a question for #automations-archived but can someone confirm that my condition is correct. Will be true once that browser state goes unchanged for 20 seconds or more?

I will somehow have to make this in a loop as the trigger happens and the conditions are checked and they fail because the wait time has not happened. I know this can be done but I'm not sure the best way to do it

mighty ledge
#

it's not

#

stop using the non-states method, use states method

#

states('xxxx.yyyy')

#

also, conditions don't support templates

marble jackal
#

Just remove that entire state line

#

Without it the condition will just check if it has been on the state it is on now for 20 seconds

bronze prawn
bronze prawn
# marble jackal Just remove that entire `state` line

Message malformed: required key not provided @ data['action'][0]['then'][2]['if'][0]['state']

When I try to do:

condition: state
entity_id: sensor.thinksmart_lr_browser_path
for:
  hours: 0
  minutes: 0
  seconds: 20
marble jackal
#

Okay, then it's required. Then you should use a template

bronze prawn
marble jackal
#

A template condition supports, well, templates

bronze prawn
#

oh yeah.. ha. I'm normally not clear thinking but today is exceptionally bad

mighty ledge
#

just not the condtion you were using

bronze prawn
#

Yep. I know what to try now, thanks

#
value_template: "{{ states('sensor.thinksmart_lr_browser_path') }}"
for:
  seconds: 20

So this is the idea but I get malformed error due to the for. I'm really trying to piece different parts together but I guess they don't match.

mighty ledge
#

value_template needs to resolve true

#

or false

#

outside that, you should really just check the time on the state object.

#
{{ (now() - states.sensor.thinksmart_lr_browser_path.last_changed) > timedelta(seconds=20) }}
silent vector
#

When we get more complicated how would I do it here

{% set x = [{"first":{"goo":"morefoo","Santa":"Claus"}},{"second":{"tree":"light"}}] %}
  {{ x | first }}
inner mesa
#

|first

#

Or [0]. Or .0

silent vector
#

Oh I edited a message instead of sending a new one. Yikes lol

#

When it's nested it appears not so easy to strip the list

inner mesa
#

You're not 'stripping the list', you're referencing an element in it

#

What is not so easy about it?

silent vector
#

In my second example how would I keep the dictionary and remove the list? Using | first will jut take the the first element vs taking both elements

inner mesa
#

What you need determines what you do

#

Again, there is no stripping the list. You can process each element in it

silent vector
#

Hm alright will play around with this

mighty ledge
silent vector
#

Lol

mighty ledge
#

Did it work?

silent vector
#

Wow it did

#

I thought you actually needed to pass it something for it to work

#

I'm using that in my code to combine dictionaries had no idea it could do this too

mighty ledge
#

so you aren't working on HA stuff then

silent vector
#

Not this time

#

Lol

#

That's why I said how did you know what this is for

mighty ledge
#

I have my ways

silent vector
#

I think frenck said he might bring combine to spook some day

#

So hopefully ha will be able to take advantage too

#

We are all amazed at work right now that this even worked

mighty ledge
#

what's so amazing about it? Ansible has a ton of functionality

silent vector
#

We are amazed because we use combine to combine dictionaries but never to do this with a list of dictionaries

#

Some things ansible does that would be amazing for ha (flatten (spook has this now), combine, json_query)

mighty ledge
#

you can flatten in HA

#

{{ x | sum(start=[]) }}

silent vector
#

Wow I didn't know that

haughty breach
#

flatten was added to Spook FWIW

silent vector
#

Yeah it was I guess the difference is flatten can also do multiple levels

mighty ledge
#

you can with sum too

#

just keep adding sums on

#

2 levels? 2 sum(start=[])

silent vector
#

Hm not as clean as | flatten(levels=2)

#

But good to know I wonder what else sum can do

mighty ledge
#

it can't sum dictionaries

silent vector
#

Interesting.

lucid thicket
# mighty ledge 2 levels? 2 sum(start=[])

Any nice way to check how many levels there are and use sum() that many times? To always “completely” flatten I’ve used a hacky method involving converting to a string and replacing brackets. If there is a better way, I’m interested.

random basin
#

Can someone please tell me whats wrong with my logic? it works until 99 but not when the value is 100

{% set battery_level = '100' %}
{{battery_level}}
{% if battery_level >= '70' %}
  mdi:battery-high
{% elif battery_level >= '20' %}
  mdi:battery-medium
{% else %}
  mdi:battery-low
{% endif %}```
#

while the value is 100, it gives me "mdi:battery-low"

haughty breach
#

You are comparing strings

random basin
#

ok how to make it float then?

haughty breach
#

get rid of the quote marks around the numbers

random basin
#

oh ok that works. Thanks for your help @haughty breach

mighty ledge
lucid thicket
plain magnetBOT
#

@cerulean matrix I converted your message into a file since it's above 15 lines :+1:

crimson lichen
#

missed comma between flow collection entries (16:2)

neon laurel
#

struggled a bit to figure out how to troubleshoot templates that use "this" variable in the template developer tool. correct syntax to assign a variable to "this" is:
{% set this = states.light.cct_light %}

broken viper
#

I have a Device that I can modify using an automation which modifies a SELECT to change from OUTPUT_HIGH to OUTPUT_LOW - I want to have this available in Home Assistant as a switch so it can be toggled and accessed through the "turn off" service.. Can anyone point me at the right documentation for something like this? This is the YAML of my automation at current..

device_id: 763a96a92040e0eb6fceab52b9b36df6
domain: select
entity_id: a605379fe60aaaccf3166628f2d24590
type: select_option
option: OUTPUT_LOW

I have ~20 devices with the same config which is why I thought a template would be suitable here.. Thanks in advance ❤️

marble jackal
#

you can't use templates in device actions

#

you can in service calls, so you need to convert that to a service call instead:

service: select.select_option
target:
  entity_id: a605379fe60aaaccf3166628f2d24590
data:
  option: OUTPUT_LOW
#

oh, wait on reading your question better, you want a switch to toggle the select entity

#

option 1: no templates required
Create a toggle helper (input boolean) and create an automation which changes the select entity to the right option based on the state of the input boolean

option 2: some templates required
Create a template switch to do the same thing, but then in one configuration part

broken viper
#

Thanks @marble jackal that's really useful, I'll lookup toggle helpers

#

Hrm, just thinking out loud, wouldn't a helper be required "per device"? IE I couldn't make a helper for all of these devices? I don't fancy making 20 helpers plus all the additional ones when I add more devices 😛

marble jackal
#

do you want a toggle per device?

broken viper
marble jackal
#

or one toggle to rule them all?

broken viper
#

One per device...

#

Ideally I want this select to be accessible as if it was a switch.. I wonder if I need to expose it different in ESPHome to HA instead of assuming HA can template this?

marble jackal
#

then you need to create a helper per device, or a template switch per device, there is nothing in HA to craete multiple entities in one go

broken viper
#

Yeah, fair enough 🙂

marble jackal
#

if it is in ESPHome you could just creeate the switch in the ESPHome config

broken viper
#

Do me a favor please, I did do some googling to find a good reference template switch but failed, could you please provide a string I can use in a search engine?

plain magnetBOT
broken viper
#

that looks pretty good

marble jackal
#

There is a link at the top of the template documentation

#

that link looks like the thing you need

#

but again, if it is for ESPHome devices, I would create the switch there

broken viper
#

I agree, I'll look into both options

#

Thanks again for your time man

#

You got anywhere I can donate you a coffee?

marble jackal
#

there is a link in my Discord profile if you really want to give me a coffee 🙂

#

what I wanted to add

#

with substitutions and packages in your ESPHome config, you can create one config for all 20 devices, so you can manage it one place

#

as an example, I have around 15 ESPHome relays (Shelly, Sonoff Mini, older gen Sonoff) which all use a config like this:

substitutions:
  name: Trapkast
  connected_light: light.trapkast
  lower_name: sonoff-trapkast
  ip: 192.168.2.63
  default_button_type: Detached

packages:
  sonoff: !include packages/sonoff/sonoff_mini_r4.yaml
#

in the end the package included here, includes a new package which has the most inportant config part, and is the same for all relays

#

If I want to change something in it, I only need to do it in one place

broken viper
#

The thing I need to wrestle with is I can't yet access the firmware on these devices. I just flashed them with tuya cloudcutter and they aren't available in the ESPHome addon but are available as an ESPHome Device if that makes sense?

marble jackal
#

You must have flashed a firmware to it, based on YAML you created

broken viper
#

I can do an OTA update

marble jackal
#

okay, well last time I tried it it only had some basic firmware without any actions, which you could use to find the right pins yourself.

#

If you can do OTA updates, it must be shown in your ESPHome add on

#

as far as I know

broken viper
#

OTA updates are through Web UI exposed by ESP on the device

marble jackal
#

ah

#

okay, I assumed using the update entities from the ESPHome integration

#

do they publish the YAML somewhere?

#

Anyway, if you want to go the ESPHome route, you might want to ask here for help

broken viper
#

I assume selects don't show up in states which is why I can't find it 😛

#

I'm just trying to ensure I have the right entity and trying this {{states('input_select.a605379fe60aaaccf3166628f2d24590')}} results in Result type: string with value unknown

marble jackal
#

it's not an input_select

#

it's a select

broken viper
#

{{states('select.a605379fe60aaaccf3166628f2d24590')}} also returns same thing

marble jackal
#

then you have the wrong entity_id

broken viper
#
alias: TEST Plug 17 pin mode to high
description: ""
trigger: []
condition: []
action:
  - device_id: 763a96a92040e0eb6fceab52b9b36df6
    domain: select
    entity_id: a605379fe60aaaccf3166628f2d24590
    type: select_option
    option: OUTPUT_LOW
mode: single
#

oh is it select_option ?

#

hrm, nope

marble jackal
#

that is not the entity id

#

that is the entry_id

#

which is used in device actions so you can change the entity_id

broken viper
#

TIL 😛

marble jackal
#

go to `Settings > Devices & Services > ESPHome and then to the right device

#

there you can click on the select entity and see the details, including the actual entity id

broken viper
#

pin_mode_15

#

heh.. For plug17.. That's gonna be fun 😛

marble jackal
#

this looks like you are using that exact firmware I was talking about

broken viper
#

eyy nice 🙂 output is now OUTPUT_LOW

#

yea where just pins are exposed etc.

marble jackal
#

which is used to find the right pins to base your actual config on

#

Write an actual switch firmware for this device, and flash it to your device, you can do that in the web interface or using the ESPHome add on. If you then place it in the esphome folder you will be able to edit it there and you will also get update entities so you can update without the web interface

plain magnetBOT
#

@broken viper I converted your message into a file since it's above 15 lines :+1:

broken viper
#

I think maybe I want "select" not "input_select" for the service

marble jackal
#

yes

#

an input_select and select are different domains, and therefor use different service calls

plain magnetBOT
#

@broken viper I converted your message into a file since it's above 15 lines :+1:

broken viper
#

Winrar 🙂 Working!.. Okay now to replicate that config 20 times... 😛

#

Thanks @marble jackal I'm defo capable to take it from here

marble jackal
#

Great!

broken viper
#

and I agree RE Firmware, that's for next week after Hackaday Berlin 😛

#

Or maybe a nice project for while I'm there assuming there will be HA presence

dry sierra
#

I'm new to templates, yaml and jinja, and trying to create a binary sensor that shows when a device tracker is moving. I have this in my configuration.yaml:
`template:

  • binary_sensor:
    • name: "Car Is Traveling"
      state: >
      {%- set new_lat = state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) %}
      {%- set new_long = state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) %}
      {{ (new_lat != state_attr('binary_sensor.niro_ev_19_is_moving', 'lat')) || (new_long != state_attr('binary_sensor.niro_ev_19_is_moving', 'long')) }}
      attributes:
      lat: "{{ new_lat }}"
      long: "{{ new_long }}"`
#

But, I get this error related to the state: > line (192):
`Logger: homeassistant.config
Source: config.py:623
First occurred: 10:32:21 (1 occurrences)
Last logged: 10:32:21

Invalid config for 'template' at configuration.yaml, line 192: invalid template (TemplateSyntaxError: expected token 'name', got '|') for dictionary value 'binary_sensor->0->state', got '{%- set new_lat = state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) %} {%- set new_long = state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) %} "{{ (new_lat != state_attr('binary_sensor.niro_ev_19_is_moving', 'lat')) || (new_long != state_attr('binary_sensor.niro_ev_19_is_moving', 'long')) }}"\n'`

#

Any ideas gratefully received 😦

broken viper
#

@marble jackal one final noob quesstion.. My Device named plug5 is called plug5 but loads of entities are stuff like sensor.pin_state_6 -- is it possible to fix that? 🙂

#

by Fix I mean change to pin_state_5 which is what you'd expect...

marble jackal
#

the config is most probably created to give it the name pin_state

#

the number is added becasue that entity_id was already in use

broken viper
marble jackal
#

as it is a binary sensor, the result of the state template should be true or false

#

not sure what you are trying to output there, but it doesn't look like this will return true or false

dry sierra
#

I thought || was or

#

logical OR?

marble jackal
#

no or is or in jinja 🙂

dry sierra
#

Blimey - no error in the config any more 🙂 Unfortunately Developer Tools shows me that the lat and long attributes are empty strings at the moment

#

Maybe the device tracker wasn't ready when the template got evaluated

fickle sand
#

That is because variables are only tied to their local scope. So the attributes are not aware of the variables you use in the state

dry sierra
#

Aha - thank you

marble jackal
#

ah, right, should have seen that 🙂

#

but I don't think this will work

#

your attribute change will trigger the state template to render again, so after the attribute are changed to the current state, the state template will render again, and the result will always be false

dry sierra
#

Huh. OK, that's what I was trying to check. Is there any other way to reference the previous values at update so that I can compare them?

#

I want to use the state transitions of this sensor (false to true, true to false) in a trigger to log the start and end of my car journeys.

#

Anyway, thanks for helping me fix up what I had. I'll keep it in my config for now to see it fail after my next drive 🙂
Current version, expected to always be false:
`template:

  • binary_sensor:
    • name: "Car Is Traveling"
      state: >
      {%- set new_lat = state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) %}
      {%- set new_long = state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) %}
      "{{ (new_lat != state_attr('binary_sensor.niro_ev_19_is_moving', 'lat')) or (new_long != state_attr('binary_sensor.niro_ev_19_is_moving', 'long')) }}"
      attributes:
      lat: "{{ state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) }}"
      long: "{{ state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) }}"
      `
broken viper
#

@marble jackal I just realized a problem w/ my config.. I make the assumption that "Pin" set.. Because during testing I was manually setting it and it sticks but when ESP restarts it is set back to a null value 😛

#

*mutters inaudibly

marble jackal
#

you really should just create a proper config for these devices

broken viper
#

yeah, I agree, it's just a case of ticking it off before I go away tho

#

4 hours sorting firmware vs 30 mins HA kinda thing

marble jackal
#

but the switch turn_on and turn_off sections are just like the sequence in a script

#

you can add mutliple actions, so you can first set it to the right pin

#
    switches:
      plug17:
        value_template: "{{ is_state('select.pin_mode_15', 'OUTPUT_LOW') }}"
        turn_on:
          - service: whatever
          - service: select.select_option
            target:
              entity_id: select.pin_mode_15
            data: 
             options: OUTPUT_LOW
        turn_off:
          - service: whatever
          - service: select.select_option
            target:
              entity_id: select.pin_mode_15
            data: 
             option: OUTPUT_HIGH
dry sierra
# marble jackal your attribute change will trigger the state template to render again, so after ...

Maybe defining a trigger will stop the attribute change re-evaluating the state? https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-images-numbers-selects-and-sensors
Version to be tested:
`template:

  • trigger:
    • platform: state
      entity_id: device_tracker.niro_ev_19_location
      binary_sensor:
    • name: "Car Is Traveling"
      state: >
      {%- set new_lat = state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) %}
      {%- set new_long = state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) %}
      "{{ (new_lat != state_attr('binary_sensor.car_is_traveling', 'lat')) or (new_long != state_attr('binary_sensor.car_is_traveling', 'long')) }}"
      attributes:
      lat: "{{ state_attr('device_tracker.niro_ev_19_location', 'latitude') | round(3) }}"
      long: "{{ state_attr('device_tracker.niro_ev_19_location', 'longitude') | round(3) }}"`
broken viper
#

and while I was doing it I wondered if they execute in parallel or series, I imagine parallel

#

anyway, all done I think now 😛

marble jackal
#

you should first set it on the right pin, and then change the pin setting

#

so not parallel

floral shuttle
#

turning it on again after that should have registered that last_changed . In stead, it seems to return to the last HA OS restart? while the individual entity did register its time correctly

mighty ledge
#

last changed is updated on restart

#

you're also not sorting the list, like I originally had

#

you completely removed the sorting

#

or omitted it

#

or maybe I accidentally did

#

regardless, sort it based on last_changed

#

| sort(reverse=True)

#

after the map

floral shuttle
#

ok will test, but you posted this: {% set last = (label_entities('label') | expand | map(attribute='last_changed') | map('as_local') | first | default(now())).strftime('%D %X') %}

mighty ledge
#
{% set last = (label_entities('label') | expand | map(attribute='last_changed') | map('as_local') | sort(reverse=True) | first | default(now())).strftime('%D %X') %}
floral shuttle
#

relief!: tekst: > {% set last = (label_entities('kritiek') |expand|map(attribute='last_changed')|sort(reverse=True)|map('as_local')|first| default(now())).strftime('%D %X') %}

#

o sorry, crosspost there.

acoustic arch
#

i have a commandline sensor running a remote shellscript. That script ends plainly with an echo, spitting out a string. the command works in the HA terminal so i presume it works because i get the string echo'd.

But the sensor stays empty. How do i catch this string?

#
23 uur```
#

terminal output

#

got it! removed unit of measure, because well.... its a string 🙂

keen swan
#

Hi all, so i have soil moisture sensor, but it all over the place, I know what on the front end i can see min, max and mean. But i would like to make an automation that is triggered by the mean of the sensor, can someone help? I have something like this

{{ (states('sensor.sonoff_7895e1021e_humidity' , 'mean'))}} 

But obviously this wont work

#

On the front end i have this

chart_type: line
period: hour
type: statistics-graph
entities:
  - sensor.sonoff_7895e1021e_humidity
stat_types:
  - mean
hide_legend: true
days_to_show: 3
logarithmic_scale: true

So here i can set the stat_type as mean

lofty mason
#

long term statistics are not extractable for further usage.
If you want a mean sensor, you'll have to create it yourself via the statistics integration

keen swan
#

i didnt think it was a long term stat. What i look at the sensor, i see a Min a max and a mean all at the same time. So i would like it to Triger if the mean drops below 19% moisture. Eg, min is 17% mean is 19% and max is 21%, and if i watch the sensor in real time it jumps between 17% and 21% in seconds. but the wetter it gets then the min max and mean are as far apart as 34% 49% and mean at like 41% in real time

lofty mason
#

What i look at the sensor, i see a Min a max and a mean all at the same time
If you're opening the more-info popup, yes those are the generated statistics. Could be short term or long term, but the answer is the same, you cannot reference them with a template or in any other way.

#

you need to create an average sensor manually

plain magnetBOT
keen swan
#

ok, so if i did this

- sensor
  - platform: statistics
    name: "Moisture humidity"
    entity_id: sensor.sonoff_7895e1021e_humidity
    state_characteristic: mean
    max_age:
      minutes: 10
#

How would i make that a trigger in an automation, i am confused

lofty mason
#

that will create a new entity, and the state of that entity will be the mean

#

then you just use that entity with a numeric_state trigger

keen swan
#

and the entity will be called Moisture humidity?

lofty mason
#

some slugified version of that, I don't know exactly what it will be called

#

but it will be a new sensor.something entity

keen swan
#

Ok, i will give this another try, because it didnt work for me earlier,

blissful cipher
#

Hi guys, I am trying to display the value of a sensor in a template, the Developer Tools -> States ui shows the status correctly, but neither

states: {{states('vacuum.535_burgstaller_m')}}
nor
state_attr {{state_attr('vacuum.535_burgstaller_m','status')}}

shows anything, what am I doing wrong? The entity is an enum entity from Husqvarna automower

keen swan
marsh cairn
marsh cairn
#

And the entity id vacuum.535_burgstaller_m really exists? Or its attribute status ?

marsh cairn
blissful cipher
marsh cairn
#

And what exactly are you posting - and where?

blissful cipher
marsh cairn
#

Okay. In some places it needs to be in quotation marks. That's why I am asking.
So you are posting {{states('vacuum.535_burgstaller_m')}} and nothing else in the template debug ui

#

That should work. My guess would still be a wrong entity id

blissful cipher
#

this it the template ui content

states: {{states('vacuum.535_burgstaller_m')}}
state_attr: {{state_attr('vacuum.535_burgstaller_m','status')}}

this is the output

states: unknown
state_attr: None
#

I am pretty certain the entity name is correct, in the templates ui it says:

This template listens for the following state changed events:

Entity: vacuum.535_burgstaller_m
#

also if I go into the states UI and filter for this entity name, it finds the sensor and shows me docked

marsh cairn
#

Are you 100% sure, that the entity id of the vacuum really ends with m?

blissful cipher
#

100%

marsh cairn
#

I see no syntax errors

blissful cipher
#

there are none, I used the same approach for lots of other entities and that worked fine, not sure whats special about this one

#

it is a device_class: enum not sure if this makes any difference

marsh cairn
mighty ledge
#

device_class enum is only for sensors

#

FYI, you can get the entity_id from the UI

blissful cipher
#

I have the same problem with sensor.535_burgstaller_m_problem_sensor

#

however the strange thing is that this entity does not appear to be related to the new husqvarna automower integration, the automower integration was previously a HACS integration which was in-sourced

#

maybe this is an "outdated" entity (I did remove the custom integration)

plain magnetBOT
#

@quick frigate I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

you can use imgur to upload the images

#

@quick frigate this is unrelated to templates, but the Studio Code Server add-on automatically saves your changes unless you turn that off, and you need to restart HA after you added customize dit the first time. After that you can reload it under developer tools > YAML

quick frigate
lost locust
#

with the forecast attribute being deprecated from the weather service, is there any way to get/save the forecast using the frontend UI or do I have to create a template sensor via configuration yaml?

when creating a template sensor from devices > helpers it doesn't seem that there's an option to set a trigger. which is what the recommendation seems to be from https://www.home-assistant.io/integrations/weather/#examples

is there no way to configure a weather service and get the forecast from the frontend? I thought frontend config was the way forward 😕

visual cedar
#

Holy cow, I just successfully created my first working template using only the documentation and my feeble mind ... sorry for spamming the channel, but I had to share my shocked satisfaction

lost locust
#

it's a little weird to me that I define the weather entity in the service but then have to specify it again in the template

daily_forecast:
  weather.home:
    forecast:
      - datetime: '2024-04-12'
inner mesa
#

as in the example, you can request for multiple entities at once

#
service: weather.get_forecasts
target:
  entity_id:
    - weather.tomorrow_io_home_nowcast
    - weather.toronto_forecast
data:
  type: hourly
response_variable: weather_forecast
#

the first implementation (without the 's') only returned a single forecast for a single entity, and this new version replaced it

blissful cipher
hoary wing
#

can somehelp help me make a template trigger for my temperature sensors when they havent been updated 24 hours? Sometimes my temperature sensors dont update anymore and i havet to reset them ..

hoary wing
#
value_template: >-
  {{ now() - states.sensor.gang_temperature.last_changed >= timedelta
  (minutes=180) }}
id: Gang temperature
alias: Gang Temperature
#

Is this correct?

marble jackal
#

@hoary wing 180 minutes is 3 hours, not 24 hours

#

Why not just use timedelta(hours=24)

#

Besides that the trigger looks fine, but do note that last_changed is updated on a HA restart, so if you frequently do a restart you might never reach 24 hours

hoary wing
#

That’s why I choose 3 hour 🤣

plain magnetBOT
#

@naive swan I converted your message into a file since it's above 15 lines :+1:

naive swan
#

Hey everyone, I've tried using the template on the docs to get the weather forecast for my morning routine at https://www.home-assistant.io/integrations/weather/ replacing weather.home with the name of my weather entity however it's just showing as unknown on the entity it creates, not sure if I'm going wrong somewhere or if it just hasn't updated yet

marble jackal
#

what happens when you run the service call in developer tools > services

service: weather.get_forecasts
data:
  type: hourly
target:
  entity_id: weather.dunedin
response_variable: hourly
naive swan
marble jackal
#

okay

#

and you wait until it triggered, or did you create it in the last hour?

#

it will trigger every hour, so until it did, it will show unknown

naive swan
#

Ah, i thought you can sometimes force them to trigger by using the service

#

Good to know i just need to wait 🙂

marble jackal
#

nope, that doesn't work on trigger based templates, they only update on the trigger

#

it should have a value now

naive swan
#

So this just gives me the high for the next hour by the looks of it. What's the best way to get all the forecast info and not just temperature for the day. switch the type to daily seems obvious but not the rest. Basically after the full read out like the weather forecast used to have to reference in tts.

marble jackal
#

that's what you asked for in your template: "{{ hourly['weather.dunedin'].forecast[0].temperature }}"

#

it takes the first item of the forecast (so that's the next or current hour (this differs per integration)) and takes the temperature value from that item

#

What value are you looking for then?

#

if you want the entire forecast, put that in an attribute

#

but that goes against the whole change to remove the attribute in the first place

naive swan
#

For the forecast I was after the condition of the day ahead so I could dress/carry items like an umbrella accordingly, as long as getting the high/low for the day and humidity. I've always wanted the chance of rain but no sensors here ever pick that up.

marble jackal
#

you can take the forecast of the next day out of the daily forecast, it should have a precipitation_probability key

floral shuttle
#

struggling a bit here with the response variable for a todo item list... having this service```
action:
- service: todo.get_items
target:
entity_id:
- todo.huishouden
data:
status: needs_action
response_variable: taken_overzicht
sensor:
- unique_id: todo_huishouden_overzicht
state: >
{{now()}}
attributes:
te_doen: >
{{taken_overzicht['todo.huishouden'].items}}

#

but it returns this

#

while the respnse should be this

#

to my eyes Ive copied a straight config from my working weather forecast sensors, but apperently not.. can anyone spot the error?

naive swan
marble jackal
#

you can try another integration

marble jackal
#

use {{ taken_overzicht['todo.huishouden']['items'] }}

floral shuttle
#

works, thanks!

naive swan
floral shuttle
#

rebuilding some templates to use the label entities, Ive found a challenge: {% set hubs = expand(label_entities('hub')|select('is_state','home')) |map(attribute='name')|list %} works perfectly, for entities that have individually set the label. Now consider a binary_sensor.doors helper, (with the label alert) containing all doors, and the template ```
{% set alerts = expand(label_entities('alert')|select('is_state','on'))|map(attribute='entity_id')|list %}

#

this expands the binary completely, and when counted, lists all member entities inside that binary (group), and not only the 'on' members.. which is what I am looking for

#

{{- expand('binary_sensor.alerts') |selectattr('state','eq','on') |map(attribute='name') |join(',') -}} does work (only counts the open doors inside the member binary_sensor.doors, and it has the exact same members as the label entities

#

can we not iterate the label_entities like that?

floral shuttle
#

can loop: {%- set ns = namespace(alerts_on=[]) %} {% for a in expand(label_entities('alert')) if a.state == 'on' %} {% set ns.alerts_on = ns.alerts_on + [a] %} {% endfor %} {{ns.alerts_on|map(attribute='name')|list}}

#

that was just a bit more involved than I would have hoped:```
{%- set ns = namespace(alerts_on=[]) %}
{% for a in expand(label_entities('alert')) if a.state == 'on' %}
{% set ns.alerts_on = ns.alerts_on + [a] %}
{% endfor %}
{% set alerts = ns.alerts_on|map(attribute='name')|list %}

        {% set count = alerts|count %}
        {%- if count == 0 -%} Ok, geen alerts, alles is in orde
        {%- elif count == 1 -%}{{count}} Alert voor: {{alerts[0]}}
        {%- elif count == 2 -%}
          {{count}} Alerts voor: {{alerts[0]}} en {{alerts[1]}}
        {%- else -%}
          {{count}} Alerts voor: {{alerts[:-1]|join(', ')}}, en {{alerts[-1]}}
        {%- endif %}```
lucid thicket
#
{{ expand(label_entities('alert'))
   | selectattr('state','eq','on') | map(attribute='entity_id')| list }}
mighty ledge
#

you dont even need expand

#
{{ label_entities("alert") | select('is_state', 'on') | list }}
#

at this point, expand should only be used to expand groups, or to access a state object's properties (context, last_reported, last_updated, last_changed)

#

all other cases, use select with is_state and is_state_attr

#

not only is it more efficient, it properly uses generators where expand always returns a list.

#

i.e. all around better to use

lucid thicket
#

But that is the case here, Mariust has labeled a group entity and wants to list out the group members that are on

mighty ledge
#

I'd probably still go a separate route to avoid expand, but yes then using expand will be ok

#

{{ label_entities('alert') | map('state_attr', 'entity_id') | sum(start=[]) ...

#

expand would still work better than that because non-groups would cause issues

lucid thicket
#

Well I still learned something today, thank you

mighty ledge
#

np

floral shuttle
mighty ledge
#

read the remaining responses 😉

floral shuttle
#

ah, sorry... {{ expand(label_entities('alert')) | selectattr('state','eq','on') | map(attribute='name')| list }} works ok indeed, thanks Mecaneck (why didnt I test that...hmm.)

#

and making that text template much more readable:```
{% set alerts = expand(label_entities('alert'))
|selectattr('state','eq','on')|map(attribute='name')| list %}
{% set count = alerts|count %}
{%- if count == 0 -%} Ok, geen alerts, alles is in orde
{%- elif count == 1 -%}{{count}} Alert voor: {{alerts[0]}}
{%- elif count == 2 -%}
{{count}} Alerts voor: {{alerts[0]}} en {{alerts[1]}}
{%- else -%}
{{count}} Alerts voor: {{alerts[:-1]|join(', ')}}, en {{alerts[-1]}}
{%- endif %}

floral shuttle
#

summary:

marble jackal
#

I would expect the 2nd one here to return what you want

#

the names of the binary sensors within the entities labeled alert

#

but maybe I missed some parts of the discussion 🙂

plain magnetBOT
#

@dry sierra I converted your message into a file since it's above 15 lines :+1:

dry sierra
#

If I define a template sensor in configuration.yaml using a trigger (platform: state), should I be able to reference trigger.from_state and trigger.to_state?

#

`template:

  • trigger:
    • platform: state
      entity_id: device_tracker.niro_ev_19_location
      binary_sensor:
    • name: "Is GPS Active"
      state: >
      "{{
      (state_attr('trigger.from_state', 'latitude')
      != state_attr('trigger.to_state', 'latitude'))
      or
      (state_attr('trigger.from_state', 'longitude')
      != state_attr('trigger.to_state', 'longitude'))
      }}"`
marble jackal
#

yes, you should be able to do that

floral shuttle
mighty ledge
floral shuttle
#

btw, 1 of my alerts was binary_sensor.meteoalarm_brabant, which is a core integration binary. It does not have a unique_id, so I can not set a lable on it.. funny we now need to make a template duplicate for that to be able to do so

marble jackal
#

but after you fixed what petro mentioned the binary sensor above will basically always be true, because it will trigger on a state change of the device tracker, indicating it changed positition so at least longitude or lattitude changed

#

unless you change the name of the entity or something like that

mighty ledge
#

I went back through all my 'old' entities that didn't allow unique_ids, turns out in the past few years unique_ids were added to all of the yaml configurations.

floral shuttle
#

Ive asked Joost and he did have a look, but the integration requires a config flowe to be able to add unique_id (or so I remember)

mighty ledge
floral shuttle
#

would really be great if that would migrate

#

i think I listed a few integrations I use that didnt have UID yet....

mighty ledge
floral shuttle
#

heavily stressing the 'think' there

#

You dont have an active recollection of that.....

mighty ledge
#

Well he does now!

#

🤣

floral shuttle
#

it's a Dutch inside joke....

#

maybe even copied from abroad, since it was used by our heavily politically spinned Prime Minister some time ago, and everybody is using that now

sleek trail
#

Currently new features are just on a low burner atm

floral shuttle
#

anyways, back to the topic of template copying another entity: do we have a fixed stategy for that? or should I simply do state: > {{states('binary_sensor.meteoalarm_brabant')}} and for the attributes list (which is rather extensive) simply refer to the original. How would I otherwise do that without hardcopying all attributes

#

a bit silly but it does the job (for now)

floral shuttle
lucid thicket
sleek trail
#

Nederlandse Spoorwegen is one that gets relevant soon

floral shuttle
lofty mason
#

Alert is all but deprecated it won't be converted.

floral shuttle
#

why is that? tbh, its quite active in guarding the mem %... had it kick in regularly, to safe the instance

#

or warning for the obvious low mem on our devices

sleek trail
#

I guess because its a blueprint in disguise

lofty mason
#

From Frenck:

The core team has discussed the alert integration and related PRs recently. We don’t want to expand the alert integration any further. Our future plans for this integration are to replace it with blueprinted automations. Once we have evolved our blueprint feature we plan to deprecate this integration.

floral shuttle
#

ok, well, thats cool. if the Blueprint would provide the same options (or better), that would probably be my first time to test that. Still have no use for any of the BP's floating around so far.

sleek trail
#

If I read the alert docs, you can already migrate this to a blueprint

mighty ledge
#

I'd wager they need to move away from notification services and move to notification entities, that's why it's not a blueprint replacement yet

lofty mason
marble jackal
#

you can always create an automation yourself, it's not so hard to replicate an alert in an automation

lofty mason
#

You can add an input_boolean yourself, but it's a bit extra work

sleek trail
lofty mason
#

alerts create an alert. entity

floral shuttle
#

@marble jackal yeah, but why, if we have the dedicated integration do it 😉 Ive never given that any thought

lofty mason
#

can put em on your dashboard

sleek trail
#

aah right

sleek trail
floral shuttle
#

sure, then we must, would be very very breaking though....

marble jackal
#

you can trigger on home assistant start and on the trigger entity going to the wanted state, and then use a repeat to send a notification every x minutes

#

a little bit more work is needed if you want different times between the notifications

mighty ledge
#

the problem that yall are glossing over is that the only way to use a notification in a blueprint currently is to have the user type out the notification service manually or use a device_action

#

major changes to notifications need to happen in order to replicate alerts in blueprints

#

specifically, we need a generic notification service and a notification selector

marble jackal
#

oh yeah, I'm not talking about the blueprint now, more like how I should tackle it in an automation

mighty ledge
#

because our current course (device selector) is extremely limited

marble jackal
#

for a blueprint you could use an action selector

mighty ledge
#

Yeah but then the user has to build the notification

#

defeats the purpose

floral shuttle
#

Given the current complex options of the Alert integration, and Frencks quote there, I think it is safe to assume it is going to be a while before Alert is deprecated... lot of 'future', 'once', 'plan', 'evolve'..

lofty mason
#

Yeah I didn't mean it was imminent, what I meant was that they aren't accepting enhancements anymore.

floral shuttle
#

sure.

marble jackal
floral shuttle
#

besides that, it is such a fundamental integration, that it would take a very well implemented replacement to not have the community go revolting 😉

mighty ledge
#

fundimental is a stretch

#

0.9% of active known HA users

floral shuttle
#

well, it has been in my system from the beginning, and I suppose many use it?

floral shuttle
#

wow, I never would have expected that

mighty ledge
#

it's yaml, only yamlers are going to use it

#

we are rare these days

floral shuttle
#

haha, well, the way I did it, when starting HA, was walking the list of core Integrations alphabetically, checking what I could use 😉

mighty ledge
#

lol, I would love if people did that

#

sadly, people now plug it in and immedately ask questions here or on reddit, completely skipping the website

floral shuttle
#

guess I am not a true heavy user of complex Alerts, and smth like this could be worth the trouble of migrating to a triple state binary template sensor and automation```
alert:

ram_too_high:
name: Ram Usage > 85%
entity_id: binary_sensor.ram_too_high
can_acknowledge: True
repeat:
- 5
- 30
- 60
notifiers:
- mobile_app_marijn```

#

maybe even combine that with a trend sensor, (which btw should be added to the list of non UID...)

floral shuttle
#

btw, Ive just found out that reload all Yaml does not reload Alert. Does it only reload Yaml with unique_id....?

lofty mason
#

It's misleading. Reload all is equivalent to clicking each of the reload buttons on the yaml page. It only reloads things that can be reloaded.

#

I actually tried to add reload for alerts, and it was denied 😢

inner mesa
#

without adding config_flow, or just because they want it to die?

lofty mason
#

I wrote it once, and then in feedback got asked to rewrite the entire thing using helpers/collections. Then after rewriting it all, I was then told, nevermind they just want it to die 😂

#

Then someone else came along 3 months later and rewrote that exact same PR again 😂, and denied again.

inner mesa
#

Oh, you want to get started with HA development? Here's your first exercise...

#

you not only get to learn how HA integrations are structured, but you're also introduced to the somtimes arbitrary and capricious decisions from core 🙂

floral shuttle
floral shuttle
dry sierra
#

I've defined a binary_sensor with two attributes that I expect to be decimal numbers, but looking at them in Developer Tools they seen to be double double quoted:
d_lat: "\"-0.036740999999999246\"" d_long: "\"-0.0014339999999999353\""

#

The attributes are defined like this:
attributes: d_lat: > "{{ trigger.to_state.attributes.latitude - trigger.from_state.attributes.latitude }}" d_long: > "{{ trigger.to_state.attributes.longitude - trigger.from_state.attributes.longitude }}"

#

How can I make the values just be numbers?

inner pagoda
#

when you're using multi-line yaml strings with the > or |, you shouldn't quote them

#

the > or | acts like quotes, so any quotes you put inside them are included in the resulting string

dry sierra
#

Thx - trying now!

#

attributes: d_lat: > {{ trigger.to_state.attributes.latitude - trigger.from_state.attributes.latitude }} d_long: > {{ trigger.to_state.attributes.longitude - trigger.from_state.attributes.longitude }}

#

Always Save File + Restart Home Assistant if I change configuration.yaml?

#

Thx - numbers now as expected 🙂

marble jackal
#

You can reload template entities from developer tools > YAML

bronze prawn
#

How can add 120 seconds to the current time? I know I can do {{ now() }} to get the current time, but how can I add time to it? I'd like to abe able to use this value to set a calendar event start time as the now() value and the now() + time as the ending time.

lucid thicket
#

You can add a timedelta object to a datetime object.
now() + timedelta(hours=2, minutes=30)

bronze prawn
#

Rock on! Thanks

floral shuttle
#

usecase: need to condition/wait_template that 2 windows (label) in 2 different areas in the same floor are closed before continuing. There is no way we can use the label entities directly in the floor, nor is there floor_entities. What am I missing here.. I might be better off hard coding those 2 windows....

#

I have these```
{{floor_areas('woongedeelte')}}

in 'woongedeelte' there are 2 areas:

{{area_entities('woonkamer')}}
{{area_entities('eetkamer')}}

in those areas, I need to find the state of

{{label_entities('schuifpui')}}

#

should I simply do {{['binary_sensor.schuifpui_groot_contact', 'binary_sensor.schuifpui_klein_contact'] |select('is_state','on')|list|count == 0}}..... and forget about all new options?

mighty ledge
#
{{ floor_areas('woongedeelte') | map('area_entities') | sum(start=[]) | select('in', label_entities('schuifpui')) | list }}
floral shuttle
#

yes, thank you. that lists the 2 entities correctly. have to consume that though.... and, I've seen the | sum(start=[]) more frequently recently, what exactly does that do

#

seems a terribly convoluted way to find the label_entities('schuifpui') in the floor 'woongedeelte'

#
{{ floor_areas('woongedeelte') 
                       | map('area_entities') 
                       | sum(start=[]) 
                       | select('in', label_entities('schuifpui')) 
                       | select('is_state','on')|list|count == 0 }}``` does check correctly
#

this would be so much more obvious: {{label_entities('schuifpui') |select('in',floor_areas('woongedeelte'))|list}}

mighty ledge
#

it combines lists

floral shuttle
#

can also do {{label_entities('schuifpui') |select('in',area_entities('woonkamer')+ area_entities('eetkamer'))|list}} but that too is a but hacky (and still requires me to hard code the area names)

floral shuttle
#

guess it would also be nice if we could do area_entities('living','dining') or maybe in the list. that would allow us to do in area_entities(floor_areas('woongedeelte'))... hope these functions will see some development in the future

marble jackal
#

I expect floor_entities() will be added

floral shuttle
#

would that expand the entities in the areas inside that floor? I mean we dont have floor entities? only areas...

bronze prawn
#

{{ now () }} produces output 2024-04-13 08:53:00.413137-05:00 I am trying to use this to set a calendar event and would like the format in yyyy-mm-dd hh:mm:ss format. I see this referenced in the docs:
https://docs.python.org/3.8/library/datetime.html#datetime.datetime

But I'm not sure how to format. Is this the way or is there some other way (fstring?) to output in that shortened form?

lucid thicket
#

{{ now().strftime('%Y-%m-%d %H:%M:%S') }}
Keep in mind now() returns a datetime object and when you convert it to a string it is shown that way you displayed. But it is not actually a string itself. The strftime() method will convert it to a string in the format you specify.

mighty ledge
#

but for the time being, this is a substitute:

{{ floor_areas('floor') | map('area_entities') | sum(start=[]) }}
mighty ledge
#

it's smart enough to handle datetime objects

#

so when I set them, e.g. 2 hours in the future {{ now() + timedelta(hours=2) }}

bronze prawn
# mighty ledge <@335837742615363604> just output the DT object to the `datetime` field. It doe...

Thanks. I had tried that and my automation did not trigger. I was thinking it may be because of the date format but it may be that it is not as percise as I am wanting. I was trying to do a 90 second timer with the start set as now and the end as now + 90 seconds. I could see that the calendar had the right time in it though it did not list seconds. The service call does allow for setting seconds but maybe it is not actually using them.

I think this calendar method can be used for things like "Remind me at 6:30pm to leave for dinner" and "Set an alarm for 5:00am tomorrow" but maybe not these timers.

mighty ledge
#

calendar is only minutely

#

input_datetime is secondly

bronze prawn
# mighty ledge calendar is only minutely

Great to know. So the two use cases above can be done using the calendar. I'm sure it'll be fun to get assist output into the correct day/time format I'll need to feed to calendar but technically it should work.

The timers are a different story. I had a chance to talk to Mike about it and he said they are wanting to create a way to have timers without the need of helpers. I think lots of folks use timers with their current voice assistants. I know we do.

bronze prawn
#
{% endif %}```
I am getting the mode value from a custom sentence.  I am wanting to compare if the variable being entered matches any of the three above and if so then this condition is true in a template value condition.  This does not equal true when I use any of the above.  I have an else that returns what I said.  I am receiving back the 'normal', 'music', 'hold' from that else condition.

Am I comparing these incorrectly?
bronze prawn
#
{% if (mode == 'normal') or (mode == 'night') or (mode == 'hold') %}
true
{% endif %}

I made an assumption that this would return true if it was true but it wasn't. Adding true fixes it

inner pagoda
#

You could do {{ mode == 'normal' or mode == 'night' or mode == 'hold' }} - that will result in either a true or false value.

#

(assuming mode is set)

#

or even shorter, {{ mode in ['normal', 'night', 'hold'] }}

bronze prawn
#

Now we're talking! Thank you!

inner mesa
#

Please understand why. You explicitly weren't returning anything at all in your original version

bronze prawn
bronze prawn
# inner pagoda or even shorter, `{{ mode in ['normal', 'night', 'hold'] }}`

So this is really cool and I'm already trying to extend it. I'm trying to add functionality for voice to remove an item from the shopping list. Using this I can ensure that the item is in the shopping list. Assume that 'Eggs' was spoken:

And this returns true. The problem is matching the case. Is there a way to do a compare like this but make it case insensitive? What I really need is to check if the item is in the list regardless of case, and if so, return that value because I need to match exactly for the todo list service remove.

inner mesa
#

{{ 'Eggs'|lower in ['foo', 'bar', 'eggs']|map('lower')|list }}

#

-> True

#

in other words, make everything one case

bronze prawn
#

Ah yes. Works for sure. How what about getting the 'true' value out? Case sensitive to pass to the service?

#

I guess I can figure out what element it is and then return that one?

inner mesa
#

you mean "true" instead of "True"?

#

it's just a boolean

#

oh, you mean the value without converting the case

bronze prawn
#

I apologize. No I mean if the item is stored as 'Eggs' in the list. I know if we put input match to lower and whole list to lower we know it is in the list. How do I get the real name out

#

Correct. I'd like it as two steps. Is it in the list? if so, then get the stored value out to send to remove

inner mesa
#
{% set items = ['foo', 'bar', 'eggs'] %}
{{ items[(items|map('lower')|list).index('EGgs'|lower)] }}
#

-> eggs

bronze prawn
#

Wow. That is REALLY cool!

#

Let me make sure I understand. You are doing a return like items[2] but it is evaluating the part between the [] to get the index value right?

inner mesa
#

Yes

bronze prawn
#

really cool

inner mesa
#

I'm getting the index based on the lowercase comparison and then returning the real value at that location

#

You probably want a |default() in there to catch the case where it doesn't exist

#

And I guess it gets the first one if there are two of the same

plain magnetBOT
#

@forest ferry I converted your message into a file since it's above 15 lines :+1:

forest ferry
#

without bot conversion....
Hi, I'd like to apply my auto-entities template below to 6 sensors (number.doorlock_front_user1, number.doorlock_front_user2, etc)
could you assist with the loop syntax I should be using? Thank you!
code above.
BTW Newbie to Discord, any way to avoid the Bot conversion for code over 15 lines? thx

plain magnetBOT
#

@forest ferry I converted your message into a file since it's above 15 lines :+1:

bronze prawn
compact ether
#

Does anyone know how I can create a template sensor based on any of a number of other sensors being in a particular state? Basically I want to do the following, but I know the asterisk wildcard doesn’t actually work:

  Problem
{%- else -%}
  OK
{%- endif %}```
marsh cairn
#

You better use a template binary sensor with device class problem.

marble jackal
#

{{ states.plant | selectattr('state', 'eq', 'problem') | list | count > 0 }}

marsh cairn
#
{{ states.plant 
  |selectattr('state', 'eq', 'problem')
  |list
  |count > 0 }}
#

Oh...

#

Well...

#

Too late shksD

compact ether
marsh cairn
#

You create a binary sensor. And with device class problem, it will show OK or Problem automatically

compact ether
#

Yeah I just didn’t know how to pull the states from all plant. entities until @marble jackal and @marsh cairn provided the above code. 🙂 I try to read the Jinja instructions for templates, but without a background in programming, it all kind of melts my brain. I’m slowly, slowly starting to improve at this stuff… Many thanks for the help!

marsh cairn
#

If you TheFes' template directly behind the state:, you need to put quotation marks around it.

#

Or a > behind the state:, if you prefer the multi line one.

compact ether
#

@marsh cairn my apologies; I don’t quite understand what you’re saying

marsh cairn
#

Example 1:

template:
  - binary_sensor:
    - name: "Dead Plant"
      state: "{{ states.plant | selectattr('state', 'eq', 'problem') | list | count > 0 }}"
      device_class: problem
#

Example 2:

template:
  - binary_sensor:
    - name: "Dead Plant"
      state: >
        {{ states.plant 
          |selectattr('state', 'eq', 'problem')
          |list
          |count > 0 }}
      device_class: problem
compact ether
#

So far @marble jackal ‘ code seems to sort of work in the binary sensor template, except it evaluates the same whether I leave it as > 0, < 1, or == 0. It always shows “OK” in the preview.

#

Are pictures prohibited here? Tried sharing a screenshot but no dice.

plain magnetBOT
#

Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

compact ether
marsh cairn
#

Ah. You are using the helper

compact ether
marble jackal
#

Is there currently a plant with a problem?

compact ether
#

Oh FFS the tick marks from the markdown got pasted into the template box 🤦‍♂️

#

I removed the tick marks and it works now.

marble jackal
#

👍

compact ether
#

Thank you so much folks. I really appreciate the help with learning stuff.

inner mesa
#

Mine would always just say 'problem'

marsh cairn
bronze prawn
#

I know that you can take time and put it into the am/pm format like:
{% now "%B %-d, %Y %-I:%M" %}

But is it possible to do the reverse? I have time as 6:00 PM and want to get it into the military time hh:mm:ss format to feed it to a service call to make a calendar event

#

Old chatgpt gave me this:

{{ "%02d" % ((time.split(':')[0]|int + (12 if "PM" in time else 0)) % 24) }}:{{ time.split(':')[1] }}```
but it returns:

```18:00 PM```

The time part appears to be working but I don't know why it's adding that PM portion
lofty mason
#

if you split on the ":", then split[0] will be 6, and split[1] will be 00 PM

lucid thicket
#

Use strptime()

lofty mason
#

{{ strptime("6:00 PM", "%I:%M %p") }} -> 1900-01-01 18:00:00
{{today_at(strptime("6:00 PM", "%I:%M %p").strftime("%H:%M")) }} -> 2024-04-13 18:00:00-07:00

lucid thicket
#

Via any method you’ll have to add todays date if the intent is to get a datetime object

{{ strptime(today_at().date() ~ " " ~ "6:00 PM", "%Y-%m-%d %I:%M %p") }}
bronze prawn
#

That's super handy. So to finish I need the date. I think I can pull that from now() as the user won't supply it. I am trying to get it so that someone says "Set a reminder to walk the dog at 6:00 PM", I can convert that time text like you are showing but I'll need to get the current date and have it all formatted like:

#
service: calendar.create_event
data:
  summary: test
  start_date_time: "2024-04-13 18:00:00"
target:
  entity_id: calendar.assist
bronze prawn
lucid thicket
#

I think karwost’s edit is cleaner

bronze prawn
#
service: calendar.create_event
target:
  entity_id: calendar.assist
data:
  summary: "{{trigger.slots.action}}"
  start_date_time: "{{today_at(strptime(trigger.slots.time, "%I:%M %p").strftime("%H:%M"))}}"
  end_date_time: "2024-04-13 20:00:00"

I'm scratching my head. I have the response showing me the template value being used for start_date_time and it appears like this:

Please remember to take out the trash at 5:30 pm 2024-04-13 17:30:00```
#

But yet the calendar event is being set for tomorrow instead of today at:

April 14, 2024 at 12:00 AM - April 15, 2024 at 12:00 AM
#

It's like it is setting it to an all day event but I am not specifying that option.

#
service: calendar.create_event
target:
  entity_id: calendar.assist
data:
  start_date_time: "2024-04-13 20:00:00"
  end_date_time: "2024-04-13 20:30:00"
  summary: test

This one works when setting from dev tools. The only thing different is the use of the template ohhhhhhhhhhhhhhhhhhhhh

#

single/double quotes

#

Nope. That did not fix it

#
service: calendar.create_event
target:
  entity_id: calendar.assist
data:
  summary: "{{trigger.slots.action}}"
  start_date_time: "{{today_at(strptime(trigger.slots.time, '%I:%M %p').strftime('%H:%M'))}}"
  end_date_time: "2024-04-13 20:00:00"

Now it does not set the event at all and gives the 'Done' response which is an indicator that something is wrong

bronze prawn
quiet creek
#

How can I make a home assistant sensor to make the states of an input select more readable. I want: unplugged, idle, paused, detached_overload, job_ongoing, job_completed = Unplugged Idle Paused Overload Running Completed

inner mesa
#

You can make the options whatever you want. Why did you choose the ones you don't want?

#

There are many ways to create a template sensor to transform the state

quiet creek
plain magnetBOT
#

@quiet creek I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

You won't be able to fix that

quiet creek
#

Why is that? Is it because I can't combine multiple entities? Maybe I could use a conditional card

inner mesa
#

Because you're just setting the time as a string

#

The frontend only displays timer values by playing games and only with actual timer entities

#

I don't even see where you would expect the remaining time to be shown based on your template

fresh pulsar
#

hey all, I am trying to measure water usage for watering my plants/lawn. My current setup is that I have a moen flo to measure my total water usage and then i have a smart valve outside my house to automatically water the plants. I was thinking that I could use a utility meter to only record the water usage while the state of my valve was 'on' but I'm not exactly sure how to accomplish that. Any help would be greatly appreciated!

plain magnetBOT
#

@fresh pulsar I converted your message into a file since it's above 15 lines :+1:

neon laurel
#

can I access from_state on a template light? Or any other way to access the previous state

marble jackal
#

You can use this to access the current state (which will be the previous state after the template is rendered)

neon laurel
# marble jackal You can use `this` to access the current state (which will be the previous state...

Mmm I don't think that's gonna work then. I'm making 2 separate lights each using 2 channels of an rgbw light. To turn the first light off but not the other, I use turn_on with rgbw_color command: 0,0,current,current. This way the first light that uses red and green is turned to 0, but the original light is still on and the values for the second light (blue and white) don't change. Problem with this is that when I try to turn the first light back on it sets r and g to the last known value, which is 0

#

I could default to a higher brightness but ideally I'd restore the previous value

#

Only way might be a helper I guess

#

Unless there's a way to arbitrarily access previous states (e.g. state(2) returns the third last known state)

inner pagoda
#

yeah, for that you'd need a helper to store the last used "on" state/level.

viscid oyster
#

Hello all, I am sure this may have been asked a million times... but, I am trying to add a custom sensor template to the energy "individual devices" list and it does not appear there

#

I have compared the states of the entity with the ones working, and the only difference I can see is that the one I created does not have the "state_class: total_increasing"

#

this is the definition:

#

pool_summation_delivered_corrected:
friendly_name: "Pool Energy usage"
unit_of_measurement: "kWh"
value_template: "{{ (states('sensor.pool_summation_delivered') | float / 1000) | round(2) }}"
device_class: energy

viscid oyster
#

yeah, but it does not allow me

lofty mason
#

I think you're using legacy template configuration format, you'd need to use the new format

viscid oyster
#

one second...

viscid oyster
#

Invalid config for "template" from integration "sensor" at configuration.yaml, line 120: "state_class" is an invalid option for "sensor.template"

#

yes, I am aware that I need the state_class: total_increasing, but how do I add it??

inner mesa
#

You put all that under sensor:

#

It belongs under template:

#

See all the examples below

viscid oyster
#

Hello, another person on reddit made me notice that I am using the legacy format in my configuration.yaml

#

that's why it was not taking the options

#

I am formatting the configuration to the new one... but although HA accepts the config without errors, I have lost all my custom sensors 😕

viscid oyster
#

no question for now, I am reviewing my configuration, removing tabs, checking spacing...

#

and, yes, now it's giving several errors

#

it's giving me an error on line 2:

#

default_config:

#

¿?¿?

#

ok, how can I have an error in the first line of my configuration.yaml? my first line is just:

#

homeassistant:

#

I am checking some configurations examples on github, and also checking with chatgpt, is it required now to split the config in several files for each section?

inner mesa
#

No

viscid oyster
#

then I do not know why it is erroring on the first sentence already

agile patrol
viscid oyster
#

I am rewriting the whole thing from scratch... it's gonna take me a bit of time

#

ok, I am starting to feel like an idiot, the examples of the configuration.yaml I am looking at in the github are using the legacy format

#

I would have thought all the examples would be updated

marble jackal
#

Those are links to configurations of persons, in most cases probably their production system.

#

And it's a huge list

#

But focus on your own config, how did you add your own template sensors now

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.

marble jackal
#

Share what you have now

viscid oyster
#

this is what I have now:

#

I can't upload the file

#

and it's too long to paste

inner mesa
#

Looks like you have a space before template: (remove it) and you didn't follow the format from the docs for the sensors

#

Look again, specifically at the -

viscid oyster
#

I am editing the whole thing, obviously the sensors are the most important right now

#

why do I get an error on column 1 line 2?

#

expected block end but found block mapping start

inner mesa
#

Just compare with the examples

agile patrol
viscid oyster
#

really? I think I removed it before and the error just went to 1, 1

#

let try again

#

let me try again

#

(also, I did not include the comment, it was part of the original file)

#

Same error on line 1, column 1 with this:

#

default_config:

#

I am guessing it wants it to be included under some branch

#

the error disappeared when I corrected the spacing in the template/sensor section

earnest arrow
#

have i ever mentioned my strong dislike for jinja

agile patrol
viscid oyster
#

checking the logs now for errors: the option color is not accepted, and I believe the friendly name is also wrong

earnest arrow
#

plain python 😉

#

main problem is i don't use it enough to remember it

viscid oyster
#

ok, so none of the sensors are working

#

I will try removing the color part first...

#

ok, the icon template is also wrong...

#

the problem with home assistant (among others), is that things change so fast, that most of the information in the forums become completely useless

#

friendly name is also gone

#

ok, it WORKED

#

I have to remove all the outdated tags, and I will have to check how to change the names now that there is no friendly name, but other than that the sensors are working, and more important, the stupid new sensor for the pool is now visible in the energy dashboard

#

Thanks a lot for the help!

#

I will keep checking the file and changing it all to the new format

earnest arrow
#

Can you not template the entity_id in the target of a service?

#
target:
  entity_id: {{ trigger.id }}

gives not a valid value for dictionary value @ data['action'][0]['target']['entity_id']

the value of trigger.id is a valid entity_id

viscid oyster
#

yes, it's what I was checking now

inner mesa
#

Like any single-line template

earnest arrow
#

baaaah

#

knew it would be something simple

ancient ether
#

Hi guys, I really need help with the dashboard. How do I get it so I can get one dashboard to show to one user and a different one to show to another user

inner mesa
#

No templates there

neon laurel
#

although I'm having issues applying scenes to the template light in general, not sure why

slow mirage
#

Hi guys, do i see it correctly that templated binary_sensors which are defined in the Web UI rather than in YAML are lacking the options for delay_on and delay_off ? I cannot find these options.

marble jackal
#

correct, if you want those more advanced options you'll have to create it using YAML

slow mirage
#

meh. i was hoping to streamline my config a bit more and migrate from YAML to the web UI

hollow plinth
#

Hey
I need some help with template sensors and helpers.
I have a temp sensor for my pool. I would like a new sensor to show the temperature only when the pump is running (i have it on a switch entity) and keep the last value it had before I stopped the pump when the pump is off.
I found a few things on the forum but I'm too uncomfortable on these sensors to get through it. :/

Can anyone help me with it?

mighty ledge
#

Post what you've tried

hollow plinth
#

I tried to reproduce the post before last of this discussion:

#

I tried to build the template sensor from the helper UI but I cannot get the state part to be accepted

#

It seems i got it right this time:

#
  {{ states('sensor.pool_water_temperature') }}
{% else %}
  {{ states('input_number.end_of_day_pool_water_temperature') }}
{% endif %}```
#

On the automation I have:

description: ""
trigger:
  - platform: state
    entity_id:
      - switch.shellyplus1_piscine_switch_0
    to: "off"
condition: []
action:
  - service: input_number.set_value
    metadata: {}
    data:
      value: "{{states('sensor.pool_water_temperature')}}"
    target:
      entity_id: input_number.end_of_day_pool_water_temperature
mode: single```
#

My issue is that I cannot find the entity "input_number.end_of_day_pool_water_temperature"

#

Do I have to create it somewhere? if so, whith an helper?

mighty ledge
#

It's a helper

#

You manually create it

#

@hollow plinth

plain magnetBOT
#

Open your Home Assistant instance and show your helper entities

mighty ledge
#

that link will open to your HA page if you set up mylinks. The link should walk you through the process, and it's secure.

hollow plinth
#

Thanks @mighty ledge

#

It will be a numer kind of helper?

#

Number seems not the right kind

mighty ledge
#

number is correct

hollow plinth
#

Ok

#

Seems to be all good.

#

Thanks a lot @mighty ledge

lilac anchor
#

hello. question on how to add "attributes" to template sensors. this video i'm following is adding the template directly into the configuration.yaml file. is that recommended? or best to use the template sensor helper.

#

but when i try to add it via the template sensor, i'm not able to figure out how to add "attributes" to my sensor

inner mesa
#

You can't add attributes from the UI

#

you have to use YAML for the whole thing if you want attributes or any of the other more advanced features

lilac anchor
inner mesa
#

Put it there or in an included file. Doesn't matter

lilac anchor
#

for the templates created through the UI, are you able to edit the yaml?

inner mesa
#

No

plain magnetBOT
#

@worn nova I converted your message into a file since it's above 15 lines :+1:

lilac anchor
# inner mesa No

thanks!

last questions. if i want to use a seperate yaml file, including this "!include advanced_templates.yaml" in my main configuration.yaml is the correct syntax right?

#

or would it be "templates: !include advnated_templates.yaml"

inner mesa
#

template: !include templates.yaml

#

or whatever you want to call it

lilac anchor
#

thank you kind sir!

#

now here to hoping my bin collection logic works 🙂

lilac anchor
#
- sensor:
    - name: days_to_next_recycling_collection
      state: >-
        {{ min(((state_attr('calendar.recycling_collection', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
      attributes:
        days: >-
          {{ ((state_attr('calendar.recycling_collection', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
          -name: days_to_next_trash_collection
      state: >-
        {{ min(((state_attr('calendar.trash_collection', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
      attributes:
        days: >-
          {{ ((state_attr('calendar.trash_collection', 'start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
#

i'm getting a "duplicate key" error but not able to understand why

plain magnetBOT
#

@lilac anchor 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.

lofty mason
#

you're missing - name: days_to_next_trash_collection ?

#

oh it's there but it's not whitespace aligned correctly it seems

lilac anchor
#

yes! thank you.

willow wing
#

Hey, i try to count my persons there are at home, my try is the following but it does not work when i try to exclude some persones, can someone assist please?

{{ dict((states.person|filter(not person.martin))|groupby('state'))['home']|count }}

inner mesa
#

that's...an interesting attempt 🙂

#

{{ states.person|rejectattr('entity_id', 'eq', 'person.martin')|selectattr('state', 'eq', 'home')|list|length }}

#

or if you have more people you want to exclude:
{{ states.person|rejectattr('entity_id', 'in', ['person.martin', 'person.someoneelse'])|selectattr('state', 'eq', 'home')|list|length }}

willow wing
#

Yeah when noobs are trying something 🤣
Thanks rob, yours are working great 👍🏻

plain magnetBOT
#

@bold grotto I converted your message into a file since it's above 15 lines :+1:

#

@bold grotto I converted your message into a file since it's above 15 lines :+1:

lilac anchor
mighty ledge
#

@bold grotto you have an error somewhere

{'apple_device': True, 'subtitle': 'the subtitle', 'push': {'interruption-level': Undefined}, 'actions': [{'option1': 'action_1'}, {'option2': 'action_2'}, {'option3': 'action_3'}], 'tag': 'the tag'}

#

notice the word Undefined for 'interruption-level'?

#

that won't translate to JSON

void robin
#

Is it possible to create a template with the number of add on updates that are pending? I have asked chat gpt and tested some that I found online but haven't got anything working.
Something alike to the Hacs sensor would be ideal.

inner mesa
#

I'm sure there are update.xxx entities that have some pattern to them

#

so then it's just counting the number of them with a state of 'on'

mighty ledge
#

I can't find any pattern to them that fit just addons

inner mesa
#

don't they start with "addon"

#

and have the slug?

mighty ledge
#

I'm not seeing that

inner mesa
#

boo

void robin
#

I was thinking something along those lines. But as @mighty ledge says, there might be other stuff there as well :/

mighty ledge
#

best case...

inner mesa
#

I thought I had a template sensor for this at some point, but I'm pretty far away from addons now

#

or maybe there was something in the supervisor integration

mighty ledge
#

ya

#
{{ integration_entities('hassio') | select('is_state','on') | list | count }}
#

Also includes core though

void robin
#

Close enough. I could live with core being included.

#

Thank you!

void robin
mighty ledge
#

you can always filter it out

#

do this

#

{{ dict(integration_entities('hassio') | expand | groupby('state') | list)['on'] }}

void robin
#

Ah, it is because z2mqtt and moquitto is running

mighty ledge
#

or that

void robin
#

I just removed the count part from the original and it printed the names of the ones set to on. So I guess it includes more than updates :/

#

Two of them I can filter out. That shouldn't be a problem.

mighty ledge
#

oh

#

yeah, filter down to just update entities

#
{{ integration_entities('hassio') | select('match','^update.') | select('is_state','on') | list | count }}
marble jackal
mighty ledge
marble jackal
#

I thought it would be actually good to use that attribute once, instead of incorrectly adding it to a state trigger

chilly furnace
lilac anchor
#

{{states(('sensor.bike_estimated_range') | float) * 0.621371}}

#

try that

marble jackal
marble jackal
plain magnetBOT
#

@bold grotto I converted your message into a file since it's above 15 lines :+1:

bold grotto
#

ok, after a restart now it seems to be working... thanks @mighty ledge for pointing out the Undefined variable

lucid thicket
#

Just open up the entity and change the drop-down for units back into miles.

plain magnetBOT
#

@bold grotto I converted your message into a file since it's above 15 lines :+1:

jolly wigeon
#

I would like to create a template sensor that states the number of open windows and doors in a group I have created with the entity id of binary_sensor.all_windows_and_doors. How would I create this count sensor so I can use it in my dashboard as a quick way to show how many open doors and or windows there are?

marble jackal
#

{{ state_attr('binary_sensor.all_windows_and_doors', 'entity_id') | select('is_state', 'on') | list | count }}

#

This would be an option

chilly furnace
mighty ledge
chilly furnace
# mighty ledge It most likely doesn’t have a known unit of measurement

It does indeed, it's set to kilometers and kph and seems to be formatted correctly. The big difference I'm seeing is that my helper functions I've defined as measurement and speed type (device class?) and I suspect the integration does not do this. The primary dev for the integration is German so it's almost certainly not been an issue he's had to worry about. I'll try and submit a PR to add the device classes where appropriate and hopefully that'll fix it for everyone 🙂

thin pivot
#

Help with new weather templating

mighty ledge
chilly furnace
mighty ledge
#

if you're going to make a lib change

thin pivot
#

How do I force an update of a template sensor that triggers only once an hour?

#

Is there a service call that does that?

mighty ledge
#

homeassistant.update_entity may work

#

you're better off just adding a second trigger

lucid thicket
thin pivot
mighty ledge
#

Yes, it may not work for trigger based template entities

jolly wigeon
mighty ledge
floral shuttle
#

having various formats (markdown, attribute, template filter..) of this {% set alert_level = states('input_number.battery_alert_level')|int %} {%- set ns = namespace(items=[]) -%} {% from 'batteries.jinja' import batteries %} {%- for b in batteries().split(',') if states(b)|int< alert_level -%} {%- set ns.items = ns.items + [ {'name': states[b].name, 'perc': states[b].state|int(-1)} ] -%} {% else %} Alles batterijen boven {{alert_level}}% {%- endfor -%} {% for i in ns.items|sort(attribute='perc') %} {{i.name}}: {{i.perc}}% {%- if not loop.last %}, {% endif -%} {% endfor %}