How can I add a suffix to an MQTT topic

18 Views Asked by At

I am using a polar H10 heart rate sensor which connects a mobile phone app called polar sensor data logger. I am using this app to publish the data using MQTT protocol . The publishes sensor readings over 3 topics i.e. XXX/ecg , XXX/hr , XXX/acc. Where the prefix XXX is taken as the user input. Is there a way in which I can add a suffix to the topics of all messages arriving at the broker? Simply put the broker should convert the topics to XXX/ecg/YYY , XXX/hr/YYY , XXX/acc/YYY.

I tried to search this topic the closest reply i could was the use of broker bridges, but as far as i could understand it only allows you to add a prefix and not a suffix

1

There are 1 best solutions below

0
hardillb On

You could write a custom mosquitto plugin to adjust the topic of messages as they are published.

There is an example in the 2.1.x development branch on GitHub here:

https://github.com/eclipse/mosquitto/tree/develop/plugins/examples/topic-modification

The example removes a section from the topic, but the same pattern would be used to add a extra section.

static int callback_message_in(int event, void *event_data, void *userdata)
{
    struct mosquitto_evt_message *ed = event_data;
    bool result;

    UNUSED(event);
    UNUSED(userdata);

    /* This simply removes "/uplink" from the end of every matching topic. You
     * can of course do much more complicated message processing if needed. */

    mosquitto_topic_matches_sub("device/+/data/uplink", ed->topic, &result);

    if(result){
        ed->topic[strlen(ed->topic) - strlen("/uplink")] = '\0';
    }

    return MOSQ_ERR_SUCCESS;
}