Global generic battery status and notification

I have a lot of devices which are battery powered and I’d like to be notified if a battery is running low.

Unfortunately, every device type is reporting battery status a little differently. Homematic for instance has an attribute called battery that can either be High or Low. My Z-Wave PIR sensors have an attribute called battery_level which will be a percentage from 0 to 100.

I didn’t want to create one template sensor/automation per device, so I came up with this:

configuration.yaml:

sensor:
  - platform: template
    sensors:
      low_batteries:
        friendly_name: Low batteries
        value_template: >-
          {%- for state in states if state.attributes.battery_level or state.attributes.battery -%}
            {%- set battery = state.attributes.battery_level or state.attributes.battery -%}
            {%- if battery == 'High' -%}
              {%- set battery = 100 -%}
            {%- endif -%}
            {%- if battery | int < 30 -%}
              {{state.attributes.friendly_name}}
            {%- endif -%}
          {%- endfor -%}
      battery_status:
        friendly_name: Batteries
        icon_template: '{% if states.sensor.low_batteries.state %}mdi:battery-10{% else %}mdi:battery{% endif %}'
        value_template: '{% if states.sensor.low_batteries.state %}{{states.sensor.low_batteries.state}}{% else %}OK{% endif %}'

automations.yaml:

- alias: Low battery notification
  trigger:
  - platform: state
    entity_id: sensor.low_batteries
  condition:
  - condition: template
    value_template: '{% if states.sensor.low_batteries.state %}true{% else %}false{%
      endif %}'
  action:
  - service: notify.pushover_jan 
    data_template:
      message: 'Empty batteries: {{ states.sensor.low_batteries.state }}'

I can now add my sensor.battery_status to my default view and see at a glance if all batteries are fine. If a battery runs low (below 30%), I will get a Pushover notification.

Note that I didn’t explicitly list any devices here. It will work with all devices (current and future) known to Home Assistant.

I’m not really happy with the result of sensor.low_batteries, though. It will simply concatenate all friendly_names of devices with low batteries. I’d much rather use a list here.

Happy to hear any suggestions on how to improve this! Thanks!

6 Likes