GithubHelp home page GithubHelp logo

tobiasschuerg / influxdb-client-for-arduino Goto Github PK

View Code? Open in Web Editor NEW
368.0 14.0 92.0 618 KB

Simple library for sending measurements to an InfluxDB with a single network request. Supports ESP8266 and ESP32.

License: MIT License

C++ 87.74% JavaScript 8.60% C 3.65%
esp8266 esp8266-arduino influxdb measurements esp32 arduino-library influxdb-client

influxdb-client-for-arduino's People

Contributors

amfasis avatar arshaver avatar blumamir avatar cail avatar davidgs avatar dependabot[bot] avatar drageryd avatar encryptic avatar gasagna avatar hpsaturn avatar indus avatar jardous avatar jotzt avatar jwillmer avatar kdriver avatar kurtbeheydt avatar moerchel avatar rcrdbrt avatar rodri16 avatar soudrug avatar technoguyfication avatar tobiasschuerg avatar vlastahajek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

influxdb-client-for-arduino's Issues

HTTPS support

The v2 branch doesn't work without https support.

Reading data from InfluxDB

Hi,

I'm sure your solution does the job and writes to InfluxDB ;-) My question is not about writing but reading from an Influx database and I understand your solution is not intended to do so. Wondering if you can advice me about software to read from my database on a Raspberry Pi and display a value from it on a display connected to an ESP8266.

Regards,

Hans.

ESP32 stops on http.getString();

Hello,

I had a problem with ESP32.
The application stops when it tries to print a response that is empty (204).
If it's not empty there is no problem.

I solved with this workaround:
// String response = http.getString();
// Serial.println(" \"" + response + "\"");

Maybe a problem with "HTTPClient.h" name?
#if defined(ESP8266)
#include <ESP8266HTTPClient.h>
#elif defined(ESP32)
#include <WiFi.h>
#include <HTTPClient.h>
#endif

Thanks,
E_R

macro "min" passed 3 arguments, but takes just 2

I always recive this error when just try to compile the example:

I don't know how to fix it

c:\users\frank\appdata\local\arduino15\packages\arduino\tools\arm-none-eabi-gcc\7-2017q4\arm-none-eabi\include\c++\7.2.1\bits\stl_algobase.h:243:56: error: macro "min" passed 3 arguments, but takes just 2

 min(const _Tp& __a, const _Tp& __b, _Compare __comp)

                                                    ^

c:\users\frank\appdata\local\arduino15\packages\arduino\tools\arm-none-eabi-gcc\7-2017q4\arm-none-eabi\include\c++\7.2.1\bits\stl_algobase.h:265:56: error: macro "max" passed 3 arguments, but takes just 2

 max(const _Tp& __a, const _Tp& __b, _Compare __comp)

SecureWrite example causing bootloop

I'm running InfluxDB-Client-for-Arduino version 3.1.2 on an Adafruit Feather HUZZAH ESP8266. When trying to run the SecureWrite example without any modifications but adding my InfluxDB cloud and WiFi credentials, I'm getting a boot loop.

Here's what I'm seeing on the serial monitor:

Connecting to wifi....................................................................
Syncing time..
Synchronized time: Sun Apr 26 06:44:12 2020


Exception (3):
epc1=0x4000bf64 epc2=0x00000000 epc3=0x00000000 excvaddr=0x402570e7 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffd70 end: 3fffffc0 offset: 01a0
3fffff10:  7fffffff 3ffefe84 3ffee8fc 40203a0a  
3fffff20:  70747400 3ffe0073 80fe88e3 40205879  
3fffff30:  3ffee9a4 3ffee878 3ffee878 40203ce8  
3fffff40:  3ffee9a4 3fffff60 3ffeea04 40205d30  
3fffff50:  3ffee9a4 00000063 3ffeea04 402010f2  
3fffff60:  3ffefb00 0019001f 80feea04 5ea5119c  
3fffff70:  3ffee9a4 3ffee878 3ffeea04 402011f3  
3fffff80:  44495300 00363600 80efeffe 3ffefb00  
3fffff90:  0018001f 80efeffe feefeffe feefeffe  
3fffffa0:  3fffdad0 00000000 3ffeea40 40206cb8  
3fffffb0:  feefeffe feefeffe 3ffe8538 40100bd9  
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1392, room 16 
tail 0
chksum 0xd0
csum 0xd0
v3d128e5c
~ld

Any suggestions as to what might be happening?

When a point not have tags the database reply with a error message

The device send a point
adc1_ch1, value=1.905,count=16i 1586936036015835

Database response:
[D] Response: {"error":"unable to parse 'adc1_ch1, value=1.905,count=16i 1586936036015835': missing tag key\nunable to parse 'adc1_ch1, value=1.902,count=17i 1586936038015642': missing tag key\nunable to parse 'adc1_ch1, value=1.902,count=18i 1586936040015650': missing tag key"}
Cause:
The library does not generate a point with the correct protocol:

<measurement>[,<tag-key>=<tag-value>...] <field-key>=<field-value>[,<field2-key>=<field2-value>...] [unix-nano-timestamp]

image

FIX:
image

The database write the point without tags
image

Multiple readings unclear

How to do multiple readings please? I am trying to send temp, humidity, pressure and voltage. I am using this function:

void postData(float temperature, float humidity, float pressure, float voltage)
{
    InfluxData row("temperature2");
    row.addTag("device", "Bathroom");
    row.addValue("value", temperature);

    InfluxData row2("humidity2");
    row2.addTag("device", "Bathroom");
    row2.addValue("value", humidity);

    InfluxData row3("pressure2");
    row3.addTag("device", "Bathroom");
    row3.addValue("value", pressure);

    InfluxData row4("voltage2");
    row4.addTag("device", "Bathroom");
    row4.addValue("value", voltage);
    
    influx.write(row);
    influx.write(row2);
    influx.write(row3);
    influx.write(row4);
}

Is this the correct way? Thanks.

TLS support

Hi!

I needed TLS and ESP32 support in this otherwise excellent library, so I have hacked that in to a branch in a forked version of your library.

I'm more of a Java-dev/Sysadmin my self if you are wondering why I've butchered your library.

https://github.com/farthinder/ESP32_Secure_Influx_DB/tree/ESP32-Secure

If you are interested in my findings I´d be more than happy if you added them to your version of the library.

Help request, trying to batch write with writeprecision::MS

I use influxdbV1 with batch writing, Writepresision::MS (or NS/US for that matter)
influxdb client library V3.2
ESP8266 board 2.7.1

And a HX711 with the latest library on pins
const int LOADCELL_DOUT_PIN = 13;
const int LOADCELL_SCK_PIN = 12;

My output in Grafana looks like this, data gets swapped

