Howto create battery alert without creating a template for every device

Hi there!
Thanks for this post, it looks great! I am not able to get the right value for the batteries of my Xiaomi PIR and door sensors. I am using zigbee2mqtt and it always display 100% which should be around 60% (last checked with the Xiaomi Mi Home app). Here is what I can read in the zigbee2mqtt log. Any clue on what to do? Is it related to retained messages?

zigbee2mqtt:info  2020-03-30 11:03:53: MQTT publish: topic 'zigbee2mqtt/0x00158d0002b93ec8', payload '{"battery":100,"voltage":3005,"illuminance":265,"illuminance_lux":265,"linkquality":81,"occupancy":false}'
zigbee2mqtt:info  2020-03-30 11:21:11: MQTT publish: topic 'zigbee2mqtt/0x00158d00034f91bb', payload '{"battery":100,"voltage":3005,"linkquality":34,"contact":true}'

Hi,
I also tried to comment those code lines but it still doesn’t work. all my battery sensors disappeared and new ones are not getting created.

I will really appreciate it if someone shares his working code.

Thanks in advance.

this works for me, HA 0.106.6

################################################################
## Battery Alert Package by NotoriousBDG
##
## Source: https://raw.githubusercontent.com/notoriousbdg/Home-AssistantConfig/master/packages/battery_alert.yaml
################################################################

################################################################
## Changelog
################################################################
##
## 1.0.0 (2018-02-14)
##   Added
##   - Added version number to enable better tracking
##
## 1.0.1 (2018-02-15)
##   Added
##   - Added battery_sensor_creation_disabled attibute to skip
##     creating a battery sensor even when an battery attribute
##     exists.
##
## 1.0.2 (2018-04-06)
##   Added
##   - Added battery icon to sensors.
##
## 1.0.3 (2018-05-10)
##   Changed
##   - Change device_class to battery and remove icon, which
##     allows dynamic icons in 0.69.
##
## 1.0.4 (2018-05-11)
##   Changed
##   - Fixed condition battery_sensor_creation_disabled condition
##   Added
##   - Documented a jinja template that can be use to assist
##     with creating a group containing all battery sensors.
##
## 1.0.5 (2018-05-14)
##   Changed
##   - Changed formatting of notifications to improve readability
##   - Nofity via Slack immediately when thresholds are modified
##   Added
##   - Entities with device_class of battery no longer need
##     battery in their friendly name to be monitored
##   - Don't create a battery sensor from an entity if
##     device_class is battery
##
## 1.0.6 (2018-05-14)
##   Changed
##   - Added object_id to notifications
##   - Updated Battery Status group jinja code to check for
##     battery device_class
##
## 1.0.7 (2018-05-16)
##   Added
##   - Added unique_id to disambiguate sensors with duplicate
##     names
##   - Added source info to mqtt config topic
##   - Consider friendly names and entity_ids that end with _bat
##     as a battery sensor (needed for rflink battery sensors)
##   - Consider entities with icon of battery, battery-alert, or
##     battery-unknown as a battery sensor regardles of its name
##   - Consider entity_ids containing battery as a battery sensor
##   Changed
##   - Reduce code duplication using yaml anchors and references
##   - Changed MQTT topic to be based on entity_id
##   - Improve method of filtering non-battery devices that have
##     battery in their name. Detection is now based on icon
##     rather than keywords.
##
## 1.0.8 (2018-06-01)
##   Added
##   - Add support for defining battery_template attibute to
##     allow manipulation of value of battery sensor
##   - Support battery attributes that contain strings
##   Removed
##   - Cleaned up notifications by removing object id
##
## 1.0.9 (2018-06-08)
##   Added
##   - Automatically create Battery Status group containing all
##     discovered batteries
##   Removed
##   - Removed sample jinja to create battery status group yaml
##
## 1.0.10 (2018-06-08)
##   Added
##   - Moved group.update_battery_status_group_members to Battery
##     Alert group
##
## 1.1.0 (2018-08-09)
##   Added
##   - Added Batteries view
##   - Added Telegram notification automation
##   - Added Pushover notification automation
##   - Added attributes to battery entities created via mqtt:
##     entity_id, attribute, mqtt_config_topic, and mqtt_state_topic
##   Changed
##   - Simplified trigger for update_battery_status_group_members
##     automation
##   - Refactored conditions on automations to rely on
##     group.battery_status members
##   Breaking Changes
##   - The attribute additions requires restarting Home Assistant
##     after the first state change or clearing retained MQTT topics
##
## 1.1.1 (2018-08-11)
##   Added
##   - Added input text box named `MQTT Topic to Clear`, which can be used
##     to clear MQTT topics with retained messages
##   - Set initial_state to on for all automations to ensure they are enabled
##     on startup
##   Changed
##   - Consider entities with battery in their entity_id or friendly_name a
##     battery sensor if neither an icon nor a device class is defined
##   - Consolidated the battery_sensor_from_* automations into a single
##     automation
##
## 1.1.2 (2018-08-23)
##   Fixed
##   - Fixed issue where non-battery sensors with Battery in their name are
##     added to group.battery_status
##
## 1.1.3 (2018-11-17)
##   Fixed
##   - Filter out trigger=none from automation.battery_sensor_from_attributes
##   - Don't convert float to int in mqtt payload
##
## 1.1.4 (2018-11-17)
##   Fixed
##   - Ignore entities with null states
##   - Fix issue causing TypeError: object of type 'NoneType' has no len()
##
## 1.1.5 (2018-11-18)
##   Added
##   - Add support for defining battery_template_string attibute to
##     support templates that return strings
##
## 1.1.6 (2018-11-21)
##   Removed
##   - Removed attribute named attribute on the sensors
##   Added
##   - Added attribute to the MQTT sensors with the same name and value as the
##     original entity
##
## 1.2.0 (2019-01-20)
##   Breaking Changes
##   - Setting up notifications have changed.  Enter the name of the notifier in the `Notifier Name` input text box
##     and select the notifier format using the `Notifier Format` input select.
##   Changed
##   - Migrate attributes from json_attributes to json_attributes_topic
##   - Remove % unit for battery level attributes that contain strings
##   - Replaced mqtt_config_topic and mqtt_state_topic attributes with delete_battery_sensor attribute
##     to make deleting battery sensors easier
##   - Renamed MQTT Topic to Clear input text box to Delete a Battery Sensor
##   Added
##   - Battery attributes containing strings now have dynamic icons that change with battery status
##   - Added Notifier Name input text box to store name of the notifier to use for notifications (defaults to notify.notify)
##   - Added Notifier Format input select to allow selection of notification format.  Options are Default and Slack.
##   - Added input_boolean.low_batteries to help with automations.  True means there are low batteries.
##
## 1.2.1 (2019-01-23)
##   Changed
##   - Fixed Time platform to time_pattern platform
##
## 1.2.2 (2019-02-09)
##   Added
##   - Alert if battery state is unavailable
##   Removed
##   - Removed startup trigger from automation.update_battery_status_group_members
##   Changed
##   - Default to notify.notify if input_text.notifier_name doesn't contain "notify."
##
## 1.2.3 (2019-03-02)
##   Changed
##   - Handle null attributes gracefully
##
## 1.2.4 (2019-03-02)
##   Added
##   - Added support for battery_critical attributes by @Djebouh
################################################################
################################################################

