Skip to content

Instantly share code, notes, and snippets.

@fxprime
Created October 23, 2023 04:47
Show Gist options
  • Save fxprime/2e8c9bd1a8b413f66610a62968d7f447 to your computer and use it in GitHub Desktop.
Save fxprime/2e8c9bd1a8b413f66610a62968d7f447 to your computer and use it in GitHub Desktop.
/**
* @brief esp8266 Module4-x test purpose
*
*/
#include <Arduino.h>
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
#define WIFI_SSID "WIFI"
#define WIFI_PASSWORD "PASS"
#define INFLUXDB_URL "http://IP:8086"
#define INFLUXDB_TOKEN "TOKEN"
#define INFLUXDB_ORG "org"
#define INFLUXDB_BUCKET "testBucket"
#define TZ_INFO "UTC7"
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
Point sensor("wifi_status");
void setup()
{
Serial.begin(115200);
// Setup wifi
WiFi.mode(WIFI_STA);
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED)
{
Serial.print(".");
delay(100);
}
Serial.println();
// Accurate time is necessary for certificate validation and writing in batches
// We use the NTP servers in your area as provided by: 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());
}
sensor.addTag("device", DEVICE);
sensor.addTag("SSID", WiFi.SSID());
}
void loop()
{
// Clear fields for reusing the point. Tags will remain the same as set above.
sensor.clearFields();
unsigned long start = millis();
// Store measured value into point
// Report RSSI of currently connected network
sensor.addField("rssi", WiFi.RSSI());
sensor.addField("temperature", sin(millis() / 10000.0) * 20 + random(-1, 1));
sensor.addField("humidity", (millis() % 10000 > 5000)*random(20, 30) + (millis() % 10000 <= 5000)*random(70, 80) );
// Print what are we exactly writing
Serial.print("Writing: ");
Serial.println(sensor.toLineProtocol());
// Check WiFi connection and reconnect if needed
if (wifiMulti.run() != WL_CONNECTED)
{
Serial.println("Wifi connection lost");
}
// Write point
if (!client.writePoint(sensor))
{
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
Serial.print("Write successful. ");
Serial.print("Took: ");
Serial.print(millis() - start);
Serial.println(" ms.");
Serial.println("Waiting 1 second");
delay(1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment