0

I'm trying to write a program for my ESP32 that writes to InfluxDB but also maintains an OTA access server and it appears that the two functions are having some impact on each other that's causing the OTA server to not work (i.e. the OTA page does not appear when I enter the IP address into the browser). I've narrowed the problem down to the

client.writePoint(sensor)

function that InfluxDB uses to write data to buffer and I'm unsure of how to remedy that. The OTA functionality works when I comment out the line that references the above function. I've included this code below.

//PASTE THIS IN ABOVE EXISTING HEADERS

//#include <WiFi.h>        //if file already has these libraries, remove it from one of the places
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>


const char* host = "esp32";
const char* ssid = "ssid"; 
const char* password = "pwd"; 
WebServer server(80);


// end OTA header file


//BEGIN HEADER FILE

#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "TEST"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>

/* Self inclusions -> Not from InfluxDB */

#define Vdd 3.3
#define Aout 35
#define LINEAR LOW
#define SQ_ROOT HIGH

const int R_0 = -1812; //Change this to your own R0 measurements

#include "max6675.h"
#include <WiFi.h>
#include <WiFiUdp.h>
/* End Self Inclusions */

// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "url"

// InfluxDB v2 server or cloud API authentication token ( Data -> Tokens -> MQ Sensors)
#define INFLUXDB_TOKEN "token"

// InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids )
#define INFLUXDB_ORG "org"

// InfluxDB v2 bucket name (Use: InfluxDB UI ->  Data -> Buckets)
#define INFLUXDB_BUCKET "bucket"

// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
// Examples:
//  Pacific Time: "PST8PDT"
//  Eastern: "EST5EDT"
//  Japanesse: "JST-9"
//  Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "EST5EDT"

// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);

// Data Point
Point sensor("VOC_data");  // Data point

// END HEADER FILE

void setup() {  //make sure this line appears one time only
  Serial.begin(115200); //make sure there are not two serial/begin functions in setup
  Serial.println("started"); //TS COMMENT

  // Connect to WiFi network
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("\n\nACCESS UPDATES AT: http://");
  Serial.print(WiFi.localIP());
  Serial.println("\n\n");
  

  pinMode(Aout, INPUT);

  // Add tags
  sensor.addTag("device", DEVICE);

    // Accurate time is necessary for certificate validation and writing in batches
  // For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
  // Syncing progress and the time will be printed to Serial.
  timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");

  // 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());
  }


  /*use mdns for host name resolution*/
  if (!MDNS.begin(host)) { //http://esp32.local
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  /*return index page which is stored in serverIndex */
  server.on("/", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", loginIndex);
    Serial.println("init1 complete"); //TS COMMENT
  });
  server.on("/serverIndex", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", serverIndex);
    Serial.println("init2 complete"); //TS COMMENT
  });
  /*handling uploading firmware file */
  server.on("/update", HTTP_POST, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
    ESP.restart();
    Serial.println("init3 complete"); //TS COMMENT
  }, []() {
    HTTPUpload& upload = server.upload();
    if (upload.status == UPLOAD_FILE_START) {
      Serial.printf("Update: %s\n", upload.filename.c_str());
      Serial.println("init4 complete"); //TS COMMENT
      if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
        Serial.println("Check at line 201");
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_WRITE) {
      /* flashing firmware to ESP*/
      if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
        Serial.println("Check at line 207");
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_END) {
      if (Update.end(true)) { //true to set the size to the current progress
        Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
      } else {
        Serial.println("Check at line 214");
        Update.printError(Serial);
      }
    }
  });
  server.begin();
  

  
}   //delete if void setup() line is deleted

void loop() { //make sure this line does not appear twice
  server.handleClient();

 float a0 = analogRead(Aout); // get raw reading from sensor
   float v_o = a0 * 4.6 / 1023; // convert reading to volts
   float R_S = (4.6-v_o) * 1000 / v_o; // apply formula for getting RS
   float R_a = R_S/R_0; // formula for the ratio
   float PPM = pow(R_a,-2.95) * 1000; //apply formula for getting PPM
   float PPM_ALCOHOL = pow(-13.17*log(R_S/R_0) + 10.35 ,1);
   //double PPM = pow(static_cast<double>(R_S/R_0),-2.95) * 1000;
   //float PPMnew = a0*0.065156122+0.746160521;
   
  sensor.clearFields();
    // Store measured value into point
  sensor.addField("VOC_Sensor", a0);
  sensor.addField("VOC_PPM", PPM);
  //sensor.addField("VOC_RS", R_S);
  //sensor.addField("VOC_ALCOHOL", PPM_ALCOHOL);
 
  /****************************** Self inclusions -> Not from InfluxDB ******************************/
  Serial.print("Sensor Voltage: ");
  Serial.print(v_o); //VOC concentration
  Serial.println(" V"); //units

  Serial.print("VOC Concentration calculation in arduino: ");
  Serial.print(PPM); //VOC concentration
  Serial.println(" PPM"); //units

  Serial.print("Raw signal: ");
  Serial.print(a0); //VOC concentration
  Serial.println(" "); //units
  delay(1000);

  /***************************************************************************************************/
  
  // Print what are we exactly writing
  Serial.println(WiFi.localIP());
  Serial.println("Line 286");
  Serial.println(sensor.toLineProtocol());
  
  
 
  // Write point
  if (client.writePoint(sensor)) {
    Serial.println("InfluxDB write successful");
  } else {
    Serial.print("InfluxDB write failed: ");
    Serial.println(client.getLastErrorMessage());
  }

  Serial.println("Wait 200ms");
  delay(200);
}  //delete if void loop() line is deleted

The serial output displays

Connected to ssid


ACCESS UPDATES AT: ESP32_IP_ADDRESS

and then continues to display the "InfluxDB write successful" message with each data point.

  • 1
    Hi @Prakhar Gupta, welcome to Stack Overflow. What does "not work" mean? Is your code crashing? If not, what output are you seeing from the OTA code that you published (please edit your question to include this, don't just reply in a comment)? You said you think it has something to do with including InfluxDB code - what happens if you strip everything out of the program except the OTA code and try to do an update using that code? – romkey Jul 07 '22 at 20:01
  • Hi @romkey, thank you for your help - just getting used to asking for help on here. I've narrowed down the problem and made some edits to my post. Thanks again:) – Prakhar Gupta Jul 08 '22 at 14:55
  • OTA page only appear when you send a POST request to `/update` endpoint. Your `loop()` constantly reading the sensor data and write it to database every 200ms as the way you programmed it even when there is no client access to any endpoint(webpage). It works as the way you code it, so what is the question and what is not working? – hcheung Jul 09 '22 at 09:50

0 Answers0