################################################################
## Install Instructions
################################################################
##
##  1. Enable MQTT using your preferred MQTT broker
##     https://home-assistant.io/components/mqtt/
##
##  2. Enable MQTT Discovery by adding `discovery: true` and
##     `discovery_prefix: homeassistant` under the `mqtt:` section
##     of your configuration.yaml
##
##     mqtt:
##       discovery: true
##       discovery_prefix: homeassistant
##
##  3. Save this file as CONFIGDIR/packages/battery_alert.yaml
##
##  4. Add `packages: !include_dir_named packages` under the
##     `homeassistant:` section of your configuration.yaml
##
##     homeassistant:
##       packages: !include_dir_named packages
##
##  5. Restart Home Assistant
##
##  6. Adjust Min Alert Threshold slider to the minimum battery
##     level to alert on.  Note: the input slider requires the
##     recorder component to keep it's state through restarts.
##     If recorder is not enabled, the threshold can be set by
##     un-remarking `initial` and setting the preferred default.
##
##  7. Adjust Max Alert Threshold slider to the maximum battery
##     level to alert on.  Note: the input slider requires the
##     recorder component to keep it's state through restarts.
##     If recorder is not enabled, the threshold can be set by
##     un-remarking `initial` and setting the preferred default.
##
##  8. Setup notifications by entering the notifier name in the `Notifier Name` input text box.
##     E.g. `notify.slack`.  If no value is entered, it defaults to `notify.notify`.
##
##  9. Set the notifier format by selecting either `Default` or `Slack.  Note: most notifiers
##     are compatible with the `Default` format.
##
## 10. To disable alerts for a specific entity, use customize to
##     set `battery_alert_disabled` to `true`
##
##     homeassistant:
##       customize:
##         sensor.sensor_name_to_ignore_battery:
##           battery_alert_disabled: true
##
## 11. To disable creating a sensor from battery attributes for a specific entity, use customize to
##     set `battery_sensor_creation_disabled` to `true`
##
##     homeassistant:
##       customize:
##         sensor.sensor_with_battery_attibute:
##           battery_sensor_creation_disabled: true
##
## 12. If a battery attribute requires a template to convert it into a usable percent, use customize
##     to add `battery_template` with the necessary template. The template result must be a number
##     that represents a percentage.
##
##     This example will create a battery sensor with the value of battery_level * 2
##
##     homeassistant:
##       customize:
##         sensor.sensor_with_battery_attibute_template:
##           battery_template: "{{ value_json.value | int * 2 }}"
##
## 13. If a battery attribute requires a template to convert it into a string, use customize to add
##     `battery_template_string` with the necessary template. The template result must be a string.
##     For example, "Low" will trigger low battery notification).
##
##     This example will create a battery sensor that contains "Low" if battery_level
##     is less than 2
##
##     homeassistant:
##       customize:
##         sensor.sensor_with_battery_attibute_template:
##           battery_template_string: >-
##             {%- if value_json.value < 2 -%}
##             Low
##             {%- else -%}
##             Full
##             {%- endif -%}
################################################################

