MQTT Library - Multiple Subscriptions

Good evening!

I will keep this short and plain.
I am not fully aware of “callback” and it’s possible implementations.
My goal: To subscribe to multiple specific topics and use those topics to control the device. Or to store a value in a variable. I am wanting each subscription to be very specific and the payload channeled.

Normal Example of Callback:

 void callback(char* topic, byte* payload, unsigned int length) {}

Below is proposed code for multiple topics.

void callback(char* topic1, byte* payload, unsigned int length) {}
void callback(char* topic2, byte* payload, unsigned int length) {}
void callback(char* topic3, byte* payload, unsigned int length) {}

Would i simply change “topic” for each topic subscribed as shown above?

If you want multiple callbacks, each function has to have its own name. You can’t call them all callback while the topic parameter can/should stay unchanged.

But there ususally is also no need for a separate callback function for each and every topic, since your callback can use the topic parameter to choose the individual code paths for each topic-task.

FWIW, I don’t believe the the hirotakaster MQTT lib supports callbacks linked to specific topic strings.

It would be really nice to have callbacks which are linked to specific topics. Having to do tons of string comparisons takes a lot of time and memory in a sensitive part of the Particle OS.

How do you think the MQTT library would do the callback routing without string comparisons?

Oh, it has to do be done at some point for sure. There’s no free lunch here. But the lib can do it in an optimized way, instead of leaving it to each developer to reinvent the wheel and do string comparisons in whichever way fits his/her programming style and skill level.

1 Like