Parse JSON data differently according to topic message was received in

Hello!

I have a mqtt consumer configured to listen to homeassistant/rooms/#. Now I receive messages in homeassistant/rooms/bedroom/window and homeassistant/rooms/bedroom/weatherstation.

The json I receive in homeassistant/rooms/bedroom/window is following:

{
    "battery": 67.5,
    "battery_low": false,
    "contact": true,
    "linkquality": 196,
    "tamper": false,
    "voltage": 2900
}

Of this message only battery and contact are of interest for me.

And in homeassistant/rooms/bedroom/weatherstation is this:

{
    "temperature": 20.9,
    "humidity":56.5,
    "co2": 1345
}

I need all measurements of this message.

This is my current MQTT input configuration

[[inputs.mqtt_consumer]]
  servers = ["tcp://mqtt:1883"]

  topics = [
    "homeassistant/rooms/#"
  ]
  topic_tag = ""

  username = "<Username>"
  password = "<Password>"

  data_format = "json_v2"
  [[inputs.mqtt_consumer.json_v2]]
    [[inputs.mqtt_consumer.json_v2.field]]
      path = "contact"
      rename = "isClosed"
      type = "bool"
    [[inputs.mqtt_consumer.json_v2.field]]
      path = "battery"
      rename = "battery"
      type = "float"
    
 [[inputs.mqtt_consumer.topic_parsing]]
    topic = "homeassistant/rooms/+/+"
    measurement = "_/_/measurement/_"
    tags = "_/_/room/sensor"

As I started with the window sensor it works fine for it. The json is correctly parsed and I get the data in my influx db as I want it.
Of course this configuration won’t work for the second message as the path contact and battery are not present for it.

I have a really hard time understanding the configuration of telegraf so this might be an easy fix but I just cannot get it running.
I tried using various configurations of processors but I just couldn’t get a hang on it.

Hopefully some of you can help me!

TL;DR

I need a way to filter the messages by the topic they were received in and then parse the json I receive accordingly.

In general if you are sending different types of messages that require different parsing, you need to set up multiple plugins to parse each of the message types. Otherwise, how does telegraf know how to parse the message?

You could mark all the tags and fields as optional under the json_v2 configuration and try to parse multiple different topics as well.

I thought it might be possible to do something with the topic tag like "if topic tag is this use this inputs.mqtt_consumer.json_v2 and if topic is that use that inputs.mqtt_consumer.json_v2. But if this is not possible I guess I have to use various consumers.

Thank you!

Is there a possibility to reuse parts of the configuration like the [[inputs.mqtt_consumer.topic_parsing]] or do I have to copy and paste that for every consumer?