Arduino Giga Wifi to Influxdb

Hello,

Arduino Giga seems very useful with onboard WiFi integration. I also have a W5500 Ethernet shield connected to it. I am trying to send the (A0) pin value to influxdb. Libraries work very well with ESP32 boards but are not designated for Arduino boards or ethernet shields. Can anyone please help me post A0 reading to influxdb via my Giga WiFi board through Ethernet? I appreciate any help.

It's not mandatory to use the provided library, you can write data to DB also using classic HTTP API.

This is a test sketch I've written some months ago (so could be needed to adapt if API was changed in the meantime). It's for ESP32, but since a classic Arduino client was used, it should be easy to adapt for other MCUs.

#include <WiFi.h>
#include <FS.h>
#include <LittleFS.h>
#include <time.h>

#define MYTZ "CET-1CEST,M3.5.0,M10.5.0/3"  // Timezone definition

const char* ssid = "xxxxx";      // Change this to your WiFi SSID
const char* password = "xxxxx";  // Change this to your WiFi password

const char* host = "192.168.xxx.xxx";
const int httpPort = 8086;
const char* organization = "work";
const char* token = "xxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==";
const char* bucket = "myBucket";
const char* measurementTag = "airSensors";
const char* sensorId = "TLM205";
const char* fieldTemp = "temperature";
const char* fieldHumidity = "humidity";


#define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 30       /* Time ESP32 will go to sleep (in seconds) */

const uint16_t batch = 5;
RTC_DATA_ATTR uint32_t activeTime = 0;
RTC_DATA_ATTR uint8_t lastHour = 0;
RTC_DATA_ATTR int bootCount = 0;
RTC_DATA_ATTR int ntpSynced = 0;
RTC_DATA_ATTR struct tm tInfo;

bool startWifi() {
  Serial.print("\nConnecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  uint32_t timeout = millis();
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    if (millis() - timeout > 10000)
      return false;
  }

  if (!ntpSynced) {
    // Set timezone
    configTzTime(MYTZ, "time.google.com", "time.windows.com", "pool.ntp.org");

    // Wait for updated NTP time
    timeout = millis();
    while (!getLocalTime(&tInfo)) {
      delay(100);
      if (millis() - timeout > 10000)
        return false;
    }
    Serial.println(&tInfo, "\n%A, %B %d %Y %H:%M:%S");
    ntpSynced = 1;
  }
  return true;
}


bool appendDataToFile(const char* path, const char* line) {
  Serial.printf("Append new record to file: %s...\n", path);
  File file = LittleFS.open(path, FILE_APPEND);
  if (!file) {
    Serial.println("failed to open file for writing");
    return false;
  }
  file.print(line);
  Serial.print(line);
  file.close();
  return true;
}

void printData(const char* path) {
  File file = LittleFS.open(path, FILE_READ);
  while (file.available()) {
    Serial.write((char)file.read());
  }
  file.close();
}


void readResponse(WiFiClient* client) {
  unsigned long timeout = millis();
  while (client->available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client->stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while (client->available()) {
    String line = client->readStringUntil('\r');
    Serial.print(line);
  }
  Serial.printf("\nClosing connection\n\n");
  client->stop();
}

bool writeDataToDB(const char* path) {
  Serial.println("Send data to InfluxDB");

  WiFiClient client;
  if (!client.connect(host, httpPort)) {
    return false;
  }

  String payload;
  File file = LittleFS.open(path, FILE_READ);
  if (!file) {
    Serial.println("failed to open file for reading");
    return false;
  }
  while (file.available()) {
    payload += (char)file.read();
  }
  file.close();
  Serial.println(payload);

  String request = "POST /api/v2/write?org=";
  request += organization;
  request += "&bucket=";
  request += bucket;
  request += "&precision=ns HTTP/1.1\r\nHost: ";
  request += host;
  request += ":";
  request += httpPort;
  request += "\r\nAuthorization: Token ";
  request += token;
  request += "\r\nAccept: application/json\r\nContent-Type: text/plain; charset=utf-8";
  request += "\r\nContent-Length: ";
  request += payload.length();
  request += "\r\n\r\n";

  client.print(request);
  client.print(payload);
  // Serial.print(request);  
  // Serial.print(payload);

  readResponse(&client);
  return true;
}



void setup() {
  uint32_t startTime = millis();
  Serial.begin(115200);

  if (!ntpSynced) {
    startWifi();
    Serial.print("\nWiFi connected. IP address: ");
    Serial.println(WiFi.localIP());
  }

  if (!LittleFS.begin(true)) {
    Serial.println("LittleFS Mount Failed");
    return;
  }

  Serial.printf("\n\nBoot counter: %d\n", ++bootCount);
  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);

  // Create and append to file a new record
  char record[256] = { 0 };
  float temp = 25.78 + (random(0, 500)/ 100);  // Some random value
  float hum = 50.0 + (random(0, 500) / 100);    // Some random value
  time_t now;
  time(&now);  // timestamp

  snprintf(record, sizeof(record),
           "%s,sensor_id=%s temperature=%3.1f,humidity=%3.1f %ld000000000\n",
           measurementTag, sensorId, temp, hum, now);
  appendDataToFile("/data.csv", record);

  // Send data to InfluxDB every 10 reboots, otherwise append new record and go to sleep
  if (bootCount % batch == 0) {
    if (startWifi()) {
      Serial.print("\nWiFi connected. IP address: ");
      Serial.println(WiFi.localIP());

      if (writeDataToDB("/data.csv")) {
        if (LittleFS.remove("/data.csv")) {
          Serial.println("Records sents to InfluxDB, file csv removed");
        }
      }
    }
  }
  
  // Sync NTP time every 100 reboots (on next one)
  if (bootCount % 100 == 0) {
    ntpSynced = 0;
  }

  // Keep track of active amount of time in last hour (useful for battery life estimation)
  activeTime += millis() - startTime;
  Serial.printf("Active time in last hour %d ms\n\n", activeTime);
  if (lastHour != tInfo.tm_hour) {
    lastHour = tInfo.tm_hour;
    activeTime = 0;
  }

  Serial.flush();
  esp_deep_sleep_start();
  // printData("/data.csv");
}


