private static void HttpGetRoot(HttpServerResponse resp, HttpServerRequest req)
        {
            networkLed.High();
            try
            {
                string SessionId = req.Header.GetCookie("SessionId");

                resp.ContentType = "text/html";
                resp.Encoding    = System.Text.Encoding.UTF8;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                if (CheckSession(SessionId))
                {
                    resp.Write("<html><head><title>Sensor</title></head><body><h1>Welcome to Sensor</h1><p>Below, choose what you want to do.</p><ul>");
                    resp.Write("<li><a href='/credentials'>Update login credentials.</a></li>");
                    resp.Write("<li>View Data</li><ul>");
                    resp.Write("<li><a href='/xml?Momentary=1'>View data as XML using REST</a></li>");
                    resp.Write("<li><a href='/json?Momentary=1'>View data as JSON using REST</a></li>");
                    resp.Write("<li><a href='/turtle?Momentary=1'>View data as TURTLE using REST</a></li>");
                    resp.Write("<li><a href='/rdf?Momentary=1'>View data as RDF using REST</a></li>");
                    resp.Write("<li><a href='/html'>Data in a HTML page with graphs</a></li></ul>");
                    resp.Write("</body></html>");
                }
                else
                {
                    OutputLoginForm(resp, string.Empty);
                }
            } finally
            {
                networkLed.Low();
            }
        }
Example #2
0
        private static void HttpGetRoot(HttpServerResponse resp, HttpServerRequest req)
        {
            networkLed.High();
            try
            {
                resp.ContentType = "text/html";
                resp.Encoding    = System.Text.Encoding.UTF8;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                resp.Write("<html><head><title>Sensor</title></head><body><h1>Welcome to Sensor</h1><p>Below, choose what you want to do.</p><ul>");
                resp.Write("<li>View Data</li><ul>");
                resp.Write("<li><a href='/xml?Momentary=1'>View data as XML using REST</a></li>");
                resp.Write("<li><a href='/json?Momentary=1'>View data as JSON using REST</a></li>");
                resp.Write("<li><a href='/turtle?Momentary=1'>View data as TURTLE using REST</a></li>");
                resp.Write("<li><a href='/rdf?Momentary=1'>View data as RDF using REST</a></li>");
                resp.Write("<li><a href='/html'>Data in a HTML page with graphs</a></li></ul>");
                resp.Write("</body></html>");
            } finally
            {
                networkLed.Low();
            }
        }
Example #3
0
        //SCHEDULER

        public static void Main()
        {
            Server srv    = new Server(SetHigh, SetLow, SetRefilled, SetNewWaterFreq, 8080);
            Thread thread = new Thread(new ThreadStart(srv.listen));

            thread.Start();
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
            {
                e.Cancel = true;
                executionLed.Low();
            };
            ///  SCHEDULER  ///
            while (executionLed.Value)
            {
                getState();

                if (waterState == WaterState.ok &&
                    waterLevelMax != 0 &&
                    DateTime.Now.Day == waterTime.Day && DateTime.Now.Minute > waterTime.Minute &&
                    DateTime.Now.Hour == waterTime.Hour &&
                    waterHistory[DateTime.Now.Hour * 60 + DateTime.Now.Minute] < waterLevelMax - acceptableMarginOfError)
                {
                    waterState = WaterState.busy;
                    new Thread(() => water(waterLevelMax)).Start();
                    waterTime = waterTime.AddDays(waterFreq);
                }

                else if (waterState == WaterState.ok && averageMoist() < waterLevelMin - acceptableMarginOfError && waterLevelMax != 0)
                {
                    waterState = WaterState.busy;
                    new Thread(() => water(waterLevelMin)).Start();
                }
                // Sleep one hour
                System.Threading.Thread.Sleep(1000);
            }
            executionLed.Dispose();
            waterPump.Low();
        }
        private static void HttpGetRoot(HttpServerResponse resp, HttpServerRequest req, bool Protected)
        {
            networkLed.High();
            try
            {
                string SessionId = req.Header.GetCookie("SessionId");
                string Host;

                resp.ContentType = "text/html";
                resp.Encoding    = System.Text.Encoding.UTF8;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                if ((!Protected) || CheckSession(SessionId))
                {
                    resp.Write("<html><head><title>Camera</title></head><body><h1>Welcome to Camera</h1><p>Below, choose what you want to do.</p><ul>");
                    resp.Write("<li><a href='/html'>View camera.</a></li>");

                    if (Protected)
                    {
                        resp.Write("<li><a href='/credentials'>Update login credentials.</a></li>");
                    }
                    else
                    {
                        int i;

                        Host = req.Header.Host;
                        if ((i = Host.IndexOf(':')) > 0)
                        {
                            Host = Host.Substring(0, i);
                        }

                        resp.Write("<li><a href='http://");
                        resp.Write(Host);
                        resp.Write(':');
                        resp.Write(upnpServer.Port.ToString());
                        resp.Write("/StillImage'>Still Image Web service.</a></li>");
                    }

                    resp.Write("</body></html>");
                }
                else
                {
                    OutputLoginForm(resp, string.Empty);
                }
            } finally
            {
                networkLed.Low();
            }
        }
