Template sensor for last battery charge when device unavailable

Hi all

I’m sure I’m going about this in the wrong way, but for the life of me I can’t figure out the correct way so thought I’d ask for guidance. I want to reflect (in a dashboard) the last known battery charge level for a device that reports ‘unavailable’ when powered off.

It would seem that the post here (Use last value instead of unknown - #19 by 123) describes almost exactly what I’m looking for. I’ve tried adding and modifying this for my device in multiple ways and cannot get it working.

I first thought I could simply add it from Developer Tools > Template, but when adding the code below I get the result ‘trigger is undefined’:

template:
  - trigger:
      - platform: state
        entity_id: sensor.unnamed_room_battery
        not_to:
          - 'unknown'
          - 'unavailable'
    sensor:
      - name: sonos_move_last_battery
        state: '{{ trigger.to_state.state }}'
        device_class: battery
        unit_of_measurement: '%'

Failing that, looked at the reference for templates and added a new template via Settings > helpers and pasted the following into the state template:

- trigger:
      - platform: state
        entity_id: sensor.unnamed_room_battery
        not_to:
          - 'unknown'
          - 'unavailable'

This results in the following in the preview:

Sensor None has device class ‘battery’, state class ‘measurement’ unit ‘%’ and suggested precision ‘None’ thus indicating it has a numeric value; however, it has the non-numeric value: ‘- trigger: - platform: state entity_id: sensor.unnamed_room_battery not_to: - ‘unknown’ - ‘unavailable’’ (<class ‘str’>)

Any obvious pointers on what I’m doing wrong?

Many thanks for any help.

The Template Editor is for testing templates, not for testing the configuration of an entire Template Sensor or Trigger-based Template Sensor. It only processes Jinja2 templates, not YAML.

Your first example is fine, but you can’t test {{trigger.to_state.state}} in the Template Editor because the trigger object doesn’t exist until the State Trigger is triggered … and that cannot happen within the Template Editor.

I suggest you add your Trigger-based Template Sensor to the template: section of the configuration.yaml file, or whatever file you’re using for template entities, then restart Home Assistant (if it’s your first Template entity, otherwise you can use Developer Tools → YAML → Reload Template Entities).

Your second example produced an error because a Template Sensor helper (the kind you create via the UI) expects you to supply it with a template only. You gave it a YAML configuration for a trigger.

In addition, a Template Sensor helper doesn’t support the creation of Trigger-based Template Sensors.

Thank you! I’m learning, so appreciate the patience. :slight_smile:

1 Like

No worries, they’re common mistakes.