2020-06-14 18:52:50 0
2020-06-14 18:52:50 0
2020-06-14 18:52:50 0
2020-06-14 18:52:49 500
2020-06-14 18:52:49 499
2020-06-14 18:52:49 500
2020-06-14 18:52:49 500
2020-06-14 18:52:49 0
2020-06-14 18:52:49 12
2020-06-14 18:52:49 499
2020-06-14 18:52:49 500
2020-06-14 18:52:49 500
2020-06-14 18:52:48 500
2020-06-14 18:52:48 500
2020-06-14 18:52:48 500
2020-06-14 18:52:48 500
2020-06-14 18:52:48 499
2020-06-14 18:52:48 500
2020-06-14 18:52:48 500
2020-06-14 18:52:48 500
2020-06-14 18:52:48 500
2020-06-14 18:52:48 500
2020-06-14 18:52:47 245
2020-06-14 18:52:47 162
2020-06-14 18:52:47 0
2020-06-14 18:52:47 0
2020-06-14 18:52:47 500
2020-06-14 18:52:47 476
2020-06-14 18:52:47 464
2020-06-14 18:52:47 449
2020-06-14 18:52:47 379
2020-06-14 18:52:46 0
2020-06-14 18:52:46 0

The output from println is okay so I'm trying to write in the right order

18:52:46.867 -> Data written to InfluxDB :-) Massa: 0.00 Tijd: 1592153566
18:52:46.970 -> Data written to InfluxDB :-) Massa: 0.00 Tijd: 1592153567
18:52:47.176 -> Data written to InfluxDB :-) Massa: 0.00 Tijd: 1592153567
18:52:47.278 -> Data written to InfluxDB :-) Massa: 162.00 Tijd: 1592153567
18:52:47.381 -> Data written to InfluxDB :-) Massa: 245.00 Tijd: 1592153567
18:52:47.483 -> Data written to InfluxDB :-) Massa: 379.00 Tijd: 1592153567
18:52:47.586 -> Data written to InfluxDB :-) Massa: 449.00 Tijd: 1592153567
18:52:47.688 -> Data written to InfluxDB :-) Massa: 464.00 Tijd: 1592153567
18:52:47.791 -> Data written to InfluxDB :-) Massa: 476.00 Tijd: 1592153567
18:52:47.895 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153567
18:52:47.998 -> Data written to InfluxDB :-) Massa: 499.00 Tijd: 1592153568
18:52:48.100 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.204 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.306 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.408 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.512 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.615 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.718 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.821 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.926 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153568
18:52:48.994 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153569
18:52:49.096 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153569
18:52:49.269 -> Data written to InfluxDB :-) Massa: 499.00 Tijd: 1592153569
18:52:49.373 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153569
18:52:49.476 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153569
18:52:49.578 -> Data written to InfluxDB :-) Massa: 500.00 Tijd: 1592153569
18:52:49.680 -> Data written to InfluxDB :-) Massa: 499.00 Tijd: 1592153569
18:52:49.784 -> Data written to InfluxDB :-) Massa: 12.00 Tijd: 1592153569
18:52:49.886 -> Data written to InfluxDB :-) Massa: 0.00 Tijd: 1592153569
18:52:49.987 -> Data written to InfluxDB :-) Massa: 0.00 Tijd: 1592153570
18:52:50.091 -> Data written to InfluxDB :-) Massa: 0.00 Tijd: 1592153570

If I try to manually set the time to resolve this (dPoint.setTime( tnow )) or dPoint.setTime( tijd )
the following happens:

InfluxDB write failed: {"error":"partial write: points beyond retention policy dropped=20"}

It even goes wrong when I set
#define MAX_BATCH_SIZE 1
#define WRITE_BUFFER_SIZE 1
effectively disabling batch-write :-S

What am I doing wrong?

My code is straightforward:

`/**

  • Secure Write Example code for InfluxDBClient library for Arduino
  • Enter WiFi and InfluxDB parameters below
  • Demonstrates connection to any InfluxDB instance accesible via:
    • unsecured http://...
    • secure https://... (appropriate certificate is required)
  • Measures signal level of all visible WiFi networks including signal level of the actually connected one
  • This example demonstrates time handling, how to write measures with different priorities, batching and retry
  • Data can be immediately seen in a InfluxDB 2 Cloud UI - measurements wifi_status and wifi_networks
    **/

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

#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>

// Setup the loadcell stuff
#include <HX711.h> // HX711 library for the scale

#define calibration_factor 923.53 //-7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch tbv china loadcell
// #define calibration_factor 701.77 //-7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch tbv dual 3kg tedea
#define calibration_factor2 3694.12 //-7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch tbv china loadcell

const int LOADCELL_DOUT_PIN = 13;
const int LOADCELL_SCK_PIN = 12;

HX711 scale;

// weight values
float weight = 0.0; // measured weight
int weightout = 0; // integer weight out
float dyntar = 0.0; // dynamic tar
const int freq = 80; // HX711 supports 10 and 80 Hertz, default = 10, hardware mod necessary
uint64_t tijd = 0; // test with usec unixtime, didn't work
int t = 0; // save measurement interval millis incrementals
#define THRESHOLD 2.1 // Measures only if the weight is greater than 2 gram.

// WiFi AP SSID
#define WIFI_SSID ********
// WiFi password
#define WIFI_PASSWORD ********

// Influxdb1 @home
#define INFLUXDB_URL ********
#define INFLUXDB_DB_NAME ********
#define INFLUXDB_USER ********
#define INFLUXDB_PASSWORD ********

// #define INFLUXDB_BUCKET "Weegschaal"

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

// Influxdb1 connect
// InfluxDB client instance for InfluxDB 1
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);
// Zie ook in de setup loop!

// 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 "CET-1CEST,M3.5.0,M10.5.0/3"
#define TZ_INFO "CET-1CEST-2,M3.5.0/2,M10.5.0/3"

#define WRITE_PRECISION WritePrecision::MS
#define MAX_BATCH_SIZE 10
#define WRITE_BUFFER_SIZE 30
#define MAX_TIME 60
#define HTTP_KEEP true

// Data point
Point sensorStatus("wifi_status");

// Number for loops to sync time using NTP
int iterations = 0;

void timeSync() {
// Synchronize UTC time with NTP servers
// Accurate time is necessary for certificate validaton and writing in batches
configTime(0, 0, "0.nl.pool.ntp.org", "3.nl.pool.ntp.org", "nl.pool.ntp.org" );
// Set timezone
setenv("TZ", TZ_INFO, 1);

// Wait till time is synced
Serial.print("Syncing time");
int i = 0;
while (time(nullptr) < 1000000000ul && i < 1000) {
Serial.print(".");
delay(100);
i++;
}
Serial.println();

// Show time
time_t tnow = time(nullptr);
Serial.print("Synchronized time: ");
Serial.println(String(ctime(&tnow)));
}

void setup() {
Serial.begin(115200);

// Setup the scale
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
delay(1000);
scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0

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

// Add tags
// sensorStatus.addTag("device", DEVICE);
// sensorStatus.addTag("SSID", WiFi.SSID());

// Sync time for certificate validation
timeSync();

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

// Set InfluxDB 1 authentication params
client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DB_NAME, INFLUXDB_USER, INFLUXDB_PASSWORD);

//Enable messages batching and retry buffer
client.setWriteOptions(WRITE_PRECISION, MAX_BATCH_SIZE, WRITE_BUFFER_SIZE, MAX_TIME, HTTP_KEEP);
}

void loop() {
// Sync time for batching once per hour
if ( (millis()/1000/3600) > iterations ) {
timeSync();
iterations++;
}

if (millis() > t + (1000/freq*2)) {
weight = (scale.get_units());
// dynamic tar if below threshold
if ( (weight + dyntar) < THRESHOLD ) { weight = -dyntar; }
weightout = int (weight + dyntar);
writeData(weightout);
t = millis();
}
delay(100);
}

void writeData(float weight) {

time_t tnow = time(nullptr);

tijd = xx_time_get_time();

Point dPoint("Massa");  
dPoint.addField("gram", weight);  

// dPoint.setTime( tijd ); //set the time
// dPoint.setTime( tnow ); //set the time
Serial.print("Massa: ");
Serial.print(weight);
Serial.print(" Tijd: ");
Serial.println(tnow);
// Serial.print(" Tijd2: ");
// print((long)tijd);
if(!client.writePoint(dPoint)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
} else {
Serial.print("Data written to InfluxDB :-) ");
}
}

/**
#include <math.h>
void print(uint64_t value)
{
const int NUM_DIGITS = log10(value) + 1;
char sz[NUM_DIGITS + 1];
sz[NUM_DIGITS] = 0;
for ( size_t i = NUM_DIGITS; i--; value /= 10)
{
sz[i] = '0' + (value % 10);
}
Serial.println(sz);
}
**/

int64_t xx_time_get_time() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * 1000LL + (tv.tv_usec / 1000LL));
}`

