Skip to content

Commit 62c51c9

Browse files
authored
Merge pull request #117 from bonitoo-io/feat/api_improvements
feat: added InfluxDBClient::pointToLineProtocol function
2 parents cba615e + 2a83222 commit 62c51c9

File tree

11 files changed

+71
-33
lines changed

11 files changed

+71
-33
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# Changelog
22
## 3.5.1 [in progress]
3+
### Features
4+
- [#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
5+
36
### Fixes
47
- [#114](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/114) - Renamed `getRemaingRetryTime()`->`getRemainingRetryTime()`
58
- [#115](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/115) - Restored writing capability after a connection failure

examples/BasicWrite/BasicWrite.ino

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ void loop() {
8181
sensor.addField("rssi", WiFi.RSSI());
8282
// Print what are we exactly writing
8383
Serial.print("Writing: ");
84-
Serial.println(sensor.toLineProtocol());
84+
Serial.println(client.pointToLineProtocol(sensor));
8585
// If no Wifi signal, try to reconnect it
8686
if ((WiFi.RSSI() == 0) && (wifiMulti.run() != WL_CONNECTED))
8787
Serial.println("Wifi connection lost");

examples/SecureBatchWrite/SecureBatchWrite.ino

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ void loop() {
120120

121121
// Print what are we exactly writing
122122
Serial.print("Writing: ");
123-
Serial.println(sensorNetworks.toLineProtocol());
123+
Serial.println(client.pointToLineProtocol(sensorNetworks));
124124

125125
// Write point into buffer - low priority measures
126126
client.writePoint(sensorNetworks);
@@ -134,7 +134,7 @@ void loop() {
134134

135135
// Print what are we exactly writing
136136
Serial.print("Writing: ");
137-
Serial.println(sensorStatus.toLineProtocol());
137+
Serial.println(client.pointToLineProtocol(sensorStatus));
138138

139139
// Write point into buffer - high priority measure
140140
client.writePoint(sensorStatus);

examples/SecureWrite/SecureWrite.ino

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ void loop() {
9191
sensor.addField("rssi", WiFi.RSSI());
9292
// Print what are we exactly writing
9393
Serial.print("Writing: ");
94-
Serial.println(sensor.toLineProtocol());
94+
Serial.println(client.pointToLineProtocol(sensor));
9595
// If no Wifi signal, try to reconnect it
9696
if ((WiFi.RSSI() == 0) && (wifiMulti.run() != WL_CONNECTED))
9797
Serial.println("Wifi connection lost");

src/InfluxDbClient.cpp

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,11 @@ static const char UserAgent[] PROGMEM = "influxdb-client-arduino/" INFLUXDB_CLIE
4444
//#define INFLUXDB_CLIENT_DEBUG_ENABLE
4545
#include "util/debug.h"
4646

47-
static const char UnitialisedMessage[] PROGMEM = "Unconfigured instance";
47+
static const char UninitializedMessage[] PROGMEM = "Unconfigured instance";
4848
static const char TooEarlyMessage[] PROGMEM = "Cannot send request yet because of applied retry strategy. Remaining ";
4949
// This cannot be put to PROGMEM due to the way how it is used
5050
static const char RetryAfter[] = "Retry-After";
51-
static const char TransferEnconding[] = "Transfer-Encoding";
51+
static const char TransferEncoding[] = "Transfer-Encoding";
5252

5353
static String escapeJSONString(String &value);
5454
#if defined(ESP8266)
@@ -110,6 +110,7 @@ void InfluxDBClient::setConnectionParamsV1(const char *serverUrl, const char *db
110110

111111
bool InfluxDBClient::init() {
112112
INFLUXDB_CLIENT_DEBUG("Init\n");
113+
INFLUXDB_CLIENT_DEBUG(" Library version: " INFLUXDB_CLIENT_VERSION "\n");
113114
INFLUXDB_CLIENT_DEBUG(" Server url: %s\n", _serverUrl.c_str());
114115
INFLUXDB_CLIENT_DEBUG(" Org: %s\n", _org.c_str());
115116
INFLUXDB_CLIENT_DEBUG(" Bucket: %s\n", _bucket.c_str());
@@ -340,7 +341,7 @@ bool InfluxDBClient::writePoint(Point & point) {
340341
if(_writeOptions._writePrecision != WritePrecision::NoTime && !point.hasTime()) {
341342
point.setTime(_writeOptions._writePrecision);
342343
}
343-
String line = point.toLineProtocol(_writeOptions._defaultTags);
344+
String line = pointToLineProtocol(point);
344345
return writeRecord(line);
345346
}
346347
return false;
@@ -504,7 +505,6 @@ bool InfluxDBClient::flushBufferInternal(bool flashOnlyFull) {
504505
return success;
505506
}
506507

507-
508508
void InfluxDBClient::dropCurrentBatch() {
509509
delete _writeBuffer[_batchPointer];
510510
_writeBuffer[_batchPointer] = nullptr;
@@ -516,13 +516,17 @@ void InfluxDBClient::dropCurrentBatch() {
516516
// we reached buffer size, that means buffer was full and now lower ceiling
517517
_bufferCeiling = _bufferPointer;
518518
}
519-
INFLUXDB_CLIENT_DEBUG("[D] Droped batch, batchpointer: %d\n", _batchPointer);
519+
INFLUXDB_CLIENT_DEBUG("[D] Dropped batch, batchpointer: %d\n", _batchPointer);
520+
}
521+
522+
String InfluxDBClient::pointToLineProtocol(const Point& point) {
523+
return point.toLineProtocol(_writeOptions._defaultTags);
520524
}
521525

522526
bool InfluxDBClient::validateConnection() {
523527
if(!_wifiClient && !init()) {
524528
_lastStatusCode = 0;
525-
_lastErrorResponse = FPSTR(UnitialisedMessage);
529+
_lastErrorResponse = FPSTR(UninitializedMessage);
526530
return false;
527531
}
528532
// on version 1.x /ping will by default return status code 204, without verbose
@@ -550,14 +554,14 @@ void InfluxDBClient::beforeRequest() {
550554
if(_authToken.length() > 0) {
551555
_httpClient.addHeader(F("Authorization"), "Token " + _authToken);
552556
}
553-
const char * headerKeys[] = {RetryAfter, TransferEnconding} ;
557+
const char * headerKeys[] = {RetryAfter, TransferEncoding} ;
554558
_httpClient.collectHeaders(headerKeys, 2);
555559
}
556560

557561
int InfluxDBClient::postData(const char *data) {
558562
if(!_wifiClient && !init()) {
559563
_lastStatusCode = 0;
560-
_lastErrorResponse = FPSTR(UnitialisedMessage);
564+
_lastErrorResponse = FPSTR(UninitializedMessage);
561565
return 0;
562566
}
563567
if(data) {
@@ -607,7 +611,7 @@ FluxQueryResult InfluxDBClient::query(String fluxQuery) {
607611
}
608612
if(!_wifiClient && !init()) {
609613
_lastStatusCode = 0;
610-
_lastErrorResponse = FPSTR(UnitialisedMessage);
614+
_lastErrorResponse = FPSTR(UninitializedMessage);
611615
return FluxQueryResult(_lastErrorResponse);
612616
}
613617
INFLUXDB_CLIENT_DEBUG("[D] Query to %s\n", _queryUrl.c_str());
@@ -630,8 +634,8 @@ FluxQueryResult InfluxDBClient::query(String fluxQuery) {
630634
afterRequest(200);
631635
if(_lastStatusCode == 200) {
632636
bool chunked = false;
633-
if(_httpClient.hasHeader(TransferEnconding)) {
634-
String header = _httpClient.header(TransferEnconding);
637+
if(_httpClient.hasHeader(TransferEncoding)) {
638+
String header = _httpClient.header(TransferEncoding);
635639
chunked = header.equalsIgnoreCase("chunked");
636640
}
637641
INFLUXDB_CLIENT_DEBUG("[D] chunked: %s\n", chunked?"true":"false");

src/InfluxDbClient.h

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,15 @@ class InfluxDBClient {
110110
// authToken - InfluxDB 2 authorization token
111111
// 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.
112112
void setConnectionParams(const char *serverUrl, const char *org, const char *bucket, const char *authToken, const char *certInfo = nullptr);
113-
// Sets parameters for connection to InfuxDB 1
113+
// Sets parameters for connection to InfluxDB 1
114114
// serverUrl - url of the InfluxDB server (e.g. http://localhost:8086)
115115
// db - database name where to store or read data
116116
// user - Optional. User name, in case of server requires authetication
117117
// password - Optional. User password, in case of server requires authetication
118118
// certInfo - Optional. InfluxDB server trusted certificate (or CA certificate) or certificate SHA1 fingerprint. Should be stored in PROGMEM. Only in case of https connection.
119119
void setConnectionParamsV1(const char *serverUrl, const char *db, const char *user = nullptr, const char *password = nullptr, const char *certInfo = nullptr);
120+
// Creates line protocol string from point data and optional default tags set in WriteOptions.
121+
String pointToLineProtocol(const Point& point);
120122
// Validates connection parameters by conecting to server
121123
// Returns true if successful, false in case of any error
122124
bool validateConnection();
@@ -126,7 +128,7 @@ class InfluxDBClient {
126128
// Writes record represented by Point to buffer
127129
// Returns true if successful, false in case of any error
128130
bool writePoint(Point& point);
129-
// Sends Flux query and returns FluxQueryResult object for subsequentialy reading flux query response.
131+
// Sends Flux query and returns FluxQueryResult object for subsequently reading flux query response.
130132
// Use FluxQueryResult::next() method to iterate over lines of the query result.
131133
// Always call of FluxQueryResult::close() when reading is finished. Check FluxQueryResult doc for more info.
132134
FluxQueryResult query(String fluxQuery);
@@ -208,7 +210,7 @@ class InfluxDBClient {
208210
uint8_t _bufferCeiling = 0;
209211
// Index of bath start for next write
210212
uint8_t _batchPointer = 0;
211-
// Last time in sec bufer has been sucessfully flushed
213+
// Last time in sec buffer has been successfully flushed
212214
uint32_t _lastFlushed = 0;
213215
// Last time in ms we made are a request to server
214216
uint32_t _lastRequestTime = 0;
@@ -218,7 +220,7 @@ class InfluxDBClient {
218220
String _lastErrorResponse;
219221
// Underlying HTTPClient instance
220222
HTTPClient _httpClient;
221-
// Underlying connenction object
223+
// Underlying connection object
222224
WiFiClient *_wifiClient = nullptr;
223225
// Certificate info
224226
const char *_certInfo = nullptr;
@@ -237,7 +239,7 @@ class InfluxDBClient {
237239
void setUrls();
238240
// Ensures buffer has required size
239241
void reserveBuffer(int size);
240-
// Drops current batcj and advances batch pointer
242+
// Drops current batch and advances batch pointer
241243
void dropCurrentBatch();
242244
// Writes all points in buffer, with respect to the batch size, and in case of success clears the buffer.
243245
// flashOnlyFull - whether to flush only full batches

src/Point.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,15 @@ void Point::putField(String name, String value) {
6161

6262
String Point::toLineProtocol(String includeTags) const {
6363
String line = _measurement;
64-
line.reserve(1 + _tags.length() + 1 + includeTags.length() + 1 + _fields.length() + 1 + _timestamp.length());
65-
if(hasTags()) {
66-
line += ",";
67-
line += _tags;
68-
}
64+
line.reserve(1 + includeTags.length() + 1 + _tags.length() + 1 + _fields.length() + 1 + _timestamp.length());
6965
if(includeTags.length()>0) {
7066
line += ",";
7167
line += includeTags;
7268
}
69+
if(hasTags()) {
70+
line += ",";
71+
line += _tags;
72+
}
7373
if(hasFields()) {
7474
line += " ";
7575
line += _fields;

src/Point.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ class Point {
6868
// True if a point contains timestamp
6969
bool hasTime() const { return _timestamp.length() > 0; }
7070
// Creates line protocol with optionaly added tags
71+
[[deprecated("Use InfluxDBClient::pointToLineProtocol()")]]
7172
String toLineProtocol(String includeTags = "") const;
7273
// returns current timestamp
7374
String getTime() const { return _timestamp; }

test/Test.cpp

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ void Test::testEcaping() {
197197
w.addDefaultTag("dta=g","dval=ue");
198198
w.addDefaultTag("dtag","dvalue");
199199
line = p.toLineProtocol(w._defaultTags);
200-
TEST_ASSERTM(line == "t\\\re=s\\\nt\\\t_t\\ e\"s\\,t,ta\\=g=val\\=ue,ta\\\tg=val\\\tue,ta\\\rg=val\\\rue,ta\\\ng=val\\\nue,ta\\ g=valu\\ e,ta\\,g=valu\\,e,tag=value,ta\"g=val\"ue,dta\\=g=dval\\=ue,dtag=dvalue fie\\=ld=\"val=ue\",fie\\\tld=\"val\tue\",fie\\\rld=\"val\rue\",fie\\\nld=\"val\nue\",fie\\ ld=\"val ue\",fie\\,ld=\"val,ue\",fie\"ld=\"val\\\"ue\"", line);
200+
TEST_ASSERTM(line == "t\\\re=s\\\nt\\\t_t\\ e\"s\\,t,dta\\=g=dval\\=ue,dtag=dvalue,ta\\=g=val\\=ue,ta\\\tg=val\\\tue,ta\\\rg=val\\\rue,ta\\\ng=val\\\nue,ta\\ g=valu\\ e,ta\\,g=valu\\,e,tag=value,ta\"g=val\"ue fie\\=ld=\"val=ue\",fie\\\tld=\"val\tue\",fie\\\rld=\"val\rue\",fie\\\nld=\"val\nue\",fie\\ ld=\"val ue\",fie\\,ld=\"val,ue\",fie\"ld=\"val\\\"ue\"", line);
201201
TEST_END();
202202
}
203203

@@ -230,7 +230,7 @@ void Test::testPoint() {
230230

231231
String defaultTags="dtag=val";
232232
line = p.toLineProtocol(defaultTags);
233-
testLine = "test,tag1=tagvalue,dtag=val fieldInt=-23i,fieldBool=true,fieldFloat1=1.12,fieldFloat2=1.12345,fieldDouble1=1.12,fieldDouble2=1.12345,fieldChar=\"A\",fieldUChar=1i,fieldUInt=23i,fieldLong=123456i,fieldULong=123456i,fieldString=\"text test\"";
233+
testLine = "test,dtag=val,tag1=tagvalue fieldInt=-23i,fieldBool=true,fieldFloat1=1.12,fieldFloat2=1.12345,fieldDouble1=1.12,fieldDouble2=1.12345,fieldChar=\"A\",fieldUChar=1i,fieldUInt=23i,fieldLong=123456i,fieldULong=123456i,fieldString=\"text test\"";
234234
TEST_ASSERTM(line == testLine, line);
235235

236236
p.clearTags();
@@ -1804,6 +1804,15 @@ void Test::testDefaultTags() {
18041804
TEST_INIT("testDefaultTags");
18051805

18061806
InfluxDBClient client(Test::apiUrl, Test::orgName, Test::bucketName, Test::token);
1807+
1808+
Point pt("test");
1809+
pt.addTag("tag1", "tagvalue");
1810+
pt.addField("fieldInt", -23);
1811+
String testLine = "test,tag1=tagvalue fieldInt=-23i";
1812+
String line = client.pointToLineProtocol(pt);
1813+
TEST_ASSERTM(line == testLine, line);
1814+
1815+
18071816

18081817
TEST_ASSERT(waitServer(Test::managementUrl, true));
18091818
for (int i = 0; i < 5; i++) {
@@ -1827,6 +1836,9 @@ void Test::testDefaultTags() {
18271836
deleteAll(Test::apiUrl);
18281837

18291838
client.setWriteOptions(WriteOptions().addDefaultTag("dtag1","dval1").addDefaultTag("dtag2","dval2"));
1839+
testLine = "test,dtag1=dval1,dtag2=dval2,tag1=tagvalue fieldInt=-23i";
1840+
line = client.pointToLineProtocol(pt);
1841+
TEST_ASSERTM(line == testLine, line);
18301842

18311843
for (int i = 0; i < 5; i++) {
18321844
Point *p = createPoint("test1");

test/TestSupport.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ void printFreeHeap() {
4242

4343
int httpPOST(String url, String mess) {
4444
HTTPClient http;
45+
http.setReuse(false);
4546
int code = 0;
4647
if(http.begin(url)) {
4748
code = http.POST(mess);
@@ -52,12 +53,14 @@ int httpPOST(String url, String mess) {
5253

5354
int httpGET(String url) {
5455
HTTPClient http;
56+
http.setReuse(false);
5557
int code = 0;
5658
if(http.begin(url)) {
5759
code = http.GET();
5860
if(code != 204) {
59-
Serial.print("[TD] ");
60-
Serial.println(http.getString());
61+
//Serial.print("[TD] ");
62+
//String res = http.getString();
63+
//Serial.println(res);
6164
}
6265
http.end();
6366
}

0 commit comments

Comments
 (0)