MQTT sensor data and value template

I’m fairly new to home-assistant, and I’m struggling to get my already existing sensors as an entity into home-assistant.

All my sensors are publishing their data under the same topic “sensors” and the data looks like this:

data,sensor=DHT22,source=office temperature=23.00,humidity=33.00

I think I need to use some sort of value template to get the sensors’ data in a usable format into home-assistant, but I can not get this to work.

Can someone maybe help me with an example config snippet on how to achieve this?

Thanks.

What is publishing this data?

If it is a DIY sensor, can it be changed to send json formatted data?

A properly structured json format will be much easier to deal with.

If that is exactly what the data looks like, you could do this:

mqtt:
  sensor:
    - name: Office temperature
      unique_id: e9ffd35d-dd9d-4f32-a365-900d1de8250c
      state_topic: "sensors"
      unit_of_measurement: "°C"
      device_class: temperature
      value_template: >
        {% if "source=office" in value %}
          {{ value|regex_findall("temperature=(\-?\d+\.?\d*)")|first }}
        {% else %}
          {{ states('sensor.office_temperature') }}
        {% endif %}
    - name: Office humidity
      unique_id: d2a27225-b2eb-41b1-a280-45da1a981e96
      state_topic: "sensors"
      unit_of_measurement: "%"
      device_class: humidity
      value_template: >
        {% if "source=office" in value %}
          {{ value|regex_findall("humidity=(\d+\.?\d*)")|first }}
        {% else %}
          {{ states('sensor.office_humidity') }}
        {% endif %}

…and so on with replacements for the source=office check. These update when a new message is published, but if they don’t see their source location they retain the prior value.

1 Like

It is a DIY sensor, but changing the format there would mean I also would need to change a few other things, which I currently do not want to do. In general, you are right, JSON would have been the much wiser choice a couple of years back when I build these things :slight_smile:

1 Like

@Troon Thank you so much. That worked perfectly for my situation!