Filter json from mqtt device in sensor

I have a sensor created like this:

mqtt:
   sensor:
     - name: "BoilerTemp"
       state_topic: "BSB/json"
       unit_of_measurement: "..C"
       value_template: "{{ value_json.BSB.value }}"

And this is the json where that’s get send to the Mosquito broker:

{
    "BSB": {
        "id": 8830,
        "name": "DHW temperature actual value top (B3)",
        "value": "43.8",
        "desc": "",
        "unit": "°C",
        "error": 0
    }
}

This all works fine if I just get 1 message. If I add extra messages to be sent by the mqtt client it starts to get challenging. They all end up in the same topic BSB/json and also have the same format:

Like this:

{
    "BSB": {
        "id": 8830,
        "name": "DHW temperature actual value top (B3)",
        "value": "43.8",
        "desc": "",
        "unit": "°C",
        "error": 0
    }
}

{
    "BSB": {
        "id": 8700,
        "name": "Outside temp sensor local",
        "value": "27.0",
        "desc": "",
        "unit": "°C",
        "error": 0
    }
}

I want to create a sensor per “id”

So I need to find a way to tell the sensor to only accept data if “id”==“8700” for a certain sensor and if “id”==“xxxx” for any other example.

I do know the logic but I cant find a example to get this done in the sensor config.

Any help or example would be much appreciated. Let me know if there is a better approach in HA

So could try something like this:

mqtt:
   sensor:
     - name: "BoilerTemp"
       state_topic: "BSB/json"
       unit_of_measurement: "..C"
       value_template: >-
          {{ value_json.BSB.value 
              if value_json.BSB.id == 8700
              else states('sensor.boilertemp') }}

Basically grab the value if the ID is right otherwise use the current state. However this self-reference may pose some issues around startup. Mqtt sensors don’t restore state so they won’t have a value at startup. Which means until the first message comes in for each ID you might get some weird values or errors.

Another option that might be easier here is to simply use a trigger template sensor with an Mqtt trigger instead like this:

template:
  - trigger:
      platform: mqtt
      topic: BSB/json
      value_template: "{{ value_json.BSB.id }}"
      payload: 8700
    sensor:
      name: BoilerTemp
      unit_of_measurement: "..C"
      state: "{{ trigger.payload_json.BSB.value }}"

This will specifically only trigger and set the sensors state when a message comes in for the particular ID it is watching. And trigger template sensors do restore state so the value will carry across restarts.

EDIT: had to tweak the second one, used value_json instead of trigger.payload_json in the state template.

2 Likes

Worked like a charm. Thanks for the swift response!

1 Like