So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By BjornJ
#72880 I have intermittent failures to transmit MQTT data.

An ESP-01 module is part of a battery powered system where an Arduino Nano powers up/down the ESP-01 via its Power Down pin. The Nano is itself in a low-power state most of the time and is awaken about every five hours by an external hardware timer. The ESP then connects to a Wi-Fi AP, then to an MQTT broker (ThingSpeak) and notifies the Nano that the connection is ready. The Nano sends sensor data via the serial port to the ESP, which then formats the data for ThingSpeak and publishes it at the broker. The ESP notifies the Nano that it is done so it can pull down the PD pin to put the ESP to sleep. This all works most of the time, but intermittently (one in 20-30) an update fails to make it to the broker. I have inserted delays in a few places before pulling the PD pin low but it does not seem to improve the situation. The delays total probably just short of two seconds now.

I suspect that the MQTT 'publish' call results in a non-blocking 'write' call somewhere in the Wi-Fi stack. Is there a way for the ESP-01 application code to tell if the transmission went through, or to block until it is finished?

I am using the Arduino IDE for the ESP-01 and the Nano.
These libraries are used for the ESP-01:
Code: Select all#include <ESP8266WiFi.h>
#include <PubSubClient.h> // For MQTT protocol

WiFiClient client;
PubSubClient mqttClient( client );            // Create an MQTT client
User avatar
By gdsports
#72956 After mqttClient.disconnect(), wait for both the mqttClient and the tcpClient to report not connected. Then do an additional 50 ms delay before going to deep sleep. Works for me.

Code: Select all  if (!mqttClient.connected() && !tcpClient.connected()) {
    // Allow time for final FIN ACK
    delay(50);
    deepsleep_normal();
  }