Open m4dm4n opened 5 years ago
As I see it your problem is that client.loop() is called only once directly after successfull connect. To make it run for longer (i. e. like 15 seconds) you could try the change below. That should do the trick, though I did not test it.
//TRANSFER CODE FROM LOOP TO HERE uint32_t loopStart = millis(); while (millis() - loopStart < 15000) { if (!client.connected()) { reconnect(); } else client.loop(); } //END OF LOOP CODE
Hello @EFWob, I had the same problem and your solution solved it!
Thank you very much and happy christmas!
A bit more detail on this for anyone else who comes along, the problem was caused (for me) by not understanding when client.loop
does and when it needs to be called, as pointed out by @EFWob.
I've kept my code in loop
, but moved the client.loop()
call to the bottom, just before calling deep sleep. It's now working perfectly!
Essentially, you must call client.loop()
after your client.publish()
, before your deep sleep wipes out the internal buffer. Without deep sleep, that buffer will still be filled on the next loop
iteration and will, therefore, be sent. Sorted.
My (simplified) loop function:
void loop(void)
{
// Connect to MQTT
if (!client.connected()) {
mqtt_reconnect();
}
// ** USED TO HAVE client.loop() HERE **
// Send to MQTT topic
bool publishSuccess = client.publish(mqtt_topic, "message");
if (publishSuccess) {
Serial.println("MQTT Message published");
}
// MQTT Loop has to be AFTER message sent when using deep sleep.
client.loop();
// Deep sleep for 15 min
ESP.deepSleep(9e8);
}
Hardware: Board: Wemos lolin Core Installation/update date: v1.0.3 IDE name: Arduino IDE Flash Frequency: 80Mhz PSRAM enabled: no Upload Speed: ?921600? Computer OS: Windows 10
If uploading the code,not using Deep sleep function, ESP32 subscribes and publishes to some topic succesfully (MQTT Broker is Rpi, all debugging is done in Node-Red + ESP32 serial monitor).
But if I transfer that same code inside Deep Sleep part of the code, ESP32 fails to subscribe (precisely receive message from topic).
I tried as simple code as possible, some messages to get some clearer picture, but I can't pinpoint the problem.
Serial Monitor Debug message when the code is NOT working (aka using Deep Sleep functionality)
Serial Monitor Debug message when the code IS working (aka using Deep Sleep functionality)
You can CLEARLY see it received the message (which is retained on MQTT broker).