Device_class: battery in template sensors

If I create a template sensor to represent a battery give it the device class of battery then it automatically gets the right icon to represent the charge level. Great!

I notice battery sensors provided by integrations do the same thing but have different icons depending on whether they’re charging (and my phone even gets different icons when wireless charging!) which is very neat.

Can I get the same effect in my template sensor without having to code for all 20+ different icon states?

if it’s a sensor w/ device_class battery and your UOM is %, then it should handle all of that already.

the charging/notcharging stuff would need to be handled by a template, which ultimately means you’d have to handle all the other cases as well.

You could, of course, use a template to reduce the number of cases you need. Something like:

icon: >
  {% set pct = states('sensor.battery_level')|int(0)//10~"0" %}
  {% if bool(states('binary_sensor.battery_charging')) %}
    mdi:battery-charging-{{ "outline" if pct == "00" else pct }}
  {% else %}
    mdi:battery{{ "-outline" if pct == "00" else "" if pct == "100" else "-"~pct }}
  {% endif %}

Should deal with the slightly inconsistent set of icon names…

if it’s a sensor w/ device_class battery and your UOM is %, then it should handle all of that already.

Indeed it does that brilliantly, I was rather pleased to find.

the charging/notcharging stuff would need to be handled by a template, which ultimately means you’d have to handle all the other cases as well.

Yes I was hoping it would be as simple as setting the device_class to something like “battery_charging” or “battery_wireless”.

Many thanks, will give that a go shortly.