Пример #1
0
        private NightFluxConnection(Configuration configuration)
        {
            Configuration = configuration;
            InfluxClient  = InfluxDBClientFactory.Create(Configuration.InfluxUrl, Configuration.InfluxToken.ToCharArray());
            var wo = WriteOptions.CreateNew()
                     .BatchSize(8192)
                     .WriteScheduler(new NewThreadScheduler())
                     .RetryInterval(750)
                     .JitterInterval(136)
                     .FlushInterval(1000)
                     .Build();

            InfluxWriteApi = InfluxClient.GetWriteApi(wo);
        }
Пример #2
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                var influxDbClient = InfluxDBClientFactory.Create("https://eu-central-1-1.aws.cloud2.influxdata.com",
                                                                  "HEjjtm6ewV0f8AjQ4S7ymvpPxGeqpjbFcyCCeQF-sYO7lvH60veVT3eqf_BabQEvsK_n3l5-AGsEGVcbxTGJfw=="
                                                                  .ToCharArray());


                MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace =
                        $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    _logger.Verbose(e.TraceMessage.Exception, "{@traceMsg}", trace);
                };

                // Setup and start a managed MQTT client.
                var options = new ManagedMqttClientOptionsBuilder()
                              .WithAutoReconnectDelay(TimeSpan.FromMilliseconds(500))
                              .WithClientOptions(new MqttClientOptionsBuilder()
                                                 .WithClientId("Client1")
                                                 .WithTcpServer("10.176.241.23").Build())
                              .Build();

                var mqttClient = new MqttFactory().CreateManagedMqttClient();
                mqttClient.UseApplicationMessageReceivedHandler(msg =>
                {
                    _logger.Information("Received: {topic} {msg}", msg.ApplicationMessage.Topic,
                                        msg.ApplicationMessage.ConvertPayloadToString());
                    using var w = influxDbClient.GetWriteApi();
                    var s       = msg.ApplicationMessage.Topic;
                    var i       = s.LastIndexOf('/');
                    var point   = PointData.Measurement(s.Substring(i + 1))
                                  .Tag("device", s.Substring(0, i))
                                  .Field("value", Convert.ToDouble(msg.ApplicationMessage.ConvertPayloadToString()))
                                  .Timestamp(DateTime.UtcNow, WritePrecision.S);
                    w.WritePoint("humidity", "f35d566fb41e6546", point);
                });
                await mqttClient.SubscribeAsync(
                    new[]
                {
                    new TopicFilterBuilder().WithTopic("rtl_433/+/devices/+/+/+/humidity").Build(),
                    new TopicFilterBuilder().WithTopic("rtl_433/+/devices/+/+/+/temperature_C").Build()
                }
                    );

                await mqttClient.StartAsync(options);
                await WhenCanceled(stoppingToken);
            }
        }
        public new async Task SetUp()
        {
            _organization = await FindMyOrg();

            var authorization = await AddAuthorization(_organization);

            Client.Dispose();
            Client = InfluxDBClientFactory.Create(InfluxDbUrl, authorization.Token.ToCharArray());

            _tasksApi = Client.GetTasksApi();

            _usersApi = Client.GetUsersApi();

            (await _tasksApi.FindTasksAsync()).ForEach(async task => await _tasksApi.DeleteTaskAsync(task));
        }
        public void Timeout()
        {
            var options = new InfluxDBClientOptions.Builder()
                          .Url("http://localhost:8086")
                          .AuthenticateToken("my-token".ToCharArray())
                          .TimeOut(TimeSpan.FromSeconds(20))
                          .ReadWriteTimeOut(TimeSpan.FromSeconds(30))
                          .Build();

            var client = InfluxDBClientFactory.Create(options);

            var apiClient = GetDeclaredField <ApiClient>(client.GetType(), client, "_apiClient");

            Assert.AreEqual(20_000, apiClient.Configuration.Timeout);
            Assert.AreEqual(30_000, apiClient.Configuration.ReadWriteTimeout);
        }