void loop() {
}
1 Like

@cotestatnt . This is perfect, and it solves the problem. It took me a while to edit and remove RTC and SD writing; now, I will try it with an Ethernet connection. I appreciate your help. Thanks.

1 Like

@cotestatnt Hello again,

I have tried the code using Wi-Fi and posting it to my influxdb on the local host, which was okay. I tried to change the URL and port for my influx cloud, it id not work, also with using Ethernet shield, connection fiald. Do you have any examples of posting to the influx db cloud using Ethernet? Thank you.

I tried this code to post random int to influxdb cloud2, but it failed to connect. However, when I use the same code to post the data to local server of the influxdb on 192.168.x.x:8086. It works perfectly.

#include <SPI.h>
#include <Ethernet.h>

// Network settings
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  // Your MAC address
char server[] = "eu-central-1-1.aws.cloud2.influxdata.com";  // InfluxDB Cloud 2 server URL
int port = 443;  // HTTPS port for InfluxDB Cloud 2

// InfluxDB settings for Cloud 2
const char* organization = "MyOrg"; // Organization name
const char* token = "MyToken";
const char* bucket = "MyBucket";

// Ethernet client
EthernetClient client;

void setup() {
  // Initialize serial communication
  Serial.begin(9600);

  // Set the CS pin to 15
  Ethernet.init(15);

  // Initialize the Ethernet shield using DHCP
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    for (;;);
  }

  // Give the Ethernet shield a second to initialize
  delay(1000);

  // Print out the IP address
  Serial.print("IP Address: ");
  Serial.println(Ethernet.localIP());

  // Start connection attempt
  if (connectToInfluxDB()) {
    Serial.println("Connected to InfluxDB Cloud 2");
  } else {
    Serial.println("Connection failed");
  }
}

void loop() {
  // Your main loop code here
  // Example: sendDataToInfluxDB();
  delay(10000);  // Example: Delay between sending data
}

bool connectToInfluxDB() {
  if (client.connect(server, port, "https")) {
    Serial.println("Connected to server");

    // Create the HTTPS POST request for InfluxDB Cloud 2
    String postStr = "POST /api/v2/write?org=" + String(organization) + "&bucket=" + String(bucket) + "&precision=s HTTP/1.1\r\n";
    postStr += "Host: " + String(server) + "\r\n";
    postStr += "Authorization: Token " + String(token) + "\r\n";
    postStr += "Connection: close\r\n";
    postStr += "Content-Type: text/plain; charset=utf-8\r\n";
    // Example: postStr += "Content-Length: " + String(data.length()) + "\r\n\r\n";
    // Example: postStr += data;

    // Send the HTTPS POST request
    client.println(postStr);  // Use println to send the complete request
    Serial.println("Sent data: ");
    Serial.println(postStr);

    // Wait for server response
    while (client.connected()) {
      if (client.available()) {
        String line = client.readStringUntil('\n');
        Serial.println(line); // Print server response for debugging
        if (line == "\r") {
          break;
        }
      }
    }

    // Check HTTPS status
    String status = client.readStringUntil('\n');
    Serial.println("HTTPS status: " + status); // Print HTTPS status for debugging
    if (status.indexOf("204") >= 0) {
      client.stop();
      return true;
    }
  } else {
    Serial.println("Connection failed");
  }
  client.stop();
  return false;
}

This is the serial debug return

IP Address: 192.168.0.62
Connected to server
Sent data: 
POST /api/v2/write?org=AquaZoa&bucket=Concentrata&precision=s HTTP/1.1
Host: eu-central-1-1.aws.cloud2.influxdata.com
Authorization: Token Fe6lpOm6ctZFNXQkKYGl9-Rr44lhDS_L7Cy2TQFubTGi4qszy6W3utJWa7mdkLl0L5Zr511N9tmjTcSLTsH3vQ==
Connection: close
Content-Type: text/plain; charset=utf-8

HTTP/1.1 400 Bad Request

Date: Mon, 08 Jul 2024 23:57:56 GMT

Content-Type: text/html

Content-Length: 248

Connection: close



HTTPS status: <html>

Connection failed