Coder Social home page Coder Social logo

influxdb-client-dart's Introduction

influxdb-client-dart

CircleCI codecov Platforms Pub Version License GitHub issues GitHub pull requests Slack Status

This repository contains the reference Dart client for the InfluxDB 2.x. It works on all platforms including web, server, and Flutter. Please submit issues and pull requests, help out, or just give encouragement.

Documentation

This section contains links to the client library documentation.

Features

InfluxDB 2.x client supports:

  • Querying data using the Flux language
    • Streaming result to Stream<FluxRecord>
  • Writing data
    • batched in chunks on background
    • automatic retries on write failures
  • Management API
    • provides all other InfluxDB 2.x APIs for managing
      • health check
      • sources, buckets
      • tasks
      • authorizations
      • ...

Supported Platforms

Library works in web, server, and Flutter.

Installation

Dart developer can add it as a dependency in their pubspec.yaml:

dependencies:
  influxdb_client: ^2.2.0

Import

import 'package:influxdb_client/api.dart';

Usage

Important: You should call close() at the end of your application to release allocated resources.

Creating a client

Specify url and token via parameters:

var client = InfluxDBClient(
    url: 'http://localhost:8086',
    token: 'my-token',
    org: 'my-org',
    bucket: 'my-bucket',
    debug: true);

Client Options

Option Description Type Default
url InfluxDB url String none
bucket Default destination bucket for writes String none
org Default organization bucket for writes String none
debug Enable verbose logging of underlying http client bool false

InfluxDB 1.8 API compatibility

var client = InfluxDBClient.connectV1(
  url: 'http://localhost:8086',
  database: 'mydb',
  retentionPolicy: 'autogen',
  username: 'my-username',
  password: 'my-password',
);

Writes

The WriteApi supports asynchronous writes into InfluxDB 2.x.

The data could be written as:

  1. String that is formatted as a InfluxDB's Line Protocol
  2. Data Point structure
  3. Array of above items

The following example demonstrates how to write data with different type of records. For further information see docs and examples.

import 'package:influxdb_client/api.dart';

main() async {
  var client = InfluxDBClient(
      url: 'http://localhost:8086',
      token: 'my-token',
      org: 'my-org',
      bucket: 'my-bucket',
      debugEnabled: true);

  var writeApi = WriteService(client);

  var point = Point('h2o')
      .addTag('location', 'Prague')
      .addField('level', 1.12345)
      .time(DateTime.now().toUtc());

  await writeApi.write(point).then((value) {
    print('Write completed 1');
  }).catchError((exception) {
    // error block
    print("Handle write error here!");
    print(exception);
  });

}

WriteOptions