Пример #5
0
            public ClientV2(List <CommandOption> options, WriteOptions writeOptions) : base(options, InfluxDb2Bucket, InfluxDb2Url, InfluxDb2Token)
            {
                if (writeOptions == null)
                {
                    var batchSize     = int.Parse(Benchmark.GetOptionValue(GetOption(options, "batchSize"), "50000"));
                    var flushInterval = int.Parse(Benchmark.GetOptionValue(GetOption(options, "flushInterval"), "10000"));
                    writeOptions = WriteOptions.CreateNew().BatchSize(batchSize).FlushInterval(flushInterval).Build();
                }
                InfluxDBClientOptions opts = InfluxDBClientOptions.Builder.CreateNew()
                                             .Url(InfluxDb2Url)
                                             .AuthenticateToken(InfluxDb2Token.ToCharArray())
                                             .LogLevel(LogLevel.Headers).Build();

                _client   = InfluxDBClientFactory.Create(opts);
                _writeApi = _client.GetWriteApi(writeOptions);
            }
Пример #6
0
        public async Task SimpleWriteAndDisposing()
        {
            // Using WriteApi
            {
                var client = InfluxDBClientFactory.Create(InfluxDbUrl, _token);

                using (var writeApi = client.GetWriteApi())
                {
                    writeApi.WriteRecord(_bucket.Name, _organization.Id, WritePrecision.Ns, "temperature,location=north value=60.0 1");
                }

                client.Dispose();
            }

            // Using both
            {
                using (var client = InfluxDBClientFactory.Create(InfluxDbUrl, _token))
                {
                    using (var writeApi = client.GetWriteApi())
                    {
                        writeApi.WriteRecord(_bucket.Name, _organization.Id, WritePrecision.Ns,
                                             "temperature,location=north value=70.0 2");
                    }
                }
            }

            // Using without
            {
                var client   = InfluxDBClientFactory.Create(InfluxDbUrl, _token);
                var writeApi = client.GetWriteApi();

                writeApi.WriteRecord(_bucket.Name, _organization.Id, WritePrecision.Ns,
                                     "temperature,location=north value=80.0 3");

                client.Dispose();
            }

            var tables = await _queryApi.QueryAsync(
                $"from(bucket:\"{_bucket.Name}\") |> range(start: 1970-01-01T00:00:00.000000001Z)",
                _organization.Id);

            Assert.AreEqual(1, tables.Count);
            Assert.AreEqual(3, tables[0].Records.Count);
            Assert.AreEqual(60, tables[0].Records[0].GetValue());
            Assert.AreEqual(70, tables[0].Records[1].GetValue());
            Assert.AreEqual(80, tables[0].Records[2].GetValue());
        }
Пример #7
0
 /// <summary>
 /// 创建host
 /// </summary>
 /// <param name="args"></param>
 /// <returns></returns>
 public static IHostBuilder CreateHostBuilder(string[] args)
 {
     return(Host
            .CreateDefaultBuilder(args)
            .ConfigureServices((context, services) =>
     {
         services
         .AddTransient <BookService>()
         .AddHostedService <BookHostedService>()
         .Configure <InfuxdbOptions>(context.Configuration.GetSection("Influxdb"))
         .AddTransient(sp =>
         {
             var opt = sp.GetRequiredService <IOptionsMonitor <InfuxdbOptions> >().CurrentValue;
             return InfluxDBClientFactory.Create(opt.Host.ToString(), opt.Token);
         });
     }));
 }
Пример #8
0
        public OctopusTariffService(ILogger <OctopusTariffService> logger)
        {
            Logger = logger;
            var options = InfluxDBClientOptions.Builder.CreateNew()
                          .Url("http://server.home:8086")
                          .Bucket(DatabaseName + "/one_year")
                          .Org("-")
                          .Build();

            _client = InfluxDBClientFactory.Create(options);

            var delay = Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromSeconds(1), retryCount: 100);

            RetryPolicy = Policy.Handle <HttpException>()
                          .WaitAndRetryAsync(delay,
                                             (ex, ts) => Logger.LogWarning(ex, "Waiting {TimeSpan} due to {Exception}", ts, ex.Message));
        }
