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!