Skip to content

Instantly share code, notes, and snippets.

@cotestatnt
Last active September 25, 2023 12:46
Show Gist options
  • Save cotestatnt/c14547750799fb5ad774ed41bf126a0d to your computer and use it in GitHub Desktop.
Save cotestatnt/c14547750799fb5ad774ed41bf126a0d to your computer and use it in GitHub Desktop.
#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 = "xxxxxxxx"; // Change this to your WiFi SSID
const char* password = "xxxxxxxx"; // Change this to your WiFi password
const char* host = "192.168.1.xxx";
const int httpPort = 8086;
const char* organization = "work";
const char* token = "xxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==";
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 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");
}
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() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment