@@ -20,6 +20,7 @@ Influxdb::Influxdb(String host, uint16_t port) {
2020
2121/* *
2222 * Set the database to be used.
23+ * @param db the Influx Database to be written to.
2324 */
2425void Influxdb::setDb (String db) {
2526 _db = String (db);
@@ -36,12 +37,61 @@ void Influxdb::setDbAuth(String db, String user, String pass) {
3637 begin ();
3738}
3839
40+ /* *
41+ * Set the Bucket to be used v2.0 ONLY.
42+ * @param bucket the InfluxDB Bucket which must already exist
43+ */
44+ void Influxdb::setBucket (String bucket) {
45+ _bucket = String (bucket);
46+ begin ();
47+ }
48+
49+ /* *
50+ * Set the influxDB port.
51+ * @param port v1.x uses 8086, v2 uses 9999
52+ */
53+ void Influxdb::setPort (uint16 port){
54+ _port = port;
55+ begin ();
56+ }
57+ /* *
58+ * Set the Organization to be used v2.0 ONLY
59+ * @param org the Name of the organization unit to use which must already exist
60+ */
61+ void Influxdb::setOrg (String org){
62+ _org = String (org);
63+ begin ();
64+ }
65+
66+ /* *
67+ * Set the authorization token v2.0 ONLY
68+ * @param token the Auth Token from InfluxDBv2 *required*
69+ */
70+ void Influxdb::setToken (String token){
71+ _token = String (token);
72+ begin ();
73+ }
74+
75+ /* *
76+ * Set the version of InfluxDB to write to
77+ * @param version accepts 1 for version 1.x or 2 for version 2.x
78+ */
79+ void Influxdb::setVersion (uint16_t version){
80+ _db_v = version;
81+ begin ();
82+ }
83+
3984void Influxdb::begin () {
4085 // TODO: recreate HttpClient on db change?
41- if (_user && _pass) {
42- http.begin (_host, _port, " /write?u=" + _user + " &p=" + _pass + " &db=" + _db);
86+ if (_db_v == 2 ){
87+ http.begin (_host, _port, " /api/v2/write?org=" + _org + " &bucket=" + _bucket);
88+ http.addHeader (" Authorization" , " Token " + _token);
4389 } else {
44- http.begin (_host, _port, " /write?db=" + _db);
90+ if (_user && _pass) {
91+ http.begin (_host, _port, " /write?u=" + _user + " &p=" + _pass + " &db=" + _db);
92+ } else {
93+ http.begin (_host, _port, " /write?db=" + _db);
94+ }
4595 }
4696 http.addHeader (" Content-Type" , " text/plain" );
4797}
@@ -76,9 +126,17 @@ boolean Influxdb::write(InfluxData data) { return write(data.toString()); }
76126 * for a list of error codes.
77127 */
78128boolean Influxdb::write (String data) {
79- Serial.print (" --> writing to " + _db + " :\n " );
80- Serial.println (data);
81-
129+ if (_db_v == 2 ){
130+ if (_token == NULL || _token.length () < 10 ){
131+ Serial.println (" #####\n Invalid Access Token\n #####" );
132+ return false ;
133+ }
134+ Serial.print (" --> writing to host: " + _host + " Port: " + _port + " URL: /api/v2/write?org=" + _org + " &bucket=" + _bucket + " :\n " );
135+ Serial.println (data);
136+ } else {
137+ Serial.print (" --> writing to " + _db + " :\n " );
138+ Serial.println (data);
139+ }
82140 int httpResponseCode = http.POST (data);
83141 Serial.print (" <-- Response: " );
84142 Serial.print (httpResponseCode);
0 commit comments