Error compiling BatchWrite example on Adafruit ESP32 Feather

hi. i try to use batch write. first step i try to run the default code up until wifi connected and comment the rest. the eror as below. i use ubuntu 18 with arduino ide 1.8.11

/Arduino/libraries/InfluxDB-Client-for-Arduino-master/src/InfluxDbClient.cpp:27:26: fatal error: core_version.h: No such file or directory
compilation terminated.
exit status 1
Error compiling for board Adafruit ESP32 Feather.

could you assist.

error: 'X509List' in namespace 'BearSSL' does not name a type

When compiling for both Generic ESP2866 and Wemos D1 I receive the following error...

In file included from C:\Users\Shane\Documents\Arduino\libraries\ESP8266_Influxdb\src/InfluxData.h:27:0,

             from C:\Users\Shane\Documents\Arduino\libraries\ESP8266_Influxdb\src/InfluxDb.h:27,

             from C:\Users\Shane\Documents\Arduino\influx_basic_test_13_04_2020\influx_basic_test_13_04_2020.ino:3:

C:\Users\Shane\Documents\Arduino\libraries\ESP8266_Influxdb\src/InfluxDbClient.h:243:3: error: 'X509List' in namespace 'BearSSL' does not name a type

BearSSL::X509List *_cert = nullptr;

^

Using library ESP8266WiFi at version 1.0 in folder: C:\Users\Shane\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.2\libraries\ESP8266WiFi
Using library ESP8266_Influxdb at version 3.1.1 in folder: C:\Users\Shane\Documents\Arduino\libraries\ESP8266_Influxdb
Using library ESP8266HTTPClient at version 1.1 in folder: C:\Users\Shane\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.2\libraries\ESP8266HTTPClient
exit status 1
Error compiling for board Generic ESP8266 Module.

Upload fails on create.arduino.cc

Hello,

I was trying to include the ESP8266 InfluxDB Library on create.arduino.cc. When I tried to load the BasicWrite example on my Arduino MKR WiFi 1010 I got the following error message:

Using library esp8266_influxdb_3_2_0 at version 3.2.0 in folder: /home/builder/opt/libraries/latest/esp8266_influxdb_3_2_0
/home/builder/opt/libraries/latest/esp8266_influxdb_3_2_0/src/InfluxDbClient.cpp:27:10: fatal error: core_version.h: No such file or directory

#include <core_version.h>
^~~~~~~~~~~~~~~~
compilation terminated.

exit status 1

Did I forget some config or is this a known issue? 

Best Wishes!

Support to https and pass username and password into encripty body

Pass username, password and database into URL is dangerous (because this information is not encrypted). Influxdb HTTP API supports usage body to pass username, password and database (see https://docs.influxdata.com/influxdb/v1.7/administration/authentication_and_authorization/).

Maybe change this lines and add https support can be resolve this issue
https://github.com/tobiasschuerg/ESP8266_Influx_DB/blob/5cd2dcf7bf60e1533dceb9d37b0a33f5c9f2fd01/InfluxDb.cpp#L42

Problem with axTLS

I get the <#error AxTLS doesn't work> and it refuses to compile on Arduino 1.8.12 for ESP32 on a Dev board on one PC and not another with the same code file and same Dev board?

The PC and Dev board are know to work well in all other circumstances. I have fresh install of Arduino on both PC's and same board definitions.

Would you know what library contains "USING AXTLS" or where I might look OR maybe I'm looking in the wrong place? Some file must be corrupted or missing (so methinks ??)

The last lines of errors are:

Using library WiFi at version 1.0 in folder: C:\Users\Peter\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\WiFi
Using library ESP8266_Influxdb at version 3.1.2 in folder: C:\Users\Peter\Documents\Arduino\libraries\ESP8266_Influxdb
Using library HTTPClient at version 1.2 in folder: C:\Users\Peter\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\HTTPClient
Using library WiFiClientSecure at version 1.0 in folder: C:\Users\Peter\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\libraries\WiFiClientSecure
exit status 1
Error compiling for board DOIT ESP32 DEVKIT V1.

Write a point with precision in microseconds not work correctly

testing version 3.1.1
with example basic write

if precision is configurare in micro seconds the point is write in 1970 date

#define WRITE_PRECISION WritePrecision::US client.setWriteOptions(WRITE_PRECISION,100,200,180,true);

image

this write a point in 1970
image
Fix in InfluxDBClient.cpp file
image

image

Write correctly date
image

InfluxDB connection failed

Hi there,

Doing something completely daft I'm sure, but I've had a temp sensor working on an ESP 8266 fine posting to Thingspeak, I'm wanting to now also write to my local NAS to an InfluxDB.... cue this awesome library...!

Turned on debugging, but it doesn't seem to produce anything useful here's the relevant part - it's booting a fail error, but can't see why!

Any help much appreciated!

22:50:43.328 -> Wifi Connection Successful 22:50:43.361 -> The IP Address of the Sensor is:192.168.1.35 22:50:43.361 -> [D] Validating connection to 192.168.1.5:8086/ping?verbose=true 22:50:43.361 -> [E] begin failed 22:50:43.361 -> InfluxDB connection failed: 22:50:43.361 -> 192.168.1.5:8086 22:50:43.361 -> Exiting DB Connection

Here's my full code (with just sensitive passes/apis removed):
`
// v2 Temp sensor
// Attempting to connect to home database to log data rather than Thingspeak

#include <DHT.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <InfluxDbClient.h>

#define SSID "XXX" //your network name
#define PASS "XXX" //your network password
#define API "XXX" //api string

// Temp Sensor 1 api - XXX
// Temp Sensor 2 api - XXX
// Temp Sensor 3 api - XXX
// Temp Sensor 4 api - XXX

// Connection Parameters for Jupiter InfluxDB
#define INFLUXDB_URL "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 'device_status`
Point sensor("wifi_status");

#define IP "api.thingspeak.com" // thingspeak.com
#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
#define DELAY_TIME 900000 //time in ms between posting data to Home Server

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("*");
}
Serial.println("");
Serial.println("Wifi Connection Successful");
Serial.print("The IP Address of the Sensor is:");
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", "1111");
sensor.addTag("SSID", "2222");