Example #5
0
        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.Register("/", HttpGetRoot, false);                                               // Synchronous, no authentication
            HttpServer.Register("/html", HttpGetHtml, false);                                           // Synchronous, no authentication
            HttpServer.Register("/historygraph", HttpGetHistoryGraph, false);                           // Synchronous, no authentication
            HttpServer.Register("/xml", HttpGetXml, false);                                             // Synchronous, no authentication
            HttpServer.Register("/json", HttpGetJson, false);                                           // Synchronous, no authentication
            HttpServer.Register("/turtle", HttpGetTurtle, false);                                       // Synchronous, no authentication
            HttpServer.Register("/rdf", HttpGetRdf, false);                                             // Synchronous, no 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);
            //
            // foreach (IHttpServerResource Resource in HttpServer.GetResources())
            //    HttpsServer.Register (Resource);
            //
            // Log.Information ("HTTPS Server receiving requests on port " + HttpsServer.Port.ToString ());

            // 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 ();
                executionLed.Dispose();
                measurementLed.Dispose();
                errorLed.Dispose();
                networkLed.Dispose();
                motion.Dispose();
                i2cBus.Dispose();
            }

            return(0);
        }
Example #6
0
        private static void SampleSensorValues(object State)
        {
            measurementLed.High();
            try
            {
                lock (synchObject)
                {
                    DateTime Now = DateTime.Now;
                    Record   Rec, Rec2;

                    // Read sensors

                    temp  = (short)tmp102.ReadTemperatureRegister();
                    light = adc.ReadRegistersBinary() [0];

                    // Calculate average of last 10 measurements, to get smoother momentary values

                    sumTemp  -= tempAvgWindow [avgPos];
                    sumLight -= lightAvgWindow [avgPos];

                    tempAvgWindow [avgPos]  = temp;
                    lightAvgWindow [avgPos] = light;

                    sumTemp       += temp;
                    sumLight      += light;
                    motionDetected = motion.Value;

                    temperatureC = (sumTemp * 0.1 / 256.0);
                    lightPercent = (100.0 * 0.1 * sumLight) / 0x0fff;
                    avgPos       = (avgPos + 1) % 10;

                    // Update history

                    Rec = new Record(Now, temperatureC, lightPercent, motionDetected);                                  // Rank 0

                    perSecond.Add(Rec);
                    if (perSecond.Count > 1000)
                    {
                        perSecond.RemoveAt(0);
                    }

                    sumSeconds += Rec;
                    nrSeconds++;

                    if (Now.Second == 0)
                    {
                        Rec = sumSeconds / nrSeconds;                                   // Rank 1
                        perMinute.Add(Rec);
                        Rec.SaveNew();

                        if (perMinute.Count > 1000)
                        {
                            Rec2 = perMinute [0];
                            perMinute.RemoveAt(0);
                            Rec2.Delete();
                        }

                        sumMinutes += Rec;
                        nrMinutes++;

                        sumSeconds = null;
                        nrSeconds  = 0;

                        if (Now.Minute == 0)
                        {
                            Rec = sumMinutes / nrMinutes;
                            perHour.Add(Rec);
                            Rec.SaveNew();

                            if (perHour.Count > 1000)
                            {
                                Rec2 = perHour [0];
                                perHour.RemoveAt(0);
                                Rec2.Delete();
                            }

                            sumHours += Rec;
                            nrHours++;

                            sumMinutes = null;
                            nrMinutes  = 0;

                            if (Now.Hour == 0)
                            {
                                Rec = sumHours / nrHours;
                                perDay.Add(Rec);
                                Rec.SaveNew();

                                if (perDay.Count > 1000)
                                {
                                    Rec2 = perDay [0];
                                    perDay.RemoveAt(0);
                                    Rec2.Delete();
                                }

                                sumDays += Rec;
                                nrDays++;

                                sumHours = null;
                                nrHours  = 0;

                                if (Now.Day == 1)
                                {
                                    Rec = sumDays / nrDays;
                                    perMonth.Add(Rec);
                                    Rec.SaveNew();

                                    sumDays = null;
                                    nrDays  = 0;
                                }
                            }
                        }
                    }
                }

                errorLed.Low();
            } catch (Exception)
            {
                errorLed.High();
            } finally
            {
                measurementLed.Low();
            }
        }
        public static int Main(string[] args)
        {
            Log.Register(new ConsoleOutEventLog(80));
            Log.Information("Initializing application...");

            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();
            }

            // Sampling of new Sensor Values

            Timer Timer = new Timer(SampleSensorValues, null, 1000 - DateTime.Now.Millisecond, 1000);                   // Every second.

            // 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();
                executionLed.Dispose();
                measurementLed.Dispose();
                errorLed.Dispose();
                networkLed.Dispose();
                motion.Dispose();
                i2cBus.Dispose();
            }

            return(0);
        }
        private static void HttpGetRoot(HttpServerResponse resp, HttpServerRequest req)
        {
            networkLed.High();
            try
            {
                string SessionId = req.Header.GetCookie("SessionId");

                resp.ContentType = "text/html";
                resp.Encoding    = System.Text.Encoding.UTF8;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                if (CheckSession(SessionId))
                {
                    StringBuilder sb = new StringBuilder();
                    string        EventParameters;

                    lock (synchObject)
                    {
                        sb.Append("?Temperature=");
                        sb.Append(XmlUtilities.DoubleToString(temperatureC, 1));
                        sb.Append("&amp;TemperatureDiff=1&amp;Light=");
                        sb.Append(XmlUtilities.DoubleToString(lightPercent, 1));
                        sb.Append("&amp;LightDiff=10&amp;Motion=");
                        sb.Append(motionDetected ? "1" : "0");
                        sb.Append("&amp;Timeout=25");
                    }

                    EventParameters = sb.ToString();

                    resp.Write("<html><head><title>Sensor</title></head><body><h1>Welcome to Sensor</h1><p>Below, choose what you want to do.</p><ul>");
                    resp.Write("<li><a href='/credentials'>Update login credentials.</a></li>");
                    resp.Write("<li>View Data</li><ul>");
                    resp.Write("<li><a href='/xml?Momentary=1'>View data as XML using REST</a></li>");
                    resp.Write("<li><a href='/json?Momentary=1'>View data as JSON using REST</a></li>");
                    resp.Write("<li><a href='/turtle?Momentary=1'>View data as TURTLE using REST</a></li>");
                    resp.Write("<li><a href='/rdf?Momentary=1'>View data as RDF using REST</a></li>");
                    resp.Write("<li><a href='/html'>Data in a HTML page with graphs</a></li></ul>");
                    resp.Write("<li>Wait for an Event</li><ul>");
                    resp.Write("<li><a href='/event/xml");
                    resp.Write(EventParameters);
                    resp.Write("'>Return XML data when event occurs.</a></li>");
                    resp.Write("<li><a href='/event/json");
                    resp.Write(EventParameters);
                    resp.Write("'>Return JSON data when event occurs.</a></li>");
                    resp.Write("<li><a href='/event/turtle");
                    resp.Write(EventParameters);
                    resp.Write("'>Return TURTLE data when event occurs.</a></li>");
                    resp.Write("<li><a href='/event/rdf");
                    resp.Write(EventParameters);
                    resp.Write("'>Return RDF data when event occurs.</a></li>");
                    resp.Write("</ul></body></html>");
                }
                else
                {
                    OutputLoginForm(resp, string.Empty);
                }
            } finally
            {
                networkLed.Low();
            }
        }
        private static void SampleSensorValues(object State)
        {
            measurementLed.High();
            try
            {
                lock (synchObject)
                {
                    DateTime Now = DateTime.Now;
                    Record   Rec, Rec2;

                    // Read sensors

                    temp  = (short)tmp102.ReadTemperatureRegister();
                    light = adc.ReadRegistersBinary() [0];

                    // Calculate average of last 10 measurements, to get smoother momentary values

                    sumTemp  -= tempAvgWindow [avgPos];
                    sumLight -= lightAvgWindow [avgPos];

                    tempAvgWindow [avgPos]  = temp;
                    lightAvgWindow [avgPos] = light;

                    sumTemp       += temp;
                    sumLight      += light;
                    motionDetected = motion.Value;

                    temperatureC = (sumTemp * 0.1 / 256.0);
                    lightPercent = (100.0 * 0.1 * sumLight) / 0x0fff;
                    avgPos       = (avgPos + 1) % 10;

                    // Update history

                    Rec = new Record(Now, temperatureC, lightPercent, motionDetected);                                  // Rank 0

                    perSecond.Add(Rec);
                    if (perSecond.Count > 1000)
                    {
                        perSecond.RemoveAt(0);
                    }

                    sumSeconds += Rec;
                    nrSeconds++;

                    if (Now.Second == 0)
                    {
                        Rec = sumSeconds / nrSeconds;                                   // Rank 1
                        perMinute.Add(Rec);
                        Rec.SaveNew();

                        if (perMinute.Count > 1000)
                        {
                            Rec2 = perMinute [0];
                            perMinute.RemoveAt(0);
                            Rec2.Delete();
                        }

                        sumMinutes += Rec;
                        nrMinutes++;

                        sumSeconds = null;
                        nrSeconds  = 0;

                        if (Now.Minute == 0)
                        {
                            Rec = sumMinutes / nrMinutes;
                            perHour.Add(Rec);
                            Rec.SaveNew();

                            if (perHour.Count > 1000)
                            {
                                Rec2 = perHour [0];
                                perHour.RemoveAt(0);
                                Rec2.Delete();
                            }

                            sumHours += Rec;
                            nrHours++;

                            sumMinutes = null;
                            nrMinutes  = 0;

                            if (Now.Hour == 0)
                            {
                                Rec = sumHours / nrHours;
                                perDay.Add(Rec);
                                Rec.SaveNew();

                                if (perDay.Count > 1000)
                                {
                                    Rec2 = perDay [0];
                                    perDay.RemoveAt(0);
                                    Rec2.Delete();
                                }

                                sumDays += Rec;
                                nrDays++;

                                sumHours = null;
                                nrHours  = 0;

                                if (Now.Day == 1)
                                {
                                    Rec = sumDays / nrDays;
                                    perMonth.Add(Rec);
                                    Rec.SaveNew();

                                    sumDays = null;
                                    nrDays  = 0;
                                }
                            }
                        }
                    }

                    // Check pending events

                    PendingEvent Event;
                    int          i = 0;
                    int          c = pendingEvents.Count;

                    while (i < c)
                    {
                        Event = pendingEvents [i];

                        if (Event.Trigger(temperatureC, lightPercent, motionDetected))
                        {
                            pendingEvents.RemoveAt(i);
                            c--;

                            HttpGetSensorData(Event.Response, Event.ContentType, Event.ExportModule, new ReadoutRequest(ReadoutType.MomentaryValues));
                            Event.Response.SendResponse();                              // Flags the end of the response, and transmission of all to the recipient.
                        }
                        else
                        {
                            i++;
                        }
                    }
                }

                errorLed.Low();
            } catch (Exception)
            {
                errorLed.High();
            } finally
            {
                measurementLed.Low();
                RemoveOldSessions();
            }
        }
        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=actuator.db;Version=3;";
            DB.BackupProviderName     = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider";
            db = DB.GetDatabaseProxy("TheActuator");

            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
            {
                e.Cancel = true;
                executionLed.Low();
            };

            // HTTP Interface

            HttpServer HttpServer = new HttpServer(80, 10, true, true, 1);
            int        i;

            Log.Information("HTTP Server receiving requests on port " + HttpServer.Port.ToString());

            HttpServer.RegisterAuthenticationMethod(new DigestAuthentication("The Actuator Realm", GetDigestUserPasswordHash));
            HttpServer.RegisterAuthenticationMethod(new SessionAuthentication());

            credentials = LoginCredentials.LoadCredentials();
            if (credentials == null)
            {
                credentials              = new LoginCredentials();
                credentials.UserName     = "******";
                credentials.PasswordHash = CalcHash("Admin", "Password");
                credentials.SaveNew();
            }

            state = State.LoadState();
            if (state == null)
            {
                state = new State();
                state.SaveNew();
            }
            else
            {
                for (i = 0; i < 8; i++)
                {
                    digitalOutputs [i].Value = state.GetDO(i + 1);
                }

                if (state.Alarm)
                {
                    AlarmOn();
                }
                else
                {
                    AlarmOff();
                }
            }

            HttpServer.Register("/", HttpGetRoot, HttpPostRoot, false);                                         // Synchronous, no authentication
            HttpServer.Register("/credentials", HttpGetCredentials, HttpPostCredentials, false);                // Synchronous, no authentication
            HttpServer.Register("/set", HttpGetSet, HttpPostSet, true);                                         // Synchronous, http 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(new WebServiceAPI(), true);

            // 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 Actuator Realm", GetDigestUserPasswordHash));
            //
            // 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));

            for (i = 1; i <= 8; i++)
            {
                CoapEndpoint.RegisterResource("do" + i.ToString() + "/txt", "Digital Output " + i.ToString() + ", as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false,
                                              CoapGetDigitalOutputTxt, CoapSetDigitalOutputTxt);
            }

            CoapEndpoint.RegisterResource("do/txt", "Digital Outputs, as a number 0-255 as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false,
                                          CoapGetDigitalOutputsTxt, CoapSetDigitalOutputsTxt);

            CoapEndpoint.RegisterResource("alarm/txt", "Alarm Output " + i.ToString() + ", as text.", CoapBlockSize.BlockLimit_64Bytes, false, 30, false,
                                          CoapGetAlarmOutputTxt, CoapSetAlarmOutputTxt);

            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);
            }

            // Main loop

            Log.Information("Initialization complete. Application started...");

            try
            {
                while (executionLed.Value)
                {
                    System.Threading.Thread.Sleep(1000);
                    RemoveOldSessions();
                }
            } catch (Exception ex)
            {
                Log.Exception(ex);
                executionLed.Low();
            } finally
            {
                Log.Information("Terminating application.");
                Log.Flush();
                Log.Terminate();

                HttpServer.Dispose();
                //HttpsServer.Dispose ();

                executionLed.Dispose();

                foreach (DigitalOutput Output in digitalOutputs)
                {
                    Output.Dispose();
                }

                if (alarmThread != null)
                {
                    alarmThread.Abort();
                    alarmThread = null;
                }
            }

            return(0);
        }
        private static void HttpGetImg(HttpServerResponse resp, HttpServerRequest req, bool Protected)
        {
            networkLed.High();
            try
            {
                if (Protected)
                {
                    string SessionId = req.Header.GetCookie("SessionId");
                    if (!CheckSession(SessionId))
                    {
                        throw new HttpException(HttpStatusCode.ClientError_Forbidden);
                    }
                }

                LinkSpriteJpegColorCamera.ImageSize Resolution;
                string Encoding;
                byte   Compression;
                ushort Size;
                byte[] Data;

                GetImageProperties(req, out Encoding, out Compression, out Resolution);

                lock (cameraLed)
                {
                    try
                    {
                        cameraLed.High();

                        if (Resolution != currentResolution)
                        {
                            try
                            {
                                camera.SetImageSize(Resolution);
                                currentResolution = Resolution;
                                camera.Reset();
                            } catch (Exception)
                            {
                                camera.Dispose();
                                camera = new LinkSpriteJpegColorCamera(LinkSpriteJpegColorCamera.BaudRate.Baud__38400);
                                camera.SetBaudRate(LinkSpriteJpegColorCamera.BaudRate.Baud_115200);
                                camera.Dispose();
                                camera = new LinkSpriteJpegColorCamera(LinkSpriteJpegColorCamera.BaudRate.Baud_115200);
                            }
                        }

                        if (Compression != currentCompressionRatio)
                        {
                            camera.SetCompressionRatio(Compression);
                            currentCompressionRatio = Compression;
                        }

                        camera.TakePicture();
                        Size = camera.GetJpegFileSize();
                        Data = camera.ReadJpegData(Size);

                        errorLed.Low();
                    } catch (Exception ex)
                    {
                        errorLed.High();
                        Log.Exception(ex);
                        throw new HttpException(HttpStatusCode.ServerError_ServiceUnavailable);
                    } finally
                    {
                        cameraLed.Low();
                        camera.StopTakingPictures();
                    }
                }

                resp.ContentType = Encoding;
                resp.Expires     = DateTime.Now;
                resp.ReturnCode  = HttpStatusCode.Successful_OK;

                if (Encoding != "imgage/jpeg")
                {
                    MemoryStream ms  = new MemoryStream(Data);
                    Bitmap       Bmp = new Bitmap(ms);
                    Data = MimeUtilities.EncodeSpecificType(Bmp, Encoding);
                }

                resp.WriteBinary(Data);
            } finally
            {
                networkLed.Low();
            }
        }
        public static void 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=camera.db;Version=3;";
            DB.BackupProviderName     = "Clayster.Library.Data.Providers.SQLiteServer.SQLiteServerProvider";
            db = DB.GetDatabaseProxy("TheCamera");

            defaultSettings = DefaultSettings.LoadSettings();
            if (defaultSettings == null)
            {
                defaultSettings = new DefaultSettings();
                defaultSettings.SaveNew();
            }

            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) =>
            {
                e.Cancel = true;
                executionLed.Low();
            };

            try
            {
                // HTTP Interface

                httpServer = new HttpServer(80, 10, true, true, 1);
                Log.Information("HTTP Server receiving requests on port " + httpServer.Port.ToString());

                httpServer.RegisterAuthenticationMethod(new DigestAuthentication("The Camera 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("/", HttpGetRootProtected, HttpPostRoot, false);                                    // Synchronous, no authentication
                httpServer.Register("/html", HttpGetHtmlProtected, false);                                              // Synchronous, no authentication
                httpServer.Register("/camera", HttpGetImgProtected, true);                                              // Synchronous, www-authentication
                httpServer.Register("/credentials", HttpGetCredentials, HttpPostCredentials, false);                    // Synchronous, no authentication

                // UPnP Interface

                upnpServer = new HttpServer(8080, 10, true, true, 1);
                Log.Information("UPnP Server receiving requests on port " + upnpServer.Port.ToString());

                upnpServer.Register("/", HttpGetRootUnprotected, HttpPostRoot, false);                                                  // Synchronous, no authentication
                upnpServer.Register("/html", HttpGetHtmlUnprotected, false);                                                            // Synchronous, no authentication
                upnpServer.Register("/camera", HttpGetImgUnprotected, false);                                                           // Synchronous, no authentication
                upnpServer.Register("/CameraDevice.xml", HttpGetCameraDevice, false);
                upnpServer.Register(new HttpServerEmbeddedResource("/StillImageService.xml", "Camera.UPnP.StillImageService.xml"));
                upnpServer.Register(stillImageWS = new DigitalSecurityCameraStillImage());

                // Icons taken from: http://www.iconarchive.com/show/the-bourne-ultimatum-icons-by-leoyue/Camera-icon.html
                upnpServer.Register(new HttpServerEmbeddedResource("/Icon/16x16.png", "Camera.UPnP.16x16.png"));
                upnpServer.Register(new HttpServerEmbeddedResource("/Icon/24x24.png", "Camera.UPnP.24x24.png"));
                upnpServer.Register(new HttpServerEmbeddedResource("/Icon/32x32.png", "Camera.UPnP.32x32.png"));
                upnpServer.Register(new HttpServerEmbeddedResource("/Icon/48x48.png", "Camera.UPnP.48x48.png"));
                upnpServer.Register(new HttpServerEmbeddedResource("/Icon/64x64.png", "Camera.UPnP.64x64.png"));
                upnpServer.Register(new HttpServerEmbeddedResource("/Icon/128x128.png", "Camera.UPnP.128x128.png"));
                upnpServer.Register(new HttpServerEmbeddedResource("/Icon/256x256.png", "Camera.UPnP.256x256.png"));

                ssdpClient              = new SsdpClient(upnpServer, 10, true, true, false, false, false, 30);
                ssdpClient.OnNotify    += OnSsdpNotify;
                ssdpClient.OnDiscovery += OnSsdpDiscovery;

                // Initializing camera

                Log.Information("Initializing camera.");
                try
                {
                    currentResolution       = defaultSettings.Resolution;
                    currentCompressionRatio = defaultSettings.CompressionLevel;

                    try
                    {
                        camera.Reset();                                 // First try @ 38400 baud
                        camera.SetImageSize(currentResolution);
                        camera.Reset();

                        camera.SetBaudRate(LinkSpriteJpegColorCamera.BaudRate.Baud_115200);
                        camera.Dispose();
                        camera = new LinkSpriteJpegColorCamera(LinkSpriteJpegColorCamera.BaudRate.Baud_115200);
                    } catch (Exception)                         // If already at 115200 baud.
                    {
                        camera.Dispose();
                        camera = new LinkSpriteJpegColorCamera(LinkSpriteJpegColorCamera.BaudRate.Baud_115200);
                    } finally
                    {
                        camera.SetCompressionRatio(currentCompressionRatio);
                    }
                } catch (Exception ex)
                {
                    Log.Exception(ex);
                    errorLed.High();
                    camera = null;
                }

                // Main loop

                Log.Information("Initialization complete. Application started.");

                while (executionLed.Value)
                {
                    Thread.Sleep(1000);
                    RemoveOldSessions();
                }
            } catch (Exception ex)
            {
                Log.Exception(ex);
                executionLed.Low();
            } finally
            {
                Log.Information("Terminating application.");
                Log.Flush();
                Log.Terminate();

                ssdpClient.Dispose();

                if (upnpServer != null)
                {
                    upnpServer.Dispose();
                }

                if (httpServer != null)
                {
                    httpServer.Dispose();
                }

                executionLed.Dispose();
                cameraLed.Dispose();
                networkLed.Dispose();
                errorLed.Dispose();
                camera.Dispose();
            }
        }
        public static int Main(string[] args)
        {
            Log.Register(new ConsoleOutEventLog(80));
            Log.Information("Initializing application...");

            HttpSocketClient.RegisterHttpProxyUse(false, false);                // Don't look for proxies.

            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();
            }

            // 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.Register("/", HttpGetRoot, false);                                               // Synchronous, no authentication
            HttpServer.Register("/html", HttpGetHtml, false);                                           // Synchronous, no authentication
            HttpServer.Register("/historygraph", HttpGetHistoryGraph, false);                           // Synchronous, no authentication
            HttpServer.Register("/xml", HttpGetXml, false);                                             // Synchronous, no authentication
            HttpServer.Register("/json", HttpGetJson, false);                                           // Synchronous, no authentication
            HttpServer.Register("/turtle", HttpGetTurtle, false);                                       // Synchronous, no authentication
            HttpServer.Register("/rdf", HttpGetRdf, false);                                             // Synchronous, no 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);
            //
            // foreach (IHttpServerResource Resource in HttpServer.GetResources())
            //    HttpsServer.Register (Resource);
            //
            // Log.Information ("HTTPS Server receiving requests on port " + HttpsServer.Port.ToString ());

            // 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 ();
                executionLed.Dispose();
                measurementLed.Dispose();
                errorLed.Dispose();
                networkLed.Dispose();
                motion.Dispose();
                i2cBus.Dispose();
            }

            return(0);
        }