EVerest / everest-framework

Apache License 2.0
21 stars 19 forks source link

Unsubscribe from MQTT topic via ModuleAdapter #154

Closed djchhp closed 9 months ago

djchhp commented 9 months ago

Scope

The intention is to implement a request / reply pattern with a dynamic and random response topic within an EVerest module.

Problem

The module has to subscribe to a topic which is used once only. The callback remains registered though and thereby leaks memory and has an impact on performance. If the request is used frequently, the handlers pile up quickly.

Proposed solution

Provide a way to unsubscribe from a MQTT topic from user code in a module

Implementation

ext_mqtt_subscribe in ModuleAdapter returns an UnsubscribeToken. When the token is called, the handler is unsubscribed from the topic. The change does not break existing code, since the return type was void previously.

Example



{
    std::string reply_topic = "/path/to/reply/topic";
    auto unsubscribe = mod->mqtt.subscribe(reply_topic, [](auto const& raw_data){
          //do something with data
    };
    wait_for_respose_for_some_time(); 
    unsubscribe(); //this unsubscribes the previously installed handler from the topic
}