Template Sensor Min/Max

I am having to create template sensors to get battery level from my Wyze Sensors. This is great but I noticed some of them are reporting battery above 100. This doesn’t work as well with some cards like the bar graph cards.

I found I can create also a Filter sensor from my template sensors to set an upper and lower bound. This does exactly what I want but my question is there an easier way than creating a duplicate sensor using the Filter platform for sensors. Feels like a lot of extra YAML to manage when it could be just defined in the template sensors if it was an option?

EDIT: Nevermind, figured it out.

# Motion Sensors
    laundry_room_motion_battery_level:
      friendly_name: "Laundry Room Motion Battery Level"
      unit_of_measurement: '%'
      value_template: >-
        {% if state_attr('binary_sensor.motion_laundry_room', 'battery')|float > 100 %}
          100
        {% elif state_attr('binary_sensor.motion_laundry_room', 'battery')|float < 0 %}
          0
        {% else %}
          {{ state_attr('binary_sensor.motion_laundry_room', 'battery') }}
        {% endif %}

That will work. But you can simplify a bit:

# Motion Sensors
    laundry_room_motion_battery_level:
      friendly_name: "Laundry Room Motion Battery Level"
      unit_of_measurement: '%'
      value_template: >
        {{ state_attr('binary_sensor.motion_laundry_room', 'battery')|float|min(100)|max(0) }}
2 Likes

Thanks! This is much cleaner.

1 Like

What integration and card did you use for the battery level

This was Wyze sensors from the gosense mqtt integration. I then used the bar cards.