• InfluxDB Arduino Client
    • Table of contents
    • Basic code for InfluxDB 2
    • Basic code for InfluxDB 1
    • Connecting to InfluxDB Cloud 2
    • Writing in Batches
      • Timestamp
      • Configure Time
      • Batch Size
      • Large batch size
      • Write Modes
    • Buffer Handling and Retrying
    • Write Options
    • HTTP Options
    • Secure Connection
      • InfluxDb 2
      • InfluxDb 1
      • Skipping certificate validation
    • Querying
      • Parametrized Queries
    • Original API
      • Initialization
      • Sending a single measurement
      • Write multiple data points at once
    • Troubleshooting
    • Contributing
    • License

    PlatformIO

    Arduino - 图2InfluxDB Arduino Client

    Simple Arduino client for writing and reading data from InfluxDB, no matter whether it is a local server or InfluxDB Cloud. The library supports authentication, secure communication over TLS, batching, automatic 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 and InfluxDB 1.

    This is a new implementation and the API, original API is still supported.

    Supported devices:

    This library doesn’t support using those devices as a peripheral.

    Arduino - 图3Table of contents

    Arduino - 图4Basic code for InfluxDB 2

    After setting up an InfluxDB 2 server, first define connection parameters and a client instance:

    1. // InfluxDB 2 server url, e.g. http://192.168.1.48:8086 (Use: InfluxDB UI -> Load Data -> Client Libraries)
    2. #define INFLUXDB_URL "influxdb-url"
    3. // InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
    4. #define INFLUXDB_TOKEN "token"
    5. // InfluxDB 2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
    6. #define INFLUXDB_ORG "org"
    7. // InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
    8. #define INFLUXDB_BUCKET "bucket"
    9. // Single InfluxDB instance
    10. 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):

    1. // Define data point in the measurement named 'device_status`
    2. Point pointDevice("device_status");
    3. // Set tags
    4. pointDevice.addTag("device", "ESP8266");
    5. pointDevice.addTag("SSID", WiFi.SSID());
    6. // Add data fields
    7. pointDevice.addField("rssi", WiFi.RSSI());
    8. pointDevice.addField("uptime", millis());

    And finally, write the data to the database:

    1. // Write data
    2. client.writePoint(pointDevice);

    Complete source code is available in the BasicWrite example.

    Data can be seen in the InfluxDB UI immediately. Use the Data Explorer or create a Dashboard.

    Arduino - 图5Basic 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.

    1. // InfluxDB server url, e.g. http://192.168.1.48:8086 (don't use localhost, always server name or ip address)
    2. #define INFLUXDB_URL "influxdb-url"
    3. // InfluxDB database name
    4. #define INFLUXDB_DB_NAME "database"
    5. // Single InfluxDB instance
    6. InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);
    7. // Define data point with measurement name 'device_status`
    8. Point pointDevice("device_status");
    9. // Set tags
    10. pointDevice.addTag("device", "ESP8266");
    11. pointDevice.addTag("SSID", WiFi.SSID());
    12. // Add data
    13. pointDevice.addField("rssi", WiFi.RSSI());
    14. pointDevice.addField("uptime", millis());
    15. // Write data
    16. client.writePoint(pointDevice);

    Complete source code is available in BasicWrite example

    Arduino - 图6Connecting to InfluxDB Cloud 2

    Instead of setting up a local InfluxDB 2 server, it is possible to quickly start with InfluxDB Cloud 2 with a 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 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.

    1. //Include also InfluxCloud 2 CA certificate
    2. #include <InfluxDbCloud.h>
    3. // InfluxDB 2 server or cloud url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
    4. #define INFLUXDB_URL "influxdb-url"
    5. // InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> <select token>)
    6. #define INFLUXDB_TOKEN "token"
    7. // InfluxDB 2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> <name under tile> )
    8. #define INFLUXDB_ORG "org"
    9. // InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets)
    10. #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:

    1. // Single InfluxDB instance
    2. InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);

    Read more about secure connection.

    Additionally, time needs to be synced:

    1. // Synchronize time with NTP servers and set timezone
    2. // Accurate time is necessary for certificate validation and writing in batches
    3. // For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
    4. configTzTime(TZ_INFO "pool.ntp.org", "time.nis.gov");

    Read more about time synchronization in Configure Time.

    Defining data and writing it to the DB is the same as in the case of BasicWrite:

    1. // Define data point with measurement name 'device_status`
    2. Point pointDevice("device_status");
    3. // Set tags
    4. pointDevice.addTag("device", "ESP8266");
    5. pointDevice.addTag("SSID", WiFi.SSID());
    6. // Add data
    7. pointDevice.addField("rssi", WiFi.RSSI());
    8. pointDevice.addField("uptime", millis());
    9. // Write data
    10. client.writePoint(pointDevice);

    Complete source code is available in SecureWrite example.

    Arduino - 图7Writing 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.

    Arduino - 图8Timestamp

    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 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:

    1. // Set write precision to milliseconds. Leave other parameters default.
    2. 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.

    Arduino - 图9Configure 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:

    1. // Synchronize time with NTP servers and set timezone
    2. // Accurate time is necessary for certificate validation and writing in batches
    3. // For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
    4. 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 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. 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:

    1. 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:

    1. // Synchronize time with NTP servers
    2. // Accurate time is necessary for certificate validation and writing in batches
    3. 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:

    1. // Synchronize time with NTP servers and waits for competition. Prints waiting progress and final synchronized time to the Serial.
    2. // Accurate time is necessary for certificate validation and writing points in batch
    3. // For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
    4. void timeSync(const char *tzInfo, const char* ntpServer1, const char* ntpServer2 = nullptr, const char* ntpServer3 = nullptr);

    Arduino - 图10Batch 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 function:

    1. // Enable lines batching
    2. client.setWriteOptions(WriteOptions().batchSize(10));

    Writing the point will add a point to the underlying buffer until the batch size is reached:

    1. // Write first point to the buffer
    2. // Buffered write always returns `true`
    3. client.writePoint(point1);
    4. // Write second point to the buffer
    5. client.writePoint(point2);
    6. ..
    7. // Write ninth point to the buffer
    8. client.writePoint(point9);
    9. // Writing tenth point will cause flushing buffer and returns actual write result.
    10. if(!client.writePoint(point10)) {
    11. Serial.print("InfluxDB write failed: ");
    12. Serial.println(client.getLastErrorMessage());
    13. }

    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 for more details.

    Arduino - 图11Large 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

    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.

    ⚠️ Thoroughly test your app when using large batch files.

    Arduino - 图12Write 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.

    1. // Enables stream write
    2. 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.

    Arduino - 图13Buffer 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 object:

    1. // Increase buffer to allow caching of failed writes
    2. 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:

    1. // Check whether buffer in not empty
    2. if (!client.isBufferEmpty()) {
    3. // Write all remaining points to db
    4. client.flushBuffer();
    5. }

    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 for example code of buffer handling functions.

    Arduino - 图14Write Options

    Writing points can be controlled via WriteOptions, which is set in the setWriteOptions function:

    ParameterDefault ValueMeaning
    writePrecisionWritePrecision::NoTimeTimestamp precision of written data
    batchSize1Number of points that will be written to the database at once
    bufferSize5Maximum 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
    flushInterval60Maximum time(in seconds) data will be held in buffer before points are written to the db
    retryInterval5Default retry interval in sec, if not sent by server. Value 0 disables retrying
    maxRetryInterval300Maximum retry interval in sec
    maxRetryAttempts3Maximum count of retry attempts of failed writes

    Arduino - 图15HTTP Options

    HTTPOptions controls some aspects of HTTP communication and they are set via setHTTPOptions function:

    ParameterDefault ValueMeaning
    connectionReusefalseWhether HTTP connection should be kept open after initial communication. Usable for frequent writes/queries.
    httpReadTimeout5000Timeout (ms) for reading server response

    Arduino - 图16Secure 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.

    📝 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:

    1. // Server certificate in PEM format, placed in the program (flash) memory to save RAM
    2. const char ServerCert[] PROGMEM = R"EOF(
    3. -----BEGIN CERTIFICATE-----
    4. MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
    5. TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
    6. cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
    7. WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
    8. ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
    9. MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
    10. h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
    11. 0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
    12. A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
    13. T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
    14. B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
    15. B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
    16. KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
    17. OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
    18. jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
    19. qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
    20. rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
    21. HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
    22. hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
    23. ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
    24. 3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
    25. NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
    26. ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
    27. TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
    28. jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
    29. oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
    30. 4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
    31. mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
    32. emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
    33. -----END CERTIFICATE-----
    34. )EOF";
    35. // Alternatively, use a fingerprint of server certificate to set trust. Works only for ESP8266.
    36. const char ServerCert[] PROGMEM = "cabd2a79a1076a31f21d253635cb039d4329a5e8";

    Arduino - 图17InfluxDb 2

    There are two ways to set the certificate or fingerprint to trust a server:

    • Use full param constructor
    1. // InfluxDB client instance with preconfigured InfluxCloud certificate
    2. InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert);
    • Use setConnectionParams function:
    1. // InfluxDB client instance
    2. InfluxDBClient client;
    3. void setup() {
    4. // configure client
    5. client.setConnectionParams(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert);
    6. }

    Arduino - 图18InfluxDb 1

    Use setConnectionParamsV1 function:

    1. // InfluxDB client instance
    2. InfluxDBClient client;
    3. void setup() {
    4. // configure client
    5. client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASSWORD, ServerCert);
    6. }

    Another important prerequisite to successfully validate a server or CA certificate is to have properly synchronized time. More on this in Configure Time.

    ℹ️ Time synchronization is not required for validating server certificate via SHA1 fingerprint.

    Arduino - 图19Skipping 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.

    📝 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:

    1. // InfluxDB client instance without a server certificate
    2. InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN);
    3. void setup() {
    4. // Set insecure connection to skip server certificate validation
    5. client.setInsecure();
    6. }

    ⚠️ Using untrusted connection is a security risk.

    Arduino - 图20Querying

    InfluxDB 2 and InfluxDB 1.7+ (with enabled flux) uses 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:

    1. #datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,long,string,string,string,string
    2. ,result,table,_start,_stop,_time,_value,SSID,_field,_measurement,device
    3. ,_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
    4. ,_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
    5. ,_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
    6. ,_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
    7. ,_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
    8. ,_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 typeGetterC type
    longgetLong()long
    unsignedLonggetUnsignedLong()unsigned long
    dateTime:RFC3339, dateTime:RFC3339NanogetDateTime()FluxDateTime
    boolgetBool()bool
    doublebooldouble
    string, base64binary, durationgetString()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.

    1. // Construct a Flux query
    2. // Query will find RSSI for last 24 hours for each connected WiFi network with this device computed by given selector function
    3. String query = "from(bucket: \"my-bucket\") |> range(start: -24h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\"";
    4. query += "and r.device == \"ESP32\")";
    5. query += "|> max()";
    6. // Send query to the server and get result
    7. FluxQueryResult result = client.query(query);
    8. // Iterate over rows. Even there is just one row, next() must be called at least once.
    9. while (result.next()) {
    10. // Get typed value for flux result column 'SSID'
    11. String ssid = result.getValueByName("SSID").getString();
    12. Serial.print("SSID '");
    13. Serial.print(ssid);
    14. Serial.print("' with RSSI ");
    15. // Get converted value for flux result column '_value' where there is RSSI value
    16. long value = result.getValueByName("_value").getLong();
    17. Serial.print(value);
    18. // Format date-time for printing
    19. // Format string according to http://www.cplusplus.com/reference/ctime/strftime/
    20. String timeStr = time.format("%F %T");
    21. Serial.print(" at ");
    22. Serial.print(timeStr);
    23. Serial.println();
    24. }
    25. // Check if there was an error
    26. if(result.getError() != "") {
    27. Serial.print("Query result error: ");
    28. Serial.println(result.getError());
    29. }

    Complete source code is available in QueryAggregated example.

    Arduino - 图21Parametrized Queries

    InfluxDB Cloud supports 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.

    Parameterized query example:

    ⚠️ Parameterized Queries are supported only in InfluxDB Cloud. There is no support in InfluxDB OSS currently.

    1. // Prepare query parameters
    2. QueryParams params;
    3. params.add("bucket", INFLUXDB_BUCKET);
    4. params.add("since", "-5m");
    5. params.add("device", DEVICE);
    6. params.add("rssiThreshold", -50);
    7. // Construct a Flux query using parameters
    8. // Parameters are accessed via the 'params' Flux object
    9. // Flux only supports only string, float and int as parameters. Duration can be converted from string.
    10. // Query will find RSSI less than defined threshold
    11. String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \
    12. |> filter(fn: (r) => r._measurement == \"wifi_status\") \
    13. |> filter(fn: (r) => r._field == \"rssi\") \
    14. |> filter(fn: (r) => r.device == params.device) \
    15. |> filter(fn: (r) => r._value < params.rssiThreshold)";
    16. // Print ouput header
    17. // Print composed query
    18. Serial.print("Querying with: ");
    19. Serial.println(query);
    20. // Send query to the server and get result
    21. FluxQueryResult result = client.query(query, params);
    22. //Print header
    23. Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI");
    24. for(int i=0;i<37;i++) {
    25. Serial.print('-');
    26. }
    27. Serial.println();
    28. // Iterate over rows. Even there is just one row, next() must be called at least once.
    29. int c = 0;
    30. while (result.next()) {
    31. // Get converted value for flux result column 'SSID'
    32. String ssid = result.getValueByName("SSID").getString();
    33. // Get converted value for flux result column '_value' where there is RSSI value
    34. long rssi = result.getValueByName("_value").getLong();
    35. // Get converted value for the _time column
    36. FluxDateTime time = result.getValueByName("_time").getDateTime();
    37. // Format date-time for printing
    38. // Format string according to http://www.cplusplus.com/reference/ctime/strftime/
    39. String timeStr = time.format("%F %T");
    40. // Print formatted row
    41. Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi);
    42. c++;
    43. }
    44. if(!c) {
    45. Serial.println(" No data found");
    46. }
    47. // Check if there was an error
    48. if(result.getError() != "") {
    49. Serial.print("Query result error: ");
    50. Serial.println(result.getError());
    51. }
    52. // Close the result
    53. result.close();

    Complete source code is available in QueryParams example.

    Arduino - 图22Original API

    Arduino - 图23Initialization

    1. #define INFLUXDB_HOST "192.168.0.32"
    2. #define INFLUXDB_PORT 1337
    3. #define INFLUXDB_DATABASE "test"
    4. //if used with authentication
    5. #define INFLUXDB_USER "user"
    6. #define INFLUXDB_PASS "password"
    7. // connect to WiFi
    8. Influxdb influx(INFLUXDB_HOST); // port defaults to 8086
    9. // or to use a custom port
    10. Influxdb influx(INFLUXDB_HOST, INFLUXDB_PORT);
    11. // set the target database
    12. influx.setDb(INFLUXDB_DATABASE);
    13. // or use a db with auth
    14. influx.setDbAuth(INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASS) // with authentication
    15. // To use the v2.0 InfluxDB
    16. influx.setVersion(2);
    17. influx.setOrg("myOrganization");
    18. influx.setBucket("myBucket");
    19. influx.setToken("myToken");
    20. influx.setPort(8086);

    Arduino - 图24Sending a single measurement

    Using an InfluxData object:

    1. // create a measurement object
    2. InfluxData measurement ("temperature");
    3. measurement.addTag("device", d2);
    4. measurement.addTag("sensor", "dht11");
    5. measurement.addValue("value", 24.0);
    6. // write it into db
    7. influx.write(measurement);

    Using raw-data

    1. influx.write("temperature,device=d2,sensor=dht11 value=24.0")

    Arduino - 图25Write multiple data points at once

    Batching measurements and send them with a single request will result in a much higher performance.

    1. InfluxData measurement1 = readTemperature()
    2. influx.prepare(measurement1)
    3. InfluxData measurement2 = readLight()
    4. influx.prepare(measurement2)
    5. InfluxData measurement3 = readVoltage()
    6. influx.prepare(measurement3)
    7. // writes all prepared measurements with a single request into db.
    8. boolean success = influx.write();

    Arduino - 图26Troubleshooting

    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/InfluxDBClient.cpp uncomment line 32:

    1. // Uncomment bellow in case of a problem and rebuild sketch
    2. #define INFLUXDB_CLIENT_DEBUG

    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.

    Arduino - 图27Contributing

    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.

    Arduino - 图28License

    The InfluxDB Arduino Client is released under the MIT License.