private void CreateNewThing(string id, string observationTopic, decimal?lat, decimal?lon)
        {
            string error = "";

            long thingID = 0;

            //Create a thing
            IO.Swagger.DatabaseInterface.DBThing dT = new IO.Swagger.DatabaseInterface.DBThing();
            if (dT.AddThing("Thing" + id, thingType, "Autogenerated Thing by OGC Discovery Manager", 1, lat, lon, id, ref error, ref thingID))
            {
                long obsID = 0;
                //Add observation
                IO.Swagger.DatabaseInterface.DBObservation dO = new IO.Swagger.DatabaseInterface.DBObservation();
                if (thingType == "SoundmeterAggregate")
                {
                    id = "";
                }
                //Tmp fix
                if (latestObsExtraValue == "AGGREGATE")
                {
                    id = "AGGREGATE";
                }
                dO.AddUpdateObservation((int)thingID, observationTopic + ":" + id + ":", DateTime.Now, "", latestObsExtraValue, null, null, ref error, ref obsID);
            }
        }
        private void CreateNewWearableAndPerson(string id, string observationTopic)
        {
            string error      = "";
            int    personID   = 0;
            long   thingID    = 0;
            long   wearableID = 0;

            //First Create a person
            IO.Swagger.DatabaseInterface.DBPerson dP = new IO.Swagger.DatabaseInterface.DBPerson();
            if (dP.AddPerson(0, "MONICA", "Wearer of " + id, "", "", 1, true, ref error, ref personID))
            {
                //Create a thing
                IO.Swagger.DatabaseInterface.DBThing dT = new IO.Swagger.DatabaseInterface.DBThing();
                if (dT.AddThing("Wearable" + id, thingType, "Autogenerated Thing by OGC Discovery Manager", 1, 0, 0, id, ref error, ref thingID))
                {
                    //Connect thing and person
                    IO.Swagger.DatabaseInterface.DBWearable dW = new IO.Swagger.DatabaseInterface.DBWearable();
                    if (dW.AddWearable(personID, (int)thingID, ref error, ref wearableID))
                    {
                        long obsID = 0;
                        //Add observation
                        IO.Swagger.DatabaseInterface.DBObservation dO = new IO.Swagger.DatabaseInterface.DBObservation();
                        dO.AddUpdateObservation((int)thingID, observationTopic + ":" + id + ":", DateTime.Now, "", "", personID, null, ref error, ref obsID);
                    }
                }
            }
        }
        private bool exist(string topic)
        {
            string error = "";

            IO.Swagger.DatabaseInterface.DBObservation obs = new IO.Swagger.DatabaseInterface.DBObservation();
            return(obs.ObservationStreamKnown(topic, ref error));
        }
        public void init()
        {
            IncidentType      = Environment.GetEnvironmentVariable("INCIDENT_TYPE");
            copApiBasePath    = Environment.GetEnvironmentVariable("COP_API_BASE_PATH");
            copApiBasePathHub = Environment.GetEnvironmentVariable("COP_API_BASE_PATH_HUB");
            copAuthToken      = Environment.GetEnvironmentVariable("COP_AUTH_TOKEN");
            string signalR     = Environment.GetEnvironmentVariable("signalR");
            string OnlySignalR = Environment.GetEnvironmentVariable("useOnlySignalR");
            string smqttDebug  = Environment.GetEnvironmentVariable("mqttDebug");

            GOSTQuery = Environment.GetEnvironmentVariable("GOSTQuery");
            string tmp = Environment.GetEnvironmentVariable("OGCServerBaseURL");

            if (tmp == null || tmp == "")
            {
                System.Console.WriteLine("Warning:Missing OGCServerBaseURL env variable.");
            }
            else
            {
                OGCServerBaseURL = tmp;
            }

            tmp = Environment.GetEnvironmentVariable("OGCServerUID");
            if (tmp == null || tmp == "")
            {
                System.Console.WriteLine("Warning:Missing OGCServerUID env variable.");
            }
            else
            {
                OGCServerUID = tmp;
            }

            tmp = Environment.GetEnvironmentVariable("OGCServerPwd");
            if (tmp == null || tmp == "")
            {
                System.Console.WriteLine("Warning:Missing OGCServerPwd env variable.");
            }
            else
            {
                OGCServerPwd = tmp;
            }

            tmp = Environment.GetEnvironmentVariable("OGCMQTTPrefix");
            if (tmp == null || tmp == "")
            {
                System.Console.WriteLine("Warning:Missing OGCMQTTPrefix env variable.");
            }
            else
            {
                OGCMQTTPrefix = tmp;
            }

            tmp = Environment.GetEnvironmentVariable("IncidentType");
            if (tmp == null || tmp == "")
            {
                System.Console.WriteLine("Warning:Missing IncidentType env variable.");
            }
            else
            {
                IncidentType = tmp;
            }

            if (signalR != null && signalR != "")
            {
                usesignalR = bool.Parse(signalR);
            }
            if (OnlySignalR != null && OnlySignalR != "")
            {
                useOnlySignalR = bool.Parse(OnlySignalR);
            }
            if (smqttDebug != null && smqttDebug != "")
            {
                mqttDebug = bool.Parse(smqttDebug);
            }


            //Find Datastreams to listen to
            XmlDocument xDoc       = null;
            string      JsonResult = "";
            WebClient   client     = new WebClient();

            try
            {
                string url = OGCServerBaseURL + "Datastreams?" + GOSTQuery;

                client.Encoding                = System.Text.Encoding.UTF8;
                client.Headers["Accept"]       = "application/json";
                client.Headers["Content-Type"] = "application/json";
                NetworkCredential myCreds = new NetworkCredential(OGCServerUID, OGCServerPwd);
                client.Credentials = myCreds;

                JsonResult = client.DownloadString(url);

                xDoc = JsonConvert.DeserializeXmlNode(JsonResult, "Root");
            }
            catch (WebException exception)
            {
                System.Console.WriteLine("Datastreams?$filter failed:" + exception.Message);
            }
            if (xDoc != null)
            {
                XmlNodeList foundOGCThings = xDoc.SelectNodes(".//value");
                foreach (XmlNode foundOGCThing in foundOGCThings)
                {
                    //Extract id and Observation link
                    string observationUrl = foundOGCThing.SelectSingleNode("Observations_x0040_iot.navigationLink").InnerText;



                    //Observation stream is the last part of the observationUrl http://monappdwp3.monica-cloud.eu:5050/gost_leeds/v1.0/Datastreams(3)/Observations
                    string[] parsedUrl        = observationUrl.Split("/");
                    string   observationTopic = OGCMQTTPrefix + "/" + parsedUrl[parsedUrl.GetUpperBound(0) - 1] + "/" + parsedUrl[parsedUrl.GetUpperBound(0)];

                    datastreams.Add(observationTopic);
                }
            }


            //Read sensor position for environment incidents
            if (IncidentType == "EnvironmentIncident")
            {
                //Fetch all datastreams that we want to handle
                string thingtype = "Windspeed";
                System.Console.WriteLine("Fetching:" + thingtype);
                string    JsonThingResult = "";
                WebClient wclient         = new WebClient();
                try
                {
                    wclient.Encoding                 = System.Text.Encoding.UTF8;
                    wclient.Headers["Accept"]        = "application/json";
                    wclient.Headers["Content-Type"]  = "application/json";
                    wclient.Headers["Authorization"] = copAuthToken;
                    string urn = copApiBasePath + "things?thingType=" + thingtype.Replace(" ", "%20");
                    JsonThingResult = wclient.DownloadString(urn);
                }
                catch (WebException exception)
                {
                    System.Console.WriteLine("Invokation error" + copApiBasePath + "things " + exception.Message);
                }

                string InnerText = JsonThingResult;


                // Build x-ref of thingId, personId, ZoneId mapped to topic.
                InnerText = "{Kalle:" + InnerText + "}";
                xSensors  = JsonConvert.DeserializeXmlNode(InnerText, "Root");
            }
            //Start DB Connect
            IO.Swagger.DatabaseInterface.DBObservation dbO = new IO.Swagger.DatabaseInterface.DBObservation();
            string error = "";

            dbO.ListObs(2, ref error);

            //Add the data streams we listen to.

            //How to listen for fighting?
            //How to listen to Button Pressed?


            //Setup SignalR
            connection = new HubConnectionBuilder()
                         .WithUrl(copApiBasePathHub + "signalR/COPUpdate")
                         .Build();
            connection.StartAsync().Wait();
            // Setup and start a managed MQTT client.
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(System.Guid.NewGuid().ToString())
                                             .WithKeepAlivePeriod(TimeSpan.FromSeconds(120))
                                             .WithCommunicationTimeout(TimeSpan.FromSeconds(60))
                                             //.WithCredentials("sm_user", "hemligt")
                                             .WithTcpServer("192.168.229.101")
                                             .Build())
                          .Build();

            ml = (MQTTnet.Extensions.ManagedClient.ManagedMqttClient) new MqttFactory().CreateManagedMqttClient();
            foreach (string topic in datastreams)
            {
                ml.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build());
            }
            //ml.ApplicationMessageReceived += (s, e) =>
            //{
            //    Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
            //    SaveToDB(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fff"), e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload)); ;

            //};
            ml.ApplicationMessageReceivedHandler =
                new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                if (IncidentType == "SoundIncident")
                {
                    ManageSoundIncident(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                }
                if (IncidentType == "CrowdIncident")
                {
                    ManageCrowdIncident(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                }
                if (IncidentType == "QueueIncident")
                {
                    ManageQueueIncident(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                }
                if (IncidentType == "EnvironmentIncident")
                {
                    ManageEnvironmentIncident(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                }
                if (IncidentType == "OverCrowding" || IncidentType == "ObjectDetection" || IncidentType == "PeopleFlow" || IncidentType == "FightDetected")
                {
                    ManageCameraIncident(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                }

                //if (e.ApplicationMessage.Topic.StartsWith("/DSS/"))
                //    ManageDSSIncident(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                //if (e.ApplicationMessage.Topic.StartsWith("GOST/"))
                //    ManageDSSIncident(e.ApplicationMessage.Topic, Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
            });
            if (mqttDebug)
            {
                MQTTnet.Diagnostics.MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    if (e.TraceMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                    }

                    CultureInfo ci = Thread.CurrentThread.CurrentCulture;
                    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("sv-SE");

                    string fileName = "MQTT" + DateTime.Now.ToShortDateString() + ".txt";

                    string logFolder = "." + Path.DirectorySeparatorChar;

                    FileStream   w  = File.Open(logFolder + fileName, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Write);
                    StreamWriter sw = new StreamWriter(w, System.Text.Encoding.Default);
                    sw.Write(trace + Environment.NewLine);
                    sw.Close();

                    Thread.CurrentThread.CurrentCulture = ci;
                };
            }
            ml.StartAsync(options).Wait();
        }
        public void CreateDatastreamsForSound()
        {
            List <IO.Swagger.Models.Thing> results = new List <IO.Swagger.Models.Thing>();

            IO.Swagger.DatabaseInterface.DBThing dbt = new IO.Swagger.DatabaseInterface.DBThing();
            string err = "";

            if (dbt.ListThings(thingType, ref err, ref results))
            {
                foreach (IO.Swagger.Models.Thing th in results)
                {
                    XmlDocument xDoc       = null;
                    string      JsonResult = "";
                    WebClient   client     = new WebClient();
                    try
                    {
                        string url = OGCServerBaseURL + "Datastreams?$filter=substringof('" + th.Name.Replace("Thing", "") + "',name)";

                        client.Encoding                = System.Text.Encoding.UTF8;
                        client.Headers["Accept"]       = "application/json";
                        client.Headers["Content-Type"] = "application/json";
                        NetworkCredential myCreds = new NetworkCredential(OGCServerUID, OGCServerPwd);
                        client.Credentials = myCreds;

                        JsonResult = client.DownloadString(url);

                        xDoc = JsonConvert.DeserializeXmlNode(JsonResult, "Root");
                    }
                    catch (WebException exception)
                    {
                        System.Console.WriteLine("Datastreams?$filter failed:" + exception.Message);
                    }
                    if (xDoc != null)
                    {
                        XmlNodeList foundOGCThings = xDoc.SelectNodes(".//value");
                        foreach (XmlNode foundOGCThing in foundOGCThings)
                        {
                            //Extract id and Observation link
                            string name           = foundOGCThing.SelectSingleNode("name").InnerText;
                            string observationUrl = foundOGCThing.SelectSingleNode("Observations_x0040_iot.navigationLink").InnerText;

                            //Id is the last part of the name
                            string[] parsedName = name.Split("/");
                            //string id = parsedName[parsedName.GetUpperBound(0)];
                            string id = "";
                            if (thingType == "SoundHeatmap")     //SoundHeatmap in a diffrent place
                            {
                                id = parsedName[1];
                            }
                            else
                            {
                                id = parsedName[parsedName.GetUpperBound(0)];
                            }
                            string type = "";
                            if (thingType == "SoundHeatmap")     //SoundHeatmap in a diffrent place
                            {
                                string tmptype = parsedName[parsedName.GetUpperBound(0)];
                                switch (tmptype)
                                {
                                case "SPL dB Cfull":
                                    type = "dbCheatmapfull";
                                    break;

                                case "SPL dB Afull":
                                    type = "dbAheatmapfull";
                                    break;

                                case "SPL dB Zfull":
                                    type = "dbZheatmapfull";
                                    break;

                                case "LCeq":
                                    type = "dbCheatmap";
                                    break;

                                case "LZeq":
                                    type = "dbZheatmap";
                                    break;

                                case "LAeq":
                                    type = "dbAheatmap";
                                    break;

                                default:
                                    type = "no match";
                                    break;
                                }
                            }
                            else
                            {
                                type = parsedName[parsedName.GetUpperBound(0) - 1];
                            };

                            //Observation stream is the last part of the observationUrl http://monappdwp3.monica-cloud.eu:5050/gost_leeds/v1.0/Datastreams(3)/Observations
                            string[] parsedUrl        = observationUrl.Split("/");
                            string   observationTopic = OGCMQTTPrefix + "/" + parsedUrl[parsedUrl.GetUpperBound(0) - 1] + "/" + parsedUrl[parsedUrl.GetUpperBound(0)];
                            if (!exist(observationTopic))
                            {
                                string error = "";
                                long   obsID = 0;
                                IO.Swagger.DatabaseInterface.DBObservation dO = new IO.Swagger.DatabaseInterface.DBObservation();
                                dO.AddUpdateObservation((int)th.Id, observationTopic + ":" + type + ":", DateTime.Now, "", latestObsExtraValue, null, null, ref error, ref obsID);
                            }
                        }
                    }
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Starts the updater
        /// </summary>
        public void init()
        {
            //Read environment settings.
            thingtype         = Environment.GetEnvironmentVariable("MONICA_THING_TYPE");
            copApiBasePath    = Environment.GetEnvironmentVariable("COP_API_BASE_PATH");
            copApiBasePathHub = Environment.GetEnvironmentVariable("COP_API_BASE_PATH_HUB");
            copAuthToken      = Environment.GetEnvironmentVariable("COP_AUTH_TOKEN");
            string signalR         = Environment.GetEnvironmentVariable("signalR");
            string OnlySignalR     = Environment.GetEnvironmentVariable("useOnlySignalR");
            string smqttDebug      = Environment.GetEnvironmentVariable("mqttDebug");
            string aggregateString = Environment.GetEnvironmentVariable("aggregate");

            if (signalR != null && signalR != "")
            {
                usesignalR = bool.Parse(signalR);
            }
            if (OnlySignalR != null && OnlySignalR != "")
            {
                useOnlySignalR = bool.Parse(OnlySignalR);
            }
            if (smqttDebug != null && smqttDebug != "")
            {
                mqttDebug = bool.Parse(smqttDebug);
            }
            if (aggregateString != null && aggregateString != "")
            {
                aggregate = bool.Parse(aggregateString);
            }


            // Start DB Connect and make a simple query to initialize it

            IO.Swagger.DatabaseInterface.DBObservation dbO = new IO.Swagger.DatabaseInterface.DBObservation();
            string error = "";

            dbO.ListObs(2, ref error);


            //Fetch all datastreams that we want to handle
            System.Console.WriteLine("Fetching:" + thingtype);
            string    JsonResult = "";
            WebClient wclient    = new WebClient();

            try
            {
                wclient.Encoding                 = System.Text.Encoding.UTF8;
                wclient.Headers["Accept"]        = "application/json";
                wclient.Headers["Content-Type"]  = "application/json";
                wclient.Headers["Authorization"] = copAuthToken;
                JsonResult = wclient.DownloadString(copApiBasePath + "thingsWithObservation?thingType=" + thingtype.Replace(" ", "%20"));
            }
            catch (WebException exception)
            {
                System.Console.WriteLine("Invokation error" + copApiBasePath + "thingsWithObservation " + exception.Message);
            }

            string InnerText = JsonResult;


            // Build x-ref of thingId, personId, ZoneId mapped to topic.
            InnerText = "{Kalle:" + InnerText + "}";
            XmlDocument xDoc = JsonConvert.DeserializeXmlNode(InnerText, "Root");
            XmlNodeList Obs  = xDoc.SelectNodes("//observations");
            int         i    = 0;

            foreach (XmlNode ob in Obs)
            {
                // If there are limits to the number of devices, be sure to keep inside them.
                if (i >= settings.deviceStartIndex && i < settings.deviceEndIndex)
                {
                    int     personId = -1;
                    int     zoneId   = -1;
                    XmlNode xThingId = ob.SelectSingleNode("./thingId");
                    if (xThingId != null)
                    {
                        int     thingId   = int.Parse(xThingId.InnerText);
                        XmlNode xPersonid = ob.SelectSingleNode("./personid");
                        if (xPersonid.InnerText != "" && xPersonid.InnerText != "null")
                        {
                            personId = int.Parse(xPersonid.InnerText);
                        }
                        XmlNode xZoneid = ob.SelectSingleNode("./zoneid");
                        if (xZoneid.InnerText != "")
                        {
                            zoneId = int.Parse(xZoneid.InnerText);
                        }
                        XmlNode xStreamIdPlusMore = ob.SelectSingleNode("./datastreamId");
                        string  streamId          = xStreamIdPlusMore.InnerText.Substring(0, xStreamIdPlusMore.InnerText.IndexOf(":"));
                        XmlNode xStreamType       = ob.SelectSingleNode("./type");
                        string  streamType        = xStreamType.InnerText;
                        if (!ThingsFromDataStreams.ContainsKey(streamId) && (streamType == "AGGREGATE" && aggregate))
                        {
                            ThingsFromDataStreams.Add(streamId, thingId);
                            datastreams.Add(streamId);
                        }
                        if (!ThingsFromDataStreams.ContainsKey(streamId) && (streamType != "AGGREGATE" && !aggregate))
                        {
                            ThingsFromDataStreams.Add(streamId, thingId);
                            datastreams.Add(streamId);
                        }
                        if (personId > 0)
                        {
                            if (!PeopleFromDataStreams.ContainsKey(streamId))
                            {
                                PeopleFromDataStreams.Add(streamId, personId);
                            }
                        }
                        if (zoneId > 0)
                        {
                            if (!ZoneFromDataStreams.ContainsKey(streamId))
                            {
                                ZoneFromDataStreams.Add(streamId, zoneId);
                            }
                        }
                    }
                }
                i++;
            }


            //ThingsFromDataStreams.Add("CrowdHeatmap", 650);
            //datastreams.Add("CrowdHeatmap");

            _logger.LogError("COPUpdater listening to " + datastreams.Count.ToString());
            //Setup SignalR
            connection = new HubConnectionBuilder()
                         .WithUrl(copApiBasePathHub + "signalR/COPupdate")
                         .Build();
            connection.StartAsync().Wait();
            connection.Closed += async(berr) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);

                await connection.StartAsync();
            };

            ml = (ManagedMqttClient) new MqttFactory().CreateManagedMqttClient();
            // Setup and start a managed MQTT client.
            var options = new ManagedMqttClientOptionsBuilder()
                          .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                          .WithClientOptions(new MqttClientOptionsBuilder()
                                             .WithClientId(System.Guid.NewGuid().ToString())
                                             .WithKeepAlivePeriod(TimeSpan.FromSeconds(120))
                                             .WithCommunicationTimeout(TimeSpan.FromSeconds(60))
                                             //.WithCredentials("mosquitto", "mosquitto")
                                             //.WithTcpServer("monappdwp5.monica-cloud.eu")
                                             .WithTcpServer("127.0.0.1")
                                             .Build())
                          .Build();

            ml = (ManagedMqttClient) new MqttFactory().CreateManagedMqttClient();

            if (mqttDebug)
            {
                MQTTnet.Diagnostics.MqttNetGlobalLogger.LogMessagePublished += (s, e) =>
                {
                    var trace = $">> [{e.TraceMessage.Timestamp:O}] [{e.TraceMessage.ThreadId}] [{e.TraceMessage.Source}] [{e.TraceMessage.Level}]: {e.TraceMessage.Message}";
                    if (e.TraceMessage.Exception != null)
                    {
                        trace += Environment.NewLine + e.TraceMessage.Exception.ToString();
                    }

                    CultureInfo ci = Thread.CurrentThread.CurrentCulture;
                    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("sv-SE");

                    string fileName = "MQTT" + DateTime.Now.ToShortDateString() + ".txt";

                    string logFolder = "." + Path.DirectorySeparatorChar;

                    FileStream   w  = File.Open(logFolder + fileName, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Write);
                    StreamWriter sw = new StreamWriter(w, System.Text.Encoding.Default);
                    sw.Write(trace + Environment.NewLine);
                    sw.Close();

                    Thread.CurrentThread.CurrentCulture = ci;
                };
            }
            foreach (string topic in datastreams)
            {
                ml.SubscribeAsync(new TopicFilterBuilder().WithTopic(topic).Build());
            }
            ml.ApplicationMessageReceivedHandler =
                new  MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                if (ThingsFromDataStreams.ContainsKey(e.ApplicationMessage.Topic))
                {
                    int thingid        = ThingsFromDataStreams[e.ApplicationMessage.Topic];
                    string observation = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);

                    int?zoneid = null;
                    if (ZoneFromDataStreams.ContainsKey(e.ApplicationMessage.Topic))
                    {
                        zoneid = ZoneFromDataStreams[e.ApplicationMessage.Topic];
                    }

                    int?personid = null;
                    if (PeopleFromDataStreams.ContainsKey(e.ApplicationMessage.Topic))
                    {
                        personid = PeopleFromDataStreams[e.ApplicationMessage.Topic];
                    }

                    string safeObs = JsonConvert.ToString(observation);


                    if (thingtype == "incidentreporter")
                    {
                        ManageIncidentReporter(observation);
                    }
                    else if (thingtype == "button_press")
                    {
                        ManageButtonPress(observation);
                    }
                    else
                    {
                        ProcessNewSensorData(e.ApplicationMessage.Topic, thingid, observation, zoneid, personid);
                    }
                }
            });

            ml.StartAsync(options).Wait();
        }
Пример #7
0
        /// <summary>
        /// Process new sensor data that arrives
        /// </summary>
        /// <param name="topic">The topic of the message</param>
        /// <param name="thingid">Set if a thing is connected to the datastream</param>
        /// <param name="observation">The actual meassage</param>
        /// <param name="zoneid">Set if a zone is connected to the datastream</param>
        /// <param name="personid">Set if a person is connected to the datastream</param>
        public void ProcessNewSensorData(string topic, int?thingid, string observation, int?zoneid, int?personid)
        {
            try
            {
                string message      = "";
                string action       = "";
                string dataStreamId = createDataStreamId(thingid.ToString(), ref observation, zoneid, personid, ref message, ref action, topic);

                string errorMessage = "Testar Loggning";
                long   newId        = 0;
                if (!useOnlySignalR) //true if the latest observation in the database should not be updated
                {
                    //Update the latest observation in the database.
                    if (thingtype == "PeopleHeatmap")
                    {
                        observation = "{\"phenomenonTime\":\"" + DateTime.Now.ToString("O") + "\", \"result\":" + observation + "}";
                    }
                    IO.Swagger.DatabaseInterface.DBObservation dbO = new IO.Swagger.DatabaseInterface.DBObservation();
                    if (!dbO.AddUpdateObservation(thingid, topic + dataStreamId, DateTime.Now, observation, ref errorMessage, ref newId))
                    {
                        _logger.LogError("COPUpdater update obs failed {errorMessage}", errorMessage);
                    }
                }

                if (action != "")   //Should we emit an update on signalR?
                {
                    if (usesignalR) //True when we use signal directly.
                    {
                        try
                        {
                            connection.InvokeAsync(action, message).Wait();
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError("signalR publish failed {ex.Message}", ex.Message);
                        }
                    }
                    else //Post the SignalR update using the COPs API
                    {
                        string payload = @"{
  ""action"": ""###action###"",
  ""message"": ###message###
}";
                        // System.Console.WriteLine("Action:" + action);
                        payload = payload.Replace("###action###", action);
                        payload = payload.Replace("###message###", JsonConvert.ToString(message));
                        HttpWebRequest client = (HttpWebRequest)WebRequest.Create(copApiBasePath + "HUBMessage");
                        try
                        {
                            client.Method = "POST";

                            client.ContentType = "application/json";
                            client.Accept      = "application/json";
                            client.Headers["Authorization"] = copAuthToken;
                            client.Timeout = 2000;
                            UTF8Encoding encoding = new UTF8Encoding();
                            byte[]       byte1    = encoding.GetBytes(payload);

                            // Set the content length of the string being posted.

                            client.ContentLength = byte1.GetLength(0);
                            Stream newStream = client.GetRequestStream();
                            newStream.Write(byte1, 0, byte1.Length);
                            newStream.Close();

                            HttpWebResponse response       = (HttpWebResponse)client.GetResponse();
                            Stream          responseStream = response.GetResponseStream();
                            StreamReader    reader         = new StreamReader(responseStream);
                            string          jsonString     = reader.ReadToEnd();
                            responseStream.Close();
                            response.Close();
                        }
                        catch (WebException exception)
                        {
                            string errorResponse = "";
                            //read the response.

                            if (exception.Response != null)
                            {
                                Stream errRes = exception.Response.GetResponseStream();
                                if (errRes != null)
                                {
                                    StreamReader sr = new StreamReader(errRes, true);

                                    errorResponse = sr.ReadToEnd();
                                    errRes.Close();
                                }
                            }
                            _logger.LogError("Invocation error {copApiBasePath} {exception.Message} {errorResponse}", copApiBasePath, exception.Message, errorResponse);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("general error when processing {ex.Message}", ex.Message);
            }
        }