Dynamic unique_id for template-defined sensor

I’m trying to monitor the battery level of various Bluetooth devices connected to my Android phone.

The Home Assistant app on my phone is sending an android.intent_received event to my HA server any time a device battery level changes. I need to convert this event into a battery level sensor for each device, so I’m using the following template:

template:
  - trigger:
      platform: event
      event_type: "android.intent_received"
      event_data:
        intent: "android.bluetooth.device.action.BATTERY_LEVEL_CHANGED"
    sensor:
      - unique_id: "{{ trigger.event.data['device_id'] }}"
        unit_of_measurement: "%"
        state: "{{ trigger.event.data['android.bluetooth.device.extra.BATTERY_LEVEL']}}"

This works except for the sensor unique_id, which shows up in HA as the literal string sensor.template_trigger_event_data_device_id. I was expecting it to be something like sensor.template_abc123, where abc123 is the device ID.

Is it possible to dynamically define the unique_id based on variables in the template itself? If not, is there a better way to capture the battery level of multiple devices without duplicating and hardcoding the device ID in multiple templates?

You cannot template a unique_id, and this will not create unique sensors for each event like you’re assuming it will.

If you want this to work, you should look into MQTT, MQTT Discovery, and Posting to an MQTT topic via automations.

Thanks, it might be worth noting in the Template integration docs that unique_id cannot be templated.

MQTT looks powerful but I don’t have time to dive into that can of worms right now. I ended up just hardcoding a template/sensor for each device.

One annoying aspect is that Android sends an event with battery level “-1” when a device is disconnected, and I couldn’t see any way to filter this out via the Home Assistant template. There’s no way I could see to have a conditional trigger (i.e. battery level greater than 0) or to otherwise simply abort if the battery level is invalid.