peterhinch / micropython-mqtt

A 'resilient' asynchronous MQTT driver. Recovers from WiFi and broker outages.
MIT License
549 stars 116 forks source link

Feature request: change sub callback after init #93

Closed SiboVG closed 1 year ago

SiboVG commented 1 year ago

In my application, I sometimes have to switch the sub callback for different scenarios. In my limited knowledge of this repo, it seems like you would always have to re-initialize the MQTT client to set a sub callback. Would it be reasonable to add a def set_subscribe_callback(self, callback) function to the MQTT client for this purpose?

peterhinch commented 1 year ago

I would consider using a function dispatch table or simply an if statement in the callback:

def sub_cb(topic, msg, retained):
    if scenario1:
        callback1(topic, msg, retained)
    elif scenario2:
        callback2(topic, msg, retained)
...
SiboVG commented 1 year ago

I would consider using a function dispatch table or simply an if statement in the callback:

def sub_cb(topic, msg, retained):
    if scenario1:
        callback1(topic, msg, retained)
    elif scenario2:
        callback2(topic, msg, retained)
...

Ah, interesting approach! Also just realized that you could just as well use client._cb = callback. Thanks for the help Peter! (also didn't mention it yet, but huge thanks for your efforts on this repo and the Micropython universe in general, can't thank you enough)