Need help with loop in script

I have a script, that checks for a number of entities, whether a binary sensor (low_bat) is on or off and sends an email in case of ‚on‘.
However, I am looking for a way, to make this a little bit mor ‚smooth‘. Is there a way to alternate over the entities in kind of a loop and send an email only for those where the condition is met? (Instead of having 12 different ‚when_then actions‘; just one)


alias: Batterieladung FBH Raumthermostate prüfen und email senden
sequence:
  - if:
      - condition: state
        entity_id: binary_sensor.ankleide_hk_7_io_device_3_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Ankleide ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.hk_8_bad_io_device_2_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Badezimmer oben ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.badunten_hk8_io_device_6_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Gästebad ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.buero_hk_1a_b_io_device_1_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Büro ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.hwr_hk7_io_device_5_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Flur unten ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.gast_hk1_io_device_1_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Gästezimmer ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.kinderbad_hk_3_io_device_6_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Kinderbad ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.sven_hk_2a_b_io_device_4_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im  Raumthermostate FBH Kinderzimmer ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.kueche_hk5_io_device_3_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Küche ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.sz_hk_5a_io_device_7_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im  Raumthermostate FBH Schlafzimmer  ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.windfang_hk6_io_device_2_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Windfang ist schwach
          title: "Meldung von Homeassistant "
  - if:
      - condition: state
        entity_id: binary_sensor.wohnzimmer_hk2_io_device_7_battery
        state: "on"
    then:
      - service: notify.email
        data:
          message: Batterie im Raumthermostate FBH Wohnzimmer ist schwach
          title: "Meldung von Homeassistant "
mode: single
icon: mdi:battery-10

I would personnaly go with an automation rather than a script:

alias: New Automation
description: ""
mode: single
trigger:
  - platform: state
    entity_id:
      - binary_sensor.ankleide_hk_7_io_device_3_battery
      - binary_sensor.hk_8_bad_io_device_2_battery
      - binary_sensor.badunten_hk8_io_device_6_battery
      - binary_sensor.buero_hk_1a_b_io_device_1_battery
      - binary_sensor.hwr_hk7_io_device_5_battery
    to: "on"
condition: []
action:
  - service: notify.email
    data:
      message: Batterie im {{ state_attr(trigger.event.data.entity_id, 'friendly_name') }} ist schwach
      title: "Meldung von Homeassistant "

So, rather than looping through the sensors we simply wait for the state of a battery to go on. When this happens the automation will be triggered. The automation will then run the action which picks up the name of triggering battery dynamically.

I haven’t fully tested this as I don’t have the notify.email service.

Well, yes, that’s what I started with, :wink:
Downside: it only sends 1 notification once the status of an entity changes.
As I am getting older, I tend to for forget to take immediate action :wink:
Therefore I would prefer to have the script checking the status every day (triggered by a time automation) and send out an email until the battery is changed.

Furthermore, I am still learning and just would love to know how to solve this with a script, as I can imagine that I will have other scenarios where I can use it.

Anyway, that’s for your reply

I did not look at all the details but note that there is a battery card solution which is really flexible

maxwroc/battery-state-card: Battery state card for Home Assistant (github.com)

There are multiple ways you can use a templates to create an ad hoc list of the entities that are ‘on’.

Template based off the assigned Area
alias: Batterieladung FBH Raumthermostate prüfen und email senden
sequence:
  - variables:
      low: >
        {{ expand('binary_sensor.badunten_hk8_io_device_6_battery',
        'binary_sensor.buero_hk_1a_b_io_device_1_battery',
        'binary_sensor.hwr_hk7_io_device_5_battery',
        'binary_sensor.gast_hk1_io_device_1_battery',
        'binary_sensor.kinderbad_hk_3_io_device_6_battery',
        'binary_sensor.sven_hk_2a_b_io_device_4_battery',
        'binary_sensor.kueche_hk5_io_device_3_battery',
        'binary_sensor.sz_hk_5a_io_device_7_battery',
        'binary_sensor.windfang_hk6_io_device_2_battery',
        'binary_sensor.wohnzimmer_hk2_io_device_7_battery',
        'binary_sensor.hk_8_bad_io_device_2_battery', 
        'binary_sensor.ankleide_hk_7_io_device_3_battery') 
        | selectattr('state','eq','on') | map(attribute='entity_id') | map('area_name') 
        | reject('eq', none) | list }}
  - service: notify.email
    data:
      title: "Meldung von Homeassistant "
      message: >
        Räume mit schwachen Batterien im Raum Thermostate FBH: {{ low }}
mode: single
icon: mdi:battery-10

Or:

Template based off the entity id
alias: Batterieladung FBH Raumthermostate prüfen und email senden
sequence:
  - variables:
      entities: >
        {{ expand('binary_sensor.badunten_hk8_io_device_6_battery',
        'binary_sensor.buero_hk_1a_b_io_device_1_battery',
        'binary_sensor.hwr_hk7_io_device_5_battery',
        'binary_sensor.gast_hk1_io_device_1_battery',
        'binary_sensor.kinderbad_hk_3_io_device_6_battery',
        'binary_sensor.sven_hk_2a_b_io_device_4_battery',
        'binary_sensor.kueche_hk5_io_device_3_battery',
        'binary_sensor.sz_hk_5a_io_device_7_battery',
        'binary_sensor.windfang_hk6_io_device_2_battery',
        'binary_sensor.wohnzimmer_hk2_io_device_7_battery',
        'binary_sensor.hk_8_bad_io_device_2_battery', 
        'binary_sensor.ankleide_hk_7_io_device_3_battery') 
        | selectattr('state','eq','on') | map(attribute='entity_id')  | list }}
      low: >
        {% for e in entities %}
        {{- (e.rsplit('.')[1]).rsplit('_')[0] | title }}
        {% endfor %}
  - service: notify.email
    data:
      title: "Meldung von Homeassistant "
      message: >
        Räume mit schwachen Batterien im Raum Thermostate FBH: {{ low }}