################################################
## Customize
################################################
homeassistant:
  customize:
    ################################################
    ## Node Anchors
    ################################################
    package.node_anchors:
      customize: &customize
        package: 'battery_alert'

    ################################################
    ## Group
    ################################################
    group.battery_view:
      <<: *customize
      friendly_name: "Batteries"
      icon: mdi:battery-alert

    group.battery_alert:
      <<: *customize
      friendly_name: "Battery Alert"
      icon: mdi:steam
#      control: hidden

    group.battery_status:
      <<: *customize
      friendly_name: "Battery Status"
      icon: mdi:battery-charging
#      control: hidden

    ################################################
    ## Automation
    ################################################
    automation.battery_persistent_notification:
      <<: *customize
      friendly_name: "Battery Persistent Notification"
      icon: mdi:comment-alert-outline

    automation.battery_persistent_notification_clear:
      <<: *customize
      friendly_name: "Battery Persistent Notification Clear"
      icon: mdi:comment-remove-outline

    automation.battery_notification_default:
      <<: *customize
      friendly_name: "Battery Notification Default Format"
      icon: mdi:comment-alert-outline

    automation.battery_notification_slack:
      <<: *customize
      friendly_name: "Battery Notification Slack Format"
      icon: mdi:comment-alert-outline

    automation.battery_sensor_from_attributes:
      <<: *customize
      friendly_name: "Create Battery Sensor from Attributes"
      icon: mdi:battery-charging-wireless-outline

    automation.update_battery_status_group_members:
      <<: *customize
      friendly_name: "Update Battery Status Group Members"
      icon: mdi:group

    automation.delete_battery_sensor:
      <<: *customize
      friendly_name: "Delete a Battery Sensor"
      icon: mdi:server-remove

################################################
## Group
################################################
group:
  battery_view:
#    view: yes
    entities:
      - group.battery_status
      - group.battery_alert

  battery_alert:
#    control: hidden
    entities:
      - input_boolean.low_batteries
      - input_number.battery_alert_threshold_min
      - input_number.battery_alert_threshold_max
      - input_text.delete_battery_sensor
      - input_text.notifier_name
      - input_select.notifier_format
      - automation.battery_persistent_notification
      - automation.battery_persistent_notification_clear
      - automation.battery_notification_default
      - automation.battery_notification_slack
      - automation.battery_sensor_from_attributes
      - automation.update_battery_status_group_members
      - automation.delete_battery_sensor

################################################
## Input Boolean
################################################
input_boolean:
  low_batteries:
    name: Low Batteries
    icon: mdi:battery-alert

################################################
## Input Number
################################################
input_number:
  battery_alert_threshold_max:
    name: "Max Alert Threshold"
    icon: mdi:arrow-collapse-up
    mode: slider
    min: -1
    max: 100
    # initial: 40

  battery_alert_threshold_min:
    name: "Min Alert Threshold"
    icon: mdi:arrow-collapse-down
    mode: slider
    min: -1
    max: 100
    # initial: -1

