Code check – erratic wifi connection on ESP 8266?

Looking for a quick scan of my code to check if there’s anything daft I’m doing here.

Have built wifi temperature sensors that I have in various locations, but I’m noticing that they’re a little erratic in whether they are submitting data or not.

A good example is the attached code for a server unit device – it’s sitting within a metre of the Orbi satellite, so naturally has a pretty rock solid connection. I’m just wondering if there’s anything in my code that’s making it less resilient and potentially failing to submit.

This code has submitted data to my influxdb for a few hours yesterday (every 15 mins), but then has failed to submit anything new since then. I’ve hit the reset button on the ESP8266 and it’s started again.

Any help most appreciated!

#include <DHT.h>
#include <DHT_U.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <InfluxDbClient.h>


// v2 Temp sensor
// Connecting to Home NAS

// Instructions
// 1. Update SensorName

#define SSID "xxx" //your network name
#define PASS "xxx" //your network password
#define VersionID "v3"


#define SensorName "ESPTemp_ServerUnit" //name of sensor used for InfluxDB and Home Assistant
// Temp Sensor 1 - ESPTemp_GardenTropical
// Temp Sensor 2 - ESPTemp_GardenRoom
// Temp Sensor 3 - ESPTemp_Greenhouse
// Temp Sensor 4 - ESPTemp_OutsideGreenhouse
// Temp Sensor 5 - ESPTemp_ServerUnit

// Connection Parameters for Jupiter InfluxDB
#define INFLUXDB_URL "http://192.168.1.5:8086"
#define INFLUXDB_DB_NAME "home_assistant"
#define INFLUXDB_USER "xxx"
#define INFLUXDB_PASSWORD "xxx"


// Single InfluxDB instance
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);
// Define data point with measurement name 'DaveTest`
Point sensor("BrynyneuaddSensors");


#define PORT 80
#define DHTPIN 4     // what pin the DHT sensor is connected to
#define DHTTYPE DHT22   // Change to DHT22 if that's what you have
#define BAUD_RATE 115200 //Another common value is 9600

// 900000 ms = every 15 mins it posts to database
const unsigned long delayTime = 15 * 60 * 1000;
unsigned long delayCounter = 0;

DHT dht(DHTPIN, DHTTYPE);


//this runs once
void setup()
{
  Serial.begin(BAUD_RATE);

  // Connect to WIFI
  WiFi.begin(SSID, PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print("*");
  }

  // Initialise OTA Routine
  ArduinoOTA.onStart([]() {
    Serial.println("Start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  //Set the unique name of device
  ArduinoOTA.setHostname(SensorName);
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());



  //initalize DHT sensor
  dht.begin();

  // set InfluxDB database connection parameters
  client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DB_NAME, INFLUXDB_USER, INFLUXDB_PASSWORD);

  // Add constant tags - only once
  sensor.addTag("device", SensorName);

  // Check server connection
  if (client.validateConnection()) {
    Serial.print("Connected to InfluxDB: ");
    Serial.println(client.getServerUrl());
  } else {
    Serial.print("InfluxDB connection failed: ");
    Serial.println(client.getLastErrorMessage());
    Serial.println(client.getServerUrl());
    Serial.println("Exiting DB Connection");

  }

}

//this runs over and over
void loop() {
  ArduinoOTA.handle();

  if (millis() - delayCounter > delayTime ) {

  //  Serial.println("DelayCounter= ");
  //  Serial.println(delayCounter);
 //   Serial.println("delayTime= ");
  //  Serial.println(delayTime);

    float h = dht.readHumidity();
    Serial.print("Humidity: ");
    Serial.println(h);
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float c = dht.readTemperature();
    Serial.print("Temperature: ");
    Serial.println(c);

    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(c)) {
      Serial.println("Reading DHT22 Failed, exiting");
      return;
    }

    //update Influx DB channel with new values
    updateTemp(c, h);

    Serial.print("Writing to InfluxDB: ");


    //INFLUXDB - clear temp data so it doesn't repeat
    sensor.clearFields();

    // Update Influx DB
    sensor.addField("Temperature", c);
    sensor.addField("Humidity", h);

    Serial.println(sensor.toLineProtocol());
    // Write data
    client.writePoint(sensor);

    delayCounter = millis();  // reset the timer
  }
}

bool updateTemp(float tempC, float humid) {

  WiFiClient client;    // Create a WiFiClient to for TCP connection


  Serial.println("Receiving HTTP response");
  while (client.available()) {
    char ch = static_cast<char>(client.read());
    Serial.print(ch);
  }
  Serial.println();


  Serial.println("Closing TCP connection");
  client.stop();
  return true;
}

Go to Source
Author: Alphatester77