// 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() {
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 ThingSpeak channel with new values
updateTemp(c, h);

// Update Influx DB
sensor.addField("rssi", "3333");

//wait for delay time before attempting to post again
delay(DELAY_TIME);
}

bool updateTemp(float tempC, float humid) {

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

if (!client.connect(IP, PORT)) {
Serial.println("HTTP connection failed");
return false;
}

Serial.println("Sending data to server");
if (client.connected()) {

// Then write to Thingspeak
client.print("GET /update?api_key="); client.print(API);
client.print("&field1="); client.print(String(tempC));
client.print("&field2="); client.print(String(humid));
client.println(" HTTP/1.1");
client.print("Host: "); client.println(IP);
client.println("Connection: close");
client.println();    //extra "\r\n" as per HTTP protocol

}

// wait for data to be available
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println("HTTP Client Timeout !");
client.stop();
return false;
}
}

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

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

New SSL certificate for https://us-west-2-1.aws.cloud2.influxdata.com

I think the InfluxDBCloud certificate embeded in the arduino library is outdated.

It was uploaded on : 30/03/2020 à 18:11:31 (heure d’été d’Europe centrale) and will be renewed in 3 months. They use letsencrypt on the website, with short renew
This is problematic, we need to update the library / reflash the ESP each 3 months...

I changed it in /src/InfluxDbCloud.h with :

const char InfluxDbCloud2CACert[] PROGMEM = R"EOF( 
-----BEGIN CERTIFICATE-----
MIIFgTCCBGmgAwIBAgISA5OIj0UCZQRvFuaYGB41FLhPMA0GCSqGSIb3DQEBCwUA
MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD
ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0yMDAzMzAxNTExMzFaFw0y
MDA2MjgxNTExMzFaMDAxLjAsBgNVBAMTJXVzLXdlc3QtMi0xLmF3cy5jbG91ZDIu
aW5mbHV4ZGF0YS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC5
DjIdtGrNNy/oTyawjXMne1LW8oaed0ZPkkOBuwVUyG9K2kAkjwLA4Jp6gGhtaGLb
z8GmB5HZR+P/51FZW711oATEnkVm2UAsJ9RjH6gB5xjgWYcZHIOysHQ9sQGtKgI9
+68UGPW8+/0gF/xXzhur/sfZHUjUc3aOT1W/2343CGEZZstw3cL4vdsOi2bYD4Wi
jhX+YMhWftmeCcMIH+d85AR5qtTa9ToByMNozJOZ4Aw90wrmt36Jao4n36A9/Rbj
Ka45VcqhMb4yDyiORIUVw+QX6Lv4dTSu6toOYY/Bay8HVLd0eWh6e3mmpSCzGZW1
h7a/g7Ua7IjPlJirKCarAgMBAAGjggJ5MIICdTAOBgNVHQ8BAf8EBAMCBaAwHQYD
VR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAwHQYDVR0O
BBYEFDc0zCH81MbAqdmDiOhd+jHVdYmGMB8GA1UdIwQYMBaAFKhKamMEfd265tE5
t6ZFZe/zqOyhMG8GCCsGAQUFBwEBBGMwYTAuBggrBgEFBQcwAYYiaHR0cDovL29j
c3AuaW50LXgzLmxldHNlbmNyeXB0Lm9yZzAvBggrBgEFBQcwAoYjaHR0cDovL2Nl
cnQuaW50LXgzLmxldHNlbmNyeXB0Lm9yZy8wMAYDVR0RBCkwJ4IldXMtd2VzdC0y
LTEuYXdzLmNsb3VkMi5pbmZsdXhkYXRhLmNvbTBMBgNVHSAERTBDMAgGBmeBDAEC
ATA3BgsrBgEEAYLfEwEBATAoMCYGCCsGAQUFBwIBFhpodHRwOi8vY3BzLmxldHNl
bmNyeXB0Lm9yZzCCAQMGCisGAQQB1nkCBAIEgfQEgfEA7wB1APCVpFnyANGCQBAt
L5OIjq1L/h1H45nh0DSmsKiqjrJzAAABcSw2WPIAAAQDAEYwRAIgRKo082T1IVws
O0DaASbnqyd7EtVOJQ7zjzotL41B2fUCIDV7tZCmJpq0smbMWsDEiT4Luat2b3FD
B0D94pQ01JG+AHYAsh4FzIuizYogTodm+Su5iiUgZ2va+nDnsklTLe+LkF4AAAFx
LDZY5wAABAMARzBFAiEAvOyZ7WfxSdZGW1LVjBY//7lcc/XApxmj9KOC3K63HNEC
IF+3feU+YhhpwUSTM7nWJsRtdipqZwkC0wUaO3dbvDNLMA0GCSqGSIb3DQEBCwUA
A4IBAQBOvhaHWaYTGJWqVpWqTOOFyloEdPojQTyhTzwBfF7Xz92uNbhsxjTK6/sj
TZpLailqn6h1ZlJPFgI3GeoXV4V8u44m5eDCNvfeCDah7dJ+3yTYju6//xW9KjqL
61jK2Sy9afeL6taoMQCzufW9A20MZjX0/p69G61bBdB5q5udb3+Tw1U3gQj7x4Yq
bKc8dsB1qUprccrcAyo9sSxT7Egxg2gLPwoCigVkcibA5UkEBluhppsLIMkITT9w
MVX9QhdrlHuqBX2AY+bl1dpl++Xo3zQbFjQFnscaEI6k5PtdjLPNsoTwb+GXmfik
Q1gdRSr3uouBOfuJK9iz0MKWu+Qa
-----END CERTIFICATE-----
)EOF";

