paho.mqtt.embedded-c
paho.mqtt.embedded-c copied to clipboard
can not call back mesage handler on the subscribed topic.
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() {
}
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.
-
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,
-
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.