Trigger mqtt message when battery goes under 20 % - my automation doesn't work anymore!

I have had this automation a few years:

- id: 'batterisjekk'
  alias: 'Batterisjekk'
  trigger:
    platform: time
    at: '10:00:00'
  action:
    service: mqtt.publish
    data_template:
      payload_template: >
        {%- for s in states.sensor  if ('battery' in s.entity_id ) and s.state|int < 20 and s.state != 'unavailable' and s.state != 'idle' %} {{s.name}}: {{ s.state }}% {%- endfor %}
      topic: eg/Batterialarm

This has told me that devices do not have more than 20 % left on the battery. Especially important for the ID Lock Z-Wave door locks. But I found out today that my door is down to 10 % without any warning! So something must have happened somewhere that has put this template out of action. When I try the template in the template section of developer’s tools I get:

ValueError: Template error: int got invalid input ‘unavailable’ when rendering template ‘{%- for s in states.sensor if (‘battery’ in s.entity_id ) and s.state|int < 50 and s.state != ‘unavailable’ and s.state != ‘idle’ %} {{s.name}}: {{ s.state }}% {%- endfor %}’ but no default was specified

Can somebody please tell me what’s going on there, it’s too cryptic for me, I’m afraid.

your entity state is unavailable. but you’re checking it for s.state|int < 20… you’re doing that before you check for s.state as unavailable.
check for your error conditions first. and/or you can do s.state | int(0) which will default it to 0 (or something else you choose) if it’s not able to cast it to int.

- id: 'batterisjekk'
  alias: 'Batterisjekk'
  trigger:
    - platform: time
      at: '10:00:00'
  action:
    - service: mqtt.publish
      data:
        topic: eg/Batterialarm
        payload_template: >
          {%- set sensors = states.sensor
            | selectattr('object_id', 'search', 'battery')
            | rejectattr('state', 'in', ['idle', 'unavailable', 'unknown'])
            | list -%}
          {%- for s in sensors if s.state | int(0) < 20 %}
            {{s.name}}: {{ s.state }}%
          {%- endfor %}

@armedad Thanks! I think I understand what I did wrong.

@123 Thanks a lot! You fixed it, works like a charm now!

1 Like