I am using an ESP32 (https://heltec.org/project/wifi-kit-32/) with a AM2302 DHT22 and an LDR, talking to mosquitto on a Linux box. Publishing data is working fine, other than the "exceeded timeout, disconnecting" lots of people seem to be having. However, when a message is sent from another client to a topic I am subscribed to, my callback is never called, so I can't consume it.
In my reconnect function, I have
boolean success = mqttClient.subscribe("sensors/basement/led");
Serial.print("Subscribe returned ");
Serial.println(success);
and it does return 1 which I believe is success (usually success is zero but I don't think that's the case here). I also see the subscription in my mosquitto logs, which are currently cranked up to debug.
1610417274: New client connected from XXX.XXX.XXX.XXX as Basement1 (c1, k15, u'XXXXXXXXX').
1610417274: Sending CONNACK to Basement1 (0, 0)
1610417275: Received SUBSCRIBE from Basement1
1610417275: sensors/basement/led (QoS 0)
1610417275: Basement1 0 sensors/basement/led
1610417275: Sending SUBACK to Basement1
When I send data to sensors/basement/led from the other client (mqttdash), the server receives it, and sends it to mqttdash, as well as Basement1, which is my ESP32:
It's definitely sending the message to the ESP32:
1610417546: mqttdash-3785c5ce 0 sensors/basement/led
1610417546: Sending SUBACK to mqttdash-3785c5ce
1610417578: Received PUBLISH from mqttdash-3785c5ce (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
1610417578: Sending PUBLISH to Basement1 (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
1610417578: Sending PUBLISH to mqttdash-3785c5ce (d0, q0, r0, m0, 'sensors/basement/led', ... (1 bytes))
However, my callback is never called. Here is the setup of the callback:
WiFiClient espClient;
PubSubClient mqttClient(espClient);
...
void setupMQTT()
{
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
mqttClient.setCallback(mqttSubHandler);
mqttConnect();
}
...
void mqttSubHandler(char *topic, byte *message, unsigned int length)
{
Serial.print("Message arrived on topic: '");
Serial.print(topic);
Serial.print("'. Message: ");
String messageTemp;
for (int i = 0; i < length; i++)
{
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
...
Full code at https://github.com/djsegfault/arduino/blob/master/basement_monitor/basement_monitor.ino
Does anyone know why the callback is not being called? Thanks in advance.
1 Answer 1
nknolleary, the owner of the library, correctly identified the problem: You need to call mqttClient.loop() in you main loop. Without that, you are never giving the client a chance to check for any incoming messages.