################################################
## Input Select
################################################
input_select:
  notifier_format:
    name: Notifier Format
    options:
     - Default
     - Slack
    icon: mdi:comment-question-outline

################################################
## Input Text
################################################
input_text:
  delete_battery_sensor:
    name: Delete a Battery Sensor
    mode: text
    initial: ''

  notifier_name:
    name: Notifier Name
    mode: text

################################################
## Automation
################################################
automation:
- alias: battery_persistent_notification
  initial_state: 'on'
  trigger:
    - platform: time_pattern
      minutes: '/15'
      seconds: 00
    - platform: state
      entity_id:
        - input_number.battery_alert_threshold_min
        - input_number.battery_alert_threshold_max
  action:
    - condition: template
      value_template: &low_battery_check >
        {% macro battery_level() %}
        {% for entity_id in states.group.battery_status.attributes.entity_id if (
          not is_state_attr(entity_id, 'battery_alert_disabled', true)
          and states(entity_id) is not none
          and (
            (
              (
                states(entity_id) is number
                or states(entity_id) | length == states(entity_id)| int | string | length
                or states(entity_id) | length == states(entity_id)| float | string | length
              )
              and states(entity_id) | int < states.input_number.battery_alert_threshold_max.state | int
              and states(entity_id) | int > states.input_number.battery_alert_threshold_min.state | int
            )
            or states(entity_id) | lower == 'low'
            or states(entity_id) | lower == 'unknown'
            or states(entity_id) | lower == 'unavailable'
          )
        ) -%}
          {{ state_attr(entity_id, "friendly_name") }} ({{ states(entity_id) }})
        {% endfor -%}
        {% endmacro %}
        {{ battery_level() | trim != "" }}
    - service: input_boolean.turn_on
      data:
        entity_id: input_boolean.low_batteries
    - service: persistent_notification.create
      data_template:
        title: "Low Battery Levels"
        notification_id: low_battery_alert
        message: &message >
          {% macro battery_level() %}
          {% for entity_id in states.group.battery_status.attributes.entity_id if (
            not is_state_attr(entity_id, 'battery_alert_disabled', true)
            and states(entity_id) is not none
            and (
              (
                (
                  states(entity_id) is number
                  or states(entity_id) | length == states(entity_id)| int | string | length
                  or states(entity_id) | length == states(entity_id)| float | string | length
                )
                and states(entity_id) | int < states.input_number.battery_alert_threshold_max.state | int
                and states(entity_id) | int > states.input_number.battery_alert_threshold_min.state | int
              )
              or states(entity_id) | lower == 'low'
              or states(entity_id) | lower == 'unknown'
              or states(entity_id) | lower == 'unavailable'
            )
          ) -%}
            {{ state_attr(entity_id, "friendly_name") }} ({{ states(entity_id) }})
          {% endfor -%}
          {% endmacro %}
          {{ battery_level() }}

- alias: battery_persistent_notification_clear
  initial_state: 'on'
  trigger:
    - platform: time_pattern
      minutes: '/15'
      seconds: 00
    - platform: state
      entity_id:
        - input_number.battery_alert_threshold_min
        - input_number.battery_alert_threshold_max
  action:
    - condition: template
      value_template: &low_battery_clear >
        {% macro battery_level() %}
        {% for entity_id in states.group.battery_status.attributes.entity_id if (
          not is_state_attr(entity_id, 'battery_alert_disabled', true)
          and states(entity_id) is not none
          and (
            (
              (
                states(entity_id) is number
                or states(entity_id) | length == states(entity_id)| int | string | length
                or states(entity_id) | length == states(entity_id)| float | string | length
              )
              and states(entity_id) | int < states.input_number.battery_alert_threshold_max.state | int
              and states(entity_id) | int > states.input_number.battery_alert_threshold_min.state | int
            )
            or states(entity_id) | lower == 'low'
            or states(entity_id) | lower == 'unknown'
            or states(entity_id) | lower == 'unavailable'
          )
        ) -%}
          {{ state_attr(entity_id, "friendly_name") }} ({{ states(entity_id) }})
        {% endfor -%}
        {% endmacro %}
        {{ battery_level() | trim == "" }}
    - service: input_boolean.turn_off
      data:
        entity_id: input_boolean.low_batteries
    - service: persistent_notification.dismiss
      data:
        notification_id: low_battery_alert