Settings for WriteService like batching, default tags, retry strategy, precision, can customized in `WriteOptions'.

Example how to modify default WriteOptions:

  var client = InfluxDBClient(
      url: 'http://localhost:8086',
      token: 'my-token',
      org: 'my-org',
      bucket: 'my-bucket',
      debug: true);

  var writeApi = client.getWriteService(WriteOptions().merge(
      precision: WritePrecision.s,
      batchSize: 100,
      flushInterval: 5000,
      gzip: true));

Queries

The result retrieved by QueryService could be formatted as a:

Query to FluxRecord

import 'package:influxdb_client/api.dart';

void main() async {
  var client = InfluxDBClient(
    url: 'http://localhost:8086',
    token: 'my-token',
    org: 'my-org',
    bucket: 'my-bucket',
  );

  var queryService = client.getQueryService();

  var recordStream = await queryService.query('''
  from(bucket: "my-bucket")
  |> range(start: 0)
  |> filter(fn: (r) => r["_measurement"] == "cpu")
  |> filter(fn: (r) => r["cpu"] == "cpu-total")
  |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
  |> yield(name: "mean")
  ''');

  var count = 0;
  await recordStream.forEach((record) {
    print(
        'record: ${count++} ${record['_time']}: ${record['host']} ${record['cpu']} ${record['_value']}');
  });

  client.close();
}

Query to String

import 'package:influxdb_client/api.dart';

main() async {
  var client = InfluxDBClient(url: 'http://localhost:8086',
      token: 'my-token', org: 'my-org', bucket: 'my-bucket');

  var queryService = client.getQueryService(client);

  var rawCSV = await queryService.queryRaw('''
      from(bucket: "my-bucket")
        |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
        |> filter(fn: (r) => r["_measurement"] == "h2o")
        |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
        |> yield(name: "mean")''');

  print(rawCSV);
  
}

Parameterized 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, currently there is no support in InfluxDB OSS.

import 'package:influxdb_client/api.dart';

void main() async {
  var client = InfluxDBClient(
    url: 'http://localhost:8086',
    token: 'my-token',
    org: 'my-org',
    bucket: 'my-bucket',
  );

  var queryService = client.getQueryService();

  var queryService = client.getQueryService();
  var queryString = '''
       from(bucket: params.bucketParam)
            |> range(start: duration(v: params.startParam))
            |> filter(fn: (r) => r["_measurement"] == "weather" 
                             and r["location"] == "Prague")''';
  var queryParams = {'bucketParam':'my-bucket', 'startParam':'-10d'};
  var query = Query(query: queryString, params: queryParams);

  // Using string for query and Map for params
  var recordMap = await queryService.query(queryString, params: queryParams);

  // Using Query class
  var recordClass = await queryService.query(query);

  client.close();
}

Delete points

The DeleteService supports deletes points from an InfluxDB bucket.

InfluxDB uses an InfluxQL-like predicate syntax to determine what data points to delete.

import 'package:influxdb_client/api.dart';

void main() async {
  var client = InfluxDBClient(
      url: 'http://localhost:8086',
      token: 'my-token',
      org: 'my-org',
      bucket: 'my-bucket',
      debugEnabled: true);

  await client
      .getDeleteService()
      .delete(
      predicate: '_measurement="temperature"',
      start: '1970-01-01T00:00:00.000000001Z',
      stop: DateTime.now().toUtc().toIso8601String(),
      bucket: 'my-bucket',
      org: 'my-org')
      .catchError((e) => print(e));

  var queryService = client.getQueryService();

  var fluxQuery = '''
  from(bucket: "my-bucket")
  |> range(start: -1d)
  |> filter(fn: (r) => r["_measurement"] == "temperature")
  ''';

  // should be empty
  var records = await queryService.query(fluxQuery);
  assert(await records.isEmpty);

  client.close();
}

Management API

The client supports following management API:

API docs
AuthorizationsAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Authorizations
BucketsAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Buckets
DBRPsAPI https://docs.influxdata.com/influxdb/latest/api/#tag/DBRPs
DeleteAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Delete
HealthAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Health
LabelsAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Labels
OrganizationsAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Organizations
PingAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Ping
ReadyAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Ready
SecretsAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Secrets
SetupAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Setup
TasksAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Tasks
UsersAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Users
VariablesAPI https://docs.influxdata.com/influxdb/latest/api/#tag/Variables

The following example demonstrates how to use a InfluxDB 2.x Management API to create new bucket. For further information see docs and examples.

import 'package:influxdb_client/api.dart';

void main() async {
// Initialize Client and API
  var client = InfluxDBClient(
      url: 'http://localhost:8086', token: 'my-token', org: 'my-org');

  //check server availability
  await client.getPingApi().getPing();

  var orgs = await client.getOrganizationsApi().getOrgs();
  var myOrgId = orgs.orgs.first.id;

  var bucketsApi = client.getBucketsApi();
  var bucketName = 'bucket-my-org';

  // find and delete bucket 'bucket-my-org'
  var buckets = await bucketsApi.getBuckets(name: bucketName);
  if (buckets.buckets.isNotEmpty) {
    var bucketID = buckets.buckets.first.id;
    await bucketsApi.deleteBucketsID(bucketID);
    print('Bucket $bucketID was deleted.');
  }

// Bucket configuration
  var request = PostBucketRequest(
      orgID: myOrgId,
      name: bucketName,
      retentionRules: [
        RetentionRule(type: RetentionRuleTypeEnum.expire, everySeconds: 3600)
      ]);

  var bucket = await bucketsApi.postBuckets(request);

// Create Authorization with permission to read/write created bucket
  var bucketResource =
  Resource(type: ResourceTypeEnum.buckets, id: bucket.id, orgID: myOrgId);

// Authorization configuration
  var auth = AuthorizationPostRequest(
      description: 'Authorization to read/write bucket:${bucket.name}',
      orgID: myOrgId,
      permissions: [
        Permission(action: PermissionActionEnum.read, resource: bucketResource),
        Permission(action: PermissionActionEnum.write, resource: bucketResource)
      ]);

// Create Authorization
  var authorizationsApi = client.getAuthorizationsApi();
  var authorization = await authorizationsApi.postAuthorizations(auth);

// Print token
  var token = authorization.token;
  print('The bucket: \'${bucket.name}\' is successfully created.');
  print('The following token can be used to read/write: ${token}');

  client.close();
}

Proxy configuration

By default the HttpClient uses the proxy configuration available from the environment, see findProxyFromEnvironment.

export http_proxy="PROXY http://localhost:8080"

Initialize a proxy from code:

HttpClient httpClient = HttpClient();
httpClient.findProxy = (url) => "PROXY localhost:8080";
var client = IOClient(httpClient);

var influxdb = InfluxDBClient(
    url: 'http://localhost:8086',
    token: 'my-token',
    org: 'my-org',
    bucket: 'my-bucket',
    client: client,
    followRedirects: true,
    maxRedirects: 5,
    debug: true);

To turn off the use of proxies set the findProxy property to null.

Client automatically follows HTTP redirects for all GET and HEAD requests with status codes 301, 302, 303, 307, 308. The default redirect policy is to follow up to 5 consecutive requests.

write and query APIs also support an automatic redirect of POST requests. You can disable followRedirects and change default maxRedirects on InfluxDBClient instance.

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.

Build Requirements:

  • dart 2.X

Build source and test targets:

./scripts/influxdb-restart.sh
dart test

Check code coverage:

./scripts/influxdb-restart.sh
dart test --enable-code-coverage

License

The client is available as open source under the terms of the MIT License.

influxdb-client-dart's People

Contributors

alespour avatar bednar avatar dependabot[bot] avatar janmoritzmeyer avatar michaelahojna avatar rhajek avatar tysonkamp avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

influxdb-client-dart's Issues

SocketExceptions while writing

Every time I'm trying to write I'll get
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: SocketException: The remote computer rejected the connection request.
(OS Error: The remote computer rejected the connection request.
, errno = 1225), address = localhost, port = 58700

Reproduce
image

  • InfluxDB Version: 2.2.0
  • Platform: Flutter Debug mode in windows

aggregateWindow() resulting in InfluxDBException: statusCode = 500, code = null, message = null

Hello,

I'm using the latest client #26 (merged into master) and are running into the following issue with Influx 1.8.5. The query is working fine against our managed influxdb cloud instance, thus I assume it's somehow related to the client or 1.8.5. It would be great if you could have a look at the issue.

Describe the bug
Using aggregateWindow() in a flux query result in an exception against InfluxDB 1.8.5 OSS using the latest Flutter client #26 (merged into master) -- InfluxDBException: statusCode = 500, code = null, message = null

To Reproduce
Run a query using aggregateWindow() against a 1.8.5 instance.

Expected behavior
The query to return aggregated results.

Specifications:

  • Client Version: influxdb_client (master branch at time of posting with #26 merged)
  • InfluxDB Version: 1.8.5 OSS
  • Platform: Flutter (running client on iOS)

Additional context
The query works

  • fine on managed InfluxData cloud
  • on the local 1.8.5 if we delete aggregatedWindow()

The following code produces the exception:

      InfluxDBClient influxClient = InfluxDbService().client;
      QueryService queryService = influxClient.getQueryService();

      String fluxQuery = '''
        from(bucket: "my-bucket")
          |> range(start: -5m)
          |> filter(fn: (r) => r["_measurement"] == "pi_sensors")
          |> filter(fn: (r) => r["_field"] == "cpu_usage")
          |> aggregateWindow(every: 10s, fn: mean, createEmpty: false)
          |> yield(name: "mean")
      ''';

      Stream<FluxRecord> recordStream = await queryService.query(fluxQuery);
      await recordStream.forEach((record) {
        // DO SOMETING
      });

and the output from debug

flutter: >> POST http://10.10.10.1:8086/api/v2/query?org =====
flutter: >> headers: {Accept-Encoding: gzip, Content-Type: application/json; charset=utf-8, Authorization: Token data_extractor:sk2RV5XuQjjtEZJj, User-Agent: influxdb-client-dart/2.1.0-dev}
flutter: >> contentLength: 499
flutter: << status: 500 - contentLength: null
flutter: << headers: {transfer-encoding: chunked, date: Wed, 05 Jan 2022 18:47:39 GMT, x-influxdb-version: 1.8.5, content-type: text/csv; charset=utf-8, x-influxdb-error: panic: runtime error: invalid memory address or nil pointer dereference, request-id: f4dcdfc5-6e57-11ec-b7c6-0242ac120007, x-influxdb-build: OSS, x-request-id: f4dcdfc5-6e57-11ec-b7c6-0242ac120007}
flutter: InfluxDBException: statusCode = 500, code = null, message = null
flutter: << status: 500 - contentLength: null
flutter: << headers: {transfer-encoding: chunked, date: Wed, 05 Jan 2022 18:47:39 GMT, x-influxdb-version: 1.8.5, content-type: text/csv; charset=utf-8, x-influxdb-error: panic: runtime error: invalid memory address or nil pointer dereference, request-id: f4dc65ce-6e57-11ec-b7c5-0242ac120007, x-influxdb-build: OSS, x-request-id: f4dc65ce-6e57-11ec-b7c5-0242ac120007}
flutter: InfluxDBException: statusCode = 500, code = null, message = null

Thanks a lot!

Connection problem - Socket Exception

Hi, I trying to connect to Influx but unfortunately I'm getting an error:
I/flutter ( 2913): >> GET http://localhost:8086/ping =====
I/flutter ( 2913): >> headers: {Authorization: Token UR5_tNrPq5fAjuL6TfX_G7KQEozzvZWT35a7xbVbojoqRwba38tU6lhWEMPoJasvMmaf9D2g793mfbBCZVzLsQ==, User-Agent: influxdb-client-dart/2.1.0}
I/flutter ( 2913): >> contentLength: 0
E/flutter ( 2913): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = localhost, port = 42422
E/flutter ( 2913): #0 _NativeSocket.startConnect (dart:io-patch/socket_patch.dart:681:35)
E/flutter ( 2913): #1 _RawSocket.startConnect (dart:io-patch/socket_patch.dart:1808:26)
E/flutter ( 2913): #2 RawSocket.startConnect (dart:io-patch/socket_patch.dart:27:23)
E/flutter ( 2913): #3 Socket._startConnect (dart:io-patch/socket_patch.dart:2027:22)
E/flutter ( 2913): #4 Socket.startConnect (dart:io/socket.dart:784:21)
E/flutter ( 2913): #5 _ConnectionTarget.connect (dart:_http/http_impl.dart:2439:18)
E/flutter ( 2913): #6 _HttpClient._getConnection.connect (dart:_http/http_impl.dart:2808:12)
E/flutter ( 2913): #7 _HttpClient._getConnection (dart:_http/http_impl.dart:2813:12)
E/flutter ( 2913): #8 _HttpClient._openUrl (dart:_http/http_impl.dart:2697:12)
E/flutter ( 2913): #9 _HttpClient.openUrl (dart:_http/http_impl.dart:2569:7)
E/flutter ( 2913): #10 IOClient.send (package:http/src/io_client.dart:35:38)
E/flutter ( 2913): #11 LoggingClient.send (package:influxdb_client/client/influxdb_client.dart:316:25)
E/flutter ( 2913): #12 BaseClient._sendUnstreamed (package:http/src/base_client.dart:93:38)
E/flutter ( 2913): #13 BaseClient.get (package:http/src/base_client.dart:27:7)
E/flutter ( 2913): #14 ApiClient.invokeAPI (package:influxdb_client/api_client.dart:152:32)
E/flutter ( 2913):
E/flutter ( 2913): #15 PingApi.getPing (package:influxdb_client/api/ping_api.dart:50:22)
E/flutter ( 2913):
E/flutter ( 2913): #16 main (package:influxdb_app/main.dart:17:3)
E/flutter ( 2913):

Will this package works for Web Browser?

Proposal:
on which http should I host to connect for InfluxDBClient.

Current behavior:
This app is linked to the debug service: ws://127.0.0.1:62792/84DCuPDXMfw=/ws
Debug service listening on ws://127.0.0.1:62792/84DCuPDXMfw=/ws
Connecting to VM Service at ws://127.0.0.1:62792/84DCuPDXMfw=/ws
The webOnlyWarmupEngine API is deprecated and will be removed in a future release. Please use bootstrapEngine from dart:ui_web instead.
The webOnlySetPluginHandler API is deprecated and will be removed in a future release. Please use setPluginHandler from dart:ui_web instead.

Use case:
We want to make a dashboard view for FlutterWeb?

Tasks

Unhandled Exception: InfluxDBException: statusCode = 400, code = invalid, message = failed to decode request body: unsupported Content-Type header value

var queryService = client.getQueryService();

                var recordStream = await queryService.query('''
                from(bucket: "pasiv")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "AAPL")
  |> filter(fn: (r) => r["_field"] == "price")
  |> aggregateWindow(every: 24h, fn: last, createEmpty: false)
  |> yield(name: "last")
                ''');

                var count = 0;
                await recordStream.forEach((record) {
                  print(record.entries.toList().toString());
                  // print(
                  //     'record: ${count++} ${record['_time']}: ${record['host']} ${record['cpu']} ${record['_value']}');
                });

   client = InfluxDBClient(
        url: 'https://us-east-1-1.aws.cloud2.influxdata.com',
        token: 'TOKEN',
        org: 'jenish',

        bucket: 'pasiv',
        debug: true);

Below is the error I get :-

 >> contentLength: 476
I/flutter (30265): << status: 400 - contentLength: 99
I/flutter (30265): << headers: {connection: keep-alive, trace-id: 15993b584670a3a2, date: Fri, 08 Oct 2021 14:47:57 GMT, trace-sampled: false, vary: Accept-Encoding, strict-transport-security: max-age=15724800; includeSubDomains, content-length: 99, content-type: application/json; charset=utf-8, x-platform-error-code: invalid, x-influxdb-build: Cloud}


[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: InfluxDBException: statusCode = 400, code = invalid, message = failed to decode request body: unsupported Content-Type header value
```