mode: single
icon: mdi:battery-10

Wow, that looks interesting. Will try it out and play a little bit around to get a better understanding.
But it definitely looks like the solution
Thanks

Well, I tried it, unfortunately it didn’t work as expected. (Both versions)
As the batteries are currently ok, I changed on to off in the line
```

| selectattr(‘state’,‘eq’,‘on’) | map(attribute=‘entity_id’) | list }}

```
off is the current state of all those entities
But all I got was an email like this:

```

Räume mit schwachen Batterien im Raum Thermostate FBH: []

```
So I assume, either something in the script is wrong or I didn’t understand how it works and changing on to off does not the trick (chances are good it’s me lacking understanding :wink: )
Any idea?

No idea why, but when I just run the script again, everything works fine
So, thanks

Although not my question, the card looks good and I will implement that to my Dashboard as well, thanks for the hint

May I ask an additional question?
Is there an easy way to return the friendly names of the entities?

Sure, you just change the attribute in the map() filter to “name”. That also removes the need for the second variable to format the output.

sequence:
  - variables:
      entities: >
        {{ expand('binary_sensor.badunten_hk8_io_device_6_battery',
        'binary_sensor.buero_hk_1a_b_io_device_1_battery',
        'binary_sensor.hwr_hk7_io_device_5_battery',
        'binary_sensor.gast_hk1_io_device_1_battery',
        'binary_sensor.kinderbad_hk_3_io_device_6_battery',
        'binary_sensor.sven_hk_2a_b_io_device_4_battery',
        'binary_sensor.kueche_hk5_io_device_3_battery',
        'binary_sensor.sz_hk_5a_io_device_7_battery',
        'binary_sensor.windfang_hk6_io_device_2_battery',
        'binary_sensor.wohnzimmer_hk2_io_device_7_battery',
        'binary_sensor.hk_8_bad_io_device_2_battery', 
        'binary_sensor.ankleide_hk_7_io_device_3_battery') 
        | selectattr('state','eq','on') | map(attribute='name')  | list | join(', ') }}
  - service: notify.email
    data:
      title: "Meldung von Homeassistant "
      message: >
        Räume mit schwachen Batterien im Raum Thermostate FBH: {{ entities }}
mode: single
icon: mdi

Thanks, I tried ‚friendly_name‘ which doesn’t work :wink:
Your scripts were extremely helpful, I learned a lot

Well, here I am again.
Script worked out good so far this morning, when started by the timed automation.
However, how can I define a ‚when-then‘ condition that prevents the email from being send, when all batteries are ok (off)?
I assume that there must be a template in the When part, that somehow looks at the variable {{entities}} but how to define that?

You can use a template condition to check if the list of entities has anything in it…

sequence:
  - variables:
      entities: >
        {{ expand('binary_sensor.badunten_hk8_io_device_6_battery',
        'binary_sensor.buero_hk_1a_b_io_device_1_battery',
        'binary_sensor.hwr_hk7_io_device_5_battery',
        'binary_sensor.gast_hk1_io_device_1_battery',
        'binary_sensor.kinderbad_hk_3_io_device_6_battery',
        'binary_sensor.sven_hk_2a_b_io_device_4_battery',
        'binary_sensor.kueche_hk5_io_device_3_battery',
        'binary_sensor.sz_hk_5a_io_device_7_battery',
        'binary_sensor.windfang_hk6_io_device_2_battery',
        'binary_sensor.wohnzimmer_hk2_io_device_7_battery',
        'binary_sensor.hk_8_bad_io_device_2_battery', 
        'binary_sensor.ankleide_hk_7_io_device_3_battery') 
        | selectattr('state','eq','on') | map(attribute='name')  | list }}
  - condition: template
    value_template: "{{ entitites | count > 0 }}" 
  - service: notify.email
    data:
      title: "Meldung von Homeassistant "
      message: >
        Räume mit schwachen Batterien im Raum Thermostate FBH: {{ entities | join(', ') }}
mode: single
icon: mdi

Thanks, I tried many different syntaxes, ‚count‘ I didn’t find.
It’s really hard to Google the correct syntax, if you don’t really know what to look for.
But I keep learning

I agree completely. Unfortunately, there isn’t a complete explainer for using Jinja templates in Home Assistant. Two good sources are the two listed on the Template tool page. But, both of those assume some level of prior knowledge…

Home Assistant’s templating documentation does not include or explain many of the basic functions and/or methods that are available.

The PalletsProjects Jinja documentation covers some of the basics, but, especially for new users, much of the info is hard figure out how to apply in Home Assistant. And it doesn’t cover the many python methods and Home Assistant specific methods that you can use when templating in Home Assistant.

Another pretty good source is skalavala’s Jinja code for Ninjas which has some explanations, alot of examples. I should note that some of the methods used are outdated, but most should still work.

Yep, that may be one of the problems :wink:
Although I agree, that HA is not so good in explaining coding/syntax, the upside is that HA provides more and more ‚programming‘ via UI and (most important) there is a good, big and great community which gives a lot of good examples and help.
I am not a coding persons anyway, but quite good in copy/paste and trial and error :wink:
And frankly I am astonished how much I have achieved to automate via HA within a couple of month I use it.
Basically mich easier than with NodeRed/FHEM/Homematic WebUI/ what I used before.
Mainly because I be got a lot of fas an, competent help.
Thanks to you and all others in the community