private void Cleanup(ref CoapEndpoint Client) { if (Client != null) { ulong[] Tokens = Client.GetActiveTokens(); ushort[] MessageIDs = Client.GetActiveMessageIDs(); Client.Dispose(); Client = null; Assert.AreEqual(0, Tokens.Length, "There are tokens that have not been unregistered properly."); Assert.AreEqual(0, MessageIDs.Length, "There are message IDs that have not been unregistered properly."); } }
private static void MonitorCoap () { CoapEndpoint Endpoint = new CoapEndpoint (); //Endpoint.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal)); CoapObserver LightObserver = new CoapObserver (Endpoint, true, "192.168.0.15", CoapEndpoint.DefaultCoapPort, "light/txt", string.Empty, 2 * 5); CoapObserver MotionObserver = new CoapObserver (Endpoint, true, "192.168.0.15", CoapEndpoint.DefaultCoapPort, "motion/txt", string.Empty, 10 * 5); bool HasLightValue = false; bool HasMotionValue = false; LightObserver.OnDataReceived += (o, e) => { string s = e.Response as string; double d; if (!string.IsNullOrEmpty (s) && s.EndsWith (" %") && XmlUtilities.TryParseDouble (s.Substring (0, s.Length - 2), out d)) { lightPercent = d; if (!HasLightValue) { HasLightValue = true; if (HasMotionValue) hasValues = true; } CheckControlRules (); } }; MotionObserver.OnDataReceived += (o, e) => { string s = e.Response as string; bool b; if (!string.IsNullOrEmpty (s) && XmlUtilities.TryParseBoolean (s, out b)) { motion = b; if (!HasMotionValue) { HasMotionValue = true; if (HasLightValue) hasValues = true; } CheckControlRules (); } }; try { WaitHandle[] Handles = new WaitHandle[]{ updateLeds, updateAlarm }; while (executing) { try { switch (WaitHandle.WaitAny (Handles, 1000)) { case 0: // Update LEDS int i; lock (synchObject) { i = lastLedMask; } Endpoint.StartPOST (true, "192.168.0.23", CoapEndpoint.DefaultCoapPort, "do/txt", string.Empty, i.ToString (), CoapBlockSize.BlockLimit_64Bytes, null, null); break; case 1: // Update Alarm bool b; lock (synchObject) { b = lastAlarm.Value; } Endpoint.StartPOST (true, "192.168.0.23", CoapEndpoint.DefaultCoapPort, "alarm/txt", string.Empty, b ? "1" : "0", CoapBlockSize.BlockLimit_64Bytes, null, null); if (b) { Thread T = new Thread (SendAlarmMail); T.Priority = ThreadPriority.BelowNormal; T.Name = "SendAlarmMail"; T.Start (); } break; default: // Timeout CheckSubscriptions (30); break; } } catch (ThreadAbortException) { // Don't log. Exception will be automatically re-raised. } catch (Exception ex) { Log.Exception (ex); } } } finally { LightObserver.Dispose (); MotionObserver.Dispose (); Endpoint.Dispose (); } }
private static void MonitorCoap() { CoapEndpoint Endpoint = new CoapEndpoint(); //Endpoint.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal)); CoapObserver LightObserver = new CoapObserver(Endpoint, true, "192.168.0.15", CoapEndpoint.DefaultCoapPort, "light/txt", string.Empty, 2 * 5); CoapObserver MotionObserver = new CoapObserver(Endpoint, true, "192.168.0.15", CoapEndpoint.DefaultCoapPort, "motion/txt", string.Empty, 10 * 5); bool HasLightValue = false; bool HasMotionValue = false; LightObserver.OnDataReceived += (o, e) => { string s = e.Response as string; double d; if (!string.IsNullOrEmpty(s) && s.EndsWith(" %") && XmlUtilities.TryParseDouble(s.Substring(0, s.Length - 2), out d)) { lightPercent = d; if (!HasLightValue) { HasLightValue = true; if (HasMotionValue) { hasValues = true; } } CheckControlRules(); } }; MotionObserver.OnDataReceived += (o, e) => { string s = e.Response as string; bool b; if (!string.IsNullOrEmpty(s) && XmlUtilities.TryParseBoolean(s, out b)) { motion = b; if (!HasMotionValue) { HasMotionValue = true; if (HasLightValue) { hasValues = true; } } CheckControlRules(); } }; try { WaitHandle[] Handles = new WaitHandle[] { updateLeds, updateAlarm }; while (executing) { try { switch (WaitHandle.WaitAny(Handles, 1000)) { case 0: // Update LEDS int i; lock (synchObject) { i = lastLedMask; } Endpoint.StartPOST(true, "192.168.0.23", CoapEndpoint.DefaultCoapPort, "do/txt", string.Empty, i.ToString(), CoapBlockSize.BlockLimit_64Bytes, null, null); break; case 1: // Update Alarm bool b; lock (synchObject) { b = lastAlarm.Value; } Endpoint.StartPOST(true, "192.168.0.23", CoapEndpoint.DefaultCoapPort, "alarm/txt", string.Empty, b ? "1" : "0", CoapBlockSize.BlockLimit_64Bytes, null, null); if (b) { Thread T = new Thread(SendAlarmMail); T.Priority = ThreadPriority.BelowNormal; T.Name = "SendAlarmMail"; T.Start(); } break; default: // Timeout CheckSubscriptions(30); break; } } catch (ThreadAbortException) { // Don't log. Exception will be automatically re-raised. } catch (Exception ex) { Log.Exception(ex); } } } finally { LightObserver.Dispose(); MotionObserver.Dispose(); Endpoint.Dispose(); } }
/// <summary> /// Stops the gateway. /// </summary> public static void Stop() { IDisposable Disposable; Log.Informational("Server shutting down."); /* * if (databaseProvider != null) * File.WriteAllText(appDataFolder + "Stop.xml", databaseProvider.ExportXml(true).Result); */ if (gatewayRunning != null) { gatewayRunning.Release(); gatewayRunning.Dispose(); gatewayRunning = null; } if (ibbClient != null) { ibbClient.Dispose(); ibbClient = null; } if (httpxServer != null) { httpxServer.Dispose(); httpxServer = null; } if (provisioningClient != null) { provisioningClient.Dispose(); provisioningClient = null; } if (thingRegistryClient != null) { thingRegistryClient.Dispose(); thingRegistryClient = null; } if (concentratorServer != null) { concentratorServer.Dispose(); concentratorServer = null; } if (xmppClient != null) { using (ManualResetEvent OfflineSent = new ManualResetEvent(false)) { xmppClient.SetPresence(Availability.Offline, string.Empty, (sender, e) => OfflineSent.Set()); OfflineSent.WaitOne(1000); } foreach (ISniffer Sniffer in xmppClient.Sniffers) { XmppClient.Remove(Sniffer); Disposable = Sniffer as IDisposable; if (Disposable != null) { Disposable.Dispose(); } } xmppClient.Dispose(); xmppClient = null; } if (connectionTimer != null) { connectionTimer.Dispose(); connectionTimer = null; } if (coapEndpoint != null) { coapEndpoint.Dispose(); coapEndpoint = null; } if (webServer != null) { foreach (ISniffer Sniffer in webServer.Sniffers) { webServer.Remove(Sniffer); Disposable = Sniffer as IDisposable; if (Disposable != null) { Disposable.Dispose(); } } webServer.Dispose(); webServer = null; } clientEvents = null; }
public static int Main (string[] args) { Log.Register (new ConsoleOutEventLog (80)); Log.Information ("Initializing application..."); HttpSocketClient.RegisterHttpProxyUse (false, false); // Don't look for proxies. DB.BackupConnectionString = "Data Source=sensor.db;Version=3;"; DB.BackupProviderName = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider"; db = DB.GetDatabaseProxy ("TheSensor"); Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; executionLed.Low (); }; // Initializing hardware and retrieving current sensor values try { tmp102.Configure (false, TexasInstrumentsTMP102.FaultQueue.ConsecutiveFaults_6, TexasInstrumentsTMP102.AlertPolarity.AlertActiveLow, TexasInstrumentsTMP102.ThermostatMode.ComparatorMode, false, TexasInstrumentsTMP102.ConversionRate.Hz_1, false); temp = (short)tmp102.ReadTemperatureRegister (); temperatureC = temp / 256.0; for (int i = 0; i < 10; i++) tempAvgWindow [i] = temp; sumTemp = temp * 10; } catch (Exception ex) { Log.Exception (ex); sumTemp = 0; temperatureC = 0; errorLed.High (); } try { adc.Configure (true, false, false, false, false, false); light = adc.ReadRegistersBinary () [0]; lightPercent = (100.0 * light) / 0x0fff; for (int i = 0; i < 10; i++) lightAvgWindow [i] = light; sumLight = light * 10; } catch (Exception ex) { Log.Exception (ex); sumLight = 0; lightPercent = 0; errorLed.High (); } // Loading historical Sensor Values Log.Information ("Loading Minute Values."); perMinute.AddRange (Record.LoadRecords (Rank.Minute)); Log.Information ("Loading Hour Values."); perHour.AddRange (Record.LoadRecords (Rank.Hour)); Log.Information ("Loading Day Values."); perDay.AddRange (Record.LoadRecords (Rank.Day)); Log.Information ("Loading Month Values."); perMonth.AddRange (Record.LoadRecords (Rank.Month)); // Resuming average calculations int Pos = perSecond.Count; DateTime CurrentTime = DateTime.Now; DateTime Timestamp; while (Pos-- > 0) { Record Rec = perSecond [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Minute == CurrentTime.Minute && Timestamp.Hour == CurrentTime.Hour && Timestamp.Date == CurrentTime.Date) { sumSeconds += Rec; nrSeconds++; } else break; } Pos = perMinute.Count; while (Pos-- > 0) { Record Rec = perMinute [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Hour == CurrentTime.Hour && Timestamp.Date == CurrentTime.Date) { sumMinutes += Rec; nrMinutes++; } else break; } Pos = perHour.Count; while (Pos-- > 0) { Record Rec = perHour [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Date == CurrentTime.Date) { sumHours += Rec; nrHours++; } else break; } Pos = perDay.Count; while (Pos-- > 0) { Record Rec = perDay [Pos]; Timestamp = Rec.Timestamp; if (Timestamp.Month == CurrentTime.Month && Timestamp.Year == CurrentTime.Year) { sumDays += Rec; nrDays++; } else break; } // Sampling of new Sensor Values Timer Timer = new Timer (SampleSensorValues, null, 1000 - DateTime.Now.Millisecond, 1000); // Every second. // HTTP Interface HttpServer HttpServer = new HttpServer (80, 10, true, true, 1); Log.Information ("HTTP Server receiving requests on port " + HttpServer.Port.ToString ()); HttpServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Sensor Realm", GetDigestUserPasswordHash)); HttpServer.RegisterAuthenticationMethod (new SessionAuthentication ()); credentials = LoginCredentials.LoadCredentials (); if (credentials == null) { credentials = new LoginCredentials (); credentials.UserName = "******"; credentials.PasswordHash = CalcHash ("Admin", "Password"); credentials.SaveNew (); } HttpServer.Register ("/", HttpGetRoot, HttpPostRoot, false); // Synchronous, no authentication HttpServer.Register ("/html", HttpGetHtml, false); // Synchronous, no authentication HttpServer.Register ("/historygraph", HttpGetHistoryGraph, false); // Synchronous, no authentication HttpServer.Register ("/credentials", HttpGetCredentials, HttpPostCredentials, false); // Synchronous, no authentication HttpServer.Register ("/xml", HttpGetXml, true); // Synchronous, http authentication HttpServer.Register ("/json", HttpGetJson, true); // Synchronous, http authentication HttpServer.Register ("/turtle", HttpGetTurtle, true); // Synchronous, http authentication HttpServer.Register ("/rdf", HttpGetRdf, true); // Synchronous, http authentication HttpServer.Register ("/event/xml", HttpGetEventXml, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/json", HttpGetEventJson, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/turtle", HttpGetEventTurtle, true, false); // Asynchronous, http authentication HttpServer.Register ("/event/rdf", HttpGetEventRdf, true, false); // Asynchronous, http authentication // HTTPS interface // Certificate must be a valid P12 (PFX) certificate file containing a private key. // X509Certificate2 Certificate = new X509Certificate2 ("Certificate.pfx", "PASSWORD"); // HttpServer HttpsServer = new HttpServer (443, 10, true, true, 1, true, false, Certificate); // // HttpsServer.RegisterAuthenticationMethod (new DigestAuthentication ("The Sensor Realm", GetDigestUserPasswordHash)); // HttpsServer.RegisterAuthenticationMethod (new SessionAuthentication ()); // // foreach (IHttpServerResource Resource in HttpServer.GetResources()) // HttpsServer.Register (Resource); // // Log.Information ("HTTPS Server receiving requests on port " + HttpsServer.Port.ToString ()); // CoAP Interface CoapEndpoint CoapEndpoint = new CoapEndpoint (); Log.Information ("CoAP endpoint receiving requests on port " + CoapEndpoint.Port.ToString ()); //CoapEndpoint.RegisterLineListener (new ConsoleOutLineListenerSink (BinaryFormat.Hexadecimal, true)); CoapEndpoint.RegisterResource ("temp/txt", "Current Temperature, as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, true, (Request, Payload) => { return FieldNumeric.Format (temperatureC, "C", 1); }); motionTxt = CoapEndpoint.RegisterResource ("motion/txt", "Motion detection, as text.", CoapBlockSize.BlockLimit_64Bytes, false, 10, true, (Request, Payload) => { return motionDetected ? "1" : "0"; }); CoapEndpoint.RegisterResource ("light/txt", "Current Light Density, as text.", CoapBlockSize.BlockLimit_64Bytes, false, 2, true, (Request, Payload) => { return FieldNumeric.Format (lightPercent, "%", 1); }); foreach (CoapBlockSize BlockSize in Enum.GetValues(typeof(CoapBlockSize))) { if (BlockSize == CoapBlockSize.BlockLimit_Datagram) continue; string Bytes = (1 << (4 + (int)BlockSize)).ToString (); CoapEndpoint.RegisterResource ("xml/" + Bytes, "Complete sensor readout, in XML. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetXml); CoapEndpoint.RegisterResource ("json/" + Bytes, "Complete sensor readout, in JSON. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetJson); CoapEndpoint.RegisterResource ("turtle/" + Bytes, "Complete sensor readout, in TURTLE. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetTurtle); CoapEndpoint.RegisterResource ("rdf/" + Bytes, "Complete sensor readout, in RDF. Control content using query parmeters. Block size=" + Bytes + " bytes.", BlockSize, false, 30, false, CoapGetRdf); } // MQTT mqttThread = new Thread (MqttThread); mqttThread.Name = "MQTT"; mqttThread.Priority = ThreadPriority.BelowNormal; mqttThread.Start (); // Main loop Log.Information ("Initialization complete. Application started..."); try { while (executionLed.Value) { System.Threading.Thread.Sleep (1000); } } catch (Exception ex) { Log.Exception (ex); executionLed.Low (); } finally { Log.Information ("Terminating application."); Log.Flush (); Log.Terminate (); Timer.Dispose (); HttpServer.Dispose (); //HttpsServer.Dispose (); CoapEndpoint.Dispose (); if (mqttThread != null) { mqttThread.Abort (); mqttThread = null; } executionLed.Dispose (); measurementLed.Dispose (); errorLed.Dispose (); networkLed.Dispose (); motion.Dispose (); i2cBus.Dispose (); } return 0; }