How to capture two different sensor readings from single MQTT publish

Hi All,

I have an MQTT server on my HA that is receiving published messages from a piece of sensor hardware. Everything on the MQTT side is working fine. The problem is that the single MQTT message sometimes has 1 or 2 or even 3 separate readings from the sensor contained in one single published message.

So my question is how to grab each of those readings and have HA consider them as separate readings from the sensor.

Here’s an example of the MQTT message:

{"msg":"advData","gmac":"BC5729052ED3","obj":[{"dmac":"DD340209C6DC","level":-59,"time":"2023-12-15 8:29:13.736"},{"dmac":"DD340209C6DC","level":-57,"time":"2023-12-15 8:29:45.243"}]}

I have set up a sensor in HA like this:

mqtt:
  sensor:
    - name: "level1"
      state_topic: "test/publish/BC5729052ED3"
      value_template: "{{ value_json.obj[0].level }}"
      json_attributes_topic: "test/publish/BC5729052ED3"
      json_attributes_template: '{{ value_json | tojson }}'

That works, but only captures the first reading (-59 in my example above) and ignores the second (-57) and third and maybe fourth (i.e. the number of readings in each MQTT message is not a set number.)

So I tried to change the value template to:

value_template: "{% for i in range(value_json.obj|count) %}{{value_json.obj[i].level}}{% endfor %}"

That “sorta” works but the results are strung together like “-59-57” which, of course, the HA is not happy about. It thinks the single reading is -59-57 which of course is not a number.

I need the HA to treat -59 as one reading and then -57 as another reading from the same sensor. Remember though that the number of readings in each MQTT message is not a set number.

Any ideas/suggestions?

Thanks in advance!

Nope, because you cannot natively make Home Assistant store readings that are in the past. All you can do is take the latest reading and let Home Assistant store that.

It seems like everything in the MQTT message is actually “in the past”, but I just want to parse out multiple readings from a single MQTT message.

I have an idea though. I’m going to try it now. Send rescue team if you don’t hear from me within 60 mins.

Update: I just tried searching this forum for other examples of this problem, and I found one that was very very close. I was reading the post with ever increasing excitement thinking that this person had a very similar case to mine. Finally I scrolled down the reveal the glorious answer…then I finally realized I was reading my own post here. :woozy_face:

1 Like

When the MQTT Sensor receives a payload, you can extract one value from it to assign to the sensor’s state property. In other words, one received payload equals one “reading”.

The only other thing you can do is store all, or parts of, the received payload in the sensor’s attributes. You’re already storing all of it using the json_attributes_template option.