Sensor icon templates

I’m trying to streamline my sensor config, and was wondering if there’s a way to streamline how I process the icon_templates for my MQTT sensors.

Right now, to get battery information displayed with the icon I want, each (eight total) sensor looks like this:

- platform: mqtt
  state_topic: "smartthings/Motion Hallway/battery"
  name: battery motion hallway
  icon_template: >
    {% if states('sensor.battery_motion_hallway') | float >= 95 %}
      mdi:battery
    {% elif states('sensor.battery_motion_hallway') | float >= 85 %}
      mdi:battery-90
    {% elif states('sensor.battery_motion_hallway') | float >= 75 %}
      mdi:battery-80
    {% elif states('sensor.battery_motion_hallway') | float >= 65 %}
      mdi:battery-70
    {% elif states('sensor.battery_motion_hallway') | float >= 55 %}
      mdi:battery-60
    {% elif states('sensor.battery_motion_hallway') | float >= 45 %}
      mdi:battery-50
    {% elif states('sensor.battery_motion_hallway') | float >= 35 %}
      mdi:battery-40
    {% elif states('sensor.battery_motion_hallway') | float >= 25 %}
      mdi:battery-30
    {% else %}
      mdi:battery-alert
    {% endif %}

As you can see, it just seems needlessly long, and I can’t figure out a way to streamline it so I don’t have to fill the icon_template data for each sensor.

You could do this, works for me…

  icon_template: >-
    {% set battery_level = states('sensor.battery_motion_hallway')|int('unknown') %}
    {% set battery_round = (battery_level|int / 10)|int * 10 %}
    {% if battery_level == 'unknown' %}
      mdi:battery-unknown
    {% else %}
      {% if battery_round >= 100 %}
        mdi:battery
      {% elif battery_round > 0 %}
        mdi:battery-{{ battery_round }}
      {% else %}
        mdi:battery-alert
      {% endif %}
    {% endif %}

EDIT:
You should probably wrap it with this, so that Home Assistant only does this if the state exists.

  {% if states.sensor.battery_motion_hallway %}
    above code
  {% endif %}

Cheers!

1 Like

As of 0.69, you can use device_class to accomplish the same thing. Like this…

- platform: mqtt
  state_topic: "smartthings/Motion Hallway/battery"
  name: battery motion hallway
  device_class: "battery"
1 Like