Data in one MQTT topic to multiple sensors

Dear all,
I’m receiving data in an MQTT sensor from various (custom) sensors I built. A sample data is something like this:

{"Measurement":{"Ordinal":4156,"Hostname":13968968,"SensorID":"11:11:11:11:11:11:11:11","Failures":8,"Value":43.4375,"Battery":3.563555956}}

From another sensor I would receive a similar one, but, of course, the SensorID field would be different, i.e. “22:22:22:22:22:22:22:22”.

My question is this: What is the best way to separate them so they will become separate sensors in HA?

so far I experimented with something like this:

- name: Solar heater
  state_topic: "viktak/spiti/esp-now-bridge/tele"
  value_template: >
      {%- if value_json["Measurement"]["SensorID"]=="11:11:11:11:11:11:11:11" %}
      {{ value_json["Measurement"]["Value"]  }}
      {% endif -%}

The problem is, that while when a new value arrives from SensorID “11:11:11:11:11:11:11:11”, it gets displayed correctly, when another one sends its data, this value template evaluates to an empty string, erasing the value from my dashboard.

Is there a way to separate data from different SensorIDs into different mqtt sensors?

Thanks for any pointers in advance!

I figured, that this will fix the problem:

      {% else %}
      {{ states("sensor.solar_heater") }}

However, I’m sure there is a better way of doing it…

The issue here is that the data published to viktak/spiti/esp-now-bridge/tele
is multiplexed. In other words, one topic is used to transmit data for multiple devices.

The simplest technique is to demultiplex the data. Create an automation that receives the data and re-publishes it to separate topics, one topic per device. Now each device can listen to its own dedicated topic and receive data that is exclusively meant for it.

I have offered this solution to several other users, here’s one example that demonstrates the concept:

Here’s a more complex example:

For your application, the automation would look like this:

alias: esp now bridge demultiplexer
trigger:
  - platform: mqtt
    topic: viktak/spiti/esp-now-bridge/tele
condition: []
action:
  - action: mqtt.publish
    data:
      topic: "espnowbridge/{{ trigger.payload_json.Measurement.SensorID | slugify }}"
      payload: "{{ trigger.payload_json.Measurement['Value'] }}"
      retain: true

Then your sensor’s configuration would simply be this:

- name: Solar heater
  state_topic: "espnowbridge/11_11_11_11_11_11_11_11"

Yepp, thanks, I got it, it makes sense. I just didn’t think of it…

Appreciate the quick reply!!! Thanks again!!!

1 Like