paho.mqtt.embedded-c icon indicating copy to clipboard operation
paho.mqtt.embedded-c copied to clipboard

can not call back mesage handler on the subscribed topic.

Open mylnz opened this issue 5 years ago • 2 comments

I have implemented an MQTT util class. I have not to get an exception, everything looks okay. I could not call back by subscribing to the topic.

I'm using the PahoMQTT Arduino library (https://platformio.org/lib/show/1560/Paho). - [email protected] verison

The code is properly compiled. Subscribe seems completed successfully. But, when I publish data to the subscribed topic, defaultMessageHandler call back method does not execute.

Subscribe callback is not working.

MqttUtils.h

class MqttUtilsClass {
private:
protected:
    bool initialSubscribeTopics();
    WiFiClient wiFiClient;
    IPStack ipstack = IPStack(wiFiClient);
    MQTT::Client<IPStack, Countdown, 1024, 5> *mqttClient = NULL;
public:
    MqttUtilsClass(){
        mqttClient= new MQTT::Client<IPStack, Countdown, 1024, 5>(ipstack);
    }
    static void defaultMessageHandler(MQTT::MessageData &md);
    bool connect();
};

MqttUtils.cpp

#include "MqttUtils.h"

void MqttUtilsClass::defaultMessageHandler(MQTT::MessageData &md) {
    MQTT::Message &message = md.message;
    DDebug.printInfo("defaultMessageHandler");
    DDebug.printInfo((char *)message.payload);
}

bool MqttUtilsClass::initialSubscribeTopics() {
    return mqttClient->subscribe("TOPIC", MQTT::QOS0, &MqttUtilsClass::defaultMessageHandler) == MQTT::SUCCESS;
}

bool MqttUtilsClass::connect() {
    int rc = ipstack.connect((char *) hostname, port);

    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.username.cstring = (char *) userName;
    data.password.cstring = (char *) password;
    data.MQTTVersion = 4;

    rc = mqttClient->connect(data);

    // subscribe to common topics
    initialSubscribeTopics();

    return true;
}

main.cpp

MqttUtilsClass mqttUtilsClass;

void setup() {
    Serial.begin(9600);
    ConnectionHandler.connectWifi();
    mqttUtilsClass.connect();
}

void loop() {

}

mylnz avatar Oct 03 '19 11:10 mylnz

I'm having this same issue, I know it's been 3 years but do you recall if you fixed it?

mickjc750 avatar Oct 12 '22 23:10 mickjc750

For others who are having trouble.. I had 2 problems.

  1. The function I was providing for network->mqttread was not attempting to read if the timeout value passed to it was 0mS. I had to change it to always attempt a read, which is how it should have been anyway,

  2. The message handler passed to MQTTSubscribe() is not called, when it appears it should be. But I was able to assign my messages handler to the .defaultMessageHandler member of my client (MQTTClient), and that works.

mickjc750 avatar Oct 13 '22 07:10 mickjc750