public static Task SubscribeAsync( this ManagedMqttClient managedMqttClient, string topic, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce) { if (managedMqttClient == null) { throw new ArgumentNullException(nameof(managedMqttClient)); } if (topic == null) { throw new ArgumentNullException(nameof(topic)); } return(managedMqttClient.SubscribeAsync( new List <MqttTopicFilter> { new MqttTopicFilterBuilder().WithTopic(topic).WithQualityOfServiceLevel(qualityOfServiceLevel).Build() })); }
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(); }
/// <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(); }