Пример #9
0
        public async Task DefaultTagsMeasurement()
        {
            Client.Dispose();

            Environment.SetEnvironmentVariable("measurement-datacenter", "LA");
            ConfigurationManager.AppSettings["measurement-sensor.version"] = "1.23a";

            var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl)
                          .AuthenticateToken(_token.ToCharArray())
                          .AddDefaultTag("id", "132-987-655")
                          .AddDefaultTag("customer", "California Miner")
                          .AddDefaultTag("env-var", "${env.measurement-datacenter}")
                          .AddDefaultTag("sensor-version", "${measurement-sensor.version}")
                          .Build();

            Client = InfluxDBClientFactory.Create(options);

            var measurement1 = new H20Measurement
            {
                Location = "coyote_creek", Level = 2.927, Time = DateTime.UtcNow
            };

            _writeApi = Client.GetWriteApi();
            var listener = new WriteApiTest.EventListener(_writeApi);

            _writeApi.WriteMeasurement(_bucket.Name, _organization.Id, WritePrecision.Ms, measurement1);
            _writeApi.Flush();

            listener.WaitToSuccess();

            _queryApi = Client.GetQueryApi();
            var tables = await _queryApi.QueryAsync(
                "from(bucket:\"" + _bucket.Name +
                "\") |> range(start: 1970-01-01T00:00:00.000000001Z) |> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")",
                _organization.Id);

            Assert.AreEqual(1, tables.Count);
            Assert.AreEqual(1, tables[0].Records.Count);
            Assert.AreEqual("h2o", tables[0].Records[0].GetMeasurement());
            Assert.AreEqual(2.927, tables[0].Records[0].GetValueByKey("level"));
            Assert.AreEqual("coyote_creek", tables[0].Records[0].GetValueByKey("location"));
            Assert.AreEqual("132-987-655", tables[0].Records[0].GetValueByKey("id"));
            Assert.AreEqual("California Miner", tables[0].Records[0].GetValueByKey("customer"));
            Assert.AreEqual("1.23a", tables[0].Records[0].GetValueByKey("sensor-version"));
            Assert.AreEqual("LA", tables[0].Records[0].GetValueByKey("env-var"));
        }
Пример #10
0
        public async Task Read()
        {
            try
            {
                Console.WriteLine("InfluxdbCommandBase.Test1() :> start querying ...");

                var influxDBClient = InfluxDBClientFactory.Create("http://localhost:9999", Token);
                Console.WriteLine("InfluxdbCommandBase.ReadRawApi() :> client created");

                string orgId = "defaultOrg";

                // Query data
                var queryApi = influxDBClient.GetQueryApi();
                var query    = $"from(bucket:\"defaultBucket\") |> range(start: -1h)";
                var tables   = await queryApi.QueryAsync(query, orgId);

                if (tables != null)
                {
                    Console.WriteLine("InfluxdbCommandBase.ReadRawApi() :> got tables");

                    tables.ForEach(fluxTable =>
                    {
                        var fluxRecords = fluxTable.Records;
                        fluxRecords.ForEach(fluxRecord =>
                        {
                            Console.WriteLine($"{fluxRecord.GetTime()}: {fluxRecord.GetValue()}");
                            Console.WriteLine($"    Field       : {fluxRecord.GetField()}");
                            Console.WriteLine($"    Measurement : {fluxRecord.GetMeasurement()}");
                            Console.WriteLine("------------------");
                            Console.WriteLine(string.Join("\n", fluxRecord.Values.Select(v => v.ToString())));
                            Console.WriteLine("------------------");
                            Console.WriteLine(fluxRecord.ToString());
                            Console.WriteLine("==================\n");
                        });
                    });
                }

                influxDBClient.Dispose();
                Console.WriteLine("InfluxdbCommandBase.ReadRawApi() :> Client disposed");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception:\n{ex.Message}\n{ex.InnerException.Message}");
            }
        }
Пример #11
0
        private static async Task Main(string[] args)
        {
            CollectorLog.RegisterErrorHandler((message, exception) =>
            {
                Console.WriteLine($"{message}: {exception}");
            });

            Console.WriteLine("Hello New World!");

            var influxDBClient = InfluxDBClientFactory.Create(DbUrl, Token);

            using (var writeApi = influxDBClient.GetWriteApi())
            {
                //    create events
                for (var i = 0; i < PlanAmount; i++)
                {
                    writeApi.WriteMeasurement(BucketName, OrgId, WritePrecision.Ns, Create_PlanCreateDTO());
                }

                //    change events
                PlanIDs.ForEach(planId =>
                {
                    for (var i = 0; i < ChangeEventPerPlanAmount; i++)
                    {
                        writeApi.WriteMeasurement(BucketName, OrgId, WritePrecision.Ns,
                                                  Create_PlanChangeValueDTO(planId, i));
                    }
                });

                //    delete events
                PlanIDs.ForEach(planId => writeApi.WriteMeasurement(BucketName, OrgId, WritePrecision.Ns,
                                                                    new PlanDeleteDTO
                {
                    PlanId      = planId,
                    UserId      = "12345",
                    PlanVersion = new Version(1, 2).ToString()
                })
                                );

                writeApi.Dispose();
            }

            await Read(influxDBClient);
        }
