eclipse / paho.mqtt.embedded-c

Paho MQTT C client library for embedded systems. Paho is an Eclipse IoT project (https://iot.eclipse.org/)

Home Page:https://eclipse.org/paho

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

can not call back mesage handler on the subscribed topic.

mylnz opened this issue · comments

commented

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). - Paho@1.0.0 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() {

}

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

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.