예제 #1
0
 public IGetResponse GetConfig()
 {
     Log.Info("GetConfig");
     return(new GetResponse(
                GetResponse.ResponseStatus.OK,
                WorkersManager.GetWorkersManager().Config));
 }
예제 #2
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
#if DEBUG
            LogManagerFactory.DefaultConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new StreamingFileTarget());
            LogManagerFactory.DefaultConfiguration.AddTarget(LogLevel.Trace, LogLevel.Fatal, new EtwTarget());
#else
            LogManagerFactory.DefaultConfiguration.AddTarget(LogLevel.Info, LogLevel.Fatal, new FileStreamingTarget());
#endif
            try
            {
                // setup the global crash handler...
                //GlobalCrashHandler.Configure();
                Log = LogManagerFactory.DefaultLogManager.GetLogger <PestoreClientBackgroundTask>();
                Log.Info($"Started PestoreClientBackgroundTask {GetAppVersion()}");
                man        = WorkersManager.GetWorkersManager();
                restRerver = new RestServer();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                man.Start();
                restRerver.Run();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                taskInstance.Canceled += TaskInstance_Canceled;
                deferral = taskInstance.GetDeferral();
            } catch (Exception ex)
            {
                Log.Fatal("Unexped exception", ex);
            }
            Log.Info("Stopped");
        }
예제 #3
0
        private double GetQueryResult(string field, string function)
        {
            var    dbConfig   = WorkersManager.GetWorkersManager().Config;
            var    location   = dbConfig.Location != null ? dbConfig.Location : "unknown";
            var    fluxTables = dbQueryApi.Query(string.Format(FluxQueryTemplate, dbConfig.Bucket, field, location, function), dbConfig.OrgId).GetAwaiter().GetResult();
            object value      = null;

            fluxTables.ForEach(fluxTable =>
            {
                var fluxRecords = fluxTable.Records;
                fluxRecords.ForEach(fluxRecord =>
                {
                    //Log.Debug($"GetQueryResul: {fluxRecord.GetTime()}: {fluxRecord.GetValue()}");
                    value = (double)fluxRecord.GetValue();
                });
            });
            if (value != null)
            {
                return((double)value);
            }
            else
            {
                return(double.NaN);
            }
        }
예제 #4
0
        public IPutResponse UpdateConfig([FromContent] Config data)
        {
            Log.Info("UpdateConfig");
            Log.Debug($"Data: {data}");
            var config     = WorkersManager.GetWorkersManager().Config;
            var urlChanged = !data.HubUrl.Equals(config.HubUrl) || !data.Url.Equals(config.Url);

            config.Update(data);
            WorkersManager.GetWorkersManager().Config.Save(LocalSettingsConfigProvider.Instance);
            if (urlChanged)
            {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                WorkersManager.GetWorkersManager().Restart();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
            return(new PutResponse(PutResponse.ResponseStatus.NoContent));
        }
예제 #5
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);
                }
            }
        }
예제 #6
0
        private void Subscribe()
        {
            var status = SubscriptionStatus.None;
            //todo: url to ui
            RestClient hubClient = new RestClient(hubUrl);

            Log.Info("Subscription check");

            var request = new RestRequest("register/{id}", Method.GET);

            //equest.AddUrlSegment("id", "1234-5678-9012-3456"); // replaces matching token in request.Resource
            request.AddUrlSegment("id", GetSerialNumber());

            hubClient.UserAgent = "Win10IoTCore.PetStore";

            var response = hubClient.Execute(request);

            if (response.ErrorException != null)
            {
                status      = SubscriptionStatus.Error;
                ErrorString = "Subscription error: " + response.ErrorException.Message;
                Log.Error("Subscribe Error: ", response.ErrorException);
                //probably temporarly net or server error, prolong delay
                if (delay == originalDelay)
                {
                    delay *= 5;
                    Log.Info($"Prolonging delay to {delay}");
                }
            }
            else
            {
                Log.Debug("statusCode: " + (int)response.StatusCode);
                switch (response.StatusCode)
                {
                case System.Net.HttpStatusCode.OK:
                    status = SubscriptionStatus.Accepted;    // "Device accepted";
                    WorkersManager.GetWorkersManager().Config.UpdateFromSubscriptionRensponseJson(response.Content);
                    WorkersManager.GetWorkersManager().Config.Save(LocalSettingsConfigProvider.Instance);
                    break;

                case System.Net.HttpStatusCode.Created:
                    status = SubscriptionStatus.WaitingForAuthorization;    // "Waiting for device authorization";
                    break;

                case System.Net.HttpStatusCode.NoContent:
                    status = SubscriptionStatus.Subscribed;
                    break;

                default:
                    status      = SubscriptionStatus.Error;
                    ErrorString = "Uknown response: " + response.StatusCode.ToString();
                    break;
                }
                if (delay != originalDelay)
                {
                    delay = originalDelay;
                    Log.Info($"Restoring delay to {delay}");
                }
            }
            if (status != lastStatus)
            {
                lastStatus = status;
                OnSubscriptionStatusChanged(status);
            }
        }
예제 #7
0
        private void WriteToDb()
        {
            if (dbClient != null)
            {
                try
                {
                    Log.Trace("WriteToDb");
                    var data     = OverviewData.GetOverviewData();
                    var dbConfig = WorkersManager.GetWorkersManager().Config;
                    var point    = Point.Measurement("air")
                                   .Tag("location", dbConfig.Location != null ? dbConfig.Location : "prosek")
                                   .Tag("device_id", dbConfig.DeviceId);
                    int validFields = 0;
                    if (!double.IsNaN(data.CurrentTemperature))
                    {
                        point.Field("temperature", data.CurrentTemperature);
                        ++validFields;
                    }
                    if (!double.IsNaN(data.CurrentPressure))
                    {
                        point.Field("pressure", data.CurrentPressure);
                        ++validFields;
                    }
                    if (!double.IsNaN(data.CurrentHumidity))
                    {
                        point.Field("humidity", data.CurrentHumidity);
                        ++validFields;
                    }
                    if (validFields > 0)
                    {
                        using (var dbWriteApi = dbClient.GetWriteApi())
                        {
                            dbWriteApi.EventHandler += DbWriteApi_EventHandler;
                            dbWriteApi.WritePoint(dbConfig.Bucket, dbConfig.OrgId, point);
                            dbWriteApi.Flush();
                        }

                        if (delay != originalDelay)
                        {
                            delay = originalDelay;
                            Log.Info($"Restoring delay to {delay}");
                        }
                    }
                    else
                    {
                        Log.Debug("InfluxDbWorker:WriteToDb - nothing to write, all values are invalid");
                    }
                }
                catch (Exception ex)
                {
                    Log.Error("Db Write error", ex);
                    OnStatusChanged("DB Write Error: " + ex.Message);
                    //probably temporarly net down or db error, prolong delay to not overload with exception
                    if (delay == originalDelay)
                    {
                        delay *= 5;
                        Log.Info($"Prolonging delay to {delay}");
                    }
                }
            }
        }