Ejemplo n.º 1
0
 private void LoadData()
 {
     if (!File.Exists("data.json"))
     {
         return;
     }
     using (StreamReader r = new StreamReader("data.json"))
     {
         string s     = r.ReadToEnd();
         JArray array = JArray.Parse(s);
         foreach (JObject obj in array)
         {
             string      name = obj["Name"].Value <string>();
             SensolusCfg cfg  = new SensolusCfg();
             cfg.Interval    = obj["Interval"].Value <int>();
             cfg.Host        = obj["Host"].Value <string>();
             cfg.ApiKey      = obj["ApiKey"].Value <string>();
             cfg.Port        = obj["Port"].Value <int>();
             cfg.Database    = obj["Database"].Value <string>();
             cfg.User        = obj["User"].Value <string>();
             cfg.Password    = obj["Password"].Value <string>();
             cfg.Pool        = obj["Pool"].Value <bool>();
             cfg.Clean       = obj["Clean"].Value <bool>();
             cfg.LastExecute = obj["LastExecute"].Value <DateTime>();
             Task.Run(() => {
                 SensolusCfg copyCfg = cfg;
                 copyCfg.Clean       = false;
                 copyCfg.Interval    = (int)(DateTime.Now - copyCfg.LastExecute).TotalMinutes;
                 DataProcessor dp    = new DataProcessor(copyCfg);
                 dp.Run(NpgsqlFactory.Instance);
                 cfg.LastExecute = DateTime.Now;
                 lock (connCfgs) {
                     if (!connCfgs.ContainsKey(name.ToLower()))
                     {
                         connCfgs.Add(name.ToLower(), cfg);
                     }
                 }
                 Responder.SuperRoot.CreateChild(name, "connNode").BuildNode();
             });
         }
     }
 }
Ejemplo n.º 2
0
        private void _createConnection(InvokeRequest request)
        {
            SensolusCfg cfg  = new SensolusCfg();
            string      name = request.Parameters["Name"].Value <String>();

            if (connCfgs.ContainsKey(name.ToLower()))
            {
                // ERROR
                return;
            }
            cfg.ApiKey   = request.Parameters["apiKey"].Value <String>();
            cfg.Host     = request.Parameters["DB Address"].Value <String>();
            cfg.Port     = request.Parameters["DB Port"].Value <int>();
            cfg.Database = request.Parameters["DB Name"].Value <String>();
            cfg.User     = request.Parameters["DB User"].Value <String>();
            cfg.Password = request.Parameters["DB Password"].Value <String>();
            cfg.Interval = request.Parameters["Interval (minutes)"].Value <int>();
            cfg.Pool     = request.Parameters["Pool"].Value <bool>();
            Task.Run(() =>
            {
                var copyCfg = cfg;
                if (request.Parameters["Old Data"].Value <bool>())
                {
                    copyCfg.Interval = (int)(DateTime.Now - new DateTime(1990, 1, 1)).TotalMinutes / 2;
                    copyCfg.Clean    = true;
                }
                DataProcessor dp = new DataProcessor(copyCfg);
                dp.Run(NpgsqlFactory.Instance);
                cfg.LastExecute = DateTime.Now;
                lock (connCfgs)
                {
                    connCfgs.Add(name.ToLower(), cfg);
                }
                SaveData();
            });
            Responder.SuperRoot.CreateChild(name, "connNode").BuildNode();
        }
 public DataProcessor(SensolusCfg cfg)
 {
     this.cfg = cfg;
     this.api = new API(cfg.ApiKey);
 }