- alias: battery_notification_default
  initial_state: 'on'
  trigger:
    - platform: time
      at: '10:00:00'
    - platform: time
      at: '18:00:00'
    - platform: state
      entity_id:
        - input_number.battery_alert_threshold_min
        - input_number.battery_alert_threshold_max
  action:
    - condition: template
      value_template: *low_battery_check
    - condition: template
      value_template: "{{ states.input_select.notifier_format.state == 'Default' }}"
    - service_template: >
        {% if "notify." in states.input_text.notifier_name.state %}
          {{ states.input_text.notifier_name.state }}
        {% else %}
          notify.notify
        {% endif %}
      data_template:
        title: "Low Battery Levels"
        message: *message

- alias: battery_notification_slack
  initial_state: 'on'
  trigger:
    - platform: time
      at: '10:00:00'
    - platform: time
      at: '18:00:00'
    - platform: state
      entity_id:
        - input_number.battery_alert_threshold_min
        - input_number.battery_alert_threshold_max
  action:
    - condition: template
      value_template: *low_battery_check
    - condition: template
      value_template: "{{ states.input_select.notifier_format.state == 'Slack' }}"
    - service_template: >
        {% if states.input_text.notifier_name.state != "" %}
          {{ states.input_text.notifier_name.state }}
        {% else %}
          notify.notify
        {% endif %}
      data_template:
        message: "Low Battery Levels"
        data:
          attachments:
          - color: '#52c0f2'
            title: "These devices have low battery levels"
            text: *message

