Assign dynamic sensor name from MQTT message

I’ve got several devices that send an MQTT message on the same topic
Device1,0,0,0,0
Device2,0,0,0,0

If I had a single device, I’d have in my template file:

mqtt:
  sensor:
    - name: "Device1 Sensor 1"
      state_topic: "Topic/Status"
      value_template: "{{ value.split(',')[1] | float}}"

How can I have a dynamic name; e.g.
- name: "{{value.split(',')[0}}"

Worst case, I’m going to have something along the lines of:
[health warning - very poor pseudo code to follow!]

If {{value.split(',')[0}} = Device 1 then
    - name: "Device1 Sensor 1"
      state_topic: "Topic/Status"
      value_template: "{{ value.split(',')[1] | float}}"
Else if {{value.split(',')[0}} = Device 2 then
    - name: "Device2 Sensor 1"
      state_topic: "Topic/Status"
      value_template: "{{ value.split(',')[1] | float}}"

What would be the correct way of achieving this?

Create a separate sensor for each device.

mqtt:
  sensor:
    - name: "Device1 Sensor 1"
      state_topic: "Topic/Status"
      value_template: >
        {% set x = value.split(',') %}
        {{ x[1] | float(0) if '1' in x[0] else this.state }}
    - name: "Device2 Sensor 1"
      state_topic: "Topic/Status"
      value_template: >
        {% set x = value.split(',') %}
        {{ x[1] | float(0) if '2' in x[0] else this.state }}

Brilliant - thanks for this

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.