Пример #12
0
        private InfluxDBClient CreateInfluxClientWithAllAccessIfGiven()
        {
            var builder = InfluxDBClientOptions
                          .Builder
                          .CreateNew()
                          .Url(_connectionInfo.Uri.ToString())
                          .Org(_connectionInfo.OrganizationId);

            if (_authMethod == AuthMethods.Token)
            {
                builder.AuthenticateToken((_connectionInfo.AllAccessToken ?? _connectionInfo.Token).ToCharArray());
            }
            else
            {
                builder.Authenticate(_connectionInfo.Username, _connectionInfo.Password.ToCharArray());
            }

            return(InfluxDBClientFactory.Create(builder.Build()));
        }
        public void V1Configuration()
        {
            var client = InfluxDBClientFactory.CreateV1("http://localhost:8086", "my-username", "my-password".ToCharArray(), "database", "week");

            var options = GetDeclaredField <InfluxDBClientOptions>(client.GetType(), client, "_options");

            Assert.AreEqual("http://localhost:8086", options.Url);
            Assert.AreEqual("-", options.Org);
            Assert.AreEqual("database/week", options.Bucket);
            Assert.AreEqual("my-username:my-password".ToCharArray(), options.Token);

            client = InfluxDBClientFactory.CreateV1("http://localhost:8086", null, null, "database", null);

            options = GetDeclaredField <InfluxDBClientOptions>(client.GetType(), client, "_options");
            Assert.AreEqual("http://localhost:8086", options.Url);
            Assert.AreEqual("-", options.Org);
            Assert.AreEqual("database/", options.Bucket);
            Assert.AreEqual(":".ToCharArray(), options.Token);
        }
        public void LoadFromConnectionStringUnitsMinutes()
        {
            var client = InfluxDBClientFactory.Create("http://localhost:9999?" +
                                                      "timeout=1ms&readWriteTimeout=3m&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org");

            var options = GetDeclaredField <InfluxDBClientOptions>(client.GetType(), client, "_options");

            Assert.AreEqual("http://localhost:9999/", options.Url);
            Assert.AreEqual("my-org", options.Org);
            Assert.AreEqual("my-bucket", options.Bucket);
            Assert.AreEqual("my-token".ToCharArray(), options.Token);
            Assert.AreEqual(LogLevel.Headers, options.LogLevel);
            Assert.AreEqual(LogLevel.Headers, client.GetLogLevel());

            var apiClient = GetDeclaredField <ApiClient>(client.GetType(), client, "_apiClient");

            Assert.AreEqual(1, apiClient.Configuration.Timeout);
            Assert.AreEqual(180_000, apiClient.Configuration.ReadWriteTimeout);
        }
Пример #15
0
        public async Task DefaultTagsPoint()
        {
            Client.Dispose();

            Environment.SetEnvironmentVariable("point-datacenter", "LA");
            ConfigurationManager.AppSettings["point-sensor.version"] = "1.23a";

            var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl)
                          .AuthenticateToken(_token)
                          .AddDefaultTag("id", "132-987-655")
                          .AddDefaultTag("customer", "California Miner")
                          .AddDefaultTag("env-var", "${env.point-datacenter}")
                          .AddDefaultTag("sensor-version", "${point-sensor.version}")
                          .Build();

            Client = InfluxDBClientFactory.Create(options);

            var point = PointData.Measurement("h2o_feet").Tag("location", "west").Field("water_level", 1);

            _writeApi = Client.GetWriteApi();
            var listener = new WriteApiTest.EventListener(_writeApi);

            _writeApi.WritePoint(_bucket.Name, _organization.Id, point);
            _writeApi.Flush();

            listener.WaitToSuccess();

            _queryApi = Client.GetQueryApi();
            var tables = await _queryApi.QueryAsync(
                $"from(bucket:\"{_bucket.Name}\") |> range(start: 1970-01-01T00:00:00.000000001Z) |> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")",
                _organization.Id);

            Assert.AreEqual(1, tables.Count);
            Assert.AreEqual(1, tables[0].Records.Count);
            Assert.AreEqual("h2o_feet", tables[0].Records[0].GetMeasurement());
            Assert.AreEqual(1, tables[0].Records[0].GetValueByKey("water_level"));
            Assert.AreEqual("west", tables[0].Records[0].GetValueByKey("location"));
            Assert.AreEqual("132-987-655", tables[0].Records[0].GetValueByKey("id"));
            Assert.AreEqual("California Miner", tables[0].Records[0].GetValueByKey("customer"));
            Assert.AreEqual("1.23a", tables[0].Records[0].GetValueByKey("sensor-version"));
            Assert.AreEqual("LA", tables[0].Records[0].GetValueByKey("env-var"));
        }
Пример #16
0
        private void InitializeDb()
        {
            var dbConfig = WorkersManager.GetWorkersManager().Config;

            if (dbClient == null && dbConfig.IsDbConfigAvailable())
            {
                try
                {
                    Log.Info("InitializeDb");
                    dbClient = InfluxDBClientFactory.Create(dbConfig.Url, dbConfig.AuthToken.ToCharArray());
                    dbClient.Health();
                    dbQueryApi = dbClient.GetQueryApi();
                }
                catch (Exception ex)
                {
                    Log.Error("Db init error", ex);
                    OnStatusChanged("DB Init Error: " + ex.Message);
                }
            }
        }
        public void UpdateSetting(InfluxDbSetting setting)
        {
            this.Dispose();

            if (string.IsNullOrWhiteSpace(setting.Token))
            {
                _influxDBClient = InfluxDBClientFactory.Create(
                    $"http://{setting.Host}:{setting.Port}"
                    , setting.Username
                    , setting.Password.ToCharArray()
                    );
            }
            else
            {
                _influxDBClient = InfluxDBClientFactory.Create(
                    $"http://{setting.Host}:{setting.Port}"
                    , setting.Token.ToCharArray()
                    );
            }
        }
Пример #18
0
 public DBConnection()
 {
     try
     {
         //lettura configurazione
         Config config     = Utils.Utils.ReadConfiguration();
         String connString = String.Format("http://{0}:{1}", config.InfluxDB.Ip, config.InfluxDB.Port);
         //creazione client per connessione al db
         database        = config.InfluxDB.Database;
         retentionPolicy = config.InfluxDB.RetentionPolicy;
         client          = InfluxDBClientFactory.CreateV1(connString, config.InfluxDB.Username, config.InfluxDB.Password.ToCharArray(), database, retentionPolicy);
         if (client == null)
         {
             throw new Exception("Impossibile stabilire connessione con il database!");
         }
     }
     catch (Exception e)
     {
         log.ErrorFormat("!ERROR: {0}", e.ToString());
     }
 }
Пример #19
0
        public void Write()
        {
            Console.WriteLine("InfluxdbCommandBase.Test1() :> creating influx db client ...");

            /**
             * or use username/password:
             * var influxDBClient = InfluxDBClientFactory.Create("http://localhost:9999", "ron", "open".ToCharArray());
             */
            var    influxDBClient = InfluxDBClientFactory.Create("http://localhost:9999", Token);
            string orgId          = "defaultOrg";
            string bucketName     = "defaultBucket";

            Console.WriteLine("InfluxdbCommandBase.Test1() :> start writing data ...");

            // Write Data
            using (var writeApi = influxDBClient.GetWriteApi())
            {
                // Write by Point
                var point = PointData.Measurement("temperature")
                            .Tag("location", "west")
                            .Field("value", 55D)
                            .Timestamp(DateTime.UtcNow.AddSeconds(-10), WritePrecision.Ns);

                writeApi.WritePoint(bucketName, orgId, point);
                Console.WriteLine("InfluxdbCommandBase.Test1() :> Write by Point completed");

                // Write by LineProtocol
                writeApi.WriteRecord(bucketName, orgId, WritePrecision.Ns, "temperature,location=north value=60.0");
                Console.WriteLine("InfluxdbCommandBase.Test1() :> Write by LineProtocol completed");

                // Write by POCO
                var temperature = new Temperature {
                    Location = "south", Value = 94D, Time = DateTime.UtcNow
                };
                writeApi.WriteMeasurement(bucketName, orgId, WritePrecision.Ns, temperature);
                Console.WriteLine("InfluxdbCommandBase.Test1() :> Write by POCO completed");
            }

            influxDBClient.Dispose();
        }
Пример #20
0
        public async Task DefaultTagsConfiguration()
        {
            Client.Dispose();

            var options = new InfluxDBClientOptions.Builder()
                          .LoadConfig()
                          .Url(InfluxDbUrl)
                          .AuthenticateToken(_token)
                          .Build();

            Client = InfluxDBClientFactory.Create(options);

            var measurement1 = new H20Measurement
            {
                Location = "coyote_creek", Level = 2.927, Time = DateTime.UtcNow
            };

            _writeApi = Client.GetWriteApi();
            var listener = new WriteApiTest.EventListener(_writeApi);

            _writeApi.WriteMeasurement(_bucket.Name, _organization.Id, WritePrecision.Ms, measurement1);
            _writeApi.Flush();

            listener.WaitToSuccess();

            _queryApi = Client.GetQueryApi();
            var tables = await _queryApi.QueryAsync(
                $"from(bucket:\"{_bucket.Name}\") |> range(start: 1970-01-01T00:00:00.000000001Z) |> pivot(rowKey:[\"_time\"], columnKey: [\"_field\"], valueColumn: \"_value\")",
                _organization.Id);

            Assert.AreEqual(1, tables.Count);
            Assert.AreEqual(1, tables[0].Records.Count);
            Assert.AreEqual("h2o", tables[0].Records[0].GetMeasurement());
            Assert.AreEqual(2.927, tables[0].Records[0].GetValueByKey("level"));
            Assert.AreEqual("coyote_creek", tables[0].Records[0].GetValueByKey("location"));
            Assert.AreEqual("132-987-655", tables[0].Records[0].GetValueByKey("id"));
            Assert.AreEqual("California Miner", tables[0].Records[0].GetValueByKey("customer"));
            Assert.AreEqual("v1.00", tables[0].Records[0].GetValueByKey("version"));
        }
Пример #21
0
 private InfluxDBClient GetInfluxDBClient()
 {
     if (_options.UseV1)
     {
         return(InfluxDBClientFactory.CreateV1(
                    _options.Uri,
                    _options.User,
                    _options.Password.ToCharArray(),
                    _options.Bucket,
                    _options.RetentionPolicy
                    ));
     }
     else
     {
         return(InfluxDBClientFactory.Create(
                    InfluxDBClientOptions.Builder.CreateNew()
                    .Url(_options.Uri)
                    .Authenticate(_options.User, _options.Password.ToCharArray())
                    .Build()
                    ));
     }
 }
Пример #22
0
        public static void PublishData(PowerFlowRealtimeDataModel model)
        {
            // You can generate a Token from the "Tokens Tab" in the UI
            const string token  = "1Xli7Idwo8AAtoyEGHWQv_4MduTk3CmFqv7Cfdw8_Be8h-m6_ehLLjG8EhsRVmAHZKtsWtbUFpsHQ7lUXsGCug==";
            const string bucket = "bc57b7930b7fff33";
            const string org    = "024ad8697c8a4f99";

            var client = InfluxDBClientFactory.Create("https://us-west-2-1.aws.cloud2.influxdata.com", token.ToCharArray());

            var prod = new Production {
                Value = (int)(model.Body.Data.Site.CurrentPVProduction ?? 0), Time = model.Head.TimeStamp.ToUniversalTime()
            };
            var cons = new Consumption {
                Value = (int)(model.Body.Data.Site.CurrentPowerConsumption), Time = model.Head.TimeStamp.ToUniversalTime()
            };

            using (var writeApi = client.GetWriteApi())
            {
                writeApi.WriteMeasurement(bucket, org, WritePrecision.Ns, prod);
                writeApi.WriteMeasurement(bucket, org, WritePrecision.Ns, cons);
            }
        }
        public new async Task SetUp()
        {
            _organization = await FindMyOrg();

            //bug: https://github.com/influxdata/influxdb/issues/19518
            var retention = new BucketRetentionRules(BucketRetentionRules.TypeEnum.Expire, 3600);

            _bucket = await Client.GetBucketsApi()
                      .CreateBucketAsync(GenerateName("h2o"), null, _organization);

            //
            // Add Permissions to read and write to the Bucket
            //
            var resource = new PermissionResource(PermissionResource.TypeEnum.Buckets, _bucket.Id, null,
                                                  _organization.Id);

            var readBucket  = new Permission(Permission.ActionEnum.Read, resource);
            var writeBucket = new Permission(Permission.ActionEnum.Write, resource);

            var loggedUser = await Client.GetUsersApi().MeAsync();

            Assert.IsNotNull(loggedUser);

            var authorization = await Client.GetAuthorizationsApi()
                                .CreateAuthorizationAsync(_organization,
                                                          new List <Permission> {
                readBucket, writeBucket
            });

            _token = authorization.Token;

            Client.Dispose();
            var options = new InfluxDBClientOptions.Builder().Url(InfluxDbUrl).AuthenticateToken(_token)
                          .Org(_organization.Id).Bucket(_bucket.Id).Build();

            Client = InfluxDBClientFactory.Create(options);

            _writeApi = Client.GetWriteApiAsync();
        }
        //_token
        public async Task FindTasksByOrganization()
        {
            var taskOrg = await Client.GetOrganizationsApi().CreateOrganizationAsync(GenerateName("Task user"));

            var authorization = await AddAuthorization(taskOrg);

            Client.Dispose();
            Client    = InfluxDBClientFactory.Create(InfluxDbUrl, authorization.Token.ToCharArray());
            _tasksApi = Client.GetTasksApi();

            var count = (await _tasksApi.FindTasksByOrganizationAsync(taskOrg)).Count;

            Assert.AreEqual(0, count);

            await _tasksApi.CreateTaskCronAsync(GenerateName("it task"), TaskFlux, "0 2 * * *", taskOrg);

            var tasks = await _tasksApi.FindTasksByOrganizationAsync(taskOrg);

            Assert.AreEqual(1, tasks.Count);

            (await _tasksApi.FindTasksAsync()).ForEach(async task => await _tasksApi.DeleteTaskAsync(task));
        }
Пример #25
0
        public static void RunSensorSimulation(string id, SensorsContainer sensors, string serverUrl, string serverToken, string serverBucket, string serverOrg)
        {
            if (id == "env")
            {
                DeviceID = Environment.GetEnvironmentVariable("SIMDEV_POD_NAME");
            }
            else
            {
                DeviceID = id;
            }
            ServerBucket = serverBucket;
            ServerOrg    = serverOrg;

            using var influxDBClient = InfluxDBClientFactory.Create(serverUrl, serverToken.ToCharArray());
            influxDBClient.DisableGzip();
            List <Task> tasks = new List <Task>();

            foreach (var sensor in sensors.Sensors)
            {
                tasks.Add(Task.Run(() => DataGeneration.GenerateSensorData(sensor, influxDBClient)));
            }
            Task.WaitAll(tasks.ToArray());
        }
        public new async Task SetUp()
        {
            _client = InfluxDBClientFactory.Create(GetInfluxDb2Url(), "my-token");
            _client.SetLogLevel(LogLevel.Body);

            // DateTime(2020, 10, 15, 8, 20, 15, DateTimeKind.Utc)
            const string sensor11 = "sensor,deployment=production,sensor_id=id-1 data=15i 1602750015";
            const string sensor21 = "sensor,deployment=production,sensor_id=id-2 data=15i 1602750015";
            // new DateTime(2020, 11, 15, 8, 20, 15, DateTimeKind.Utc)
            const string sensor12 = "sensor,deployment=production,sensor_id=id-1 data=28i 1605428415";
            const string sensor22 = "sensor,deployment=production,sensor_id=id-2 data=28i 1605428415";
            // new DateTime(2020, 11, 16, 8, 20, 15, DateTimeKind.Utc)
            const string sensor13 = "sensor,deployment=production,sensor_id=id-1 data=12i 1605514815";
            const string sensor23 = "sensor,deployment=production,sensor_id=id-2 data=12i 1605514815";
            // new DateTime(2020, 11, 17, 8, 20, 15, DateTimeKind.Utc)
            const string sensor14 = "sensor,deployment=production,sensor_id=id-1 data=89i 1605601215";
            const string sensor24 = "sensor,deployment=production,sensor_id=id-2 data=89i 1605601215";

            await _client
            .GetWriteApiAsync()
            .WriteRecordsAsync("my-bucket", "my-org", WritePrecision.S,
                               sensor11, sensor21, sensor12, sensor22, sensor13, sensor23, sensor14, sensor24);
        }
        public static void Main(string[] args)
        {
            using var client = InfluxDBClientFactory.Create("http://localhost:9999", "my-token");

            const string query = "from(bucket:\"my-bucket\") |> range(start: 0)";

            //
            // QueryData
            //
            var queryApi = client.GetQueryApiSync();
            var tables   = queryApi.QuerySync(query, "my-org");

            //
            // Process results
            //
            tables.ForEach(table =>
            {
                table.Records.ForEach(record =>
                {
                    Console.WriteLine($"{record.GetTime()}: {record.GetValueByKey("_value")}");
                });
            });
        }
        // change name of method to Main
        public static async Task MainDisabled(string[] args)
        {
            const string database        = "telegraf";
            const string retentionPolicy = "autogen";

            var client = InfluxDBClientFactory.CreateV1("http://localhost:8086",
                                                        "username",
                                                        "password".ToCharArray(),
                                                        database,
                                                        retentionPolicy);

            Console.WriteLine("*** Write Points ***");

            using (var writeApi = client.GetWriteApi())
            {
                var point = PointData.Measurement("mem")
                            .Tag("host", "host1")
                            .Field("used_percent", 28.43234543);

                writeApi.WritePoint(point);
            }

            Console.WriteLine("*** Query Points ***");

            var query      = $"from(bucket: \"{database}/{retentionPolicy}\") |> range(start: -1h)";
            var fluxTables = await client.GetQueryApi().QueryAsync(query);

            var fluxRecords = fluxTables[0].Records;

            fluxRecords.ForEach(record =>
            {
                Console.WriteLine($"{record.GetTime()} {record.GetMeasurement()}: {record.GetField()} {record.GetValue()}");
            });

            client.Dispose();
        }
        public static IServiceCollection AddInfluxDbBufferedWriter(this IServiceCollection services, InfluxDBClientOptions clientOptions, BufferedChannelOptions options = null)
        {
            if (clientOptions == null)
            {
                throw new ArgumentNullException(nameof(clientOptions));
            }

            if (options == null)
            {
                options = new BufferedChannelOptions
                {
                    BufferSize    = BufferedChannelOptions.DefaultBufferSize,
                    FlushInterval = BufferedChannelOptions.DefaultFlushInterval
                };
            }

            return(services
                   .AddTransient <IDefaultMetrics, DefaultMetrics>()
                   .AddSingleton <IInfluxDbClientWriter>(p =>
            {
                var client = InfluxDBClientFactory.Create(clientOptions);
                return new InfluxDbClientWriter(client, options);
            }));
        }
Пример #30
0
        public async Task Onboarding()
        {
            var url = $"http://{GetOrDefaultEnvironmentVariable("INFLUXDB_2_ONBOARDING_IP", "127.0.0.1")}:" +
                      $"{GetOrDefaultEnvironmentVariable("INFLUXDB_2_ONBOARDING_PORT", "9990")}";

            using (var client = InfluxDBClientFactory.Create(url))
            {
                Assert.IsTrue(await client.IsOnboardingAllowed());
            }

            var onboarding = await InfluxDBClientFactory.Onboarding(url, "admin", "11111111", "Testing", "test");

            Assert.IsNotNull(onboarding.User);
            Assert.IsNotEmpty(onboarding.User.Id);
            Assert.AreEqual("admin", onboarding.User.Name);

            Assert.IsNotNull(onboarding.Bucket);
            Assert.IsNotEmpty(onboarding.Bucket.Id);
            Assert.AreEqual("test", onboarding.Bucket.Name);

            Assert.IsNotNull(onboarding.Org);
            Assert.IsNotEmpty(onboarding.Org.Id);
            Assert.AreEqual("Testing", onboarding.Org.Name);

            Assert.IsNotNull(onboarding.Auth);
            Assert.IsNotEmpty(onboarding.Auth.Id);
            Assert.IsNotEmpty(onboarding.Auth.Token);

            using (var client = InfluxDBClientFactory.Create(url, onboarding.Auth.Token.ToCharArray()))
            {
                var user = await client.GetUsersApi().Me();

                Assert.IsNotNull(user);
                Assert.AreEqual("admin", user.Name);
            }
        }