and the connection worked.

Thanks for your work 🎉

Selfsigned certificate issue on ESP8266

Hi Tobias,

First off awesome job on the library here. However I can't seem to get the library working with a selfsigned cert over SSL. I tried enabling line 30 in the InfluxDBclient.cpp which gave me following output on the monitor:

23:54:59.966 -> [D] Validating connection to https://192.168.0.3:8086/ping?verbose=true
23:55:00.170 -> [D] HTTP status code - -1
23:55:00.170 -> [E] Error - connection refused
23:55:00.170 -> InfluxDB connection failed: connection refused

My Influxdb is running on a raspberry pi, connecton is sucessfull:

  • Without https, using the WemosD Mini ESP8266 controller
  • With https on the raspberry itself wtith the connectin string client = InfluxDBClient(host='192.168.0.3', port=8086, database='test', username='Omitted', password='Omitted', ssl=True)

However using the code provided I can't seem to get it make a succesfull connection, the reponse is "connection refused". Further looking into the logs I get following error: apr 03 23:36:00 raspberrypi influxd[4730]: 2020/04/03 23:36:00 http: TLS handshake error from 192.168.0.130:62296: tls: oversized record received with length 21536.

I was wondering, could this have something to do with the -unsafeSsl flag that is set in the "normal" selsigned connections to the database, (https://docs.influxdata.com/influxdb/v1.7/administration/https_setup/)

I've included my sketch in attachment, do you have any idea whats going wrong as it does seem to work on your end?
SensorToInflux.txt

Extend library for simplified read of database

Can you add a function to use the same influx object, but send a query and output the result?

The code works great for writing my values to the database, but I am struggling because I want to use information in the last entry to modify the query to a different webpage. If a new function is not appropriate, can you direct me to a standalone Arduino example of submitting a query to an InfluxDB? Thank you

_time or _timestamp in InfluxData.h

There is a little mismatch between the variables name here:

void setTimestamp(long int seconds)
{
_timestamp = " " + String(seconds) + "000000000";
}`

String toString() const { return _measurement + _tags + _values + _time; }

private:
String _measurement;
String _tags;
String _values;
String _timestamp;
};

I solved changing from _time to _timestamp

vector: no such file or directory

On linux (arch), installing latest arduino download from website. I get the following error:

In file included from /home/jmorris/Arduino/libraries/ESP8266_Influxdb/src/InfluxDbClient.h:33:0,
                 from /home/jmorris/commonDrive/CloudStation/docs/Arduino/influx_write/influx_write.ino:28:
/home/jmorris/Arduino/libraries/ESP8266_Influxdb/src/query/FluxParser.h:30:10: fatal error: vector: No such file or directory
 #include <vector>
          ^~~~~~~~
compilation terminated.

I've tried installing libaries 'Vector', 'ArduinoSTL' and others. Nothing enables vector support that this library uses.

Granted im a newbie and may be making a dumb mistake, but the instructions should say at least SOMETHING about installing vector support for people who start with vanilla install.

Release of Bugfixes

Hi @tobiasschuerg,

it would be nice if you release a bugfix version of your library. The current 2.0.0 release have a few issues which have been already fixed, but are currently not being distributed.

Thanks.

invalid conversion type influxdb_port

Hello!

if i change the port, the compiler will break. i try to change the data type but no success.

any ideas? :(

here my log:

Arduino: 1.8.10 (Linux), Board: "NodeMCU 1.0 (ESP-12E Module), 160 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), 4MB (FS:2MB OTA:~1019KB), 2, v2 IPv6 Higher Bandwidth, Disabled, None, Only Sketch, 115200"

bme280influxdb:16:45: error: invalid conversion from 'const char*' to 'uint16_t {aka short unsigned int}' [-fpermissive]
Influxdb influx(INFLUXDB_HOST, INFLUXDB_PORT);
^
In file included from /home/wynton/Arduino/bme280influxdb/bme280influxdb.ino:6:0:
/home/wynton/Arduino/libraries/ESP8266_Influxdb/InfluxDb.h:24:3: error: initializing argument 2 of 'Influxdb::Influxdb(String, uint16_t)' [-fpermissive]
Influxdb(String host, uint16_t port = 8086);
^

exit status 1
invalid conversion from 'const char*' to 'uint16_t {aka short unsigned int}' [-fpermissive]

Tag value with spaces

How to write in the code when I need spaces in tag values?

. Backslash charactersdoes not work.

thx, Miro

Escaping Characters
If a measurement, tag key, tag value, or field key contains a space , comma ,, or an equals sign = it must be escaped using the backslash character . Backslash characters do not need to be escaped.

Buffer on SPFFIS or SD Card

Hi Tobias,
it should be good having the option to store buffer in SPFFIS or SD Card for data sampled each minute or more, so it's possible to put ESP in deepsleep without losing buffered data.
Regards,
Andrea

ESPAsyncTCP support

I like the way your lib provides access to the features of InfluxDB, especially the support of multiple values/tags of a measurement.
I'm working on a ESPurna based gateway from Jeelink compatible temperature sensor towards MQTT and Influx. I'm using your lib.
Basically it is working, but from time to time I experience the system to stop.
I wonder if this is caused by some timing and race conditions.

Is it possible to add ESPAsyncTCP support?

Help needed... Trying to write measurements with the same timestamp

So I have tried writing a set of measurement to influxDB with the same timestamp. I have not used the buffer yet, that's next.
Using indivule point writes to influx, setting 16 measurement takes over 3 seconds. So I want the timestamp to be the same on each of them.

My idea was to use this code:

Point pointItem(Item::unit());
pointItem.setTime(thisEpoch);
pointItem.addTag("instance",Item::name);     
pointItem.addField("value", i.val());
client.writePoint(pointItem)

This is part of a templated ApplyEach() to plot all measurement from a smart meter structure.
The timeEpoch = now() and the time is synchronized with the UTC time.

Now without the setTime it works just fine. It writes the measurements to the influxdb instance, and all is happy.
But once I start to use setTime(thisEpoch) then it just fails.

Here is some of the debug I captures:
[23:12:39][ 16256| 15016] epoch ( 180): Amsterdam time:Tuesday, 30-Jun-2020 23:12:39 CEST
[23:12:39][ 15584| 14368] epoch ( 181): UTC time:Tuesday, 30-Jun-2020 21:12:39 UTC
[23:12:39][ 15584| 14368] handleInflux( 107): Epoc = 1593551559 (this) 1593558759 (NL) 1593551559 (UTC)
[23:12:39][ 15504| 14368] apply ( 80): Writing to influxdb:kWh,instance=energy_delivered_tariff1 value=10515.55
[23:12:39][ 18192| 15664] apply ( 80): Writing to influxdb:kWh,instance=energy_delivered_tariff2 value=11462.46
[23:12:39][ 18000| 15664] apply ( 80): Writing to influxdb:kWh,instance=energy_returned_tariff1 value=79.45
[23:12:40][ 17592| 15664] apply ( 80): Writing to influxdb:kWh,instance=energy_returned_tariff2 value=208.27

I am using ezTime to do my TZ math...

So how do I debug this?

TSL handshake error

I'm trying to set up a Secure Connection to an InfluxDB 1 server with an ESP8266, but I keep getting
a TSL handshake error. I was able to get a raspberry pi and grafana to connect to this InfluxDB server so I don't suspect that there is anything wrong with the InfluxDB setup.

on the server and the following output from the ESP6266....

11:11:39.421 -> ......................[D] Validating connection to https://192.168.0.100:8086/ping?verbose=true
11:11:45.998 -> [D] HTTP status code - -1
11:11:45.998 -> [E] Error - connection refused
11:11:45.998 -> 0[D] Validating connection to https://192.168.0.100:8086/ping?verbose=true
11:11:46.098 -> [D] HTTP status code - -1
11:11:46.098 -> [E] Error - connection refused
11:11:46.098 -> InfluxDB connection failed: connection refused
11:11:46.098 -> Writing: wifi_status,device=ESP8266,SSID=Acanac_9XEzV rssi=-56i
11:11:46.098 -> [D] Flushing buffer: is oversized true, is timeout false, is buffer full false
11:11:46.098 -> [D] Prepare batch: bufferPointer: 1, batchPointer: 0, ceiling 1
11:11:46.098 -> [D] Prepare batch size 1
11:11:46.098 -> [D] Writing batch, size 1
11:11:46.098 -> [D] Writing to https://192.168.0.100:8086/write?db=test&u=james&p=Password123
11:11:46.098 -> [D] Sending:
11:11:46.098 -> wifi_status,device=ESP8266,SSID=Acanac_9XEzV rssi=-56i
11:11:46.098 ->
11:11:46.198 -> [D] HTTP status code - -1
11:11:46.198 -> [E] Error - connection refused
11:11:46.198 -> [D] Leaving data in buffer for retry
11:11:46.198 -> InfluxDB write failed: connection refused
11:11:46.198 -> Wait 10s
11:11:56.232 -> Writing: wifi_status,device=ESP8266,SSID=Acanac_9XEzV rssi=-58i
11:11:56.232 -> [D] Flushing buffer: is oversized true, is timeout false, is buffer full false
11:11:56.232 -> [D] Prepare batch: bufferPointer: 2, batchPointer: 0, ceiling 2
11:11:56.232 -> [D] Prepare batch size 1
11:11:56.232 -> [D] Writing batch, size 1
11:11:56.232 -> [D] Writing to https://192.168.0.100:8086/write?db=test&u=james&p=Password123
11:11:56.232 -> [D] Sending:
11:11:56.232 -> wifi_status,device=ESP8266,SSID=Acanac_9XEzV rssi=-56i
11:11:56.232 ->
11:11:56.332 -> [D] HTTP status code - -1
11:11:56.332 -> [E] Error - connection refused
11:11:56.332 -> [D] Leaving data in buffer for retry
11:11:56.332 -> InfluxDB write failed: connection refused
11:11:56.332 -> Wait 10s


here is the code..

My_SecureWrite.zip

Can't connect with Infludb server 1.7.10 running locally

I'm using nodemcu with this library which is working fine for the sketch "Secure write" to write data to Influx DB cloud v2. But the "Basic write" is throwing an error.
Local Influxdb server is running on the pc which is connected to same network as that of nodemcu.
Here is the arduino sketch:

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

#include <InfluxDbClient.h>
#define INFLUXDB_CLIENT_DEBUG

// WiFi AP SSID
#define WIFI_SSID "ssid"
// WiFi password
#define WIFI_PASSWORD "sciences"
// InfluxDB  server url. Don't use localhost, always server name or ip address.
// For InfluxDB 1 e.g. http://192.168.1.48:8086
#define INFLUXDB_URL "http://192.168.43.125:8086"

// InfluxDB v1 database name 
#define INFLUXDB_DB_NAME "mydb"

// InfluxDB client instance for InfluxDB 1
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);

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

void setup() {
  Serial.begin(115200);

  // Connect WiFi
  Serial.println("Connecting to WiFi");
  WiFi.mode(WIFI_STA);
  wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
  while (wifiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    delay(100);
  }
  Serial.println();

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

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

void loop() {
  // Store measured value into point
  sensor.clearFields();
  // Report RSSI of currently connected network
  sensor.addField("rssi", WiFi.RSSI());
  // Print what are we exactly writing
  Serial.print("Writing: ");
  Serial.println(sensor.toLineProtocol());
  // If no Wifi signal, try to reconnect it
  if ((WiFi.RSSI() == 0) && (wifiMulti.run() != WL_CONNECTED))
    Serial.println("Wifi connection lost");
  // Write point
  if (!client.writePoint(sensor)) {
    Serial.print("InfluxDB write failed: ");
    Serial.println(client.getLastErrorMessage());
  }

  //Wait 10s
  Serial.println("Wait 10s");
  delay(10000);
}

I haven't used any auth/user with my measurement "mydb". This is the error:

InfluxDB connection failed: connection refused
Writing: wifi_status,device=ESP8266,SSID=ssid rssi=-49i
InfluxDB write failed: connection refused

Support String in addValue(String key, String value)

I have added new method in InfluxData.h to suport also String as a value.
I needed to add changing access points MAC address, or changing DHCP IP address so it's not a tag but a value.
Please consider to add it also your lib.
thanks

void addValue(String key, String value) { _values = (_values == "") ? (" ") : (_values += ","); _values += key + "=\"" + value + "\""; }

Query error with InfluxDB v1.8.0

I'm trying to query an InfluxDb database (v1.8.0) with the use of ESP8266 but during this process the query fails and I get the following error: 404 page not found

I also tested the Flux query with Cronograph and it seems to work without any problems, while importing this string into the code it doesn't seem to work anymore.

for information purpose I leave my current code:

#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;



#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>

// WiFi AP SSID
#define WIFI_SSID         "WIFI_SSID"
// WiFi password
#define WIFI_PASSWORD     "WIFI_PASSWORD"

#define INFLUXDB_URL      "http://192.168.5.125:8086"
#define INFLUXDB_DB_NAME  "database_name"
#define INFLUXDB_USER     "user"
#define INFLUXDB_PASSWORD "passwd"


#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"

InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);



//--SETUP--
void setup() {
  Serial.begin(9600);

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

  client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DB_NAME, INFLUXDB_USER, INFLUXDB_PASSWORD);
  
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.print(WiFi.localIP());

  Serial.println();
  
  Serial.print("Singnal strength:");
  Serial.print(WiFi.RSSI());
  Serial.print("dBm");
  
  Serial.println();

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

  Serial.println();
}



//--LOOP--
void loop() {

  VALUE();

  Serial.println("Wait 10s");
  delay(10000);
}



//--VALUE1--
void VALUE() {
  
  String query = "from(bucket: \"database_name/autogen\") |> range(start: -1h) |> filter(fn: (r) => r._measurement == \"measurement_name\" and (r._field == \"value_name\")) |> bottom(n:1)";

  // Print composed query
  Serial.print("Querying with: ");
  Serial.println(query);

  // Send query to the server and get result
  FluxQueryResult result = client.query(query);

  while (result.next()) {
  long value = result.getValueByName("_value").getLong();
  Serial.print(value);

  Serial.println();

  }    

  if(result.getError() != "") {
    Serial.print("Query result error: ");
    Serial.println(result.getError());
    }
    
  result.close();
}

Errores al probar la version 3.1.1

compile el ejemplo 'BasicWrite'

este es el log de la compilacion

Visual studio code 1.44
PlatformIO Core 4.3.2a1 Home 3.1.1

Verbose mode can be enabled via -v, --verbose option
CONFIGURATION: https://docs.platformio.org/page/boards/espressif32/esp32doit-devkit-v1.html
PLATFORM: Espressif 32 1.12.0 > DOIT ESP32 DEVKIT V1
HARDWARE: ESP32 240MHz, 320KB RAM, 4MB Flash
DEBUG: Current (esp-prog) External (esp-prog, iot-bus-jtag, jlink, minimodule, olimex-arm-usb-ocd, olimex-arm-usb-ocd-h, olimex-arm-usb-tiny-h, olimex-jtag-tiny, tumpa)
PACKAGES:

  • framework-arduinoespressif32 3.10004.200129 (1.0.4)
  • tool-esptoolpy 1.20600.0 (2.6.0)
  • toolchain-xtensa32 2.50200.80 (5.2.0)
    LDF: Library Dependency Finder -> http://bit.ly/configure-pio-ldf
    LDF Modes: Finder ~ chain, Compatibility ~ soft
    Found 27 compatible libraries
    Scanning dependencies...
    Dependency Graph
    |-- ESP8266 Influxdb 3.1.1
    | |-- HTTPClient 1.2
    | | |-- WiFi 1.0
    | | |-- WiFiClientSecure 1.0
    | | | |-- WiFi 1.0
    |-- WiFi 1.0
    Building in release mode
    Compiling .pio\build\esp32doit-devkit-v1\src\main.cpp.o
    Compiling .pio\build\esp32doit-devkit-v1\libe0a\ESP8266 Influxdb_ID1639\InfluxDbClient.cpp.o
    In file included from src\main.cpp:22:0:
    .pio/libdeps/esp32doit-devkit-v1/ESP8266 Influxdb_ID1639/src/InfluxDbClient.h:44:19: warning: missing terminating ' character
    #error AxTLS doesn't work
    ^
    In file included from .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:27:0:
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.h:44:19: warning: missing terminating ' character
    #error AxTLS doesn't work
    ^
    Compiling .pio\build\esp32doit-devkit-v1\FrameworkArduino\cbuf.cpp.o
    Compiling .pio\build\esp32doit-devkit-v1\FrameworkArduino\esp32-hal-adc.c.o
    In file included from .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:27:0:
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.h: In constructor 'Point::Point(String)':
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.h:103:12: error: 'Point::_measurement' will be initialized after [-Werror=reorder]
    String _measurement;
    ^
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.h:101:12: error: 'String Point::_tags' [-Werror=reorder]
    String _tags;
    ^
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:75:1: error: when initialized here [-Werror=reorder]
    Point::Point(String measurement):
    ^
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp: In member function 'void Point::setTime(WritePrecision)':
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:119:58: warning: format '%d' expects argument of type 'int', but argument 3 has type 'long unsigned int' [-Wformat=]
    sprintf(buff, "%06d000", micros()%1000000uL);
    ^
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:119:58: warning: format '%d' expects argument of type 'int', but argument 3 has type 'long unsigned int' [-Wformat=]
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:123:55: warning: format '%d' expects argument of type 'int', but argument 3 has type 'long unsigned int' [-Wformat=]
    sprintf(buff, "%06d", micros()%1000000uL);
    ^
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:123:55: warning: format '%d' expects argument of type 'int', but argument 3 has type 'long unsigned int' [-Wformat=]
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:127:51: warning: format '%d' expects argument of type 'int', but argument 3 has type 'long unsigned int' [-Wformat=]
    sprintf(buff, "%03d", millis()%1000u);
    ^
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:127:51: warning: format '%d' expects argument of type 'int', but argument 3 has type 'long unsigned int' [-Wformat=]
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp: In member function 'bool InfluxDBClient::flushBuffer()':
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:376:35: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
    while(data = prepareBatch(size)) {
    ^
    Compiling .pio\build\esp32doit-devkit-v1\FrameworkArduino\esp32-hal-bt.c.o
    Compiling .pio\build\esp32doit-devkit-v1\FrameworkArduino\esp32-hal-cpu.c.o
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp: At global scope:
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:58:15: warning: 'String escapeJSONString(String&)' declared 'static' but never defined [-Wunused-function]
    static String escapeJSONString(String &value);
    ^
    .pio\libdeps\esp32doit-devkit-v1\ESP8266 Influxdb_ID1639\src\InfluxDbClient.cpp:597:15: warning: 'String escapeTagValue(const char*)' defined
    but not used [-Wunused-function]
    static String escapeTagValue(const char *value) {
    ^
    cc1plus.exe: some warnings being treated as errors
    *** [.pio\build\esp32doit-devkit-v1\libe0a\ESP8266 Influxdb_ID1639\InfluxDbClient.cpp.o] Error 1
    ========================================================= [FAILED] Took 5.77 seconds =========================================================

ESP8266 BasicWrite compile error

When compiling BasicWrite for Adafruit Feather HUZZAH with ESP8266, receive the following error:


C:\Users\joschob\Documents\Arduino\libraries\InfluxDB-Client-for-Arduino-master\src\util\helpers.cpp: In function 'void timeSync(const char*, const char*, const char*, const char*)':

C:\Users\joschob\Documents\Arduino\libraries\InfluxDB-Client-for-Arduino-master\src\util\helpers.cpp:32:57: error: 'configTzTime' was not declared in this scope

configTzTime(tzInfo,ntpServer1, ntpServer2, ntpServer3);

                                                     ^

exit status 1
Error compiling for board Adafruit Feather HUZZAH ESP8266.


ESP8266 SecureBatchWrite compile error

When compiling SecureBatchWrite example code for Adafruit Feather HUZZAH with ESP8266, receive the following error (SecureWrite example code compile successful)-


C:\Users\joschob\AppData\Local\Temp\arduino_modified_sketch_336161\SecureBatchWrite.ino: In function 'void loop()':

SecureBatchWrite:99:14: error: too few arguments to function 'void timeSync(const char*, const char*, const char*, const char*)'

 timeSync();

          ^

In file included from C:\Users\joschob\Documents\Arduino\libraries\InfluxDB-Client-for-Arduino-master\src/InfluxDbClient.h:34:0,

             from C:\Users\joschob\AppData\Local\Temp\arduino_modified_sketch_336161\SecureBatchWrite.ino:25:

C:\Users\joschob\Documents\Arduino\libraries\InfluxDB-Client-for-Arduino-master\src/util/helpers.h:35:6: note: declared here

void timeSync(const char tzInfo, const char ntpServer1, const char* ntpServer2 = nullptr, const char* ntpServer3 = nullptr);

  ^

exit status 1
too few arguments to function 'void timeSync(const char*, const char*, const char*, const char*)'

Question: Is it possible to do bi-directional communication to InfluxDB?

Hi,
You did an awesome job on Arduino InfluxDB client. Thanks.

I wonder if I could trouble you with a question? InfluxDB is a fantastic historical storage system, but can it manage commands? For example an Arduino is monitoring temperatures, and it's also connected to an on/off fan. The fan control is manual and a user would send a command to turn it on/off remotely. Would the ON/OFF command need to be done in MQTT or REDIS, or is it possible to do it in InfluxDB ? If so how would you read the command in the Arduino ?

Again, thanks for all your good work.
Cheers
Pete

Cert changed again

Sooo.. they changed cert and fingerprint again?

//#define INFLUXDB_FINGER "16 0E 8D FE A4 1C E0 63 FB 75 F5 BB 63 8F 1B E3 3D 93 55 05"
#define INFLUXDB_FINGER "58 04 D0 88 2D 0A 38 D3 E2 A6 A2 F8 42 0E 0C A0 4F CC CF 13"

Have to reflash all my sensor devices ((

Any idea how this could be fixed?

InfluxDBClient::validateConnection fails for v1.x DBs

Hello, Thank you for creating and maintaining this library. I recently used version 3.1.2 to connect a ESP8266 to InfluxDB 1.6.4 running on a Raspberry Pi 3B+. I found a bug in the function InfluxDBClient::validateConnection().

When calling the validateConnection() function, an error is given which prevents connecting to the DB. The issue is that the expected return status is hard coded to 200 no matter the DB version 1 or 2. The comment on line 478 in src/InfluxDbClient.cpp gives a hint. Version 1.x DBs have a return code of 204, with or without the verbose option.

// on version 1.x /ping will by default return status code 204, without verbose

I modified my installed file src/InfluxDbClient.cpp to add a local variable (_expectedStatusCode). This variable is dependent on the DB version. See the modifications below. The modifications work well on my application.

Insert between lines 479 and 480:
int _expectedStatusCode = _dbVersion==2?200:204;

Line 492 modification:
postRequest(_expectedStatusCode);

Line 497 modification:
return _lastStatusCode == _expectedStatusCode;

1.0 API is not functional on last version

Hello
I verified that api 1.0 is no more functional in last version.
Compilation is ok but then I get a reboot every time it the esp8266 tries to write on db. On 2.0 the code is ok

WiFiNINA

Hello is it possible to support Arduino library WiFiNINA.h in place of ESP?

POST FAILED - Response: -1

I've been using the library for a couple of weeks with no issue, but since Friday I've been getting this error:

<- Response: -1 ""

POST FAILED

I'm running influxdb on my local computer. Any idea what's causing this?

Use a gloabl flag to enable/disable debug output

I'm trying to log data at ~50hz, and the serial debugging that is on and not possible to disable is a major performance issue.

Why is it a thing at all?

In general, libraries should never print at all, unless a debug flag is explicitly set.

unable to parse authentication credentials

Hi, using latest version of your library with old API, when I try to write a Point I get:

{"error":"unable to parse authentication credentials"}

Using version 3.1.0 it perfectly works.
*NOTE: i need to check for nan (not a number values) because using that values in influx.write function will crash the ESP.

Follow an extract of my scratch:

// # OMISSISS 
// Influx DB Data
#define INFLUXDB_HOST "192.168.1.112"
#define INFLUXDB_PORT 8086
#define INFLUXDB_NAME "test"
#define INFLUXDB_USER "test"
#define INFLUXDB_PASS "test"
#define INFLUXDB_DEVICE "DHT22"
#define INFLUXDB_SENSOR "esp_01s"
#define INFLUXDB_LOCATION "veranda"

// Libreria InfluxDb
#include <InfluxDb.h>

int errore=0;
String state="OK";

int statoRete = WL_DISCONNECTED;

// onDisconnect
WiFiEventHandler mDisConnectHandler;

// Influx
Influxdb influx(INFLUXDB_HOST);

bool writeMeasure(String table, float value, int error, String state) {
  
  InfluxData row(table);

  row.addTag("device", INFLUXDB_DEVICE);
  row.addTag("sensor", INFLUXDB_SENSOR);
  row.addTag("status", state);
  row.addTag("location", INFLUXDB_LOCATION);
  row.addField("value", value);
  row.addField("error", error);

  return influx.write(row);
}

/*
 * Update DHT Sensor data
 */
void aggiornaDatiSensore() {

  float t = dht.getTemperature();
  float h = dht.getHumidity();
  
  th.temperature = isnan(t) ? -273.15 : t;
  th.humidity =  isnan(h) ? -1 : h;
  errore = dht.getStatus();
  state = dht.getStatusString();

  if (errore != DHTesp::ERROR_NONE) {
    th.temperature = 0.0;
    th.humidity = 0.0;
  }

  writeMeasure("temperature", th.temperature, errore, state);
  writeMeasure("humidity", th.humidity, errore, state);
}


void onDisconnect(const WiFiEventStationModeDisconnected& event){
   statoRete = WL_DISCONNECTED;
}

void setup()
{
  // Serial.begin(115200);
  WiFi.hostname(HOSTNAME);
  
  // Imposto handler di disconnessione
  mDisConnectHandler = WiFi.onStationModeDisconnected(onDisconnect);

  // init dht
  dht.setup(DHTPIN, DHTesp::DHT22);

  // init Influx auth
  influx.setDbAuth(INFLUXDB_NAME, INFLUXDB_USER, INFLUXDB_PASS);

  // Init blynk connection
  Blynk.begin(DEVICE_TOKEN, WIFI_SSID, WIFI_PASS, blynkServer, BLYNK_SERVER_PORT);

  // DHT read inteval
  timer.setInterval(DHT_READ_DELAY, aggiornaDatiSensore);

  // blynk update
  timer.setInterval(DHT_SEND_DELAY, blynk_send_all);

}

void loop()
{

  timer.run();
  // Gestione timer
    Blynk.run();
}

error when I compile on NodeMCU 1.0

this is the message using the example "writing_single"

InfluxData.h:26:69: error: '_time' was not declared in this scope
String toString() const { return _measurement + _tags + _values + _time; }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.