`

@pauldix  @brettbuddin @mkmik @stuartcarnie @rockstar 

Doublequotes in string field

Describe the bug
Writing string from dart containing

[{"measurement":"Temperature","label":"Temperature","unit":"°C"...

results in this string in influxdb

[{\measurement\:\Temperature\,\label\:\Temperature\,\unit\:\°C\...

Expected behavior
Returned string from query will be same as written one

Specifications:

  • Client Version: main-git
  • InfluxDB Version: 2.0.9
  • Platform: Win/Android

Web - Refused to set unsafe header

Describe the bug
I'm having an issue when querying an influxdb server on an app running on web.

When I query the server I get this error in Chrome (or Edge) console:

Refused to set unsafe header "Accept-Encoding"
Refused to set unsafe header "User-Agent"

Firefox presents only this one as a warning:

Attempt to set a forbidden header was denied: Accept-Encoding

To Reproduce
Steps to reproduce the behavior:

  1. init client
  2. get query service
  3. query server

Specifications:

  • Client Version: 2.4.0
  • InfluxDB Version: 1.8 or 2.2
  • Platform: Web

Data not update continously(not Loop)

Hi. I tried that code and its working, but the new data not showing after 10 second(because default delay is 10 second) in debug console. Unless I restart the debugging, new data updated in debug console

Web - "Error: XMLHttpRequest error"

Describe the bug
I'm having an issue when querying an influxdb server on an app running on web (either chrome or edge).
When I query the server I get this error:

Error: XMLHttpRequest error. C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 963:28 get current packages/http/src/browser_client.dart 69:22 <fn> C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1685:54 runUnary C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18 handleValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13 _propagateToListeners C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 557:7 [_complete] C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1530:7 <fn> C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14 _checkAndCall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39 dcall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37309:58 <fn>

Same code works without problem on Android and Windows.

To Reproduce
Steps to reproduce the behavior:

  1. init client
  2. get query service
  3. query server

Specifications:

  • Client Version: 2.3.0
  • InfluxDB Version: 1.8
  • Platform: Web

Connect to two diferrent IPs

Hi. I a developing an APP with flutter, in this case I want to check if the connection to the first IP has been made correctly, make the query correctly; otherwise try to make the connection to the second IP. Next I leave you the code that I have implemented and it works correctly with the first IP, however when I select the second IP it does not give any error, but the query is not done, because it returns the empty variables.

import '../Cuidador/screen_Paciente.dart';

class InfluxDBService {
  late InfluxDBClient client;

  // var url = 'http://192.168.72.11:8086'; // PC POM
  var url = 'http://212.256.20.330:8086'; // PC POM

  var token =
      'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  var org = 'XXXXXXXXXXXXXXXXXX';
  var bucket = 'XXXXXXXXXXXXXXXX';
  InfluxDBService() {
    //PC POM
    client = InfluxDBClient(
      url: url, // PC POM
      token: token,
      org: org,
      bucket: bucket,
      followRedirects: true,
      maxRedirects: 5,
      debug: true,
    );
  }

  Future GetSteps(COD_PACIENTE_WEARABLE, startDateString, endDateString) async {
    var startDate = DateTime.parse(startDateString);
    var endDate = DateTime.parse(endDateString);
    var queryService = client.getQueryService();
    var StepsQuery = '''
      from(bucket: "${bucket}")
        |> range(start: ${startDate.toIso8601String()}, stop: ${endDate.toIso8601String()})
        |> filter(fn: (r) => r["_measurement"] == "${COD_PACIENTE_WEARABLE}")
        |> filter(fn: (r) => r["Data_type"] == "MISC")
        |> filter(fn: (r) => r["Sensor_type"] == "Movement")
        |> filter(fn: (r) => r["_field"] == "Steps")     
    ''';
    var StepsResponse = await queryService.query(StepsQuery);
    // Convertir el Stream en una lista
    var StepsRecords = await StepsResponse.toList();
    client.close();
    // Procesa los resultados y devuelve el nivel de la batería
    // Procesar los resultados
    var StepList = <StepData>[];
    for (var record in StepsRecords) {
      var Step = record["_value"];
      var timestampString = record["_time"];
      var timestamp = DateTime.parse(timestampString).toLocal();

      StepList.add(StepData(Step, timestamp));
    }
    StepList.sort((a, b) => b.timestamp.compareTo(a.timestamp));

    return StepList;
  }
}

InfluxDB 1.8 compatibility

The documentation state compatible with InfluxDB 1.8, where in 1.8 do you find org and buckets?

InfluxDB 1.8 API compatibility var client = InfluxDBClient( url: 'http://localhost:8086', username: '...', password: '...', org: 'my-org', bucket: 'my-bucket', debug: true);

Web client error: String.fromEnvironment can only be used as a const constructor

Thank you for adding web support to the client. Very happy about it! would be great if you could have a look at the issue, which is assume is a bug somewhere inside the client.

Describe the bug
Influxdb_client 2.0.0 running on web (Chrome debug) against a local influx 1.8.5 OSS instance throws the following error:

Error: Unsupported operation: String.fromEnvironment can only be used as a const constructor
    at Object.throw_ [as throw] (http://localhost:64108/dart_sdk.js:5061:11)
    at Function.fromEnvironment (http://localhost:64108/dart_sdk.js:44051:17)
at new api$.InfluxDBClient.new (http://localhost:64108/packages/influxdb_client/api.dart.lib.js:17429:58)

Based on the following comment I found on the web, I believe the error to be somewhere in the client code:
This is because browsers do not have access to system environment properties. fromEnvironment constructor can only be accessed during compilation and therefore they are constant as far as Dart code is concerned.

To Reproduce
Steps to reproduce the behavior:

  1. Try to connect the influx client against a 1.8 influx instance using in a web env.

Expected behavior
The operation to be supported

Specifications:

  • Client Version: 2.0.0
  • InfluxDB Version: 1.8.5 OSS
  • Platform: Flutter (Chrome)

Additional context
I have not tested this against an Influx 2.0 instance. So I cannot tell whether this is a downward compatibility issue.

Many thanks for looking into this!

Influx 1.8 OSS with 2.0.0 client: InfluxDBException: statusCode = 401, code = null, message = null

Describe the bug
Authentication fails, when trying to query a 1.8.5 based Influx instance with the 2.0.0 flutter client.

[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: InfluxDBException: statusCode = 401, code = null, message = null #0 DefaultService._handleResponse package:influxdb_client/client/influxdb_client.dart:108 <asynchronous suspension> #1 QueryService._send package:influxdb_client/client/query_service.dart:80 <asynchronous suspension> #2 QueryService.query package:influxdb_client/client/query_service.dart:66 <asynchronous suspension> #3 _SysHealthState._loadHistoricalData package:screens/syshealth.dart:222 <asynchronous suspension>

To Reproduce
Steps to reproduce the behavior:

  1. Query data from a 1.8.5 influx db with auth-enabled = true

Expected behavior
The query to execute successfully as it does with influxdb_client: ^1.1.0

Specifications:

  • Client Version: influxdb_client: ^2.0.0
  • InfluxDB Version: 1.8.5
  • Platform: Flutter (running client on iOS)

Additional context
The code is working fine with influxdb_client: ^1.1.0

Sample code I used works with client 1.1.0 but not 2.0.0

InfluxDBClient client = InfluxDBClient(
        url: 'http://localhost:8086',
        username: 'my_user',
        password: 'my_password',
        org: '',
        bucket: 'my_db',
        debug: false);

    QueryService queryService = client.getQueryService();

    String fluxQuery = '''
    lat = from(bucket: "my_db")
          |> range(start: -1d)
          |> filter(fn: (r) => r["_measurement"] == "gps_pos")
          |> filter(fn: (r) => r["_field"] == "lat")
          |> limit(n:20)

    long = from(bucket: "my_db")
          |> range(start: -1d)
          |> filter(fn: (r) => r["_measurement"] == "gps_pos")
          |> filter(fn: (r) => r["_field"] == "long")
          |> limit(n:20)

      join(tables: {lat: lat, long: long}, on: ["_time"])
    ''';

    Stream<FluxRecord> recordStream = await queryService.query(fluxQuery);
    await recordStream.forEach((record) {
      double lat = double.parse(record["_value_lat"].toString());
      double long = double.parse(record["_value_long"].toString());
      print('${record["_time"]} lat: $lat long: $long');
    });

bump intl to 0.18.1

influxdb_client 2.8.0 still depends on intl 0.17
I've noticed that milestone 2.9.0 already updated this dependency to 0.18 but flutter_localizations is already requesting 0.18.1

Because every version of flutter_localizations from sdk depends on intl 0.18.1 and influxdb_client depends on intl ^0.17.0, flutter_localizations from sdk is forbidden.

Flutter web support

Hey there,

do you guys plan to support flutter web anytime soon? If so, when do you think this might be available?

Thanks & best,
Benny

dependencies conflict when used with firebase - upgrade to intl. 0.17.0

When using the library with friebase_auth: 3.0.1 it doesn't resolve dependencies since firebase_auth depends on intl 0.17.0 and influxdb_client depends on 0.16.1.
dart put get fails with the error: version solving failed

To Reproduce
Steps to reproduce the behavior:

  1. add dependency firebase_core: 1.4.0 and firebase_auth: 3.0.1 together with influxdb_client in the pubspec.yaml file
  2. urn dart pub get

Expected behavior
no dependency conflict / automatic version solving succeeds

Thank you for the library!

InfluxDB Client Invalid HTTP Header Type

Describe the bug
Flutter for Andriod development runs into fatal error when trying a basic query with this library. The error claims that the header Content-Type is invalid and is receiving a 400 error from the InfluxDB cloud server.

Expected behavior
Connect to InfluxDB cloud instance and spit out raw CSV as confirmation

Specifications:

  • Client Version: Flutter 3.3.9
  • InfluxDB Version: Latest Cloud
  • Platform: Windows/ Android Emulation

Additional context
Add any other context about the problem here.

Logs:
I/flutter ( 8049): << status: 204 - contentLength: null
I/flutter ( 8049): << headers: {connection: keep-alive, trace-id: 54aaa331a1e1f5eb, date: Fri, 03 Feb 2023 16:32:05 GMT, x-influxdb-request-id: 8413e2e10ff08cd9e4ad0505e922e23d, trace-sampled: false, x-influxdb-version: 2.0, strict-transport-security: max-age=15724800; includeSubDomains, x-influxdb-build: cloud2,Cloud}
I/flutter ( 8049): >> POST https://eastus-1.azure.cloud2.influxdata.com/api/v2/query?org=popoviciu18%40ecu.edu =====
I/flutter ( 8049): >> headers: {Authorization: Token REDACTED_TOKEN, User-Agent: influxdb-client-dart/2.8.0, content-type: text/plain; charset=utf-8}
I/flutter ( 8049): >> contentLength: 364
I/flutter ( 8049): << status: 400 - contentLength: 77
I/flutter ( 8049): << headers: {connection: keep-alive, trace-id: fc6f0c43970577b7, date: Fri, 03 Feb 2023 16:32:06 GMT, x-influxdb-request-id: a495f719bbbfffb3588c8d507f663ed0, trace-sampled: false, vary: Accept-Encoding, strict-transport-security: max-age=15724800; includeSubDomains, content-length: 77, content-type: application/json; charset=utf-8, x-platform-error-code: invalid, x-influxdb-build: Cloud}

Flutter Debug (VSCode):
image

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.