Deep sleep and MQTT publishing

I’m trying to make a remote solar powered temp sensor sending data back to node red via MQTT.
I have the following code that "‘works’’ BUT does not always publish the data (currently just sending battery voltage for testing).
As the code is in all in SETUP it obviously only runs once and not again unit the ESP8266 wakes back up after the deep sleep.
What code do I need to either keep attempting to publish the data or not move on (deepsleep) until a publish acknowledged is received. However could such code keep the unit running and flatten the battery, maybe a code that tried maybe 5 times then gives up??

I’m not very experienced

#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>

#define WIFI_SSID "WiFi-86F4"
#define WIFI_PASSWORD "75831431"

// Raspberri Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, 168, 1, 113)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST ""
#define MQTT_PORT 1883

// Temperature MQTT Topics
#define MQTT_PUB_TEMP "esp/ds18b20/solar"

// GPIO where the DS18B20 is connected to
const int oneWireBus = 14;    //first DS18B20 (GPIO4-D2)
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);

// Temperature value
float temp;

const int analogInPin = A0;  // ESP8266 Analog Pin ADC0 = A0
int sensorValue = 0;  // value read from the pot
float batteryLevel = sensorValue*(3.3/1023.0); //analogread returns a number 0-1023
// Voltage Divider Vout = (Vin*R2)/(R1+R2)  27K and 100K = Vout = (4.2*100k)/(27k + 100k) = 3.3V

AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;

WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker wifiReconnectTimer;

unsigned long previousMillis = 0;   // Stores last time temperature was published
const long interval = 10000;        // Interval at which to publish sensor readings

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");

void onWifiConnect(const WiFiEventStationModeGotIP& event) {
  Serial.println("Connected to Wi-Fi.");

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  Serial.println("Disconnected from Wi-Fi.");
  mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
  wifiReconnectTimer.once(2, connectToWifi);

void connectToMqtt() {
  Serial.println("Connecting to MQTT...");

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");

  if (WiFi.isConnected()) {
    mqttReconnectTimer.once(2, connectToMqtt);

/*void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.print("  qos: ");

void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");

void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");

void setup() {

  // read the analog in value
  sensorValue = analogRead(analogInPin);
 delay (250);
  // print the readings in the Serial Monitor
  Serial.print("sensor = ");

  batteryLevel = (sensorValue*(3.3/1023.0))-0.15;   //-0.15 is an offset .Corrected to a measured value on DMV

  Serial.print("Battery Level = ");


  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  // If your broker requires authentication (username and password), set them below
  //mqttClient.setCredentials("REPlACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");
  delay (5000); 

if (WiFi.isConnected()) {
    // Temperature in Celsius degrees
    temp = sensors.getTempCByIndex(0);
    // Publish an MQTT message on topic esp/ds18b20/solar
    uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(batteryLevel).c_str());                            
    Serial.printf("Publishing on topic %s at QoS 1, packetId: %i ", MQTT_PUB_TEMP, packetIdPub1);
    Serial.printf("Message: %.2f \n", temp);

delay (5000);

// code to only go to sleep if publish acknoledged?? - or will this keep it active?

ESP.deepSleep(1.8e9); // 1.8e9 is 30 minutes, 6e7 is 60 seconds in microseconds take into account other delays above


void loop() 



in code, more of a cut and paste right now.

Why do you use an asynchronous MQTT client if you want a synchronous result?

The AsyncMqttClient library offers a onPublish callback. Register that callback and set a flag once the publish was successful, react on that flag in the main loop.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.