- alias: battery_sensor_from_attributes
  initial_state: 'on'
  trigger:
    - platform: event
      event_type: state_changed
  condition:
    - condition: template
      value_template: "{{ trigger is not none }}"
    - condition: template
      value_template: "{{ trigger.event.data is not none }}"
    - condition: template
      value_template: "{{ trigger.event.data.old_state is not none }}"
    - condition: template
      value_template: "{{ trigger.event.data.new_state is not none }}"
    - condition: template
      value_template: "{{ 'battery' not in trigger.event.data.new_state.name | lower }}"
    - condition: template
      value_template: "{{ not is_state_attr(trigger.event.data.entity_id, 'device_class', 'battery') }}"
    - condition: template
      value_template: "{{ not is_state_attr(trigger.event.data.entity_id, 'battery_sensor_creation_disabled', true) }}"
    - condition: or
      conditions:
        - condition: and
          conditions:
            - condition: template
              value_template: "{{ trigger.event.data.new_state.attributes.battery_level is defined }}"
            - condition: template
              value_template: "{{ trigger.event.data.new_state.attributes.battery_level is not none }}"
        - condition: and
          conditions:
            - condition: template
              value_template: "{{ trigger.event.data.new_state.attributes.battery is defined }}"
            - condition: template
              value_template: "{{ trigger.event.data.new_state.attributes.battery is not none }}"
        - condition: and
          conditions:
            - condition: template
              value_template: "{{ trigger.event.data.new_state.attributes['Battery numeric'] is defined }}"
            - condition: template
              value_template: "{{ trigger.event.data.new_state.attributes['Battery numeric'] is not none }}"
        - condition: and
          conditions:
            - condition: template
              value_template: "{{ trigger.event.data.new_state.attributes.battery_critical is defined }}"
            - condition: template
              value_template: "{{ trigger.event.data.new_state.attributes.battery_critical is not none }}"
  action:
    - service: mqtt.publish
      data_template:
        topic: "homeassistant/sensor/{{ trigger.event.data.entity_id.split('.')[1] }}_battery/config"
        retain: true
        payload: &config_payload >-
          {
            {% if trigger.event.data.new_state.attributes.battery_level is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery_level -%}
              {%- set attribname = 'battery_level' -%}
            {%- elif trigger.event.data.new_state.attributes.battery is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery -%}
              {%- set attribname = 'battery' -%}
            {%- elif trigger.event.data.new_state.attributes['Battery numeric'] is defined -%}
              {%- set attribval = (trigger.event.data.new_state.attributes['Battery numeric'] | int + 1) * 10 -%}
              {%- set attribname = 'Battery numeric' -%}
            {% elif trigger.event.data.new_state.attributes.battery_critical is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery_critical -%}
              {%- set attribname = 'battery_critical' -%}
            {%- endif -%}
            "name": "{{ trigger.event.data.new_state.name }} Battery",
            "state_topic": "homeassistant/sensor/{{ trigger.event.data.entity_id.split('.')[1] }}_battery/state",
            {% if trigger.event.data.new_state.attributes.battery_template is defined -%}
            "value_template": "{{ trigger.event.data.new_state.attributes.battery_template }}",
            "unit_of_measurement": "%",
            "device_class": "battery",
            {% elif trigger.event.data.new_state.attributes.battery_template_string is defined -%}
            "value_template": "{{ trigger.event.data.new_state.attributes.battery_template_string }}",
            "icon": "mdi:battery",
            {% elif trigger.event.data.new_state.attributes.battery_critical is defined -%}
            "value_template": "{{ "{{" }} 'low' if value_json.value else 'full' {{ "}}" }}",
            "icon": "mdi:battery",
            {% else -%}
            "value_template": "{{ "{{" }} value_json.value | int {{ "}}" }}",
            {% if attribval | int == attribval or attribval | float == attribval or attribval | length == attribval | float | string | length or attribval | length == attribval | int | string | length -%}
            "unit_of_measurement": "%",
            "device_class": "battery",
            {%- elif attribval == "High" or attribval == "Full" -%}
            "icon": "mdi:battery",
            {%- elif attribval == "Medium" or attribval == "Med"-%}
            "icon": "mdi:battery-50",
            {%- elif attribval == "Low" -%}
            "icon": "mdi:battery-alert",
            {%- else -%}
            "icon": "mdi:battery-unknown",
            {%- endif %}
            {% endif -%}
            "unique_id": "{{ trigger.event.data.entity_id.split('.')[1] }}_battery",
            "json_attributes_topic": "homeassistant/sensor/{{ trigger.event.data.entity_id.split('.')[1] }}_battery/attributes"
          }
    - service: mqtt.publish
      data_template:
        topic: "homeassistant/sensor/{{ trigger.event.data.entity_id.split('.')[1] }}_battery/state"
        retain: true
        payload: >-
          {
            {% if trigger.event.data.new_state.attributes.battery_level is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery_level -%}
            {%- elif trigger.event.data.new_state.attributes.battery is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery -%}
            {%- elif trigger.event.data.new_state.attributes['Battery numeric'] is defined -%}
              {%- set attribval = (trigger.event.data.new_state.attributes['Battery numeric'] | int + 1) * 10 -%}
            {%- elif trigger.event.data.new_state.attributes.battery_critical is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery_critical -%}
            {%- endif -%}
            "value": {% if attribval | int == attribval -%}
              {{ attribval | int }}
            {%- elif attribval | float == attribval -%}
              {{ attribval | float }}
            {%- elif attribval | length == attribval | float | string | length -%}
              {{ attribval | float }}
            {%- elif attribval | length == attribval | int | string | length -%}
              {{ attribval | int }}
            {%- else -%}
              "{{ attribval }}"
            {%- endif %}
          }
    - service: mqtt.publish
      data_template:
        topic: "homeassistant/sensor/{{ trigger.event.data.entity_id.split('.')[1] }}_battery/attributes"
        retain: true
        payload: >-
          {
            {% if trigger.event.data.new_state.attributes.battery_level is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery_level -%}
              {%- set attribname = 'battery_level' -%}
            {%- elif trigger.event.data.new_state.attributes.battery is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery -%}
              {%- set attribname = 'battery' -%}
            {%- elif trigger.event.data.new_state.attributes['Battery numeric'] is defined -%}
              {%- set attribval = (trigger.event.data.new_state.attributes['Battery numeric'] | int + 1) * 10 -%}
              {%- set attribname = 'Battery numeric' -%}
            {%- elif trigger.event.data.new_state.attributes.battery_critical is defined -%}
              {%- set attribval = trigger.event.data.new_state.attributes.battery_critical -%}
              {%- set attribname = 'battery_critical' -%}
            {%- endif -%}
            "entity_id": "{{ trigger.event.data.entity_id }}",
            {% if attribname is defined -%}
            "{{ attribname }}": "{{ attribval }}",
            {%- endif %}
            "delete_battery_sensor": "homeassistant/sensor/{{ trigger.event.data.entity_id.split('.')[1] }}_battery"
          }

- alias: update_battery_status_group_members
  initial_state: 'on'
  trigger:
    - platform: time_pattern
      minutes: '/1'
      seconds: 00
  action:
    - service: group.set
      data_template:
        object_id: "battery_status"
        entities: >-
          {%- for item in states.sensor if (
            not is_state_attr(item.entity_id, 'hidden', true)
            and (
              is_state_attr(item.entity_id, 'device_class', 'battery')
              or 'battery' in item.attributes.icon | lower
              or (item.entity_id | lower).endswith('_bat')
              or (item.name | lower).endswith('_bat')
              ) or (
                (
                  'battery' in item.entity_id | lower
                  or 'battery' in item.name | lower
                ) and (
                  item.attributes.icon is not defined
                ) and (
                  not is_state_attr(item.entity_id, 'battery_alert_disabled', true)
                )
              )
            )
          -%}
            {{ item.entity_id }}{% if not loop.last %}, {% endif %}
          {%- endfor -%}

