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:
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // For MQTT protocol
WiFiClient client;
PubSubClient mqttClient( client ); // Create an MQTT client