Ejemplo n.º 4
0
        private async void _handleActivityNotification(InvokeRequest request)
        {
            Uri uri = new Uri("http://localhost" + request.Parameters[SensolusConstants.PATH].Value <string>());

            if (uri.Segments.Length <= 1)
            {
                return;
            }
            string context = uri.Segments[1].Replace("/", "");

            if (!connCfgs.ContainsKey(context))
            {
                return;
            }
            SensolusCfg cfg   = connCfgs[context];
            var         query = System.Web.HttpUtility.ParseQueryString(uri.Query);

            DateTime      start = DateTime.Now;
            DataProcessor dp    = new DataProcessor(cfg);

            IDbTransaction transaction = null;

            string serial = "";

            try
            {
                var connectionStringBuilder = NpgsqlFactory.Instance.CreateConnectionStringBuilder();
                connectionStringBuilder.ConnectionString = $"Server={cfg.Host};Database={cfg.Database};User ID={cfg.User};Password={cfg.Password}";
                using (DatabaseWrapper client = new DatabaseWrapper(NpgsqlFactory.Instance, connectionStringBuilder.ToString()))
                {
                    client.Open();
                    transaction = client.BeginTransaction();

                    //dp.FirstPhase(client);
                    List <DimTracker> trackers = client.GetDimTrackers();

                    FactActivity activity = new FactActivity();
                    activity.Id         = request.Parameters[SensolusConstants.ACTIVITY_ID].Value <long>();
                    activity.Evttime    = DateTime.Parse(request.Parameters[SensolusConstants.ACTIVITY_TIME].Value <string>());
                    activity.Inserttime = DateTime.Parse(request.Parameters[SensolusConstants.ACTIVITY_INSERTTIME].Value <string>());
                    activity.Serial     = request.Parameters[SensolusConstants.SERIAL].Value <string>();
                    activity.Evttype    = request.Parameters[SensolusConstants.ACTIVITY_STATE]?.Value <string>();
                    activity.Lat        = request.Parameters[SensolusConstants.ACTIVITY_LAT]?.Value <double?>();
                    activity.Lon        = request.Parameters[SensolusConstants.ACTIVITY_LON]?.Value <double?>();
                    activity.Src        = request.Parameters[SensolusConstants.ACTIVITY_SRC]?.Value <string>();
                    activity.Accuracy   = request.Parameters[SensolusConstants.ACTIVITY_ACCURACY]?.Value <int?>();
                    activity.Address    = request.Parameters[SensolusConstants.ACTIVITY_ADDRESS]?.Value <string>();
                    activity.Geozones   = request.Parameters[SensolusConstants.ACTIVITY_GEOZONE]?.Value <string>();

                    serial = activity.Serial;

                    DimTracker tracker = trackers.Find(x => x.Serial == activity.Serial);
                    if (tracker == default(DimTracker))
                    {
                        dp.FirstPhase(client);
                        tracker = client.GetDimTrackers().Find(x => x.Serial == activity.Serial);
                    }

                    activity.Trackerrecid = tracker.Recid;

                    DateTime epoch = new DateTime(1970, 1, 1);

                    if (tracker.TBRef != null && ThingsBoardURL != "")
                    {
                        // send to TB
                        JObject data = new JObject();
                        if (activity.Evttype == "GeozoneInsideAlertType")
                        {
                            data["inGz"] = true;
                            JArray geozones = JArray.Parse(activity.Geozones);
                            data["lastGz"] = geozones[0].Value <string>();
                            if (client.GetZones().Find(x => x.Id == long.Parse(data["lastGz"])) == default(DimZone))
                            {
                                dp.FirstPhase(client);
                            }
                            data["lastGzEntry"] = (activity.Evttime - epoch).TotalMilliseconds;
                        }

                        else if (activity.Evttype == "GeozoneOutsideAlertType")
                        {
                            data["inGz"]       = false;
                            data["lastGzExit"] = (activity.Evttime - epoch).TotalMilliseconds;
                        }

                        if (activity.Lat != null)
                        {
                            data["latitude"] = activity.Lat;
                        }
                        if (activity.Lon != null)
                        {
                            data["longitude"] = activity.Lon;
                        }
                        if (activity.Accuracy != null)
                        {
                            data["locAccuracy"] = activity.Accuracy;
                        }
                        if (activity.Lat != null || activity.Lon != null || activity.Accuracy != null)
                        {
                            data["lastLocTime"] = (activity.Evttime - epoch).TotalMilliseconds;
                        }
                        data["tracker"] = activity.Serial;

                        // send POST request to ThingsBoard
                        using (var httpClient = new HttpClient())
                        {
                            var response = await httpClient.PostAsync(
                                $"{ThingsBoardURL}/api/v1/{tracker.TBRef.Value.TBAt}/attributes",
                                new StringContent(data.ToString(), Encoding.UTF8, "application/json"));
                        }
                    }

                    transaction.Commit();
                }
            }
            catch (SqlException e)
            {
                Serilog.Log.Error(e.Message);
                Serilog.Log.Error(e.StackTrace);
                transaction?.Rollback();
                return;
            }
            catch (ArgumentException e)
            {
                //wrong SQL Connection string
                Serilog.Log.Error("Wrong SQL Connection string: " + $"Server={cfg.Host};Database={cfg.Database};User ID={cfg.User};Password=*****");
                Serilog.Log.Error(e.Message);
                Serilog.Log.Error(e.StackTrace);
                return;
            }
            catch (Exception e)
            {
                Serilog.Log.Error("Unexpected error");
                Serilog.Log.Error(e.Message);
                Serilog.Log.Error(e.StackTrace);
                return;
            }

            TimeSpan duration = DateTime.Now - start;

            try
            {
                var connectionStringBuilder = NpgsqlFactory.Instance.CreateConnectionStringBuilder();
                connectionStringBuilder.ConnectionString = $"Server={cfg.Host};Database={cfg.Database};User ID={cfg.User};Password={cfg.Password}";
                using (DatabaseWrapper client = new DatabaseWrapper(NpgsqlFactory.Instance, connectionStringBuilder.ToString()))
                {
                    client.Open();
                    IDbCommand cmd = client.CreateCommand();
                    cmd.CommandText = $"INSERT INTO log (ts, duration, reqcount, initevent, serial) VALUES ({SqlConvert.Convert(DateTime.Now)}, {duration.TotalMilliseconds}, {dp.api.Count}, 'PN', {SqlConvert.Convert(serial)})";
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception e)
            {
                Serilog.Log.Error("Could not make log record");
                Serilog.Log.Error(e.Message);
                Serilog.Log.Error(e.StackTrace);
                return;
            }

            Serilog.Log.Information($"ts: {DateTime.Now}, duration: {duration.TotalMilliseconds}, reqCount: {dp.api.Count}, initevent: PN, serial: {serial}");
        }
Ejemplo n.º 5
0
        private void _handleAlertNotification(InvokeRequest request)
        {
            Uri uri = new Uri("http://localhost" + request.Parameters[SensolusConstants.PATH].Value <string>());

            if (uri.Segments.Length <= 1)
            {
                return;
            }
            string context = uri.Segments[1].Replace("/", "");

            if (!connCfgs.ContainsKey(context))
            {
                return;
            }
            SensolusCfg cfg   = connCfgs[context];
            var         query = System.Web.HttpUtility.ParseQueryString(uri.Query);

            DateTime       start       = DateTime.Now;
            DataProcessor  dp          = new DataProcessor(cfg);
            IDbTransaction transaction = null;

            string serial = "";

            try
            {
                var connectionStringBuilder = NpgsqlFactory.Instance.CreateConnectionStringBuilder();
                connectionStringBuilder.ConnectionString = $"Server={cfg.Host};Database={cfg.Database};User ID={cfg.User};Password={cfg.Password}";
                using (DatabaseWrapper client = new DatabaseWrapper(NpgsqlFactory.Instance, connectionStringBuilder.ToString()))
                {
                    client.Open();
                    transaction = client.BeginTransaction();

                    //dp.FirstPhase(client);

                    serial = request.Parameters[SensolusConstants.SERIAL]?.Value <string>();

                    FactActivity      latestActivity = client.GetLatestActivity(serial);
                    int               halfMinutes    = (int)Math.Ceiling((DateTime.Now - latestActivity.Evttime).TotalMinutes / 2);
                    List <DimTracker> trackers       = new List <DimTracker>();
                    DimTracker        tracker        = client.GetDimTracker(serial);
                    if (tracker == default(DimTracker))
                    {
                        dp.FirstPhase(client);
                        tracker = client.GetDimTracker(serial);
                    }
                    trackers.Add(tracker);
                    dp.SecondPhase(client, halfMinutes, trackers);
                    dp.ThirdPhase(client, new string[] { serial });

                    transaction.Commit();
                }
            }
            catch (SqlException e)
            {
                Serilog.Log.Error(e.Message);
                Serilog.Log.Error(e.StackTrace);
                transaction?.Rollback();
                return;
            }
            catch (ArgumentException e)
            {
                //wrong SQL Connection string
                Serilog.Log.Error("Wrong SQL Connection string: " + $"Server={cfg.Host};Database={cfg.Database};User ID={cfg.User};Password=*****");
                Serilog.Log.Error(e.Message);
                Serilog.Log.Error(e.StackTrace);
                return;
            }
            catch (Exception e)
            {
                Serilog.Log.Error("Unexpected error");
                Serilog.Log.Error(e.Message);
                Serilog.Log.Error(e.StackTrace);
                return;
            }

            TimeSpan duration = DateTime.Now - start;

            try
            {
                var connectionStringBuilder = NpgsqlFactory.Instance.CreateConnectionStringBuilder();
                connectionStringBuilder.ConnectionString = $"Server={cfg.Host};Database={cfg.Database};User ID={cfg.User};Password={cfg.Password}";
                using (DatabaseWrapper client = new DatabaseWrapper(NpgsqlFactory.Instance, connectionStringBuilder.ToString()))
                {
                    client.Open();
                    IDbCommand cmd = client.CreateCommand();
                    cmd.CommandText = $"INSERT INTO log (ts, duration, reqcount, initevent, serial) VALUES ({SqlConvert.Convert(DateTime.Now)}, {duration.TotalMilliseconds}, {dp.api.Count}, 'PN', {SqlConvert.Convert(serial)})";
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception e)
            {
                Serilog.Log.Error("Could not make log record");
                Serilog.Log.Error(e.Message);
                Serilog.Log.Error(e.StackTrace);
                return;
            }

            Serilog.Log.Information($"ts: {DateTime.Now}, duration: {duration.TotalMilliseconds}, reqCount: {dp.api.Count}, initevent: PN, serial: {serial}");
        }