- alias: delete_battery_sensor
  initial_state: 'on'
  trigger:
    - platform: state
      entity_id:
        - input_text.delete_battery_sensor
  condition:
    - condition: template
      value_template: "{{ 'homeassistant/sensor/' in states.input_text.delete_battery_sensor.state }}"
  action:
    - service: mqtt.publish
      data_template:
        topic: "{{ states.input_text.delete_battery_sensor.state }}"
        retain: true
    - service: mqtt.publish
      data_template:
        topic: "{{ states.input_text.delete_battery_sensor.state }}/attributes"
        retain: true
    - service: mqtt.publish
      data_template:
        topic: "{{ states.input_text.delete_battery_sensor.state }}/state"
        retain: true
    - service: mqtt.publish
      data_template:
        topic: "{{ states.input_text.delete_battery_sensor.state }}/config"
        retain: true

and using AutoEntities custom card:

card:
  show_header_toggle: false
  title: Battery Status
  type: entities
filter:
  include:
    - entity_id: sensor.*battery*
sort:
  method: state
  numeric: true
type: 'custom:auto-entities'
1 Like

off top of head having smoko at work

zigbee2mqtt:info  2020-03-30 11:03:53: MQTT publish: topic 'zigbee2mqtt/0x00158d0002b93ec8', payload '{"battery":100,"voltage":3005,"illuminance":265,"illuminance_lux":265,"linkquality":81,"occupancy":false}'
- platform: mqtt
  name:  Battery for zigbee Item
  unit_of_measurement: "%"
  state_topic: "zigbee2mqtt/0x00158d0002b93ec8"
  value_template: "{{value_json.battery }}"

Why do you need it? the package should have take care of it by it self, no?

Regards,
Naor

tbh, I can’t remember - it used to do it, but something changed in lovelace, and so I have to use that now.

Hmm - i used to use Group-card - Howto create battery alert without creating a template for every device

Feel so frustrated.

The working code sent, is not working on my setup. not creating the sensors at all…

And also, can’t configure the custom element . whatever I do, I get the red “Custom element doesn’t exist”.

Please help. I am out of ideas where to look…

ok - assuming you are using the copy of the package I have (which I take zero credit for - I’ve just posted it here as it works for me on .106/.107).

  1. have you saved it as a package in /packages/battery.yaml (or whatever)?
  2. assuming you have done that, do you have an MQTT server installed? the package requires MQTT
  3. assuming you have that, does the package load - do you get any errors at start up?
  4. assuming no errors, do the automations show in the configurations/automations page?

for the AutoEntities custom card, you need to add this separately - https://github.com/thomasloven/lovelace-auto-entities

Hi, thanks for the reply. I had it working for a long time till the last update that killed the group attributes. That’s when it stopped working… so, ill try to answer your questions:

  1. yes I did. I edited the file currently in use and replaced the content
  2. Yes, there is a working MQTT server
  3. I don’t know if it loads… no evidence of failure in the log file
  4. I can see all the sensors and automations on the page.

Now I tried to execute one manually and went to see the logs and saw the error below. But I think it is way beyond my coding understanding…

Thanks again…
Naor

Logger: homeassistant.components.automation
Source: helpers/service.py:107
Integration: Automation (documentation, issues)
First occurred: 10:08:55 AM (1 occurrences)
Last logged: 10:08:55 AM

battery_sensor_from_attributes: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: ‘trigger’ is undefined

