Updated required libraries
This commit is contained in:
parent
7a97677e0d
commit
417493c8ba
895 changed files with 376142 additions and 1043 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
1147
firmware/libraries/APDS9930-master/src/APDS9930 2.cpp
Executable file
1147
firmware/libraries/APDS9930-master/src/APDS9930 2.cpp
Executable file
File diff suppressed because it is too large
Load diff
231
firmware/libraries/APDS9930-master/src/APDS9930 2.h
Executable file
231
firmware/libraries/APDS9930-master/src/APDS9930 2.h
Executable file
|
@ -0,0 +1,231 @@
|
||||||
|
/**
|
||||||
|
* @file APDS-9930.h
|
||||||
|
* @brief Library for the SparkFun APDS-9930 breakout board
|
||||||
|
* @author Shawn Hymel (SparkFun Electronics)
|
||||||
|
*
|
||||||
|
* @copyright This code is public domain but you buy me a beer if you use
|
||||||
|
* this and we meet someday (Beerware license).
|
||||||
|
*
|
||||||
|
* This library interfaces the Avago APDS-9930 to Arduino over I2C. The library
|
||||||
|
* relies on the Arduino Wire (I2C) library. to use the library, instantiate an
|
||||||
|
* APDS9930 object, call init(), and call the appropriate functions.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef APDS9930_H
|
||||||
|
#define APDS9930_H
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
/* Debug */
|
||||||
|
#define DEBUG 0
|
||||||
|
|
||||||
|
/* APDS-9930 I2C address */
|
||||||
|
#define APDS9930_I2C_ADDR 0x39
|
||||||
|
|
||||||
|
/* Command register modes */
|
||||||
|
#define REPEATED_BYTE 0x80
|
||||||
|
#define AUTO_INCREMENT 0xA0
|
||||||
|
#define SPECIAL_FN 0xE0
|
||||||
|
|
||||||
|
/* Error code for returned values */
|
||||||
|
#define ERROR 0xFF
|
||||||
|
|
||||||
|
/* Acceptable device IDs */
|
||||||
|
#define APDS9930_ID_1 0x12
|
||||||
|
#define APDS9930_ID_2 0x39
|
||||||
|
|
||||||
|
/* Misc parameters */
|
||||||
|
#define FIFO_PAUSE_TIME 30 // Wait period (ms) between FIFO reads
|
||||||
|
|
||||||
|
/* APDS-9930 register addresses */
|
||||||
|
#define APDS9930_ENABLE 0x00
|
||||||
|
#define APDS9930_ATIME 0x01
|
||||||
|
#define APDS9930_PTIME 0x02
|
||||||
|
#define APDS9930_WTIME 0x03
|
||||||
|
#define APDS9930_AILTL 0x04
|
||||||
|
#define APDS9930_AILTH 0x05
|
||||||
|
#define APDS9930_AIHTL 0x06
|
||||||
|
#define APDS9930_AIHTH 0x07
|
||||||
|
#define APDS9930_PILTL 0x08
|
||||||
|
#define APDS9930_PILTH 0x09
|
||||||
|
#define APDS9930_PIHTL 0x0A
|
||||||
|
#define APDS9930_PIHTH 0x0B
|
||||||
|
#define APDS9930_PERS 0x0C
|
||||||
|
#define APDS9930_CONFIG 0x0D
|
||||||
|
#define APDS9930_PPULSE 0x0E
|
||||||
|
#define APDS9930_CONTROL 0x0F
|
||||||
|
#define APDS9930_ID 0x12
|
||||||
|
#define APDS9930_STATUS 0x13
|
||||||
|
#define APDS9930_Ch0DATAL 0x14
|
||||||
|
#define APDS9930_Ch0DATAH 0x15
|
||||||
|
#define APDS9930_Ch1DATAL 0x16
|
||||||
|
#define APDS9930_Ch1DATAH 0x17
|
||||||
|
#define APDS9930_PDATAL 0x18
|
||||||
|
#define APDS9930_PDATAH 0x19
|
||||||
|
#define APDS9930_POFFSET 0x1E
|
||||||
|
|
||||||
|
|
||||||
|
/* Bit fields */
|
||||||
|
#define APDS9930_PON 0b00000001
|
||||||
|
#define APDS9930_AEN 0b00000010
|
||||||
|
#define APDS9930_PEN 0b00000100
|
||||||
|
#define APDS9930_WEN 0b00001000
|
||||||
|
#define APSD9930_AIEN 0b00010000
|
||||||
|
#define APDS9930_PIEN 0b00100000
|
||||||
|
#define APDS9930_SAI 0b01000000
|
||||||
|
|
||||||
|
/* On/Off definitions */
|
||||||
|
#define OFF 0
|
||||||
|
#define ON 1
|
||||||
|
|
||||||
|
/* Acceptable parameters for setMode */
|
||||||
|
#define POWER 0
|
||||||
|
#define AMBIENT_LIGHT 1
|
||||||
|
#define PROXIMITY 2
|
||||||
|
#define WAIT 3
|
||||||
|
#define AMBIENT_LIGHT_INT 4
|
||||||
|
#define PROXIMITY_INT 5
|
||||||
|
#define SLEEP_AFTER_INT 6
|
||||||
|
#define ALL 7
|
||||||
|
|
||||||
|
/* LED Drive values */
|
||||||
|
#define LED_DRIVE_100MA 0
|
||||||
|
#define LED_DRIVE_50MA 1
|
||||||
|
#define LED_DRIVE_25MA 2
|
||||||
|
#define LED_DRIVE_12_5MA 3
|
||||||
|
|
||||||
|
/* Proximity Gain (PGAIN) values */
|
||||||
|
#define PGAIN_1X 0
|
||||||
|
#define PGAIN_2X 1
|
||||||
|
#define PGAIN_4X 2
|
||||||
|
#define PGAIN_8X 3
|
||||||
|
|
||||||
|
/* ALS Gain (AGAIN) values */
|
||||||
|
#define AGAIN_1X 0
|
||||||
|
#define AGAIN_8X 1
|
||||||
|
#define AGAIN_16X 2
|
||||||
|
#define AGAIN_120X 3
|
||||||
|
|
||||||
|
/* Interrupt clear values */
|
||||||
|
#define CLEAR_PROX_INT 0xE5
|
||||||
|
#define CLEAR_ALS_INT 0xE6
|
||||||
|
#define CLEAR_ALL_INTS 0xE7
|
||||||
|
|
||||||
|
/* Default values */
|
||||||
|
#define DEFAULT_ATIME 0xED
|
||||||
|
#define DEFAULT_WTIME 0xFF
|
||||||
|
#define DEFAULT_PTIME 0xFF
|
||||||
|
#define DEFAULT_PPULSE 0x08
|
||||||
|
#define DEFAULT_POFFSET 0 // 0 offset
|
||||||
|
#define DEFAULT_CONFIG 0
|
||||||
|
#define DEFAULT_PDRIVE LED_DRIVE_100MA
|
||||||
|
#define DEFAULT_PDIODE 2
|
||||||
|
#define DEFAULT_PGAIN PGAIN_8X
|
||||||
|
#define DEFAULT_AGAIN AGAIN_1X
|
||||||
|
#define DEFAULT_PILT 0 // Low proximity threshold
|
||||||
|
#define DEFAULT_PIHT 50 // High proximity threshold
|
||||||
|
#define DEFAULT_AILT 0xFFFF // Force interrupt for calibration
|
||||||
|
#define DEFAULT_AIHT 0
|
||||||
|
#define DEFAULT_PERS 0x22 // 2 consecutive prox or ALS for int.
|
||||||
|
|
||||||
|
/* ALS coefficients */
|
||||||
|
#define DF 52
|
||||||
|
#define GA 0.49
|
||||||
|
#define B 1.862
|
||||||
|
#define C 0.746
|
||||||
|
#define D 1.291
|
||||||
|
|
||||||
|
/* State definitions */
|
||||||
|
enum {
|
||||||
|
NOTAVAILABLE_STATE,
|
||||||
|
NEAR_STATE,
|
||||||
|
FAR_STATE,
|
||||||
|
ALL_STATE
|
||||||
|
};
|
||||||
|
|
||||||
|
#ifdef _AVR_IO_H_
|
||||||
|
// Do not use this alias as it's deprecated
|
||||||
|
#define NA_STATE NOTAVAILABLE_STATE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* APDS9930 Class */
|
||||||
|
class APDS9930 {
|
||||||
|
public:
|
||||||
|
|
||||||
|
/* Initialization methods */
|
||||||
|
APDS9930();
|
||||||
|
~APDS9930();
|
||||||
|
bool init();
|
||||||
|
uint8_t getMode();
|
||||||
|
bool setMode(uint8_t mode, uint8_t enable);
|
||||||
|
|
||||||
|
/* Turn the APDS-9930 on and off */
|
||||||
|
bool enablePower();
|
||||||
|
bool disablePower();
|
||||||
|
|
||||||
|
/* Enable or disable specific sensors */
|
||||||
|
bool enableLightSensor(bool interrupts = false);
|
||||||
|
bool disableLightSensor();
|
||||||
|
bool enableProximitySensor(bool interrupts = false);
|
||||||
|
bool disableProximitySensor();
|
||||||
|
|
||||||
|
/* LED drive strength control */
|
||||||
|
uint8_t getLEDDrive();
|
||||||
|
bool setLEDDrive(uint8_t drive);
|
||||||
|
// uint8_t getGestureLEDDrive();
|
||||||
|
// bool setGestureLEDDrive(uint8_t drive);
|
||||||
|
|
||||||
|
/* Gain control */
|
||||||
|
uint8_t getAmbientLightGain();
|
||||||
|
bool setAmbientLightGain(uint8_t gain);
|
||||||
|
uint8_t getProximityGain();
|
||||||
|
bool setProximityGain(uint8_t gain);
|
||||||
|
bool setProximityDiode(uint8_t drive);
|
||||||
|
uint8_t getProximityDiode();
|
||||||
|
|
||||||
|
|
||||||
|
/* Get and set light interrupt thresholds */
|
||||||
|
bool getLightIntLowThreshold(uint16_t &threshold);
|
||||||
|
bool setLightIntLowThreshold(uint16_t threshold);
|
||||||
|
bool getLightIntHighThreshold(uint16_t &threshold);
|
||||||
|
bool setLightIntHighThreshold(uint16_t threshold);
|
||||||
|
|
||||||
|
/* Get and set interrupt enables */
|
||||||
|
uint8_t getAmbientLightIntEnable();
|
||||||
|
bool setAmbientLightIntEnable(uint8_t enable);
|
||||||
|
uint8_t getProximityIntEnable();
|
||||||
|
bool setProximityIntEnable(uint8_t enable);
|
||||||
|
|
||||||
|
/* Clear interrupts */
|
||||||
|
bool clearAmbientLightInt();
|
||||||
|
bool clearProximityInt();
|
||||||
|
bool clearAllInts();
|
||||||
|
|
||||||
|
/* Proximity methods */
|
||||||
|
bool readProximity(uint16_t &val);
|
||||||
|
|
||||||
|
/* Ambient light methods */
|
||||||
|
bool readAmbientLightLux(float &val);
|
||||||
|
bool readAmbientLightLux(unsigned long &val);
|
||||||
|
float floatAmbientToLux(uint16_t Ch0, uint16_t Ch1);
|
||||||
|
unsigned long ulongAmbientToLux(uint16_t Ch0, uint16_t Ch1);
|
||||||
|
bool readCh0Light(uint16_t &val);
|
||||||
|
bool readCh1Light(uint16_t &val);
|
||||||
|
|
||||||
|
//private:
|
||||||
|
|
||||||
|
/* Proximity Interrupt Threshold */
|
||||||
|
uint16_t getProximityIntLowThreshold();
|
||||||
|
bool setProximityIntLowThreshold(uint16_t threshold);
|
||||||
|
uint16_t getProximityIntHighThreshold();
|
||||||
|
bool setProximityIntHighThreshold(uint16_t threshold);
|
||||||
|
|
||||||
|
/* Raw I2C Commands */
|
||||||
|
bool wireWriteByte(uint8_t val);
|
||||||
|
bool wireWriteDataByte(uint8_t reg, uint8_t val);
|
||||||
|
bool wireWriteDataBlock(uint8_t reg, uint8_t *val, unsigned int len);
|
||||||
|
bool wireReadDataByte(uint8_t reg, uint8_t &val);
|
||||||
|
int wireReadDataBlock(uint8_t reg, uint8_t *val, unsigned int len);
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
BIN
firmware/libraries/Adafruit_APDS9960_Library/assets/board 2.jpg
Executable file
BIN
firmware/libraries/Adafruit_APDS9960_Library/assets/board 2.jpg
Executable file
Binary file not shown.
After Width: | Height: | Size: 285 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
firmware/libraries/Adafruit_BME280_Library/assets/board 2.jpg
Executable file
BIN
firmware/libraries/Adafruit_BME280_Library/assets/board 2.jpg
Executable file
Binary file not shown.
After Width: | Height: | Size: 431 KiB |
Binary file not shown.
Binary file not shown.
BIN
firmware/libraries/Adafruit_Unified_Sensor/.library 2.properties.icloud
Executable file
BIN
firmware/libraries/Adafruit_Unified_Sensor/.library 2.properties.icloud
Executable file
Binary file not shown.
156
firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor 2.h
Executable file
156
firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor 2.h
Executable file
|
@ -0,0 +1,156 @@
|
||||||
|
/*
|
||||||
|
* Copyright (C) 2008 The Android Open Source Project
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software< /span>
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Update by K. Townsend (Adafruit Industries) for lighter typedefs, and
|
||||||
|
* extended sensor support to include color, voltage and current */
|
||||||
|
|
||||||
|
#ifndef _ADAFRUIT_SENSOR_H
|
||||||
|
#define _ADAFRUIT_SENSOR_H
|
||||||
|
|
||||||
|
#ifndef ARDUINO
|
||||||
|
#include <stdint.h>
|
||||||
|
#elif ARDUINO >= 100
|
||||||
|
#include "Arduino.h"
|
||||||
|
#include "Print.h"
|
||||||
|
#else
|
||||||
|
#include "WProgram.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Intentionally modeled after sensors.h in the Android API:
|
||||||
|
* https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */
|
||||||
|
|
||||||
|
/* Constants */
|
||||||
|
#define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */
|
||||||
|
#define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */
|
||||||
|
#define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */
|
||||||
|
#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH)
|
||||||
|
#define SENSORS_MAGFIELD_EARTH_MAX (60.0F) /**< Maximum magnetic field on Earth's surface */
|
||||||
|
#define SENSORS_MAGFIELD_EARTH_MIN (30.0F) /**< Minimum magnetic field on Earth's surface */
|
||||||
|
#define SENSORS_PRESSURE_SEALEVELHPA (1013.25F) /**< Average sea level pressure is 1013.25 hPa */
|
||||||
|
#define SENSORS_DPS_TO_RADS (0.017453293F) /**< Degrees/s to rad/s multiplier */
|
||||||
|
#define SENSORS_GAUSS_TO_MICROTESLA (100) /**< Gauss to micro-Tesla multiplier */
|
||||||
|
|
||||||
|
/** Sensor types */
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */
|
||||||
|
SENSOR_TYPE_MAGNETIC_FIELD = (2),
|
||||||
|
SENSOR_TYPE_ORIENTATION = (3),
|
||||||
|
SENSOR_TYPE_GYROSCOPE = (4),
|
||||||
|
SENSOR_TYPE_LIGHT = (5),
|
||||||
|
SENSOR_TYPE_PRESSURE = (6),
|
||||||
|
SENSOR_TYPE_PROXIMITY = (8),
|
||||||
|
SENSOR_TYPE_GRAVITY = (9),
|
||||||
|
SENSOR_TYPE_LINEAR_ACCELERATION = (10), /**< Acceleration not including gravity */
|
||||||
|
SENSOR_TYPE_ROTATION_VECTOR = (11),
|
||||||
|
SENSOR_TYPE_RELATIVE_HUMIDITY = (12),
|
||||||
|
SENSOR_TYPE_AMBIENT_TEMPERATURE = (13),
|
||||||
|
SENSOR_TYPE_VOLTAGE = (15),
|
||||||
|
SENSOR_TYPE_CURRENT = (16),
|
||||||
|
SENSOR_TYPE_COLOR = (17)
|
||||||
|
} sensors_type_t;
|
||||||
|
|
||||||
|
/** struct sensors_vec_s is used to return a vector in a common format. */
|
||||||
|
typedef struct {
|
||||||
|
union {
|
||||||
|
float v[3];
|
||||||
|
struct {
|
||||||
|
float x;
|
||||||
|
float y;
|
||||||
|
float z;
|
||||||
|
};
|
||||||
|
/* Orientation sensors */
|
||||||
|
struct {
|
||||||
|
float roll; /**< Rotation around the longitudinal axis (the plane body, 'X axis'). Roll is positive and increasing when moving downward. -90°<=roll<=90° */
|
||||||
|
float pitch; /**< Rotation around the lateral axis (the wing span, 'Y axis'). Pitch is positive and increasing when moving upwards. -180°<=pitch<=180°) */
|
||||||
|
float heading; /**< Angle between the longitudinal axis (the plane body) and magnetic north, measured clockwise when viewing from the top of the device. 0-359° */
|
||||||
|
};
|
||||||
|
};
|
||||||
|
int8_t status;
|
||||||
|
uint8_t reserved[3];
|
||||||
|
} sensors_vec_t;
|
||||||
|
|
||||||
|
/** struct sensors_color_s is used to return color data in a common format. */
|
||||||
|
typedef struct {
|
||||||
|
union {
|
||||||
|
float c[3];
|
||||||
|
/* RGB color space */
|
||||||
|
struct {
|
||||||
|
float r; /**< Red component */
|
||||||
|
float g; /**< Green component */
|
||||||
|
float b; /**< Blue component */
|
||||||
|
};
|
||||||
|
};
|
||||||
|
uint32_t rgba; /**< 24-bit RGBA value */
|
||||||
|
} sensors_color_t;
|
||||||
|
|
||||||
|
/* Sensor event (36 bytes) */
|
||||||
|
/** struct sensor_event_s is used to provide a single sensor event in a common format. */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
int32_t version; /**< must be sizeof(struct sensors_event_t) */
|
||||||
|
int32_t sensor_id; /**< unique sensor identifier */
|
||||||
|
int32_t type; /**< sensor type */
|
||||||
|
int32_t reserved0; /**< reserved */
|
||||||
|
int32_t timestamp; /**< time is in milliseconds */
|
||||||
|
union
|
||||||
|
{
|
||||||
|
float data[4];
|
||||||
|
sensors_vec_t acceleration; /**< acceleration values are in meter per second per second (m/s^2) */
|
||||||
|
sensors_vec_t magnetic; /**< magnetic vector values are in micro-Tesla (uT) */
|
||||||
|
sensors_vec_t orientation; /**< orientation values are in degrees */
|
||||||
|
sensors_vec_t gyro; /**< gyroscope values are in rad/s */
|
||||||
|
float temperature; /**< temperature is in degrees centigrade (Celsius) */
|
||||||
|
float distance; /**< distance in centimeters */
|
||||||
|
float light; /**< light in SI lux units */
|
||||||
|
float pressure; /**< pressure in hectopascal (hPa) */
|
||||||
|
float relative_humidity; /**< relative humidity in percent */
|
||||||
|
float current; /**< current in milliamps (mA) */
|
||||||
|
float voltage; /**< voltage in volts (V) */
|
||||||
|
sensors_color_t color; /**< color in RGB component values */
|
||||||
|
};
|
||||||
|
} sensors_event_t;
|
||||||
|
|
||||||
|
/* Sensor details (40 bytes) */
|
||||||
|
/** struct sensor_s is used to describe basic information about a specific sensor. */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
char name[12]; /**< sensor name */
|
||||||
|
int32_t version; /**< version of the hardware + driver */
|
||||||
|
int32_t sensor_id; /**< unique sensor identifier */
|
||||||
|
int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */
|
||||||
|
float max_value; /**< maximum value of this sensor's value in SI units */
|
||||||
|
float min_value; /**< minimum value of this sensor's value in SI units */
|
||||||
|
float resolution; /**< smallest difference between two values reported by this sensor */
|
||||||
|
int32_t min_delay; /**< min delay in microseconds between events. zero = not a constant rate */
|
||||||
|
} sensor_t;
|
||||||
|
|
||||||
|
class Adafruit_Sensor {
|
||||||
|
public:
|
||||||
|
// Constructor(s)
|
||||||
|
Adafruit_Sensor() {}
|
||||||
|
virtual ~Adafruit_Sensor() {}
|
||||||
|
|
||||||
|
// These must be defined by the subclass
|
||||||
|
virtual void enableAutoRange(bool enabled) { (void)enabled; /* suppress unused warning */ };
|
||||||
|
virtual bool getEvent(sensors_event_t*) = 0;
|
||||||
|
virtual void getSensor(sensor_t*) = 0;
|
||||||
|
|
||||||
|
private:
|
||||||
|
bool _autoRange;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
229
firmware/libraries/Adafruit_Unified_Sensor/README 2.md
Executable file
229
firmware/libraries/Adafruit_Unified_Sensor/README 2.md
Executable file
|
@ -0,0 +1,229 @@
|
||||||
|
# Adafruit Unified Sensor Driver #
|
||||||
|
|
||||||
|
Many small embedded systems exist to collect data from sensors, analyse the data, and either take an appropriate action or send that sensor data to another system for processing.
|
||||||
|
|
||||||
|
One of the many challenges of embedded systems design is the fact that parts you used today may be out of production tomorrow, or system requirements may change and you may need to choose a different sensor down the road.
|
||||||
|
|
||||||
|
Creating new drivers is a relatively easy task, but integrating them into existing systems is both error prone and time consuming since sensors rarely use the exact same units of measurement.
|
||||||
|
|
||||||
|
By reducing all data to a single **sensors\_event\_t** 'type' and settling on specific, **standardised SI units** for each sensor family the same sensor types return values that are comparable with any other similar sensor. This enables you to switch sensor models with very little impact on the rest of the system, which can help mitigate some of the risks and problems of sensor availability and code reuse.
|
||||||
|
|
||||||
|
The unified sensor abstraction layer is also useful for data-logging and data-transmission since you only have one well-known type to log or transmit over the air or wire.
|
||||||
|
|
||||||
|
## Unified Sensor Drivers ##
|
||||||
|
|
||||||
|
The following drivers are based on the Adafruit Unified Sensor Driver:
|
||||||
|
|
||||||
|
**Accelerometers**
|
||||||
|
- [Adafruit\_ADXL345](https://github.com/adafruit/Adafruit_ADXL345)
|
||||||
|
- [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC)
|
||||||
|
- [Adafruit\_MMA8451\_Library](https://github.com/adafruit/Adafruit_MMA8451_Library)
|
||||||
|
|
||||||
|
**Gyroscope**
|
||||||
|
- [Adafruit\_L3GD20\_U](https://github.com/adafruit/Adafruit_L3GD20_U)
|
||||||
|
|
||||||
|
**Light**
|
||||||
|
- [Adafruit\_TSL2561](https://github.com/adafruit/Adafruit_TSL2561)
|
||||||
|
- [Adafruit\_TSL2591\_Library](https://github.com/adafruit/Adafruit_TSL2591_Library)
|
||||||
|
|
||||||
|
**Magnetometers**
|
||||||
|
- [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC)
|
||||||
|
- [Adafruit\_HMC5883\_Unified](https://github.com/adafruit/Adafruit_HMC5883_Unified)
|
||||||
|
|
||||||
|
**Barometric Pressure**
|
||||||
|
- [Adafruit\_BMP085\_Unified](https://github.com/adafruit/Adafruit_BMP085_Unified)
|
||||||
|
- [Adafruit\_BMP183\_Unified\_Library](https://github.com/adafruit/Adafruit_BMP183_Unified_Library)
|
||||||
|
|
||||||
|
**Humidity & Temperature**
|
||||||
|
- [DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library)
|
||||||
|
|
||||||
|
**Humidity, Temperature, & Barometric Pressure**
|
||||||
|
- [Adafruit_BME280_Library](https://github.com/adafruit/Adafruit_BME280_Library/)
|
||||||
|
|
||||||
|
**Orientation**
|
||||||
|
- [Adafruit_BNO055](https://github.com/adafruit/Adafruit_BNO055)
|
||||||
|
|
||||||
|
**All in one device**
|
||||||
|
- [Adafruit_LSM9DS0](https://github.com/adafruit/Adafruit_LSM9DS0_Library) (accelerometer, gyroscope, magnetometer)
|
||||||
|
- [Adafruit_LSM9DS1](https://github.com/adafruit/Adafruit_LSM9DS1/) (accelerometer, gyroscope, magnetometer)
|
||||||
|
|
||||||
|
|
||||||
|
## How Does it Work? ##
|
||||||
|
|
||||||
|
Any driver that supports the Adafruit unified sensor abstraction layer will implement the Adafruit\_Sensor base class. There are two main typedefs and one enum defined in Adafruit_Sensor.h that are used to 'abstract' away the sensor details and values:
|
||||||
|
|
||||||
|
**Sensor Types (sensors\_type\_t)**
|
||||||
|
|
||||||
|
These pre-defined sensor types are used to properly handle the two related typedefs below, and allows us determine what types of units the sensor uses, etc.
|
||||||
|
|
||||||
|
```
|
||||||
|
/** Sensor types */
|
||||||
|
typedef enum
|
||||||
|
{
|
||||||
|
SENSOR_TYPE_ACCELEROMETER = (1),
|
||||||
|
SENSOR_TYPE_MAGNETIC_FIELD = (2),
|
||||||
|
SENSOR_TYPE_ORIENTATION = (3),
|
||||||
|
SENSOR_TYPE_GYROSCOPE = (4),
|
||||||
|
SENSOR_TYPE_LIGHT = (5),
|
||||||
|
SENSOR_TYPE_PRESSURE = (6),
|
||||||
|
SENSOR_TYPE_PROXIMITY = (8),
|
||||||
|
SENSOR_TYPE_GRAVITY = (9),
|
||||||
|
SENSOR_TYPE_LINEAR_ACCELERATION = (10),
|
||||||
|
SENSOR_TYPE_ROTATION_VECTOR = (11),
|
||||||
|
SENSOR_TYPE_RELATIVE_HUMIDITY = (12),
|
||||||
|
SENSOR_TYPE_AMBIENT_TEMPERATURE = (13),
|
||||||
|
SENSOR_TYPE_VOLTAGE = (15),
|
||||||
|
SENSOR_TYPE_CURRENT = (16),
|
||||||
|
SENSOR_TYPE_COLOR = (17)
|
||||||
|
} sensors_type_t;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Sensor Details (sensor\_t)**
|
||||||
|
|
||||||
|
This typedef describes the specific capabilities of this sensor, and allows us to know what sensor we are using beneath the abstraction layer.
|
||||||
|
|
||||||
|
```
|
||||||
|
/* Sensor details (40 bytes) */
|
||||||
|
/** struct sensor_s is used to describe basic information about a specific sensor. */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
char name[12];
|
||||||
|
int32_t version;
|
||||||
|
int32_t sensor_id;
|
||||||
|
int32_t type;
|
||||||
|
float max_value;
|
||||||
|
float min_value;
|
||||||
|
float resolution;
|
||||||
|
int32_t min_delay;
|
||||||
|
} sensor_t;
|
||||||
|
```
|
||||||
|
|
||||||
|
The individual fields are intended to be used as follows:
|
||||||
|
|
||||||
|
- **name**: The sensor name or ID, up to a maximum of twelve characters (ex. "MPL115A2")
|
||||||
|
- **version**: The version of the sensor HW and the driver to allow us to differentiate versions of the board or driver
|
||||||
|
- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network
|
||||||
|
- **type**: The sensor type, based on **sensors\_type\_t** in sensors.h
|
||||||
|
- **max\_value**: The maximum value that this sensor can return (in the appropriate SI unit)
|
||||||
|
- **min\_value**: The minimum value that this sensor can return (in the appropriate SI unit)
|
||||||
|
- **resolution**: The smallest difference between two values that this sensor can report (in the appropriate SI unit)
|
||||||
|
- **min\_delay**: The minimum delay in microseconds between two sensor events, or '0' if there is no constant sensor rate
|
||||||
|
|
||||||
|
**Sensor Data/Events (sensors\_event\_t)**
|
||||||
|
|
||||||
|
This typedef is used to return sensor data from any sensor supported by the abstraction layer, using standard SI units and scales.
|
||||||
|
|
||||||
|
```
|
||||||
|
/* Sensor event (36 bytes) */
|
||||||
|
/** struct sensor_event_s is used to provide a single sensor event in a common format. */
|
||||||
|
typedef struct
|
||||||
|
{
|
||||||
|
int32_t version;
|
||||||
|
int32_t sensor_id;
|
||||||
|
int32_t type;
|
||||||
|
int32_t reserved0;
|
||||||
|
int32_t timestamp;
|
||||||
|
union
|
||||||
|
{
|
||||||
|
float data[4];
|
||||||
|
sensors_vec_t acceleration;
|
||||||
|
sensors_vec_t magnetic;
|
||||||
|
sensors_vec_t orientation;
|
||||||
|
sensors_vec_t gyro;
|
||||||
|
float temperature;
|
||||||
|
float distance;
|
||||||
|
float light;
|
||||||
|
float pressure;
|
||||||
|
float relative_humidity;
|
||||||
|
float current;
|
||||||
|
float voltage;
|
||||||
|
sensors_color_t color;
|
||||||
|
};
|
||||||
|
} sensors_event_t;
|
||||||
|
```
|
||||||
|
It includes the following fields:
|
||||||
|
|
||||||
|
- **version**: Contain 'sizeof(sensors\_event\_t)' to identify which version of the API we're using in case this changes in the future
|
||||||
|
- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network (must match the sensor\_id value in the corresponding sensor\_t enum above!)
|
||||||
|
- **type**: the sensor type, based on **sensors\_type\_t** in sensors.h
|
||||||
|
- **timestamp**: time in milliseconds when the sensor value was read
|
||||||
|
- **data[4]**: An array of four 32-bit values that allows us to encapsulate any type of sensor data via a simple union (further described below)
|
||||||
|
|
||||||
|
**Required Functions**
|
||||||
|
|
||||||
|
In addition to the two standard types and the sensor type enum, all drivers based on Adafruit_Sensor must also implement the following two functions:
|
||||||
|
|
||||||
|
```
|
||||||
|
bool getEvent(sensors_event_t*);
|
||||||
|
```
|
||||||
|
Calling this function will populate the supplied sensors\_event\_t reference with the latest available sensor data. You should call this function as often as you want to update your data.
|
||||||
|
|
||||||
|
```
|
||||||
|
void getSensor(sensor_t*);
|
||||||
|
```
|
||||||
|
Calling this function will provide some basic information about the sensor (the sensor name, driver version, min and max values, etc.
|
||||||
|
|
||||||
|
**Standardised SI values for sensors\_event\_t**
|
||||||
|
|
||||||
|
A key part of the abstraction layer is the standardisation of values on SI units of a particular scale, which is accomplished via the data[4] union in sensors\_event\_t above. This 16 byte union includes fields for each main sensor type, and uses the following SI units and scales:
|
||||||
|
|
||||||
|
- **acceleration**: values are in **meter per second per second** (m/s^2)
|
||||||
|
- **magnetic**: values are in **micro-Tesla** (uT)
|
||||||
|
- **orientation**: values are in **degrees**
|
||||||
|
- **gyro**: values are in **rad/s**
|
||||||
|
- **temperature**: values in **degrees centigrade** (Celsius)
|
||||||
|
- **distance**: values are in **centimeters**
|
||||||
|
- **light**: values are in **SI lux** units
|
||||||
|
- **pressure**: values are in **hectopascal** (hPa)
|
||||||
|
- **relative\_humidity**: values are in **percent**
|
||||||
|
- **current**: values are in **milliamps** (mA)
|
||||||
|
- **voltage**: values are in **volts** (V)
|
||||||
|
- **color**: values are in 0..1.0 RGB channel luminosity and 32-bit RGBA format
|
||||||
|
|
||||||
|
## The Unified Driver Abstraction Layer in Practice ##
|
||||||
|
|
||||||
|
Using the unified sensor abstraction layer is relatively easy once a compliant driver has been created.
|
||||||
|
|
||||||
|
Every compliant sensor can now be read using a single, well-known 'type' (sensors\_event\_t), and there is a standardised way of interrogating a sensor about its specific capabilities (via sensor\_t).
|
||||||
|
|
||||||
|
An example of reading the [TSL2561](https://github.com/adafruit/Adafruit_TSL2561) light sensor can be seen below:
|
||||||
|
|
||||||
|
```
|
||||||
|
Adafruit_TSL2561 tsl = Adafruit_TSL2561(TSL2561_ADDR_FLOAT, 12345);
|
||||||
|
...
|
||||||
|
/* Get a new sensor event */
|
||||||
|
sensors_event_t event;
|
||||||
|
tsl.getEvent(&event);
|
||||||
|
|
||||||
|
/* Display the results (light is measured in lux) */
|
||||||
|
if (event.light)
|
||||||
|
{
|
||||||
|
Serial.print(event.light); Serial.println(" lux");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
/* If event.light = 0 lux the sensor is probably saturated
|
||||||
|
and no reliable data could be generated! */
|
||||||
|
Serial.println("Sensor overload");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Similarly, we can get the basic technical capabilities of this sensor with the following code:
|
||||||
|
|
||||||
|
```
|
||||||
|
sensor_t sensor;
|
||||||
|
|
||||||
|
sensor_t sensor;
|
||||||
|
tsl.getSensor(&sensor);
|
||||||
|
|
||||||
|
/* Display the sensor details */
|
||||||
|
Serial.println("------------------------------------");
|
||||||
|
Serial.print ("Sensor: "); Serial.println(sensor.name);
|
||||||
|
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
|
||||||
|
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
|
||||||
|
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux");
|
||||||
|
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux");
|
||||||
|
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux");
|
||||||
|
Serial.println("------------------------------------");
|
||||||
|
Serial.println("");
|
||||||
|
```
|
176
firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.cpp
Executable file
176
firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.cpp
Executable file
|
@ -0,0 +1,176 @@
|
||||||
|
#include "Arduino.h"
|
||||||
|
#include "ESP8266Influxdb.h"
|
||||||
|
#include <ESP8266WiFi.h>
|
||||||
|
|
||||||
|
#define DEBUG_PRINT // comment this line to disable debug print
|
||||||
|
|
||||||
|
#ifndef DEBUG_PRINT
|
||||||
|
#define DEBUG_PRINT(a)
|
||||||
|
#else
|
||||||
|
#define DEBUG_PRINT(a) (Serial.println(String(F("[Debug]: "))+(a)))
|
||||||
|
#define _DEBUG
|
||||||
|
#endif
|
||||||
|
|
||||||
|
Influxdb::Influxdb(const char *host, uint16_t port) : WiFiClient() {
|
||||||
|
_port = port;
|
||||||
|
_host = host;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB_RESPONSE Influxdb::opendb(String db, String user, String password) {
|
||||||
|
_db = "db=" + db + "&u=" + user + "&p=" + password;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB_RESPONSE Influxdb::opendb(String db) {
|
||||||
|
_db = "db=" + db;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
DB_RESPONSE Influxdb::write(FIELD data) {
|
||||||
|
return write(data.postString());
|
||||||
|
}
|
||||||
|
|
||||||
|
DB_RESPONSE Influxdb::write(String data) {
|
||||||
|
if (!connect(_host, _port)) {
|
||||||
|
DEBUG_PRINT("connection failed");
|
||||||
|
_response = DB_CONNECT_FAILED;
|
||||||
|
return _response;
|
||||||
|
}
|
||||||
|
String postHead = "POST /write?" + _db + " HTTP/1.1\r\n";
|
||||||
|
postHead += "Host: " + String(_host) + ":" + String(_port) + "\r\n";
|
||||||
|
// postHead += "Content-Type: application/x-www-form-urlencoded\r\n";
|
||||||
|
postHead += "Content-Length: " + String(data.length()) + "\r\n\r\n";
|
||||||
|
|
||||||
|
DEBUG_PRINT("Writing data to " + String(_host) + ":" + String(_port));
|
||||||
|
print(postHead + data);
|
||||||
|
DEBUG_PRINT(postHead + data);
|
||||||
|
|
||||||
|
uint8_t t = 0;
|
||||||
|
// Check the reply whether writing is success or not
|
||||||
|
while (!available() && t < 200) {
|
||||||
|
delay(10);
|
||||||
|
t++;
|
||||||
|
}
|
||||||
|
if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out.
|
||||||
|
|
||||||
|
#if !defined _DEBUG
|
||||||
|
if (available()) {
|
||||||
|
_response = (findUntil("204", "\r")) ? DB_SUCCESS : DB_ERROR;
|
||||||
|
return _response;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
_response=DB_ERROR;
|
||||||
|
while (available()) {
|
||||||
|
String line = readStringUntil('\n');
|
||||||
|
if (line.substring(9,12)=="204")
|
||||||
|
_response = DB_SUCCESS;
|
||||||
|
DEBUG_PRINT("(Responsed): " + line);
|
||||||
|
}
|
||||||
|
return _response;
|
||||||
|
#endif
|
||||||
|
return DB_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB_RESPONSE Influxdb::query(String sql) {
|
||||||
|
|
||||||
|
if (!connect(_host, _port)) {
|
||||||
|
DEBUG_PRINT("connection failed");
|
||||||
|
_response = DB_CONNECT_FAILED;
|
||||||
|
return _response;
|
||||||
|
}
|
||||||
|
|
||||||
|
String url = "/query?";
|
||||||
|
#if defined _DEBUG
|
||||||
|
url += "pretty=true&";
|
||||||
|
#endif
|
||||||
|
url += _db;
|
||||||
|
url += "&q=" + URLEncode(sql);
|
||||||
|
DEBUG_PRINT("Requesting URL: ");
|
||||||
|
DEBUG_PRINT(url);
|
||||||
|
|
||||||
|
// This will send the request to the server
|
||||||
|
print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + _host +
|
||||||
|
":" + _port + "\r\n" + "Connection: close\r\n\r\n");
|
||||||
|
|
||||||
|
// Read all the lines of the reply from server and print them to Serial
|
||||||
|
uint8_t t = 0;
|
||||||
|
while (!available() && t < 200) {
|
||||||
|
delay(10);
|
||||||
|
t++;
|
||||||
|
}
|
||||||
|
if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out.
|
||||||
|
|
||||||
|
DEBUG_PRINT("Receiving....");
|
||||||
|
uint8_t i=0;
|
||||||
|
String line = readStringUntil('\n');
|
||||||
|
DEBUG_PRINT("[HEAD] " + line);
|
||||||
|
|
||||||
|
if (line.substring(9,12) == "200") {
|
||||||
|
while (available()) {
|
||||||
|
line = readStringUntil('\n');
|
||||||
|
DEBUG_PRINT("(HEAD) " + line);
|
||||||
|
if (i < 6 ) i++; else return _response;
|
||||||
|
}
|
||||||
|
_response = DB_SUCCESS;
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
_response = DB_ERROR;
|
||||||
|
#if defined _DEBUG
|
||||||
|
while (available()) {
|
||||||
|
line = readStringUntil('\n');
|
||||||
|
DEBUG_PRINT("[HEAD] " + line);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
return _response;
|
||||||
|
}
|
||||||
|
|
||||||
|
DB_RESPONSE Influxdb::response() {
|
||||||
|
return _response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -----------------------------------------------*/
|
||||||
|
// Field object
|
||||||
|
/* -----------------------------------------------*/
|
||||||
|
FIELD::FIELD(String m) {
|
||||||
|
measurement = m;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FIELD::empty() {
|
||||||
|
_data = "";
|
||||||
|
_tag = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
void FIELD::addTag(String key, String value) {
|
||||||
|
_tag += "," + key + "=" + value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FIELD::addField(String key, float value) {
|
||||||
|
_data = (_data == "") ? (" ") : (_data += ",");
|
||||||
|
_data += key + "=" + String(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
String FIELD::postString() {
|
||||||
|
// uint32_t utc = 1448114561 + millis() /1000;
|
||||||
|
return measurement + _tag + _data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// URL Encode with Arduino String object
|
||||||
|
String URLEncode(String msg) {
|
||||||
|
const char *hex = "0123456789abcdef";
|
||||||
|
String encodedMsg = "";
|
||||||
|
|
||||||
|
uint16_t i;
|
||||||
|
for (i = 0; i < msg.length(); i++) {
|
||||||
|
if (('a' <= msg.charAt(i) && msg.charAt(i) <= 'z') ||
|
||||||
|
('A' <= msg.charAt(i) && msg.charAt(i) <= 'Z') ||
|
||||||
|
('0' <= msg.charAt(i) && msg.charAt(i) <= '9')) {
|
||||||
|
encodedMsg += msg.charAt(i);
|
||||||
|
} else {
|
||||||
|
encodedMsg += '%';
|
||||||
|
encodedMsg += hex[msg.charAt(i) >> 4];
|
||||||
|
encodedMsg += hex[msg.charAt(i) & 15];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return encodedMsg;
|
||||||
|
}
|
72
firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.h
Executable file
72
firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.h
Executable file
|
@ -0,0 +1,72 @@
|
||||||
|
/* Influxdb library
|
||||||
|
|
||||||
|
MIT license
|
||||||
|
Written by HW Wong
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef INFLUXDB_H
|
||||||
|
#define INFLUXDB_H
|
||||||
|
#include "Arduino.h"
|
||||||
|
#include <ESP8266WiFi.h>
|
||||||
|
|
||||||
|
enum DB_RESPONSE {DB_SUCCESS, DB_ERROR, DB_CONNECT_FAILED};
|
||||||
|
|
||||||
|
// Url encode function
|
||||||
|
String URLEncode(String msg);
|
||||||
|
|
||||||
|
class FIELD
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
FIELD(String m);
|
||||||
|
|
||||||
|
String measurement;
|
||||||
|
|
||||||
|
void addField(String key, float value);
|
||||||
|
void addTag(String key, String value);
|
||||||
|
void empty();
|
||||||
|
String postString();
|
||||||
|
|
||||||
|
private:
|
||||||
|
String _data;
|
||||||
|
String _tag;
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
class Influxdb : private WiFiClient
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
Influxdb(const char* host, uint16_t port);
|
||||||
|
|
||||||
|
DB_RESPONSE opendb(String db);
|
||||||
|
DB_RESPONSE opendb(String db, String user, String password);
|
||||||
|
DB_RESPONSE write(FIELD data);
|
||||||
|
DB_RESPONSE write(String data);
|
||||||
|
DB_RESPONSE query(String sql);
|
||||||
|
//uint8_t createDatabase(char *dbname);
|
||||||
|
DB_RESPONSE response();
|
||||||
|
|
||||||
|
using WiFiClient::available;
|
||||||
|
using WiFiClient::read;
|
||||||
|
using WiFiClient::flush;
|
||||||
|
using WiFiClient::find;
|
||||||
|
using WiFiClient::findUntil;
|
||||||
|
using WiFiClient::peek;
|
||||||
|
using WiFiClient::readBytes;
|
||||||
|
using WiFiClient::readBytesUntil;
|
||||||
|
using WiFiClient::readString;
|
||||||
|
using WiFiClient::readStringUntil;
|
||||||
|
using WiFiClient::parseInt;
|
||||||
|
using WiFiClient::setTimeout;
|
||||||
|
|
||||||
|
private:
|
||||||
|
uint16_t _port;
|
||||||
|
const char* _host;
|
||||||
|
String _db;
|
||||||
|
DB_RESPONSE _response;
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
1
firmware/libraries/ESP8266Influxdb/README 2.md
Executable file
1
firmware/libraries/ESP8266Influxdb/README 2.md
Executable file
|
@ -0,0 +1 @@
|
||||||
|
# ESP8266Influxdb
|
Binary file not shown.
24
firmware/libraries/ESP8266Influxdb/keywords 2.txt
Executable file
24
firmware/libraries/ESP8266Influxdb/keywords 2.txt
Executable file
|
@ -0,0 +1,24 @@
|
||||||
|
##################################################
|
||||||
|
# Syntax Coloring Map For ESP8266 Influxdb library
|
||||||
|
##################################################
|
||||||
|
|
||||||
|
##################################################
|
||||||
|
# Datatypes (KEYWORD1)
|
||||||
|
##################################################
|
||||||
|
|
||||||
|
Influxdb KEYWORD1
|
||||||
|
FIELD KEYWORD1
|
||||||
|
DB_RESPOND KEYWORD1
|
||||||
|
|
||||||
|
##################################################
|
||||||
|
# Methods and Functions (KEYWORD2)
|
||||||
|
##################################################
|
||||||
|
|
||||||
|
addField KEYWORD2
|
||||||
|
addTag KEYWORD2
|
||||||
|
empty KEYWORD2
|
||||||
|
opendb KEYWORD2
|
||||||
|
write KEYWORD2
|
||||||
|
query KEYWORD2
|
||||||
|
postString KEYWORD2
|
||||||
|
response KEYWORD2
|
148
firmware/libraries/ESP8266_Influxdb/CHANGELOG.md
Normal file
148
firmware/libraries/ESP8266_Influxdb/CHANGELOG.md
Normal file
|
@ -0,0 +1,148 @@
|
||||||
|
# Changelog
|
||||||
|
## 3.12.1 [2022-08-29]
|
||||||
|
### Fixes
|
||||||
|
- [193](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/193) - Automatically adjusting point timestamp according to the setting of write precision.
|
||||||
|
|
||||||
|
## 3.12.0 [2022-03-21]
|
||||||
|
### Features
|
||||||
|
- [185](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/185) - Added diagnostic server connection state getter `bool InfluxDBClient::isConnected()`
|
||||||
|
|
||||||
|
## 3.11.0 [2022-02-18]
|
||||||
|
### Features
|
||||||
|
- [174](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/174),[181](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/181) - All API methods with a string param allow specifying string by all basic types:
|
||||||
|
- Arduino `String` class
|
||||||
|
- C `char *` or `char[]`
|
||||||
|
- Flash string using `F`,`PSTR` or `FPSTR` macros
|
||||||
|
### Fixes
|
||||||
|
- [176](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/176) - Cleared all compiler warnings
|
||||||
|
|
||||||
|
## 3.10.0 [2022-01-20]
|
||||||
|
### Features
|
||||||
|
- [167](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/167) - Added `InfluxDBClient::writeRecord(const char *record)`.
|
||||||
|
- [167](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/167) - Added possibility to disable retrying by setting `maxRetryAttempts` to zero: `client.setWriteOptions(WriteOptions().maxRetryAttempts(0));`
|
||||||
|
- [172](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/172) - Added directly streaming batch for write. It can be enabled by `InfluxDBClient::setStreamWrite(bool enable = true)`. Writing by streaming lines of batch saves RAM as it sends data without allocating a buffer. On the other hand, this way of writing is about half times slower than the classic way, when allocating the buffer for writing the whole batch.
|
||||||
|
- [172](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/172) - Allowing larger batch size, > 255.
|
||||||
|
- [173](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/173) - Added Flux query parameters. Now supported by InfluxDB Cloud only.
|
||||||
|
|
||||||
|
## 3.9.0 [2021-09-17]
|
||||||
|
### Features
|
||||||
|
- [#147](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/147) - Updated InfluxDB 2 Cloud CA root certificate to _ISRG Root X1_.
|
||||||
|
Current InfluxDB 2 Cloud CA root certificate _DST Root CA X3_ expires on September 30th 2021!
|
||||||
|
- [#157](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/157) - Added Buckets sub-client for managing buckets in InfluxDB 2.
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- [#150](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/150) - `HTTPOptions::httpReadTimeout` is also set as the connect timeout for HTTP connection on ESP32. It also works for HTTPS connection since ESP32 Arduino Core 2.0.0.
|
||||||
|
- [#156](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/156) - Correctly rounding _writeBufferSize_, when _bufferSize/batchSize >= 256_.
|
||||||
|
- [#162](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/162) - Fixed flushing of not full buffer after the flush timeout.
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
- [#163](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/163) - More precise description of supported devices.
|
||||||
|
|
||||||
|
## 3.8.0 [2021-04-01]
|
||||||
|
### Features
|
||||||
|
- [#143](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/143) - `InfluxDBClient::setInsecure` now works also for ESP32. Requires Arduino ESP32 SDK 1.0.5 or higher
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
- [#134](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/134):
|
||||||
|
- Added untrusted connection (skipping certificate validation) info to Readme
|
||||||
|
- `SecureWrite` and `SecureBatchWrite` demos enhanced with example about using untrusted connection
|
||||||
|
- Various fixes of typos
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- [#137](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/137) - Fixed parsing Flux response with unexpected annotations
|
||||||
|
|
||||||
|
## 3.7.0 [2020-12-24]
|
||||||
|
### Features
|
||||||
|
- [#125](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/124) - Added credentials to the InfluxDB 1.x validation endpoint (/ping). To leverage this, [enable ping authentication](https://docs.influxdata.com/influxdb/v1.8/administration/config/#ping-auth-enabled-false)
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- [#129](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/129) - Updated InfluxDB 2 Cloud CA certificate to trust servers from all cloud providers (AWS, Azure, GCP)
|
||||||
|
|
||||||
|
## 3.6.1 [2020-11-30]
|
||||||
|
### Features
|
||||||
|
### Fixes
|
||||||
|
- [#121](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/121) - Fixed compile error in case of warning is treated as an error
|
||||||
|
- [#122](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/122) - Deleting WiFiClient instance to avoid memory leaking when the InfluxDBClient is reinitialized
|
||||||
|
- [#124](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/124) - Fixed compilation warnings
|
||||||
|
|
||||||
|
### Doc
|
||||||
|
- [#120](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/120) - Improved language wording in the Readme
|
||||||
|
|
||||||
|
## 3.6.0 [2020-11-10]
|
||||||
|
### Features
|
||||||
|
- [#117](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/117) - Added `InfluxDBClient::pointToLineProtocol(const Point& point)` for simple creation of InfluxDB line-protocol string with respect to default tags
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- [#114](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/114) - Renamed `getRemaingRetryTime()`->`getRemainingRetryTime()`
|
||||||
|
- [#115](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/115) - Restored writing capability after a connection failure
|
||||||
|
- [#118](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/118) - Added escaping of URL params (org, bucker, V1 username and pass)
|
||||||
|
|
||||||
|
## 3.5.0 [2020-10-30]
|
||||||
|
### Features
|
||||||
|
- [#107](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/107) - Added possibility to set default tags. Use `WriteOptions::addDefaultTag()` to add a tag that will be added to each written point using the `writePoint()` function.
|
||||||
|
- [#109](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/109) - Retry strategy improvements:
|
||||||
|
- Added `canSendRequest()` function to check if retry strategy is applied
|
||||||
|
- Added `getRemaingRetryTime()` function to get wait time before another request (write/query) can be sent
|
||||||
|
- Removed applying retry wait time in case of network error
|
||||||
|
- Better explanatory error message when a request is about to be sent in the retry wait state
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- [#108](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/108) - Added optional param for specifying decimal places of double.: `void Point::addField(String name, double value, int decimalPlaces = 2)`
|
||||||
|
- [#111](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/111) - Fixed blocked writing after another point reached max retry count (#110)
|
||||||
|
|
||||||
|
## 3.4.0 [2020-10-02]
|
||||||
|
### Features
|
||||||
|
- [#89](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/89) - ESP8266 only - Added Max Fragment Length Negotiation for TLS communication to reduce memory allocation. If server supports MFLN, it saves ~10kB. Standalone InfluxDB OSS server doesn't support MFLN, Cloud yes. To leverage MFLN for standalone OSS, a reverse proxy needs to be used.
|
||||||
|
- [#91](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/91) - Improved API for settings of write and HTTP options:
|
||||||
|
- Introduced `WriteOptions` to wrap the write related options (write precision, batch-size, etc). It offers fluent style API allowing to change only the required options. `InfluxDBClient` has overloaded `setWriteOptions(const WriteOptions& writeOptions)` method.
|
||||||
|
- Introduced `HTTPOptions` to wrap the HTTP related options (e.g. reusing connection). It offers fluent style API allowing to change only the required options. `InfluxDBClient` has `setHTTPOptions(const HTTPOptions& httpOptions)` method.
|
||||||
|
- Added possibility to set HTTP response read timeout (part of the `HTTPOptions`).
|
||||||
|
- Method `InfluxDBClient::void setWriteOptions(WritePrecision precision, uint16_t batchSize = 1, uint16_t bufferSize = 5, uint16_t flushInterval = 60, bool preserveConnection = true)` is deprecated and it will be removed in the next release.
|
||||||
|
- [#93](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/93) - Write logic improvements
|
||||||
|
- Retry on failure logic unification with other InfluxDB clients (exponential retry, max retry count 3, max retry interval)
|
||||||
|
- Better write buffer memory management
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
- [#87](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/87) - Fixed include file name in the Readme
|
||||||
|
- [#99](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/99) - Changed default InfluxDB 2 port from 9999 to 8086 (default since InfluxDB 2 RC0)
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
- [#90](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/90) - Fixed boolean type recognition of InfluxDB Flux
|
||||||
|
- [#101](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/101) - Better memory efficient point line composition
|
||||||
|
|
||||||
|
## Version 3.3.0 (2020-07-07)
|
||||||
|
- [NEW] Added possibility skip server certification validation (`setInsecure()` method)
|
||||||
|
- [NEW] Added possibility to query flux on secured InfluxDB 1.8 using V1 approach
|
||||||
|
- [NEW] `validateConnection()` can be used also for the [forward compatibility](https://docs.influxdata.com/influxdb/latest/tools/api/#influxdb-2-0-api-compatibility-endpoints) connection to InfluxDB 1.8
|
||||||
|
- [FIX] More precise default timestamp generating, up to microseconds
|
||||||
|
- [FIX] Debug compilation error
|
||||||
|
- [FIX] SecureBatchWrite compile error
|
||||||
|
|
||||||
|
## Version 3.2.0 (2020-06-09)
|
||||||
|
- [NEW] Added possibility to read data from InfluxDB using Flux queries
|
||||||
|
- [NEW] `timeSync` utility function for synchronous time synchronization using NTP
|
||||||
|
- [FIX] Properly initialize member variable (#59)
|
||||||
|
- [FIX] ASCII chars & compilation warning fix (#60)
|
||||||
|
- [Update] ESP8266 SDK 2.7+ required
|
||||||
|
|
||||||
|
## Version 3.1.3 (2020-04-27)
|
||||||
|
- [FIX] SecureWrite crash (#54)
|
||||||
|
|
||||||
|
## Version 3.1.2 (2020-04-18)
|
||||||
|
- [FIX] Compilation error on fields order (#43)
|
||||||
|
- [FIX] Invalid precision constant for microseconds (#49)
|
||||||
|
- [FIX] Write error in case point has no tags (#50)
|
||||||
|
|
||||||
|
## Version 3.1.1 (2020-04-06)
|
||||||
|
- [Updated] CA Certificate for SSL (#38)
|
||||||
|
|
||||||
|
## Version 3.1.0 (2020-03-12)
|
||||||
|
- [NEW] Added User-agent header
|
||||||
|
- [FIX] status code check when pinging an InfluxDB version 1.x instance
|
||||||
|
|
||||||
|
## Version 3.0.0 (2020-02-11)
|
||||||
|
- New API with similar keywords as other official InfluxDB clients
|
||||||
|
- Richer set of data types for fields and timestamp methods
|
||||||
|
- Advanced features, such as implicit batching, automatic retrying on server back-pressure and connection failure, along with secured communication over TLS supported for both devices and authentication
|
||||||
|
- Special characters escaping
|
||||||
|
- Backward support for original API of V1/V2
|
21
firmware/libraries/ESP8266_Influxdb/LICENSE
Normal file
21
firmware/libraries/ESP8266_Influxdb/LICENSE
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2018-2020 Tobias Schürg, InfluxData
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
696
firmware/libraries/ESP8266_Influxdb/README.md
Normal file
696
firmware/libraries/ESP8266_Influxdb/README.md
Normal file
|
@ -0,0 +1,696 @@
|
||||||
|
[![PlatformIO](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/workflows/PlatformIO/badge.svg)](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/actions/)
|
||||||
|
|
||||||
|
# InfluxDB Arduino Client
|
||||||
|
|
||||||
|
Simple Arduino client for writing and reading data from [InfluxDB](https://www.influxdata.com/products/influxdb-overview/), no matter whether it is a local server or InfluxDB Cloud. The library supports authentication, secure communication over TLS, [batching](#writing-in-batches), [automatic retrying](#buffer-handling-and-retrying) on server back-pressure and connection failure.
|
||||||
|
|
||||||
|
It also allows setting data in various formats, automatically escapes special characters and offers specifying timestamp in various precisions.
|
||||||
|
|
||||||
|
Library supports both [InfluxDB 2](#basic-code-for-influxdb-2) and [InfluxDB 1](#basic-code-for-influxdb-2).
|
||||||
|
|
||||||
|
This is a new implementation and the API, [original API](#original-api) is still supported.
|
||||||
|
|
||||||
|
Supported devices:
|
||||||
|
- ESP8266 with [Arduino core for ESP8266](https://github.com/esp8266/Arduino) at least version [3.0.2](https://github.com/esp8266/Arduino/releases/tag/3.0.2).
|
||||||
|
- ESP32 with [Arduino core for the ESP32](https://github.com/espressif/arduino-esp32) at least version [2.0.2](https://github.com/espressif/arduino-esp32/releases/tag/2.0.2).
|
||||||
|
|
||||||
|
This library doesn't support using those devices as a peripheral.
|
||||||
|
|
||||||
|
:warning: Only connection over internal WiFi capability is supported for now.
|
||||||
|
|
||||||
|
## Table of contents
|
||||||
|
- [InfluxDB Arduino Client](#influxdb-arduino-client)
|
||||||
|
- [Basic code for InfluxDB 2](#basic-code-for-influxdb-2)
|
||||||
|
- [Basic code for InfluxDB 1](#basic-code-for-influxdb-1)
|
||||||
|
- [Connecting to InfluxDB Cloud 2](#connecting-to-influxdb-cloud-2)
|
||||||
|
- [Writing in Batches](#writing-in-batches)
|
||||||
|
- [Timestamp](#timestamp)
|
||||||
|
- [Configure Time](#configure-time)
|
||||||
|
- [Batch Size](#batch-size)
|
||||||
|
- [Large Batch Size](#large-batch-size)
|
||||||
|
- [Write Modes](#write-modes)
|
||||||
|
- [Buffer Handling and Retrying](#buffer-handling-and-retrying)
|
||||||
|
- [Write Options](#write-options)
|
||||||
|
- [HTTP Options](#http-options)
|
||||||
|
- [Secure Connection](#secure-connection)
|
||||||
|
- [InfluxDb 2](#influxdb-2)
|
||||||
|
- [InfluxDb 1](#influxdb-1)
|
||||||
|
- [Skipping certificate validation](#skipping-certificate-validation)
|
||||||
|
- [Querying](#querying)
|
||||||
|
- [Parametrized Queries](#parametrized-queries)
|
||||||
|
- [Original API](#original-api)
|
||||||
|
- [Initialization](#initialization)
|
||||||
|
- [Sending a single measurement](#sending-a-single-measurement)
|
||||||
|
- [Write multiple data points at once](#write-multiple-data-points-at-once)
|
||||||
|
- [Troubleshooting](#troubleshooting)
|
||||||
|
- [Contributing](#contributing)
|
||||||
|
- [License](#license)
|
||||||
|
|
||||||
|
|
||||||
|
## Basic code for InfluxDB 2
|
||||||
|
After [setting up an InfluxDB 2 server](https://docs.influxdata.com/influxdb/v2.0/get-started/), first define connection parameters and a client instance:
|
||||||
|
```cpp
|
||||||
|
// InfluxDB 2 server url, e.g. http://192.168.1.48:8086 (Use: InfluxDB UI -> Load Data -> Client Libraries)
|
||||||
|
#define INFLUXDB_URL "influxdb-url"
|
||||||
|
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
#define INFLUXDB_TOKEN "token"
|
||||||
|
// InfluxDB 2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org"
|
||||||
|
// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
#define INFLUXDB_BUCKET "bucket"
|
||||||
|
|
||||||
|
// Single InfluxDB instance
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
```
|
||||||
|
|
||||||
|
The next step is adding data. A single row of data is represented by the `Point` class. It consists of a measurement name (like a table name), tags (which labels data) and fields ( the values to store):
|
||||||
|
```cpp
|
||||||
|
// Define data point in the measurement named 'device_status`
|
||||||
|
Point pointDevice("device_status");
|
||||||
|
// Set tags
|
||||||
|
pointDevice.addTag("device", "ESP8266");
|
||||||
|
pointDevice.addTag("SSID", WiFi.SSID());
|
||||||
|
// Add data fields
|
||||||
|
pointDevice.addField("rssi", WiFi.RSSI());
|
||||||
|
pointDevice.addField("uptime", millis());
|
||||||
|
```
|
||||||
|
|
||||||
|
And finally, write the data to the database:
|
||||||
|
```cpp
|
||||||
|
// Write data
|
||||||
|
client.writePoint(pointDevice);
|
||||||
|
```
|
||||||
|
|
||||||
|
Complete source code is available in the [BasicWrite example](examples/BasicWrite/BasicWrite.ino).
|
||||||
|
|
||||||
|
Data can be seen in the InfluxDB UI immediately. Use the [Data Explorer](https://docs.influxdata.com/influxdb/v2.0/query-data/execute-queries/data-explorer/) or create a [Dashboard](https://docs.influxdata.com/influxdb/v2.0/visualize-data/dashboards/).
|
||||||
|
|
||||||
|
## Basic code for InfluxDB 1
|
||||||
|
Using InfluxDB Arduino client for InfluxDB 1 is almost the same as for InfluxDB 2. The only difference is that InfluxDB 1 uses _database_ as classic name for data storage instead of bucket and the server is unsecured by default.
|
||||||
|
There is also a different `InfluxDBClient constructor` and `setConnectionParametersV1` function for setting the security params. Everything else remains the same.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// InfluxDB server url, e.g. http://192.168.1.48:8086 (don't use localhost, always server name or ip address)
|
||||||
|
#define INFLUXDB_URL "influxdb-url"
|
||||||
|
// InfluxDB database name
|
||||||
|
#define INFLUXDB_DB_NAME "database"
|
||||||
|
|
||||||
|
// Single InfluxDB instance
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);
|
||||||
|
|
||||||
|
// Define data point with measurement name 'device_status`
|
||||||
|
Point pointDevice("device_status");
|
||||||
|
// Set tags
|
||||||
|
pointDevice.addTag("device", "ESP8266");
|
||||||
|
pointDevice.addTag("SSID", WiFi.SSID());
|
||||||
|
// Add data
|
||||||
|
pointDevice.addField("rssi", WiFi.RSSI());
|
||||||
|
pointDevice.addField("uptime", millis());
|
||||||
|
|
||||||
|
// Write data
|
||||||
|
client.writePoint(pointDevice);
|
||||||
|
```
|
||||||
|
|
||||||
|
Complete source code is available in [BasicWrite example](examples/BasicWrite/BasicWrite.ino)
|
||||||
|
|
||||||
|
## Connecting to InfluxDB Cloud 2
|
||||||
|
Instead of setting up a local InfluxDB 2 server, it is possible to quickly [start with InfluxDB Cloud 2](https://docs.influxdata.com/influxdb/cloud/get-started/) with a [Free Plan](https://docs.influxdata.com/influxdb/cloud/account-management/pricing-plans/#free-plan).
|
||||||
|
|
||||||
|
InfluxDB Cloud uses secure communication over TLS (https). We need to tell the client to trust this connection. The paragraph bellow describes how to set trusted connection. However, InfluxDB cloud servers have only 3 months validity period. Their CA certificate, included in this library, is valid until 2035. Check [Skipping certification validation](#skipping-certificate-validation) for more details.
|
||||||
|
|
||||||
|
Connecting an Arduino client to InfluxDB Cloud server requires a few additional steps comparing to connecting to local server.
|
||||||
|
|
||||||
|
Connection parameters are almost the same as above, the only difference is that server URL now points to the InfluxDB Cloud 2, you set up after you've finished creating an InfluxDB Cloud 2 subscription. You will find the correct server URL in `InfluxDB UI -> Load Data -> Client Libraries`.
|
||||||
|
```cpp
|
||||||
|
//Include also InfluxCloud 2 CA certificate
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
// InfluxDB 2 server or cloud url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
|
||||||
|
#define INFLUXDB_URL "influxdb-url"
|
||||||
|
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
#define INFLUXDB_TOKEN "token"
|
||||||
|
// InfluxDB 2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org"
|
||||||
|
// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
#define INFLUXDB_BUCKET "bucket"
|
||||||
|
```
|
||||||
|
|
||||||
|
You need to pass an additional parameter to the client constructor, which is a certificate of the server to trust. The constant `InfluxDbCloud2CACert` contains the InfluxDB Cloud 2 CA certificate, which is predefined in this library:
|
||||||
|
```cpp
|
||||||
|
// Single InfluxDB instance
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
```
|
||||||
|
Read more about [secure connection](#secure-connection).
|
||||||
|
|
||||||
|
Additionally, time needs to be synced:
|
||||||
|
```cpp
|
||||||
|
// Synchronize time with NTP servers and set timezone
|
||||||
|
// 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/
|
||||||
|
configTzTime(TZ_INFO "pool.ntp.org", "time.nis.gov");
|
||||||
|
```
|
||||||
|
Read more about time synchronization in [Configure Time](#configure-time).
|
||||||
|
|
||||||
|
Defining data and writing it to the DB is the same as in the case of [BasicWrite](#basic-code):
|
||||||
|
```cpp
|
||||||
|
// Define data point with measurement name 'device_status`
|
||||||
|
Point pointDevice("device_status");
|
||||||
|
// Set tags
|
||||||
|
pointDevice.addTag("device", "ESP8266");
|
||||||
|
pointDevice.addTag("SSID", WiFi.SSID());
|
||||||
|
// Add data
|
||||||
|
pointDevice.addField("rssi", WiFi.RSSI());
|
||||||
|
pointDevice.addField("uptime", millis());
|
||||||
|
|
||||||
|
// Write data
|
||||||
|
client.writePoint(pointDevice);
|
||||||
|
```
|
||||||
|
Complete source code is available in [SecureWrite example](examples/SecureWrite/SecureWrite.ino).
|
||||||
|
|
||||||
|
## Writing in Batches
|
||||||
|
InfluxDB client for Arduino can also write data in batches. A batch is simply a set of points that will be sent at once. To create a batch, the client will keep all points until the number of points reaches the batch size and then it will write all points at once to the InfluxDB server. This is often more efficient than writing each point separately.
|
||||||
|
|
||||||
|
### Timestamp
|
||||||
|
If using batch writes, the timestamp should be employed. Timestamp specifies the time when data was gathered and it is used in the form of a number of seconds (milliseconds, etc) from epoch (1.1.1970) UTC.
|
||||||
|
If points have no timestamp assigned, InfluxDB assigns a timestamp at the time of writing, which could happen much later than the data has been obtained, because the final batch write will happen when the batch is full (or when [flush buffer](#buffer-handling-and-retrying) is forced).
|
||||||
|
|
||||||
|
InfluxDB allows sending timestamps in various precisions - nanoseconds, microseconds, milliseconds or seconds. The milliseconds precision is usually enough for using on Arduino. The maximum available precision is microseconds. Setting the timestamp to nanoseconds will just add zeroes for microseconds fraction and will not improve timestamp accuracy.
|
||||||
|
|
||||||
|
The client has to be configured with a time precision. The default settings is to not use the timestamp, which means that the server will assign a timestamp when the data is written to the database. The `setWriteOptions` functions allows setting custom `WriteOptions` params and one of them is __write precision__:
|
||||||
|
``` cpp
|
||||||
|
// Set write precision to milliseconds. Leave other parameters default.
|
||||||
|
client.setWriteOptions(WriteOptions().writePrecision(WritePrecision::MS));
|
||||||
|
```
|
||||||
|
When a write precision is configured, the client will automatically assign the current time to the timestamp of each written point which doesn't have a timestamp assigned.
|
||||||
|
|
||||||
|
If you want to manage timestamp on your own, there are several ways to set the timestamp explicitly.
|
||||||
|
- `setTime(WritePrecision writePrecision)` - Sets the timestamp to the actual time in the desired precision. The same precision must set in WriteOptions.
|
||||||
|
- `setTime(unsigned long long timestamp)` - Sets the timestamp to an offset since the epoch. Correct precision must be set InfluxDBClient::setWriteOptions.
|
||||||
|
- `setTime(String timestamp)` - Sets the timestamp to an offset since the epoch. Correct precision must be set InfluxDBClient::setWriteOptions.
|
||||||
|
|
||||||
|
The `getTime()` method allows copying the timestamp between points.
|
||||||
|
|
||||||
|
|
||||||
|
### Configure Time
|
||||||
|
Dealing with timestamps, and also validating server or CA certificate, requires that the device has correctly set the time. This can be done with one line of code:
|
||||||
|
```cpp
|
||||||
|
// Synchronize time with NTP servers and set timezone
|
||||||
|
// 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/
|
||||||
|
configTzTime("PST8PDT", "pool.ntp.org", "time.nis.gov");
|
||||||
|
```
|
||||||
|
The `configTzTime` function starts the time synchronization with NTP servers. The first parameter specifies the timezone information, which is important for distinguishing between UTC and a local timezone and for daylight saving changes.
|
||||||
|
The last two string parameters are the internet addresses of NTP servers. Check [pool.ntp.org](https://www.pool.ntp.org/zone) for address of some local NTP servers.
|
||||||
|
|
||||||
|
Timezone string details are described at [https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html](https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html).
|
||||||
|
Values for some timezones:
|
||||||
|
- Central Europe: `CET-1CEST,M3.5.0,M10.5.0/3`
|
||||||
|
- Eastern: `EST5EDT`
|
||||||
|
- Japanese: `JST-9`
|
||||||
|
- Pacific Time: `PST8PDT`
|
||||||
|
|
||||||
|
There is also another function for syncing the time, which takes timezone and DST offset. As DST info is set via static offset it will create local time problem when DST change occurs.
|
||||||
|
It's declaration is following:
|
||||||
|
```cpp
|
||||||
|
configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1, const char* server2 = nullptr, const char* server3 = nullptr);
|
||||||
|
```
|
||||||
|
|
||||||
|
In the example code it would be:
|
||||||
|
```cpp
|
||||||
|
// Synchronize time with NTP servers
|
||||||
|
// Accurate time is necessary for certificate validation and writing in batches
|
||||||
|
configTime(3600, 3600, "pool.ntp.org", "time.nis.gov");
|
||||||
|
```
|
||||||
|
|
||||||
|
Both `configTzTime` and `configTime` functions are asynchronous. This means that calling the functions just starts the time synchronization. Time is often not synchronized yet upon returning from call.
|
||||||
|
|
||||||
|
There is a helper function `timeSync` provided with the this library. The function starts time synchronization by calling the `configTzTime` and waits maximum 20 seconds for time to be synchronized. It prints progress info and final local time to the `Serial` console.
|
||||||
|
`timeSync` has the same signature as `configTzTime` and it is included with the main header file `InfluxDbClient.h`:
|
||||||
|
```cpp
|
||||||
|
// Synchronize time with NTP servers and waits for competition. Prints waiting progress and final synchronized time to the Serial.
|
||||||
|
// Accurate time is necessary for certificate validation and writing points in batch
|
||||||
|
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
|
||||||
|
void timeSync(const char *tzInfo, const char* ntpServer1, const char* ntpServer2 = nullptr, const char* ntpServer3 = nullptr);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Batch Size
|
||||||
|
Setting batch size depends on data gathering and DB updating strategy.
|
||||||
|
|
||||||
|
If data is written in short periods (seconds), the batch size should be set according to your expected write periods and update frequency requirements.
|
||||||
|
For example, if you would like to see updates (on the dashboard or in processing) each minute and you are measuring a single value (1 point) every 10s (6 points per minute), the batch size should be 6. If it is sufficient to update each hour and you are creating 1 point each minute, your batch size should be 60.
|
||||||
|
|
||||||
|
In cases where the data should be written in longer periods and gathered data consists of several points, the batch size should be set to the expected number of points to be gathered.
|
||||||
|
|
||||||
|
To set the batch size we use `WriteOptions` object and [setWriteOptions](#write-options) function:
|
||||||
|
```cpp
|
||||||
|
// Enable lines batching
|
||||||
|
client.setWriteOptions(WriteOptions().batchSize(10));
|
||||||
|
```
|
||||||
|
Writing the point will add a point to the underlying buffer until the batch size is reached:
|
||||||
|
```cpp
|
||||||
|
// Write first point to the buffer
|
||||||
|
// Buffered write always returns `true`
|
||||||
|
client.writePoint(point1);
|
||||||
|
// Write second point to the buffer
|
||||||
|
client.writePoint(point2);
|
||||||
|
..
|
||||||
|
// Write ninth point to the buffer
|
||||||
|
client.writePoint(point9);
|
||||||
|
// Writing tenth point will cause flushing buffer and returns actual write result.
|
||||||
|
if(!client.writePoint(point10)) {
|
||||||
|
Serial.print("InfluxDB write failed: ");
|
||||||
|
Serial.println(client.getLastErrorMessage());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In case cases where the number of points is not always the same, set the batch size to the maximum number of points and use the `flushBuffer()` function to force writing to the database. See [Buffer Handling](#buffer-handling-and-retrying) for more details.
|
||||||
|
|
||||||
|
### Large batch size
|
||||||
|
The maximum batch size depends on the available RAM of the device (~45KB for ESP8266 and ~260KB for ESP32). Larger batch size, >100 for ESP8255, >2000 for ESP32, must be chosen carefully to not crash the app with out of memory error. The Stream write mode must be used, see [Write Modes](#write-modes)
|
||||||
|
|
||||||
|
Always determine your typical line length using `client.pointToLineProtocol(point).length()`. For example, ESP32 can handle 2048 lines with an average length of 69. When the length of line or batch size is increased, the device becomes unstable, even there is more than 76k, it cannot send data or even crashes. ESP8266 handles successfully 330 of such lines.
|
||||||
|
|
||||||
|
:warning: Thoroughly test your app when using large batch files.
|
||||||
|
|
||||||
|
### Write Modes
|
||||||
|
Client has two modes of writing:
|
||||||
|
- Buffer (default)
|
||||||
|
- Stream
|
||||||
|
|
||||||
|
Writing is performed the way that client keeps written lines (points) separately and when a batch is completed, it allocates a data buffer for sending to a server via WiFi Client.
|
||||||
|
This is the fastest way to write data but requires some amount of free memory. Thus a big batch size cannot be used.
|
||||||
|
|
||||||
|
Another way of writing is *stream write*.
|
||||||
|
```cpp
|
||||||
|
// Enables stream write
|
||||||
|
client.setStreamWrite(true);
|
||||||
|
```
|
||||||
|
In this mode client continuously streams lines from batch to WiFi Client. No buffer allocation. As lines are allocated separately, it avoids problems with max allocable block size. The downside is, that writing is about 50% slower than in the Buffer mode.
|
||||||
|
|
||||||
|
## Buffer Handling and Retrying
|
||||||
|
InfluxDB contains an underlying buffer for handling writing in batches and automatic retrying on server back-pressure and connection failure.
|
||||||
|
|
||||||
|
Its size is controlled by the `bufferSize` param of [WriteOptions](#write-options) object:
|
||||||
|
```cpp
|
||||||
|
// Increase buffer to allow caching of failed writes
|
||||||
|
client.setWriteOptions(WriteOptions().bufferSize(50));
|
||||||
|
```
|
||||||
|
The recommended size is at least 2 x batch size.
|
||||||
|
|
||||||
|
The state of the buffer can be determined via two functions:
|
||||||
|
- `isBufferEmpty()` - Returns true if buffer is empty
|
||||||
|
- `isBufferFull()` - Returns true if buffer is full
|
||||||
|
|
||||||
|
A full buffer can occur when there is a problem with the internet connection or the InfluxDB server is overloaded. In such cases, points to write remain in the buffer. When more points are added and connection problem remains, the buffer will reach the top and new points will overwrite older points.
|
||||||
|
|
||||||
|
Each attempt to write a point will try to send older points in the buffer. So, the `isBufferFull()` function can be used to skip low priority points.
|
||||||
|
|
||||||
|
The `flushBuffer()` function can be used to force writing, even if the number of points in the buffer is lower than the batch size. With the help of the `isBufferEmpty()` function a check can be made before a device goes to sleep:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Check whether buffer in not empty
|
||||||
|
if (!client.isBufferEmpty()) {
|
||||||
|
// Write all remaining points to db
|
||||||
|
client.flushBuffer();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Other functions for dealing with buffer:
|
||||||
|
- `checkBuffer()` - Checks point buffer status and flushes if the number of points reaches batch size or flush interval runs out. This is the main function for controlling the buffer and it is used internally.
|
||||||
|
- `resetBuffer()` - Clears the buffer.
|
||||||
|
|
||||||
|
Check [SecureBatchWrite example](examples/SecureBatchWrite/SecureBatchWrite.ino) for example code of buffer handling functions.
|
||||||
|
|
||||||
|
## Write Options
|
||||||
|
Writing points can be controlled via `WriteOptions`, which is set in the `setWriteOptions` function:
|
||||||
|
|
||||||
|
| Parameter | Default Value | Meaning |
|
||||||
|
|-----------|---------------|---------|
|
||||||
|
| writePrecision | `WritePrecision::NoTime` | Timestamp precision of written data |
|
||||||
|
| batchSize | `1` | Number of points that will be written to the database at once |
|
||||||
|
| bufferSize | `5` | Maximum number of points in buffer. Buffer contains new data that will be written to the database and also data that failed to be written due to network failure or server overloading |
|
||||||
|
| flushInterval | `60` | Maximum time(in seconds) data will be held in buffer before points are written to the db |
|
||||||
|
| retryInterval | `5` | Default retry interval in sec, if not sent by server. Value `0` disables retrying |
|
||||||
|
| maxRetryInterval | `300` | Maximum retry interval in sec |
|
||||||
|
| maxRetryAttempts | `3` | Maximum count of retry attempts of failed writes |
|
||||||
|
|
||||||
|
## HTTP Options
|
||||||
|
`HTTPOptions` controls some aspects of HTTP communication and they are set via `setHTTPOptions` function:
|
||||||
|
| Parameter | Default Value | Meaning |
|
||||||
|
|-----------|---------------|---------|
|
||||||
|
| connectionReuse | `false` | Whether HTTP connection should be kept open after initial communication. Usable for frequent writes/queries. |
|
||||||
|
| httpReadTimeout | `5000` | Timeout (ms) for reading server response |
|
||||||
|
|
||||||
|
## Secure Connection
|
||||||
|
Connecting to a secured server requires configuring the client to trust the server. This is achieved by providing the client with a server certificate, certificate authority certificate or certificate SHA1 fingerprint.
|
||||||
|
|
||||||
|
:memo: In ESP32 arduino SDK (1.0.4), `WiFiClientSecure` doesn't support fingerprint to validate the server certificate.
|
||||||
|
|
||||||
|
The certificate (in PEM format) or SHA1 fingerprint should be placed in flash memory to save RAM.
|
||||||
|
Code bellow is an example certificate in PEM format. Valid InfluxDB 2 Cloud CA certificate is included in the library in the constant `InfluxDbCloud2CACert`, located in the `InfluxDBCloud.h`.
|
||||||
|
|
||||||
|
You can use a custom server certificate by exporting it, e.g. using a web browser:
|
||||||
|
```cpp
|
||||||
|
// Server certificate in PEM format, placed in the program (flash) memory to save RAM
|
||||||
|
const char ServerCert[] PROGMEM = R"EOF(
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
||||||
|
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
||||||
|
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
||||||
|
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
||||||
|
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
||||||
|
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
||||||
|
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
||||||
|
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
||||||
|
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
|
||||||
|
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
|
||||||
|
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
|
||||||
|
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
|
||||||
|
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
|
||||||
|
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
|
||||||
|
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
|
||||||
|
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
|
||||||
|
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
|
||||||
|
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
|
||||||
|
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
|
||||||
|
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
|
||||||
|
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
|
||||||
|
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
|
||||||
|
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
|
||||||
|
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
|
||||||
|
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
|
||||||
|
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
|
||||||
|
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
|
||||||
|
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
||||||
|
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
)EOF";
|
||||||
|
|
||||||
|
// Alternatively, use a fingerprint of server certificate to set trust. Works only for ESP8266.
|
||||||
|
const char ServerCert[] PROGMEM = "cabd2a79a1076a31f21d253635cb039d4329a5e8";
|
||||||
|
```
|
||||||
|
|
||||||
|
### InfluxDb 2
|
||||||
|
There are two ways to set the certificate or fingerprint to trust a server:
|
||||||
|
- Use full param constructor
|
||||||
|
```cpp
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert);
|
||||||
|
```
|
||||||
|
- Use `setConnectionParams` function:
|
||||||
|
```cpp
|
||||||
|
// InfluxDB client instance
|
||||||
|
InfluxDBClient client;
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
// configure client
|
||||||
|
client.setConnectionParams(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### InfluxDb 1
|
||||||
|
|
||||||
|
Use `setConnectionParamsV1` function:
|
||||||
|
```cpp
|
||||||
|
// InfluxDB client instance
|
||||||
|
InfluxDBClient client;
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
// configure client
|
||||||
|
client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASSWORD, ServerCert);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Another important prerequisite to successfully validate a server or CA certificate is to have properly synchronized time. More on this in [Configure Time](#configure-time).
|
||||||
|
|
||||||
|
:information_source: Time synchronization is not required for validating server certificate via SHA1 fingerprint.
|
||||||
|
|
||||||
|
### Skipping certificate validation
|
||||||
|
The CA certificate provided with the library is ISRG Root X1. This certificate lasts a very long time, until 2035. It is not necessary to update your device until then when using ISRG Root X1.
|
||||||
|
|
||||||
|
If you are using your own certificate, plase keep in mind server certificates have limited validity period, often only a few months. It will be necessary to frequently change trusted certificate in the source code and reflashing the device. A solution could be using OTA update, but you will still need to care about certificate validity and updating it ahead of time to avoid connection failures.
|
||||||
|
|
||||||
|
The best way to prevent frequent updates is to use a root certificate like the one provided with the library. If you are unable to use a root certificate from a trusted authority, you may want to use insecure mode instead. This is done with the help of `InfluxDBClient::setInsecure()` method.
|
||||||
|
You will also save space in flash (and RAM) by leaving certificate param empty when calling constructor or `setConnectionParams` method.
|
||||||
|
|
||||||
|
:memo: The `InfluxDBClient::setInsecure()` method must be called before calling any function that will establish connection. The best place to call it is in the `setup` method:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// InfluxDB client instance without a server certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
// Set insecure connection to skip server certificate validation
|
||||||
|
client.setInsecure();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
:warning: Using untrusted connection is a security risk.
|
||||||
|
|
||||||
|
## Querying
|
||||||
|
InfluxDB 2 and InfluxDB 1.7+ (with [enabled flux](https://docs.influxdata.com/influxdb/latest/administration/config/#flux-enabled-false)) uses [Flux](https://www.influxdata.com/products/flux/) to process and query data. InfluxDB client for Arduino offers a simple, but powerful, way how to query data with `query` function. It parses response line by line, so it can read a huge responses (thousands data lines), without consuming a lot device memory.
|
||||||
|
|
||||||
|
The `query` returns `FluxQueryResult` object, which parses response and provides useful getters for accessing values from result set.
|
||||||
|
|
||||||
|
The InfluxDB flux query result set is returned in CSV format. In the example below, the first line contains type information and the second column names, and the rest is data:
|
||||||
|
```CSV
|
||||||
|
#datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,long,string,string,string,string
|
||||||
|
,result,table,_start,_stop,_time,_value,SSID,_field,_measurement,device
|
||||||
|
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:13Z,-55,667G,rssi,wifi_status,ESP32
|
||||||
|
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:27Z,-54,667G,rssi,wifi_status,ESP32
|
||||||
|
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:40Z,-54,667G,rssi,wifi_status,ESP32
|
||||||
|
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:54Z,-54,667G,rssi,wifi_status,ESP32
|
||||||
|
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:08:07Z,-55,667G,rssi,wifi_status,ESP32
|
||||||
|
,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:08:20Z,-56,667G,rssi,wifi_status,ESP32
|
||||||
|
```
|
||||||
|
|
||||||
|
Accessing data using `FluxQueryResult` requires knowing the query result structure, especially the name and the type of the column. The best practice is to tune the query
|
||||||
|
in the `InfluxDB Data Explorer` and use the final query with this library.
|
||||||
|
|
||||||
|
Browsing thought the result set is done by repeatedly calling the `next()` method, until it returns false. Unsuccessful reading is distinguished by a non empty value from the `getError()` method.
|
||||||
|
As a flux query result can contain several tables, differing by grouping key, use the `hasTableChanged()` method to determine when there is a new table.
|
||||||
|
Single values are returned using the `getValueByIndex()` or `getValueByName()` methods.
|
||||||
|
All row values at once are retrieved by the `getValues()` method.
|
||||||
|
Always call the `close()` method at the of reading.
|
||||||
|
|
||||||
|
A value in the flux query result column, retrieved by the `getValueByIndex()` or `getValueByName()` methods, is represented by the `FluxValue` object.
|
||||||
|
It provides getter methods for supported flux types:
|
||||||
|
|
||||||
|
| Flux type | Getter | C type |
|
||||||
|
| ----- | ------ | --- |
|
||||||
|
| long | getLong() | long |
|
||||||
|
| unsignedLong | getUnsignedLong() | unsigned long |
|
||||||
|
| dateTime:RFC3339, dateTime:RFC3339Nano | getDateTime() | [FluxDateTime](src/query/FluxTypes.h#L100) |
|
||||||
|
| bool | getBool() | bool |
|
||||||
|
| double | bool | double |
|
||||||
|
| string, base64binary, duration | getString() | String |
|
||||||
|
|
||||||
|
Calling improper type getter will result in a zero (empty) value.
|
||||||
|
|
||||||
|
Check for null (missing) value using the `isNull()` method.
|
||||||
|
|
||||||
|
Use the `getRawValue()` method for getting the original string form.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Construct a Flux query
|
||||||
|
// Query will find RSSI for last 24 hours for each connected WiFi network with this device computed by given selector function
|
||||||
|
String query = "from(bucket: \"my-bucket\") |> range(start: -24h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
|
||||||
|
query += "and r.device == \"ESP32\")";
|
||||||
|
query += "|> max()";
|
||||||
|
|
||||||
|
// Send query to the server and get result
|
||||||
|
FluxQueryResult result = client.query(query);
|
||||||
|
|
||||||
|
// Iterate over rows. Even there is just one row, next() must be called at least once.
|
||||||
|
while (result.next()) {
|
||||||
|
// Get typed value for flux result column 'SSID'
|
||||||
|
String ssid = result.getValueByName("SSID").getString();
|
||||||
|
Serial.print("SSID '");
|
||||||
|
Serial.print(ssid);
|
||||||
|
|
||||||
|
Serial.print("' with RSSI ");
|
||||||
|
|
||||||
|
// Get converted value for flux result column '_value' where there is RSSI value
|
||||||
|
long value = result.getValueByName("_value").getLong();
|
||||||
|
Serial.print(value);
|
||||||
|
|
||||||
|
// Format date-time for printing
|
||||||
|
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
|
||||||
|
String timeStr = time.format("%F %T");
|
||||||
|
|
||||||
|
Serial.print(" at ");
|
||||||
|
Serial.print(timeStr);
|
||||||
|
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if(result.getError() != "") {
|
||||||
|
Serial.print("Query result error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Complete source code is available in [QueryAggregated example](examples/QueryAggregated/QueryAggregated.ino).
|
||||||
|
|
||||||
|
### Parametrized Queries
|
||||||
|
InfluxDB Cloud supports [Parameterized Queries](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/)
|
||||||
|
that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more
|
||||||
|
reusable and can also be used to help prevent injection attacks.
|
||||||
|
|
||||||
|
InfluxDB Cloud inserts the params object into the Flux query as a Flux record named `params`. Use dot or bracket
|
||||||
|
notation to access parameters in the `params` record in your Flux query. Parameterized Flux queries support only `int`
|
||||||
|
, `float`, and `string` data types. To convert the supported data types into
|
||||||
|
other [Flux basic data types, use Flux type conversion functions](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/#supported-parameter-data-types).
|
||||||
|
|
||||||
|
Parameterized query example:
|
||||||
|
> :warning: Parameterized Queries are supported only in InfluxDB Cloud. There is no support in InfluxDB OSS currently.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
// Prepare query parameters
|
||||||
|
QueryParams params;
|
||||||
|
params.add("bucket", INFLUXDB_BUCKET);
|
||||||
|
params.add("since", "-5m");
|
||||||
|
params.add("device", DEVICE);
|
||||||
|
params.add("rssiThreshold", -50);
|
||||||
|
|
||||||
|
// Construct a Flux query using parameters
|
||||||
|
// Parameters are accessed via the 'params' Flux object
|
||||||
|
// Flux only supports only string, float and int as parameters. Duration can be converted from string.
|
||||||
|
// Query will find RSSI less than defined threshold
|
||||||
|
String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \
|
||||||
|
|> filter(fn: (r) => r._measurement == \"wifi_status\") \
|
||||||
|
|> filter(fn: (r) => r._field == \"rssi\") \
|
||||||
|
|> filter(fn: (r) => r.device == params.device) \
|
||||||
|
|> filter(fn: (r) => r._value < params.rssiThreshold)";
|
||||||
|
|
||||||
|
// Print ouput header
|
||||||
|
// Print composed query
|
||||||
|
Serial.print("Querying with: ");
|
||||||
|
Serial.println(query);
|
||||||
|
|
||||||
|
// Send query to the server and get result
|
||||||
|
FluxQueryResult result = client.query(query, params);
|
||||||
|
|
||||||
|
//Print header
|
||||||
|
Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI");
|
||||||
|
|
||||||
|
for(int i=0;i<37;i++) {
|
||||||
|
Serial.print('-');
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Iterate over rows. Even there is just one row, next() must be called at least once.
|
||||||
|
int c = 0;
|
||||||
|
while (result.next()) {
|
||||||
|
// Get converted value for flux result column 'SSID'
|
||||||
|
String ssid = result.getValueByName("SSID").getString();
|
||||||
|
|
||||||
|
// Get converted value for flux result column '_value' where there is RSSI value
|
||||||
|
long rssi = result.getValueByName("_value").getLong();
|
||||||
|
|
||||||
|
// Get converted value for the _time column
|
||||||
|
FluxDateTime time = result.getValueByName("_time").getDateTime();
|
||||||
|
|
||||||
|
// Format date-time for printing
|
||||||
|
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
|
||||||
|
String timeStr = time.format("%F %T");
|
||||||
|
// Print formatted row
|
||||||
|
Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi);
|
||||||
|
c++;
|
||||||
|
}
|
||||||
|
if(!c) {
|
||||||
|
Serial.println(" No data found");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if(result.getError() != "") {
|
||||||
|
Serial.print("Query result error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the result
|
||||||
|
result.close();
|
||||||
|
```
|
||||||
|
Complete source code is available in [QueryParams example](examples/QueryParams/QueryParams.ino).
|
||||||
|
|
||||||
|
## Original API
|
||||||
|
|
||||||
|
### Initialization
|
||||||
|
```cpp
|
||||||
|
#define INFLUXDB_HOST "192.168.0.32"
|
||||||
|
#define INFLUXDB_PORT 1337
|
||||||
|
#define INFLUXDB_DATABASE "test"
|
||||||
|
//if used with authentication
|
||||||
|
#define INFLUXDB_USER "user"
|
||||||
|
#define INFLUXDB_PASS "password"
|
||||||
|
|
||||||
|
// connect to WiFi
|
||||||
|
|
||||||
|
Influxdb influx(INFLUXDB_HOST); // port defaults to 8086
|
||||||
|
// or to use a custom port
|
||||||
|
Influxdb influx(INFLUXDB_HOST, INFLUXDB_PORT);
|
||||||
|
|
||||||
|
// set the target database
|
||||||
|
influx.setDb(INFLUXDB_DATABASE);
|
||||||
|
// or use a db with auth
|
||||||
|
influx.setDbAuth(INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASS) // with authentication
|
||||||
|
|
||||||
|
// To use the v2.0 InfluxDB
|
||||||
|
influx.setVersion(2);
|
||||||
|
influx.setOrg("myOrganization");
|
||||||
|
influx.setBucket("myBucket");
|
||||||
|
influx.setToken("myToken");
|
||||||
|
influx.setPort(8086);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Sending a single measurement
|
||||||
|
**Using an InfluxData object:**
|
||||||
|
```cpp
|
||||||
|
// create a measurement object
|
||||||
|
InfluxData measurement ("temperature");
|
||||||
|
measurement.addTag("device", d2);
|
||||||
|
measurement.addTag("sensor", "dht11");
|
||||||
|
measurement.addValue("value", 24.0);
|
||||||
|
|
||||||
|
// write it into db
|
||||||
|
influx.write(measurement);
|
||||||
|
```
|
||||||
|
|
||||||
|
**Using raw-data**
|
||||||
|
```cpp
|
||||||
|
influx.write("temperature,device=d2,sensor=dht11 value=24.0")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Write multiple data points at once
|
||||||
|
Batching measurements and send them with a single request will result in a much higher performance.
|
||||||
|
```cpp
|
||||||
|
|
||||||
|
InfluxData measurement1 = readTemperature()
|
||||||
|
influx.prepare(measurement1)
|
||||||
|
|
||||||
|
InfluxData measurement2 = readLight()
|
||||||
|
influx.prepare(measurement2)
|
||||||
|
|
||||||
|
InfluxData measurement3 = readVoltage()
|
||||||
|
influx.prepare(measurement3)
|
||||||
|
|
||||||
|
// writes all prepared measurements with a single request into db.
|
||||||
|
boolean success = influx.write();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
All db methods return status. Value `false` means something went wrong. Call `getLastErrorMessage()` to get the error message.
|
||||||
|
|
||||||
|
When error message doesn't help to explain the bad behavior, go to the library sources and in the file `src/util/debug.h` uncomment line 33:
|
||||||
|
```cpp
|
||||||
|
// Uncomment bellow in case of a problem and rebuild sketch
|
||||||
|
#define INFLUXDB_CLIENT_DEBUG_ENABLE
|
||||||
|
```
|
||||||
|
Then upload your sketch again and see the debug output in the Serial Monitor.
|
||||||
|
|
||||||
|
If you couldn't solve a problem by yourself, please, post an issue including the debug output.
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the `master` branch.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
The InfluxDB Arduino Client is released under the [MIT License](https://opensource.org/licenses/MIT).
|
|
@ -0,0 +1,98 @@
|
||||||
|
/**
|
||||||
|
* Basic Write Example code for InfluxDBClient library for Arduino
|
||||||
|
* Data can be immediately seen in a InfluxDB UI: wifi_status measurement
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
*
|
||||||
|
* Measures signal level of the actually connected WiFi network
|
||||||
|
* This example supports only InfluxDB running from unsecure (http://...)
|
||||||
|
* For secure (https://...) or Influx Cloud 2 use SecureWrite example
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "ssid"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "password"
|
||||||
|
// InfluxDB server url. Don't use localhost, always server name or ip address.
|
||||||
|
// E.g. http://192.168.1.48:8086 (In InfluxDB 2 UI -> Load Data -> Client Libraries),
|
||||||
|
#define INFLUXDB_URL "influxdb-url"
|
||||||
|
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
#define INFLUXDB_TOKEN "toked-id"
|
||||||
|
// InfluxDB 2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org"
|
||||||
|
// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
#define INFLUXDB_BUCKET "bucket"
|
||||||
|
// InfluxDB v1 database name
|
||||||
|
//#define INFLUXDB_DB_NAME "database"
|
||||||
|
|
||||||
|
// InfluxDB client instance
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
// 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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Set InfluxDB 1 authentication params
|
||||||
|
//client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DB_NAME, INFLUXDB_USER, INFLUXDB_PASSWORD);
|
||||||
|
|
||||||
|
// 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(client.pointToLineProtocol(sensor));
|
||||||
|
// If no Wifi signal, try to reconnect it
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
//Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
|
@ -0,0 +1,98 @@
|
||||||
|
/**
|
||||||
|
* Basic Write Example code for InfluxDBClient library for Arduino
|
||||||
|
* Data can be immediately seen in a InfluxDB UI: wifi_status measurement
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
*
|
||||||
|
* Measures signal level of the actually connected WiFi network
|
||||||
|
* This example supports only InfluxDB running from unsecure (http://...)
|
||||||
|
* For secure (https://...) or Influx Cloud 2 use SecureWrite example
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "ssid"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "password"
|
||||||
|
// InfluxDB server url. Don't use localhost, always server name or ip address.
|
||||||
|
// E.g. http://192.168.1.48:8086 (In InfluxDB 2 UI -> Load Data -> Client Libraries),
|
||||||
|
#define INFLUXDB_URL "influxdb-url"
|
||||||
|
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
#define INFLUXDB_TOKEN "toked-id"
|
||||||
|
// InfluxDB 2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org"
|
||||||
|
// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
#define INFLUXDB_BUCKET "bucket"
|
||||||
|
// InfluxDB v1 database name
|
||||||
|
//#define INFLUXDB_DB_NAME "database"
|
||||||
|
|
||||||
|
// InfluxDB client instance
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
// 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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Set InfluxDB 1 authentication params
|
||||||
|
//client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DB_NAME, INFLUXDB_USER, INFLUXDB_PASSWORD);
|
||||||
|
|
||||||
|
// 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(client.pointToLineProtocol(sensor));
|
||||||
|
// If no Wifi signal, try to reconnect it
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
//Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
|
@ -0,0 +1,136 @@
|
||||||
|
/**
|
||||||
|
* Buckets management Example code for InfluxDBClient library for Arduino
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
*
|
||||||
|
* This example supports only InfluxDB running from unsecure (http://...)
|
||||||
|
* For secure (https://...) or Influx Cloud 2 connection check SecureWrite example to
|
||||||
|
* see how connect using secured connection (https)
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "ssid"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "password"
|
||||||
|
// InfluxDB server url. Don't use localhost, always server name or ip address.
|
||||||
|
// E.g. http://192.168.1.48:8086 (In InfluxDB 2 UI -> Load Data -> Client Libraries),
|
||||||
|
#define INFLUXDB_URL "influxdb-url"
|
||||||
|
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
// This token must have all buckets permission
|
||||||
|
#define INFLUXDB_TOKEN "toked-id"
|
||||||
|
// InfluxDB 2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org"
|
||||||
|
// Bucket name that doesn't exist in the db yet
|
||||||
|
#define INFLUXDB_BUCKET "test-bucket"
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(74880);
|
||||||
|
|
||||||
|
// Connect WiFi
|
||||||
|
Serial.println("Connecting to " WIFI_SSID);
|
||||||
|
WiFi.mode(WIFI_STA);
|
||||||
|
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
|
||||||
|
while (wifiMulti.run() != WL_CONNECTED) {
|
||||||
|
Serial.print(".");
|
||||||
|
delay(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creates client, bucket, writes data, verifies data and deletes bucket
|
||||||
|
void testClient() {
|
||||||
|
// InfluxDB client instance
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
|
||||||
|
// 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());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get dedicated client for buckets management
|
||||||
|
BucketsClient buckets = client.getBucketsClient();
|
||||||
|
|
||||||
|
// Verify bucket does not exist, or delete it
|
||||||
|
if(buckets.checkBucketExists(INFLUXDB_BUCKET)) {
|
||||||
|
Serial.println("Bucket " INFLUXDB_BUCKET " already exists, deleting" );
|
||||||
|
// get reference
|
||||||
|
Bucket b = buckets.findBucket(INFLUXDB_BUCKET);
|
||||||
|
// Delete bucket
|
||||||
|
buckets.deleteBucket(b.getID());
|
||||||
|
}
|
||||||
|
|
||||||
|
// create a bucket with retention policy one month. Leave out or set zero to infinity
|
||||||
|
uint32_t monthSec = 30*24*3600;
|
||||||
|
Bucket b = buckets.createBucket(INFLUXDB_BUCKET, monthSec);
|
||||||
|
if(!b) {
|
||||||
|
// some error occurred
|
||||||
|
Serial.print("Bucket creating error: ");
|
||||||
|
Serial.println(buckets.getLastErrorMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Serial.print("Created bucket: ");
|
||||||
|
Serial.println(b.toString());
|
||||||
|
|
||||||
|
int numPoints = 10;
|
||||||
|
// Write some points
|
||||||
|
for(int i=0;i<numPoints;i++) {
|
||||||
|
Point point("test");
|
||||||
|
point.addTag("device_name", DEVICE);
|
||||||
|
point.addField("temperature", random(-20, 40) * 1.1f);
|
||||||
|
point.addField("humidity", random(10, 90));
|
||||||
|
if(!client.writePoint(point)) {
|
||||||
|
Serial.print("Write error: ");
|
||||||
|
Serial.println(client.getLastErrorMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// verify written points
|
||||||
|
String query= "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -1h) |> pivot(rowKey:[\"_time\"],columnKey: [\"_field\"],valueColumn: \"_value\") |> count(column: \"humidity\")";
|
||||||
|
FluxQueryResult result = client.query(query);
|
||||||
|
// We expect one row
|
||||||
|
if(result.next()) {
|
||||||
|
// Get count value
|
||||||
|
FluxValue val = result.getValueByName("humidity");
|
||||||
|
if(val.getLong() != numPoints) {
|
||||||
|
Serial.print("Test failure, expected ");
|
||||||
|
Serial.print(numPoints);
|
||||||
|
Serial.print(" got ");
|
||||||
|
Serial.println(val.getLong());
|
||||||
|
} else {
|
||||||
|
Serial.println("Test successfull");
|
||||||
|
}
|
||||||
|
// Advance to the end
|
||||||
|
result.next();
|
||||||
|
} else {
|
||||||
|
Serial.print("Query error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
};
|
||||||
|
result.close();
|
||||||
|
|
||||||
|
buckets.deleteBucket(b.getID());
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Lets do an E2E test
|
||||||
|
// call a client test
|
||||||
|
testClient();
|
||||||
|
|
||||||
|
Serial.println("Stopping");
|
||||||
|
// Stop here, don't loop
|
||||||
|
while(1) delay(1);
|
||||||
|
}
|
136
firmware/libraries/ESP8266_Influxdb/examples/Buckets/Buckets.ino
Normal file
136
firmware/libraries/ESP8266_Influxdb/examples/Buckets/Buckets.ino
Normal file
|
@ -0,0 +1,136 @@
|
||||||
|
/**
|
||||||
|
* Buckets management Example code for InfluxDBClient library for Arduino
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
*
|
||||||
|
* This example supports only InfluxDB running from unsecure (http://...)
|
||||||
|
* For secure (https://...) or Influx Cloud 2 connection check SecureWrite example to
|
||||||
|
* see how connect using secured connection (https)
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "ssid"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "password"
|
||||||
|
// InfluxDB server url. Don't use localhost, always server name or ip address.
|
||||||
|
// E.g. http://192.168.1.48:8086 (In InfluxDB 2 UI -> Load Data -> Client Libraries),
|
||||||
|
#define INFLUXDB_URL "influxdb-url"
|
||||||
|
// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
// This token must have all buckets permission
|
||||||
|
#define INFLUXDB_TOKEN "toked-id"
|
||||||
|
// InfluxDB 2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org"
|
||||||
|
// Bucket name that doesn't exist in the db yet
|
||||||
|
#define INFLUXDB_BUCKET "test-bucket"
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(74880);
|
||||||
|
|
||||||
|
// Connect WiFi
|
||||||
|
Serial.println("Connecting to " WIFI_SSID);
|
||||||
|
WiFi.mode(WIFI_STA);
|
||||||
|
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
|
||||||
|
while (wifiMulti.run() != WL_CONNECTED) {
|
||||||
|
Serial.print(".");
|
||||||
|
delay(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creates client, bucket, writes data, verifies data and deletes bucket
|
||||||
|
void testClient() {
|
||||||
|
// InfluxDB client instance
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
|
||||||
|
// 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());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get dedicated client for buckets management
|
||||||
|
BucketsClient buckets = client.getBucketsClient();
|
||||||
|
|
||||||
|
// Verify bucket does not exist, or delete it
|
||||||
|
if(buckets.checkBucketExists(INFLUXDB_BUCKET)) {
|
||||||
|
Serial.println("Bucket " INFLUXDB_BUCKET " already exists, deleting" );
|
||||||
|
// get reference
|
||||||
|
Bucket b = buckets.findBucket(INFLUXDB_BUCKET);
|
||||||
|
// Delete bucket
|
||||||
|
buckets.deleteBucket(b.getID());
|
||||||
|
}
|
||||||
|
|
||||||
|
// create a bucket with retention policy one month. Leave out or set zero to infinity
|
||||||
|
uint32_t monthSec = 30*24*3600;
|
||||||
|
Bucket b = buckets.createBucket(INFLUXDB_BUCKET, monthSec);
|
||||||
|
if(!b) {
|
||||||
|
// some error occurred
|
||||||
|
Serial.print("Bucket creating error: ");
|
||||||
|
Serial.println(buckets.getLastErrorMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Serial.print("Created bucket: ");
|
||||||
|
Serial.println(b.toString());
|
||||||
|
|
||||||
|
int numPoints = 10;
|
||||||
|
// Write some points
|
||||||
|
for(int i=0;i<numPoints;i++) {
|
||||||
|
Point point("test");
|
||||||
|
point.addTag("device_name", DEVICE);
|
||||||
|
point.addField("temperature", random(-20, 40) * 1.1f);
|
||||||
|
point.addField("humidity", random(10, 90));
|
||||||
|
if(!client.writePoint(point)) {
|
||||||
|
Serial.print("Write error: ");
|
||||||
|
Serial.println(client.getLastErrorMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// verify written points
|
||||||
|
String query= "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -1h) |> pivot(rowKey:[\"_time\"],columnKey: [\"_field\"],valueColumn: \"_value\") |> count(column: \"humidity\")";
|
||||||
|
FluxQueryResult result = client.query(query);
|
||||||
|
// We expect one row
|
||||||
|
if(result.next()) {
|
||||||
|
// Get count value
|
||||||
|
FluxValue val = result.getValueByName("humidity");
|
||||||
|
if(val.getLong() != numPoints) {
|
||||||
|
Serial.print("Test failure, expected ");
|
||||||
|
Serial.print(numPoints);
|
||||||
|
Serial.print(" got ");
|
||||||
|
Serial.println(val.getLong());
|
||||||
|
} else {
|
||||||
|
Serial.println("Test successfull");
|
||||||
|
}
|
||||||
|
// Advance to the end
|
||||||
|
result.next();
|
||||||
|
} else {
|
||||||
|
Serial.print("Query error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
};
|
||||||
|
result.close();
|
||||||
|
|
||||||
|
buckets.deleteBucket(b.getID());
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Lets do an E2E test
|
||||||
|
// call a client test
|
||||||
|
testClient();
|
||||||
|
|
||||||
|
Serial.println("Stopping");
|
||||||
|
// Stop here, don't loop
|
||||||
|
while(1) delay(1);
|
||||||
|
}
|
|
@ -0,0 +1,163 @@
|
||||||
|
/**
|
||||||
|
* QueryAggregated Example code for InfluxDBClient library for Arduino.
|
||||||
|
*
|
||||||
|
* This example demonstrates querying basic aggregated statistic parameters of WiFi signal level measured and stored in BasicWrite and SecureWrite examples.
|
||||||
|
*
|
||||||
|
* Demonstrates connection to any InfluxDB instance accesible via:
|
||||||
|
* - unsecured http://...
|
||||||
|
* - secure https://... (appropriate certificate is required)
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
*
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
|
||||||
|
#define INFLUXDB_URL "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
|
||||||
|
#define INFLUXDB_ORG "org name/id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use database name
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
|
||||||
|
// Accurate time is necessary for certificate validation
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Get max RSSI
|
||||||
|
printAgregateResult("max");
|
||||||
|
// Get mean RSSI
|
||||||
|
printAgregateResult("mean");
|
||||||
|
// Get min RSSI
|
||||||
|
printAgregateResult("min");
|
||||||
|
|
||||||
|
//Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// printAgregateResult queries db for aggregated RSSI value computed by given InfluxDB selector function (max, mean, min)
|
||||||
|
// Prints composed query and the result values.
|
||||||
|
void printAgregateResult(String selectorFunction) {
|
||||||
|
// Construct a Flux query
|
||||||
|
// Query will find RSSI for last hour for each connected WiFi network with this device computed by given selector function
|
||||||
|
String query = "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -1h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
|
||||||
|
query += " and r.device == \"" DEVICE "\")";
|
||||||
|
query += "|> " + selectorFunction + "()";
|
||||||
|
|
||||||
|
// Print ouput header
|
||||||
|
Serial.print("==== ");
|
||||||
|
Serial.print(selectorFunction);
|
||||||
|
Serial.println(" ====");
|
||||||
|
|
||||||
|
// Print composed query
|
||||||
|
Serial.print("Querying with: ");
|
||||||
|
Serial.println(query);
|
||||||
|
|
||||||
|
// Send query to the server and get result
|
||||||
|
FluxQueryResult result = client.query(query);
|
||||||
|
|
||||||
|
// Iterate over rows. Even there is just one row, next() must be called at least once.
|
||||||
|
while (result.next()) {
|
||||||
|
// Get converted value for flux result column 'SSID'
|
||||||
|
String ssid = result.getValueByName("SSID").getString();
|
||||||
|
Serial.print("SSID '");
|
||||||
|
Serial.print(ssid);
|
||||||
|
|
||||||
|
Serial.print("' with RSSI ");
|
||||||
|
// Get converted value for flux result column '_value' where there is RSSI value
|
||||||
|
// RSSI is integer value and so on min and max selected results,
|
||||||
|
// whereas mean is computed and the result type is double.
|
||||||
|
if(selectorFunction == "mean") {
|
||||||
|
double value = result.getValueByName("_value").getDouble();
|
||||||
|
Serial.print(value, 1);
|
||||||
|
// computed value has not got a _time column, so omitting getting time here
|
||||||
|
} else {
|
||||||
|
long value = result.getValueByName("_value").getLong();
|
||||||
|
Serial.print(value);
|
||||||
|
|
||||||
|
// Get converted value for the _time column
|
||||||
|
FluxDateTime time = result.getValueByName("_time").getDateTime();
|
||||||
|
|
||||||
|
// Format date-time for printing
|
||||||
|
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
|
||||||
|
String timeStr = time.format("%F %T");
|
||||||
|
|
||||||
|
Serial.print(" at ");
|
||||||
|
Serial.print(timeStr);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if(result.getError() != "") {
|
||||||
|
Serial.print("Query result error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the result
|
||||||
|
result.close();
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,163 @@
|
||||||
|
/**
|
||||||
|
* QueryAggregated Example code for InfluxDBClient library for Arduino.
|
||||||
|
*
|
||||||
|
* This example demonstrates querying basic aggregated statistic parameters of WiFi signal level measured and stored in BasicWrite and SecureWrite examples.
|
||||||
|
*
|
||||||
|
* Demonstrates connection to any InfluxDB instance accesible via:
|
||||||
|
* - unsecured http://...
|
||||||
|
* - secure https://... (appropriate certificate is required)
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
*
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
|
||||||
|
#define INFLUXDB_URL "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
|
||||||
|
#define INFLUXDB_ORG "org name/id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use database name
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
|
||||||
|
// Accurate time is necessary for certificate validation
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Get max RSSI
|
||||||
|
printAgregateResult("max");
|
||||||
|
// Get mean RSSI
|
||||||
|
printAgregateResult("mean");
|
||||||
|
// Get min RSSI
|
||||||
|
printAgregateResult("min");
|
||||||
|
|
||||||
|
//Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// printAgregateResult queries db for aggregated RSSI value computed by given InfluxDB selector function (max, mean, min)
|
||||||
|
// Prints composed query and the result values.
|
||||||
|
void printAgregateResult(String selectorFunction) {
|
||||||
|
// Construct a Flux query
|
||||||
|
// Query will find RSSI for last hour for each connected WiFi network with this device computed by given selector function
|
||||||
|
String query = "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -1h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
|
||||||
|
query += " and r.device == \"" DEVICE "\")";
|
||||||
|
query += "|> " + selectorFunction + "()";
|
||||||
|
|
||||||
|
// Print ouput header
|
||||||
|
Serial.print("==== ");
|
||||||
|
Serial.print(selectorFunction);
|
||||||
|
Serial.println(" ====");
|
||||||
|
|
||||||
|
// Print composed query
|
||||||
|
Serial.print("Querying with: ");
|
||||||
|
Serial.println(query);
|
||||||
|
|
||||||
|
// Send query to the server and get result
|
||||||
|
FluxQueryResult result = client.query(query);
|
||||||
|
|
||||||
|
// Iterate over rows. Even there is just one row, next() must be called at least once.
|
||||||
|
while (result.next()) {
|
||||||
|
// Get converted value for flux result column 'SSID'
|
||||||
|
String ssid = result.getValueByName("SSID").getString();
|
||||||
|
Serial.print("SSID '");
|
||||||
|
Serial.print(ssid);
|
||||||
|
|
||||||
|
Serial.print("' with RSSI ");
|
||||||
|
// Get converted value for flux result column '_value' where there is RSSI value
|
||||||
|
// RSSI is integer value and so on min and max selected results,
|
||||||
|
// whereas mean is computed and the result type is double.
|
||||||
|
if(selectorFunction == "mean") {
|
||||||
|
double value = result.getValueByName("_value").getDouble();
|
||||||
|
Serial.print(value, 1);
|
||||||
|
// computed value has not got a _time column, so omitting getting time here
|
||||||
|
} else {
|
||||||
|
long value = result.getValueByName("_value").getLong();
|
||||||
|
Serial.print(value);
|
||||||
|
|
||||||
|
// Get converted value for the _time column
|
||||||
|
FluxDateTime time = result.getValueByName("_time").getDateTime();
|
||||||
|
|
||||||
|
// Format date-time for printing
|
||||||
|
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
|
||||||
|
String timeStr = time.format("%F %T");
|
||||||
|
|
||||||
|
Serial.print(" at ");
|
||||||
|
Serial.print(timeStr);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if(result.getError() != "") {
|
||||||
|
Serial.print("Query result error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the result
|
||||||
|
result.close();
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,154 @@
|
||||||
|
/**
|
||||||
|
* QueryParams Example code for InfluxDBClient library for Arduino.
|
||||||
|
*
|
||||||
|
* This example demonstrates querying using parameters inserted into the Flux query. We select WiFi signal level values bellow a certain threshold.
|
||||||
|
* WiFi signal is measured and stored in BasicWrite and SecureWrite examples.
|
||||||
|
*
|
||||||
|
* Demonstrates connection to any InfluxDB instance accesible via:
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
*
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
|
||||||
|
#define INFLUXDB_URL "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
|
||||||
|
#define INFLUXDB_ORG "org name/id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use database name
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
|
||||||
|
// Accurate time is necessary for certificate validation
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Queries WiFi signal level values bellow a certain threshold using parameters inserted into the Flux query
|
||||||
|
// Prints composed query and the result values.
|
||||||
|
void loop() {
|
||||||
|
// Prepare query parameters
|
||||||
|
QueryParams params;
|
||||||
|
params.add("bucket", INFLUXDB_BUCKET);
|
||||||
|
params.add("since", "-5m");
|
||||||
|
params.add("device", DEVICE);
|
||||||
|
params.add("rssiTreshold", -50);
|
||||||
|
|
||||||
|
// Construct a Flux query using parameters
|
||||||
|
// Parameters are accessed via the 'params' Flux object
|
||||||
|
// Flux only supports only string, float and int as parameters. Duration can be converted from string.
|
||||||
|
// Query will find RSSI less than defined treshold
|
||||||
|
String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \
|
||||||
|
|> filter(fn: (r) => r._measurement == \"wifi_status\") \
|
||||||
|
|> filter(fn: (r) => r._field == \"rssi\") \
|
||||||
|
|> filter(fn: (r) => r.device == params.device) \
|
||||||
|
|> filter(fn: (r) => r._value < params.rssiTreshold)";
|
||||||
|
|
||||||
|
// Print ouput header
|
||||||
|
// Print composed query
|
||||||
|
Serial.print("Querying with: ");
|
||||||
|
Serial.println(query);
|
||||||
|
|
||||||
|
// Send query to the server and get result
|
||||||
|
FluxQueryResult result = client.query(query, params);
|
||||||
|
|
||||||
|
//Print header
|
||||||
|
Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI");
|
||||||
|
|
||||||
|
for(int i=0;i<37;i++) {
|
||||||
|
Serial.print('-');
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Iterate over rows. Even there is just one row, next() must be called at least once.
|
||||||
|
int c = 0;
|
||||||
|
while (result.next()) {
|
||||||
|
// Get converted value for flux result column 'SSID'
|
||||||
|
String ssid = result.getValueByName("SSID").getString();
|
||||||
|
|
||||||
|
// Get converted value for flux result column '_value' where there is RSSI value
|
||||||
|
long rssi = result.getValueByName("_value").getLong();
|
||||||
|
|
||||||
|
// Get converted value for the _time column
|
||||||
|
FluxDateTime time = result.getValueByName("_time").getDateTime();
|
||||||
|
|
||||||
|
// Format date-time for printing
|
||||||
|
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
|
||||||
|
String timeStr = time.format("%F %T");
|
||||||
|
// Print formatted row
|
||||||
|
Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi);
|
||||||
|
c++;
|
||||||
|
}
|
||||||
|
if(!c) {
|
||||||
|
Serial.println(" No data found");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if(result.getError() != "") {
|
||||||
|
Serial.print("Query result error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the result
|
||||||
|
result.close();
|
||||||
|
// Wait 15s
|
||||||
|
delay(15000);
|
||||||
|
}
|
|
@ -0,0 +1,154 @@
|
||||||
|
/**
|
||||||
|
* QueryParams Example code for InfluxDBClient library for Arduino.
|
||||||
|
*
|
||||||
|
* This example demonstrates querying using parameters inserted into the Flux query. We select WiFi signal level values bellow a certain threshold.
|
||||||
|
* WiFi signal is measured and stored in BasicWrite and SecureWrite examples.
|
||||||
|
*
|
||||||
|
* Demonstrates connection to any InfluxDB instance accesible via:
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
*
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
|
||||||
|
#define INFLUXDB_URL "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
|
||||||
|
#define INFLUXDB_ORG "org name/id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use database name
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
|
||||||
|
// Accurate time is necessary for certificate validation
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Queries WiFi signal level values bellow a certain threshold using parameters inserted into the Flux query
|
||||||
|
// Prints composed query and the result values.
|
||||||
|
void loop() {
|
||||||
|
// Prepare query parameters
|
||||||
|
QueryParams params;
|
||||||
|
params.add("bucket", INFLUXDB_BUCKET);
|
||||||
|
params.add("since", "-5m");
|
||||||
|
params.add("device", DEVICE);
|
||||||
|
params.add("rssiTreshold", -50);
|
||||||
|
|
||||||
|
// Construct a Flux query using parameters
|
||||||
|
// Parameters are accessed via the 'params' Flux object
|
||||||
|
// Flux only supports only string, float and int as parameters. Duration can be converted from string.
|
||||||
|
// Query will find RSSI less than defined treshold
|
||||||
|
String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \
|
||||||
|
|> filter(fn: (r) => r._measurement == \"wifi_status\") \
|
||||||
|
|> filter(fn: (r) => r._field == \"rssi\") \
|
||||||
|
|> filter(fn: (r) => r.device == params.device) \
|
||||||
|
|> filter(fn: (r) => r._value < params.rssiTreshold)";
|
||||||
|
|
||||||
|
// Print ouput header
|
||||||
|
// Print composed query
|
||||||
|
Serial.print("Querying with: ");
|
||||||
|
Serial.println(query);
|
||||||
|
|
||||||
|
// Send query to the server and get result
|
||||||
|
FluxQueryResult result = client.query(query, params);
|
||||||
|
|
||||||
|
//Print header
|
||||||
|
Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI");
|
||||||
|
|
||||||
|
for(int i=0;i<37;i++) {
|
||||||
|
Serial.print('-');
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Iterate over rows. Even there is just one row, next() must be called at least once.
|
||||||
|
int c = 0;
|
||||||
|
while (result.next()) {
|
||||||
|
// Get converted value for flux result column 'SSID'
|
||||||
|
String ssid = result.getValueByName("SSID").getString();
|
||||||
|
|
||||||
|
// Get converted value for flux result column '_value' where there is RSSI value
|
||||||
|
long rssi = result.getValueByName("_value").getLong();
|
||||||
|
|
||||||
|
// Get converted value for the _time column
|
||||||
|
FluxDateTime time = result.getValueByName("_time").getDateTime();
|
||||||
|
|
||||||
|
// Format date-time for printing
|
||||||
|
// Format string according to http://www.cplusplus.com/reference/ctime/strftime/
|
||||||
|
String timeStr = time.format("%F %T");
|
||||||
|
// Print formatted row
|
||||||
|
Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi);
|
||||||
|
c++;
|
||||||
|
}
|
||||||
|
if(!c) {
|
||||||
|
Serial.println(" No data found");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if(result.getError() != "") {
|
||||||
|
Serial.print("Query result error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the result
|
||||||
|
result.close();
|
||||||
|
// Wait 15s
|
||||||
|
delay(15000);
|
||||||
|
}
|
|
@ -0,0 +1,148 @@
|
||||||
|
/**
|
||||||
|
* QueryTable Example code for InfluxDBClient library for Arduino.
|
||||||
|
*
|
||||||
|
* This example demonstrates querying recent history of values of WiFi signal level measured and stored in BasicWrite and SecureWrite examples.
|
||||||
|
*
|
||||||
|
* Demonstrates connection to any InfluxDB instance accesible via:
|
||||||
|
* - unsecured http://...
|
||||||
|
* - secure https://... (appropriate certificate is required)
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
*
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
|
||||||
|
#define INFLUXDB_URL "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
|
||||||
|
#define INFLUXDB_ORG "org name/id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use database name
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Accurate time is necessary for certificate validation
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Construct a Flux query
|
||||||
|
// Query will list RSSI for last 24 hours for each connected WiFi network of this device type
|
||||||
|
String query = "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -24h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
|
||||||
|
query += " and r.device == \"" DEVICE "\")";
|
||||||
|
|
||||||
|
Serial.println("==== List results ====");
|
||||||
|
|
||||||
|
// Print composed query
|
||||||
|
Serial.print("Querying with: ");
|
||||||
|
Serial.println(query);
|
||||||
|
|
||||||
|
// Send query to the server and get result
|
||||||
|
FluxQueryResult result = client.query(query);
|
||||||
|
|
||||||
|
// Iterate over rows. Even there is just one row, next() must be called at least once.
|
||||||
|
while (result.next()) {
|
||||||
|
// Check for new grouping key
|
||||||
|
if(result.hasTableChanged()) {
|
||||||
|
Serial.println("Table:");
|
||||||
|
Serial.print(" ");
|
||||||
|
// Print all columns name
|
||||||
|
for(String &name: result.getColumnsName()) {
|
||||||
|
Serial.print(name);
|
||||||
|
Serial.print(",");
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
Serial.print(" ");
|
||||||
|
// Print all columns datatype
|
||||||
|
for(String &tp: result.getColumnsDatatype()) {
|
||||||
|
Serial.print(tp);
|
||||||
|
Serial.print(",");
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
Serial.print(" ");
|
||||||
|
// Print values of the row
|
||||||
|
for(FluxValue &val: result.getValues()) {
|
||||||
|
// Check whether the value is null
|
||||||
|
if(!val.isNull()) {
|
||||||
|
// Use raw string, unconverted value
|
||||||
|
Serial.print(val.getRawValue());
|
||||||
|
} else {
|
||||||
|
// Print null value substite
|
||||||
|
Serial.print("<null>");
|
||||||
|
}
|
||||||
|
Serial.print(",");
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if(result.getError().length() > 0) {
|
||||||
|
Serial.print("Query result error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the result
|
||||||
|
result.close();
|
||||||
|
|
||||||
|
//Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,148 @@
|
||||||
|
/**
|
||||||
|
* QueryTable Example code for InfluxDBClient library for Arduino.
|
||||||
|
*
|
||||||
|
* This example demonstrates querying recent history of values of WiFi signal level measured and stored in BasicWrite and SecureWrite examples.
|
||||||
|
*
|
||||||
|
* Demonstrates connection to any InfluxDB instance accesible via:
|
||||||
|
* - unsecured http://...
|
||||||
|
* - secure https://... (appropriate certificate is required)
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
*
|
||||||
|
* Enter WiFi and InfluxDB parameters below
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086
|
||||||
|
#define INFLUXDB_URL "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use any non empty string
|
||||||
|
#define INFLUXDB_ORG "org name/id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
// InfluxDB 1.8+ (v2 compatibility API) use database name
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Accurate time is necessary for certificate validation
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Construct a Flux query
|
||||||
|
// Query will list RSSI for last 24 hours for each connected WiFi network of this device type
|
||||||
|
String query = "from(bucket: \"" INFLUXDB_BUCKET "\") |> range(start: -24h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
|
||||||
|
query += " and r.device == \"" DEVICE "\")";
|
||||||
|
|
||||||
|
Serial.println("==== List results ====");
|
||||||
|
|
||||||
|
// Print composed query
|
||||||
|
Serial.print("Querying with: ");
|
||||||
|
Serial.println(query);
|
||||||
|
|
||||||
|
// Send query to the server and get result
|
||||||
|
FluxQueryResult result = client.query(query);
|
||||||
|
|
||||||
|
// Iterate over rows. Even there is just one row, next() must be called at least once.
|
||||||
|
while (result.next()) {
|
||||||
|
// Check for new grouping key
|
||||||
|
if(result.hasTableChanged()) {
|
||||||
|
Serial.println("Table:");
|
||||||
|
Serial.print(" ");
|
||||||
|
// Print all columns name
|
||||||
|
for(String &name: result.getColumnsName()) {
|
||||||
|
Serial.print(name);
|
||||||
|
Serial.print(",");
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
Serial.print(" ");
|
||||||
|
// Print all columns datatype
|
||||||
|
for(String &tp: result.getColumnsDatatype()) {
|
||||||
|
Serial.print(tp);
|
||||||
|
Serial.print(",");
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
Serial.print(" ");
|
||||||
|
// Print values of the row
|
||||||
|
for(FluxValue &val: result.getValues()) {
|
||||||
|
// Check whether the value is null
|
||||||
|
if(!val.isNull()) {
|
||||||
|
// Use raw string, unconverted value
|
||||||
|
Serial.print(val.getRawValue());
|
||||||
|
} else {
|
||||||
|
// Print null value substite
|
||||||
|
Serial.print("<null>");
|
||||||
|
}
|
||||||
|
Serial.print(",");
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there was an error
|
||||||
|
if(result.getError().length() > 0) {
|
||||||
|
Serial.print("Query result error: ");
|
||||||
|
Serial.println(result.getError());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the result
|
||||||
|
result.close();
|
||||||
|
|
||||||
|
//Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,167 @@
|
||||||
|
/**
|
||||||
|
* 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)
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
* 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>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// 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 "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
// 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"
|
||||||
|
// NTP servers the for time synchronization.
|
||||||
|
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
|
||||||
|
#define NTP_SERVER1 "pool.ntp.org"
|
||||||
|
#define NTP_SERVER2 "time.nis.gov"
|
||||||
|
#define WRITE_PRECISION WritePrecision::S
|
||||||
|
#define MAX_BATCH_SIZE 10
|
||||||
|
#define WRITE_BUFFER_SIZE 30
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection
|
||||||
|
//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
|
||||||
|
// Data point
|
||||||
|
Point sensorStatus("wifi_status");
|
||||||
|
|
||||||
|
// Number for loops to sync time using NTP
|
||||||
|
int iterations = 0;
|
||||||
|
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Add tags
|
||||||
|
sensorStatus.addTag("device", DEVICE);
|
||||||
|
sensorStatus.addTag("SSID", WiFi.SSID());
|
||||||
|
|
||||||
|
// Alternatively, set insecure connection to skip server certificate validation
|
||||||
|
//client.setInsecure();
|
||||||
|
|
||||||
|
// Accurate time is necessary for certificate validation and writing in batches
|
||||||
|
// Syncing progress and the time will be printed to Serial.
|
||||||
|
timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2);
|
||||||
|
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enable messages batching and retry buffer
|
||||||
|
client.setWriteOptions(WriteOptions().writePrecision(WRITE_PRECISION).batchSize(MAX_BATCH_SIZE).bufferSize(WRITE_BUFFER_SIZE));
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Sync time for batching once per hour
|
||||||
|
if (iterations++ >= 360) {
|
||||||
|
timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2);
|
||||||
|
iterations = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Report networks (low priority data) just in case we successfully wrote the previous batch
|
||||||
|
if (client.isBufferEmpty()) {
|
||||||
|
// Report all the detected wifi networks
|
||||||
|
int networks = WiFi.scanNetworks();
|
||||||
|
// Set identical time for the whole network scan
|
||||||
|
time_t tnow = time(nullptr);
|
||||||
|
for (int i = 0; i < networks; i++) {
|
||||||
|
Point sensorNetworks("wifi_networks");
|
||||||
|
sensorNetworks.addTag("device", DEVICE);
|
||||||
|
sensorNetworks.addTag("SSID", WiFi.SSID(i));
|
||||||
|
sensorNetworks.addTag("channel", String(WiFi.channel(i)));
|
||||||
|
sensorNetworks.addTag("open", String(WiFi.encryptionType(i) == WIFI_AUTH_OPEN));
|
||||||
|
sensorNetworks.addField("rssi", WiFi.RSSI(i));
|
||||||
|
sensorNetworks.setTime(tnow); //set the time
|
||||||
|
|
||||||
|
// Print what are we exactly writing
|
||||||
|
Serial.print("Writing: ");
|
||||||
|
Serial.println(client.pointToLineProtocol(sensorNetworks));
|
||||||
|
|
||||||
|
// Write point into buffer - low priority measures
|
||||||
|
client.writePoint(sensorNetworks);
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
Serial.println("Wifi networks reporting skipped due to communication issues");
|
||||||
|
|
||||||
|
// Report RSSI of currently connected network
|
||||||
|
sensorStatus.setTime(time(nullptr));
|
||||||
|
sensorStatus.addField("rssi", WiFi.RSSI());
|
||||||
|
|
||||||
|
// Print what are we exactly writing
|
||||||
|
Serial.print("Writing: ");
|
||||||
|
Serial.println(client.pointToLineProtocol(sensorStatus));
|
||||||
|
|
||||||
|
// Write point into buffer - high priority measure
|
||||||
|
client.writePoint(sensorStatus);
|
||||||
|
|
||||||
|
// Clear fields for next usage. Tags remain the same.
|
||||||
|
sensorStatus.clearFields();
|
||||||
|
|
||||||
|
// If no Wifi signal, try to reconnect it
|
||||||
|
if (wifiMulti.run() != WL_CONNECTED) {
|
||||||
|
Serial.println("Wifi connection lost");
|
||||||
|
}
|
||||||
|
|
||||||
|
// End of the iteration - force write of all the values into InfluxDB as single transaction
|
||||||
|
Serial.println("Flushing data into InfluxDB");
|
||||||
|
if (!client.flushBuffer()) {
|
||||||
|
Serial.print("InfluxDB flush failed: ");
|
||||||
|
Serial.println(client.getLastErrorMessage());
|
||||||
|
Serial.print("Full buffer: ");
|
||||||
|
Serial.println(client.isBufferFull() ? "Yes" : "No");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
|
@ -0,0 +1,167 @@
|
||||||
|
/**
|
||||||
|
* 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)
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
* 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>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// 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 "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
// 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"
|
||||||
|
// NTP servers the for time synchronization.
|
||||||
|
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
|
||||||
|
#define NTP_SERVER1 "pool.ntp.org"
|
||||||
|
#define NTP_SERVER2 "time.nis.gov"
|
||||||
|
#define WRITE_PRECISION WritePrecision::S
|
||||||
|
#define MAX_BATCH_SIZE 10
|
||||||
|
#define WRITE_BUFFER_SIZE 30
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection
|
||||||
|
//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
|
||||||
|
// Data point
|
||||||
|
Point sensorStatus("wifi_status");
|
||||||
|
|
||||||
|
// Number for loops to sync time using NTP
|
||||||
|
int iterations = 0;
|
||||||
|
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Add tags
|
||||||
|
sensorStatus.addTag("device", DEVICE);
|
||||||
|
sensorStatus.addTag("SSID", WiFi.SSID());
|
||||||
|
|
||||||
|
// Alternatively, set insecure connection to skip server certificate validation
|
||||||
|
//client.setInsecure();
|
||||||
|
|
||||||
|
// Accurate time is necessary for certificate validation and writing in batches
|
||||||
|
// Syncing progress and the time will be printed to Serial.
|
||||||
|
timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2);
|
||||||
|
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enable messages batching and retry buffer
|
||||||
|
client.setWriteOptions(WriteOptions().writePrecision(WRITE_PRECISION).batchSize(MAX_BATCH_SIZE).bufferSize(WRITE_BUFFER_SIZE));
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// Sync time for batching once per hour
|
||||||
|
if (iterations++ >= 360) {
|
||||||
|
timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2);
|
||||||
|
iterations = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Report networks (low priority data) just in case we successfully wrote the previous batch
|
||||||
|
if (client.isBufferEmpty()) {
|
||||||
|
// Report all the detected wifi networks
|
||||||
|
int networks = WiFi.scanNetworks();
|
||||||
|
// Set identical time for the whole network scan
|
||||||
|
time_t tnow = time(nullptr);
|
||||||
|
for (int i = 0; i < networks; i++) {
|
||||||
|
Point sensorNetworks("wifi_networks");
|
||||||
|
sensorNetworks.addTag("device", DEVICE);
|
||||||
|
sensorNetworks.addTag("SSID", WiFi.SSID(i));
|
||||||
|
sensorNetworks.addTag("channel", String(WiFi.channel(i)));
|
||||||
|
sensorNetworks.addTag("open", String(WiFi.encryptionType(i) == WIFI_AUTH_OPEN));
|
||||||
|
sensorNetworks.addField("rssi", WiFi.RSSI(i));
|
||||||
|
sensorNetworks.setTime(tnow); //set the time
|
||||||
|
|
||||||
|
// Print what are we exactly writing
|
||||||
|
Serial.print("Writing: ");
|
||||||
|
Serial.println(client.pointToLineProtocol(sensorNetworks));
|
||||||
|
|
||||||
|
// Write point into buffer - low priority measures
|
||||||
|
client.writePoint(sensorNetworks);
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
Serial.println("Wifi networks reporting skipped due to communication issues");
|
||||||
|
|
||||||
|
// Report RSSI of currently connected network
|
||||||
|
sensorStatus.setTime(time(nullptr));
|
||||||
|
sensorStatus.addField("rssi", WiFi.RSSI());
|
||||||
|
|
||||||
|
// Print what are we exactly writing
|
||||||
|
Serial.print("Writing: ");
|
||||||
|
Serial.println(client.pointToLineProtocol(sensorStatus));
|
||||||
|
|
||||||
|
// Write point into buffer - high priority measure
|
||||||
|
client.writePoint(sensorStatus);
|
||||||
|
|
||||||
|
// Clear fields for next usage. Tags remain the same.
|
||||||
|
sensorStatus.clearFields();
|
||||||
|
|
||||||
|
// If no Wifi signal, try to reconnect it
|
||||||
|
if (wifiMulti.run() != WL_CONNECTED) {
|
||||||
|
Serial.println("Wifi connection lost");
|
||||||
|
}
|
||||||
|
|
||||||
|
// End of the iteration - force write of all the values into InfluxDB as single transaction
|
||||||
|
Serial.println("Flushing data into InfluxDB");
|
||||||
|
if (!client.flushBuffer()) {
|
||||||
|
Serial.print("InfluxDB flush failed: ");
|
||||||
|
Serial.println(client.getLastErrorMessage());
|
||||||
|
Serial.print("Full buffer: ");
|
||||||
|
Serial.println(client.isBufferFull() ? "Yes" : "No");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
|
@ -0,0 +1,113 @@
|
||||||
|
/**
|
||||||
|
* 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)
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
* Measures signal level of the actually connected WiFi network
|
||||||
|
* This example demonstrates time handling, secure connection and measurement writing into InfluxDB
|
||||||
|
* Data can be immediately seen in a InfluxDB 2 Cloud UI - measurement wifi_status
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// 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 "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection
|
||||||
|
//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
|
||||||
|
// Data point
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Add tags
|
||||||
|
sensor.addTag("device", DEVICE);
|
||||||
|
sensor.addTag("SSID", WiFi.SSID());
|
||||||
|
|
||||||
|
// Alternatively, set insecure connection to skip server certificate validation
|
||||||
|
//client.setInsecure();
|
||||||
|
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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(client.pointToLineProtocol(sensor));
|
||||||
|
// If no Wifi signal, try to reconnect it
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
//Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
|
@ -0,0 +1,113 @@
|
||||||
|
/**
|
||||||
|
* 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)
|
||||||
|
* - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured)
|
||||||
|
* Measures signal level of the actually connected WiFi network
|
||||||
|
* This example demonstrates time handling, secure connection and measurement writing into InfluxDB
|
||||||
|
* Data can be immediately seen in a InfluxDB 2 Cloud UI - measurement wifi_status
|
||||||
|
**/
|
||||||
|
|
||||||
|
#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>
|
||||||
|
#include <InfluxDbCloud.h>
|
||||||
|
|
||||||
|
// WiFi AP SSID
|
||||||
|
#define WIFI_SSID "SSID"
|
||||||
|
// WiFi password
|
||||||
|
#define WIFI_PASSWORD "PASSWORD"
|
||||||
|
// 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 "server-url"
|
||||||
|
// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
|
||||||
|
#define INFLUXDB_TOKEN "server token"
|
||||||
|
// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
|
||||||
|
#define INFLUXDB_ORG "org id"
|
||||||
|
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
|
||||||
|
#define INFLUXDB_BUCKET "bucket name"
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
|
||||||
|
// InfluxDB client instance with preconfigured InfluxCloud certificate
|
||||||
|
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
|
||||||
|
// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection
|
||||||
|
//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
|
||||||
|
|
||||||
|
// Data point
|
||||||
|
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(500);
|
||||||
|
}
|
||||||
|
Serial.println();
|
||||||
|
|
||||||
|
// Add tags
|
||||||
|
sensor.addTag("device", DEVICE);
|
||||||
|
sensor.addTag("SSID", WiFi.SSID());
|
||||||
|
|
||||||
|
// Alternatively, set insecure connection to skip server certificate validation
|
||||||
|
//client.setInsecure();
|
||||||
|
|
||||||
|
// 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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(client.pointToLineProtocol(sensor));
|
||||||
|
// If no Wifi signal, try to reconnect it
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
//Wait 10s
|
||||||
|
Serial.println("Wait 10s");
|
||||||
|
delay(10000);
|
||||||
|
}
|
45
firmware/libraries/ESP8266_Influxdb/keywords.txt
Normal file
45
firmware/libraries/ESP8266_Influxdb/keywords.txt
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
# Syntax Coloring Map For InfluxDBClient library
|
||||||
|
|
||||||
|
# Datatypes (KEYWORD1)
|
||||||
|
WritePrecision KEYWORD1
|
||||||
|
Point KEYWORD1
|
||||||
|
InfluxDBClient KEYWORD1
|
||||||
|
InfluxData KEYWORD1
|
||||||
|
Influxdb KEYWORD1
|
||||||
|
FluxValue KEYWORD1
|
||||||
|
FluxQueryResult KEYWORD1
|
||||||
|
FluxDateTime KEYWORD1
|
||||||
|
|
||||||
|
# Methods and Functions (KEYWORD2)
|
||||||
|
addTag KEYWORD2
|
||||||
|
addField KEYWORD2
|
||||||
|
setTime KEYWORD2
|
||||||
|
clearFields KEYWORD2
|
||||||
|
clearTags KEYWORD2
|
||||||
|
hasFields KEYWORD2
|
||||||
|
hasTags KEYWORD2
|
||||||
|
hasTime KEYWORD2
|
||||||
|
toLineProtocol KEYWORD2
|
||||||
|
setWriteOptions KEYWORD2
|
||||||
|
validateConnection KEYWORD2
|
||||||
|
writeRecord KEYWORD2
|
||||||
|
writePoint KEYWORD2
|
||||||
|
query KEYWORD2
|
||||||
|
flushBuffer KEYWORD2
|
||||||
|
isBufferFull KEYWORD2
|
||||||
|
isBufferEmpty KEYWORD2
|
||||||
|
checkBuffer KEYWORD2
|
||||||
|
getLastStatusCode KEYWORD2
|
||||||
|
resetBuffer KEYWORD2
|
||||||
|
getLastErrorMessage KEYWORD2
|
||||||
|
getServerUrl KEYWORD2
|
||||||
|
setDb KEYWORD2
|
||||||
|
prepare KEYWORD2
|
||||||
|
write KEYWORD2
|
||||||
|
|
||||||
|
# Constants (LITERAL1)
|
||||||
|
NoTime LITERAL1
|
||||||
|
S LITERAL1
|
||||||
|
MS LITERAL1
|
||||||
|
US LITERAL1
|
||||||
|
NS LITERAL1
|
10
firmware/libraries/ESP8266_Influxdb/library.properties
Normal file
10
firmware/libraries/ESP8266_Influxdb/library.properties
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
name=ESP8266 Influxdb
|
||||||
|
version=3.12.1
|
||||||
|
author=Tobias Schürg, InfluxData
|
||||||
|
maintainer=Tobias Schürg, InfluxData
|
||||||
|
sentence=InfluxDB Client for Arduino.
|
||||||
|
url=https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino
|
||||||
|
paragraph=This library allows writing and reading data from InfluxDB server or InfluxDB Cloud. Supports authentication, secure communication over TLS, batching and retrying.
|
||||||
|
category=Data Storage
|
||||||
|
architectures=*
|
||||||
|
includes=InfluxDbClient.h
|
45
firmware/libraries/ESP8266_Influxdb/platformio.ini
Normal file
45
firmware/libraries/ESP8266_Influxdb/platformio.ini
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
; CanAirIO Sensorlib
|
||||||
|
;
|
||||||
|
; Full guide and details: https://github.com/kike-canaries/canairio_sensorlib
|
||||||
|
|
||||||
|
|
||||||
|
[platformio]
|
||||||
|
src_dir = ./test/
|
||||||
|
|
||||||
|
[env]
|
||||||
|
framework = arduino
|
||||||
|
upload_speed = 1500000
|
||||||
|
monitor_speed = 115200
|
||||||
|
monitor_filters = time
|
||||||
|
build_flags =
|
||||||
|
-D CORE_DEBUG_LEVEL=0
|
||||||
|
lib_deps =
|
||||||
|
https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino.git
|
||||||
|
|
||||||
|
[esp32_common]
|
||||||
|
platform = espressif32
|
||||||
|
board = esp32dev
|
||||||
|
framework = ${env.framework}
|
||||||
|
upload_speed = ${env.upload_speed}
|
||||||
|
monitor_speed = ${env.monitor_speed}
|
||||||
|
lib_deps = ${env.lib_deps}
|
||||||
|
build_flags =
|
||||||
|
${env.build_flags}
|
||||||
|
|
||||||
|
[esp8266_common]
|
||||||
|
platform = espressif8266
|
||||||
|
framework = ${env.framework}
|
||||||
|
board = esp12e
|
||||||
|
monitor_speed = ${env.monitor_speed}
|
||||||
|
build_flags =
|
||||||
|
${env.build_flags}
|
||||||
|
lib_deps =
|
||||||
|
${env.lib_deps}
|
||||||
|
|
||||||
|
[env:esp8266BasicTest]
|
||||||
|
extends = esp8266_common
|
||||||
|
|
||||||
|
[env:esp32BasicTest]
|
||||||
|
extends = esp32_common
|
||||||
|
|
||||||
|
|
244
firmware/libraries/ESP8266_Influxdb/src/BucketsClient 2.cpp
Normal file
244
firmware/libraries/ESP8266_Influxdb/src/BucketsClient 2.cpp
Normal file
|
@ -0,0 +1,244 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* BucketsClient.cpp: InfluxDB Buckets Client
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "BucketsClient.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
#include "util/debug.h"
|
||||||
|
|
||||||
|
static const char *propTemplate PROGMEM = "\"%s\":";
|
||||||
|
// Finds first id property from JSON response
|
||||||
|
enum class PropType {
|
||||||
|
String,
|
||||||
|
Number
|
||||||
|
};
|
||||||
|
|
||||||
|
static String findProperty(const char *prop,const String &json, PropType type = PropType::String);
|
||||||
|
|
||||||
|
static String findProperty(const char *prop,const String &json, PropType type) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Searching for %s in %s\n", prop, json.c_str());
|
||||||
|
int propLen = strlen_P(propTemplate)+strlen(prop)-2;
|
||||||
|
char *propSearch = new char[propLen+1];
|
||||||
|
sprintf_P(propSearch, propTemplate, prop);
|
||||||
|
int i = json.indexOf(propSearch);
|
||||||
|
delete [] propSearch;
|
||||||
|
if(i>-1) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found at %d\n", i);
|
||||||
|
switch(type) {
|
||||||
|
case PropType::String:
|
||||||
|
i = json.indexOf("\"", i+propLen);
|
||||||
|
if(i>-1) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found starting \" at %d\n", i);
|
||||||
|
int e = json.indexOf("\"", i+1);
|
||||||
|
if(e>-1) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found ending \" at %d\n", e);
|
||||||
|
return json.substring(i+1, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case PropType::Number:
|
||||||
|
i = i+propLen;
|
||||||
|
while(json[i] == ' ') {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found beginning of number at %d\n", i);
|
||||||
|
int e = json.indexOf(",", i+1);
|
||||||
|
if(e>-1) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found , at %d\n", e);
|
||||||
|
return json.substring(i, e);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
char *copyChars(const char *str) {
|
||||||
|
char *ret = new char[strlen(str)+1];
|
||||||
|
strcpy(ret, str);
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::Bucket():_data(nullptr) {
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::Bucket(const char *id, const char *name, const uint32_t expire) {
|
||||||
|
_data = std::make_shared<Data>(id, name, expire);
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::Bucket(const Bucket &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket& Bucket::operator=(const Bucket& other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::~Bucket() {
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Bucket::Data::Data(const char *id, const char *name, const uint32_t expire) {
|
||||||
|
this->id = copyChars(id);
|
||||||
|
this->name = copyChars(name);
|
||||||
|
this->expire = expire;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::Data::~Data() {
|
||||||
|
delete [] id;
|
||||||
|
delete [] name;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const char *toStringTmplt PROGMEM = "Bucket: ID %s, Name %s, expire %u";
|
||||||
|
String Bucket::toString() const {
|
||||||
|
int len = strlen_P(toStringTmplt) + (_data?strlen(_data->name):0) + (_data?strlen(_data->id):0) + 10 + 1; //10 is maximum length of string representation of expire
|
||||||
|
char *buff = new char[len];
|
||||||
|
sprintf_P(buff, toStringTmplt, getID(), getName(), getExpire());
|
||||||
|
String ret = buff;
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient::BucketsClient() {
|
||||||
|
_data = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient::BucketsClient(ConnectionInfo *pConnInfo, HTTPService *service) {
|
||||||
|
_data = std::make_shared<Data>(pConnInfo, service);
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient::BucketsClient(const BucketsClient &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient &BucketsClient::operator=(const BucketsClient &other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient &BucketsClient::operator=(std::nullptr_t) {
|
||||||
|
_data = nullptr;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
String BucketsClient::getOrgID(const char *org) {
|
||||||
|
if(!_data) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if(isValidID(org)) {
|
||||||
|
return org;
|
||||||
|
}
|
||||||
|
String url = _data->pService->getServerAPIURL();
|
||||||
|
url += "orgs?org=";
|
||||||
|
url += urlEncode(org);
|
||||||
|
String id;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] getOrgID: url %s\n", url.c_str());
|
||||||
|
_data->pService->doGET(url.c_str(), 200, [&id](HTTPClient *client){
|
||||||
|
id = findProperty("id",client->getString());
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BucketsClient::checkBucketExists(const char *bucketName) {
|
||||||
|
Bucket b = findBucket(bucketName);
|
||||||
|
return !b.isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *CreateBucketTemplate PROGMEM = "{\"name\":\"%s\",\"orgID\":\"%s\",\"retentionRules\":[{\"everySeconds\":%u}]}";
|
||||||
|
|
||||||
|
Bucket BucketsClient::createBucket(const char *bucketName, uint32_t expiresSec) {
|
||||||
|
Bucket b;
|
||||||
|
if(_data) {
|
||||||
|
String orgID = getOrgID(_data->pConnInfo->org.c_str());
|
||||||
|
|
||||||
|
if(!orgID.length()) {
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
int expireLen = 0;
|
||||||
|
uint32_t e = expiresSec;
|
||||||
|
do {
|
||||||
|
expireLen++;
|
||||||
|
e /=10;
|
||||||
|
} while(e > 0);
|
||||||
|
int len = strlen_P(CreateBucketTemplate) + strlen(bucketName) + orgID.length() + expireLen+1;
|
||||||
|
char *body = new char[len];
|
||||||
|
sprintf_P(body, CreateBucketTemplate, bucketName, orgID.c_str(), expiresSec);
|
||||||
|
String url = _data->pService->getServerAPIURL();
|
||||||
|
url += "buckets";
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] CreateBucket: url %s, body %s\n", url.c_str(), body);
|
||||||
|
_data->pService->doPOST(url.c_str(), body, "application/json", 201, [&b](HTTPClient *client){
|
||||||
|
String resp = client->getString();
|
||||||
|
String id = findProperty("id", resp);
|
||||||
|
String name = findProperty("name", resp);
|
||||||
|
String expireStr = findProperty("everySeconds", resp, PropType::Number);
|
||||||
|
uint32_t expire = strtoul(expireStr.c_str(), nullptr, 10);
|
||||||
|
b = Bucket(id.c_str(), name.c_str(), expire);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
delete [] body;
|
||||||
|
}
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BucketsClient::deleteBucket(const char *id) {
|
||||||
|
if(!_data) {
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String url = _data->pService->getServerAPIURL();
|
||||||
|
url += "buckets/";
|
||||||
|
url += id;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] deleteBucket: url %s\n", url.c_str());
|
||||||
|
return _data->pService->doDELETE(url.c_str(), 204, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket BucketsClient::findBucket(const char *bucketName) {
|
||||||
|
Bucket b;
|
||||||
|
if(_data) {
|
||||||
|
String url = _data->pService->getServerAPIURL();
|
||||||
|
url += "buckets?name=";
|
||||||
|
url += urlEncode(bucketName);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] findBucket: url %s\n", url.c_str());
|
||||||
|
_data->pService->doGET(url.c_str(), 200, [&b](HTTPClient *client){
|
||||||
|
String resp = client->getString();
|
||||||
|
String id = findProperty("id", resp);
|
||||||
|
if(id.length()) {
|
||||||
|
String name = findProperty("name", resp);
|
||||||
|
String expireStr = findProperty("everySeconds", resp, PropType::Number);
|
||||||
|
uint32_t expire = strtoul(expireStr.c_str(), nullptr, 10);
|
||||||
|
b = Bucket(id.c_str(), name.c_str(), expire);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return b;
|
||||||
|
}
|
122
firmware/libraries/ESP8266_Influxdb/src/BucketsClient 2.h
Normal file
122
firmware/libraries/ESP8266_Influxdb/src/BucketsClient 2.h
Normal file
|
@ -0,0 +1,122 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* BucketsClient.h: InfluxDB Buckets Client
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _BUCKETS_CLIENT_H_
|
||||||
|
#define _BUCKETS_CLIENT_H_
|
||||||
|
|
||||||
|
#include <HTTPService.h>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
class BucketsClient;
|
||||||
|
class Test;
|
||||||
|
/**
|
||||||
|
* Bucket represents a bucket in the InfluxDB 2 server
|
||||||
|
**/
|
||||||
|
class Bucket {
|
||||||
|
friend class BucketsClient;
|
||||||
|
friend class Test;
|
||||||
|
public:
|
||||||
|
// Create empty, invalid, bucket instance
|
||||||
|
Bucket();
|
||||||
|
// Create a bucket instance
|
||||||
|
Bucket(const char *id, const char *name, const uint32_t expire);
|
||||||
|
// Copy constructor
|
||||||
|
Bucket(const Bucket &other);
|
||||||
|
// Assignment operator
|
||||||
|
Bucket &operator=(const Bucket &other);
|
||||||
|
// for testing validity
|
||||||
|
operator bool() const { return !isNull(); }
|
||||||
|
// Clean bucket
|
||||||
|
~Bucket();
|
||||||
|
// Returns Bucket ID
|
||||||
|
const char *getID() const { return _data?_data->id:nullptr; }
|
||||||
|
// Retuns bucket name
|
||||||
|
const char *getName() const { return _data?_data->name:nullptr; }
|
||||||
|
// Retention policy in sec, 0 - inifinite
|
||||||
|
uint32_t getExpire() const { return _data?_data->expire:0; }
|
||||||
|
// Checks if it is null instance
|
||||||
|
bool isNull() const { return _data == nullptr; }
|
||||||
|
// String representation
|
||||||
|
String toString() const;
|
||||||
|
private:
|
||||||
|
class Data {
|
||||||
|
public:
|
||||||
|
Data(const char *id, const char *name, const uint32_t expire);
|
||||||
|
~Data();
|
||||||
|
char *id;
|
||||||
|
char *name;
|
||||||
|
uint32_t expire;
|
||||||
|
};
|
||||||
|
std::shared_ptr<Data> _data;
|
||||||
|
};
|
||||||
|
|
||||||
|
class InfluxDBClient;
|
||||||
|
class E2ETest;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BucketsClient is a client for managing buckets in the InfluxDB 2 server
|
||||||
|
* A new bucket can be created, or a bucket can be checked for existence by its name.
|
||||||
|
* A bucket can be also deleted.
|
||||||
|
**/
|
||||||
|
class BucketsClient {
|
||||||
|
friend class InfluxDBClient;
|
||||||
|
friend class Test;
|
||||||
|
friend class E2ETest;
|
||||||
|
public:
|
||||||
|
// Copy contructor
|
||||||
|
BucketsClient(const BucketsClient &other);
|
||||||
|
// Assignment operator
|
||||||
|
BucketsClient &operator=(const BucketsClient &other);
|
||||||
|
// nullptr assignment for clearing
|
||||||
|
BucketsClient &operator=(std::nullptr_t);
|
||||||
|
// for testing validity
|
||||||
|
operator bool() const { return !isNull(); }
|
||||||
|
// Returns true if a bucket exists
|
||||||
|
bool checkBucketExists(const char *bucketName);
|
||||||
|
// Returns a Bucket instance if a bucket is found.
|
||||||
|
Bucket findBucket(const char *bucketName);
|
||||||
|
// Creates a bucket with given name and optional retention policy. 0 means infinite.
|
||||||
|
Bucket createBucket(const char *bucketName, uint32_t expiresSec = 0);
|
||||||
|
// Delete a bucket with given id. Use findBucket to get a bucket with id.
|
||||||
|
bool deleteBucket(const char *id);
|
||||||
|
// Returns last error message
|
||||||
|
String getLastErrorMessage() { return _data?_data->pConnInfo->lastError:""; }
|
||||||
|
// check validity
|
||||||
|
bool isNull() const { return _data == nullptr; }
|
||||||
|
protected:
|
||||||
|
BucketsClient();
|
||||||
|
BucketsClient(ConnectionInfo *pConnInfo, HTTPService *service);
|
||||||
|
String getOrgID(const char *org);
|
||||||
|
private:
|
||||||
|
class Data {
|
||||||
|
public:
|
||||||
|
Data(ConnectionInfo *pConnInfo, HTTPService *pService):pConnInfo(pConnInfo),pService(pService) {};
|
||||||
|
ConnectionInfo *pConnInfo;
|
||||||
|
HTTPService *pService;
|
||||||
|
};
|
||||||
|
std::shared_ptr<Data> _data;
|
||||||
|
};
|
||||||
|
#endif
|
244
firmware/libraries/ESP8266_Influxdb/src/BucketsClient.cpp
Normal file
244
firmware/libraries/ESP8266_Influxdb/src/BucketsClient.cpp
Normal file
|
@ -0,0 +1,244 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* BucketsClient.cpp: InfluxDB Buckets Client
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "BucketsClient.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
#include "util/debug.h"
|
||||||
|
|
||||||
|
static const char *propTemplate PROGMEM = "\"%s\":";
|
||||||
|
// Finds first id property from JSON response
|
||||||
|
enum class PropType {
|
||||||
|
String,
|
||||||
|
Number
|
||||||
|
};
|
||||||
|
|
||||||
|
static String findProperty(const char *prop,const String &json, PropType type = PropType::String);
|
||||||
|
|
||||||
|
static String findProperty(const char *prop,const String &json, PropType type) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Searching for %s in %s\n", prop, json.c_str());
|
||||||
|
int propLen = strlen_P(propTemplate)+strlen(prop)-2;
|
||||||
|
char *propSearch = new char[propLen+1];
|
||||||
|
sprintf_P(propSearch, propTemplate, prop);
|
||||||
|
int i = json.indexOf(propSearch);
|
||||||
|
delete [] propSearch;
|
||||||
|
if(i>-1) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found at %d\n", i);
|
||||||
|
switch(type) {
|
||||||
|
case PropType::String:
|
||||||
|
i = json.indexOf("\"", i+propLen);
|
||||||
|
if(i>-1) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found starting \" at %d\n", i);
|
||||||
|
int e = json.indexOf("\"", i+1);
|
||||||
|
if(e>-1) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found ending \" at %d\n", e);
|
||||||
|
return json.substring(i+1, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case PropType::Number:
|
||||||
|
i = i+propLen;
|
||||||
|
while(json[i] == ' ') {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found beginning of number at %d\n", i);
|
||||||
|
int e = json.indexOf(",", i+1);
|
||||||
|
if(e>-1) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Found , at %d\n", e);
|
||||||
|
return json.substring(i, e);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
char *copyChars(const char *str) {
|
||||||
|
char *ret = new char[strlen(str)+1];
|
||||||
|
strcpy(ret, str);
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::Bucket():_data(nullptr) {
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::Bucket(const char *id, const char *name, const uint32_t expire) {
|
||||||
|
_data = std::make_shared<Data>(id, name, expire);
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::Bucket(const Bucket &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket& Bucket::operator=(const Bucket& other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::~Bucket() {
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Bucket::Data::Data(const char *id, const char *name, const uint32_t expire) {
|
||||||
|
this->id = copyChars(id);
|
||||||
|
this->name = copyChars(name);
|
||||||
|
this->expire = expire;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket::Data::~Data() {
|
||||||
|
delete [] id;
|
||||||
|
delete [] name;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const char *toStringTmplt PROGMEM = "Bucket: ID %s, Name %s, expire %u";
|
||||||
|
String Bucket::toString() const {
|
||||||
|
int len = strlen_P(toStringTmplt) + (_data?strlen(_data->name):0) + (_data?strlen(_data->id):0) + 10 + 1; //10 is maximum length of string representation of expire
|
||||||
|
char *buff = new char[len];
|
||||||
|
sprintf_P(buff, toStringTmplt, getID(), getName(), getExpire());
|
||||||
|
String ret = buff;
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient::BucketsClient() {
|
||||||
|
_data = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient::BucketsClient(ConnectionInfo *pConnInfo, HTTPService *service) {
|
||||||
|
_data = std::make_shared<Data>(pConnInfo, service);
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient::BucketsClient(const BucketsClient &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient &BucketsClient::operator=(const BucketsClient &other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient &BucketsClient::operator=(std::nullptr_t) {
|
||||||
|
_data = nullptr;
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
String BucketsClient::getOrgID(const char *org) {
|
||||||
|
if(!_data) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
if(isValidID(org)) {
|
||||||
|
return org;
|
||||||
|
}
|
||||||
|
String url = _data->pService->getServerAPIURL();
|
||||||
|
url += "orgs?org=";
|
||||||
|
url += urlEncode(org);
|
||||||
|
String id;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] getOrgID: url %s\n", url.c_str());
|
||||||
|
_data->pService->doGET(url.c_str(), 200, [&id](HTTPClient *client){
|
||||||
|
id = findProperty("id",client->getString());
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BucketsClient::checkBucketExists(const char *bucketName) {
|
||||||
|
Bucket b = findBucket(bucketName);
|
||||||
|
return !b.isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *CreateBucketTemplate PROGMEM = "{\"name\":\"%s\",\"orgID\":\"%s\",\"retentionRules\":[{\"everySeconds\":%u}]}";
|
||||||
|
|
||||||
|
Bucket BucketsClient::createBucket(const char *bucketName, uint32_t expiresSec) {
|
||||||
|
Bucket b;
|
||||||
|
if(_data) {
|
||||||
|
String orgID = getOrgID(_data->pConnInfo->org.c_str());
|
||||||
|
|
||||||
|
if(!orgID.length()) {
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
int expireLen = 0;
|
||||||
|
uint32_t e = expiresSec;
|
||||||
|
do {
|
||||||
|
expireLen++;
|
||||||
|
e /=10;
|
||||||
|
} while(e > 0);
|
||||||
|
int len = strlen_P(CreateBucketTemplate) + strlen(bucketName) + orgID.length() + expireLen+1;
|
||||||
|
char *body = new char[len];
|
||||||
|
sprintf_P(body, CreateBucketTemplate, bucketName, orgID.c_str(), expiresSec);
|
||||||
|
String url = _data->pService->getServerAPIURL();
|
||||||
|
url += "buckets";
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] CreateBucket: url %s, body %s\n", url.c_str(), body);
|
||||||
|
_data->pService->doPOST(url.c_str(), body, "application/json", 201, [&b](HTTPClient *client){
|
||||||
|
String resp = client->getString();
|
||||||
|
String id = findProperty("id", resp);
|
||||||
|
String name = findProperty("name", resp);
|
||||||
|
String expireStr = findProperty("everySeconds", resp, PropType::Number);
|
||||||
|
uint32_t expire = strtoul(expireStr.c_str(), nullptr, 10);
|
||||||
|
b = Bucket(id.c_str(), name.c_str(), expire);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
delete [] body;
|
||||||
|
}
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BucketsClient::deleteBucket(const char *id) {
|
||||||
|
if(!_data) {
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String url = _data->pService->getServerAPIURL();
|
||||||
|
url += "buckets/";
|
||||||
|
url += id;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] deleteBucket: url %s\n", url.c_str());
|
||||||
|
return _data->pService->doDELETE(url.c_str(), 204, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
Bucket BucketsClient::findBucket(const char *bucketName) {
|
||||||
|
Bucket b;
|
||||||
|
if(_data) {
|
||||||
|
String url = _data->pService->getServerAPIURL();
|
||||||
|
url += "buckets?name=";
|
||||||
|
url += urlEncode(bucketName);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] findBucket: url %s\n", url.c_str());
|
||||||
|
_data->pService->doGET(url.c_str(), 200, [&b](HTTPClient *client){
|
||||||
|
String resp = client->getString();
|
||||||
|
String id = findProperty("id", resp);
|
||||||
|
if(id.length()) {
|
||||||
|
String name = findProperty("name", resp);
|
||||||
|
String expireStr = findProperty("everySeconds", resp, PropType::Number);
|
||||||
|
uint32_t expire = strtoul(expireStr.c_str(), nullptr, 10);
|
||||||
|
b = Bucket(id.c_str(), name.c_str(), expire);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return b;
|
||||||
|
}
|
122
firmware/libraries/ESP8266_Influxdb/src/BucketsClient.h
Normal file
122
firmware/libraries/ESP8266_Influxdb/src/BucketsClient.h
Normal file
|
@ -0,0 +1,122 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* BucketsClient.h: InfluxDB Buckets Client
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _BUCKETS_CLIENT_H_
|
||||||
|
#define _BUCKETS_CLIENT_H_
|
||||||
|
|
||||||
|
#include <HTTPService.h>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
class BucketsClient;
|
||||||
|
class Test;
|
||||||
|
/**
|
||||||
|
* Bucket represents a bucket in the InfluxDB 2 server
|
||||||
|
**/
|
||||||
|
class Bucket {
|
||||||
|
friend class BucketsClient;
|
||||||
|
friend class Test;
|
||||||
|
public:
|
||||||
|
// Create empty, invalid, bucket instance
|
||||||
|
Bucket();
|
||||||
|
// Create a bucket instance
|
||||||
|
Bucket(const char *id, const char *name, const uint32_t expire);
|
||||||
|
// Copy constructor
|
||||||
|
Bucket(const Bucket &other);
|
||||||
|
// Assignment operator
|
||||||
|
Bucket &operator=(const Bucket &other);
|
||||||
|
// for testing validity
|
||||||
|
operator bool() const { return !isNull(); }
|
||||||
|
// Clean bucket
|
||||||
|
~Bucket();
|
||||||
|
// Returns Bucket ID
|
||||||
|
const char *getID() const { return _data?_data->id:nullptr; }
|
||||||
|
// Retuns bucket name
|
||||||
|
const char *getName() const { return _data?_data->name:nullptr; }
|
||||||
|
// Retention policy in sec, 0 - inifinite
|
||||||
|
uint32_t getExpire() const { return _data?_data->expire:0; }
|
||||||
|
// Checks if it is null instance
|
||||||
|
bool isNull() const { return _data == nullptr; }
|
||||||
|
// String representation
|
||||||
|
String toString() const;
|
||||||
|
private:
|
||||||
|
class Data {
|
||||||
|
public:
|
||||||
|
Data(const char *id, const char *name, const uint32_t expire);
|
||||||
|
~Data();
|
||||||
|
char *id;
|
||||||
|
char *name;
|
||||||
|
uint32_t expire;
|
||||||
|
};
|
||||||
|
std::shared_ptr<Data> _data;
|
||||||
|
};
|
||||||
|
|
||||||
|
class InfluxDBClient;
|
||||||
|
class E2ETest;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BucketsClient is a client for managing buckets in the InfluxDB 2 server
|
||||||
|
* A new bucket can be created, or a bucket can be checked for existence by its name.
|
||||||
|
* A bucket can be also deleted.
|
||||||
|
**/
|
||||||
|
class BucketsClient {
|
||||||
|
friend class InfluxDBClient;
|
||||||
|
friend class Test;
|
||||||
|
friend class E2ETest;
|
||||||
|
public:
|
||||||
|
// Copy contructor
|
||||||
|
BucketsClient(const BucketsClient &other);
|
||||||
|
// Assignment operator
|
||||||
|
BucketsClient &operator=(const BucketsClient &other);
|
||||||
|
// nullptr assignment for clearing
|
||||||
|
BucketsClient &operator=(std::nullptr_t);
|
||||||
|
// for testing validity
|
||||||
|
operator bool() const { return !isNull(); }
|
||||||
|
// Returns true if a bucket exists
|
||||||
|
bool checkBucketExists(const char *bucketName);
|
||||||
|
// Returns a Bucket instance if a bucket is found.
|
||||||
|
Bucket findBucket(const char *bucketName);
|
||||||
|
// Creates a bucket with given name and optional retention policy. 0 means infinite.
|
||||||
|
Bucket createBucket(const char *bucketName, uint32_t expiresSec = 0);
|
||||||
|
// Delete a bucket with given id. Use findBucket to get a bucket with id.
|
||||||
|
bool deleteBucket(const char *id);
|
||||||
|
// Returns last error message
|
||||||
|
String getLastErrorMessage() { return _data?_data->pConnInfo->lastError:""; }
|
||||||
|
// check validity
|
||||||
|
bool isNull() const { return _data == nullptr; }
|
||||||
|
protected:
|
||||||
|
BucketsClient();
|
||||||
|
BucketsClient(ConnectionInfo *pConnInfo, HTTPService *service);
|
||||||
|
String getOrgID(const char *org);
|
||||||
|
private:
|
||||||
|
class Data {
|
||||||
|
public:
|
||||||
|
Data(ConnectionInfo *pConnInfo, HTTPService *pService):pConnInfo(pConnInfo),pService(pService) {};
|
||||||
|
ConnectionInfo *pConnInfo;
|
||||||
|
HTTPService *pService;
|
||||||
|
};
|
||||||
|
std::shared_ptr<Data> _data;
|
||||||
|
};
|
||||||
|
#endif
|
220
firmware/libraries/ESP8266_Influxdb/src/HTTPService 2.cpp
Normal file
220
firmware/libraries/ESP8266_Influxdb/src/HTTPService 2.cpp
Normal file
|
@ -0,0 +1,220 @@
|
||||||
|
|
||||||
|
#include "HTTPService.h"
|
||||||
|
#include "Platform.h"
|
||||||
|
#include "Version.h"
|
||||||
|
|
||||||
|
#include "util/debug.h"
|
||||||
|
|
||||||
|
static const char UserAgent[] PROGMEM = "influxdb-client-arduino/" INFLUXDB_CLIENT_VERSION " (" INFLUXDB_CLIENT_PLATFORM " " INFLUXDB_CLIENT_PLATFORM_VERSION ")";
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
bool checkMFLN(BearSSL::WiFiClientSecure *client, String url);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// This cannot be put to PROGMEM due to the way how it is used
|
||||||
|
static const char *RetryAfter = "Retry-After";
|
||||||
|
const char *TransferEncoding = "Transfer-Encoding";
|
||||||
|
|
||||||
|
HTTPService::HTTPService(ConnectionInfo *pConnInfo):_pConnInfo(pConnInfo) {
|
||||||
|
_apiURL = pConnInfo->serverUrl;
|
||||||
|
_apiURL += "/api/v2/";
|
||||||
|
bool https = pConnInfo->serverUrl.startsWith("https");
|
||||||
|
if(https) {
|
||||||
|
#if defined(ESP8266)
|
||||||
|
BearSSL::WiFiClientSecure *wifiClientSec = new BearSSL::WiFiClientSecure;
|
||||||
|
if (pConnInfo->insecure) {
|
||||||
|
wifiClientSec->setInsecure();
|
||||||
|
} else if(pConnInfo->certInfo && strlen_P(pConnInfo->certInfo) > 0) {
|
||||||
|
if(strlen_P(pConnInfo->certInfo) > 60 ) { //differentiate fingerprint and cert
|
||||||
|
_cert = new BearSSL::X509List(pConnInfo->certInfo);
|
||||||
|
wifiClientSec->setTrustAnchors(_cert);
|
||||||
|
} else {
|
||||||
|
wifiClientSec->setFingerprint(pConnInfo->certInfo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkMFLN(wifiClientSec, pConnInfo->serverUrl);
|
||||||
|
#elif defined(ESP32)
|
||||||
|
WiFiClientSecure *wifiClientSec = new WiFiClientSecure;
|
||||||
|
if (pConnInfo->insecure) {
|
||||||
|
#ifndef ARDUINO_ESP32_RELEASE_1_0_4
|
||||||
|
// This works only in ESP32 SDK 1.0.5 and higher
|
||||||
|
wifiClientSec->setInsecure();
|
||||||
|
#endif
|
||||||
|
} else if(pConnInfo->certInfo && strlen_P(pConnInfo->certInfo) > 0) {
|
||||||
|
wifiClientSec->setCACert(pConnInfo->certInfo);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
_wifiClient = wifiClientSec;
|
||||||
|
} else {
|
||||||
|
_wifiClient = new WiFiClient;
|
||||||
|
}
|
||||||
|
if(!_httpClient) {
|
||||||
|
_httpClient = new HTTPClient;
|
||||||
|
}
|
||||||
|
_httpClient->setReuse(_httpOptions._connectionReuse);
|
||||||
|
|
||||||
|
_httpClient->setUserAgent(FPSTR(UserAgent));
|
||||||
|
};
|
||||||
|
|
||||||
|
HTTPService::~HTTPService() {
|
||||||
|
if(_httpClient) {
|
||||||
|
delete _httpClient;
|
||||||
|
_httpClient = nullptr;
|
||||||
|
}
|
||||||
|
if(_wifiClient) {
|
||||||
|
delete _wifiClient;
|
||||||
|
_wifiClient = nullptr;
|
||||||
|
}
|
||||||
|
#if defined(ESP8266)
|
||||||
|
if(_cert) {
|
||||||
|
delete _cert;
|
||||||
|
_cert = nullptr;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void HTTPService::setHTTPOptions(const HTTPOptions & httpOptions) {
|
||||||
|
_httpOptions = httpOptions;
|
||||||
|
if(!_httpClient) {
|
||||||
|
_httpClient = new HTTPClient;
|
||||||
|
}
|
||||||
|
_httpClient->setReuse(_httpOptions._connectionReuse);
|
||||||
|
_httpClient->setTimeout(_httpOptions._httpReadTimeout);
|
||||||
|
#if defined(ESP32)
|
||||||
|
_httpClient->setConnectTimeout(_httpOptions._httpReadTimeout);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse URL for host and port and call probeMaxFragmentLength
|
||||||
|
#if defined(ESP8266)
|
||||||
|
bool checkMFLN(BearSSL::WiFiClientSecure *client, String url) {
|
||||||
|
int index = url.indexOf(':');
|
||||||
|
if(index < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String protocol = url.substring(0, index);
|
||||||
|
int port = -1;
|
||||||
|
url.remove(0, (index + 3)); // remove http:// or https://
|
||||||
|
|
||||||
|
if (protocol == "http") {
|
||||||
|
// set default port for 'http'
|
||||||
|
port = 80;
|
||||||
|
} else if (protocol == "https") {
|
||||||
|
// set default port for 'https'
|
||||||
|
port = 443;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
index = url.indexOf('/');
|
||||||
|
String host = url.substring(0, index);
|
||||||
|
url.remove(0, index); // remove host
|
||||||
|
// check Authorization
|
||||||
|
index = host.indexOf('@');
|
||||||
|
if(index >= 0) {
|
||||||
|
host.remove(0, index + 1); // remove auth part including @
|
||||||
|
}
|
||||||
|
// get port
|
||||||
|
index = host.indexOf(':');
|
||||||
|
if(index >= 0) {
|
||||||
|
String portS = host;
|
||||||
|
host = host.substring(0, index); // hostname
|
||||||
|
portS.remove(0, (index + 1)); // remove hostname + :
|
||||||
|
port = portS.toInt(); // get port
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] probeMaxFragmentLength to %s:%d\n", host.c_str(), port);
|
||||||
|
bool mfln = client->probeMaxFragmentLength(host, port, 1024);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] MFLN:%s\n", mfln ? "yes" : "no");
|
||||||
|
if (mfln) {
|
||||||
|
client->setBufferSizes(1024, 1024);
|
||||||
|
}
|
||||||
|
return mfln;
|
||||||
|
}
|
||||||
|
#endif //ESP8266
|
||||||
|
|
||||||
|
bool HTTPService::beforeRequest(const char *url) {
|
||||||
|
if(!_httpClient->begin(*_wifiClient, url)) {
|
||||||
|
_pConnInfo->lastError = F("begin failed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(_pConnInfo->authToken.length() > 0) {
|
||||||
|
_httpClient->addHeader(F("Authorization"), "Token " + _pConnInfo->authToken);
|
||||||
|
}
|
||||||
|
const char * headerKeys[] = {RetryAfter, TransferEncoding} ;
|
||||||
|
_httpClient->collectHeaders(headerKeys, 2);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::doPOST(const char *url, const char *data, const char *contentType, int expectedCode, httpResponseCallback cb) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] POST request - %s, data: %dbytes, type %s\n", url, strlen(data), contentType);
|
||||||
|
if(!beforeRequest(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(contentType) {
|
||||||
|
_httpClient->addHeader(F("Content-Type"), FPSTR(contentType));
|
||||||
|
}
|
||||||
|
_lastStatusCode = _httpClient->POST((uint8_t *) data, strlen(data));
|
||||||
|
return afterRequest(expectedCode, cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::doPOST(const char *url, Stream *stream, const char *contentType, int expectedCode, httpResponseCallback cb) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] POST request - %s, data: %dbytes, type %s\n", url, stream->available(), contentType);
|
||||||
|
if(!beforeRequest(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(contentType) {
|
||||||
|
_httpClient->addHeader(F("Content-Type"), FPSTR(contentType));
|
||||||
|
}
|
||||||
|
_lastStatusCode = _httpClient->sendRequest("POST", stream, stream->available());
|
||||||
|
return afterRequest(expectedCode, cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::doGET(const char *url, int expectedCode, httpResponseCallback cb) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] GET request - %s\n", url);
|
||||||
|
if(!beforeRequest(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_lastStatusCode = _httpClient->GET();
|
||||||
|
return afterRequest(expectedCode, cb, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::doDELETE(const char *url, int expectedCode, httpResponseCallback cb) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] DELETE - %s\n", url);
|
||||||
|
if(!beforeRequest(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_lastStatusCode = _httpClient->sendRequest("DELETE");
|
||||||
|
return afterRequest(expectedCode, cb, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::afterRequest(int expectedStatusCode, httpResponseCallback cb, bool modifyLastConnStatus) {
|
||||||
|
if(modifyLastConnStatus) {
|
||||||
|
_lastRequestTime = millis();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HTTP status code - %d\n", _lastStatusCode);
|
||||||
|
_lastRetryAfter = 0;
|
||||||
|
if(_lastStatusCode >= 429) { //retryable server errors
|
||||||
|
if(_httpClient->hasHeader(RetryAfter)) {
|
||||||
|
_lastRetryAfter = _httpClient->header(RetryAfter).toInt();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Reply after - %d\n", _lastRetryAfter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_pConnInfo->lastError = (char *)nullptr;
|
||||||
|
bool ret = _lastStatusCode == expectedStatusCode;
|
||||||
|
bool endConnection = true;
|
||||||
|
if(!ret) {
|
||||||
|
if(_lastStatusCode > 0) {
|
||||||
|
_pConnInfo->lastError = _httpClient->getString();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Response:\n%s\n", _pConnInfo->lastError.c_str());
|
||||||
|
} else {
|
||||||
|
_pConnInfo->lastError = _httpClient->errorToString(_lastStatusCode);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[E] Error - %s\n", _pConnInfo->lastError.c_str());
|
||||||
|
}
|
||||||
|
} else if(cb){
|
||||||
|
endConnection = cb(_httpClient);
|
||||||
|
}
|
||||||
|
if(endConnection) {
|
||||||
|
_httpClient->end();
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
136
firmware/libraries/ESP8266_Influxdb/src/HTTPService 2.h
Normal file
136
firmware/libraries/ESP8266_Influxdb/src/HTTPService 2.h
Normal file
|
@ -0,0 +1,136 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* HTTPService.h: HTTP Service
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _HTTP_SERVICE_H_
|
||||||
|
#define _HTTP_SERVICE_H_
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#if defined(ESP8266)
|
||||||
|
# include <WiFiClientSecureBearSSL.h>
|
||||||
|
# include <ESP8266HTTPClient.h>
|
||||||
|
#elif defined(ESP32)
|
||||||
|
# include <HTTPClient.h>
|
||||||
|
#else
|
||||||
|
# error "This library currently supports only ESP8266 and ESP32."
|
||||||
|
#endif
|
||||||
|
#include "Options.h"
|
||||||
|
|
||||||
|
|
||||||
|
class Test;
|
||||||
|
typedef std::function<bool(HTTPClient *client)> httpResponseCallback;
|
||||||
|
extern const char *TransferEncoding;
|
||||||
|
|
||||||
|
struct ConnectionInfo {
|
||||||
|
// Connection info
|
||||||
|
String serverUrl;
|
||||||
|
// Write & query targets
|
||||||
|
String bucket;
|
||||||
|
String org;
|
||||||
|
// v2 authetication token
|
||||||
|
String authToken;
|
||||||
|
// Version of InfluxDB 1 or 2
|
||||||
|
uint8_t dbVersion;
|
||||||
|
// V1 user authetication
|
||||||
|
String user;
|
||||||
|
String password;
|
||||||
|
// Certificate info
|
||||||
|
const char *certInfo;
|
||||||
|
// flag if https should ignore cert validation
|
||||||
|
bool insecure;
|
||||||
|
// Error message of last failed operation
|
||||||
|
String lastError;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTPService provides HTTP methods for communicating with InfluxDBServer,
|
||||||
|
* while taking care of Authorization and error handling
|
||||||
|
**/
|
||||||
|
class HTTPService {
|
||||||
|
friend class Test;
|
||||||
|
private:
|
||||||
|
// Connection info data
|
||||||
|
ConnectionInfo *_pConnInfo;
|
||||||
|
// Server API URL
|
||||||
|
String _apiURL;
|
||||||
|
// Last time in ms we made are a request to server
|
||||||
|
uint32_t _lastRequestTime = 0;
|
||||||
|
// HTTP status code of last request to server
|
||||||
|
int _lastStatusCode = 0;
|
||||||
|
// Underlying HTTPClient instance
|
||||||
|
HTTPClient *_httpClient = nullptr;
|
||||||
|
// Underlying connection object
|
||||||
|
WiFiClient *_wifiClient = nullptr;
|
||||||
|
#ifdef ESP8266
|
||||||
|
// Trusted cert chain
|
||||||
|
BearSSL::X509List *_cert = nullptr;
|
||||||
|
#endif
|
||||||
|
// Store retry timeout suggested by server after last request
|
||||||
|
int _lastRetryAfter = 0;
|
||||||
|
// HTTP options
|
||||||
|
HTTPOptions _httpOptions;
|
||||||
|
protected:
|
||||||
|
// Sets request params
|
||||||
|
bool beforeRequest(const char *url);
|
||||||
|
// Handles response
|
||||||
|
bool afterRequest(int expectedStatusCode, httpResponseCallback cb, bool modifyLastConnStatus = true);
|
||||||
|
public:
|
||||||
|
// Creates HTTPService instance
|
||||||
|
// serverUrl - url of the InfluxDB 2 server (e.g. http://localhost:8086)
|
||||||
|
// authToken - InfluxDB 2 authorization token
|
||||||
|
// certInfo - InfluxDB 2 server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM.
|
||||||
|
HTTPService(ConnectionInfo *pConnInfo);
|
||||||
|
// Clean instance on deletion
|
||||||
|
~HTTPService();
|
||||||
|
// Sets custom HTTP options. See HTTPOptions doc for more info.
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// Example:
|
||||||
|
// service.setHTTPOptions(HTTPOptions().httpReadTimeout(20000)).
|
||||||
|
void setHTTPOptions(const HTTPOptions &httpOptions);
|
||||||
|
// Returns current HTTPOption
|
||||||
|
HTTPOptions &getHTTPOptions() { return _httpOptions; }
|
||||||
|
// Performs HTTP POST by sending data. On success calls response call back
|
||||||
|
bool doPOST(const char *url, const char *data, const char *contentType, int expectedCode, httpResponseCallback cb);
|
||||||
|
// Performs HTTP POST by sending stream. On success calls response call back
|
||||||
|
bool doPOST(const char *url, Stream *stream, const char *contentType, int expectedCode, httpResponseCallback cb);
|
||||||
|
// Performs HTTP GET. On success calls response call back
|
||||||
|
bool doGET(const char *url, int expectedCode, httpResponseCallback cb);
|
||||||
|
// Performs HTTP DELETE. On success calls response call back
|
||||||
|
bool doDELETE(const char *url, int expectedCode, httpResponseCallback cb);
|
||||||
|
// Returns InfluxDBServer API URL
|
||||||
|
String getServerAPIURL() const { return _apiURL; }
|
||||||
|
// Returns value of the Retry-After HTTP header from recent call. 0 if it was missing.
|
||||||
|
int getLastRetryAfter() const { return _lastRetryAfter; }
|
||||||
|
// Returns HTTP status code of recent call.
|
||||||
|
int getLastStatusCode() const { return _lastStatusCode; }
|
||||||
|
// Returns time of recent call successful call.
|
||||||
|
uint32_t getLastRequestTime() const { return _lastRequestTime; }
|
||||||
|
// Returns response of last failed call.
|
||||||
|
String getLastErrorMessage() const { return _pConnInfo->lastError; }
|
||||||
|
// Returns true if HTTP connection is kept open
|
||||||
|
bool isConnected() const { return _httpClient && _httpClient->connected(); }
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_HTTP_SERVICE_H_
|
220
firmware/libraries/ESP8266_Influxdb/src/HTTPService.cpp
Normal file
220
firmware/libraries/ESP8266_Influxdb/src/HTTPService.cpp
Normal file
|
@ -0,0 +1,220 @@
|
||||||
|
|
||||||
|
#include "HTTPService.h"
|
||||||
|
#include "Platform.h"
|
||||||
|
#include "Version.h"
|
||||||
|
|
||||||
|
#include "util/debug.h"
|
||||||
|
|
||||||
|
static const char UserAgent[] PROGMEM = "influxdb-client-arduino/" INFLUXDB_CLIENT_VERSION " (" INFLUXDB_CLIENT_PLATFORM " " INFLUXDB_CLIENT_PLATFORM_VERSION ")";
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
bool checkMFLN(BearSSL::WiFiClientSecure *client, String url);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// This cannot be put to PROGMEM due to the way how it is used
|
||||||
|
static const char *RetryAfter = "Retry-After";
|
||||||
|
const char *TransferEncoding = "Transfer-Encoding";
|
||||||
|
|
||||||
|
HTTPService::HTTPService(ConnectionInfo *pConnInfo):_pConnInfo(pConnInfo) {
|
||||||
|
_apiURL = pConnInfo->serverUrl;
|
||||||
|
_apiURL += "/api/v2/";
|
||||||
|
bool https = pConnInfo->serverUrl.startsWith("https");
|
||||||
|
if(https) {
|
||||||
|
#if defined(ESP8266)
|
||||||
|
BearSSL::WiFiClientSecure *wifiClientSec = new BearSSL::WiFiClientSecure;
|
||||||
|
if (pConnInfo->insecure) {
|
||||||
|
wifiClientSec->setInsecure();
|
||||||
|
} else if(pConnInfo->certInfo && strlen_P(pConnInfo->certInfo) > 0) {
|
||||||
|
if(strlen_P(pConnInfo->certInfo) > 60 ) { //differentiate fingerprint and cert
|
||||||
|
_cert = new BearSSL::X509List(pConnInfo->certInfo);
|
||||||
|
wifiClientSec->setTrustAnchors(_cert);
|
||||||
|
} else {
|
||||||
|
wifiClientSec->setFingerprint(pConnInfo->certInfo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkMFLN(wifiClientSec, pConnInfo->serverUrl);
|
||||||
|
#elif defined(ESP32)
|
||||||
|
WiFiClientSecure *wifiClientSec = new WiFiClientSecure;
|
||||||
|
if (pConnInfo->insecure) {
|
||||||
|
#ifndef ARDUINO_ESP32_RELEASE_1_0_4
|
||||||
|
// This works only in ESP32 SDK 1.0.5 and higher
|
||||||
|
wifiClientSec->setInsecure();
|
||||||
|
#endif
|
||||||
|
} else if(pConnInfo->certInfo && strlen_P(pConnInfo->certInfo) > 0) {
|
||||||
|
wifiClientSec->setCACert(pConnInfo->certInfo);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
_wifiClient = wifiClientSec;
|
||||||
|
} else {
|
||||||
|
_wifiClient = new WiFiClient;
|
||||||
|
}
|
||||||
|
if(!_httpClient) {
|
||||||
|
_httpClient = new HTTPClient;
|
||||||
|
}
|
||||||
|
_httpClient->setReuse(_httpOptions._connectionReuse);
|
||||||
|
|
||||||
|
_httpClient->setUserAgent(FPSTR(UserAgent));
|
||||||
|
};
|
||||||
|
|
||||||
|
HTTPService::~HTTPService() {
|
||||||
|
if(_httpClient) {
|
||||||
|
delete _httpClient;
|
||||||
|
_httpClient = nullptr;
|
||||||
|
}
|
||||||
|
if(_wifiClient) {
|
||||||
|
delete _wifiClient;
|
||||||
|
_wifiClient = nullptr;
|
||||||
|
}
|
||||||
|
#if defined(ESP8266)
|
||||||
|
if(_cert) {
|
||||||
|
delete _cert;
|
||||||
|
_cert = nullptr;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void HTTPService::setHTTPOptions(const HTTPOptions & httpOptions) {
|
||||||
|
_httpOptions = httpOptions;
|
||||||
|
if(!_httpClient) {
|
||||||
|
_httpClient = new HTTPClient;
|
||||||
|
}
|
||||||
|
_httpClient->setReuse(_httpOptions._connectionReuse);
|
||||||
|
_httpClient->setTimeout(_httpOptions._httpReadTimeout);
|
||||||
|
#if defined(ESP32)
|
||||||
|
_httpClient->setConnectTimeout(_httpOptions._httpReadTimeout);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse URL for host and port and call probeMaxFragmentLength
|
||||||
|
#if defined(ESP8266)
|
||||||
|
bool checkMFLN(BearSSL::WiFiClientSecure *client, String url) {
|
||||||
|
int index = url.indexOf(':');
|
||||||
|
if(index < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String protocol = url.substring(0, index);
|
||||||
|
int port = -1;
|
||||||
|
url.remove(0, (index + 3)); // remove http:// or https://
|
||||||
|
|
||||||
|
if (protocol == "http") {
|
||||||
|
// set default port for 'http'
|
||||||
|
port = 80;
|
||||||
|
} else if (protocol == "https") {
|
||||||
|
// set default port for 'https'
|
||||||
|
port = 443;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
index = url.indexOf('/');
|
||||||
|
String host = url.substring(0, index);
|
||||||
|
url.remove(0, index); // remove host
|
||||||
|
// check Authorization
|
||||||
|
index = host.indexOf('@');
|
||||||
|
if(index >= 0) {
|
||||||
|
host.remove(0, index + 1); // remove auth part including @
|
||||||
|
}
|
||||||
|
// get port
|
||||||
|
index = host.indexOf(':');
|
||||||
|
if(index >= 0) {
|
||||||
|
String portS = host;
|
||||||
|
host = host.substring(0, index); // hostname
|
||||||
|
portS.remove(0, (index + 1)); // remove hostname + :
|
||||||
|
port = portS.toInt(); // get port
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] probeMaxFragmentLength to %s:%d\n", host.c_str(), port);
|
||||||
|
bool mfln = client->probeMaxFragmentLength(host, port, 1024);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] MFLN:%s\n", mfln ? "yes" : "no");
|
||||||
|
if (mfln) {
|
||||||
|
client->setBufferSizes(1024, 1024);
|
||||||
|
}
|
||||||
|
return mfln;
|
||||||
|
}
|
||||||
|
#endif //ESP8266
|
||||||
|
|
||||||
|
bool HTTPService::beforeRequest(const char *url) {
|
||||||
|
if(!_httpClient->begin(*_wifiClient, url)) {
|
||||||
|
_pConnInfo->lastError = F("begin failed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(_pConnInfo->authToken.length() > 0) {
|
||||||
|
_httpClient->addHeader(F("Authorization"), "Token " + _pConnInfo->authToken);
|
||||||
|
}
|
||||||
|
const char * headerKeys[] = {RetryAfter, TransferEncoding} ;
|
||||||
|
_httpClient->collectHeaders(headerKeys, 2);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::doPOST(const char *url, const char *data, const char *contentType, int expectedCode, httpResponseCallback cb) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] POST request - %s, data: %dbytes, type %s\n", url, strlen(data), contentType);
|
||||||
|
if(!beforeRequest(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(contentType) {
|
||||||
|
_httpClient->addHeader(F("Content-Type"), FPSTR(contentType));
|
||||||
|
}
|
||||||
|
_lastStatusCode = _httpClient->POST((uint8_t *) data, strlen(data));
|
||||||
|
return afterRequest(expectedCode, cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::doPOST(const char *url, Stream *stream, const char *contentType, int expectedCode, httpResponseCallback cb) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] POST request - %s, data: %dbytes, type %s\n", url, stream->available(), contentType);
|
||||||
|
if(!beforeRequest(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(contentType) {
|
||||||
|
_httpClient->addHeader(F("Content-Type"), FPSTR(contentType));
|
||||||
|
}
|
||||||
|
_lastStatusCode = _httpClient->sendRequest("POST", stream, stream->available());
|
||||||
|
return afterRequest(expectedCode, cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::doGET(const char *url, int expectedCode, httpResponseCallback cb) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] GET request - %s\n", url);
|
||||||
|
if(!beforeRequest(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_lastStatusCode = _httpClient->GET();
|
||||||
|
return afterRequest(expectedCode, cb, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::doDELETE(const char *url, int expectedCode, httpResponseCallback cb) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] DELETE - %s\n", url);
|
||||||
|
if(!beforeRequest(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_lastStatusCode = _httpClient->sendRequest("DELETE");
|
||||||
|
return afterRequest(expectedCode, cb, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HTTPService::afterRequest(int expectedStatusCode, httpResponseCallback cb, bool modifyLastConnStatus) {
|
||||||
|
if(modifyLastConnStatus) {
|
||||||
|
_lastRequestTime = millis();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HTTP status code - %d\n", _lastStatusCode);
|
||||||
|
_lastRetryAfter = 0;
|
||||||
|
if(_lastStatusCode >= 429) { //retryable server errors
|
||||||
|
if(_httpClient->hasHeader(RetryAfter)) {
|
||||||
|
_lastRetryAfter = _httpClient->header(RetryAfter).toInt();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Reply after - %d\n", _lastRetryAfter);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_pConnInfo->lastError = (char *)nullptr;
|
||||||
|
bool ret = _lastStatusCode == expectedStatusCode;
|
||||||
|
bool endConnection = true;
|
||||||
|
if(!ret) {
|
||||||
|
if(_lastStatusCode > 0) {
|
||||||
|
_pConnInfo->lastError = _httpClient->getString();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Response:\n%s\n", _pConnInfo->lastError.c_str());
|
||||||
|
} else {
|
||||||
|
_pConnInfo->lastError = _httpClient->errorToString(_lastStatusCode);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[E] Error - %s\n", _pConnInfo->lastError.c_str());
|
||||||
|
}
|
||||||
|
} else if(cb){
|
||||||
|
endConnection = cb(_httpClient);
|
||||||
|
}
|
||||||
|
if(endConnection) {
|
||||||
|
_httpClient->end();
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
136
firmware/libraries/ESP8266_Influxdb/src/HTTPService.h
Normal file
136
firmware/libraries/ESP8266_Influxdb/src/HTTPService.h
Normal file
|
@ -0,0 +1,136 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* HTTPService.h: HTTP Service
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _HTTP_SERVICE_H_
|
||||||
|
#define _HTTP_SERVICE_H_
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#if defined(ESP8266)
|
||||||
|
# include <WiFiClientSecureBearSSL.h>
|
||||||
|
# include <ESP8266HTTPClient.h>
|
||||||
|
#elif defined(ESP32)
|
||||||
|
# include <HTTPClient.h>
|
||||||
|
#else
|
||||||
|
# error "This library currently supports only ESP8266 and ESP32."
|
||||||
|
#endif
|
||||||
|
#include "Options.h"
|
||||||
|
|
||||||
|
|
||||||
|
class Test;
|
||||||
|
typedef std::function<bool(HTTPClient *client)> httpResponseCallback;
|
||||||
|
extern const char *TransferEncoding;
|
||||||
|
|
||||||
|
struct ConnectionInfo {
|
||||||
|
// Connection info
|
||||||
|
String serverUrl;
|
||||||
|
// Write & query targets
|
||||||
|
String bucket;
|
||||||
|
String org;
|
||||||
|
// v2 authetication token
|
||||||
|
String authToken;
|
||||||
|
// Version of InfluxDB 1 or 2
|
||||||
|
uint8_t dbVersion;
|
||||||
|
// V1 user authetication
|
||||||
|
String user;
|
||||||
|
String password;
|
||||||
|
// Certificate info
|
||||||
|
const char *certInfo;
|
||||||
|
// flag if https should ignore cert validation
|
||||||
|
bool insecure;
|
||||||
|
// Error message of last failed operation
|
||||||
|
String lastError;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTPService provides HTTP methods for communicating with InfluxDBServer,
|
||||||
|
* while taking care of Authorization and error handling
|
||||||
|
**/
|
||||||
|
class HTTPService {
|
||||||
|
friend class Test;
|
||||||
|
private:
|
||||||
|
// Connection info data
|
||||||
|
ConnectionInfo *_pConnInfo;
|
||||||
|
// Server API URL
|
||||||
|
String _apiURL;
|
||||||
|
// Last time in ms we made are a request to server
|
||||||
|
uint32_t _lastRequestTime = 0;
|
||||||
|
// HTTP status code of last request to server
|
||||||
|
int _lastStatusCode = 0;
|
||||||
|
// Underlying HTTPClient instance
|
||||||
|
HTTPClient *_httpClient = nullptr;
|
||||||
|
// Underlying connection object
|
||||||
|
WiFiClient *_wifiClient = nullptr;
|
||||||
|
#ifdef ESP8266
|
||||||
|
// Trusted cert chain
|
||||||
|
BearSSL::X509List *_cert = nullptr;
|
||||||
|
#endif
|
||||||
|
// Store retry timeout suggested by server after last request
|
||||||
|
int _lastRetryAfter = 0;
|
||||||
|
// HTTP options
|
||||||
|
HTTPOptions _httpOptions;
|
||||||
|
protected:
|
||||||
|
// Sets request params
|
||||||
|
bool beforeRequest(const char *url);
|
||||||
|
// Handles response
|
||||||
|
bool afterRequest(int expectedStatusCode, httpResponseCallback cb, bool modifyLastConnStatus = true);
|
||||||
|
public:
|
||||||
|
// Creates HTTPService instance
|
||||||
|
// serverUrl - url of the InfluxDB 2 server (e.g. http://localhost:8086)
|
||||||
|
// authToken - InfluxDB 2 authorization token
|
||||||
|
// certInfo - InfluxDB 2 server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM.
|
||||||
|
HTTPService(ConnectionInfo *pConnInfo);
|
||||||
|
// Clean instance on deletion
|
||||||
|
~HTTPService();
|
||||||
|
// Sets custom HTTP options. See HTTPOptions doc for more info.
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// Example:
|
||||||
|
// service.setHTTPOptions(HTTPOptions().httpReadTimeout(20000)).
|
||||||
|
void setHTTPOptions(const HTTPOptions &httpOptions);
|
||||||
|
// Returns current HTTPOption
|
||||||
|
HTTPOptions &getHTTPOptions() { return _httpOptions; }
|
||||||
|
// Performs HTTP POST by sending data. On success calls response call back
|
||||||
|
bool doPOST(const char *url, const char *data, const char *contentType, int expectedCode, httpResponseCallback cb);
|
||||||
|
// Performs HTTP POST by sending stream. On success calls response call back
|
||||||
|
bool doPOST(const char *url, Stream *stream, const char *contentType, int expectedCode, httpResponseCallback cb);
|
||||||
|
// Performs HTTP GET. On success calls response call back
|
||||||
|
bool doGET(const char *url, int expectedCode, httpResponseCallback cb);
|
||||||
|
// Performs HTTP DELETE. On success calls response call back
|
||||||
|
bool doDELETE(const char *url, int expectedCode, httpResponseCallback cb);
|
||||||
|
// Returns InfluxDBServer API URL
|
||||||
|
String getServerAPIURL() const { return _apiURL; }
|
||||||
|
// Returns value of the Retry-After HTTP header from recent call. 0 if it was missing.
|
||||||
|
int getLastRetryAfter() const { return _lastRetryAfter; }
|
||||||
|
// Returns HTTP status code of recent call.
|
||||||
|
int getLastStatusCode() const { return _lastStatusCode; }
|
||||||
|
// Returns time of recent call successful call.
|
||||||
|
uint32_t getLastRequestTime() const { return _lastRequestTime; }
|
||||||
|
// Returns response of last failed call.
|
||||||
|
String getLastErrorMessage() const { return _pConnInfo->lastError; }
|
||||||
|
// Returns true if HTTP connection is kept open
|
||||||
|
bool isConnected() const { return _httpClient && _httpClient->connected(); }
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_HTTP_SERVICE_H_
|
39
firmware/libraries/ESP8266_Influxdb/src/InfluxData 2.cpp
Normal file
39
firmware/libraries/ESP8266_Influxdb/src/InfluxData 2.cpp
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxData.cpp: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 Tobias Schürg
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "InfluxData.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
void InfluxData::setTimestamp(long int seconds)
|
||||||
|
{
|
||||||
|
_timestamp = timeStampToString(seconds,9);
|
||||||
|
strcat(_timestamp, "000000000");
|
||||||
|
}
|
||||||
|
|
||||||
|
String InfluxData::toString() const {
|
||||||
|
String t;
|
||||||
|
return createLineProtocol(t);
|
||||||
|
}
|
37
firmware/libraries/ESP8266_Influxdb/src/InfluxData 2.h
Normal file
37
firmware/libraries/ESP8266_Influxdb/src/InfluxData 2.h
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxData.h: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 Tobias Schürg
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "InfluxDbClient.h"
|
||||||
|
|
||||||
|
class InfluxData : public Point {
|
||||||
|
public:
|
||||||
|
InfluxData(String measurement) : Point(measurement) {}
|
||||||
|
|
||||||
|
void addValue(String key, float value) { addField(key, value); }
|
||||||
|
void addValueString(String key, String value) { addField(key, value); }
|
||||||
|
void setTimestamp(long int seconds);
|
||||||
|
String toString() const;
|
||||||
|
};
|
39
firmware/libraries/ESP8266_Influxdb/src/InfluxData.cpp
Normal file
39
firmware/libraries/ESP8266_Influxdb/src/InfluxData.cpp
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxData.cpp: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 Tobias Schürg
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "InfluxData.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
void InfluxData::setTimestamp(long int seconds)
|
||||||
|
{
|
||||||
|
_timestamp = timeStampToString(seconds,9);
|
||||||
|
strcat(_timestamp, "000000000");
|
||||||
|
}
|
||||||
|
|
||||||
|
String InfluxData::toString() const {
|
||||||
|
String t;
|
||||||
|
return createLineProtocol(t);
|
||||||
|
}
|
37
firmware/libraries/ESP8266_Influxdb/src/InfluxData.h
Normal file
37
firmware/libraries/ESP8266_Influxdb/src/InfluxData.h
Normal file
|
@ -0,0 +1,37 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxData.h: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 Tobias Schürg
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "InfluxDbClient.h"
|
||||||
|
|
||||||
|
class InfluxData : public Point {
|
||||||
|
public:
|
||||||
|
InfluxData(String measurement) : Point(measurement) {}
|
||||||
|
|
||||||
|
void addValue(String key, float value) { addField(key, value); }
|
||||||
|
void addValueString(String key, String value) { addField(key, value); }
|
||||||
|
void setTimestamp(long int seconds);
|
||||||
|
String toString() const;
|
||||||
|
};
|
157
firmware/libraries/ESP8266_Influxdb/src/InfluxDb 2.cpp
Normal file
157
firmware/libraries/ESP8266_Influxdb/src/InfluxDb 2.cpp
Normal file
|
@ -0,0 +1,157 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDb.cpp: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 Tobias Schürg
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "InfluxDb.h"
|
||||||
|
#include "Arduino.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Construct an InfluxDb instance.
|
||||||
|
* @param host the InfluxDb host
|
||||||
|
* @param port the InfluxDb port
|
||||||
|
*/
|
||||||
|
Influxdb::Influxdb(String host, uint16_t port) {
|
||||||
|
if(port == 443) {
|
||||||
|
// this happens usualy when influxdb is behind fw/proxy. Mostly, when influxdb is switched to https, the port remains the same (8086)
|
||||||
|
// port number shouldn't be qualificator for secure connection, either scheme or a flag
|
||||||
|
_connInfo.serverUrl = "https://";
|
||||||
|
} else {
|
||||||
|
_connInfo.serverUrl = "http://";
|
||||||
|
}
|
||||||
|
_connInfo.serverUrl += host + ":" + String(port);
|
||||||
|
_connInfo.dbVersion = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the database to be used.
|
||||||
|
* @param db the Influx Database to be written to.
|
||||||
|
*/
|
||||||
|
void Influxdb::setDb(String db) {
|
||||||
|
_connInfo.bucket = db;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the database to be used with authentication.
|
||||||
|
*/
|
||||||
|
void Influxdb::setDbAuth(String db, String user, String pass) {
|
||||||
|
_connInfo.bucket = db;
|
||||||
|
_connInfo.user = user;
|
||||||
|
_connInfo.password = pass;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the Bucket to be used v2.0 ONLY.
|
||||||
|
* @param bucket the InfluxDB Bucket which must already exist
|
||||||
|
*/
|
||||||
|
void Influxdb::setBucket(String bucket) {
|
||||||
|
_connInfo.bucket = bucket;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the influxDB port.
|
||||||
|
* @param port both v1.x and v3 use 8086
|
||||||
|
*/
|
||||||
|
void Influxdb::setPort(uint16_t port){
|
||||||
|
int b = _connInfo.serverUrl.indexOf(":",5);
|
||||||
|
if(b > 0) {
|
||||||
|
_connInfo.serverUrl = _connInfo.serverUrl.substring(0, b+1) + String(port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Set the Organization to be used v2.0 ONLY
|
||||||
|
* @param org the Name of the organization unit to use which must already exist
|
||||||
|
*/
|
||||||
|
void Influxdb::setOrg(String org){
|
||||||
|
_connInfo.org = org;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the authorization token v2.0 ONLY
|
||||||
|
* @param token the Auth Token from InfluxDBv2 *required*
|
||||||
|
*/
|
||||||
|
void Influxdb::setToken(String token){
|
||||||
|
_connInfo.authToken = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the version of InfluxDB to write to
|
||||||
|
* @param version accepts 1 for version 1.x or 2 for version 2.x
|
||||||
|
*/
|
||||||
|
void Influxdb::setVersion(uint16_t version){
|
||||||
|
_connInfo.dbVersion = version;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
/**
|
||||||
|
* Set server certificate finger print
|
||||||
|
* @param fingerPrint server certificate finger print
|
||||||
|
*/
|
||||||
|
void Influxdb::setFingerPrint(const char *fingerPrint){
|
||||||
|
_connInfo.certInfo = fingerPrint;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void Influxdb::begin() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare a measurement to be sent.
|
||||||
|
*/
|
||||||
|
void Influxdb::prepare(InfluxData data) {
|
||||||
|
++_preparedPoints;
|
||||||
|
if(_writeOptions._batchSize <= _preparedPoints) {
|
||||||
|
// for preparation, batchsize must be greater than number of prepared points, or it will send data right away
|
||||||
|
_writeOptions._batchSize = _preparedPoints+1;
|
||||||
|
reserveBuffer(2*_writeOptions._batchSize);
|
||||||
|
}
|
||||||
|
write(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write all prepared measurements into the db.
|
||||||
|
*/
|
||||||
|
boolean Influxdb::write() {
|
||||||
|
_preparedPoints = 0;
|
||||||
|
return flushBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write a single measurement into the db.
|
||||||
|
*/
|
||||||
|
boolean Influxdb::write(InfluxData data) {
|
||||||
|
return write(pointToLineProtocol(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send raw data to InfluxDb.
|
||||||
|
*
|
||||||
|
* @see
|
||||||
|
* https://github.com/esp8266/Arduino/blob/cc0bfa04d401810ed3f5d7d01be6e88b9011997f/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h#L44-L55
|
||||||
|
* for a list of error codes.
|
||||||
|
*/
|
||||||
|
boolean Influxdb::write(String data) {
|
||||||
|
return writeRecord(data);
|
||||||
|
}
|
59
firmware/libraries/ESP8266_Influxdb/src/InfluxDb 2.h
Normal file
59
firmware/libraries/ESP8266_Influxdb/src/InfluxDb 2.h
Normal file
|
@ -0,0 +1,59 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDb.h: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 Tobias Schürg
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _INFLUXDB_H_
|
||||||
|
#define _INFLUXDB_H
|
||||||
|
|
||||||
|
#include "InfluxData.h"
|
||||||
|
|
||||||
|
class Influxdb : public InfluxDBClient {
|
||||||
|
public:
|
||||||
|
Influxdb(String host, uint16_t port = 8086);
|
||||||
|
|
||||||
|
void setDb(String db);
|
||||||
|
void setDbAuth(String db, String user, String pass);
|
||||||
|
|
||||||
|
void setVersion(uint16_t version);
|
||||||
|
void setBucket(String bucket);
|
||||||
|
void setOrg(String org);
|
||||||
|
void setToken(String token);
|
||||||
|
void setPort(uint16_t port);
|
||||||
|
#if defined(ESP8266)
|
||||||
|
void setFingerPrint(const char *fingerPrint);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void prepare(InfluxData data);
|
||||||
|
boolean write();
|
||||||
|
|
||||||
|
boolean write(InfluxData data);
|
||||||
|
boolean write(String data);
|
||||||
|
|
||||||
|
private:
|
||||||
|
uint16_t _preparedPoints;
|
||||||
|
|
||||||
|
void begin();
|
||||||
|
};
|
||||||
|
#endif
|
157
firmware/libraries/ESP8266_Influxdb/src/InfluxDb.cpp
Normal file
157
firmware/libraries/ESP8266_Influxdb/src/InfluxDb.cpp
Normal file
|
@ -0,0 +1,157 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDb.cpp: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 Tobias Schürg
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "InfluxDb.h"
|
||||||
|
#include "Arduino.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Construct an InfluxDb instance.
|
||||||
|
* @param host the InfluxDb host
|
||||||
|
* @param port the InfluxDb port
|
||||||
|
*/
|
||||||
|
Influxdb::Influxdb(String host, uint16_t port) {
|
||||||
|
if(port == 443) {
|
||||||
|
// this happens usualy when influxdb is behind fw/proxy. Mostly, when influxdb is switched to https, the port remains the same (8086)
|
||||||
|
// port number shouldn't be qualificator for secure connection, either scheme or a flag
|
||||||
|
_connInfo.serverUrl = "https://";
|
||||||
|
} else {
|
||||||
|
_connInfo.serverUrl = "http://";
|
||||||
|
}
|
||||||
|
_connInfo.serverUrl += host + ":" + String(port);
|
||||||
|
_connInfo.dbVersion = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the database to be used.
|
||||||
|
* @param db the Influx Database to be written to.
|
||||||
|
*/
|
||||||
|
void Influxdb::setDb(String db) {
|
||||||
|
_connInfo.bucket = db;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the database to be used with authentication.
|
||||||
|
*/
|
||||||
|
void Influxdb::setDbAuth(String db, String user, String pass) {
|
||||||
|
_connInfo.bucket = db;
|
||||||
|
_connInfo.user = user;
|
||||||
|
_connInfo.password = pass;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the Bucket to be used v2.0 ONLY.
|
||||||
|
* @param bucket the InfluxDB Bucket which must already exist
|
||||||
|
*/
|
||||||
|
void Influxdb::setBucket(String bucket) {
|
||||||
|
_connInfo.bucket = bucket;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the influxDB port.
|
||||||
|
* @param port both v1.x and v3 use 8086
|
||||||
|
*/
|
||||||
|
void Influxdb::setPort(uint16_t port){
|
||||||
|
int b = _connInfo.serverUrl.indexOf(":",5);
|
||||||
|
if(b > 0) {
|
||||||
|
_connInfo.serverUrl = _connInfo.serverUrl.substring(0, b+1) + String(port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Set the Organization to be used v2.0 ONLY
|
||||||
|
* @param org the Name of the organization unit to use which must already exist
|
||||||
|
*/
|
||||||
|
void Influxdb::setOrg(String org){
|
||||||
|
_connInfo.org = org;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the authorization token v2.0 ONLY
|
||||||
|
* @param token the Auth Token from InfluxDBv2 *required*
|
||||||
|
*/
|
||||||
|
void Influxdb::setToken(String token){
|
||||||
|
_connInfo.authToken = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the version of InfluxDB to write to
|
||||||
|
* @param version accepts 1 for version 1.x or 2 for version 2.x
|
||||||
|
*/
|
||||||
|
void Influxdb::setVersion(uint16_t version){
|
||||||
|
_connInfo.dbVersion = version;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
/**
|
||||||
|
* Set server certificate finger print
|
||||||
|
* @param fingerPrint server certificate finger print
|
||||||
|
*/
|
||||||
|
void Influxdb::setFingerPrint(const char *fingerPrint){
|
||||||
|
_connInfo.certInfo = fingerPrint;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void Influxdb::begin() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepare a measurement to be sent.
|
||||||
|
*/
|
||||||
|
void Influxdb::prepare(InfluxData data) {
|
||||||
|
++_preparedPoints;
|
||||||
|
if(_writeOptions._batchSize <= _preparedPoints) {
|
||||||
|
// for preparation, batchsize must be greater than number of prepared points, or it will send data right away
|
||||||
|
_writeOptions._batchSize = _preparedPoints+1;
|
||||||
|
reserveBuffer(2*_writeOptions._batchSize);
|
||||||
|
}
|
||||||
|
write(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write all prepared measurements into the db.
|
||||||
|
*/
|
||||||
|
boolean Influxdb::write() {
|
||||||
|
_preparedPoints = 0;
|
||||||
|
return flushBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write a single measurement into the db.
|
||||||
|
*/
|
||||||
|
boolean Influxdb::write(InfluxData data) {
|
||||||
|
return write(pointToLineProtocol(data));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send raw data to InfluxDb.
|
||||||
|
*
|
||||||
|
* @see
|
||||||
|
* https://github.com/esp8266/Arduino/blob/cc0bfa04d401810ed3f5d7d01be6e88b9011997f/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h#L44-L55
|
||||||
|
* for a list of error codes.
|
||||||
|
*/
|
||||||
|
boolean Influxdb::write(String data) {
|
||||||
|
return writeRecord(data);
|
||||||
|
}
|
59
firmware/libraries/ESP8266_Influxdb/src/InfluxDb.h
Normal file
59
firmware/libraries/ESP8266_Influxdb/src/InfluxDb.h
Normal file
|
@ -0,0 +1,59 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDb.h: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 Tobias Schürg
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _INFLUXDB_H_
|
||||||
|
#define _INFLUXDB_H
|
||||||
|
|
||||||
|
#include "InfluxData.h"
|
||||||
|
|
||||||
|
class Influxdb : public InfluxDBClient {
|
||||||
|
public:
|
||||||
|
Influxdb(String host, uint16_t port = 8086);
|
||||||
|
|
||||||
|
void setDb(String db);
|
||||||
|
void setDbAuth(String db, String user, String pass);
|
||||||
|
|
||||||
|
void setVersion(uint16_t version);
|
||||||
|
void setBucket(String bucket);
|
||||||
|
void setOrg(String org);
|
||||||
|
void setToken(String token);
|
||||||
|
void setPort(uint16_t port);
|
||||||
|
#if defined(ESP8266)
|
||||||
|
void setFingerPrint(const char *fingerPrint);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void prepare(InfluxData data);
|
||||||
|
boolean write();
|
||||||
|
|
||||||
|
boolean write(InfluxData data);
|
||||||
|
boolean write(String data);
|
||||||
|
|
||||||
|
private:
|
||||||
|
uint16_t _preparedPoints;
|
||||||
|
|
||||||
|
void begin();
|
||||||
|
};
|
||||||
|
#endif
|
778
firmware/libraries/ESP8266_Influxdb/src/InfluxDbClient 2.cpp
Normal file
778
firmware/libraries/ESP8266_Influxdb/src/InfluxDbClient 2.cpp
Normal file
|
@ -0,0 +1,778 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDBClient.cpp: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "InfluxDbClient.h"
|
||||||
|
#include "Platform.h"
|
||||||
|
#include "Version.h"
|
||||||
|
|
||||||
|
#include "util/debug.h"
|
||||||
|
|
||||||
|
static const char TooEarlyMessage[] PROGMEM = "Cannot send request yet because of applied retry strategy. Remaining ";
|
||||||
|
|
||||||
|
static String escapeJSONString(const String &value);
|
||||||
|
static String precisionToString(WritePrecision precision, uint8_t version = 2) {
|
||||||
|
switch(precision) {
|
||||||
|
case WritePrecision::US:
|
||||||
|
return version==1?"u":"us";
|
||||||
|
case WritePrecision::MS:
|
||||||
|
return "ms";
|
||||||
|
case WritePrecision::NS:
|
||||||
|
return "ns";
|
||||||
|
case WritePrecision::S:
|
||||||
|
return "s";
|
||||||
|
default:
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
InfluxDBClient::InfluxDBClient() {
|
||||||
|
resetBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &db):InfluxDBClient() {
|
||||||
|
setConnectionParamsV1(serverUrl, db);
|
||||||
|
}
|
||||||
|
|
||||||
|
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken):InfluxDBClient(serverUrl, org, bucket, authToken, nullptr) {
|
||||||
|
}
|
||||||
|
|
||||||
|
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *serverCert):InfluxDBClient() {
|
||||||
|
setConnectionParams(serverUrl, org, bucket, authToken, serverCert);
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::setInsecure(bool value){
|
||||||
|
_connInfo.insecure = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::setConnectionParams(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *certInfo) {
|
||||||
|
clean();
|
||||||
|
_connInfo.serverUrl = serverUrl;
|
||||||
|
_connInfo.bucket = bucket;
|
||||||
|
_connInfo.org = org;
|
||||||
|
_connInfo.authToken = authToken;
|
||||||
|
_connInfo.certInfo = certInfo;
|
||||||
|
_connInfo.dbVersion = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::setConnectionParamsV1(const String &serverUrl, const String &db, const String &user, const String &password, const char *certInfo) {
|
||||||
|
clean();
|
||||||
|
_connInfo.serverUrl = serverUrl;
|
||||||
|
_connInfo.bucket = db;
|
||||||
|
_connInfo.user = user;
|
||||||
|
_connInfo.password = password;
|
||||||
|
_connInfo.certInfo = certInfo;
|
||||||
|
_connInfo.dbVersion = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::init() {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Init\n");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Library version: " INFLUXDB_CLIENT_VERSION "\n");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Device : " INFLUXDB_CLIENT_PLATFORM "\n");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] SDK version: " INFLUXDB_CLIENT_PLATFORM_VERSION "\n");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Server url: %s\n", _connInfo.serverUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Org: %s\n", _connInfo.org.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Bucket: %s\n", _connInfo.bucket.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Token: %s\n", _connInfo.authToken.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] DB version: %d\n", _connInfo.dbVersion);
|
||||||
|
if(_connInfo.serverUrl.length() == 0 || (_connInfo.dbVersion == 2 && (_connInfo.org.length() == 0 || _connInfo.bucket.length() == 0 || _connInfo.authToken.length() == 0))) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[E] Invalid parameters\n");
|
||||||
|
_connInfo.lastError = F("Invalid parameters");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(_connInfo.serverUrl.endsWith("/")) {
|
||||||
|
_connInfo.serverUrl = _connInfo.serverUrl.substring(0,_connInfo.serverUrl.length()-1);
|
||||||
|
}
|
||||||
|
if(!_connInfo.serverUrl.startsWith("http")) {
|
||||||
|
_connInfo.lastError = F("Invalid URL scheme");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_service = new HTTPService(&_connInfo);
|
||||||
|
|
||||||
|
setUrls();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
InfluxDBClient::~InfluxDBClient() {
|
||||||
|
if(_writeBuffer) {
|
||||||
|
for(int i=0;i<_writeBufferSize;i++) {
|
||||||
|
delete _writeBuffer[i];
|
||||||
|
}
|
||||||
|
delete [] _writeBuffer;
|
||||||
|
_writeBuffer = nullptr;
|
||||||
|
_bufferPointer = 0;
|
||||||
|
_batchPointer = 0;
|
||||||
|
_bufferCeiling = 0;
|
||||||
|
}
|
||||||
|
clean();
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::clean() {
|
||||||
|
if(_service) {
|
||||||
|
delete _service;
|
||||||
|
_service = nullptr;
|
||||||
|
}
|
||||||
|
_buckets = nullptr;
|
||||||
|
_lastFlushed = millis();
|
||||||
|
_retryTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::setUrls() {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] setUrls\n");
|
||||||
|
if( _connInfo.dbVersion == 2) {
|
||||||
|
_writeUrl = _service->getServerAPIURL();
|
||||||
|
_writeUrl += "write?org=";
|
||||||
|
_writeUrl += urlEncode(_connInfo.org.c_str());
|
||||||
|
_writeUrl += "&bucket=";
|
||||||
|
_writeUrl += urlEncode(_connInfo.bucket.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
|
||||||
|
_queryUrl = _service->getServerAPIURL();;
|
||||||
|
_queryUrl += "query?org=";
|
||||||
|
_queryUrl += urlEncode(_connInfo.org.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] queryUrl: %s\n", _queryUrl.c_str());
|
||||||
|
} else {
|
||||||
|
_writeUrl = _connInfo.serverUrl;
|
||||||
|
_writeUrl += "/write?db=";
|
||||||
|
_writeUrl += urlEncode(_connInfo.bucket.c_str());
|
||||||
|
_queryUrl = _connInfo.serverUrl;
|
||||||
|
_queryUrl += "/api/v2/query";
|
||||||
|
if(_connInfo.user.length() > 0 && _connInfo.password.length() > 0) {
|
||||||
|
String auth = "&u=";
|
||||||
|
auth += urlEncode(_connInfo.user.c_str());
|
||||||
|
auth += "&p=";
|
||||||
|
auth += urlEncode(_connInfo.password.c_str());
|
||||||
|
_writeUrl += auth;
|
||||||
|
_queryUrl += "?";
|
||||||
|
_queryUrl += auth;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] queryUrl: %s\n", _queryUrl.c_str());
|
||||||
|
}
|
||||||
|
if(_writeOptions._writePrecision != WritePrecision::NoTime) {
|
||||||
|
_writeUrl += "&precision=";
|
||||||
|
_writeUrl += precisionToString(_writeOptions._writePrecision, _connInfo.dbVersion);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::setWriteOptions(WritePrecision precision, uint16_t batchSize, uint16_t bufferSize, uint16_t flushInterval, bool preserveConnection) {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(!setWriteOptions(WriteOptions().writePrecision(precision).batchSize(batchSize).bufferSize(bufferSize).flushInterval(flushInterval))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(!setHTTPOptions(_service->getHTTPOptions().connectionReuse(preserveConnection))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::setWriteOptions(const WriteOptions & writeOptions) {
|
||||||
|
if(_writeOptions._writePrecision != writeOptions._writePrecision) {
|
||||||
|
_writeOptions._writePrecision = writeOptions._writePrecision;
|
||||||
|
if(!setUrls()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bool writeBufferSizeChanges = false;
|
||||||
|
if(writeOptions._batchSize > 0 && _writeOptions._batchSize != writeOptions._batchSize) {
|
||||||
|
_writeOptions._batchSize = writeOptions._batchSize;
|
||||||
|
writeBufferSizeChanges = true;
|
||||||
|
}
|
||||||
|
if(writeOptions._bufferSize > 0 && _writeOptions._bufferSize != writeOptions._bufferSize) {
|
||||||
|
_writeOptions._bufferSize = writeOptions._bufferSize;
|
||||||
|
if(_writeOptions._bufferSize < 2*_writeOptions._batchSize) {
|
||||||
|
_writeOptions._bufferSize = 2*_writeOptions._batchSize;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Changing buffer size to %d\n", _writeOptions._bufferSize);
|
||||||
|
}
|
||||||
|
writeBufferSizeChanges = true;
|
||||||
|
}
|
||||||
|
if(writeBufferSizeChanges) {
|
||||||
|
resetBuffer();
|
||||||
|
}
|
||||||
|
_writeOptions._flushInterval = writeOptions._flushInterval;
|
||||||
|
_writeOptions._retryInterval = writeOptions._retryInterval;
|
||||||
|
_writeOptions._maxRetryInterval = writeOptions._maxRetryInterval;
|
||||||
|
_writeOptions._maxRetryAttempts = writeOptions._maxRetryAttempts;
|
||||||
|
_writeOptions._defaultTags = writeOptions._defaultTags;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::setHTTPOptions(const HTTPOptions & httpOptions) {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_service->setHTTPOptions(httpOptions);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient InfluxDBClient::getBucketsClient() {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return BucketsClient();
|
||||||
|
}
|
||||||
|
if(!_buckets) {
|
||||||
|
_buckets = BucketsClient(&_connInfo, _service);
|
||||||
|
}
|
||||||
|
return _buckets;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::resetBuffer() {
|
||||||
|
if(_writeBuffer) {
|
||||||
|
for(int i=0;i<_writeBufferSize;i++) {
|
||||||
|
delete _writeBuffer[i];
|
||||||
|
}
|
||||||
|
delete [] _writeBuffer;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Reset buffer: buffer Size: %d, batch size: %d\n", _writeOptions._bufferSize, _writeOptions._batchSize);
|
||||||
|
uint16_t a = _writeOptions._bufferSize/_writeOptions._batchSize;
|
||||||
|
//limit to max(byte)
|
||||||
|
_writeBufferSize = a>=(1<<8)?(1<<8)-1:a;
|
||||||
|
if(_writeBufferSize < 2) {
|
||||||
|
_writeBufferSize = 2;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Reset buffer: writeBuffSize: %d\n", _writeBufferSize);
|
||||||
|
_writeBuffer = new Batch*[_writeBufferSize];
|
||||||
|
for(int i=0;i<_writeBufferSize;i++) {
|
||||||
|
_writeBuffer[i] = nullptr;
|
||||||
|
}
|
||||||
|
_bufferPointer = 0;
|
||||||
|
_batchPointer = 0;
|
||||||
|
_bufferCeiling = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::reserveBuffer(int size) {
|
||||||
|
if(size > _writeBufferSize) {
|
||||||
|
Batch **newBuffer = new Batch*[size];
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Resizing buffer from %d to %d\n",_writeBufferSize, size);
|
||||||
|
for(int i=0;i<_bufferCeiling; i++) {
|
||||||
|
newBuffer[i] = _writeBuffer[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
delete [] _writeBuffer;
|
||||||
|
_writeBuffer = newBuffer;
|
||||||
|
_writeBufferSize = size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::addZerosToTimestamp(Point &point, int zeroes) {
|
||||||
|
char *ts = point._timestamp, *s;
|
||||||
|
point._timestamp = new char[strlen(point._timestamp) + 1 + zeroes];
|
||||||
|
strcpy(point._timestamp, ts);
|
||||||
|
s = point._timestamp+strlen(ts);
|
||||||
|
for(int i=0;i<zeroes;i++) {
|
||||||
|
*s++ = '0';
|
||||||
|
}
|
||||||
|
*s = 0;
|
||||||
|
delete [] ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::checkPrecisions(Point & point) {
|
||||||
|
if(_writeOptions._writePrecision != WritePrecision::NoTime) {
|
||||||
|
if(!point.hasTime()) {
|
||||||
|
point.setTime(_writeOptions._writePrecision);
|
||||||
|
// Check different write precisions
|
||||||
|
} else if(point._tsWritePrecision != WritePrecision::NoTime && point._tsWritePrecision != _writeOptions._writePrecision) {
|
||||||
|
int diff = int(point._tsWritePrecision) - int(_writeOptions._writePrecision);
|
||||||
|
if(diff > 0) { //point has higher precision, cut
|
||||||
|
point._timestamp[strlen(point._timestamp)-diff*3] = 0;
|
||||||
|
} else { //point has lower precision, add zeroes
|
||||||
|
addZerosToTimestamp(point, diff*-3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// check someone set WritePrecision on point and not on client. NS precision is ok, cause it is default on server
|
||||||
|
} else if(point.hasTime() && point._tsWritePrecision != WritePrecision::NoTime && point._tsWritePrecision != WritePrecision::NS) {
|
||||||
|
int diff = int(WritePrecision::NS) - int(point._tsWritePrecision);
|
||||||
|
addZerosToTimestamp(point, diff*3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::writePoint(Point & point) {
|
||||||
|
if (point.hasFields()) {
|
||||||
|
checkPrecisions(point);
|
||||||
|
String line = pointToLineProtocol(point);
|
||||||
|
return writeRecord(line);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
InfluxDBClient::Batch::Batch(uint16_t size):_size(size) {
|
||||||
|
buffer = new char*[size];
|
||||||
|
for(int i=0;i< _size; i++) {
|
||||||
|
buffer[i] = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
InfluxDBClient::Batch::~Batch() {
|
||||||
|
clear();
|
||||||
|
delete [] buffer;
|
||||||
|
buffer = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::Batch::clear() {
|
||||||
|
for(int i=0;i< _size; i++) {
|
||||||
|
free(buffer[i]);
|
||||||
|
buffer[i] = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::Batch::append(const char *line) {
|
||||||
|
if(pointer == _size) {
|
||||||
|
//overwriting, clean buffer
|
||||||
|
clear();
|
||||||
|
pointer = 0;
|
||||||
|
}
|
||||||
|
buffer[pointer] = strdup(line);
|
||||||
|
++pointer;
|
||||||
|
return isFull();
|
||||||
|
}
|
||||||
|
|
||||||
|
char * InfluxDBClient::Batch::createData() {
|
||||||
|
int length = 0;
|
||||||
|
char *buff = nullptr;
|
||||||
|
for(int c=0; c < pointer; c++) {
|
||||||
|
length += strlen(buffer[c]);
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
//create buffer for all lines including new line char and terminating char
|
||||||
|
if(length) {
|
||||||
|
buff = new char[length + pointer + 1];
|
||||||
|
if(buff) {
|
||||||
|
buff[0] = 0;
|
||||||
|
for(int c=0; c < pointer; c++) {
|
||||||
|
strcat(buff+strlen(buff), buffer[c]);
|
||||||
|
strcat(buff+strlen(buff), "\n");
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return buff;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::writeRecord(const String &record) {
|
||||||
|
return writeRecord(record.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::writeRecord(const char *record) {
|
||||||
|
if(!_writeBuffer[_bufferPointer]) {
|
||||||
|
_writeBuffer[_bufferPointer] = new Batch(_writeOptions._batchSize);
|
||||||
|
}
|
||||||
|
if(isBufferFull() && _batchPointer <= _bufferPointer) {
|
||||||
|
// When we are overwriting buffer and nothing is written, batchPointer must point to the oldest point
|
||||||
|
_batchPointer = _bufferPointer+1;
|
||||||
|
if(_batchPointer == _writeBufferSize) {
|
||||||
|
_batchPointer = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(_writeBuffer[_bufferPointer]->append(record)) { //we reached batch size
|
||||||
|
_bufferPointer++;
|
||||||
|
if(_bufferPointer == _writeBufferSize) { // writeBuffer is full
|
||||||
|
_bufferPointer = 0;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[W] Reached write buffer size, old points will be overwritten\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
if(_bufferCeiling < _writeBufferSize) {
|
||||||
|
_bufferCeiling++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] writeRecord: bufferPointer: %d, batchPointer: %d, _bufferCeiling: %d\n", _bufferPointer, _batchPointer, _bufferCeiling);
|
||||||
|
return checkBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::checkBuffer() {
|
||||||
|
// in case we (over)reach batchSize with non full buffer
|
||||||
|
bool bufferReachedBatchsize = _writeBuffer[_batchPointer] && _writeBuffer[_batchPointer]->isFull();
|
||||||
|
// or flush interval timed out
|
||||||
|
bool flushTimeout = _writeOptions._flushInterval > 0 && ((millis() - _lastFlushed)/1000) >= _writeOptions._flushInterval;
|
||||||
|
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Flushing buffer: is oversized %s, is timeout %s, is buffer full %s\n",
|
||||||
|
bool2string(bufferReachedBatchsize),bool2string(flushTimeout), bool2string(isBufferFull()));
|
||||||
|
|
||||||
|
if(bufferReachedBatchsize || flushTimeout || isBufferFull() ) {
|
||||||
|
|
||||||
|
return flushBufferInternal(!flushTimeout);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::flushBuffer() {
|
||||||
|
return flushBufferInternal(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t InfluxDBClient::getRemainingRetryTime() {
|
||||||
|
uint32_t rem = 0;
|
||||||
|
if(_retryTime > 0) {
|
||||||
|
int32_t diff = _retryTime - (millis()-_service->getLastRequestTime())/1000;
|
||||||
|
rem = diff<0?0:(uint32_t)diff;
|
||||||
|
}
|
||||||
|
return rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::flushBufferInternal(bool flashOnlyFull) {
|
||||||
|
uint32_t rwt = getRemainingRetryTime();
|
||||||
|
if(rwt > 0) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[W] Cannot write yet, pause %ds, %ds yet\n", _retryTime, rwt);
|
||||||
|
// retry after period didn't run out yet
|
||||||
|
_connInfo.lastError = FPSTR(TooEarlyMessage);
|
||||||
|
_connInfo.lastError += String(rwt);
|
||||||
|
_connInfo.lastError += "s";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
char *data;
|
||||||
|
bool success = true;
|
||||||
|
// send all batches, It could happen there was long network outage and buffer is full
|
||||||
|
while(_writeBuffer[_batchPointer] && (!flashOnlyFull || _writeBuffer[_batchPointer]->isFull())) {
|
||||||
|
if(!_writeBuffer[_batchPointer]->isFull() && _writeBuffer[_batchPointer]->retryCount == 0 ) { //do not increase pointer in case of retrying
|
||||||
|
// points will be written so increase _bufferPointer as it happen when buffer is flushed when is full
|
||||||
|
if(++_bufferPointer == _writeBufferSize) {
|
||||||
|
_bufferPointer = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Writing batch, batchpointer: %d, size %d\n", _batchPointer, _writeBuffer[_batchPointer]->pointer);
|
||||||
|
if(!_writeBuffer[_batchPointer]->isEmpty()) {
|
||||||
|
int statusCode = 0;
|
||||||
|
if(_streamWrite) {
|
||||||
|
statusCode = postData(_writeBuffer[_batchPointer]);
|
||||||
|
} else {
|
||||||
|
data = _writeBuffer[_batchPointer]->createData();
|
||||||
|
statusCode = postData(data);
|
||||||
|
delete [] data;
|
||||||
|
}
|
||||||
|
// retry on unsuccessfull connection or retryable status codes
|
||||||
|
bool retry = (statusCode < 0 || statusCode >= 429) && _writeOptions._maxRetryAttempts > 0;
|
||||||
|
success = statusCode >= 200 && statusCode < 300;
|
||||||
|
// advance even on message failure x e <300;429)
|
||||||
|
if(success || !retry) {
|
||||||
|
_lastFlushed = millis();
|
||||||
|
dropCurrentBatch();
|
||||||
|
} else if(retry) {
|
||||||
|
_writeBuffer[_batchPointer]->retryCount++;
|
||||||
|
if(statusCode > 0) { //apply retry strategy only in case of HTTP errors
|
||||||
|
if(_writeBuffer[_batchPointer]->retryCount > _writeOptions._maxRetryAttempts) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Reached max retry count, dropping batch\n");
|
||||||
|
dropCurrentBatch();
|
||||||
|
}
|
||||||
|
if(!_retryTime) {
|
||||||
|
_retryTime = _writeOptions._retryInterval;
|
||||||
|
if(_writeBuffer[_batchPointer]) {
|
||||||
|
for(int i=1;i<_writeBuffer[_batchPointer]->retryCount;i++) {
|
||||||
|
_retryTime *= _writeOptions._retryInterval;
|
||||||
|
}
|
||||||
|
if(_retryTime > _writeOptions._maxRetryInterval) {
|
||||||
|
_retryTime = _writeOptions._maxRetryInterval;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Leaving data in buffer for retry, retryInterval: %d\n",_retryTime);
|
||||||
|
// in case of retryable failure break loop
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
//Have we emptied the buffer?
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Success: %d, _bufferPointer: %d, _batchPointer: %d, _writeBuffer[_bufferPointer]_%p\n",success,_bufferPointer,_batchPointer, _writeBuffer[_bufferPointer]);
|
||||||
|
if(_batchPointer == _bufferPointer && !_writeBuffer[_bufferPointer]) {
|
||||||
|
_bufferPointer = 0;
|
||||||
|
_batchPointer = 0;
|
||||||
|
_bufferCeiling = 0;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Buffer empty\n");
|
||||||
|
}
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::dropCurrentBatch() {
|
||||||
|
delete _writeBuffer[_batchPointer];
|
||||||
|
_writeBuffer[_batchPointer] = nullptr;
|
||||||
|
_batchPointer++;
|
||||||
|
//did we got over top?
|
||||||
|
if(_batchPointer == _writeBufferSize) {
|
||||||
|
// restart _batchPointer in ring buffer from start
|
||||||
|
_batchPointer = 0;
|
||||||
|
// we reached buffer size, that means buffer was full and now lower ceiling
|
||||||
|
_bufferCeiling = _bufferPointer;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Dropped batch, batchpointer: %d\n", _batchPointer);
|
||||||
|
}
|
||||||
|
|
||||||
|
String InfluxDBClient::pointToLineProtocol(const Point& point) {
|
||||||
|
return point.createLineProtocol(_writeOptions._defaultTags);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::validateConnection() {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// on version 1.x /ping will by default return status code 204, without verbose
|
||||||
|
String url = _connInfo.serverUrl + (_connInfo.dbVersion==2?"/health":"/ping?verbose=true");
|
||||||
|
if(_connInfo.dbVersion==1 && _connInfo.user.length() > 0 && _connInfo.password.length() > 0) {
|
||||||
|
url += "&u=";
|
||||||
|
url += urlEncode(_connInfo.user.c_str());
|
||||||
|
url += "&p=";
|
||||||
|
url += urlEncode(_connInfo.password.c_str());
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Validating connection to %s\n", url.c_str());
|
||||||
|
|
||||||
|
bool ret = _service->doGET(url.c_str(), 200, nullptr);
|
||||||
|
if(!ret) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::postData(const char *data) {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if(data) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Writing to %s\n", _writeUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Sending:\n%s\n", data);
|
||||||
|
if(!_service->doPOST(_writeUrl.c_str(), data, PSTR("text/plain"), 204, nullptr)) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
|
||||||
|
}
|
||||||
|
_retryTime = _service->getLastRetryAfter();
|
||||||
|
return _service->getLastStatusCode();
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::postData(Batch *batch) {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
BatchStreamer *bs = new BatchStreamer(batch);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Writing to %s\n", _writeUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Sending:\n");
|
||||||
|
|
||||||
|
if(!_service->doPOST(_writeUrl.c_str(), bs, PSTR("text/plain"), 204, nullptr)) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
|
||||||
|
}
|
||||||
|
delete bs;
|
||||||
|
_retryTime = _service->getLastRetryAfter();
|
||||||
|
return _service->getLastStatusCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::setStreamWrite(bool enable) {
|
||||||
|
_streamWrite = enable;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char QueryDialect[] PROGMEM = "\
|
||||||
|
\"dialect\": {\
|
||||||
|
\"annotations\": [\
|
||||||
|
\"datatype\"\
|
||||||
|
],\
|
||||||
|
\"dateTimeFormat\": \"RFC3339\",\
|
||||||
|
\"header\": true,\
|
||||||
|
\"delimiter\": \",\",\
|
||||||
|
\"commentPrefix\": \"#\"\
|
||||||
|
}";
|
||||||
|
|
||||||
|
static const char Params[] PROGMEM = ",\
|
||||||
|
\"params\": {";
|
||||||
|
|
||||||
|
FluxQueryResult InfluxDBClient::query(const String &fluxQuery) {
|
||||||
|
return query(fluxQuery, QueryParams());
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult InfluxDBClient::query(const String &fluxQuery, QueryParams params) {
|
||||||
|
uint32_t rwt = getRemainingRetryTime();
|
||||||
|
if(rwt > 0) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[W] Cannot query yet, pause %ds, %ds yet\n", _retryTime, rwt);
|
||||||
|
// retry after period didn't run out yet
|
||||||
|
String mess = FPSTR(TooEarlyMessage);
|
||||||
|
mess += String(rwt);
|
||||||
|
mess += "s";
|
||||||
|
return FluxQueryResult(mess);
|
||||||
|
}
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return FluxQueryResult(_connInfo.lastError);
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Query to %s\n", _queryUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] JSON query:\n%s\n", fluxQuery.c_str());
|
||||||
|
|
||||||
|
String queryEsc = escapeJSONString(fluxQuery);
|
||||||
|
String body;
|
||||||
|
body.reserve(150 + queryEsc.length() + params.size()*30);
|
||||||
|
body = F("{\"type\":\"flux\",\"query\":\"");
|
||||||
|
body += queryEsc;
|
||||||
|
body += "\",";
|
||||||
|
body += FPSTR(QueryDialect);
|
||||||
|
if(params.size()) {
|
||||||
|
body += FPSTR(Params);
|
||||||
|
body += params.jsonString(0);
|
||||||
|
for(int i=1;i<params.size();i++) {
|
||||||
|
body +=",";
|
||||||
|
char *js = params.jsonString(i);
|
||||||
|
body += js;
|
||||||
|
delete [] js;
|
||||||
|
}
|
||||||
|
body += '}';
|
||||||
|
}
|
||||||
|
body += '}';
|
||||||
|
CsvReader *reader = nullptr;
|
||||||
|
_retryTime = 0;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Query: %s\n", body.c_str());
|
||||||
|
if(_service->doPOST(_queryUrl.c_str(), body.c_str(), PSTR("application/json"), 200, [&](HTTPClient *httpClient){
|
||||||
|
bool chunked = false;
|
||||||
|
if(httpClient->hasHeader(TransferEncoding)) {
|
||||||
|
String header = httpClient->header(TransferEncoding);
|
||||||
|
chunked = header.equalsIgnoreCase("chunked");
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] chunked: %s\n", bool2string(chunked));
|
||||||
|
HttpStreamScanner *scanner = new HttpStreamScanner(httpClient, chunked);
|
||||||
|
reader = new CsvReader(scanner);
|
||||||
|
return false;
|
||||||
|
})) {
|
||||||
|
return FluxQueryResult(reader);
|
||||||
|
} else {
|
||||||
|
_retryTime = _service->getLastRetryAfter();
|
||||||
|
return FluxQueryResult(_service->getLastErrorMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static String escapeJSONString(const String &value) {
|
||||||
|
String ret;
|
||||||
|
int d = 0;
|
||||||
|
int i,from = 0;
|
||||||
|
while((i = value.indexOf('"',from)) > -1) {
|
||||||
|
d++;
|
||||||
|
if(i == (int)value.length()-1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
from = i+1;
|
||||||
|
}
|
||||||
|
ret.reserve(value.length()+d); //most probably we will escape just double quotes
|
||||||
|
for (char c: value)
|
||||||
|
{
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '"': ret += "\\\""; break;
|
||||||
|
case '\\': ret += "\\\\"; break;
|
||||||
|
case '\b': ret += "\\b"; break;
|
||||||
|
case '\f': ret += "\\f"; break;
|
||||||
|
case '\n': ret += "\\n"; break;
|
||||||
|
case '\r': ret += "\\r"; break;
|
||||||
|
case '\t': ret += "\\t"; break;
|
||||||
|
default:
|
||||||
|
if (c <= '\x1f') {
|
||||||
|
ret += "\\u";
|
||||||
|
char buf[3 + 8 * sizeof(unsigned int)];
|
||||||
|
sprintf(buf, "\\u%04u", c);
|
||||||
|
ret += buf;
|
||||||
|
} else {
|
||||||
|
ret += c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
InfluxDBClient::BatchStreamer::BatchStreamer(InfluxDBClient::Batch *batch) {
|
||||||
|
_batch = batch;
|
||||||
|
_read = 0;
|
||||||
|
_length = 0;
|
||||||
|
_pointer = 0;
|
||||||
|
_linePointer = 0;
|
||||||
|
for(uint16_t i=0;i<_batch->pointer;i++) {
|
||||||
|
_length += strlen(_batch->buffer[i])+1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::BatchStreamer::available() {
|
||||||
|
return _length-_read;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::BatchStreamer::availableForWrite() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
int InfluxDBClient::BatchStreamer::read(uint8_t* buffer, size_t len) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("BatchStream::read %d\n", len);
|
||||||
|
return readBytes((char *)buffer, len);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
size_t InfluxDBClient::BatchStreamer::readBytes(char* buffer, size_t len) {
|
||||||
|
|
||||||
|
INFLUXDB_CLIENT_DEBUG("BatchStream::readBytes %d\n", len);
|
||||||
|
unsigned int r=0;
|
||||||
|
for(unsigned int i=0;i<len;i++) {
|
||||||
|
if(available()) {
|
||||||
|
buffer[i] = read();
|
||||||
|
r++;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::BatchStreamer::read() {
|
||||||
|
int r = peek();
|
||||||
|
if(r > 0) {
|
||||||
|
++_read;
|
||||||
|
++_linePointer;
|
||||||
|
if(!_batch->buffer[_pointer][_linePointer-1]) {
|
||||||
|
++_pointer;
|
||||||
|
_linePointer = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::BatchStreamer::peek() {
|
||||||
|
if(_pointer == _batch->pointer) {
|
||||||
|
//This should not happen
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int r;
|
||||||
|
if(!_batch->buffer[_pointer][_linePointer]) {
|
||||||
|
r = '\n';
|
||||||
|
} else {
|
||||||
|
r = _batch->buffer[_pointer][_linePointer];
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t InfluxDBClient::BatchStreamer::write(uint8_t) {
|
||||||
|
return 0;
|
||||||
|
}
|
273
firmware/libraries/ESP8266_Influxdb/src/InfluxDbClient 2.h
Normal file
273
firmware/libraries/ESP8266_Influxdb/src/InfluxDbClient 2.h
Normal file
|
@ -0,0 +1,273 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDBClient.h: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _INFLUXDB_CLIENT_H_
|
||||||
|
#define _INFLUXDB_CLIENT_H_
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "HTTPService.h"
|
||||||
|
#include "Point.h"
|
||||||
|
#include "WritePrecision.h"
|
||||||
|
#include "query/FluxParser.h"
|
||||||
|
#include "query/Params.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
#include "Options.h"
|
||||||
|
#include "BucketsClient.h"
|
||||||
|
#include "Version.h"
|
||||||
|
|
||||||
|
#ifdef USING_AXTLS
|
||||||
|
#error AxTLS does not work
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InfluxDBClient handles connection and basic operations for an InfluxDB server.
|
||||||
|
* It provides write API with ability to write data in batches and retrying failed writes.
|
||||||
|
* Automaticaly retries failed writes during next write, if server is overloaded.
|
||||||
|
*/
|
||||||
|
class InfluxDBClient {
|
||||||
|
friend class Test;
|
||||||
|
public:
|
||||||
|
// Creates InfluxDBClient unconfigured instance.
|
||||||
|
// Call to setConnectionParams is required to set up client
|
||||||
|
InfluxDBClient();
|
||||||
|
// Creates InfluxDBClient instance for unsecured connection to InfluxDB 1
|
||||||
|
// serverUrl - url of the InfluxDB 1 server (e.g. http://localhost:8086)
|
||||||
|
// db - database name where to store or read data
|
||||||
|
InfluxDBClient(const String &serverUrl, const String &db);
|
||||||
|
// Creates InfluxDBClient instance for unsecured connection
|
||||||
|
// serverUrl - url of the InfluxDB 2 server (e.g. http://localhost:8086)
|
||||||
|
// org - name of the organization, which bucket belongs to
|
||||||
|
// bucket - name of the bucket to write data into
|
||||||
|
// authToken - InfluxDB 2 authorization token
|
||||||
|
InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken);
|
||||||
|
// Creates InfluxDBClient instance for secured connection
|
||||||
|
// serverUrl - url of the InfluxDB 2 server (e.g. https://localhost:8086)
|
||||||
|
// org - name of the organization, which bucket belongs to
|
||||||
|
// bucket - name of the bucket to write data into
|
||||||
|
// authToken - InfluxDB 2 authorization token
|
||||||
|
// certInfo - InfluxDB 2 server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM.
|
||||||
|
InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *certInfo);
|
||||||
|
// Clears instance.
|
||||||
|
~InfluxDBClient();
|
||||||
|
// Allows insecure connection by skiping server certificate validation.
|
||||||
|
// setInsecure must be called before calling any method initiating a connection to server.
|
||||||
|
void setInsecure(bool value = true);
|
||||||
|
// Sets custom write options.
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// precision - timestamp precision of written data
|
||||||
|
// batchSize - number of points that will be written to the databases at once. Default 1 - writes immediately
|
||||||
|
// bufferSize - maximum size of Points buffer. Buffer contains new data that will be written to the database
|
||||||
|
// and also data that failed to be written due to network failure or server overloading
|
||||||
|
// flushInterval - maximum number of seconds data will be held in buffer before are written to the db.
|
||||||
|
// Data are written either when number of points in buffer reaches batchSize or time of
|
||||||
|
// preserveConnection - true if HTTP connection should be kept open. Usable for frequent writes.
|
||||||
|
// Returns true if setting was successful. Otherwise check getLastErrorMessage() for an error.
|
||||||
|
bool setWriteOptions(WritePrecision precision, uint16_t batchSize = 1, uint16_t bufferSize = 5, uint16_t flushInterval = 60, bool preserveConnection = true) __attribute__ ((deprecated("Use setWriteOptions(const WriteOptions &writeOptions)")));
|
||||||
|
// Sets custom write options. See WriteOptions doc for more info.
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// Returns true if setting was successful. Otherwise check getLastErrorMessage() for an error.
|
||||||
|
// Example:
|
||||||
|
// client.setWriteOptions(WriteOptions().batchSize(10).bufferSize(50)).
|
||||||
|
bool setWriteOptions(const WriteOptions &writeOptions);
|
||||||
|
// Sets custom HTTP options. See HTTPOptions doc for more info.
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// Returns true if setting was successful. Otherwise check getLastErrorMessage() for an error.
|
||||||
|
// Example:
|
||||||
|
// client.setHTTPOptions(HTTPOptions().httpReadTimeout(20000)).
|
||||||
|
bool setHTTPOptions(const HTTPOptions &httpOptions);
|
||||||
|
// Sets connection parameters for InfluxDB 2
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// serverUrl - url of the InfluxDB 2 server (e.g. https//localhost:8086)
|
||||||
|
// org - name of the organization, which bucket belongs to
|
||||||
|
// bucket - name of the bucket to write data into
|
||||||
|
// authToken - InfluxDB 2 authorization token
|
||||||
|
// serverCert - Optional. InfluxDB 2 server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM. Only in case of https connection.
|
||||||
|
void setConnectionParams(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *certInfo = nullptr);
|
||||||
|
// Sets parameters for connection to InfluxDB 1
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// serverUrl - url of the InfluxDB server (e.g. http://localhost:8086)
|
||||||
|
// db - database name where to store or read data
|
||||||
|
// user - Optional. User name, in case of server requires authetication
|
||||||
|
// password - Optional. User password, in case of server requires authetication
|
||||||
|
// certInfo - Optional. InfluxDB server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM. Only in case of https connection.
|
||||||
|
void setConnectionParamsV1(const String &serverUrl, const String &db, const String &user = (const char *)nullptr, const String &password = (const char *)nullptr, const char *certInfo = nullptr);
|
||||||
|
// Creates line protocol string from point data and optional default tags set in WriteOptions.
|
||||||
|
String pointToLineProtocol(const Point& point);
|
||||||
|
// Validates connection parameters by conecting to server
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool validateConnection();
|
||||||
|
// Writes record in InfluxDB line protocol format to write buffer.
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool writeRecord(const String &record);
|
||||||
|
bool writeRecord(const char *record);
|
||||||
|
// Writes record represented by Point to buffer
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool writePoint(Point& point);
|
||||||
|
// Sends Flux query and returns FluxQueryResult object for subsequently reading flux query response.
|
||||||
|
// Use FluxQueryResult::next() method to iterate over lines of the query result.
|
||||||
|
// Always call of FluxQueryResult::close() when reading is finished. Check FluxQueryResult doc for more info.
|
||||||
|
FluxQueryResult query(const String &fluxQuery);
|
||||||
|
// Sends Flux query with params and returns FluxQueryResult object for subsequently reading flux query response.
|
||||||
|
// Use FluxQueryResult::next() method to iterate over lines of the query result.
|
||||||
|
// Always call of FluxQueryResult::close() when reading is finished. Check FluxQueryResult doc for more info.
|
||||||
|
FluxQueryResult query(const String &fluxQuery, QueryParams params);
|
||||||
|
// Forces writing of all points in buffer, even the batch is not full.
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool flushBuffer();
|
||||||
|
// Returns true if points buffer is full. Usefull when server is overloaded and we may want increase period of write points or decrease number of points
|
||||||
|
bool isBufferFull() const { return _bufferCeiling == _writeBufferSize; };
|
||||||
|
// Returns true if buffer is empty. Usefull when going to sleep and check if there is sth in write buffer (it can happens when batch size if bigger than 1). Call flushBuffer() then.
|
||||||
|
bool isBufferEmpty() const { return _bufferCeiling == 0 && !_writeBuffer[0]; };
|
||||||
|
// Checks points buffer status and flushes if number of points reached batch size or flush interval runs out.
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool checkBuffer();
|
||||||
|
// Wipes out buffered points
|
||||||
|
void resetBuffer();
|
||||||
|
// Returns HTTP status of last request to server. Usefull for advanced handling of failures.
|
||||||
|
int getLastStatusCode() const { return _service?_service->getLastStatusCode():0; }
|
||||||
|
// Returns last response when operation failed
|
||||||
|
String getLastErrorMessage() const { return _connInfo.lastError; }
|
||||||
|
// Returns server url
|
||||||
|
String getServerUrl() const { return _connInfo.serverUrl; }
|
||||||
|
// Check if it is possible to send write/query request to server.
|
||||||
|
// Returns true if write or query can be send, or false, if server is overloaded and retry strategy is applied.
|
||||||
|
// Use getRemainingRetryTime() to get wait time in such case.
|
||||||
|
bool canSendRequest() { return getRemainingRetryTime() == 0; }
|
||||||
|
// Returns remaining wait time in seconds when retry strategy is applied.
|
||||||
|
uint32_t getRemainingRetryTime();
|
||||||
|
// Returns sub-client for managing buckets
|
||||||
|
BucketsClient getBucketsClient();
|
||||||
|
// Enables/disables streaming write. This allows sending large batches without allocating buffer.
|
||||||
|
// It is about 50% slower than writing by allocated buffer (default);
|
||||||
|
void setStreamWrite(bool enable = true);
|
||||||
|
// Returns true if HTTP connection is kept open (connection reuse must be set to true)
|
||||||
|
bool isConnected() const { return _service && _service->isConnected(); }
|
||||||
|
protected:
|
||||||
|
// Checks params and sets up security, if needed.
|
||||||
|
// Returns true in case of success, otherwise false
|
||||||
|
bool init();
|
||||||
|
// Cleans instances
|
||||||
|
void clean();
|
||||||
|
protected:
|
||||||
|
class Batch {
|
||||||
|
friend class Test;
|
||||||
|
private:
|
||||||
|
uint16_t _size = 0;
|
||||||
|
public:
|
||||||
|
uint16_t pointer = 0;
|
||||||
|
char **buffer = nullptr;
|
||||||
|
uint8_t retryCount = 0;
|
||||||
|
Batch(uint16_t size);
|
||||||
|
~Batch();
|
||||||
|
bool append(const char *line);
|
||||||
|
char *createData();
|
||||||
|
void clear();
|
||||||
|
bool isFull() const {
|
||||||
|
return pointer == _size;
|
||||||
|
}
|
||||||
|
bool isEmpty() const {
|
||||||
|
return pointer == 0 && !buffer[0];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
class BatchStreamer : public Stream {
|
||||||
|
private:
|
||||||
|
Batch *_batch;
|
||||||
|
int _length;
|
||||||
|
int _read;
|
||||||
|
uint16_t _pointer; //points to the item in batch
|
||||||
|
uint16_t _linePointer; //pointes to char in line of batch
|
||||||
|
public:
|
||||||
|
BatchStreamer(Batch *batch) ;
|
||||||
|
virtual ~BatchStreamer() {};
|
||||||
|
|
||||||
|
// Stream overrides
|
||||||
|
virtual int available() override;
|
||||||
|
|
||||||
|
virtual int availableForWrite() override;
|
||||||
|
|
||||||
|
virtual int read() override;
|
||||||
|
#if defined(ESP8266)
|
||||||
|
virtual int read(uint8_t* buffer, size_t len) override;
|
||||||
|
#endif
|
||||||
|
virtual size_t readBytes(char* buffer, size_t len) override;
|
||||||
|
|
||||||
|
virtual void flush() override {};
|
||||||
|
virtual int peek() override;
|
||||||
|
|
||||||
|
virtual size_t write(uint8_t data) override;
|
||||||
|
|
||||||
|
};
|
||||||
|
ConnectionInfo _connInfo;
|
||||||
|
// Cached full write url
|
||||||
|
String _writeUrl;
|
||||||
|
// Cached full query url
|
||||||
|
String _queryUrl;
|
||||||
|
// Points buffer
|
||||||
|
Batch **_writeBuffer = nullptr;
|
||||||
|
// Batch buffer size
|
||||||
|
uint8_t _writeBufferSize;
|
||||||
|
// Write options
|
||||||
|
WriteOptions _writeOptions;
|
||||||
|
// Store retry timeout suggested by server or computed
|
||||||
|
int _retryTime = 0;
|
||||||
|
// HTTP operations object
|
||||||
|
HTTPService *_service = nullptr;
|
||||||
|
// Index to buffer where to store new batch
|
||||||
|
uint8_t _bufferPointer = 0;
|
||||||
|
// Actual count of batches in buffer
|
||||||
|
uint8_t _bufferCeiling = 0;
|
||||||
|
// Index of bath start for next write
|
||||||
|
uint8_t _batchPointer = 0;
|
||||||
|
// Last time in sec buffer has been successfully flushed
|
||||||
|
uint32_t _lastFlushed;
|
||||||
|
// Bucket sub-client
|
||||||
|
BucketsClient _buckets;
|
||||||
|
// Write using buffer or stream
|
||||||
|
bool _streamWrite = false;
|
||||||
|
protected:
|
||||||
|
// Sends POST request with data in body
|
||||||
|
int postData(const char *data);
|
||||||
|
int postData(Batch *batch);
|
||||||
|
// Sets cached InfluxDB server API URLs
|
||||||
|
bool setUrls();
|
||||||
|
// Ensures buffer has required size
|
||||||
|
void reserveBuffer(int size);
|
||||||
|
// Drops current batch and advances batch pointer
|
||||||
|
void dropCurrentBatch();
|
||||||
|
// Writes all points in buffer, with respect to the batch size, and in case of success clears the buffer.
|
||||||
|
// flashOnlyFull - whether to flush only full batches
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool flushBufferInternal(bool flashOnlyFull);
|
||||||
|
// Checks precision of point and mofifies if needed
|
||||||
|
void checkPrecisions(Point & point);
|
||||||
|
// helper which adds zeroes to timestamo of point to increase precision
|
||||||
|
static void addZerosToTimestamp(Point &point, int zeroes);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
#endif //_INFLUXDB_CLIENT_H_
|
778
firmware/libraries/ESP8266_Influxdb/src/InfluxDbClient.cpp
Normal file
778
firmware/libraries/ESP8266_Influxdb/src/InfluxDbClient.cpp
Normal file
|
@ -0,0 +1,778 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDBClient.cpp: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "InfluxDbClient.h"
|
||||||
|
#include "Platform.h"
|
||||||
|
#include "Version.h"
|
||||||
|
|
||||||
|
#include "util/debug.h"
|
||||||
|
|
||||||
|
static const char TooEarlyMessage[] PROGMEM = "Cannot send request yet because of applied retry strategy. Remaining ";
|
||||||
|
|
||||||
|
static String escapeJSONString(const String &value);
|
||||||
|
static String precisionToString(WritePrecision precision, uint8_t version = 2) {
|
||||||
|
switch(precision) {
|
||||||
|
case WritePrecision::US:
|
||||||
|
return version==1?"u":"us";
|
||||||
|
case WritePrecision::MS:
|
||||||
|
return "ms";
|
||||||
|
case WritePrecision::NS:
|
||||||
|
return "ns";
|
||||||
|
case WritePrecision::S:
|
||||||
|
return "s";
|
||||||
|
default:
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
InfluxDBClient::InfluxDBClient() {
|
||||||
|
resetBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &db):InfluxDBClient() {
|
||||||
|
setConnectionParamsV1(serverUrl, db);
|
||||||
|
}
|
||||||
|
|
||||||
|
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken):InfluxDBClient(serverUrl, org, bucket, authToken, nullptr) {
|
||||||
|
}
|
||||||
|
|
||||||
|
InfluxDBClient::InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *serverCert):InfluxDBClient() {
|
||||||
|
setConnectionParams(serverUrl, org, bucket, authToken, serverCert);
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::setInsecure(bool value){
|
||||||
|
_connInfo.insecure = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::setConnectionParams(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *certInfo) {
|
||||||
|
clean();
|
||||||
|
_connInfo.serverUrl = serverUrl;
|
||||||
|
_connInfo.bucket = bucket;
|
||||||
|
_connInfo.org = org;
|
||||||
|
_connInfo.authToken = authToken;
|
||||||
|
_connInfo.certInfo = certInfo;
|
||||||
|
_connInfo.dbVersion = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::setConnectionParamsV1(const String &serverUrl, const String &db, const String &user, const String &password, const char *certInfo) {
|
||||||
|
clean();
|
||||||
|
_connInfo.serverUrl = serverUrl;
|
||||||
|
_connInfo.bucket = db;
|
||||||
|
_connInfo.user = user;
|
||||||
|
_connInfo.password = password;
|
||||||
|
_connInfo.certInfo = certInfo;
|
||||||
|
_connInfo.dbVersion = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::init() {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Init\n");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Library version: " INFLUXDB_CLIENT_VERSION "\n");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Device : " INFLUXDB_CLIENT_PLATFORM "\n");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] SDK version: " INFLUXDB_CLIENT_PLATFORM_VERSION "\n");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Server url: %s\n", _connInfo.serverUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Org: %s\n", _connInfo.org.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Bucket: %s\n", _connInfo.bucket.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Token: %s\n", _connInfo.authToken.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] DB version: %d\n", _connInfo.dbVersion);
|
||||||
|
if(_connInfo.serverUrl.length() == 0 || (_connInfo.dbVersion == 2 && (_connInfo.org.length() == 0 || _connInfo.bucket.length() == 0 || _connInfo.authToken.length() == 0))) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[E] Invalid parameters\n");
|
||||||
|
_connInfo.lastError = F("Invalid parameters");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(_connInfo.serverUrl.endsWith("/")) {
|
||||||
|
_connInfo.serverUrl = _connInfo.serverUrl.substring(0,_connInfo.serverUrl.length()-1);
|
||||||
|
}
|
||||||
|
if(!_connInfo.serverUrl.startsWith("http")) {
|
||||||
|
_connInfo.lastError = F("Invalid URL scheme");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_service = new HTTPService(&_connInfo);
|
||||||
|
|
||||||
|
setUrls();
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
InfluxDBClient::~InfluxDBClient() {
|
||||||
|
if(_writeBuffer) {
|
||||||
|
for(int i=0;i<_writeBufferSize;i++) {
|
||||||
|
delete _writeBuffer[i];
|
||||||
|
}
|
||||||
|
delete [] _writeBuffer;
|
||||||
|
_writeBuffer = nullptr;
|
||||||
|
_bufferPointer = 0;
|
||||||
|
_batchPointer = 0;
|
||||||
|
_bufferCeiling = 0;
|
||||||
|
}
|
||||||
|
clean();
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::clean() {
|
||||||
|
if(_service) {
|
||||||
|
delete _service;
|
||||||
|
_service = nullptr;
|
||||||
|
}
|
||||||
|
_buckets = nullptr;
|
||||||
|
_lastFlushed = millis();
|
||||||
|
_retryTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::setUrls() {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] setUrls\n");
|
||||||
|
if( _connInfo.dbVersion == 2) {
|
||||||
|
_writeUrl = _service->getServerAPIURL();
|
||||||
|
_writeUrl += "write?org=";
|
||||||
|
_writeUrl += urlEncode(_connInfo.org.c_str());
|
||||||
|
_writeUrl += "&bucket=";
|
||||||
|
_writeUrl += urlEncode(_connInfo.bucket.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
|
||||||
|
_queryUrl = _service->getServerAPIURL();;
|
||||||
|
_queryUrl += "query?org=";
|
||||||
|
_queryUrl += urlEncode(_connInfo.org.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] queryUrl: %s\n", _queryUrl.c_str());
|
||||||
|
} else {
|
||||||
|
_writeUrl = _connInfo.serverUrl;
|
||||||
|
_writeUrl += "/write?db=";
|
||||||
|
_writeUrl += urlEncode(_connInfo.bucket.c_str());
|
||||||
|
_queryUrl = _connInfo.serverUrl;
|
||||||
|
_queryUrl += "/api/v2/query";
|
||||||
|
if(_connInfo.user.length() > 0 && _connInfo.password.length() > 0) {
|
||||||
|
String auth = "&u=";
|
||||||
|
auth += urlEncode(_connInfo.user.c_str());
|
||||||
|
auth += "&p=";
|
||||||
|
auth += urlEncode(_connInfo.password.c_str());
|
||||||
|
_writeUrl += auth;
|
||||||
|
_queryUrl += "?";
|
||||||
|
_queryUrl += auth;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] queryUrl: %s\n", _queryUrl.c_str());
|
||||||
|
}
|
||||||
|
if(_writeOptions._writePrecision != WritePrecision::NoTime) {
|
||||||
|
_writeUrl += "&precision=";
|
||||||
|
_writeUrl += precisionToString(_writeOptions._writePrecision, _connInfo.dbVersion);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] writeUrl: %s\n", _writeUrl.c_str());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::setWriteOptions(WritePrecision precision, uint16_t batchSize, uint16_t bufferSize, uint16_t flushInterval, bool preserveConnection) {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(!setWriteOptions(WriteOptions().writePrecision(precision).batchSize(batchSize).bufferSize(bufferSize).flushInterval(flushInterval))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(!setHTTPOptions(_service->getHTTPOptions().connectionReuse(preserveConnection))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::setWriteOptions(const WriteOptions & writeOptions) {
|
||||||
|
if(_writeOptions._writePrecision != writeOptions._writePrecision) {
|
||||||
|
_writeOptions._writePrecision = writeOptions._writePrecision;
|
||||||
|
if(!setUrls()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bool writeBufferSizeChanges = false;
|
||||||
|
if(writeOptions._batchSize > 0 && _writeOptions._batchSize != writeOptions._batchSize) {
|
||||||
|
_writeOptions._batchSize = writeOptions._batchSize;
|
||||||
|
writeBufferSizeChanges = true;
|
||||||
|
}
|
||||||
|
if(writeOptions._bufferSize > 0 && _writeOptions._bufferSize != writeOptions._bufferSize) {
|
||||||
|
_writeOptions._bufferSize = writeOptions._bufferSize;
|
||||||
|
if(_writeOptions._bufferSize < 2*_writeOptions._batchSize) {
|
||||||
|
_writeOptions._bufferSize = 2*_writeOptions._batchSize;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Changing buffer size to %d\n", _writeOptions._bufferSize);
|
||||||
|
}
|
||||||
|
writeBufferSizeChanges = true;
|
||||||
|
}
|
||||||
|
if(writeBufferSizeChanges) {
|
||||||
|
resetBuffer();
|
||||||
|
}
|
||||||
|
_writeOptions._flushInterval = writeOptions._flushInterval;
|
||||||
|
_writeOptions._retryInterval = writeOptions._retryInterval;
|
||||||
|
_writeOptions._maxRetryInterval = writeOptions._maxRetryInterval;
|
||||||
|
_writeOptions._maxRetryAttempts = writeOptions._maxRetryAttempts;
|
||||||
|
_writeOptions._defaultTags = writeOptions._defaultTags;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::setHTTPOptions(const HTTPOptions & httpOptions) {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_service->setHTTPOptions(httpOptions);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
BucketsClient InfluxDBClient::getBucketsClient() {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return BucketsClient();
|
||||||
|
}
|
||||||
|
if(!_buckets) {
|
||||||
|
_buckets = BucketsClient(&_connInfo, _service);
|
||||||
|
}
|
||||||
|
return _buckets;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::resetBuffer() {
|
||||||
|
if(_writeBuffer) {
|
||||||
|
for(int i=0;i<_writeBufferSize;i++) {
|
||||||
|
delete _writeBuffer[i];
|
||||||
|
}
|
||||||
|
delete [] _writeBuffer;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Reset buffer: buffer Size: %d, batch size: %d\n", _writeOptions._bufferSize, _writeOptions._batchSize);
|
||||||
|
uint16_t a = _writeOptions._bufferSize/_writeOptions._batchSize;
|
||||||
|
//limit to max(byte)
|
||||||
|
_writeBufferSize = a>=(1<<8)?(1<<8)-1:a;
|
||||||
|
if(_writeBufferSize < 2) {
|
||||||
|
_writeBufferSize = 2;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Reset buffer: writeBuffSize: %d\n", _writeBufferSize);
|
||||||
|
_writeBuffer = new Batch*[_writeBufferSize];
|
||||||
|
for(int i=0;i<_writeBufferSize;i++) {
|
||||||
|
_writeBuffer[i] = nullptr;
|
||||||
|
}
|
||||||
|
_bufferPointer = 0;
|
||||||
|
_batchPointer = 0;
|
||||||
|
_bufferCeiling = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::reserveBuffer(int size) {
|
||||||
|
if(size > _writeBufferSize) {
|
||||||
|
Batch **newBuffer = new Batch*[size];
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Resizing buffer from %d to %d\n",_writeBufferSize, size);
|
||||||
|
for(int i=0;i<_bufferCeiling; i++) {
|
||||||
|
newBuffer[i] = _writeBuffer[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
delete [] _writeBuffer;
|
||||||
|
_writeBuffer = newBuffer;
|
||||||
|
_writeBufferSize = size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::addZerosToTimestamp(Point &point, int zeroes) {
|
||||||
|
char *ts = point._timestamp, *s;
|
||||||
|
point._timestamp = new char[strlen(point._timestamp) + 1 + zeroes];
|
||||||
|
strcpy(point._timestamp, ts);
|
||||||
|
s = point._timestamp+strlen(ts);
|
||||||
|
for(int i=0;i<zeroes;i++) {
|
||||||
|
*s++ = '0';
|
||||||
|
}
|
||||||
|
*s = 0;
|
||||||
|
delete [] ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::checkPrecisions(Point & point) {
|
||||||
|
if(_writeOptions._writePrecision != WritePrecision::NoTime) {
|
||||||
|
if(!point.hasTime()) {
|
||||||
|
point.setTime(_writeOptions._writePrecision);
|
||||||
|
// Check different write precisions
|
||||||
|
} else if(point._tsWritePrecision != WritePrecision::NoTime && point._tsWritePrecision != _writeOptions._writePrecision) {
|
||||||
|
int diff = int(point._tsWritePrecision) - int(_writeOptions._writePrecision);
|
||||||
|
if(diff > 0) { //point has higher precision, cut
|
||||||
|
point._timestamp[strlen(point._timestamp)-diff*3] = 0;
|
||||||
|
} else { //point has lower precision, add zeroes
|
||||||
|
addZerosToTimestamp(point, diff*-3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// check someone set WritePrecision on point and not on client. NS precision is ok, cause it is default on server
|
||||||
|
} else if(point.hasTime() && point._tsWritePrecision != WritePrecision::NoTime && point._tsWritePrecision != WritePrecision::NS) {
|
||||||
|
int diff = int(WritePrecision::NS) - int(point._tsWritePrecision);
|
||||||
|
addZerosToTimestamp(point, diff*3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::writePoint(Point & point) {
|
||||||
|
if (point.hasFields()) {
|
||||||
|
checkPrecisions(point);
|
||||||
|
String line = pointToLineProtocol(point);
|
||||||
|
return writeRecord(line);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
InfluxDBClient::Batch::Batch(uint16_t size):_size(size) {
|
||||||
|
buffer = new char*[size];
|
||||||
|
for(int i=0;i< _size; i++) {
|
||||||
|
buffer[i] = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
InfluxDBClient::Batch::~Batch() {
|
||||||
|
clear();
|
||||||
|
delete [] buffer;
|
||||||
|
buffer = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::Batch::clear() {
|
||||||
|
for(int i=0;i< _size; i++) {
|
||||||
|
free(buffer[i]);
|
||||||
|
buffer[i] = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::Batch::append(const char *line) {
|
||||||
|
if(pointer == _size) {
|
||||||
|
//overwriting, clean buffer
|
||||||
|
clear();
|
||||||
|
pointer = 0;
|
||||||
|
}
|
||||||
|
buffer[pointer] = strdup(line);
|
||||||
|
++pointer;
|
||||||
|
return isFull();
|
||||||
|
}
|
||||||
|
|
||||||
|
char * InfluxDBClient::Batch::createData() {
|
||||||
|
int length = 0;
|
||||||
|
char *buff = nullptr;
|
||||||
|
for(int c=0; c < pointer; c++) {
|
||||||
|
length += strlen(buffer[c]);
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
//create buffer for all lines including new line char and terminating char
|
||||||
|
if(length) {
|
||||||
|
buff = new char[length + pointer + 1];
|
||||||
|
if(buff) {
|
||||||
|
buff[0] = 0;
|
||||||
|
for(int c=0; c < pointer; c++) {
|
||||||
|
strcat(buff+strlen(buff), buffer[c]);
|
||||||
|
strcat(buff+strlen(buff), "\n");
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return buff;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::writeRecord(const String &record) {
|
||||||
|
return writeRecord(record.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::writeRecord(const char *record) {
|
||||||
|
if(!_writeBuffer[_bufferPointer]) {
|
||||||
|
_writeBuffer[_bufferPointer] = new Batch(_writeOptions._batchSize);
|
||||||
|
}
|
||||||
|
if(isBufferFull() && _batchPointer <= _bufferPointer) {
|
||||||
|
// When we are overwriting buffer and nothing is written, batchPointer must point to the oldest point
|
||||||
|
_batchPointer = _bufferPointer+1;
|
||||||
|
if(_batchPointer == _writeBufferSize) {
|
||||||
|
_batchPointer = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(_writeBuffer[_bufferPointer]->append(record)) { //we reached batch size
|
||||||
|
_bufferPointer++;
|
||||||
|
if(_bufferPointer == _writeBufferSize) { // writeBuffer is full
|
||||||
|
_bufferPointer = 0;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[W] Reached write buffer size, old points will be overwritten\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
if(_bufferCeiling < _writeBufferSize) {
|
||||||
|
_bufferCeiling++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] writeRecord: bufferPointer: %d, batchPointer: %d, _bufferCeiling: %d\n", _bufferPointer, _batchPointer, _bufferCeiling);
|
||||||
|
return checkBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::checkBuffer() {
|
||||||
|
// in case we (over)reach batchSize with non full buffer
|
||||||
|
bool bufferReachedBatchsize = _writeBuffer[_batchPointer] && _writeBuffer[_batchPointer]->isFull();
|
||||||
|
// or flush interval timed out
|
||||||
|
bool flushTimeout = _writeOptions._flushInterval > 0 && ((millis() - _lastFlushed)/1000) >= _writeOptions._flushInterval;
|
||||||
|
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Flushing buffer: is oversized %s, is timeout %s, is buffer full %s\n",
|
||||||
|
bool2string(bufferReachedBatchsize),bool2string(flushTimeout), bool2string(isBufferFull()));
|
||||||
|
|
||||||
|
if(bufferReachedBatchsize || flushTimeout || isBufferFull() ) {
|
||||||
|
|
||||||
|
return flushBufferInternal(!flushTimeout);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::flushBuffer() {
|
||||||
|
return flushBufferInternal(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t InfluxDBClient::getRemainingRetryTime() {
|
||||||
|
uint32_t rem = 0;
|
||||||
|
if(_retryTime > 0) {
|
||||||
|
int32_t diff = _retryTime - (millis()-_service->getLastRequestTime())/1000;
|
||||||
|
rem = diff<0?0:(uint32_t)diff;
|
||||||
|
}
|
||||||
|
return rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::flushBufferInternal(bool flashOnlyFull) {
|
||||||
|
uint32_t rwt = getRemainingRetryTime();
|
||||||
|
if(rwt > 0) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[W] Cannot write yet, pause %ds, %ds yet\n", _retryTime, rwt);
|
||||||
|
// retry after period didn't run out yet
|
||||||
|
_connInfo.lastError = FPSTR(TooEarlyMessage);
|
||||||
|
_connInfo.lastError += String(rwt);
|
||||||
|
_connInfo.lastError += "s";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
char *data;
|
||||||
|
bool success = true;
|
||||||
|
// send all batches, It could happen there was long network outage and buffer is full
|
||||||
|
while(_writeBuffer[_batchPointer] && (!flashOnlyFull || _writeBuffer[_batchPointer]->isFull())) {
|
||||||
|
if(!_writeBuffer[_batchPointer]->isFull() && _writeBuffer[_batchPointer]->retryCount == 0 ) { //do not increase pointer in case of retrying
|
||||||
|
// points will be written so increase _bufferPointer as it happen when buffer is flushed when is full
|
||||||
|
if(++_bufferPointer == _writeBufferSize) {
|
||||||
|
_bufferPointer = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Writing batch, batchpointer: %d, size %d\n", _batchPointer, _writeBuffer[_batchPointer]->pointer);
|
||||||
|
if(!_writeBuffer[_batchPointer]->isEmpty()) {
|
||||||
|
int statusCode = 0;
|
||||||
|
if(_streamWrite) {
|
||||||
|
statusCode = postData(_writeBuffer[_batchPointer]);
|
||||||
|
} else {
|
||||||
|
data = _writeBuffer[_batchPointer]->createData();
|
||||||
|
statusCode = postData(data);
|
||||||
|
delete [] data;
|
||||||
|
}
|
||||||
|
// retry on unsuccessfull connection or retryable status codes
|
||||||
|
bool retry = (statusCode < 0 || statusCode >= 429) && _writeOptions._maxRetryAttempts > 0;
|
||||||
|
success = statusCode >= 200 && statusCode < 300;
|
||||||
|
// advance even on message failure x e <300;429)
|
||||||
|
if(success || !retry) {
|
||||||
|
_lastFlushed = millis();
|
||||||
|
dropCurrentBatch();
|
||||||
|
} else if(retry) {
|
||||||
|
_writeBuffer[_batchPointer]->retryCount++;
|
||||||
|
if(statusCode > 0) { //apply retry strategy only in case of HTTP errors
|
||||||
|
if(_writeBuffer[_batchPointer]->retryCount > _writeOptions._maxRetryAttempts) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Reached max retry count, dropping batch\n");
|
||||||
|
dropCurrentBatch();
|
||||||
|
}
|
||||||
|
if(!_retryTime) {
|
||||||
|
_retryTime = _writeOptions._retryInterval;
|
||||||
|
if(_writeBuffer[_batchPointer]) {
|
||||||
|
for(int i=1;i<_writeBuffer[_batchPointer]->retryCount;i++) {
|
||||||
|
_retryTime *= _writeOptions._retryInterval;
|
||||||
|
}
|
||||||
|
if(_retryTime > _writeOptions._maxRetryInterval) {
|
||||||
|
_retryTime = _writeOptions._maxRetryInterval;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Leaving data in buffer for retry, retryInterval: %d\n",_retryTime);
|
||||||
|
// in case of retryable failure break loop
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
yield();
|
||||||
|
}
|
||||||
|
//Have we emptied the buffer?
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Success: %d, _bufferPointer: %d, _batchPointer: %d, _writeBuffer[_bufferPointer]_%p\n",success,_bufferPointer,_batchPointer, _writeBuffer[_bufferPointer]);
|
||||||
|
if(_batchPointer == _bufferPointer && !_writeBuffer[_bufferPointer]) {
|
||||||
|
_bufferPointer = 0;
|
||||||
|
_batchPointer = 0;
|
||||||
|
_bufferCeiling = 0;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Buffer empty\n");
|
||||||
|
}
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::dropCurrentBatch() {
|
||||||
|
delete _writeBuffer[_batchPointer];
|
||||||
|
_writeBuffer[_batchPointer] = nullptr;
|
||||||
|
_batchPointer++;
|
||||||
|
//did we got over top?
|
||||||
|
if(_batchPointer == _writeBufferSize) {
|
||||||
|
// restart _batchPointer in ring buffer from start
|
||||||
|
_batchPointer = 0;
|
||||||
|
// we reached buffer size, that means buffer was full and now lower ceiling
|
||||||
|
_bufferCeiling = _bufferPointer;
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Dropped batch, batchpointer: %d\n", _batchPointer);
|
||||||
|
}
|
||||||
|
|
||||||
|
String InfluxDBClient::pointToLineProtocol(const Point& point) {
|
||||||
|
return point.createLineProtocol(_writeOptions._defaultTags);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InfluxDBClient::validateConnection() {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// on version 1.x /ping will by default return status code 204, without verbose
|
||||||
|
String url = _connInfo.serverUrl + (_connInfo.dbVersion==2?"/health":"/ping?verbose=true");
|
||||||
|
if(_connInfo.dbVersion==1 && _connInfo.user.length() > 0 && _connInfo.password.length() > 0) {
|
||||||
|
url += "&u=";
|
||||||
|
url += urlEncode(_connInfo.user.c_str());
|
||||||
|
url += "&p=";
|
||||||
|
url += urlEncode(_connInfo.password.c_str());
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Validating connection to %s\n", url.c_str());
|
||||||
|
|
||||||
|
bool ret = _service->doGET(url.c_str(), 200, nullptr);
|
||||||
|
if(!ret) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::postData(const char *data) {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if(data) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Writing to %s\n", _writeUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Sending:\n%s\n", data);
|
||||||
|
if(!_service->doPOST(_writeUrl.c_str(), data, PSTR("text/plain"), 204, nullptr)) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
|
||||||
|
}
|
||||||
|
_retryTime = _service->getLastRetryAfter();
|
||||||
|
return _service->getLastStatusCode();
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::postData(Batch *batch) {
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
BatchStreamer *bs = new BatchStreamer(batch);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Writing to %s\n", _writeUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Sending:\n");
|
||||||
|
|
||||||
|
if(!_service->doPOST(_writeUrl.c_str(), bs, PSTR("text/plain"), 204, nullptr)) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] error %d: %s\n", _service->getLastStatusCode(), _service->getLastErrorMessage().c_str());
|
||||||
|
}
|
||||||
|
delete bs;
|
||||||
|
_retryTime = _service->getLastRetryAfter();
|
||||||
|
return _service->getLastStatusCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
void InfluxDBClient::setStreamWrite(bool enable) {
|
||||||
|
_streamWrite = enable;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char QueryDialect[] PROGMEM = "\
|
||||||
|
\"dialect\": {\
|
||||||
|
\"annotations\": [\
|
||||||
|
\"datatype\"\
|
||||||
|
],\
|
||||||
|
\"dateTimeFormat\": \"RFC3339\",\
|
||||||
|
\"header\": true,\
|
||||||
|
\"delimiter\": \",\",\
|
||||||
|
\"commentPrefix\": \"#\"\
|
||||||
|
}";
|
||||||
|
|
||||||
|
static const char Params[] PROGMEM = ",\
|
||||||
|
\"params\": {";
|
||||||
|
|
||||||
|
FluxQueryResult InfluxDBClient::query(const String &fluxQuery) {
|
||||||
|
return query(fluxQuery, QueryParams());
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult InfluxDBClient::query(const String &fluxQuery, QueryParams params) {
|
||||||
|
uint32_t rwt = getRemainingRetryTime();
|
||||||
|
if(rwt > 0) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[W] Cannot query yet, pause %ds, %ds yet\n", _retryTime, rwt);
|
||||||
|
// retry after period didn't run out yet
|
||||||
|
String mess = FPSTR(TooEarlyMessage);
|
||||||
|
mess += String(rwt);
|
||||||
|
mess += "s";
|
||||||
|
return FluxQueryResult(mess);
|
||||||
|
}
|
||||||
|
if(!_service && !init()) {
|
||||||
|
return FluxQueryResult(_connInfo.lastError);
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Query to %s\n", _queryUrl.c_str());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] JSON query:\n%s\n", fluxQuery.c_str());
|
||||||
|
|
||||||
|
String queryEsc = escapeJSONString(fluxQuery);
|
||||||
|
String body;
|
||||||
|
body.reserve(150 + queryEsc.length() + params.size()*30);
|
||||||
|
body = F("{\"type\":\"flux\",\"query\":\"");
|
||||||
|
body += queryEsc;
|
||||||
|
body += "\",";
|
||||||
|
body += FPSTR(QueryDialect);
|
||||||
|
if(params.size()) {
|
||||||
|
body += FPSTR(Params);
|
||||||
|
body += params.jsonString(0);
|
||||||
|
for(int i=1;i<params.size();i++) {
|
||||||
|
body +=",";
|
||||||
|
char *js = params.jsonString(i);
|
||||||
|
body += js;
|
||||||
|
delete [] js;
|
||||||
|
}
|
||||||
|
body += '}';
|
||||||
|
}
|
||||||
|
body += '}';
|
||||||
|
CsvReader *reader = nullptr;
|
||||||
|
_retryTime = 0;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] Query: %s\n", body.c_str());
|
||||||
|
if(_service->doPOST(_queryUrl.c_str(), body.c_str(), PSTR("application/json"), 200, [&](HTTPClient *httpClient){
|
||||||
|
bool chunked = false;
|
||||||
|
if(httpClient->hasHeader(TransferEncoding)) {
|
||||||
|
String header = httpClient->header(TransferEncoding);
|
||||||
|
chunked = header.equalsIgnoreCase("chunked");
|
||||||
|
}
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] chunked: %s\n", bool2string(chunked));
|
||||||
|
HttpStreamScanner *scanner = new HttpStreamScanner(httpClient, chunked);
|
||||||
|
reader = new CsvReader(scanner);
|
||||||
|
return false;
|
||||||
|
})) {
|
||||||
|
return FluxQueryResult(reader);
|
||||||
|
} else {
|
||||||
|
_retryTime = _service->getLastRetryAfter();
|
||||||
|
return FluxQueryResult(_service->getLastErrorMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static String escapeJSONString(const String &value) {
|
||||||
|
String ret;
|
||||||
|
int d = 0;
|
||||||
|
int i,from = 0;
|
||||||
|
while((i = value.indexOf('"',from)) > -1) {
|
||||||
|
d++;
|
||||||
|
if(i == (int)value.length()-1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
from = i+1;
|
||||||
|
}
|
||||||
|
ret.reserve(value.length()+d); //most probably we will escape just double quotes
|
||||||
|
for (char c: value)
|
||||||
|
{
|
||||||
|
switch (c)
|
||||||
|
{
|
||||||
|
case '"': ret += "\\\""; break;
|
||||||
|
case '\\': ret += "\\\\"; break;
|
||||||
|
case '\b': ret += "\\b"; break;
|
||||||
|
case '\f': ret += "\\f"; break;
|
||||||
|
case '\n': ret += "\\n"; break;
|
||||||
|
case '\r': ret += "\\r"; break;
|
||||||
|
case '\t': ret += "\\t"; break;
|
||||||
|
default:
|
||||||
|
if (c <= '\x1f') {
|
||||||
|
ret += "\\u";
|
||||||
|
char buf[3 + 8 * sizeof(unsigned int)];
|
||||||
|
sprintf(buf, "\\u%04u", c);
|
||||||
|
ret += buf;
|
||||||
|
} else {
|
||||||
|
ret += c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
InfluxDBClient::BatchStreamer::BatchStreamer(InfluxDBClient::Batch *batch) {
|
||||||
|
_batch = batch;
|
||||||
|
_read = 0;
|
||||||
|
_length = 0;
|
||||||
|
_pointer = 0;
|
||||||
|
_linePointer = 0;
|
||||||
|
for(uint16_t i=0;i<_batch->pointer;i++) {
|
||||||
|
_length += strlen(_batch->buffer[i])+1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::BatchStreamer::available() {
|
||||||
|
return _length-_read;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::BatchStreamer::availableForWrite() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
int InfluxDBClient::BatchStreamer::read(uint8_t* buffer, size_t len) {
|
||||||
|
INFLUXDB_CLIENT_DEBUG("BatchStream::read %d\n", len);
|
||||||
|
return readBytes((char *)buffer, len);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
size_t InfluxDBClient::BatchStreamer::readBytes(char* buffer, size_t len) {
|
||||||
|
|
||||||
|
INFLUXDB_CLIENT_DEBUG("BatchStream::readBytes %d\n", len);
|
||||||
|
unsigned int r=0;
|
||||||
|
for(unsigned int i=0;i<len;i++) {
|
||||||
|
if(available()) {
|
||||||
|
buffer[i] = read();
|
||||||
|
r++;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::BatchStreamer::read() {
|
||||||
|
int r = peek();
|
||||||
|
if(r > 0) {
|
||||||
|
++_read;
|
||||||
|
++_linePointer;
|
||||||
|
if(!_batch->buffer[_pointer][_linePointer-1]) {
|
||||||
|
++_pointer;
|
||||||
|
_linePointer = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int InfluxDBClient::BatchStreamer::peek() {
|
||||||
|
if(_pointer == _batch->pointer) {
|
||||||
|
//This should not happen
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int r;
|
||||||
|
if(!_batch->buffer[_pointer][_linePointer]) {
|
||||||
|
r = '\n';
|
||||||
|
} else {
|
||||||
|
r = _batch->buffer[_pointer][_linePointer];
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t InfluxDBClient::BatchStreamer::write(uint8_t) {
|
||||||
|
return 0;
|
||||||
|
}
|
273
firmware/libraries/ESP8266_Influxdb/src/InfluxDbClient.h
Normal file
273
firmware/libraries/ESP8266_Influxdb/src/InfluxDbClient.h
Normal file
|
@ -0,0 +1,273 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDBClient.h: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _INFLUXDB_CLIENT_H_
|
||||||
|
#define _INFLUXDB_CLIENT_H_
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "HTTPService.h"
|
||||||
|
#include "Point.h"
|
||||||
|
#include "WritePrecision.h"
|
||||||
|
#include "query/FluxParser.h"
|
||||||
|
#include "query/Params.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
#include "Options.h"
|
||||||
|
#include "BucketsClient.h"
|
||||||
|
#include "Version.h"
|
||||||
|
|
||||||
|
#ifdef USING_AXTLS
|
||||||
|
#error AxTLS does not work
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* InfluxDBClient handles connection and basic operations for an InfluxDB server.
|
||||||
|
* It provides write API with ability to write data in batches and retrying failed writes.
|
||||||
|
* Automaticaly retries failed writes during next write, if server is overloaded.
|
||||||
|
*/
|
||||||
|
class InfluxDBClient {
|
||||||
|
friend class Test;
|
||||||
|
public:
|
||||||
|
// Creates InfluxDBClient unconfigured instance.
|
||||||
|
// Call to setConnectionParams is required to set up client
|
||||||
|
InfluxDBClient();
|
||||||
|
// Creates InfluxDBClient instance for unsecured connection to InfluxDB 1
|
||||||
|
// serverUrl - url of the InfluxDB 1 server (e.g. http://localhost:8086)
|
||||||
|
// db - database name where to store or read data
|
||||||
|
InfluxDBClient(const String &serverUrl, const String &db);
|
||||||
|
// Creates InfluxDBClient instance for unsecured connection
|
||||||
|
// serverUrl - url of the InfluxDB 2 server (e.g. http://localhost:8086)
|
||||||
|
// org - name of the organization, which bucket belongs to
|
||||||
|
// bucket - name of the bucket to write data into
|
||||||
|
// authToken - InfluxDB 2 authorization token
|
||||||
|
InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken);
|
||||||
|
// Creates InfluxDBClient instance for secured connection
|
||||||
|
// serverUrl - url of the InfluxDB 2 server (e.g. https://localhost:8086)
|
||||||
|
// org - name of the organization, which bucket belongs to
|
||||||
|
// bucket - name of the bucket to write data into
|
||||||
|
// authToken - InfluxDB 2 authorization token
|
||||||
|
// certInfo - InfluxDB 2 server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM.
|
||||||
|
InfluxDBClient(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *certInfo);
|
||||||
|
// Clears instance.
|
||||||
|
~InfluxDBClient();
|
||||||
|
// Allows insecure connection by skiping server certificate validation.
|
||||||
|
// setInsecure must be called before calling any method initiating a connection to server.
|
||||||
|
void setInsecure(bool value = true);
|
||||||
|
// Sets custom write options.
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// precision - timestamp precision of written data
|
||||||
|
// batchSize - number of points that will be written to the databases at once. Default 1 - writes immediately
|
||||||
|
// bufferSize - maximum size of Points buffer. Buffer contains new data that will be written to the database
|
||||||
|
// and also data that failed to be written due to network failure or server overloading
|
||||||
|
// flushInterval - maximum number of seconds data will be held in buffer before are written to the db.
|
||||||
|
// Data are written either when number of points in buffer reaches batchSize or time of
|
||||||
|
// preserveConnection - true if HTTP connection should be kept open. Usable for frequent writes.
|
||||||
|
// Returns true if setting was successful. Otherwise check getLastErrorMessage() for an error.
|
||||||
|
bool setWriteOptions(WritePrecision precision, uint16_t batchSize = 1, uint16_t bufferSize = 5, uint16_t flushInterval = 60, bool preserveConnection = true) __attribute__ ((deprecated("Use setWriteOptions(const WriteOptions &writeOptions)")));
|
||||||
|
// Sets custom write options. See WriteOptions doc for more info.
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// Returns true if setting was successful. Otherwise check getLastErrorMessage() for an error.
|
||||||
|
// Example:
|
||||||
|
// client.setWriteOptions(WriteOptions().batchSize(10).bufferSize(50)).
|
||||||
|
bool setWriteOptions(const WriteOptions &writeOptions);
|
||||||
|
// Sets custom HTTP options. See HTTPOptions doc for more info.
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// Returns true if setting was successful. Otherwise check getLastErrorMessage() for an error.
|
||||||
|
// Example:
|
||||||
|
// client.setHTTPOptions(HTTPOptions().httpReadTimeout(20000)).
|
||||||
|
bool setHTTPOptions(const HTTPOptions &httpOptions);
|
||||||
|
// Sets connection parameters for InfluxDB 2
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// serverUrl - url of the InfluxDB 2 server (e.g. https//localhost:8086)
|
||||||
|
// org - name of the organization, which bucket belongs to
|
||||||
|
// bucket - name of the bucket to write data into
|
||||||
|
// authToken - InfluxDB 2 authorization token
|
||||||
|
// serverCert - Optional. InfluxDB 2 server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM. Only in case of https connection.
|
||||||
|
void setConnectionParams(const String &serverUrl, const String &org, const String &bucket, const String &authToken, const char *certInfo = nullptr);
|
||||||
|
// Sets parameters for connection to InfluxDB 1
|
||||||
|
// Must be called before calling any method initiating a connection to server.
|
||||||
|
// serverUrl - url of the InfluxDB server (e.g. http://localhost:8086)
|
||||||
|
// db - database name where to store or read data
|
||||||
|
// user - Optional. User name, in case of server requires authetication
|
||||||
|
// password - Optional. User password, in case of server requires authetication
|
||||||
|
// certInfo - Optional. InfluxDB server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM. Only in case of https connection.
|
||||||
|
void setConnectionParamsV1(const String &serverUrl, const String &db, const String &user = (const char *)nullptr, const String &password = (const char *)nullptr, const char *certInfo = nullptr);
|
||||||
|
// Creates line protocol string from point data and optional default tags set in WriteOptions.
|
||||||
|
String pointToLineProtocol(const Point& point);
|
||||||
|
// Validates connection parameters by conecting to server
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool validateConnection();
|
||||||
|
// Writes record in InfluxDB line protocol format to write buffer.
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool writeRecord(const String &record);
|
||||||
|
bool writeRecord(const char *record);
|
||||||
|
// Writes record represented by Point to buffer
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool writePoint(Point& point);
|
||||||
|
// Sends Flux query and returns FluxQueryResult object for subsequently reading flux query response.
|
||||||
|
// Use FluxQueryResult::next() method to iterate over lines of the query result.
|
||||||
|
// Always call of FluxQueryResult::close() when reading is finished. Check FluxQueryResult doc for more info.
|
||||||
|
FluxQueryResult query(const String &fluxQuery);
|
||||||
|
// Sends Flux query with params and returns FluxQueryResult object for subsequently reading flux query response.
|
||||||
|
// Use FluxQueryResult::next() method to iterate over lines of the query result.
|
||||||
|
// Always call of FluxQueryResult::close() when reading is finished. Check FluxQueryResult doc for more info.
|
||||||
|
FluxQueryResult query(const String &fluxQuery, QueryParams params);
|
||||||
|
// Forces writing of all points in buffer, even the batch is not full.
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool flushBuffer();
|
||||||
|
// Returns true if points buffer is full. Usefull when server is overloaded and we may want increase period of write points or decrease number of points
|
||||||
|
bool isBufferFull() const { return _bufferCeiling == _writeBufferSize; };
|
||||||
|
// Returns true if buffer is empty. Usefull when going to sleep and check if there is sth in write buffer (it can happens when batch size if bigger than 1). Call flushBuffer() then.
|
||||||
|
bool isBufferEmpty() const { return _bufferCeiling == 0 && !_writeBuffer[0]; };
|
||||||
|
// Checks points buffer status and flushes if number of points reached batch size or flush interval runs out.
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool checkBuffer();
|
||||||
|
// Wipes out buffered points
|
||||||
|
void resetBuffer();
|
||||||
|
// Returns HTTP status of last request to server. Usefull for advanced handling of failures.
|
||||||
|
int getLastStatusCode() const { return _service?_service->getLastStatusCode():0; }
|
||||||
|
// Returns last response when operation failed
|
||||||
|
String getLastErrorMessage() const { return _connInfo.lastError; }
|
||||||
|
// Returns server url
|
||||||
|
String getServerUrl() const { return _connInfo.serverUrl; }
|
||||||
|
// Check if it is possible to send write/query request to server.
|
||||||
|
// Returns true if write or query can be send, or false, if server is overloaded and retry strategy is applied.
|
||||||
|
// Use getRemainingRetryTime() to get wait time in such case.
|
||||||
|
bool canSendRequest() { return getRemainingRetryTime() == 0; }
|
||||||
|
// Returns remaining wait time in seconds when retry strategy is applied.
|
||||||
|
uint32_t getRemainingRetryTime();
|
||||||
|
// Returns sub-client for managing buckets
|
||||||
|
BucketsClient getBucketsClient();
|
||||||
|
// Enables/disables streaming write. This allows sending large batches without allocating buffer.
|
||||||
|
// It is about 50% slower than writing by allocated buffer (default);
|
||||||
|
void setStreamWrite(bool enable = true);
|
||||||
|
// Returns true if HTTP connection is kept open (connection reuse must be set to true)
|
||||||
|
bool isConnected() const { return _service && _service->isConnected(); }
|
||||||
|
protected:
|
||||||
|
// Checks params and sets up security, if needed.
|
||||||
|
// Returns true in case of success, otherwise false
|
||||||
|
bool init();
|
||||||
|
// Cleans instances
|
||||||
|
void clean();
|
||||||
|
protected:
|
||||||
|
class Batch {
|
||||||
|
friend class Test;
|
||||||
|
private:
|
||||||
|
uint16_t _size = 0;
|
||||||
|
public:
|
||||||
|
uint16_t pointer = 0;
|
||||||
|
char **buffer = nullptr;
|
||||||
|
uint8_t retryCount = 0;
|
||||||
|
Batch(uint16_t size);
|
||||||
|
~Batch();
|
||||||
|
bool append(const char *line);
|
||||||
|
char *createData();
|
||||||
|
void clear();
|
||||||
|
bool isFull() const {
|
||||||
|
return pointer == _size;
|
||||||
|
}
|
||||||
|
bool isEmpty() const {
|
||||||
|
return pointer == 0 && !buffer[0];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
class BatchStreamer : public Stream {
|
||||||
|
private:
|
||||||
|
Batch *_batch;
|
||||||
|
int _length;
|
||||||
|
int _read;
|
||||||
|
uint16_t _pointer; //points to the item in batch
|
||||||
|
uint16_t _linePointer; //pointes to char in line of batch
|
||||||
|
public:
|
||||||
|
BatchStreamer(Batch *batch) ;
|
||||||
|
virtual ~BatchStreamer() {};
|
||||||
|
|
||||||
|
// Stream overrides
|
||||||
|
virtual int available() override;
|
||||||
|
|
||||||
|
virtual int availableForWrite() override;
|
||||||
|
|
||||||
|
virtual int read() override;
|
||||||
|
#if defined(ESP8266)
|
||||||
|
virtual int read(uint8_t* buffer, size_t len) override;
|
||||||
|
#endif
|
||||||
|
virtual size_t readBytes(char* buffer, size_t len) override;
|
||||||
|
|
||||||
|
virtual void flush() override {};
|
||||||
|
virtual int peek() override;
|
||||||
|
|
||||||
|
virtual size_t write(uint8_t data) override;
|
||||||
|
|
||||||
|
};
|
||||||
|
ConnectionInfo _connInfo;
|
||||||
|
// Cached full write url
|
||||||
|
String _writeUrl;
|
||||||
|
// Cached full query url
|
||||||
|
String _queryUrl;
|
||||||
|
// Points buffer
|
||||||
|
Batch **_writeBuffer = nullptr;
|
||||||
|
// Batch buffer size
|
||||||
|
uint8_t _writeBufferSize;
|
||||||
|
// Write options
|
||||||
|
WriteOptions _writeOptions;
|
||||||
|
// Store retry timeout suggested by server or computed
|
||||||
|
int _retryTime = 0;
|
||||||
|
// HTTP operations object
|
||||||
|
HTTPService *_service = nullptr;
|
||||||
|
// Index to buffer where to store new batch
|
||||||
|
uint8_t _bufferPointer = 0;
|
||||||
|
// Actual count of batches in buffer
|
||||||
|
uint8_t _bufferCeiling = 0;
|
||||||
|
// Index of bath start for next write
|
||||||
|
uint8_t _batchPointer = 0;
|
||||||
|
// Last time in sec buffer has been successfully flushed
|
||||||
|
uint32_t _lastFlushed;
|
||||||
|
// Bucket sub-client
|
||||||
|
BucketsClient _buckets;
|
||||||
|
// Write using buffer or stream
|
||||||
|
bool _streamWrite = false;
|
||||||
|
protected:
|
||||||
|
// Sends POST request with data in body
|
||||||
|
int postData(const char *data);
|
||||||
|
int postData(Batch *batch);
|
||||||
|
// Sets cached InfluxDB server API URLs
|
||||||
|
bool setUrls();
|
||||||
|
// Ensures buffer has required size
|
||||||
|
void reserveBuffer(int size);
|
||||||
|
// Drops current batch and advances batch pointer
|
||||||
|
void dropCurrentBatch();
|
||||||
|
// Writes all points in buffer, with respect to the batch size, and in case of success clears the buffer.
|
||||||
|
// flashOnlyFull - whether to flush only full batches
|
||||||
|
// Returns true if successful, false in case of any error
|
||||||
|
bool flushBufferInternal(bool flashOnlyFull);
|
||||||
|
// Checks precision of point and mofifies if needed
|
||||||
|
void checkPrecisions(Point & point);
|
||||||
|
// helper which adds zeroes to timestamo of point to increase precision
|
||||||
|
static void addZerosToTimestamp(Point &point, int zeroes);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
#endif //_INFLUXDB_CLIENT_H_
|
68
firmware/libraries/ESP8266_Influxdb/src/InfluxDbCloud 2.h
Normal file
68
firmware/libraries/ESP8266_Influxdb/src/InfluxDbCloud 2.h
Normal file
|
@ -0,0 +1,68 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDBCloud.h: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _INFLUXDB_CLOUD_H_
|
||||||
|
#define _INFLUXDB_CLOUD_H_
|
||||||
|
|
||||||
|
// Root Certificate Authority of InfluxData Cloud 2 servers.
|
||||||
|
// Valid with all providers (AWS, Azure, GCP)
|
||||||
|
// ISRG Root X1
|
||||||
|
// Valid until 2035-04-04T04:04:38Z
|
||||||
|
const char InfluxDbCloud2CACert[] PROGMEM = R"EOF(
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
||||||
|
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
||||||
|
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
||||||
|
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
||||||
|
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
||||||
|
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
||||||
|
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
||||||
|
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
||||||
|
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
|
||||||
|
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
|
||||||
|
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
|
||||||
|
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
|
||||||
|
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
|
||||||
|
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
|
||||||
|
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
|
||||||
|
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
|
||||||
|
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
|
||||||
|
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
|
||||||
|
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
|
||||||
|
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
|
||||||
|
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
|
||||||
|
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
|
||||||
|
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
|
||||||
|
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
|
||||||
|
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
|
||||||
|
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
|
||||||
|
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
|
||||||
|
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
||||||
|
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
)EOF";
|
||||||
|
|
||||||
|
#endif //_INFLUXDB_CLOUD_H_
|
68
firmware/libraries/ESP8266_Influxdb/src/InfluxDbCloud.h
Normal file
68
firmware/libraries/ESP8266_Influxdb/src/InfluxDbCloud.h
Normal file
|
@ -0,0 +1,68 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* InfluxDBCloud.h: InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _INFLUXDB_CLOUD_H_
|
||||||
|
#define _INFLUXDB_CLOUD_H_
|
||||||
|
|
||||||
|
// Root Certificate Authority of InfluxData Cloud 2 servers.
|
||||||
|
// Valid with all providers (AWS, Azure, GCP)
|
||||||
|
// ISRG Root X1
|
||||||
|
// Valid until 2035-04-04T04:04:38Z
|
||||||
|
const char InfluxDbCloud2CACert[] PROGMEM = R"EOF(
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
||||||
|
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
||||||
|
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
||||||
|
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
||||||
|
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
||||||
|
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
||||||
|
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
||||||
|
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
||||||
|
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
|
||||||
|
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
|
||||||
|
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
|
||||||
|
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
|
||||||
|
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
|
||||||
|
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
|
||||||
|
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
|
||||||
|
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
|
||||||
|
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
|
||||||
|
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
|
||||||
|
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
|
||||||
|
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
|
||||||
|
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
|
||||||
|
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
|
||||||
|
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
|
||||||
|
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
|
||||||
|
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
|
||||||
|
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
|
||||||
|
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
|
||||||
|
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
||||||
|
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
)EOF";
|
||||||
|
|
||||||
|
#endif //_INFLUXDB_CLOUD_H_
|
43
firmware/libraries/ESP8266_Influxdb/src/Options 2.cpp
Normal file
43
firmware/libraries/ESP8266_Influxdb/src/Options 2.cpp
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Options.cpp: InfluxDB Client write options and HTTP options
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "Options.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
WriteOptions& WriteOptions::addDefaultTag(const String &name, const String &value) {
|
||||||
|
if(_defaultTags.length() > 0) {
|
||||||
|
_defaultTags += ',';
|
||||||
|
}
|
||||||
|
char *s = escapeKey(name);
|
||||||
|
_defaultTags += s;
|
||||||
|
delete [] s;
|
||||||
|
s = escapeKey(value);
|
||||||
|
_defaultTags += '=';
|
||||||
|
_defaultTags += s;
|
||||||
|
delete [] s;
|
||||||
|
return *this;
|
||||||
|
}
|
112
firmware/libraries/ESP8266_Influxdb/src/Options 2.h
Normal file
112
firmware/libraries/ESP8266_Influxdb/src/Options 2.h
Normal file
|
@ -0,0 +1,112 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Options.h: InfluxDB Client write options and HTTP options
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _OPTIONS_H_
|
||||||
|
#define _OPTIONS_H_
|
||||||
|
|
||||||
|
#include "WritePrecision.h"
|
||||||
|
|
||||||
|
class InfluxDBClient;
|
||||||
|
class HTTPService;
|
||||||
|
class Influxdb;
|
||||||
|
class Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WriteOptions holds write related options
|
||||||
|
*/
|
||||||
|
class WriteOptions {
|
||||||
|
private:
|
||||||
|
friend class InfluxDBClient;
|
||||||
|
friend class Influxdb;
|
||||||
|
friend class Test;
|
||||||
|
// Points timestamp precision
|
||||||
|
WritePrecision _writePrecision;
|
||||||
|
// Number of points that will be written to the databases at once.
|
||||||
|
// Default 1 (immediate write, no batching)
|
||||||
|
uint16_t _batchSize;
|
||||||
|
// Write buffer size - maximum number of record to keep.
|
||||||
|
// When max size is reached, oldest records are overwritten.
|
||||||
|
// Default 5
|
||||||
|
uint16_t _bufferSize;
|
||||||
|
// Maximum number of seconds points can be held in buffer before are written to the db.
|
||||||
|
// Buffer is flushed when it reaches batch size or when flush interval runs out.
|
||||||
|
uint16_t _flushInterval;
|
||||||
|
// Default retry interval in sec, if not sent by server. Default 5s.
|
||||||
|
// Setting to zero disables retrying.
|
||||||
|
uint16_t _retryInterval;
|
||||||
|
// Maximum retry interval in sec, default 5min (300s)
|
||||||
|
uint16_t _maxRetryInterval;
|
||||||
|
// Maximum count of retry attempts of failed writes, default 3
|
||||||
|
uint16_t _maxRetryAttempts;
|
||||||
|
// Default tags. Default tags are added to every written point.
|
||||||
|
// There cannot be duplicate tags in default tags and tags included in a point.
|
||||||
|
String _defaultTags;
|
||||||
|
public:
|
||||||
|
WriteOptions():
|
||||||
|
_writePrecision(WritePrecision::NoTime),
|
||||||
|
_batchSize(1),
|
||||||
|
_bufferSize(5),
|
||||||
|
_flushInterval(60),
|
||||||
|
_retryInterval(5),
|
||||||
|
_maxRetryInterval(300),
|
||||||
|
_maxRetryAttempts(3) {
|
||||||
|
}
|
||||||
|
WriteOptions& writePrecision(WritePrecision precision) { _writePrecision = precision; return *this; }
|
||||||
|
WriteOptions& batchSize(uint16_t batchSize) { _batchSize = batchSize; return *this; }
|
||||||
|
WriteOptions& bufferSize(uint16_t bufferSize) { _bufferSize = bufferSize; return *this; }
|
||||||
|
WriteOptions& flushInterval(uint16_t flushIntervalSec) { _flushInterval = flushIntervalSec; return *this; }
|
||||||
|
WriteOptions& retryInterval(uint16_t retryIntervalSec) { _retryInterval = retryIntervalSec; return *this; }
|
||||||
|
WriteOptions& maxRetryInterval(uint16_t maxRetryIntervalSec) { _maxRetryInterval = maxRetryIntervalSec; return *this; }
|
||||||
|
WriteOptions& maxRetryAttempts(uint16_t maxRetryAttempts) { _maxRetryAttempts = maxRetryAttempts; return *this; }
|
||||||
|
WriteOptions& addDefaultTag(const String &name, const String &value);
|
||||||
|
WriteOptions& clearDefaultTags() { _defaultTags = (char *)nullptr; return *this; }
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTPOptions holds HTTP related options
|
||||||
|
*/
|
||||||
|
class HTTPOptions {
|
||||||
|
private:
|
||||||
|
friend class InfluxDBClient;
|
||||||
|
friend class HTTPService;
|
||||||
|
friend class Influxdb;
|
||||||
|
friend class Test;
|
||||||
|
// true if HTTP connection should be kept open. Usable for frequent writes.
|
||||||
|
// Default false.
|
||||||
|
bool _connectionReuse;
|
||||||
|
// Timeout [ms] for reading server response.
|
||||||
|
// Default 5000ms
|
||||||
|
int _httpReadTimeout;
|
||||||
|
public:
|
||||||
|
HTTPOptions():
|
||||||
|
_connectionReuse(false),
|
||||||
|
_httpReadTimeout(5000) {
|
||||||
|
}
|
||||||
|
HTTPOptions& connectionReuse(bool connectionReuse) { _connectionReuse = connectionReuse; return *this; }
|
||||||
|
HTTPOptions& httpReadTimeout(int httpReadTimeoutMs) { _httpReadTimeout = httpReadTimeoutMs; return *this; }
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_OPTIONS_H_
|
43
firmware/libraries/ESP8266_Influxdb/src/Options.cpp
Normal file
43
firmware/libraries/ESP8266_Influxdb/src/Options.cpp
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Options.cpp: InfluxDB Client write options and HTTP options
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "Options.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
WriteOptions& WriteOptions::addDefaultTag(const String &name, const String &value) {
|
||||||
|
if(_defaultTags.length() > 0) {
|
||||||
|
_defaultTags += ',';
|
||||||
|
}
|
||||||
|
char *s = escapeKey(name);
|
||||||
|
_defaultTags += s;
|
||||||
|
delete [] s;
|
||||||
|
s = escapeKey(value);
|
||||||
|
_defaultTags += '=';
|
||||||
|
_defaultTags += s;
|
||||||
|
delete [] s;
|
||||||
|
return *this;
|
||||||
|
}
|
112
firmware/libraries/ESP8266_Influxdb/src/Options.h
Normal file
112
firmware/libraries/ESP8266_Influxdb/src/Options.h
Normal file
|
@ -0,0 +1,112 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Options.h: InfluxDB Client write options and HTTP options
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _OPTIONS_H_
|
||||||
|
#define _OPTIONS_H_
|
||||||
|
|
||||||
|
#include "WritePrecision.h"
|
||||||
|
|
||||||
|
class InfluxDBClient;
|
||||||
|
class HTTPService;
|
||||||
|
class Influxdb;
|
||||||
|
class Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WriteOptions holds write related options
|
||||||
|
*/
|
||||||
|
class WriteOptions {
|
||||||
|
private:
|
||||||
|
friend class InfluxDBClient;
|
||||||
|
friend class Influxdb;
|
||||||
|
friend class Test;
|
||||||
|
// Points timestamp precision
|
||||||
|
WritePrecision _writePrecision;
|
||||||
|
// Number of points that will be written to the databases at once.
|
||||||
|
// Default 1 (immediate write, no batching)
|
||||||
|
uint16_t _batchSize;
|
||||||
|
// Write buffer size - maximum number of record to keep.
|
||||||
|
// When max size is reached, oldest records are overwritten.
|
||||||
|
// Default 5
|
||||||
|
uint16_t _bufferSize;
|
||||||
|
// Maximum number of seconds points can be held in buffer before are written to the db.
|
||||||
|
// Buffer is flushed when it reaches batch size or when flush interval runs out.
|
||||||
|
uint16_t _flushInterval;
|
||||||
|
// Default retry interval in sec, if not sent by server. Default 5s.
|
||||||
|
// Setting to zero disables retrying.
|
||||||
|
uint16_t _retryInterval;
|
||||||
|
// Maximum retry interval in sec, default 5min (300s)
|
||||||
|
uint16_t _maxRetryInterval;
|
||||||
|
// Maximum count of retry attempts of failed writes, default 3
|
||||||
|
uint16_t _maxRetryAttempts;
|
||||||
|
// Default tags. Default tags are added to every written point.
|
||||||
|
// There cannot be duplicate tags in default tags and tags included in a point.
|
||||||
|
String _defaultTags;
|
||||||
|
public:
|
||||||
|
WriteOptions():
|
||||||
|
_writePrecision(WritePrecision::NoTime),
|
||||||
|
_batchSize(1),
|
||||||
|
_bufferSize(5),
|
||||||
|
_flushInterval(60),
|
||||||
|
_retryInterval(5),
|
||||||
|
_maxRetryInterval(300),
|
||||||
|
_maxRetryAttempts(3) {
|
||||||
|
}
|
||||||
|
WriteOptions& writePrecision(WritePrecision precision) { _writePrecision = precision; return *this; }
|
||||||
|
WriteOptions& batchSize(uint16_t batchSize) { _batchSize = batchSize; return *this; }
|
||||||
|
WriteOptions& bufferSize(uint16_t bufferSize) { _bufferSize = bufferSize; return *this; }
|
||||||
|
WriteOptions& flushInterval(uint16_t flushIntervalSec) { _flushInterval = flushIntervalSec; return *this; }
|
||||||
|
WriteOptions& retryInterval(uint16_t retryIntervalSec) { _retryInterval = retryIntervalSec; return *this; }
|
||||||
|
WriteOptions& maxRetryInterval(uint16_t maxRetryIntervalSec) { _maxRetryInterval = maxRetryIntervalSec; return *this; }
|
||||||
|
WriteOptions& maxRetryAttempts(uint16_t maxRetryAttempts) { _maxRetryAttempts = maxRetryAttempts; return *this; }
|
||||||
|
WriteOptions& addDefaultTag(const String &name, const String &value);
|
||||||
|
WriteOptions& clearDefaultTags() { _defaultTags = (char *)nullptr; return *this; }
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTTPOptions holds HTTP related options
|
||||||
|
*/
|
||||||
|
class HTTPOptions {
|
||||||
|
private:
|
||||||
|
friend class InfluxDBClient;
|
||||||
|
friend class HTTPService;
|
||||||
|
friend class Influxdb;
|
||||||
|
friend class Test;
|
||||||
|
// true if HTTP connection should be kept open. Usable for frequent writes.
|
||||||
|
// Default false.
|
||||||
|
bool _connectionReuse;
|
||||||
|
// Timeout [ms] for reading server response.
|
||||||
|
// Default 5000ms
|
||||||
|
int _httpReadTimeout;
|
||||||
|
public:
|
||||||
|
HTTPOptions():
|
||||||
|
_connectionReuse(false),
|
||||||
|
_httpReadTimeout(5000) {
|
||||||
|
}
|
||||||
|
HTTPOptions& connectionReuse(bool connectionReuse) { _connectionReuse = connectionReuse; return *this; }
|
||||||
|
HTTPOptions& httpReadTimeout(int httpReadTimeoutMs) { _httpReadTimeout = httpReadTimeoutMs; return *this; }
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_OPTIONS_H_
|
17
firmware/libraries/ESP8266_Influxdb/src/Platform 2.h
Normal file
17
firmware/libraries/ESP8266_Influxdb/src/Platform 2.h
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
#ifndef _PLATFORM_H_
|
||||||
|
#define _PLATFORM_H_
|
||||||
|
|
||||||
|
#include <core_version.h>
|
||||||
|
|
||||||
|
#define STRHELPER(x) #x
|
||||||
|
#define STR(x) STRHELPER(x) // stringifier
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
# define INFLUXDB_CLIENT_PLATFORM "ESP8266"
|
||||||
|
# define INFLUXDB_CLIENT_PLATFORM_VERSION STR(ARDUINO_ESP8266_GIT_DESC)
|
||||||
|
#elif defined(ESP32)
|
||||||
|
# define INFLUXDB_CLIENT_PLATFORM "ESP32"
|
||||||
|
# define INFLUXDB_CLIENT_PLATFORM_VERSION STR(ARDUINO_ESP32_GIT_DESC)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif //_PLATFORM_H_
|
17
firmware/libraries/ESP8266_Influxdb/src/Platform.h
Normal file
17
firmware/libraries/ESP8266_Influxdb/src/Platform.h
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
#ifndef _PLATFORM_H_
|
||||||
|
#define _PLATFORM_H_
|
||||||
|
|
||||||
|
#include <core_version.h>
|
||||||
|
|
||||||
|
#define STRHELPER(x) #x
|
||||||
|
#define STR(x) STRHELPER(x) // stringifier
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
# define INFLUXDB_CLIENT_PLATFORM "ESP8266"
|
||||||
|
# define INFLUXDB_CLIENT_PLATFORM_VERSION STR(ARDUINO_ESP8266_GIT_DESC)
|
||||||
|
#elif defined(ESP32)
|
||||||
|
# define INFLUXDB_CLIENT_PLATFORM "ESP32"
|
||||||
|
# define INFLUXDB_CLIENT_PLATFORM_VERSION STR(ARDUINO_ESP32_GIT_DESC)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif //_PLATFORM_H_
|
203
firmware/libraries/ESP8266_Influxdb/src/Point 2.cpp
Normal file
203
firmware/libraries/ESP8266_Influxdb/src/Point 2.cpp
Normal file
|
@ -0,0 +1,203 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Point.cpp: Point for write into InfluxDB server
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "Point.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
Point::Point(const String & measurement)
|
||||||
|
{
|
||||||
|
_measurement = escapeKey(measurement, false);
|
||||||
|
_timestamp = nullptr;
|
||||||
|
_tsWritePrecision = WritePrecision::NoTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
Point::~Point() {
|
||||||
|
delete [] _measurement;
|
||||||
|
delete [] _timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addTag(const String &name, String value) {
|
||||||
|
if(_tags.length() > 0) {
|
||||||
|
_tags += ',';
|
||||||
|
}
|
||||||
|
char *s = escapeKey(name);
|
||||||
|
_tags += s;
|
||||||
|
delete [] s;
|
||||||
|
_tags += '=';
|
||||||
|
s = escapeKey(value);
|
||||||
|
_tags += s;
|
||||||
|
delete [] s;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, long long value) {
|
||||||
|
char buff[23];
|
||||||
|
snprintf(buff, 50, "%lld", value);
|
||||||
|
putField(name, String(buff)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, unsigned long long value) {
|
||||||
|
char buff[23];
|
||||||
|
snprintf(buff, 50, "%llu", value);
|
||||||
|
putField(name, String(buff)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, const char *value) {
|
||||||
|
putField(name, escapeValue(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, const __FlashStringHelper *pstr) {
|
||||||
|
addField(name, String(pstr));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, float value, int decimalPlaces) {
|
||||||
|
if(!isnan(value)) putField(name, String(value, decimalPlaces));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, double value, int decimalPlaces) {
|
||||||
|
if(!isnan(value)) putField(name, String(value, decimalPlaces));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, char value) {
|
||||||
|
addField(name, String(value).c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, unsigned char value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, int value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, unsigned int value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, long value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, unsigned long value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, bool value) {
|
||||||
|
putField(name, bool2string(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, const String &value) {
|
||||||
|
addField(name, value.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::putField(const String &name, const String &value) {
|
||||||
|
if(_fields.length() > 0) {
|
||||||
|
_fields += ',';
|
||||||
|
}
|
||||||
|
char *s = escapeKey(name);
|
||||||
|
_fields += s;
|
||||||
|
delete [] s;
|
||||||
|
_fields += '=';
|
||||||
|
_fields += value;
|
||||||
|
}
|
||||||
|
|
||||||
|
String Point::toLineProtocol(const String &includeTags) const {
|
||||||
|
return createLineProtocol(includeTags);
|
||||||
|
}
|
||||||
|
|
||||||
|
String Point::createLineProtocol(const String &incTags) const {
|
||||||
|
String line;
|
||||||
|
line.reserve(strLen(_measurement) + 1 + incTags.length() + 1 + _tags.length() + 1 + _fields.length() + 1 + strLen(_timestamp));
|
||||||
|
line += _measurement;
|
||||||
|
if(incTags.length()>0) {
|
||||||
|
line += ",";
|
||||||
|
line += incTags;
|
||||||
|
}
|
||||||
|
if(hasTags()) {
|
||||||
|
line += ",";
|
||||||
|
line += _tags;
|
||||||
|
}
|
||||||
|
if(hasFields()) {
|
||||||
|
line += " ";
|
||||||
|
line += _fields;
|
||||||
|
}
|
||||||
|
if(hasTime()) {
|
||||||
|
line += " ";
|
||||||
|
line += _timestamp;
|
||||||
|
}
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(WritePrecision precision) {
|
||||||
|
struct timeval tv;
|
||||||
|
gettimeofday(&tv, NULL);
|
||||||
|
|
||||||
|
switch(precision) {
|
||||||
|
case WritePrecision::NS:
|
||||||
|
setTime(getTimeStamp(&tv,9));
|
||||||
|
break;
|
||||||
|
case WritePrecision::US:
|
||||||
|
setTime(getTimeStamp(&tv,6));
|
||||||
|
break;
|
||||||
|
case WritePrecision::MS:
|
||||||
|
setTime(getTimeStamp(&tv,3));
|
||||||
|
break;
|
||||||
|
case WritePrecision::S:
|
||||||
|
setTime(getTimeStamp(&tv,0));
|
||||||
|
break;
|
||||||
|
case WritePrecision::NoTime:
|
||||||
|
setTime((char *)nullptr);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_tsWritePrecision = precision;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(unsigned long long timestamp) {
|
||||||
|
setTime(timeStampToString(timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(const String ×tamp) {
|
||||||
|
setTime(cloneStr(timestamp.c_str()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(const char *timestamp) {
|
||||||
|
setTime(cloneStr(timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(char *timestamp) {
|
||||||
|
delete [] _timestamp;
|
||||||
|
_timestamp = timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::clearFields() {
|
||||||
|
_fields = (char *)nullptr;
|
||||||
|
delete [] _timestamp;
|
||||||
|
_timestamp = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point:: clearTags() {
|
||||||
|
_tags = (char *)nullptr;
|
||||||
|
}
|
96
firmware/libraries/ESP8266_Influxdb/src/Point 2.h
Normal file
96
firmware/libraries/ESP8266_Influxdb/src/Point 2.h
Normal file
|
@ -0,0 +1,96 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Point.h: Point for write into InfluxDB server
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _POINT_H_
|
||||||
|
#define _POINT_H_
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "WritePrecision.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class Point represents InfluxDB point in line protocol.
|
||||||
|
* It defines data to be written to InfluxDB.
|
||||||
|
*/
|
||||||
|
class Point {
|
||||||
|
friend class InfluxDBClient;
|
||||||
|
public:
|
||||||
|
Point(const String &measurement);
|
||||||
|
virtual ~Point();
|
||||||
|
// Adds string tag
|
||||||
|
void addTag(const String &name, String value);
|
||||||
|
// Add field with various types
|
||||||
|
void addField(const String &name, float value, int decimalPlaces = 2);
|
||||||
|
void addField(const String &name, double value, int decimalPlaces = 2);
|
||||||
|
void addField(const String &name, char value);
|
||||||
|
void addField(const String &name, unsigned char value);
|
||||||
|
void addField(const String &name, int value);
|
||||||
|
void addField(const String &name, unsigned int value);
|
||||||
|
void addField(const String &name, long value);
|
||||||
|
void addField(const String &name, unsigned long value);
|
||||||
|
void addField(const String &name, bool value);
|
||||||
|
void addField(const String &name, const String &value);
|
||||||
|
void addField(const String &name, const __FlashStringHelper *pstr);
|
||||||
|
void addField(const String &name, long long value);
|
||||||
|
void addField(const String &name, unsigned long long value);
|
||||||
|
void addField(const String &name, const char *value);
|
||||||
|
// Set timestamp to `now()` and store it in specified precision, nanoseconds by default. Date and time must be already set. See `configTime` in the device API
|
||||||
|
void setTime(WritePrecision writePrecision = WritePrecision::NS);
|
||||||
|
// Set timestamp in offset since epoch (1.1.1970). Correct precision must be set InfluxDBClient::setWriteOptions.
|
||||||
|
void setTime(unsigned long long timestamp);
|
||||||
|
// Set timestamp in offset since epoch (1.1.1970 00:00:00). Correct precision must be set InfluxDBClient::setWriteOptions.
|
||||||
|
void setTime(const String ×tamp);
|
||||||
|
// Set timestamp in offset since epoch (1.1.1970 00:00:00). Correct precision must be set InfluxDBClient::setWriteOptions.
|
||||||
|
void setTime(const char *timestamp);
|
||||||
|
// Clear all fields. Usefull for reusing point
|
||||||
|
void clearFields();
|
||||||
|
// Clear tags
|
||||||
|
void clearTags();
|
||||||
|
// True if a point contains at least one field. Points without a field cannot be written to db
|
||||||
|
bool hasFields() const { return _fields.length() > 0; }
|
||||||
|
// True if a point contains at least one tag
|
||||||
|
bool hasTags() const { return _tags.length() > 0; }
|
||||||
|
// True if a point contains timestamp
|
||||||
|
bool hasTime() const { return strLen(_timestamp) > 0; }
|
||||||
|
// Creates line protocol with optionally added tags
|
||||||
|
String toLineProtocol(const String &includeTags = "") const;
|
||||||
|
// returns current timestamp
|
||||||
|
String getTime() const { return _timestamp; }
|
||||||
|
protected:
|
||||||
|
char *_measurement;
|
||||||
|
String _tags;
|
||||||
|
String _fields;
|
||||||
|
char *_timestamp;
|
||||||
|
WritePrecision _tsWritePrecision;
|
||||||
|
protected:
|
||||||
|
// method for formating field into line protocol
|
||||||
|
void putField(const String &name, const String &value);
|
||||||
|
// set timestamp
|
||||||
|
void setTime(char *timestamp);
|
||||||
|
// Creates line protocol string
|
||||||
|
String createLineProtocol(const String &incTags) const;
|
||||||
|
};
|
||||||
|
#endif //_POINT_H_
|
203
firmware/libraries/ESP8266_Influxdb/src/Point.cpp
Normal file
203
firmware/libraries/ESP8266_Influxdb/src/Point.cpp
Normal file
|
@ -0,0 +1,203 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Point.cpp: Point for write into InfluxDB server
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "Point.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
Point::Point(const String & measurement)
|
||||||
|
{
|
||||||
|
_measurement = escapeKey(measurement, false);
|
||||||
|
_timestamp = nullptr;
|
||||||
|
_tsWritePrecision = WritePrecision::NoTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
Point::~Point() {
|
||||||
|
delete [] _measurement;
|
||||||
|
delete [] _timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addTag(const String &name, String value) {
|
||||||
|
if(_tags.length() > 0) {
|
||||||
|
_tags += ',';
|
||||||
|
}
|
||||||
|
char *s = escapeKey(name);
|
||||||
|
_tags += s;
|
||||||
|
delete [] s;
|
||||||
|
_tags += '=';
|
||||||
|
s = escapeKey(value);
|
||||||
|
_tags += s;
|
||||||
|
delete [] s;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, long long value) {
|
||||||
|
char buff[23];
|
||||||
|
snprintf(buff, 50, "%lld", value);
|
||||||
|
putField(name, String(buff)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, unsigned long long value) {
|
||||||
|
char buff[23];
|
||||||
|
snprintf(buff, 50, "%llu", value);
|
||||||
|
putField(name, String(buff)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, const char *value) {
|
||||||
|
putField(name, escapeValue(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, const __FlashStringHelper *pstr) {
|
||||||
|
addField(name, String(pstr));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, float value, int decimalPlaces) {
|
||||||
|
if(!isnan(value)) putField(name, String(value, decimalPlaces));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, double value, int decimalPlaces) {
|
||||||
|
if(!isnan(value)) putField(name, String(value, decimalPlaces));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, char value) {
|
||||||
|
addField(name, String(value).c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, unsigned char value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, int value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, unsigned int value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, long value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, unsigned long value) {
|
||||||
|
putField(name, String(value)+"i");
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, bool value) {
|
||||||
|
putField(name, bool2string(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::addField(const String &name, const String &value) {
|
||||||
|
addField(name, value.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::putField(const String &name, const String &value) {
|
||||||
|
if(_fields.length() > 0) {
|
||||||
|
_fields += ',';
|
||||||
|
}
|
||||||
|
char *s = escapeKey(name);
|
||||||
|
_fields += s;
|
||||||
|
delete [] s;
|
||||||
|
_fields += '=';
|
||||||
|
_fields += value;
|
||||||
|
}
|
||||||
|
|
||||||
|
String Point::toLineProtocol(const String &includeTags) const {
|
||||||
|
return createLineProtocol(includeTags);
|
||||||
|
}
|
||||||
|
|
||||||
|
String Point::createLineProtocol(const String &incTags) const {
|
||||||
|
String line;
|
||||||
|
line.reserve(strLen(_measurement) + 1 + incTags.length() + 1 + _tags.length() + 1 + _fields.length() + 1 + strLen(_timestamp));
|
||||||
|
line += _measurement;
|
||||||
|
if(incTags.length()>0) {
|
||||||
|
line += ",";
|
||||||
|
line += incTags;
|
||||||
|
}
|
||||||
|
if(hasTags()) {
|
||||||
|
line += ",";
|
||||||
|
line += _tags;
|
||||||
|
}
|
||||||
|
if(hasFields()) {
|
||||||
|
line += " ";
|
||||||
|
line += _fields;
|
||||||
|
}
|
||||||
|
if(hasTime()) {
|
||||||
|
line += " ";
|
||||||
|
line += _timestamp;
|
||||||
|
}
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(WritePrecision precision) {
|
||||||
|
struct timeval tv;
|
||||||
|
gettimeofday(&tv, NULL);
|
||||||
|
|
||||||
|
switch(precision) {
|
||||||
|
case WritePrecision::NS:
|
||||||
|
setTime(getTimeStamp(&tv,9));
|
||||||
|
break;
|
||||||
|
case WritePrecision::US:
|
||||||
|
setTime(getTimeStamp(&tv,6));
|
||||||
|
break;
|
||||||
|
case WritePrecision::MS:
|
||||||
|
setTime(getTimeStamp(&tv,3));
|
||||||
|
break;
|
||||||
|
case WritePrecision::S:
|
||||||
|
setTime(getTimeStamp(&tv,0));
|
||||||
|
break;
|
||||||
|
case WritePrecision::NoTime:
|
||||||
|
setTime((char *)nullptr);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_tsWritePrecision = precision;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(unsigned long long timestamp) {
|
||||||
|
setTime(timeStampToString(timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(const String ×tamp) {
|
||||||
|
setTime(cloneStr(timestamp.c_str()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(const char *timestamp) {
|
||||||
|
setTime(cloneStr(timestamp));
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::setTime(char *timestamp) {
|
||||||
|
delete [] _timestamp;
|
||||||
|
_timestamp = timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point::clearFields() {
|
||||||
|
_fields = (char *)nullptr;
|
||||||
|
delete [] _timestamp;
|
||||||
|
_timestamp = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Point:: clearTags() {
|
||||||
|
_tags = (char *)nullptr;
|
||||||
|
}
|
96
firmware/libraries/ESP8266_Influxdb/src/Point.h
Normal file
96
firmware/libraries/ESP8266_Influxdb/src/Point.h
Normal file
|
@ -0,0 +1,96 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Point.h: Point for write into InfluxDB server
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _POINT_H_
|
||||||
|
#define _POINT_H_
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include "WritePrecision.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class Point represents InfluxDB point in line protocol.
|
||||||
|
* It defines data to be written to InfluxDB.
|
||||||
|
*/
|
||||||
|
class Point {
|
||||||
|
friend class InfluxDBClient;
|
||||||
|
public:
|
||||||
|
Point(const String &measurement);
|
||||||
|
virtual ~Point();
|
||||||
|
// Adds string tag
|
||||||
|
void addTag(const String &name, String value);
|
||||||
|
// Add field with various types
|
||||||
|
void addField(const String &name, float value, int decimalPlaces = 2);
|
||||||
|
void addField(const String &name, double value, int decimalPlaces = 2);
|
||||||
|
void addField(const String &name, char value);
|
||||||
|
void addField(const String &name, unsigned char value);
|
||||||
|
void addField(const String &name, int value);
|
||||||
|
void addField(const String &name, unsigned int value);
|
||||||
|
void addField(const String &name, long value);
|
||||||
|
void addField(const String &name, unsigned long value);
|
||||||
|
void addField(const String &name, bool value);
|
||||||
|
void addField(const String &name, const String &value);
|
||||||
|
void addField(const String &name, const __FlashStringHelper *pstr);
|
||||||
|
void addField(const String &name, long long value);
|
||||||
|
void addField(const String &name, unsigned long long value);
|
||||||
|
void addField(const String &name, const char *value);
|
||||||
|
// Set timestamp to `now()` and store it in specified precision, nanoseconds by default. Date and time must be already set. See `configTime` in the device API
|
||||||
|
void setTime(WritePrecision writePrecision = WritePrecision::NS);
|
||||||
|
// Set timestamp in offset since epoch (1.1.1970). Correct precision must be set InfluxDBClient::setWriteOptions.
|
||||||
|
void setTime(unsigned long long timestamp);
|
||||||
|
// Set timestamp in offset since epoch (1.1.1970 00:00:00). Correct precision must be set InfluxDBClient::setWriteOptions.
|
||||||
|
void setTime(const String ×tamp);
|
||||||
|
// Set timestamp in offset since epoch (1.1.1970 00:00:00). Correct precision must be set InfluxDBClient::setWriteOptions.
|
||||||
|
void setTime(const char *timestamp);
|
||||||
|
// Clear all fields. Usefull for reusing point
|
||||||
|
void clearFields();
|
||||||
|
// Clear tags
|
||||||
|
void clearTags();
|
||||||
|
// True if a point contains at least one field. Points without a field cannot be written to db
|
||||||
|
bool hasFields() const { return _fields.length() > 0; }
|
||||||
|
// True if a point contains at least one tag
|
||||||
|
bool hasTags() const { return _tags.length() > 0; }
|
||||||
|
// True if a point contains timestamp
|
||||||
|
bool hasTime() const { return strLen(_timestamp) > 0; }
|
||||||
|
// Creates line protocol with optionally added tags
|
||||||
|
String toLineProtocol(const String &includeTags = "") const;
|
||||||
|
// returns current timestamp
|
||||||
|
String getTime() const { return _timestamp; }
|
||||||
|
protected:
|
||||||
|
char *_measurement;
|
||||||
|
String _tags;
|
||||||
|
String _fields;
|
||||||
|
char *_timestamp;
|
||||||
|
WritePrecision _tsWritePrecision;
|
||||||
|
protected:
|
||||||
|
// method for formating field into line protocol
|
||||||
|
void putField(const String &name, const String &value);
|
||||||
|
// set timestamp
|
||||||
|
void setTime(char *timestamp);
|
||||||
|
// Creates line protocol string
|
||||||
|
String createLineProtocol(const String &incTags) const;
|
||||||
|
};
|
||||||
|
#endif //_POINT_H_
|
32
firmware/libraries/ESP8266_Influxdb/src/Version 2.h
Normal file
32
firmware/libraries/ESP8266_Influxdb/src/Version 2.h
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Version.h: Version constant
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _VERSION_H_
|
||||||
|
#define _VERSION_H_
|
||||||
|
|
||||||
|
#define INFLUXDB_CLIENT_VERSION "3.12.1"
|
||||||
|
|
||||||
|
#endif //_VERSION_H_
|
32
firmware/libraries/ESP8266_Influxdb/src/Version.h
Normal file
32
firmware/libraries/ESP8266_Influxdb/src/Version.h
Normal file
|
@ -0,0 +1,32 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Version.h: Version constant
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _VERSION_H_
|
||||||
|
#define _VERSION_H_
|
||||||
|
|
||||||
|
#define INFLUXDB_CLIENT_VERSION "3.12.1"
|
||||||
|
|
||||||
|
#endif //_VERSION_H_
|
43
firmware/libraries/ESP8266_Influxdb/src/WritePrecision 2.h
Normal file
43
firmware/libraries/ESP8266_Influxdb/src/WritePrecision 2.h
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* WritePrecision.h: Write precision for InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _WRITE_PRECISION_H_
|
||||||
|
#define _WRITE_PRECISION_H_
|
||||||
|
// Enum WritePrecision defines constants for specifying InfluxDB write prcecision
|
||||||
|
enum class WritePrecision:uint8_t {
|
||||||
|
// Specifyies that points has no timestamp (default). Server will assign timestamp.
|
||||||
|
NoTime = 0,
|
||||||
|
// Seconds
|
||||||
|
S,
|
||||||
|
// Milli-seconds
|
||||||
|
MS,
|
||||||
|
// Micro-seconds
|
||||||
|
US,
|
||||||
|
// Nano-seconds
|
||||||
|
NS
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_WRITE_PRECISION_H_
|
43
firmware/libraries/ESP8266_Influxdb/src/WritePrecision.h
Normal file
43
firmware/libraries/ESP8266_Influxdb/src/WritePrecision.h
Normal file
|
@ -0,0 +1,43 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* WritePrecision.h: Write precision for InfluxDB Client for Arduino
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _WRITE_PRECISION_H_
|
||||||
|
#define _WRITE_PRECISION_H_
|
||||||
|
// Enum WritePrecision defines constants for specifying InfluxDB write prcecision
|
||||||
|
enum class WritePrecision:uint8_t {
|
||||||
|
// Specifyies that points has no timestamp (default). Server will assign timestamp.
|
||||||
|
NoTime = 0,
|
||||||
|
// Seconds
|
||||||
|
S,
|
||||||
|
// Milli-seconds
|
||||||
|
MS,
|
||||||
|
// Micro-seconds
|
||||||
|
US,
|
||||||
|
// Nano-seconds
|
||||||
|
NS
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_WRITE_PRECISION_H_
|
108
firmware/libraries/ESP8266_Influxdb/src/query/CsvReader 2.cpp
Normal file
108
firmware/libraries/ESP8266_Influxdb/src/query/CsvReader 2.cpp
Normal file
|
@ -0,0 +1,108 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* CsvReader.cpp: Simple Csv parser for comma separated values, with double quotes suppport
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "CsvReader.h"
|
||||||
|
|
||||||
|
CsvReader::CsvReader(HttpStreamScanner *scanner) {
|
||||||
|
_scanner = scanner;
|
||||||
|
}
|
||||||
|
|
||||||
|
CsvReader::~CsvReader() {
|
||||||
|
delete _scanner;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<String> CsvReader::getRow() {
|
||||||
|
return _row;
|
||||||
|
};
|
||||||
|
|
||||||
|
void CsvReader::close() {
|
||||||
|
clearRow();
|
||||||
|
_scanner->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CsvReader::clearRow() {
|
||||||
|
std::for_each(_row.begin(), _row.end(), [](String &value){ value = (const char *)nullptr; });
|
||||||
|
_row.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class CsvParsingState {
|
||||||
|
UnquotedField,
|
||||||
|
QuotedField,
|
||||||
|
QuotedQuote
|
||||||
|
};
|
||||||
|
|
||||||
|
bool CsvReader::next() {
|
||||||
|
clearRow();
|
||||||
|
bool status = _scanner->next();
|
||||||
|
if(!status) {
|
||||||
|
_error = _scanner->getError();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String line = _scanner->getLine();
|
||||||
|
CsvParsingState state = CsvParsingState::UnquotedField;
|
||||||
|
std::vector<String> fields {""};
|
||||||
|
size_t i = 0; // index of the current field
|
||||||
|
for (char c : line) {
|
||||||
|
switch (state) {
|
||||||
|
case CsvParsingState::UnquotedField:
|
||||||
|
switch (c) {
|
||||||
|
case ',': // end of field
|
||||||
|
fields.push_back(""); i++;
|
||||||
|
break;
|
||||||
|
case '"': state = CsvParsingState::QuotedField;
|
||||||
|
break;
|
||||||
|
default: fields[i] += c;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case CsvParsingState::QuotedField:
|
||||||
|
switch (c) {
|
||||||
|
case '"': state = CsvParsingState::QuotedQuote;
|
||||||
|
break;
|
||||||
|
default: fields[i] += c;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case CsvParsingState::QuotedQuote:
|
||||||
|
switch (c) {
|
||||||
|
case ',': // , after closing quote
|
||||||
|
fields.push_back(""); i++;
|
||||||
|
state = CsvParsingState::UnquotedField;
|
||||||
|
break;
|
||||||
|
case '"': // "" -> "
|
||||||
|
fields[i] += '"';
|
||||||
|
state = CsvParsingState::QuotedField;
|
||||||
|
break;
|
||||||
|
default: // end of quote
|
||||||
|
state = CsvParsingState::UnquotedField;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_row = fields;
|
||||||
|
return true;
|
||||||
|
}
|
51
firmware/libraries/ESP8266_Influxdb/src/query/CsvReader 2.h
Normal file
51
firmware/libraries/ESP8266_Influxdb/src/query/CsvReader 2.h
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* CsvReader.h: Simple Csv parser for comma separated values, with double quotes suppport
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _CSV_READER_
|
||||||
|
#define _CSV_READER_
|
||||||
|
|
||||||
|
#include "HttpStreamScanner.h"
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CsvReader parses csv line to token by ',' (comma) character.
|
||||||
|
* It suppports escaped quotes, excaped comma
|
||||||
|
**/
|
||||||
|
class CsvReader {
|
||||||
|
public:
|
||||||
|
CsvReader(HttpStreamScanner *scanner);
|
||||||
|
~CsvReader();
|
||||||
|
bool next();
|
||||||
|
void close();
|
||||||
|
std::vector<String> getRow();
|
||||||
|
int getError() const { return _error; };
|
||||||
|
private:
|
||||||
|
void clearRow();
|
||||||
|
HttpStreamScanner *_scanner = nullptr;
|
||||||
|
std::vector<String> _row;
|
||||||
|
int _error = 0;
|
||||||
|
};
|
||||||
|
#endif //_CSV_READER_
|
108
firmware/libraries/ESP8266_Influxdb/src/query/CsvReader.cpp
Normal file
108
firmware/libraries/ESP8266_Influxdb/src/query/CsvReader.cpp
Normal file
|
@ -0,0 +1,108 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* CsvReader.cpp: Simple Csv parser for comma separated values, with double quotes suppport
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "CsvReader.h"
|
||||||
|
|
||||||
|
CsvReader::CsvReader(HttpStreamScanner *scanner) {
|
||||||
|
_scanner = scanner;
|
||||||
|
}
|
||||||
|
|
||||||
|
CsvReader::~CsvReader() {
|
||||||
|
delete _scanner;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<String> CsvReader::getRow() {
|
||||||
|
return _row;
|
||||||
|
};
|
||||||
|
|
||||||
|
void CsvReader::close() {
|
||||||
|
clearRow();
|
||||||
|
_scanner->close();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CsvReader::clearRow() {
|
||||||
|
std::for_each(_row.begin(), _row.end(), [](String &value){ value = (const char *)nullptr; });
|
||||||
|
_row.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class CsvParsingState {
|
||||||
|
UnquotedField,
|
||||||
|
QuotedField,
|
||||||
|
QuotedQuote
|
||||||
|
};
|
||||||
|
|
||||||
|
bool CsvReader::next() {
|
||||||
|
clearRow();
|
||||||
|
bool status = _scanner->next();
|
||||||
|
if(!status) {
|
||||||
|
_error = _scanner->getError();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String line = _scanner->getLine();
|
||||||
|
CsvParsingState state = CsvParsingState::UnquotedField;
|
||||||
|
std::vector<String> fields {""};
|
||||||
|
size_t i = 0; // index of the current field
|
||||||
|
for (char c : line) {
|
||||||
|
switch (state) {
|
||||||
|
case CsvParsingState::UnquotedField:
|
||||||
|
switch (c) {
|
||||||
|
case ',': // end of field
|
||||||
|
fields.push_back(""); i++;
|
||||||
|
break;
|
||||||
|
case '"': state = CsvParsingState::QuotedField;
|
||||||
|
break;
|
||||||
|
default: fields[i] += c;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case CsvParsingState::QuotedField:
|
||||||
|
switch (c) {
|
||||||
|
case '"': state = CsvParsingState::QuotedQuote;
|
||||||
|
break;
|
||||||
|
default: fields[i] += c;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case CsvParsingState::QuotedQuote:
|
||||||
|
switch (c) {
|
||||||
|
case ',': // , after closing quote
|
||||||
|
fields.push_back(""); i++;
|
||||||
|
state = CsvParsingState::UnquotedField;
|
||||||
|
break;
|
||||||
|
case '"': // "" -> "
|
||||||
|
fields[i] += '"';
|
||||||
|
state = CsvParsingState::QuotedField;
|
||||||
|
break;
|
||||||
|
default: // end of quote
|
||||||
|
state = CsvParsingState::UnquotedField;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_row = fields;
|
||||||
|
return true;
|
||||||
|
}
|
51
firmware/libraries/ESP8266_Influxdb/src/query/CsvReader.h
Normal file
51
firmware/libraries/ESP8266_Influxdb/src/query/CsvReader.h
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* CsvReader.h: Simple Csv parser for comma separated values, with double quotes suppport
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _CSV_READER_
|
||||||
|
#define _CSV_READER_
|
||||||
|
|
||||||
|
#include "HttpStreamScanner.h"
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CsvReader parses csv line to token by ',' (comma) character.
|
||||||
|
* It suppports escaped quotes, excaped comma
|
||||||
|
**/
|
||||||
|
class CsvReader {
|
||||||
|
public:
|
||||||
|
CsvReader(HttpStreamScanner *scanner);
|
||||||
|
~CsvReader();
|
||||||
|
bool next();
|
||||||
|
void close();
|
||||||
|
std::vector<String> getRow();
|
||||||
|
int getError() const { return _error; };
|
||||||
|
private:
|
||||||
|
void clearRow();
|
||||||
|
HttpStreamScanner *_scanner = nullptr;
|
||||||
|
std::vector<String> _row;
|
||||||
|
int _error = 0;
|
||||||
|
};
|
||||||
|
#endif //_CSV_READER_
|
275
firmware/libraries/ESP8266_Influxdb/src/query/FluxParser 2.cpp
Normal file
275
firmware/libraries/ESP8266_Influxdb/src/query/FluxParser 2.cpp
Normal file
|
@ -0,0 +1,275 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* FluxParser.cpp: InfluxDB flux query result parser
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "FluxParser.h"
|
||||||
|
// Uncomment bellow in case of a problem and rebuild sketch
|
||||||
|
//#define INFLUXDB_CLIENT_DEBUG_ENABLE
|
||||||
|
#include "util/debug.h"
|
||||||
|
|
||||||
|
FluxQueryResult::FluxQueryResult(CsvReader *reader) {
|
||||||
|
_data = std::make_shared<Data>(reader);
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult::FluxQueryResult(const String &error):FluxQueryResult((CsvReader *)nullptr) {
|
||||||
|
_data->_error = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult::FluxQueryResult(const FluxQueryResult &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
FluxQueryResult &FluxQueryResult::operator=(const FluxQueryResult &other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult::~FluxQueryResult() {
|
||||||
|
}
|
||||||
|
|
||||||
|
int FluxQueryResult::getColumnIndex(const String &columnName) {
|
||||||
|
int i = -1;
|
||||||
|
std::vector<String>::iterator it = find(_data->_columnNames.begin(), _data->_columnNames.end(), columnName);
|
||||||
|
if (it != _data->_columnNames.end()) {
|
||||||
|
i = distance(_data->_columnNames.begin(), it);
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxValue FluxQueryResult::getValueByIndex(int index) {
|
||||||
|
FluxValue ret;
|
||||||
|
if(index >= 0 && index < (int)_data->_columnValues.size()) {
|
||||||
|
ret = _data->_columnValues[index];
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxValue FluxQueryResult::getValueByName(const String &columnName) {
|
||||||
|
FluxValue ret;
|
||||||
|
int i = getColumnIndex(columnName);
|
||||||
|
if(i > -1) {
|
||||||
|
ret = getValueByIndex(i);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FluxQueryResult::close() {
|
||||||
|
clearValues();
|
||||||
|
clearColumns();
|
||||||
|
if(_data->_reader) {
|
||||||
|
_data->_reader->close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void FluxQueryResult::clearValues() {
|
||||||
|
std::for_each(_data->_columnValues.begin(), _data->_columnValues.end(), [](FluxValue &value){ value = nullptr; });
|
||||||
|
_data->_columnValues.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void FluxQueryResult::clearColumns() {
|
||||||
|
std::for_each(_data->_columnNames.begin(), _data->_columnNames.end(), [](String &value){ value = (const char *)nullptr; });
|
||||||
|
_data->_columnNames.clear();
|
||||||
|
|
||||||
|
std::for_each(_data->_columnDatatypes.begin(), _data->_columnDatatypes.end(), [](String &value){ value = (const char *)nullptr; });
|
||||||
|
_data->_columnDatatypes.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult::Data::Data(CsvReader *reader):_reader(reader) {}
|
||||||
|
|
||||||
|
FluxQueryResult::Data::~Data() {
|
||||||
|
delete _reader;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ParsingState {
|
||||||
|
ParsingStateNormal = 0,
|
||||||
|
ParsingStateNameRow,
|
||||||
|
ParsingStateError
|
||||||
|
};
|
||||||
|
|
||||||
|
bool FluxQueryResult::next() {
|
||||||
|
if(!_data->_reader) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
ParsingState parsingState = ParsingStateNormal;
|
||||||
|
_data->_tableChanged = false;
|
||||||
|
clearValues();
|
||||||
|
_data->_error = "";
|
||||||
|
readRow:
|
||||||
|
bool stat = _data->_reader->next();
|
||||||
|
if(!stat) {
|
||||||
|
if(_data->_reader->getError()< 0) {
|
||||||
|
_data->_error = HTTPClient::errorToString(_data->_reader->getError());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
std::vector<String> vals = _data->_reader->getRow();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] FluxQueryResult: vals.size %d\n", vals.size());
|
||||||
|
if(vals.size() < 2) {
|
||||||
|
goto readRow;
|
||||||
|
}
|
||||||
|
if(vals[0] == "") {
|
||||||
|
if (parsingState == ParsingStateError) {
|
||||||
|
String message ;
|
||||||
|
if (vals.size() > 1 && vals[1].length() > 0) {
|
||||||
|
message = vals[1];
|
||||||
|
} else {
|
||||||
|
message = F("Unknown query error");
|
||||||
|
}
|
||||||
|
String reference = "";
|
||||||
|
if (vals.size() > 2 && vals[2].length() > 0) {
|
||||||
|
reference = "," + vals[2];
|
||||||
|
}
|
||||||
|
_data->_error = message + reference;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
} else if (parsingState == ParsingStateNameRow) {
|
||||||
|
if (vals[1] == "error") {
|
||||||
|
parsingState = ParsingStateError;
|
||||||
|
} else {
|
||||||
|
if (vals.size()-1 != _data->_columnDatatypes.size()) {
|
||||||
|
_data->_error = String(F("Parsing error, header has different number of columns than table: ")) + String(vals.size()-1) + " vs " + String(_data->_columnDatatypes.size());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
for(unsigned int i=1;i < vals.size(); i++) {
|
||||||
|
_data->_columnNames.push_back(vals[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parsingState = ParsingStateNormal;
|
||||||
|
}
|
||||||
|
goto readRow;
|
||||||
|
}
|
||||||
|
if(_data->_columnDatatypes.size() == 0) {
|
||||||
|
_data->_error = F("Parsing error, datatype annotation not found");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (vals.size()-1 != _data->_columnNames.size()) {
|
||||||
|
_data->_error = String(F("Parsing error, row has different number of columns than table: ")) + String(vals.size()-1) + " vs " + String(_data->_columnNames.size());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for(unsigned int i=1;i < vals.size(); i++) {
|
||||||
|
FluxBase *v = nullptr;
|
||||||
|
if(vals[i].length() > 0) {
|
||||||
|
v = convertValue(vals[i], _data->_columnDatatypes[i-1]);
|
||||||
|
if(!v) {
|
||||||
|
_data->_error = String(F("Unsupported datatype: ")) + _data->_columnDatatypes[i-1];
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FluxValue val(v);
|
||||||
|
_data->_columnValues.push_back(val);
|
||||||
|
}
|
||||||
|
} else if(vals[0] == "#datatype") {
|
||||||
|
_data->_tablePosition++;
|
||||||
|
clearColumns();
|
||||||
|
_data->_tableChanged = true;
|
||||||
|
for(unsigned int i=1;i < vals.size(); i++) {
|
||||||
|
_data->_columnDatatypes.push_back(vals[i]);
|
||||||
|
}
|
||||||
|
parsingState = ParsingStateNameRow;
|
||||||
|
goto readRow;
|
||||||
|
} else {
|
||||||
|
goto readRow;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxDateTime *FluxQueryResult::convertRfc3339(String &value, const char *type) {
|
||||||
|
tm t = {0,0,0,0,0,0,0,0,0};
|
||||||
|
// has the time part
|
||||||
|
int zet = value.indexOf('Z');
|
||||||
|
unsigned long fracts = 0;
|
||||||
|
if(value.indexOf('T') > 0 && zet > 0) { //Full datetime string - 2020-05-22T11:25:22.037735433Z
|
||||||
|
int f = sscanf(value.c_str(),"%d-%d-%dT%d:%d:%d", &t.tm_year,&t.tm_mon,&t.tm_mday, &t.tm_hour,&t.tm_min,&t.tm_sec);
|
||||||
|
if(f != 6) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
t.tm_year -= 1900; //adjust to years after 1900
|
||||||
|
t.tm_mon -= 1; //adjust to range 0-11
|
||||||
|
int dot = value.indexOf('.');
|
||||||
|
|
||||||
|
if(dot > 0) {
|
||||||
|
int tail = zet;
|
||||||
|
int len = zet-dot-1;
|
||||||
|
if (len > 6) {
|
||||||
|
tail = dot + 7;
|
||||||
|
len = 6;
|
||||||
|
}
|
||||||
|
String secParts = value.substring(dot+1, tail);
|
||||||
|
fracts = strtoul((const char *) secParts.c_str(), NULL, 10);
|
||||||
|
if(len < 6) {
|
||||||
|
fracts *= 10^(6-len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
int f = sscanf(value.c_str(),"%d-%d-%d", &t.tm_year,&t.tm_mon,&t.tm_mday);
|
||||||
|
if(f != 3) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
t.tm_year -= 1900; //adjust to years after 1900
|
||||||
|
t.tm_mon -= 1; //adjust to range 0-11
|
||||||
|
}
|
||||||
|
return new FluxDateTime(value, type, t, fracts);
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxBase *FluxQueryResult::convertValue(String &value, String &dataType) {
|
||||||
|
FluxBase *ret = nullptr;
|
||||||
|
if(dataType.equals(FluxDatatypeDatetimeRFC3339) || dataType.equals(FluxDatatypeDatetimeRFC3339Nano)) {
|
||||||
|
const char *type = FluxDatatypeDatetimeRFC3339;
|
||||||
|
if(dataType.equals(FluxDatatypeDatetimeRFC3339Nano)) {
|
||||||
|
type = FluxDatatypeDatetimeRFC3339Nano;
|
||||||
|
}
|
||||||
|
ret = convertRfc3339(value, type);
|
||||||
|
if (!ret) {
|
||||||
|
_data->_error = String(F("Invalid value for '")) + dataType + F("': ") + value;
|
||||||
|
}
|
||||||
|
} else if(dataType.equals(FluxDatatypeDouble)) {
|
||||||
|
double val = strtod((const char *) value.c_str(), NULL);
|
||||||
|
ret = new FluxDouble(value, val);
|
||||||
|
} else if(dataType.equals(FluxDatatypeBool)) {
|
||||||
|
bool val = value.equalsIgnoreCase("true");
|
||||||
|
ret = new FluxBool(value, val);
|
||||||
|
} else if(dataType.equals(FluxDatatypeLong)) {
|
||||||
|
long l = strtol((const char *) value.c_str(), NULL, 10);
|
||||||
|
ret = new FluxLong(value, l);
|
||||||
|
} else if(dataType.equals(FluxDatatypeUnsignedLong)) {
|
||||||
|
unsigned long ul = strtoul((const char *) value.c_str(), NULL, 10);
|
||||||
|
ret = new FluxUnsignedLong(value, ul);
|
||||||
|
} else if(dataType.equals(FluxBinaryDataTypeBase64)) {
|
||||||
|
ret = new FluxString(value, FluxBinaryDataTypeBase64);
|
||||||
|
} else if(dataType.equals(FluxDatatypeDuration)) {
|
||||||
|
ret = new FluxString(value, FluxDatatypeDuration);
|
||||||
|
} else if(dataType.equals(FluxDatatypeString)) {
|
||||||
|
ret = new FluxString(value, FluxDatatypeString);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
109
firmware/libraries/ESP8266_Influxdb/src/query/FluxParser 2.h
Normal file
109
firmware/libraries/ESP8266_Influxdb/src/query/FluxParser 2.h
Normal file
|
@ -0,0 +1,109 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* FLuxParser.h: InfluxDB flux query result parser
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _FLUX_PARSER_H_
|
||||||
|
#define _FLUX_PARSER_H_
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "CsvReader.h"
|
||||||
|
#include "FluxTypes.h"
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FluxQueryResult represents result from InfluxDB flux query.
|
||||||
|
* It parses stream from server, line by line, so it allows to read a huge responses.
|
||||||
|
*
|
||||||
|
* Browsing thought the result is done by repeatedly calling the next() method, until it returns false.
|
||||||
|
* Unsuccesful reading is distinqushed by non empty value from getError().
|
||||||
|
*
|
||||||
|
* As a flux query result can contain several tables differing by grouping key, use hasTableChanged() to
|
||||||
|
* know when there is a new table.
|
||||||
|
*
|
||||||
|
* Single values are returned using getValueByIndex() or getValueByName() methods.
|
||||||
|
* All row values are retreived by getValues().
|
||||||
|
*
|
||||||
|
* Always call close() at the of reading.
|
||||||
|
*
|
||||||
|
* FluxQueryResult supports passing by value.
|
||||||
|
*/
|
||||||
|
class FluxQueryResult {
|
||||||
|
public:
|
||||||
|
// Constructor for reading result
|
||||||
|
FluxQueryResult(CsvReader *reader);
|
||||||
|
// Constructor for error result
|
||||||
|
FluxQueryResult(const String &error);
|
||||||
|
// Copy constructor
|
||||||
|
FluxQueryResult(const FluxQueryResult &other);
|
||||||
|
// Assignment operator
|
||||||
|
FluxQueryResult &operator=(const FluxQueryResult &other);
|
||||||
|
// Advances to next values row in the result set.
|
||||||
|
// Returns true on successful reading new row, false means end of the result set
|
||||||
|
// or an error. Call getError() and check non empty value
|
||||||
|
bool next();
|
||||||
|
// Returns index of the column, or -1 if not found
|
||||||
|
int getColumnIndex(const String &columnName);
|
||||||
|
// Returns a converted value by index, or nullptr in case of missing value or wrong index
|
||||||
|
FluxValue getValueByIndex(int index);
|
||||||
|
// Returns a result value by column name, or nullptr in case of missing value or wrong column name
|
||||||
|
FluxValue getValueByName(const String &columnName);
|
||||||
|
// Returns flux datatypes of all columns
|
||||||
|
std::vector<String> getColumnsDatatype() { return _data->_columnDatatypes; }
|
||||||
|
// Returns names of all columns
|
||||||
|
std::vector<String> getColumnsName() { return _data->_columnNames; }
|
||||||
|
// Returns all values from current row
|
||||||
|
std::vector<FluxValue> getValues() { return _data->_columnValues; }
|
||||||
|
// Returns true if new table was encountered
|
||||||
|
bool hasTableChanged() const { return _data->_tableChanged; }
|
||||||
|
// Returns current table position in the results set
|
||||||
|
int getTablePosition() const { return _data->_tablePosition; }
|
||||||
|
// Returns an error found during parsing if any, othewise empty string
|
||||||
|
String getError() { return _data->_error; }
|
||||||
|
// Releases all resources and closes server reponse. It must be always called at end of reading.
|
||||||
|
void close();
|
||||||
|
// Descructor
|
||||||
|
~FluxQueryResult();
|
||||||
|
protected:
|
||||||
|
FluxBase *convertValue(String &value, String &dataType);
|
||||||
|
static FluxDateTime *convertRfc3339(String &value, const char *type);
|
||||||
|
void clearValues();
|
||||||
|
void clearColumns();
|
||||||
|
private:
|
||||||
|
class Data {
|
||||||
|
public:
|
||||||
|
Data(CsvReader *reader);
|
||||||
|
~Data();
|
||||||
|
CsvReader *_reader;
|
||||||
|
int _tablePosition = -1;
|
||||||
|
bool _tableChanged = false;
|
||||||
|
std::vector<String> _columnDatatypes;
|
||||||
|
std::vector<String> _columnNames;
|
||||||
|
std::vector<FluxValue> _columnValues;
|
||||||
|
String _error;
|
||||||
|
};
|
||||||
|
std::shared_ptr<Data> _data;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //#_FLUX_PARSER_H_
|
275
firmware/libraries/ESP8266_Influxdb/src/query/FluxParser.cpp
Normal file
275
firmware/libraries/ESP8266_Influxdb/src/query/FluxParser.cpp
Normal file
|
@ -0,0 +1,275 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* FluxParser.cpp: InfluxDB flux query result parser
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "FluxParser.h"
|
||||||
|
// Uncomment bellow in case of a problem and rebuild sketch
|
||||||
|
//#define INFLUXDB_CLIENT_DEBUG_ENABLE
|
||||||
|
#include "util/debug.h"
|
||||||
|
|
||||||
|
FluxQueryResult::FluxQueryResult(CsvReader *reader) {
|
||||||
|
_data = std::make_shared<Data>(reader);
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult::FluxQueryResult(const String &error):FluxQueryResult((CsvReader *)nullptr) {
|
||||||
|
_data->_error = error;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult::FluxQueryResult(const FluxQueryResult &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
FluxQueryResult &FluxQueryResult::operator=(const FluxQueryResult &other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult::~FluxQueryResult() {
|
||||||
|
}
|
||||||
|
|
||||||
|
int FluxQueryResult::getColumnIndex(const String &columnName) {
|
||||||
|
int i = -1;
|
||||||
|
std::vector<String>::iterator it = find(_data->_columnNames.begin(), _data->_columnNames.end(), columnName);
|
||||||
|
if (it != _data->_columnNames.end()) {
|
||||||
|
i = distance(_data->_columnNames.begin(), it);
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxValue FluxQueryResult::getValueByIndex(int index) {
|
||||||
|
FluxValue ret;
|
||||||
|
if(index >= 0 && index < (int)_data->_columnValues.size()) {
|
||||||
|
ret = _data->_columnValues[index];
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxValue FluxQueryResult::getValueByName(const String &columnName) {
|
||||||
|
FluxValue ret;
|
||||||
|
int i = getColumnIndex(columnName);
|
||||||
|
if(i > -1) {
|
||||||
|
ret = getValueByIndex(i);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FluxQueryResult::close() {
|
||||||
|
clearValues();
|
||||||
|
clearColumns();
|
||||||
|
if(_data->_reader) {
|
||||||
|
_data->_reader->close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void FluxQueryResult::clearValues() {
|
||||||
|
std::for_each(_data->_columnValues.begin(), _data->_columnValues.end(), [](FluxValue &value){ value = nullptr; });
|
||||||
|
_data->_columnValues.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
void FluxQueryResult::clearColumns() {
|
||||||
|
std::for_each(_data->_columnNames.begin(), _data->_columnNames.end(), [](String &value){ value = (const char *)nullptr; });
|
||||||
|
_data->_columnNames.clear();
|
||||||
|
|
||||||
|
std::for_each(_data->_columnDatatypes.begin(), _data->_columnDatatypes.end(), [](String &value){ value = (const char *)nullptr; });
|
||||||
|
_data->_columnDatatypes.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxQueryResult::Data::Data(CsvReader *reader):_reader(reader) {}
|
||||||
|
|
||||||
|
FluxQueryResult::Data::~Data() {
|
||||||
|
delete _reader;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum ParsingState {
|
||||||
|
ParsingStateNormal = 0,
|
||||||
|
ParsingStateNameRow,
|
||||||
|
ParsingStateError
|
||||||
|
};
|
||||||
|
|
||||||
|
bool FluxQueryResult::next() {
|
||||||
|
if(!_data->_reader) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
ParsingState parsingState = ParsingStateNormal;
|
||||||
|
_data->_tableChanged = false;
|
||||||
|
clearValues();
|
||||||
|
_data->_error = "";
|
||||||
|
readRow:
|
||||||
|
bool stat = _data->_reader->next();
|
||||||
|
if(!stat) {
|
||||||
|
if(_data->_reader->getError()< 0) {
|
||||||
|
_data->_error = HTTPClient::errorToString(_data->_reader->getError());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
std::vector<String> vals = _data->_reader->getRow();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] FluxQueryResult: vals.size %d\n", vals.size());
|
||||||
|
if(vals.size() < 2) {
|
||||||
|
goto readRow;
|
||||||
|
}
|
||||||
|
if(vals[0] == "") {
|
||||||
|
if (parsingState == ParsingStateError) {
|
||||||
|
String message ;
|
||||||
|
if (vals.size() > 1 && vals[1].length() > 0) {
|
||||||
|
message = vals[1];
|
||||||
|
} else {
|
||||||
|
message = F("Unknown query error");
|
||||||
|
}
|
||||||
|
String reference = "";
|
||||||
|
if (vals.size() > 2 && vals[2].length() > 0) {
|
||||||
|
reference = "," + vals[2];
|
||||||
|
}
|
||||||
|
_data->_error = message + reference;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
} else if (parsingState == ParsingStateNameRow) {
|
||||||
|
if (vals[1] == "error") {
|
||||||
|
parsingState = ParsingStateError;
|
||||||
|
} else {
|
||||||
|
if (vals.size()-1 != _data->_columnDatatypes.size()) {
|
||||||
|
_data->_error = String(F("Parsing error, header has different number of columns than table: ")) + String(vals.size()-1) + " vs " + String(_data->_columnDatatypes.size());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
for(unsigned int i=1;i < vals.size(); i++) {
|
||||||
|
_data->_columnNames.push_back(vals[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parsingState = ParsingStateNormal;
|
||||||
|
}
|
||||||
|
goto readRow;
|
||||||
|
}
|
||||||
|
if(_data->_columnDatatypes.size() == 0) {
|
||||||
|
_data->_error = F("Parsing error, datatype annotation not found");
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (vals.size()-1 != _data->_columnNames.size()) {
|
||||||
|
_data->_error = String(F("Parsing error, row has different number of columns than table: ")) + String(vals.size()-1) + " vs " + String(_data->_columnNames.size());
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for(unsigned int i=1;i < vals.size(); i++) {
|
||||||
|
FluxBase *v = nullptr;
|
||||||
|
if(vals[i].length() > 0) {
|
||||||
|
v = convertValue(vals[i], _data->_columnDatatypes[i-1]);
|
||||||
|
if(!v) {
|
||||||
|
_data->_error = String(F("Unsupported datatype: ")) + _data->_columnDatatypes[i-1];
|
||||||
|
INFLUXDB_CLIENT_DEBUG("Error '%s'\n", _data->_error.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FluxValue val(v);
|
||||||
|
_data->_columnValues.push_back(val);
|
||||||
|
}
|
||||||
|
} else if(vals[0] == "#datatype") {
|
||||||
|
_data->_tablePosition++;
|
||||||
|
clearColumns();
|
||||||
|
_data->_tableChanged = true;
|
||||||
|
for(unsigned int i=1;i < vals.size(); i++) {
|
||||||
|
_data->_columnDatatypes.push_back(vals[i]);
|
||||||
|
}
|
||||||
|
parsingState = ParsingStateNameRow;
|
||||||
|
goto readRow;
|
||||||
|
} else {
|
||||||
|
goto readRow;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxDateTime *FluxQueryResult::convertRfc3339(String &value, const char *type) {
|
||||||
|
tm t = {0,0,0,0,0,0,0,0,0};
|
||||||
|
// has the time part
|
||||||
|
int zet = value.indexOf('Z');
|
||||||
|
unsigned long fracts = 0;
|
||||||
|
if(value.indexOf('T') > 0 && zet > 0) { //Full datetime string - 2020-05-22T11:25:22.037735433Z
|
||||||
|
int f = sscanf(value.c_str(),"%d-%d-%dT%d:%d:%d", &t.tm_year,&t.tm_mon,&t.tm_mday, &t.tm_hour,&t.tm_min,&t.tm_sec);
|
||||||
|
if(f != 6) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
t.tm_year -= 1900; //adjust to years after 1900
|
||||||
|
t.tm_mon -= 1; //adjust to range 0-11
|
||||||
|
int dot = value.indexOf('.');
|
||||||
|
|
||||||
|
if(dot > 0) {
|
||||||
|
int tail = zet;
|
||||||
|
int len = zet-dot-1;
|
||||||
|
if (len > 6) {
|
||||||
|
tail = dot + 7;
|
||||||
|
len = 6;
|
||||||
|
}
|
||||||
|
String secParts = value.substring(dot+1, tail);
|
||||||
|
fracts = strtoul((const char *) secParts.c_str(), NULL, 10);
|
||||||
|
if(len < 6) {
|
||||||
|
fracts *= 10^(6-len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
int f = sscanf(value.c_str(),"%d-%d-%d", &t.tm_year,&t.tm_mon,&t.tm_mday);
|
||||||
|
if(f != 3) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
t.tm_year -= 1900; //adjust to years after 1900
|
||||||
|
t.tm_mon -= 1; //adjust to range 0-11
|
||||||
|
}
|
||||||
|
return new FluxDateTime(value, type, t, fracts);
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxBase *FluxQueryResult::convertValue(String &value, String &dataType) {
|
||||||
|
FluxBase *ret = nullptr;
|
||||||
|
if(dataType.equals(FluxDatatypeDatetimeRFC3339) || dataType.equals(FluxDatatypeDatetimeRFC3339Nano)) {
|
||||||
|
const char *type = FluxDatatypeDatetimeRFC3339;
|
||||||
|
if(dataType.equals(FluxDatatypeDatetimeRFC3339Nano)) {
|
||||||
|
type = FluxDatatypeDatetimeRFC3339Nano;
|
||||||
|
}
|
||||||
|
ret = convertRfc3339(value, type);
|
||||||
|
if (!ret) {
|
||||||
|
_data->_error = String(F("Invalid value for '")) + dataType + F("': ") + value;
|
||||||
|
}
|
||||||
|
} else if(dataType.equals(FluxDatatypeDouble)) {
|
||||||
|
double val = strtod((const char *) value.c_str(), NULL);
|
||||||
|
ret = new FluxDouble(value, val);
|
||||||
|
} else if(dataType.equals(FluxDatatypeBool)) {
|
||||||
|
bool val = value.equalsIgnoreCase("true");
|
||||||
|
ret = new FluxBool(value, val);
|
||||||
|
} else if(dataType.equals(FluxDatatypeLong)) {
|
||||||
|
long l = strtol((const char *) value.c_str(), NULL, 10);
|
||||||
|
ret = new FluxLong(value, l);
|
||||||
|
} else if(dataType.equals(FluxDatatypeUnsignedLong)) {
|
||||||
|
unsigned long ul = strtoul((const char *) value.c_str(), NULL, 10);
|
||||||
|
ret = new FluxUnsignedLong(value, ul);
|
||||||
|
} else if(dataType.equals(FluxBinaryDataTypeBase64)) {
|
||||||
|
ret = new FluxString(value, FluxBinaryDataTypeBase64);
|
||||||
|
} else if(dataType.equals(FluxDatatypeDuration)) {
|
||||||
|
ret = new FluxString(value, FluxDatatypeDuration);
|
||||||
|
} else if(dataType.equals(FluxDatatypeString)) {
|
||||||
|
ret = new FluxString(value, FluxDatatypeString);
|
||||||
|
}
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
109
firmware/libraries/ESP8266_Influxdb/src/query/FluxParser.h
Normal file
109
firmware/libraries/ESP8266_Influxdb/src/query/FluxParser.h
Normal file
|
@ -0,0 +1,109 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* FLuxParser.h: InfluxDB flux query result parser
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _FLUX_PARSER_H_
|
||||||
|
#define _FLUX_PARSER_H_
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "CsvReader.h"
|
||||||
|
#include "FluxTypes.h"
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FluxQueryResult represents result from InfluxDB flux query.
|
||||||
|
* It parses stream from server, line by line, so it allows to read a huge responses.
|
||||||
|
*
|
||||||
|
* Browsing thought the result is done by repeatedly calling the next() method, until it returns false.
|
||||||
|
* Unsuccesful reading is distinqushed by non empty value from getError().
|
||||||
|
*
|
||||||
|
* As a flux query result can contain several tables differing by grouping key, use hasTableChanged() to
|
||||||
|
* know when there is a new table.
|
||||||
|
*
|
||||||
|
* Single values are returned using getValueByIndex() or getValueByName() methods.
|
||||||
|
* All row values are retreived by getValues().
|
||||||
|
*
|
||||||
|
* Always call close() at the of reading.
|
||||||
|
*
|
||||||
|
* FluxQueryResult supports passing by value.
|
||||||
|
*/
|
||||||
|
class FluxQueryResult {
|
||||||
|
public:
|
||||||
|
// Constructor for reading result
|
||||||
|
FluxQueryResult(CsvReader *reader);
|
||||||
|
// Constructor for error result
|
||||||
|
FluxQueryResult(const String &error);
|
||||||
|
// Copy constructor
|
||||||
|
FluxQueryResult(const FluxQueryResult &other);
|
||||||
|
// Assignment operator
|
||||||
|
FluxQueryResult &operator=(const FluxQueryResult &other);
|
||||||
|
// Advances to next values row in the result set.
|
||||||
|
// Returns true on successful reading new row, false means end of the result set
|
||||||
|
// or an error. Call getError() and check non empty value
|
||||||
|
bool next();
|
||||||
|
// Returns index of the column, or -1 if not found
|
||||||
|
int getColumnIndex(const String &columnName);
|
||||||
|
// Returns a converted value by index, or nullptr in case of missing value or wrong index
|
||||||
|
FluxValue getValueByIndex(int index);
|
||||||
|
// Returns a result value by column name, or nullptr in case of missing value or wrong column name
|
||||||
|
FluxValue getValueByName(const String &columnName);
|
||||||
|
// Returns flux datatypes of all columns
|
||||||
|
std::vector<String> getColumnsDatatype() { return _data->_columnDatatypes; }
|
||||||
|
// Returns names of all columns
|
||||||
|
std::vector<String> getColumnsName() { return _data->_columnNames; }
|
||||||
|
// Returns all values from current row
|
||||||
|
std::vector<FluxValue> getValues() { return _data->_columnValues; }
|
||||||
|
// Returns true if new table was encountered
|
||||||
|
bool hasTableChanged() const { return _data->_tableChanged; }
|
||||||
|
// Returns current table position in the results set
|
||||||
|
int getTablePosition() const { return _data->_tablePosition; }
|
||||||
|
// Returns an error found during parsing if any, othewise empty string
|
||||||
|
String getError() { return _data->_error; }
|
||||||
|
// Releases all resources and closes server reponse. It must be always called at end of reading.
|
||||||
|
void close();
|
||||||
|
// Descructor
|
||||||
|
~FluxQueryResult();
|
||||||
|
protected:
|
||||||
|
FluxBase *convertValue(String &value, String &dataType);
|
||||||
|
static FluxDateTime *convertRfc3339(String &value, const char *type);
|
||||||
|
void clearValues();
|
||||||
|
void clearColumns();
|
||||||
|
private:
|
||||||
|
class Data {
|
||||||
|
public:
|
||||||
|
Data(CsvReader *reader);
|
||||||
|
~Data();
|
||||||
|
CsvReader *_reader;
|
||||||
|
int _tablePosition = -1;
|
||||||
|
bool _tableChanged = false;
|
||||||
|
std::vector<String> _columnDatatypes;
|
||||||
|
std::vector<String> _columnNames;
|
||||||
|
std::vector<FluxValue> _columnValues;
|
||||||
|
String _error;
|
||||||
|
};
|
||||||
|
std::shared_ptr<Data> _data;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //#_FLUX_PARSER_H_
|
239
firmware/libraries/ESP8266_Influxdb/src/query/FluxTypes 2.cpp
Normal file
239
firmware/libraries/ESP8266_Influxdb/src/query/FluxTypes 2.cpp
Normal file
|
@ -0,0 +1,239 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* FluxTypes.cpp: InfluxDB flux query types support
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "FluxTypes.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
const char *FluxDatatypeString = "string";
|
||||||
|
const char *FluxDatatypeDouble = "double";
|
||||||
|
const char *FluxDatatypeBool = "boolean";
|
||||||
|
const char *FluxDatatypeLong = "long";
|
||||||
|
const char *FluxDatatypeUnsignedLong = "unsignedLong";
|
||||||
|
const char *FluxDatatypeDuration = "duration";
|
||||||
|
const char *FluxBinaryDataTypeBase64 = "base64Binary";
|
||||||
|
const char *FluxDatatypeDatetimeRFC3339 = "dateTime:RFC3339";
|
||||||
|
const char *FluxDatatypeDatetimeRFC3339Nano = "dateTime:RFC3339Nano";
|
||||||
|
|
||||||
|
FluxBase::FluxBase(const String &rawValue):_rawValue(rawValue) {
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxBase::~FluxBase() {
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FluxLong::FluxLong(const String &rawValue, long value):FluxBase(rawValue),value(value) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxLong::getType() {
|
||||||
|
return FluxDatatypeLong;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxLong::jsonString() {
|
||||||
|
int len =_rawValue.length()+3+getNumLength(value)+2;
|
||||||
|
char *json = new char[len+1];
|
||||||
|
snprintf_P(json, len, PSTR("\"%s\":%ld"), _rawValue.c_str(), value);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FluxUnsignedLong::FluxUnsignedLong(const String &rawValue, unsigned long value):FluxBase(rawValue),value(value) {
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxUnsignedLong::getType() {
|
||||||
|
return FluxDatatypeUnsignedLong;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxUnsignedLong::jsonString() {
|
||||||
|
int len =_rawValue.length()+3+getNumLength(value)+2;
|
||||||
|
char *json = new char[len+1];
|
||||||
|
snprintf_P(json,len, PSTR("\"%s\":%lu"), _rawValue.c_str(), value);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxDouble::FluxDouble(const String &rawValue, double value):FluxDouble(rawValue, value, 0) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxDouble::FluxDouble(const String &rawValue, double value, int precision):FluxBase(rawValue),
|
||||||
|
value(value),precision(precision) {}
|
||||||
|
|
||||||
|
const char *FluxDouble::getType() {
|
||||||
|
return FluxDatatypeDouble;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxDouble::jsonString() {
|
||||||
|
int len = _rawValue.length()+3+getNumLength(value)+precision+2;
|
||||||
|
char *json = new char[len+1];
|
||||||
|
char format[10];
|
||||||
|
sprintf_P(format, PSTR("\"%%s\":%%.%df"), precision);
|
||||||
|
snprintf(json, len, format , _rawValue.c_str(), value);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxBool::FluxBool(const String &rawValue, bool value):FluxBase(rawValue),value(value) {
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxBool::getType() {
|
||||||
|
return FluxDatatypeBool;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxBool::jsonString() {
|
||||||
|
int len = _rawValue.length()+9;
|
||||||
|
char *json = new char[len+1];
|
||||||
|
snprintf_P(json, len, PSTR("\"%s\":%s"), _rawValue.c_str(), bool2string(value));
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FluxDateTime::FluxDateTime(const String &rawValue, const char *type, struct tm value, unsigned long microseconds):FluxBase(rawValue),_type(type),value(value), microseconds(microseconds) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxDateTime::getType() {
|
||||||
|
return _type;
|
||||||
|
}
|
||||||
|
|
||||||
|
String FluxDateTime::format(const String &formatString) {
|
||||||
|
int len = formatString.length() + 20; //+20 for safety
|
||||||
|
char *buff = new char[len];
|
||||||
|
strftime(buff,len, formatString.c_str(),&value);
|
||||||
|
String str = buff;
|
||||||
|
delete [] buff;
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxDateTime::jsonString() {
|
||||||
|
int len = _rawValue.length()+3+21+(microseconds?10:0);
|
||||||
|
char *buff = new char[len+1];
|
||||||
|
snprintf_P(buff, len, PSTR("\"%s\":\""), _rawValue.c_str());
|
||||||
|
strftime(buff+strlen(buff), len-strlen(buff), "%FT%T",&value);
|
||||||
|
if(microseconds) {
|
||||||
|
snprintf_P(buff+strlen(buff), len - strlen(buff), PSTR(".%06luZ"), microseconds);
|
||||||
|
}
|
||||||
|
strcat(buff+strlen(buff), "\"");
|
||||||
|
return buff;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxString::FluxString(const String &rawValue, const char *type):FluxString(rawValue, rawValue, type) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxString::FluxString(const String &rawValue, const String &value, const char *type):FluxBase(rawValue),_type(type),value(value)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxString::getType() {
|
||||||
|
return _type;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxString::jsonString() {
|
||||||
|
int len = _rawValue.length()+value.length()+7;
|
||||||
|
char *buff = new char[len+1];
|
||||||
|
snprintf(buff, len, "\"%s\":\"%s\"", _rawValue.c_str(), value.c_str());
|
||||||
|
return buff;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FluxValue::FluxValue() {}
|
||||||
|
|
||||||
|
FluxValue::FluxValue(FluxBase *fluxValue):_data(fluxValue) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxValue::FluxValue(const FluxValue &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxValue& FluxValue::operator=(const FluxValue& other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type accessor. If value is different type zero value for given time is returned.
|
||||||
|
String FluxValue::getString() {
|
||||||
|
if(_data && (_data->getType() == FluxDatatypeString ||_data->getType() == FluxDatatypeDuration || _data->getType() == FluxBinaryDataTypeBase64)) {
|
||||||
|
FluxString *s = (FluxString *)_data.get();
|
||||||
|
return s->value;
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
long FluxValue::getLong() {
|
||||||
|
if(_data && _data->getType() == FluxDatatypeLong) {
|
||||||
|
FluxLong *l = (FluxLong *)_data.get();
|
||||||
|
return l->value;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned long FluxValue::getUnsignedLong() {
|
||||||
|
if(_data && _data->getType() == FluxDatatypeUnsignedLong) {
|
||||||
|
FluxUnsignedLong *l = (FluxUnsignedLong *)_data.get();
|
||||||
|
return l->value;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
}
|
||||||
|
FluxDateTime FluxValue::getDateTime() {
|
||||||
|
if(_data && (_data->getType() == FluxDatatypeDatetimeRFC3339 ||_data->getType() == FluxDatatypeDatetimeRFC3339Nano)) {
|
||||||
|
FluxDateTime *d = (FluxDateTime *)_data.get();
|
||||||
|
return *d;
|
||||||
|
}
|
||||||
|
return FluxDateTime("",FluxDatatypeDatetimeRFC3339, {0,0,0,0,0,0,0,0,0}, 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FluxValue::getBool() {
|
||||||
|
if(_data && _data->getType() == FluxDatatypeBool) {
|
||||||
|
FluxBool *b = (FluxBool *)_data.get();
|
||||||
|
return b->value;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
double FluxValue::getDouble() {
|
||||||
|
if(_data && _data->getType() == FluxDatatypeDouble) {
|
||||||
|
FluxDouble *d = (FluxDouble *)_data.get();
|
||||||
|
return d->value;
|
||||||
|
}
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// returns string representation of non-string values
|
||||||
|
String FluxValue::getRawValue() {
|
||||||
|
if(_data) {
|
||||||
|
return _data->getRawValue();
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FluxValue::isNull() {
|
||||||
|
return _data == nullptr;
|
||||||
|
}
|
178
firmware/libraries/ESP8266_Influxdb/src/query/FluxTypes 2.h
Normal file
178
firmware/libraries/ESP8266_Influxdb/src/query/FluxTypes 2.h
Normal file
|
@ -0,0 +1,178 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* FLuxTypes.h: InfluxDB flux types representation
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _FLUX_TYPES_H_
|
||||||
|
#define _FLUX_TYPES_H_
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
/** Supported flux types:
|
||||||
|
* - long - converts to long
|
||||||
|
* - unsignedLong - converts to unsigned long
|
||||||
|
* - double - converts to double
|
||||||
|
* - bool - converts to bool
|
||||||
|
* - dateTime:RFC3339 - converts to FluxDataTime
|
||||||
|
* - dateTime:RFC3339Nano - converts to FluxDataTime
|
||||||
|
* other types defaults to String
|
||||||
|
*/
|
||||||
|
|
||||||
|
extern const char *FluxDatatypeString;
|
||||||
|
extern const char *FluxDatatypeDouble;
|
||||||
|
extern const char *FluxDatatypeBool;
|
||||||
|
extern const char *FluxDatatypeLong;
|
||||||
|
extern const char *FluxDatatypeUnsignedLong;
|
||||||
|
extern const char *FluxDatatypeDuration;
|
||||||
|
extern const char *FluxBinaryDataTypeBase64;
|
||||||
|
extern const char *FluxDatatypeDatetimeRFC3339;
|
||||||
|
extern const char *FluxDatatypeDatetimeRFC3339Nano;
|
||||||
|
|
||||||
|
// Base type for all specific flux types
|
||||||
|
class FluxBase {
|
||||||
|
protected:
|
||||||
|
String _rawValue;
|
||||||
|
public:
|
||||||
|
FluxBase(const String &rawValue);
|
||||||
|
virtual ~FluxBase();
|
||||||
|
String getRawValue() const { return _rawValue; }
|
||||||
|
virtual const char *getType() = 0;
|
||||||
|
virtual char *jsonString() = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux long
|
||||||
|
class FluxLong : public FluxBase {
|
||||||
|
public:
|
||||||
|
FluxLong(const String &rawValue, long value);
|
||||||
|
long value;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux unsignedLong
|
||||||
|
class FluxUnsignedLong : public FluxBase {
|
||||||
|
public:
|
||||||
|
FluxUnsignedLong(const String &rawValue, unsigned long value);
|
||||||
|
unsigned long value;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux double
|
||||||
|
class FluxDouble : public FluxBase {
|
||||||
|
public:
|
||||||
|
FluxDouble(const String &rawValue, double value);
|
||||||
|
FluxDouble(const String &rawValue, double value, int precision);
|
||||||
|
double value;
|
||||||
|
// For JSON serialization
|
||||||
|
int precision;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux bool
|
||||||
|
class FluxBool : public FluxBase {
|
||||||
|
public:
|
||||||
|
FluxBool(const String &rawValue, bool value);
|
||||||
|
bool value;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux dateTime:RFC3339 and dateTime:RFC3339Nano
|
||||||
|
// Date and time are stored in classic struct tm.
|
||||||
|
// Fraction of second is stored in microseconds
|
||||||
|
// There are several classic functions for using struct tm: http://www.cplusplus.com/reference/ctime/
|
||||||
|
class FluxDateTime : public FluxBase {
|
||||||
|
protected:
|
||||||
|
const char *_type;
|
||||||
|
public:
|
||||||
|
FluxDateTime(const String &rawValue, const char *type, struct tm value, unsigned long microseconds);
|
||||||
|
// Struct tm for date and time
|
||||||
|
struct tm value;
|
||||||
|
// microseconds part
|
||||||
|
unsigned long microseconds;
|
||||||
|
// Formats the value part to string according to the given format. Microseconds are skipped.
|
||||||
|
// Format string must be compatible with the http://www.cplusplus.com/reference/ctime/strftime/
|
||||||
|
String format(const String &formatString);
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux string, duration, base64binary
|
||||||
|
class FluxString : public FluxBase {
|
||||||
|
protected:
|
||||||
|
const char *_type;
|
||||||
|
public:
|
||||||
|
FluxString(const String &rawValue, const char *type);
|
||||||
|
FluxString(const String &rawValue, const String &value, const char *type);
|
||||||
|
String value;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FluxValue wraps a value from a flux query result column.
|
||||||
|
* It provides getter methods for supported flux types:
|
||||||
|
* * getString() - string, base64binary or duration
|
||||||
|
* * getLong() - long
|
||||||
|
* * getUnsignedLong() - unsignedLong
|
||||||
|
* * getDateTime() - dateTime:RFC3339 or dateTime:RFC3339Nano
|
||||||
|
* * getBool() - bool
|
||||||
|
* * getDouble() - double
|
||||||
|
*
|
||||||
|
* Calling improper type getter will result in zero (empty) value.
|
||||||
|
* Check for null value using isNull().
|
||||||
|
* Use getRawValue() for getting original string form.
|
||||||
|
*
|
||||||
|
**/
|
||||||
|
|
||||||
|
class FluxValue {
|
||||||
|
public:
|
||||||
|
FluxValue();
|
||||||
|
FluxValue(FluxBase *value);
|
||||||
|
FluxValue(const FluxValue &other);
|
||||||
|
FluxValue& operator=(const FluxValue& other);
|
||||||
|
// Check if value represent null - not present - value.
|
||||||
|
bool isNull();
|
||||||
|
// Returns a value of string, base64binary or duration type column, or empty string if column is a different type.
|
||||||
|
String getString();
|
||||||
|
// Returns a value of long type column, or zero if column is a different type.
|
||||||
|
long getLong();
|
||||||
|
// Returns a value of unsigned long type column, or zero if column is a different type.
|
||||||
|
unsigned long getUnsignedLong();
|
||||||
|
// Returns a value of dateTime:RFC3339 or dateTime:RFC3339Nano, or zeroed FluxDateTime instance if column is a different type.
|
||||||
|
FluxDateTime getDateTime();
|
||||||
|
// Returns a value of bool type column, or false if column is a different type.
|
||||||
|
bool getBool();
|
||||||
|
// Returns a value of double type column, or 0.0 if column is a different type.
|
||||||
|
double getDouble();
|
||||||
|
// Returns a value in the original string form, as presented in the response.
|
||||||
|
String getRawValue();
|
||||||
|
private:
|
||||||
|
std::shared_ptr<FluxBase> _data;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_FLUX_TYPES_H_
|
239
firmware/libraries/ESP8266_Influxdb/src/query/FluxTypes.cpp
Normal file
239
firmware/libraries/ESP8266_Influxdb/src/query/FluxTypes.cpp
Normal file
|
@ -0,0 +1,239 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* FluxTypes.cpp: InfluxDB flux query types support
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2018-2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "FluxTypes.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
const char *FluxDatatypeString = "string";
|
||||||
|
const char *FluxDatatypeDouble = "double";
|
||||||
|
const char *FluxDatatypeBool = "boolean";
|
||||||
|
const char *FluxDatatypeLong = "long";
|
||||||
|
const char *FluxDatatypeUnsignedLong = "unsignedLong";
|
||||||
|
const char *FluxDatatypeDuration = "duration";
|
||||||
|
const char *FluxBinaryDataTypeBase64 = "base64Binary";
|
||||||
|
const char *FluxDatatypeDatetimeRFC3339 = "dateTime:RFC3339";
|
||||||
|
const char *FluxDatatypeDatetimeRFC3339Nano = "dateTime:RFC3339Nano";
|
||||||
|
|
||||||
|
FluxBase::FluxBase(const String &rawValue):_rawValue(rawValue) {
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxBase::~FluxBase() {
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FluxLong::FluxLong(const String &rawValue, long value):FluxBase(rawValue),value(value) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxLong::getType() {
|
||||||
|
return FluxDatatypeLong;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxLong::jsonString() {
|
||||||
|
int len =_rawValue.length()+3+getNumLength(value)+2;
|
||||||
|
char *json = new char[len+1];
|
||||||
|
snprintf_P(json, len, PSTR("\"%s\":%ld"), _rawValue.c_str(), value);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FluxUnsignedLong::FluxUnsignedLong(const String &rawValue, unsigned long value):FluxBase(rawValue),value(value) {
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxUnsignedLong::getType() {
|
||||||
|
return FluxDatatypeUnsignedLong;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxUnsignedLong::jsonString() {
|
||||||
|
int len =_rawValue.length()+3+getNumLength(value)+2;
|
||||||
|
char *json = new char[len+1];
|
||||||
|
snprintf_P(json,len, PSTR("\"%s\":%lu"), _rawValue.c_str(), value);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxDouble::FluxDouble(const String &rawValue, double value):FluxDouble(rawValue, value, 0) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxDouble::FluxDouble(const String &rawValue, double value, int precision):FluxBase(rawValue),
|
||||||
|
value(value),precision(precision) {}
|
||||||
|
|
||||||
|
const char *FluxDouble::getType() {
|
||||||
|
return FluxDatatypeDouble;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxDouble::jsonString() {
|
||||||
|
int len = _rawValue.length()+3+getNumLength(value)+precision+2;
|
||||||
|
char *json = new char[len+1];
|
||||||
|
char format[10];
|
||||||
|
sprintf_P(format, PSTR("\"%%s\":%%.%df"), precision);
|
||||||
|
snprintf(json, len, format , _rawValue.c_str(), value);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxBool::FluxBool(const String &rawValue, bool value):FluxBase(rawValue),value(value) {
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxBool::getType() {
|
||||||
|
return FluxDatatypeBool;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxBool::jsonString() {
|
||||||
|
int len = _rawValue.length()+9;
|
||||||
|
char *json = new char[len+1];
|
||||||
|
snprintf_P(json, len, PSTR("\"%s\":%s"), _rawValue.c_str(), bool2string(value));
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FluxDateTime::FluxDateTime(const String &rawValue, const char *type, struct tm value, unsigned long microseconds):FluxBase(rawValue),_type(type),value(value), microseconds(microseconds) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxDateTime::getType() {
|
||||||
|
return _type;
|
||||||
|
}
|
||||||
|
|
||||||
|
String FluxDateTime::format(const String &formatString) {
|
||||||
|
int len = formatString.length() + 20; //+20 for safety
|
||||||
|
char *buff = new char[len];
|
||||||
|
strftime(buff,len, formatString.c_str(),&value);
|
||||||
|
String str = buff;
|
||||||
|
delete [] buff;
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxDateTime::jsonString() {
|
||||||
|
int len = _rawValue.length()+3+21+(microseconds?10:0);
|
||||||
|
char *buff = new char[len+1];
|
||||||
|
snprintf_P(buff, len, PSTR("\"%s\":\""), _rawValue.c_str());
|
||||||
|
strftime(buff+strlen(buff), len-strlen(buff), "%FT%T",&value);
|
||||||
|
if(microseconds) {
|
||||||
|
snprintf_P(buff+strlen(buff), len - strlen(buff), PSTR(".%06luZ"), microseconds);
|
||||||
|
}
|
||||||
|
strcat(buff+strlen(buff), "\"");
|
||||||
|
return buff;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxString::FluxString(const String &rawValue, const char *type):FluxString(rawValue, rawValue, type) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxString::FluxString(const String &rawValue, const String &value, const char *type):FluxBase(rawValue),_type(type),value(value)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
const char *FluxString::getType() {
|
||||||
|
return _type;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *FluxString::jsonString() {
|
||||||
|
int len = _rawValue.length()+value.length()+7;
|
||||||
|
char *buff = new char[len+1];
|
||||||
|
snprintf(buff, len, "\"%s\":\"%s\"", _rawValue.c_str(), value.c_str());
|
||||||
|
return buff;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FluxValue::FluxValue() {}
|
||||||
|
|
||||||
|
FluxValue::FluxValue(FluxBase *fluxValue):_data(fluxValue) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxValue::FluxValue(const FluxValue &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxValue& FluxValue::operator=(const FluxValue& other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type accessor. If value is different type zero value for given time is returned.
|
||||||
|
String FluxValue::getString() {
|
||||||
|
if(_data && (_data->getType() == FluxDatatypeString ||_data->getType() == FluxDatatypeDuration || _data->getType() == FluxBinaryDataTypeBase64)) {
|
||||||
|
FluxString *s = (FluxString *)_data.get();
|
||||||
|
return s->value;
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
long FluxValue::getLong() {
|
||||||
|
if(_data && _data->getType() == FluxDatatypeLong) {
|
||||||
|
FluxLong *l = (FluxLong *)_data.get();
|
||||||
|
return l->value;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned long FluxValue::getUnsignedLong() {
|
||||||
|
if(_data && _data->getType() == FluxDatatypeUnsignedLong) {
|
||||||
|
FluxUnsignedLong *l = (FluxUnsignedLong *)_data.get();
|
||||||
|
return l->value;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
}
|
||||||
|
FluxDateTime FluxValue::getDateTime() {
|
||||||
|
if(_data && (_data->getType() == FluxDatatypeDatetimeRFC3339 ||_data->getType() == FluxDatatypeDatetimeRFC3339Nano)) {
|
||||||
|
FluxDateTime *d = (FluxDateTime *)_data.get();
|
||||||
|
return *d;
|
||||||
|
}
|
||||||
|
return FluxDateTime("",FluxDatatypeDatetimeRFC3339, {0,0,0,0,0,0,0,0,0}, 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FluxValue::getBool() {
|
||||||
|
if(_data && _data->getType() == FluxDatatypeBool) {
|
||||||
|
FluxBool *b = (FluxBool *)_data.get();
|
||||||
|
return b->value;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
double FluxValue::getDouble() {
|
||||||
|
if(_data && _data->getType() == FluxDatatypeDouble) {
|
||||||
|
FluxDouble *d = (FluxDouble *)_data.get();
|
||||||
|
return d->value;
|
||||||
|
}
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// returns string representation of non-string values
|
||||||
|
String FluxValue::getRawValue() {
|
||||||
|
if(_data) {
|
||||||
|
return _data->getRawValue();
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FluxValue::isNull() {
|
||||||
|
return _data == nullptr;
|
||||||
|
}
|
178
firmware/libraries/ESP8266_Influxdb/src/query/FluxTypes.h
Normal file
178
firmware/libraries/ESP8266_Influxdb/src/query/FluxTypes.h
Normal file
|
@ -0,0 +1,178 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* FLuxTypes.h: InfluxDB flux types representation
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _FLUX_TYPES_H_
|
||||||
|
#define _FLUX_TYPES_H_
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
/** Supported flux types:
|
||||||
|
* - long - converts to long
|
||||||
|
* - unsignedLong - converts to unsigned long
|
||||||
|
* - double - converts to double
|
||||||
|
* - bool - converts to bool
|
||||||
|
* - dateTime:RFC3339 - converts to FluxDataTime
|
||||||
|
* - dateTime:RFC3339Nano - converts to FluxDataTime
|
||||||
|
* other types defaults to String
|
||||||
|
*/
|
||||||
|
|
||||||
|
extern const char *FluxDatatypeString;
|
||||||
|
extern const char *FluxDatatypeDouble;
|
||||||
|
extern const char *FluxDatatypeBool;
|
||||||
|
extern const char *FluxDatatypeLong;
|
||||||
|
extern const char *FluxDatatypeUnsignedLong;
|
||||||
|
extern const char *FluxDatatypeDuration;
|
||||||
|
extern const char *FluxBinaryDataTypeBase64;
|
||||||
|
extern const char *FluxDatatypeDatetimeRFC3339;
|
||||||
|
extern const char *FluxDatatypeDatetimeRFC3339Nano;
|
||||||
|
|
||||||
|
// Base type for all specific flux types
|
||||||
|
class FluxBase {
|
||||||
|
protected:
|
||||||
|
String _rawValue;
|
||||||
|
public:
|
||||||
|
FluxBase(const String &rawValue);
|
||||||
|
virtual ~FluxBase();
|
||||||
|
String getRawValue() const { return _rawValue; }
|
||||||
|
virtual const char *getType() = 0;
|
||||||
|
virtual char *jsonString() = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux long
|
||||||
|
class FluxLong : public FluxBase {
|
||||||
|
public:
|
||||||
|
FluxLong(const String &rawValue, long value);
|
||||||
|
long value;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux unsignedLong
|
||||||
|
class FluxUnsignedLong : public FluxBase {
|
||||||
|
public:
|
||||||
|
FluxUnsignedLong(const String &rawValue, unsigned long value);
|
||||||
|
unsigned long value;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux double
|
||||||
|
class FluxDouble : public FluxBase {
|
||||||
|
public:
|
||||||
|
FluxDouble(const String &rawValue, double value);
|
||||||
|
FluxDouble(const String &rawValue, double value, int precision);
|
||||||
|
double value;
|
||||||
|
// For JSON serialization
|
||||||
|
int precision;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux bool
|
||||||
|
class FluxBool : public FluxBase {
|
||||||
|
public:
|
||||||
|
FluxBool(const String &rawValue, bool value);
|
||||||
|
bool value;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux dateTime:RFC3339 and dateTime:RFC3339Nano
|
||||||
|
// Date and time are stored in classic struct tm.
|
||||||
|
// Fraction of second is stored in microseconds
|
||||||
|
// There are several classic functions for using struct tm: http://www.cplusplus.com/reference/ctime/
|
||||||
|
class FluxDateTime : public FluxBase {
|
||||||
|
protected:
|
||||||
|
const char *_type;
|
||||||
|
public:
|
||||||
|
FluxDateTime(const String &rawValue, const char *type, struct tm value, unsigned long microseconds);
|
||||||
|
// Struct tm for date and time
|
||||||
|
struct tm value;
|
||||||
|
// microseconds part
|
||||||
|
unsigned long microseconds;
|
||||||
|
// Formats the value part to string according to the given format. Microseconds are skipped.
|
||||||
|
// Format string must be compatible with the http://www.cplusplus.com/reference/ctime/strftime/
|
||||||
|
String format(const String &formatString);
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents flux string, duration, base64binary
|
||||||
|
class FluxString : public FluxBase {
|
||||||
|
protected:
|
||||||
|
const char *_type;
|
||||||
|
public:
|
||||||
|
FluxString(const String &rawValue, const char *type);
|
||||||
|
FluxString(const String &rawValue, const String &value, const char *type);
|
||||||
|
String value;
|
||||||
|
virtual const char *getType() override;
|
||||||
|
virtual char *jsonString() override;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FluxValue wraps a value from a flux query result column.
|
||||||
|
* It provides getter methods for supported flux types:
|
||||||
|
* * getString() - string, base64binary or duration
|
||||||
|
* * getLong() - long
|
||||||
|
* * getUnsignedLong() - unsignedLong
|
||||||
|
* * getDateTime() - dateTime:RFC3339 or dateTime:RFC3339Nano
|
||||||
|
* * getBool() - bool
|
||||||
|
* * getDouble() - double
|
||||||
|
*
|
||||||
|
* Calling improper type getter will result in zero (empty) value.
|
||||||
|
* Check for null value using isNull().
|
||||||
|
* Use getRawValue() for getting original string form.
|
||||||
|
*
|
||||||
|
**/
|
||||||
|
|
||||||
|
class FluxValue {
|
||||||
|
public:
|
||||||
|
FluxValue();
|
||||||
|
FluxValue(FluxBase *value);
|
||||||
|
FluxValue(const FluxValue &other);
|
||||||
|
FluxValue& operator=(const FluxValue& other);
|
||||||
|
// Check if value represent null - not present - value.
|
||||||
|
bool isNull();
|
||||||
|
// Returns a value of string, base64binary or duration type column, or empty string if column is a different type.
|
||||||
|
String getString();
|
||||||
|
// Returns a value of long type column, or zero if column is a different type.
|
||||||
|
long getLong();
|
||||||
|
// Returns a value of unsigned long type column, or zero if column is a different type.
|
||||||
|
unsigned long getUnsignedLong();
|
||||||
|
// Returns a value of dateTime:RFC3339 or dateTime:RFC3339Nano, or zeroed FluxDateTime instance if column is a different type.
|
||||||
|
FluxDateTime getDateTime();
|
||||||
|
// Returns a value of bool type column, or false if column is a different type.
|
||||||
|
bool getBool();
|
||||||
|
// Returns a value of double type column, or 0.0 if column is a different type.
|
||||||
|
double getDouble();
|
||||||
|
// Returns a value in the original string form, as presented in the response.
|
||||||
|
String getRawValue();
|
||||||
|
private:
|
||||||
|
std::shared_ptr<FluxBase> _data;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_FLUX_TYPES_H_
|
|
@ -0,0 +1,104 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* HttpStreamScanner.cpp: Scannes HttpClient stream for lines. Supports chunking.
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "HttpStreamScanner.h"
|
||||||
|
|
||||||
|
// Uncomment bellow in case of a problem and rebuild sketch
|
||||||
|
//#define INFLUXDB_CLIENT_DEBUG_ENABLE
|
||||||
|
#include "util/debug.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
HttpStreamScanner::HttpStreamScanner(HTTPClient *client, bool chunked)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_stream = client->getStreamPtr();
|
||||||
|
_chunked = chunked;
|
||||||
|
_chunkHeader = chunked;
|
||||||
|
_len = client->getSize();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HttpStreamScanner: chunked: %s, size: %d\n", bool2string(_chunked), _len);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HttpStreamScanner::next() {
|
||||||
|
while(_client->connected() && (_len > 0 || _len == -1)) {
|
||||||
|
_line = _stream->readStringUntil('\n');
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HttpStreamScanner: line: %s\n", _line.c_str());
|
||||||
|
++_linesNum;
|
||||||
|
int lineLen = _line.length();
|
||||||
|
if(lineLen == 0) {
|
||||||
|
_error = HTTPC_ERROR_READ_TIMEOUT;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int r = lineLen +1; //+1 for terminating \n
|
||||||
|
_line.trim(); //remove \r
|
||||||
|
if(!_chunked || !_chunkHeader) {
|
||||||
|
_read += r;
|
||||||
|
if(_lastChunkLine.length() > 0) { //fix broken line
|
||||||
|
_line = _lastChunkLine + _line;
|
||||||
|
_lastChunkLine = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
if(_chunkHeader && r == 2) { //empty line at the end of chunk
|
||||||
|
//last line was complete so return
|
||||||
|
_line = _lastChunkLine;
|
||||||
|
_lastChunkLine = "";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if(_chunkHeader){
|
||||||
|
_chunkLen = (int) strtol((const char *) _line.c_str(), NULL, 16);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HttpStreamScanner chunk len: %d\n", _chunkLen);
|
||||||
|
_chunkHeader = false;
|
||||||
|
_read = 0;
|
||||||
|
if(_chunkLen == 0) { //last chunk
|
||||||
|
_error = 0;
|
||||||
|
_line = "";
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else if(_chunked && _read >= _chunkLen){ //we reached end of chunk.
|
||||||
|
_lastChunkLine = _line;
|
||||||
|
_chunkHeader = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(_len > 0) {
|
||||||
|
_len -= r;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HttpStreamScanner new len: %d\n", _len);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if(!_client->connected() && ( (_chunked && _chunkLen > 0) || (!_chunked && _len > 0))) { //report error only if we didn't went to
|
||||||
|
_error = HTTPC_ERROR_CONNECTION_LOST;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("HttpStreamScanner connection lost\n");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpStreamScanner::close() {
|
||||||
|
_client->end();
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,64 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* HttpStreamScanner.h: Scannes HttpClient stream for lines. Supports chunking.
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _HTTP_STREAM_SCANNER_
|
||||||
|
#define _HTTP_STREAM_SCANNER_
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
# include <ESP8266HTTPClient.h>
|
||||||
|
#elif defined(ESP32)
|
||||||
|
# include <HTTPClient.h>
|
||||||
|
#endif //ESP8266
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HttpStreamScanner parses response stream from HTTPClient for lines.
|
||||||
|
* By repeatedly calling next() it searches for new line.
|
||||||
|
* If next() returns false, it can mean end of stream or an error.
|
||||||
|
* Check getError() for nonzero if an error occured
|
||||||
|
*/
|
||||||
|
class HttpStreamScanner {
|
||||||
|
public:
|
||||||
|
HttpStreamScanner(HTTPClient *client, bool chunked);
|
||||||
|
bool next();
|
||||||
|
void close();
|
||||||
|
const String &getLine() const { return _line; }
|
||||||
|
int getError() const { return _error; }
|
||||||
|
int getLinesNum() const {return _linesNum; }
|
||||||
|
private:
|
||||||
|
HTTPClient *_client;
|
||||||
|
Stream *_stream = nullptr;
|
||||||
|
int _len;
|
||||||
|
String _line;
|
||||||
|
int _linesNum= 0;
|
||||||
|
int _read = 0;
|
||||||
|
bool _chunked;
|
||||||
|
bool _chunkHeader;
|
||||||
|
int _chunkLen = 0;
|
||||||
|
String _lastChunkLine;
|
||||||
|
int _error = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //#_HTTP_STREAM_SCANNER_
|
|
@ -0,0 +1,104 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* HttpStreamScanner.cpp: Scannes HttpClient stream for lines. Supports chunking.
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#include "HttpStreamScanner.h"
|
||||||
|
|
||||||
|
// Uncomment bellow in case of a problem and rebuild sketch
|
||||||
|
//#define INFLUXDB_CLIENT_DEBUG_ENABLE
|
||||||
|
#include "util/debug.h"
|
||||||
|
#include "util/helpers.h"
|
||||||
|
|
||||||
|
HttpStreamScanner::HttpStreamScanner(HTTPClient *client, bool chunked)
|
||||||
|
{
|
||||||
|
_client = client;
|
||||||
|
_stream = client->getStreamPtr();
|
||||||
|
_chunked = chunked;
|
||||||
|
_chunkHeader = chunked;
|
||||||
|
_len = client->getSize();
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HttpStreamScanner: chunked: %s, size: %d\n", bool2string(_chunked), _len);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HttpStreamScanner::next() {
|
||||||
|
while(_client->connected() && (_len > 0 || _len == -1)) {
|
||||||
|
_line = _stream->readStringUntil('\n');
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HttpStreamScanner: line: %s\n", _line.c_str());
|
||||||
|
++_linesNum;
|
||||||
|
int lineLen = _line.length();
|
||||||
|
if(lineLen == 0) {
|
||||||
|
_error = HTTPC_ERROR_READ_TIMEOUT;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
int r = lineLen +1; //+1 for terminating \n
|
||||||
|
_line.trim(); //remove \r
|
||||||
|
if(!_chunked || !_chunkHeader) {
|
||||||
|
_read += r;
|
||||||
|
if(_lastChunkLine.length() > 0) { //fix broken line
|
||||||
|
_line = _lastChunkLine + _line;
|
||||||
|
_lastChunkLine = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
if(_chunkHeader && r == 2) { //empty line at the end of chunk
|
||||||
|
//last line was complete so return
|
||||||
|
_line = _lastChunkLine;
|
||||||
|
_lastChunkLine = "";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if(_chunkHeader){
|
||||||
|
_chunkLen = (int) strtol((const char *) _line.c_str(), NULL, 16);
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HttpStreamScanner chunk len: %d\n", _chunkLen);
|
||||||
|
_chunkHeader = false;
|
||||||
|
_read = 0;
|
||||||
|
if(_chunkLen == 0) { //last chunk
|
||||||
|
_error = 0;
|
||||||
|
_line = "";
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else if(_chunked && _read >= _chunkLen){ //we reached end of chunk.
|
||||||
|
_lastChunkLine = _line;
|
||||||
|
_chunkHeader = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if(_len > 0) {
|
||||||
|
_len -= r;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("[D] HttpStreamScanner new len: %d\n", _len);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if(!_client->connected() && ( (_chunked && _chunkLen > 0) || (!_chunked && _len > 0))) { //report error only if we didn't went to
|
||||||
|
_error = HTTPC_ERROR_CONNECTION_LOST;
|
||||||
|
INFLUXDB_CLIENT_DEBUG("HttpStreamScanner connection lost\n");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void HttpStreamScanner::close() {
|
||||||
|
_client->end();
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,64 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* HttpStreamScanner.h: Scannes HttpClient stream for lines. Supports chunking.
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _HTTP_STREAM_SCANNER_
|
||||||
|
#define _HTTP_STREAM_SCANNER_
|
||||||
|
|
||||||
|
#if defined(ESP8266)
|
||||||
|
# include <ESP8266HTTPClient.h>
|
||||||
|
#elif defined(ESP32)
|
||||||
|
# include <HTTPClient.h>
|
||||||
|
#endif //ESP8266
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HttpStreamScanner parses response stream from HTTPClient for lines.
|
||||||
|
* By repeatedly calling next() it searches for new line.
|
||||||
|
* If next() returns false, it can mean end of stream or an error.
|
||||||
|
* Check getError() for nonzero if an error occured
|
||||||
|
*/
|
||||||
|
class HttpStreamScanner {
|
||||||
|
public:
|
||||||
|
HttpStreamScanner(HTTPClient *client, bool chunked);
|
||||||
|
bool next();
|
||||||
|
void close();
|
||||||
|
const String &getLine() const { return _line; }
|
||||||
|
int getError() const { return _error; }
|
||||||
|
int getLinesNum() const {return _linesNum; }
|
||||||
|
private:
|
||||||
|
HTTPClient *_client;
|
||||||
|
Stream *_stream = nullptr;
|
||||||
|
int _len;
|
||||||
|
String _line;
|
||||||
|
int _linesNum= 0;
|
||||||
|
int _read = 0;
|
||||||
|
bool _chunked;
|
||||||
|
bool _chunkHeader;
|
||||||
|
int _chunkLen = 0;
|
||||||
|
String _lastChunkLine;
|
||||||
|
int _error = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //#_HTTP_STREAM_SCANNER_
|
151
firmware/libraries/ESP8266_Influxdb/src/query/Params 2.cpp
Normal file
151
firmware/libraries/ESP8266_Influxdb/src/query/Params 2.cpp
Normal file
|
@ -0,0 +1,151 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Params.cpp: InfluxDB flux query param
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "Params.h"
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
QueryParams::QueryParams() {
|
||||||
|
_data = std::make_shared<ParamsList>();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
QueryParams::QueryParams(const QueryParams& other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams::~QueryParams() {
|
||||||
|
if(_data) {
|
||||||
|
std::for_each(_data->begin(), _data->end(), [](FluxBase *&value){ delete value; });
|
||||||
|
_data->clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::operator=(const QueryParams &other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, float value, int decimalPlaces) {
|
||||||
|
return add(name, (double)value, decimalPlaces);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, double value, int decimalPlaces) {
|
||||||
|
return add(new FluxDouble(name, value, decimalPlaces));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, char value) {
|
||||||
|
String s(value);
|
||||||
|
return add(name, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, unsigned char value) {
|
||||||
|
return add(name, (unsigned long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, int value) {
|
||||||
|
return add(name,(long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, unsigned int value) {
|
||||||
|
return add(name,(unsigned long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, long value) {
|
||||||
|
return add(new FluxLong(name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, unsigned long value) {
|
||||||
|
return add(new FluxUnsignedLong(name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, bool value) {
|
||||||
|
return add(new FluxBool(name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, const String &value) {
|
||||||
|
return add(name, value.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, const __FlashStringHelper *pstr) {
|
||||||
|
return add(name, String(pstr));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, long long value) {
|
||||||
|
return add(name,(long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, unsigned long long value) {
|
||||||
|
return add(name,(unsigned long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, const char *value) {
|
||||||
|
return add(new FluxString(name, value, FluxDatatypeString));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, struct tm tm, unsigned long micros ) {
|
||||||
|
return add(new FluxDateTime(name, FluxDatatypeDatetimeRFC3339Nano, tm, micros));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(FluxBase *value) {
|
||||||
|
if(_data) {
|
||||||
|
_data->push_back(value);
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void QueryParams::remove(const String &name) {
|
||||||
|
if(_data) {
|
||||||
|
auto it = std::find_if(_data->begin(),_data->end(), [name](FluxBase *f){ return f->getRawValue() == name; } );
|
||||||
|
if(it != _data->end()) {
|
||||||
|
delete *it;
|
||||||
|
_data->erase(it);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Copy constructor
|
||||||
|
int QueryParams::size() {
|
||||||
|
if(_data) {
|
||||||
|
return _data->size();
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxBase *QueryParams::get(int i) {
|
||||||
|
if(_data) {
|
||||||
|
return _data->at(i);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *QueryParams::jsonString(int i) {
|
||||||
|
if(_data) {
|
||||||
|
return _data->at(i)->jsonString();
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
95
firmware/libraries/ESP8266_Influxdb/src/query/Params 2.h
Normal file
95
firmware/libraries/ESP8266_Influxdb/src/query/Params 2.h
Normal file
|
@ -0,0 +1,95 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Prams.h: InfluxDB flux query param
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _QUERY_PARAM_H_
|
||||||
|
#define _QUERY_PARAM_H_
|
||||||
|
|
||||||
|
#include "FluxTypes.h"
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
typedef std::vector<FluxBase *> ParamsList;
|
||||||
|
/**
|
||||||
|
* QueryParams holds parameters for Flux query.
|
||||||
|
* Parameters are accessed via the 'params.' prefix: e.g. params.start
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
class QueryParams {
|
||||||
|
public:
|
||||||
|
// Constructor
|
||||||
|
QueryParams();
|
||||||
|
// Copy constructor
|
||||||
|
QueryParams(const QueryParams& other);
|
||||||
|
// Assignment operator
|
||||||
|
QueryParams &operator=(const QueryParams &other);
|
||||||
|
// Descructor
|
||||||
|
~QueryParams();
|
||||||
|
// Adds param with a float value. A number of decimal places can be optionally set.
|
||||||
|
QueryParams &add(const String &name, float value, int decimalPlaces = 2);
|
||||||
|
// Adds param with a double value. A number of decimal places can be optionally set.
|
||||||
|
QueryParams &add(const String &name, double value, int decimalPlaces = 2);
|
||||||
|
// Adds param with a character value.
|
||||||
|
QueryParams &add(const String &name, char value);
|
||||||
|
// Adds param with an unsigned character value. It is added as a number.
|
||||||
|
QueryParams &add(const String &name, unsigned char value);
|
||||||
|
// Adds param with an integer value.
|
||||||
|
QueryParams &add(const String &name, int value);
|
||||||
|
// Adds param with an unsigned integer value.
|
||||||
|
QueryParams &add(const String &name, unsigned int value);
|
||||||
|
// Adds param with a long value.
|
||||||
|
QueryParams &add(const String &name, long value);
|
||||||
|
// Adds param with an unsigned long value.
|
||||||
|
QueryParams &add(const String &name, unsigned long value);
|
||||||
|
// Adds param with a boolen value.
|
||||||
|
QueryParams &add(const String &name, bool value);
|
||||||
|
// Adds param with a String value.
|
||||||
|
QueryParams &add(const String &name, const String &value);
|
||||||
|
// Adds param with a progmem string value.
|
||||||
|
QueryParams &add(const String &name, const __FlashStringHelper *pstr);
|
||||||
|
// Adds param with a long long value. It is converted to long.
|
||||||
|
QueryParams &add(const String &name, long long value);
|
||||||
|
// Adds param with an unsigned long long value. It is converted to long.
|
||||||
|
QueryParams &add(const String &name, unsigned long long value);
|
||||||
|
// Adds param with a string value.
|
||||||
|
QueryParams &add(const String &name, const char *value);
|
||||||
|
// Adds param as a string representation of date-time value in UTC timezone, e.g. "2022-01-12T23:12:30.124Z"
|
||||||
|
// Micros is fractional part of seconds up to microseconds precision. E.g. if millisecond are provided
|
||||||
|
// it must be converted to microseconds: micros = 1000*millis
|
||||||
|
QueryParams &add(const String &name, struct tm tm, unsigned long micros = 0);
|
||||||
|
// Removed a param
|
||||||
|
void remove(const String &name);
|
||||||
|
// Returns i-th param
|
||||||
|
FluxBase *get(int i);
|
||||||
|
// Returns params count
|
||||||
|
int size();
|
||||||
|
// Returns JSON representation of i-th param
|
||||||
|
char *jsonString(int i);
|
||||||
|
private:
|
||||||
|
QueryParams &add(FluxBase *value);
|
||||||
|
std::shared_ptr<ParamsList> _data;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_QUERY_PARAM_H_
|
151
firmware/libraries/ESP8266_Influxdb/src/query/Params.cpp
Normal file
151
firmware/libraries/ESP8266_Influxdb/src/query/Params.cpp
Normal file
|
@ -0,0 +1,151 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Params.cpp: InfluxDB flux query param
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "Params.h"
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
QueryParams::QueryParams() {
|
||||||
|
_data = std::make_shared<ParamsList>();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
QueryParams::QueryParams(const QueryParams& other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams::~QueryParams() {
|
||||||
|
if(_data) {
|
||||||
|
std::for_each(_data->begin(), _data->end(), [](FluxBase *&value){ delete value; });
|
||||||
|
_data->clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::operator=(const QueryParams &other) {
|
||||||
|
if(this != &other) {
|
||||||
|
_data = other._data;
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, float value, int decimalPlaces) {
|
||||||
|
return add(name, (double)value, decimalPlaces);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, double value, int decimalPlaces) {
|
||||||
|
return add(new FluxDouble(name, value, decimalPlaces));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, char value) {
|
||||||
|
String s(value);
|
||||||
|
return add(name, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, unsigned char value) {
|
||||||
|
return add(name, (unsigned long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, int value) {
|
||||||
|
return add(name,(long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, unsigned int value) {
|
||||||
|
return add(name,(unsigned long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, long value) {
|
||||||
|
return add(new FluxLong(name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, unsigned long value) {
|
||||||
|
return add(new FluxUnsignedLong(name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, bool value) {
|
||||||
|
return add(new FluxBool(name, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, const String &value) {
|
||||||
|
return add(name, value.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, const __FlashStringHelper *pstr) {
|
||||||
|
return add(name, String(pstr));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, long long value) {
|
||||||
|
return add(name,(long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, unsigned long long value) {
|
||||||
|
return add(name,(unsigned long)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, const char *value) {
|
||||||
|
return add(new FluxString(name, value, FluxDatatypeString));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(const String &name, struct tm tm, unsigned long micros ) {
|
||||||
|
return add(new FluxDateTime(name, FluxDatatypeDatetimeRFC3339Nano, tm, micros));
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryParams &QueryParams::add(FluxBase *value) {
|
||||||
|
if(_data) {
|
||||||
|
_data->push_back(value);
|
||||||
|
}
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
void QueryParams::remove(const String &name) {
|
||||||
|
if(_data) {
|
||||||
|
auto it = std::find_if(_data->begin(),_data->end(), [name](FluxBase *f){ return f->getRawValue() == name; } );
|
||||||
|
if(it != _data->end()) {
|
||||||
|
delete *it;
|
||||||
|
_data->erase(it);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Copy constructor
|
||||||
|
int QueryParams::size() {
|
||||||
|
if(_data) {
|
||||||
|
return _data->size();
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
FluxBase *QueryParams::get(int i) {
|
||||||
|
if(_data) {
|
||||||
|
return _data->at(i);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
char *QueryParams::jsonString(int i) {
|
||||||
|
if(_data) {
|
||||||
|
return _data->at(i)->jsonString();
|
||||||
|
}
|
||||||
|
return nullptr;
|
||||||
|
}
|
95
firmware/libraries/ESP8266_Influxdb/src/query/Params.h
Normal file
95
firmware/libraries/ESP8266_Influxdb/src/query/Params.h
Normal file
|
@ -0,0 +1,95 @@
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* Prams.h: InfluxDB flux query param
|
||||||
|
*
|
||||||
|
* MIT License
|
||||||
|
*
|
||||||
|
* Copyright (c) 2020 InfluxData
|
||||||
|
*
|
||||||
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
* of this software and associated documentation files (the "Software"), to deal
|
||||||
|
* in the Software without restriction, including without limitation the rights
|
||||||
|
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
* copies of the Software, and to permit persons to whom the Software is
|
||||||
|
* furnished to do so, subject to the following conditions:
|
||||||
|
*
|
||||||
|
* The above copyright notice and this permission notice shall be included in all
|
||||||
|
* copies or substantial portions of the Software.
|
||||||
|
*
|
||||||
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
* SOFTWARE.
|
||||||
|
*/
|
||||||
|
#ifndef _QUERY_PARAM_H_
|
||||||
|
#define _QUERY_PARAM_H_
|
||||||
|
|
||||||
|
#include "FluxTypes.h"
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
typedef std::vector<FluxBase *> ParamsList;
|
||||||
|
/**
|
||||||
|
* QueryParams holds parameters for Flux query.
|
||||||
|
* Parameters are accessed via the 'params.' prefix: e.g. params.start
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
class QueryParams {
|
||||||
|
public:
|
||||||
|
// Constructor
|
||||||
|
QueryParams();
|
||||||
|
// Copy constructor
|
||||||
|
QueryParams(const QueryParams& other);
|
||||||
|
// Assignment operator
|
||||||
|
QueryParams &operator=(const QueryParams &other);
|
||||||
|
// Descructor
|
||||||
|
~QueryParams();
|
||||||
|
// Adds param with a float value. A number of decimal places can be optionally set.
|
||||||
|
QueryParams &add(const String &name, float value, int decimalPlaces = 2);
|
||||||
|
// Adds param with a double value. A number of decimal places can be optionally set.
|
||||||
|
QueryParams &add(const String &name, double value, int decimalPlaces = 2);
|
||||||
|
// Adds param with a character value.
|
||||||
|
QueryParams &add(const String &name, char value);
|
||||||
|
// Adds param with an unsigned character value. It is added as a number.
|
||||||
|
QueryParams &add(const String &name, unsigned char value);
|
||||||
|
// Adds param with an integer value.
|
||||||
|
QueryParams &add(const String &name, int value);
|
||||||
|
// Adds param with an unsigned integer value.
|
||||||
|
QueryParams &add(const String &name, unsigned int value);
|
||||||
|
// Adds param with a long value.
|
||||||
|
QueryParams &add(const String &name, long value);
|
||||||
|
// Adds param with an unsigned long value.
|
||||||
|
QueryParams &add(const String &name, unsigned long value);
|
||||||
|
// Adds param with a boolen value.
|
||||||
|
QueryParams &add(const String &name, bool value);
|
||||||
|
// Adds param with a String value.
|
||||||
|
QueryParams &add(const String &name, const String &value);
|
||||||
|
// Adds param with a progmem string value.
|
||||||
|
QueryParams &add(const String &name, const __FlashStringHelper *pstr);
|
||||||
|
// Adds param with a long long value. It is converted to long.
|
||||||
|
QueryParams &add(const String &name, long long value);
|
||||||
|
// Adds param with an unsigned long long value. It is converted to long.
|
||||||
|
QueryParams &add(const String &name, unsigned long long value);
|
||||||
|
// Adds param with a string value.
|
||||||
|
QueryParams &add(const String &name, const char *value);
|
||||||
|
// Adds param as a string representation of date-time value in UTC timezone, e.g. "2022-01-12T23:12:30.124Z"
|
||||||
|
// Micros is fractional part of seconds up to microseconds precision. E.g. if millisecond are provided
|
||||||
|
// it must be converted to microseconds: micros = 1000*millis
|
||||||
|
QueryParams &add(const String &name, struct tm tm, unsigned long micros = 0);
|
||||||
|
// Removed a param
|
||||||
|
void remove(const String &name);
|
||||||
|
// Returns i-th param
|
||||||
|
FluxBase *get(int i);
|
||||||
|
// Returns params count
|
||||||
|
int size();
|
||||||
|
// Returns JSON representation of i-th param
|
||||||
|
char *jsonString(int i);
|
||||||
|
private:
|
||||||
|
QueryParams &add(FluxBase *value);
|
||||||
|
std::shared_ptr<ParamsList> _data;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif //_QUERY_PARAM_H_
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue