public async Task TestPostPointAsyncNonDefaultRetention()
        {
            try
            {
                var client   = new InfluxDBClient(influxUrl, dbUName, dbpwd);
                var time     = DateTime.Now;
                var rand     = new Random();
                var valMixed = new InfluxDatapoint <InfluxValueField>();
                valMixed.UtcTimestamp = DateTime.UtcNow;
                valMixed.Tags.Add("TestDate", time.ToShortDateString());
                valMixed.Tags.Add("TestTime", time.ToShortTimeString());
                valMixed.Fields.Add("Doublefield", new InfluxValueField(rand.NextDouble()));
                valMixed.Fields.Add("Stringfield", new InfluxValueField(DataGen.RandomString()));
                valMixed.Fields.Add("Boolfield", new InfluxValueField(true));
                valMixed.Fields.Add("Int Field", new InfluxValueField(rand.Next()));

                valMixed.MeasurementName = measurementName;
                valMixed.Precision       = TimePrecision.Seconds;
                valMixed.Retention       = new InfluxRetentionPolicy()
                {
                    Duration = TimeSpan.FromHours(6)
                };

                var r = await client.PostPointAsync(dbName, valMixed);

                Assert.IsTrue(r && valMixed.Saved, "PostPointAsync retunred false");
            }
            catch (Exception e)
            {
                Assert.Fail($"Unexpected exception of type {e.GetType()} caught: {e.Message}");
                return;
            }
        }
        public async Task TestPostBooleanPointAsync()
        {
            try
            {
                var client = new InfluxDBClient(influxUrl, dbUName, dbpwd);
                var time   = DateTime.Now;

                var valBool = new InfluxDatapoint <bool> ();
                valBool.UtcTimestamp = DateTime.UtcNow;
                valBool.Tags.Add("TestDate", time.ToShortDateString());
                valBool.Tags.Add("TestTime", time.ToShortTimeString());
                valBool.Fields.Add("Booleanfield", time.Ticks % 2 == 0);
                valBool.MeasurementName = measurementName;
                valBool.Precision       = TimePrecision.Seconds;
                var r = await client.PostPointAsync(dbName, valBool);

                Assert.IsTrue(r, "PostPointAsync retunred false");
            }
            catch (Exception e)
            {
                Assert.Fail("Unexpected exception of type {0} caught: {1}",
                            e.GetType(), e.Message);
                return;
            }
        }
        public async Task TestPostDoublePointAsync()
        {
            try
            {
                var client    = new InfluxDBClient(influxUrl, dbUName, dbpwd);
                var time      = DateTime.Now;
                var rand      = new Random();
                var valDouble = new InfluxDatapoint <double> ();
                valDouble.UtcTimestamp = DateTime.UtcNow;
                valDouble.Tags.Add("TestDate", time.ToShortDateString());
                valDouble.Tags.Add("TestTime", time.ToShortTimeString());
                valDouble.Fields.Add("Doublefield", rand.NextDouble());
                valDouble.Fields.Add("Doublefield2", rand.NextDouble());
                valDouble.MeasurementName = measurementName;
                valDouble.Precision       = TimePrecision.Seconds;
                var r = await client.PostPointAsync(dbName, valDouble);

                Assert.IsTrue(r, "PostPointAsync retunred false");
            }
            catch (Exception e)
            {
                Assert.Fail("Unexpected exception of type {0} caught: {1}",
                            e.GetType(), e.Message);
                return;
            }
        }
        public async Task TestPostObjectPointAsync()
        {
            try
            {
                var client = new InfluxDBClient(influxUrl, dbUName, dbpwd);

                var point = new PointObjectWithStringRetention
                {
                    Time        = DateTime.UtcNow,
                    Measurement = measurementName,
                    Precision   = TimePrecision.Seconds,
                    StringTag   = "FromObject",
                    IntTag      = DataGen.RandomInt(),
                    StringField = DataGen.RandomString(),
                    DoubleField = DataGen.RandomDouble(),
                    IntField    = DataGen.RandomInt(),
                    BoolField   = true,
                };

                var r = await client.PostPointAsync(dbName, point);

                Assert.IsTrue(r, "PostPointAsync returned false");
            }
            catch (Exception e)
            {
                Assert.Fail($"Unexpected exception of type {e.GetType()} caught: {e.Message}");
                return;
            }
        }
Example #5
0
        public void InsertBatteryPointsTest()
        {
            //var now = DateTime.Now;
            //var utcNow = DateTime.UtcNow;
            //var convertUtc = TimeZone.CurrentTimeZone.ToUniversalTime(now);

            // var config = new ConfigurationBuilder()
            //.AddJsonFile("appsettings.json")
            //.Build();
            // var connectionString = config["Data:CXEntities:ConnectionString"];

            // var connStr = ConfigurationManager.ConnectionStrings["CXEntities"]?.ConnectionString;
            // string conString = Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString(this.Configuration, "DefaultConnection");

            // return;

            var client = new InfluxDBClient(influxUrl, dbUName, dbpwd);

            var batteryRepos = new CarBatteryRepository();
            var batteries    = batteryRepos.Query("SELECT * FROM carbattery").ToList();

            //return;
            batteries.ForEach(e =>
            {
                var item              = new CarBatteryPoint();
                item.DeviceNumber     = NoEmptyValue(e.DeviceNumber, "DeviceNumber");
                item.CustomerCode     = NoEmptyValue(e.CustomerCode, "CustomerCode");
                item.DeviceWays       = NoEmptyValue(e.DeviceWays, "DeviceWays");
                item.TransactionID    = NoEmptyValue(e.TransactionID, "TransactionID");
                item.VIN              = NoEmptyValue(e.VIN, "VIN");
                item.RVOL             = e.RVOL;
                item.RCUR             = e.RCUR;
                item.Ptemp            = e.Ptemp;
                item.Ntemp            = e.Ntemp;
                item.BATType          = e.BATType;
                item.BATPOW           = e.BATPOW;
                item.Capacity         = e.Capacity;
                item.MaxCVol          = e.MaxCVol;
                item.MaxCCur          = e.MaxCCur;
                item.SigleMaxVol      = e.SigleMaxVol;
                item.SigleMinVol      = e.SigleMinVol;
                item.StartSigleMaxVol = e.StartSigleMaxVol;
                item.StartSigleMinVol = e.StartSigleMinVol;
                item.EndSigleMaxVol   = e.EndSigleMaxVol;
                item.EndSigleMinVol   = e.EndSigleMinVol;
                item.MaxTemp          = e.MaxTemp;
                item.StartVol         = e.StartVol;
                var utcTime           = TimeZone.CurrentTimeZone.ToUniversalTime(e.CreateDate);
                item.CreateDate       = utcTime;
                item.MeasurementName  = measurementName;
                item.Precision        = TimePrecision.Nanoseconds;
                var r = client.PostPointAsync(dbName, item).Result;
                output.WriteLine("add point:" + e.Id);
            });
        }
Example #6
0
        private static async Task InsertMonthlyValues(MonthlyValues monthlyValues)
        {
            if (monthlyValues != null)
            {
                var influxMonthlyValues = new InfluxDatapoint <InfluxValueField>();
                influxMonthlyValues.UtcTimestamp = DateTime.Now.PreviousMonth().LastDayOfMonth().EndOfDay().ToUniversalTime();
                influxMonthlyValues.Fields.Add("PvMonth", new InfluxValueField(monthlyValues.PvMonth));
                influxMonthlyValues.Fields.Add("LoadMonth", new InfluxValueField(monthlyValues.LoadMonth));
                influxMonthlyValues.Fields.Add("InvMonth", new InfluxValueField(monthlyValues.InvMonth));
                influxMonthlyValues.Fields.Add("DemandMonth", new InfluxValueField(monthlyValues.DemandMonth));
                influxMonthlyValues.Fields.Add("FeedInMonth", new InfluxValueField(monthlyValues.FeedInMonth));
                influxMonthlyValues.Fields.Add("MonthIndex", new InfluxValueField(monthlyValues.MonthIndex));
                influxMonthlyValues.Fields.Add("YearIndex", new InfluxValueField(monthlyValues.YearIndex));

                influxMonthlyValues.MeasurementName = measurement_PVmonthly;
                influxMonthlyValues.Precision       = TimePrecision.Minutes;
                influxMonthlyValues.Retention       = new InfluxRetentionPolicy()
                {
                    Name = ret_policy_longterm
                };
                var result = await influxClient.PostPointAsync(influxDbNameLongterm, influxMonthlyValues);  //save the monthly value
            }
        }
        public async Task <int> AggregateAsync(string metricKey)
        {
            var redisDb = connectionMultiplexer.GetDatabase();

            // Read newly added values
            var metricValues = await redisDb.SortedSetRangeByRankWithScoresAsync <MetricRedisValue>(metricKey, 0, -1);

            // Create the metric if it doesn't exist
            var metricId = "0";

            var timestamp = metricValues.FirstOrDefault().TimestampGranulated;

            var aggregatedMetricData = new AggregatedMetricData
            {
                Measurement = "m_" + metricId,
                MetricId    = metricId,
                Sum         = metricValues.Sum(x => x.Value),
                Average     = metricValues.Average(x => x.Value),
                Min         = metricValues.Min(x => x.Value),
                Max         = metricValues.Max(x => x.Value),
                Count       = metricValues.Length,
                Timestamp   = timestamp,
                Precision   = TimePrecision.Seconds,
            };

            aggregatedMetricData.Time = DateTimeOffset.FromUnixTimeSeconds(aggregatedMetricData.Timestamp).UtcDateTime;

            // Insert this metric to InfluxDb
            var datapoint = new InfluxDatapoint <InfluxValueField>
            {
                MeasurementName = "m_" + aggregatedMetricData.MetricId,
                UtcTimestamp    = DateTimeOffset.FromUnixTimeSeconds(aggregatedMetricData.Timestamp).UtcDateTime,
                Precision       = TimePrecision.Seconds
            };

            datapoint.Fields.Add("sum", new InfluxValueField(aggregatedMetricData.Sum));
            datapoint.Fields.Add("average", new InfluxValueField(aggregatedMetricData.Average));
            datapoint.Fields.Add("min", new InfluxValueField(aggregatedMetricData.Min));
            datapoint.Fields.Add("max", new InfluxValueField(aggregatedMetricData.Max));
            datapoint.Fields.Add("count", new InfluxValueField(aggregatedMetricData.Count));

            var result = await influxDBClient.PostPointAsync("myDatabase", datapoint);

            // Remove the metric's sorted set
            await redisDb.KeyDeleteAsync(metricKey);

            return(metricValues.Length);
        }
        public async Task InsertAsync(InfluxDbBase dbBase)
        {
            var valMixed = new InfluxDatapoint <InfluxValueField>();

            valMixed.UtcTimestamp = DateTime.UtcNow;
            valMixed.Tags.Add("Date", DateTime.UtcNow.ToShortDateString());
            valMixed.Tags.Add("Time", DateTime.UtcNow.ToShortTimeString());
            var list = JsonConvert.DeserializeObject <Dictionary <string, string> >(JsonConvert.SerializeObject(dbBase));

            foreach (var item in list)
            {
                valMixed.Fields.Add($"{item.Key}", new InfluxValueField(item.Value));
            }

            var r = await InfluxDBConnection.PostPointAsync(DbName, valMixed);
        }
Example #9
0
        public async Task AddDataPoint(DockerStatDataModel model)
        {
            var valMixed = new InfluxDatapoint <InfluxValueField>();

            valMixed.UtcTimestamp = model.Read.UtcDateTime;
            valMixed.Tags.Add("ContainerId", model.Id);
            valMixed.Tags.Add("ContainerName", model.Name);
            valMixed.Fields.Add("CpuPercent", new InfluxValueField(CpuCycleConverter.CalculateCPUPercentWindows(model)));
            valMixed.Fields.Add("MemoryUsage", new InfluxValueField(BinaryConverter.ConvertBytesToMegabytes(model.MemoryStats.Privateworkingset)));
            valMixed.Fields.Add("DiskInput", new InfluxValueField(BinaryConverter.ConvertBytesToMegabytes(model.StorageStats.WriteSizeBytes)));
            valMixed.Fields.Add("DiskOutput", new InfluxValueField(BinaryConverter.ConvertBytesToMegabytes(model.StorageStats.ReadSizeBytes)));

            valMixed.MeasurementName = _settings.MeasurementName;
            valMixed.Precision       = TimePrecision.Seconds;

            var r = await _dbClient.PostPointAsync(_settings.DbName, valMixed);
        }
        public async Task TestPostPointAsync_InvalidReq()
        {
            var client = new InfluxDBClient(influxUrl, dbUName, dbpwd);
            var time   = DateTime.Now;
            var today  = DateTime.Now.ToShortDateString();
            var now    = DateTime.Now.ToShortTimeString();

            var valDouble = new InfluxDatapoint <double>();

            valDouble.UtcTimestamp = DateTime.UtcNow;
            valDouble.Tags.Add("TestDate", today);
            valDouble.Tags.Add("TestTime", now);
            valDouble.Fields.Add("Doublefield", DataGen.RandomDouble());
            valDouble.Fields.Add("Doublefield2", Double.NaN);
            valDouble.MeasurementName = measurementName;
            valDouble.Precision       = TimePrecision.Seconds;

            var r = await AssertEx.ThrowsAsync <InfluxDBException>(() => client.PostPointAsync(dbName, valDouble));
        }
        async public static Task Init()
        {
            int count2 = dataClass.countOfElements / 100;
            int count  = ((dataClass.countOfDays + 100) / 100);
            //====================================================================================Коннект в бд============
            string         nameDB = "Process";
            InfluxDBClient client = new InfluxDBClient("http://localhost:8086", "root", "root");
            await client.CreateDatabaseAsync(nameDB);

            InfluxDatabase name = new InfluxDatabase(nameDB);
            var            m    = await client.DropDatabaseAsync(name);

            await client.CreateDatabaseAsync(nameDB);

            for (int i = 0; i < dataClass.countOfDays; i++)
            {
                var valMixed1 = new InfluxDatapoint <InfluxValueField>();
                var valMixed2 = new InfluxDatapoint <InfluxValueField>();
                var valMixed3 = new InfluxDatapoint <InfluxValueField>();
                var valMixed4 = new InfluxDatapoint <InfluxValueField>();
                var valMixed5 = new InfluxDatapoint <InfluxValueField>();
                valMixed1.UtcTimestamp    = rmseClass.rmseDates[i].ToUniversalTime();
                valMixed2.UtcTimestamp    = rmseClass.rmseDates[i].ToUniversalTime();
                valMixed3.UtcTimestamp    = rmseClass.rmseDates[i].ToUniversalTime();
                valMixed4.UtcTimestamp    = rmseClass.rmseDates[i].ToUniversalTime();
                valMixed5.UtcTimestamp    = rmseClass.rmseDates[i].ToUniversalTime();
                valMixed1.MeasurementName = "RmseValuesForAlgOne";
                valMixed2.MeasurementName = "RmseValuesForAlgTwo";
                valMixed3.MeasurementName = "RmseValuesForAlgThree";
                valMixed4.MeasurementName = "RmseValuesForAlgFour";
                valMixed5.MeasurementName = "RmseValuesForAlgFive";
                double[] values = new double[5];
                values[0] = rmseClass.ValuesRMSE1[i];
                values[1] = rmseClass.ValuesRMSE2[i];
                values[2] = rmseClass.ValuesRMSE3[i];
                values[3] = rmseClass.ValuesRMSE4[i];
                values[4] = rmseClass.ValuesRMSE5[i];
                valMixed1.Fields.Add("value", new InfluxValueField(values[0]));
                valMixed2.Fields.Add("value", new InfluxValueField(values[1]));
                valMixed3.Fields.Add("value", new InfluxValueField(values[2]));
                valMixed4.Fields.Add("value", new InfluxValueField(values[3]));
                valMixed5.Fields.Add("value", new InfluxValueField(values[4]));
                var r = await client.PostPointAsync(nameDB, valMixed1);

                var s = await client.PostPointAsync(nameDB, valMixed2);

                var t = await client.PostPointAsync(nameDB, valMixed3);

                var u = await client.PostPointAsync(nameDB, valMixed4);

                var f = await client.PostPointAsync(nameDB, valMixed5);

                label.Text = $"Запись значений RMSE (Выполнено {i/count}%)";
            }
            for (int i = 0; i < dataClass.countOfElements; i++)
            {
                var valMixed6  = new InfluxDatapoint <InfluxValueField>();
                var valMixed7  = new InfluxDatapoint <InfluxValueField>();
                var valMixed8  = new InfluxDatapoint <InfluxValueField>();
                var valMixed9  = new InfluxDatapoint <InfluxValueField>();
                var valMixed10 = new InfluxDatapoint <InfluxValueField>();
                var valMixed11 = new InfluxDatapoint <InfluxValueField>();
                valMixed6.UtcTimestamp     = dataClass.famousDates[i].ToUniversalTime();
                valMixed7.UtcTimestamp     = dataClass.famousDates[i].ToUniversalTime();
                valMixed8.UtcTimestamp     = dataClass.famousDates[i].ToUniversalTime();
                valMixed9.UtcTimestamp     = dataClass.famousDates[i].ToUniversalTime();
                valMixed10.UtcTimestamp    = dataClass.famousDates[i].ToUniversalTime();
                valMixed11.UtcTimestamp    = dataClass.famousDates[i].ToUniversalTime();
                valMixed6.MeasurementName  = "ValuesOne";
                valMixed7.MeasurementName  = "ValuesTwo";
                valMixed8.MeasurementName  = "ValuesThree";
                valMixed9.MeasurementName  = "ValuesFour";
                valMixed10.MeasurementName = "ValuesFive";
                valMixed11.MeasurementName = "FamousValues";
                double[] values1 = new double[6];
                values1[0] = logicClass.ValuesLog1[i];
                values1[1] = logicClass.ValuesLog2[i];
                values1[2] = logicClass.ValuesLog3[i];
                values1[3] = logicClass.ValuesLog4[i];
                values1[4] = logicClass.ValuesLog5[i];
                values1[5] = dataClass.famousValues[i];
                valMixed6.Fields.Add("value", new InfluxValueField(values1[0]));
                valMixed7.Fields.Add("value", new InfluxValueField(values1[1]));
                valMixed8.Fields.Add("value", new InfluxValueField(values1[2]));
                valMixed9.Fields.Add("value", new InfluxValueField(values1[3]));
                valMixed10.Fields.Add("value", new InfluxValueField(values1[4]));
                valMixed11.Fields.Add("value", new InfluxValueField(values1[5]));
                var r1 = await client.PostPointAsync(nameDB, valMixed6);

                var s1 = await client.PostPointAsync(nameDB, valMixed7);

                var t1 = await client.PostPointAsync(nameDB, valMixed8);

                var u1 = await client.PostPointAsync(nameDB, valMixed9);

                var f1 = await client.PostPointAsync(nameDB, valMixed10);

                var f2 = await client.PostPointAsync(nameDB, valMixed11);

                label.Text = $"Запись значений алгоритмов (Выполнено {i/count2}%)";
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            string sSource;
            string sLog;
            string sEvent;

            sSource = "AwesomeMiner2InfluxDb";
            sLog    = "Application";

            if (!EventLog.SourceExists(sSource))
            {
                EventLog.CreateEventSource(sSource, sLog);
            }

            try
            {
                var appSettings = ConfigurationManager.AppSettings;
                var host        = appSettings["Host"];
                var minerId     = appSettings["MinerId"];
                var url         = $"http://{host}/api/miners/{minerId}";
                var request     = WebRequest.Create(url);
                request.ContentType = "application/json; charset=utf-8";
                string text;
                var    response = (HttpWebResponse)request.GetResponse();
                Console.WriteLine("Reading json data from AwesomeMiner api");
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    text = sr.ReadToEnd();
                }

                AwesomeInfo awesomeInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <AwesomeInfo>(text);
                Console.WriteLine("Json received and parsed");
                var influxUrl    = appSettings["InfluxDbHost"];
                var influxDbName = appSettings["InfluxDbName"];

                Console.WriteLine($"Connecting to Influxdb @ {influxUrl} DBName: {influxDbName}");
                InfluxDBClient client = new InfluxDBClient($"http://{influxUrl}");
                client.CreateDatabaseAsync(influxDbName).Wait();
                var utcNow   = DateTime.UtcNow;
                var valMixed = new InfluxDatapoint <InfluxValueField>();
                valMixed.UtcTimestamp = utcNow;
                valMixed.Tags.Add("MinerId", awesomeInfo.id.ToString());
                valMixed.Tags.Add("Algo", awesomeInfo.coinInfo.displayName);
                valMixed.Tags.Add("Pool", awesomeInfo.poolList[0].name);
                var hashRate       = awesomeInfo.speedInfo.hashrate.Substring(0, awesomeInfo.speedInfo.hashrate.IndexOf(" "));
                var hashRateDouble = double.Parse(hashRate);
                valMixed.Fields.Add("HashRate", new InfluxValueField(hashRateDouble));
                var profitPerday    = double.Parse(awesomeInfo.coinInfo.profitPerDay.Substring(1));
                var profitPerMonth  = double.Parse(awesomeInfo.coinInfo.profitPerMonth.Substring(1));
                var revenuePerDay   = double.Parse(awesomeInfo.coinInfo.revenuePerDay.Substring(1));
                var revenuePerMonth = double.Parse(awesomeInfo.coinInfo.revenuePerMonth.Substring(1));
                valMixed.Fields.Add("ProfitPerDay", new InfluxValueField(profitPerday));
                valMixed.Fields.Add("ProfitPerMonth", new InfluxValueField(profitPerMonth));
                valMixed.Fields.Add("RevenuePerDay", new InfluxValueField(revenuePerDay));
                valMixed.Fields.Add("RevenuePerMonth", new InfluxValueField(revenuePerMonth));


                valMixed.MeasurementName = $"Miner.{awesomeInfo.id}";

                Console.WriteLine("Trying to write miner data to DB");
                client.PostPointAsync(influxDbName, valMixed).Wait();
                EventLog.WriteEntry(sSource, "Miner data written successfully", EventLogEntryType.Information);
                Console.WriteLine("Miner data written successfully");

                foreach (var gpuInfo in awesomeInfo.gpuList)
                {
                    var gpuToInflux = new InfluxDatapoint <InfluxValueField>();
                    gpuToInflux.UtcTimestamp = utcNow;
                    gpuToInflux.Tags.Add("GPUName", gpuInfo.name);
                    gpuToInflux.Fields.Add("Temperature", new InfluxValueField(gpuInfo.deviceInfo.temperature));
                    gpuToInflux.Fields.Add("FanPercent", new InfluxValueField(gpuInfo.deviceInfo.fanPercent));
                    gpuToInflux.Fields.Add("FanSpeed", new InfluxValueField(gpuInfo.deviceInfo.fanSpeed));
                    gpuToInflux.Fields.Add("GpuClock", new InfluxValueField(gpuInfo.deviceInfo.gpuClock));
                    gpuToInflux.Fields.Add("MemoryClock", new InfluxValueField(gpuInfo.deviceInfo.gpuMemoryClock));
                    var intensity = double.Parse(gpuInfo.deviceInfo.intensity);
                    gpuToInflux.Fields.Add("Intensity", new InfluxValueField(intensity));
                    var gpuHashrate       = gpuInfo.speedInfo.hashrate.Substring(0, gpuInfo.speedInfo.hashrate.IndexOf(" "));
                    var gpuHashrateDouble = double.Parse(gpuHashrate);
                    gpuToInflux.Fields.Add("Speed", new InfluxValueField(gpuHashrateDouble));

                    gpuToInflux.MeasurementName = gpuInfo.name.Replace(' ', '_');

                    Console.WriteLine("Trying to write GPU info to DB");
                    client.PostPointAsync(influxDbName, gpuToInflux).Wait();
                    Console.WriteLine("GPU info written successfully");
                }
            }
            catch (Exception e)
            {
                // Console.WriteLine(e);
                EventLog.WriteEntry(sSource, e.Message, EventLogEntryType.Error);
            }
        }
        static async Task Main(string[] args)
        {
            string SENTRON_IP = Environment.GetEnvironmentVariable("SENTRON_IP");
            string SENTRON_ID = Environment.GetEnvironmentVariable("SENTRON_ID");
            string INFLUXDB_IP = Environment.GetEnvironmentVariable("INFLUXDB_IP");
            string INFLUXDB_PORT = Environment.GetEnvironmentVariable("INFLUXDB_PORT");
            string INFLUXDB_DATABASE = Environment.GetEnvironmentVariable("INFLUXDB_DATABASE");
            string INFLUXDB_USERNAME = Environment.GetEnvironmentVariable("INFLUXDB_USERNAME");
            string INFLUXDB_PASSWORD = Environment.GetEnvironmentVariable("INFLUXDB_PASSWORD");
            int    RETRY, READING;

            if (!Int32.TryParse(Environment.GetEnvironmentVariable("RETRY"), out RETRY))
            {
                Console.WriteLine("Invalid RETRY using 10");
                RETRY = 10 * 1000;
            }
            else
            {
                RETRY = RETRY * 1000;
            }
            if (!Int32.TryParse(Environment.GetEnvironmentVariable("READING"), out READING))
            {
                Console.WriteLine("Invalid READING using 5");
                READING = 5 * 1000;
            }
            else
            {
                READING = READING * 1000;
            }

            string statusURLString = "http://" + SENTRON_IP + "/";
            string influxDbURL     = "http://" + INFLUXDB_IP + ":" + INFLUXDB_PORT;

            Console.WriteLine("Running with below parameters");
            Console.WriteLine("\tSENTRON_IP {0}", SENTRON_IP);
            Console.WriteLine("\tSENTRON_ID {0}", SENTRON_ID);
            Console.WriteLine("\tINFLUXDB_IP {0}", INFLUXDB_IP);
            Console.WriteLine("\tINFLUXDB_PORT {0}", INFLUXDB_PORT);
            Console.WriteLine("\tINFLUXDB_DATABASE {0}", INFLUXDB_DATABASE);
            Console.WriteLine("\tINFLUXDB_USERNAME {0}", INFLUXDB_USERNAME);
            Console.WriteLine("\tINFLUXDB_PASSWORD {0}", INFLUXDB_PASSWORD);
            Console.WriteLine("\tRETRY {0}", RETRY / 1000);
            Console.WriteLine("\tREADING {0}", READING / 1000);
            Console.WriteLine("\n\nUsing Status URL   : {0}", statusURLString);
            Console.WriteLine("Using InfluxDB URL : {0}", influxDbURL);


            while (true)
            {
                InfluxDBClient influxClient = new InfluxDBClient(influxDbURL, INFLUXDB_USERNAME, INFLUXDB_PASSWORD);
                try
                {
                    while (true)
                    {
                        byte unitIdentifier = 0xFF;

                        client.Connect(IPAddress.Parse(SENTRON_IP));
                        var data = client.ReadHoldingRegisters(unitIdentifier, 200, 122).ToArray();

                        var valMixed = new InfluxDatapoint <InfluxValueField>();
                        valMixed.UtcTimestamp = DateTime.UtcNow;
                        valMixed.Tags.Add("id", SENTRON_ID);
                        valMixed.MeasurementName = "METER_DATA";
                        valMixed.Precision       = TimePrecision.Seconds;

                        var Va = ToFloatStart201(data, 201);
                        var Vb = ToFloatStart201(data, 203);
                        var Vc = ToFloatStart201(data, 205);
                        var VN = ToFloatStart201(data, 207);

                        valMixed.Fields.Add("Va", new InfluxValueField(Va));
                        valMixed.Fields.Add("Vb", new InfluxValueField(Vb));
                        valMixed.Fields.Add("Vc", new InfluxValueField(Vc));
                        valMixed.Fields.Add("VN", new InfluxValueField(VN));

                        var Ia = ToFloatStart201(data, 209);
                        var Ib = ToFloatStart201(data, 211);
                        var Ic = ToFloatStart201(data, 213);
                        var IN = ToFloatStart201(data, 215);

                        valMixed.Fields.Add("Ia", new InfluxValueField(Ia));
                        valMixed.Fields.Add("Ib", new InfluxValueField(Ib));
                        valMixed.Fields.Add("Ic", new InfluxValueField(Ic));
                        valMixed.Fields.Add("IN", new InfluxValueField(IN));

                        var Vab = ToFloatStart201(data, 217);
                        var Vbc = ToFloatStart201(data, 219);
                        var Vca = ToFloatStart201(data, 221);

                        valMixed.Fields.Add("Vab", new InfluxValueField(Vab));
                        valMixed.Fields.Add("Vbc", new InfluxValueField(Vbc));
                        valMixed.Fields.Add("Vca", new InfluxValueField(Vca));

                        var Vavg = ToFloatStart201(data, 223);
                        var Iavg = ToFloatStart201(data, 225);

                        valMixed.Fields.Add("Vavg", new InfluxValueField(Vavg));
                        valMixed.Fields.Add("Iavg", new InfluxValueField(Iavg));

                        var Pa = ToFloatStart201(data, 227);
                        var Pb = ToFloatStart201(data, 229);
                        var Pc = ToFloatStart201(data, 231);
                        var P  = ToFloatStart201(data, 233);

                        valMixed.Fields.Add("Pa", new InfluxValueField(Pa));
                        valMixed.Fields.Add("Pb", new InfluxValueField(Pb));
                        valMixed.Fields.Add("Pc", new InfluxValueField(Pc));
                        valMixed.Fields.Add("P", new InfluxValueField(P));

                        var Qa = ToFloatStart201(data, 235);
                        var Qb = ToFloatStart201(data, 237);
                        var Qc = ToFloatStart201(data, 239);
                        var Q  = ToFloatStart201(data, 241);

                        var Sa = ToFloatStart201(data, 243);
                        var Sb = ToFloatStart201(data, 245);
                        var Sc = ToFloatStart201(data, 247);
                        var S  = ToFloatStart201(data, 249);

                        var cos_phi_a = ToFloatStart201(data, 251);
                        var cos_phi_b = ToFloatStart201(data, 253);
                        var cos_phi_c = ToFloatStart201(data, 255);
                        var cos_phi   = ToFloatStart201(data, 257);

                        var PFa = ToFloatStart201(data, 259);
                        var PFb = ToFloatStart201(data, 261);
                        var PFc = ToFloatStart201(data, 263);
                        var PF  = ToFloatStart201(data, 265);

                        valMixed.Fields.Add("PFa", new InfluxValueField(PFa));
                        valMixed.Fields.Add("PFb", new InfluxValueField(PFb));
                        valMixed.Fields.Add("PFc", new InfluxValueField(PFc));
                        valMixed.Fields.Add("PF", new InfluxValueField(PF));

                        var phi_a = ToFloatStart201(data, 267);
                        var phi_b = ToFloatStart201(data, 269);
                        var phi_c = ToFloatStart201(data, 271);
                        var phi   = ToFloatStart201(data, 273);

                        var f  = ToFloatStart201(data, 275);
                        var U2 = ToFloatStart201(data, 277);

                        var THDS_Va_Vab = ToFloatStart201(data, 295);
                        var THDS_Vb_Vbc = ToFloatStart201(data, 297);
                        var THDS_Vc_Vca = ToFloatStart201(data, 299);

                        var THDS_Ia = ToFloatStart201(data, 301);
                        var THDS_Ib = ToFloatStart201(data, 303);
                        var THDS_Ic = ToFloatStart201(data, 305);

                        var V_phi_12 = ToFloatStart201(data, 307);
                        var V_phi_13 = ToFloatStart201(data, 309);
                        var I_phi_12 = ToFloatStart201(data, 311);
                        var I_phi_13 = ToFloatStart201(data, 313);

                        var Q1a = ToFloatStart201(data, 315);
                        var Q1b = ToFloatStart201(data, 317);
                        var Q1c = ToFloatStart201(data, 319);
                        var Q1  = ToFloatStart201(data, 321);

                        var r = await influxClient.PostPointAsync(INFLUXDB_DATABASE, valMixed);

                        Console.WriteLine(r);
                        Thread.Sleep(READING);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
                client.Disconnect();
                influxClient.Dispose();
                Thread.Sleep(RETRY);
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            string sSource;
            string sLog;
            string sEvent;

            sSource = "PoolWalletStatus2InfluxDb";
            sLog    = "Application";

            if (!EventLog.SourceExists(sSource))
            {
                EventLog.CreateEventSource(sSource, sLog);
            }

            var appSettings = ConfigurationManager.AppSettings;
            var btcAddress  = appSettings["BTCAddress"];


            var zpoolUrl     = ZpoolApiURL + btcAddress;
            var ahashpoolUrl = AhashpoolApiURL + btcAddress;
            var zergpoolUrl  = ZergpoolApiURL + btcAddress;

            var influxUrl    = appSettings["InfluxDbHost"];
            var influxDbName = appSettings["InfluxDbName"];

            var utcNow = DateTime.UtcNow;

            try
            {
                var request = WebRequest.Create(zpoolUrl);
                request.ContentType = "application/json; charset=utf-8";
                string text;
                var    response = (HttpWebResponse)request.GetResponse();

                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    text = sr.ReadToEnd();
                }

                ZpoolStatus zpoolStatus = Newtonsoft.Json.JsonConvert.DeserializeObject <ZpoolStatus>(text);

                Console.WriteLine("Json received and parsed");


                Console.WriteLine($"Connecting to Influxdb @ {influxUrl} DBName: {influxDbName}");
                InfluxDBClient client = new InfluxDBClient($"http://{influxUrl}");
                client.CreateDatabaseAsync(influxDbName).Wait();

                var valMixed = new InfluxDatapoint <InfluxValueField>();
                valMixed.UtcTimestamp = utcNow;
                valMixed.Tags.Add("BTC_Address", btcAddress);
                valMixed.Fields.Add("currency", new InfluxValueField(zpoolStatus.currency));
                valMixed.Fields.Add("unsold", new InfluxValueField(zpoolStatus.unsold));
                valMixed.Fields.Add("balance", new InfluxValueField(zpoolStatus.balance));
                valMixed.Fields.Add("total_unpaid", new InfluxValueField(zpoolStatus.unpaid));
                valMixed.Fields.Add("total_paid", new InfluxValueField(zpoolStatus.paid24h));
                valMixed.Fields.Add("total_earned", new InfluxValueField(zpoolStatus.total));

                valMixed.MeasurementName = "Zpool";

                Console.WriteLine("Trying to write zpool data to DB");
                client.PostPointAsync(influxDbName, valMixed).Wait();
            }
            catch (Exception e)
            {
                EventLog.WriteEntry(sSource, "Error while writing zpool data: " + e.Message, EventLogEntryType.Error);
            }
            try
            {
                var request = WebRequest.Create(ahashpoolUrl);
                request.ContentType = "application/json; charset=utf-8";
                string text;
                var    response = (HttpWebResponse)request.GetResponse();

                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    text = sr.ReadToEnd();
                }

                AhashPoolStatus ahashPoolStatus = Newtonsoft.Json.JsonConvert.DeserializeObject <AhashPoolStatus>(text);
                InfluxDBClient  client          = new InfluxDBClient($"http://{influxUrl}");
                client.CreateDatabaseAsync(influxDbName).Wait();
                var valMixed = new InfluxDatapoint <InfluxValueField>();
                valMixed = new InfluxDatapoint <InfluxValueField>();
                valMixed.UtcTimestamp = utcNow;
                valMixed.Tags.Add("BTC_Address", btcAddress);
                valMixed.Fields.Add("currency", new InfluxValueField(ahashPoolStatus.currency));
                valMixed.Fields.Add("unsold", new InfluxValueField(ahashPoolStatus.unsold));
                valMixed.Fields.Add("balance", new InfluxValueField(ahashPoolStatus.balance));
                valMixed.Fields.Add("total_unpaid", new InfluxValueField(ahashPoolStatus.total_unpaid));
                valMixed.Fields.Add("total_paid", new InfluxValueField(ahashPoolStatus.total_paid));
                valMixed.Fields.Add("total_earned", new InfluxValueField(ahashPoolStatus.total_earned));

                valMixed.MeasurementName = "Ahashpool";

                Console.WriteLine("Trying to write ahashpool data to DB");
                client.PostPointAsync(influxDbName, valMixed).Wait();
            }
            catch (Exception e)
            {
                EventLog.WriteEntry(sSource, "Error while writing ahashpool data: " + e.Message, EventLogEntryType.Error);
            }
            try {
                var request = WebRequest.Create(zergpoolUrl);
                request.ContentType = "application/json; charset=utf-8";
                string text;
                var    response = (HttpWebResponse)request.GetResponse();

                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    text = sr.ReadToEnd();
                }

                ZpoolStatus    zergpoolStatus = Newtonsoft.Json.JsonConvert.DeserializeObject <ZpoolStatus>(text);
                InfluxDBClient client         = new InfluxDBClient($"http://{influxUrl}");
                client.CreateDatabaseAsync(influxDbName).Wait();
                var valMixed = new InfluxDatapoint <InfluxValueField>();
                valMixed = new InfluxDatapoint <InfluxValueField>();
                valMixed.UtcTimestamp = utcNow;
                valMixed.Tags.Add("BTC_Address", btcAddress);
                valMixed.Fields.Add("currency", new InfluxValueField(zergpoolStatus.currency));
                valMixed.Fields.Add("unsold", new InfluxValueField(zergpoolStatus.unsold));
                valMixed.Fields.Add("balance", new InfluxValueField(zergpoolStatus.balance));
                valMixed.Fields.Add("total_unpaid", new InfluxValueField(zergpoolStatus.unpaid));
                valMixed.Fields.Add("total_paid", new InfluxValueField(zergpoolStatus.paid24h));
                valMixed.Fields.Add("total_earned", new InfluxValueField(zergpoolStatus.total));

                valMixed.MeasurementName = "Zergpool";

                Console.WriteLine("Trying to write zergpool data to DB");
                client.PostPointAsync(influxDbName, valMixed).Wait();
            }
            catch (Exception e)
            {
                EventLog.WriteEntry(sSource, e.Message, EventLogEntryType.Error);
            }
        }