Traceback (most recent call last): File “/usr/src/homeassistant/homeassistant/helpers/template.py”, line 221, in async_render return compiled.render(kwargs).strip() File “/usr/local/lib/python3.7/site-packages/jinja2/environment.py”, line 1090, in render self.environment.handle_exception() File “/usr/local/lib/python3.7/site-packages/jinja2/environment.py”, line 832, in handle_exception reraise(*rewrite_traceback_stack(source=source)) File “/usr/local/lib/python3.7/site-packages/jinja2/_compat.py”, line 28, in reraise raise value.with_traceback(tb) File “”, line 1, in top-level template code File “/usr/local/lib/python3.7/site-packages/jinja2/sandbox.py”, line 407, in getattr value = getattr(obj, attribute) jinja2.exceptions.UndefinedError: ‘trigger’ is undefined During handling of the above exception, another exception occurred: Traceback (most recent call last): File “/usr/src/homeassistant/homeassistant/helpers/service.py”, line 104, in async_prepare_call_from_config template.render_complex(config[CONF_SERVICE_DATA_TEMPLATE], variables) File “/usr/src/homeassistant/homeassistant/helpers/template.py”, line 70, in render_complex return {key: render_complex(item, variables) for key, item in value.items()} File “/usr/src/homeassistant/homeassistant/helpers/template.py”, line 70, in return {key: render_complex(item, variables) for key, item in value.items()} File “/usr/src/homeassistant/homeassistant/helpers/template.py”, line 72, in render_complex return value.async_render(variables) File “/usr/src/homeassistant/homeassistant/helpers/template.py”, line 223, in async_render raise TemplateError(err) homeassistant.exceptions.TemplateError: UndefinedError: ‘trigger’ is undefined The above exception was the direct cause of the following exception: Traceback (most recent call last): File “/usr/src/homeassistant/homeassistant/helpers/script.py”, line 154, in _async_step self, f"async{cv.determine_script_action(self._action)}_step" File “/usr/src/homeassistant/homeassistant/helpers/script.py”, line 624, in _async_call_service_step *self._prep_call_service_step(), blocking=True, context=self._context File “/usr/src/homeassistant/homeassistant/helpers/script.py”, line 253, in _prep_call_service_step return async_prepare_call_from_config(self._hass, self._action, self._variables) File “/usr/src/homeassistant/homeassistant/helpers/service.py”, line 107, in async_prepare_call_from_config raise HomeAssistantError(f"Error rendering data template: {ex}") from ex homeassistant.exceptions.HomeAssistantError: Error rendering data template: UndefinedError: ‘trigger’ is undefined

After doing some digging, it looks like this error should happen because I fired the automation manually, and not triggered by an event… which means the package is loaded…

ok, so it used to work so all the prerequisites are there. And something is being loaded.

I can manually execute “Create Battery Sensor from Attributes” with no problem, so it if fails for you, something is wrong with the actual text of the package.

I’ve just done “copy to clipboard” from my post and using vi in my system paste the contents into a new file. diff shows no difference so that works for me.

How did you get the text onto your system? I suspect something has broken there.

Well, I just opened the file with BBedit and made the changes. But, I start to think it began even earlier… I switched from working with HA installed directly on my mac to HA running on a virtual box. That’s the only big change I’ve done to the system in very long time.

So, after your post, I tried to do the same… clicked the raw button in GitHub, copied the text, opened a new file with BBedit, pasted and commented the problematic lines, saved and replaced the file in my HA, and restarted the system.
ended up with the same result… when running the automation, same error shows in the log.

Just saw something weird… I had an idea to try an create a sensor via MQTT just to check if it works.

So I opened my MQTT browser and I was surprised to see that all the sensors are publish and accounted!!

So how come I can’t see them in HA??

how are you expecting to see them? Dont forget nothing shows in lovelace unless you actively add it .

I am looking for them in “developer tools/states” or inc “configuration/entities”…
but they are not there. And I am sure they are active and not ghosts because I can see recent MQTT updates on these sensors… how can it be?

do you have a group.battery_status in dev/states?

not really sure why the package is able to update mqtt, but not create the sensors. Something broken on the HA/mqtt side?

Which mqtt browser are you using to see this? I’ve been trying to get this working and can’t. Thanks.

I also made a little test… I deleted some of the sensor topics. just to make sure they are not ghosts retained from old config. and after few hours they returned with all the data.
So, i’m pretty sure its something related to those log messaged that started to appear after I replaced the package file:
update_battery_status_group_members: Error executing script. Invalid data for call_service at pos 1: Entity ID is an invalid entity id for dictionary value @ data['entities']
But nothing really found on the web that can be related or helpful .
Have you seen this kind of message before?

@plonka2000, I am using “MQTT Explorer” on my mac

https://github.com/notoriousbdg/Home-AssistantConfig/issues/16

seems the package isn’t initiating correctly.

I would suggest going into the entity editor and deleting anything related to battery, and restarting?

Well… it looks exactly like my problem! I’ll try to do a total overhaul to the package.

  1. remove the package and restart
  2. remove any entity left after that
  3. remove all the MQTT topics sensors and restart
  4. copy the package back and restart

I hope that will fix it. I will try it later on today and update.

Thanks!