public async Task Invoke(HttpContext context, IEnumerable <IHttpServerEventCallback> callbacks)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (callbacks == null)
            {
                throw new ArgumentNullException(nameof(callbacks));
            }

            var stopwatch = Stopwatch.StartNew();

            callbacks.Invoke(() => HttpServerRequest.Create(context));

            try
            {
                await _next(context);
            }
            catch (HttpException e)
            {
                await WriteResponse(context, e.StatusCode, e.Message);
            }
            catch (Exception e)
            {
                await WriteResponse(context, HttpStatusCode.InternalServerError, "FAIL!");

                callbacks.Invoke(() => HttpServerException.Create(context, stopwatch.ElapsedMilliseconds, e));
            }

            callbacks.Invoke(() => HttpServerResponse.Create(context, stopwatch.ElapsedMilliseconds));
        }
示例#2
0
 private static void AddHeaderIfNotNull(IHttpHeader contentEncodingHeader, HttpServerResponse newResponse)
 {
     if (contentEncodingHeader != null)
     {
         newResponse.AddHeader(contentEncodingHeader);
     }
 }
示例#3
0
        private static HttpServerResponse GetUnauthorizedResponse(string realm)
        {
            var response = HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.Unauthorized);

            response.AddHeader("WWW-Authenticate", $"Basic realm=\"{realm}\"");
            return(response);
        }
示例#4
0
        private void OnHttpServerRequest(HttpServerRequest httpRequest, HttpServerResponse httpResponse)
        {
            UrlData     urlData = Url.Parse(httpRequest.Url, /* parseQueryString */ true);
            ServerRoute route   = _router.Match(urlData.PathName);

            Action <Exception> errorHandler = delegate(Exception e) {
                httpResponse.WriteHead(HttpStatusCode.InternalServerError, e.Message);
                httpResponse.End();

                Runtime.TraceInfo("500 : %s %s", httpRequest.Method, httpRequest.Url);
                return;
            };

            ServerRequest         request      = new ServerRequest(httpRequest, urlData, route);
            Task <ServerResponse> responseTask = null;

            try {
                responseTask = _modules[0].ProcessRequest(request);
            }
            catch (Exception e) {
                errorHandler(e);
                return;
            }

            responseTask.Done(delegate(ServerResponse response) {
                response.Write(httpResponse);

                Runtime.TraceInfo("%d : %s %s", response.StatusCode, httpRequest.Method, httpRequest.Url);
            })
            .Fail(errorHandler);
        }
        private static void HttpGetRoot(HttpServerResponse resp, HttpServerRequest req)
        {
            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>Actuator</title></head><body><h1>Welcome to Actuator</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><a href='/set'>Control Outputs</a></li>");
                resp.Write("<li>View Output States</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></ul>");
                resp.Write("</ul></body></html>");
            }
            else
            {
                OutputLoginForm(resp, string.Empty);
            }
        }
示例#6
0
        public string ParseToString(HttpServerResponse response)
        {
            if (response.Content == null)
                return string.Empty;

            return DEFAULT_CONTENT_ENCODING.GetString(response.Content);
        }
示例#7
0
        public StaticFileRouteHandlerFluentTests GetRequestReceived(string uri, HttpMethod method = HttpMethod.GET)
        {
            var request = Utils.CreateHttpRequest(uri: new Uri(uri, UriKind.Relative), method: method);

            response = routeHandler.HandleRequest(request).Result;

            return(this);
        }
示例#8
0
        public static HttpServerResponse CreateOkHttpServerResponse(byte[] content = null)
        {
            var response = HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.OK);

            response.Content = content;

            return(response);
        }
示例#9
0
        public string ParseToString(HttpServerResponse response)
        {
            var version    = GetHttpVersion(response.HttpVersion);
            var status     = (int)response.ResponseStatus;
            var statusText = HttpCodesTranslator.Default.GetHttpStatusCodeText(status);

            return($"{version} {status} {statusText}\r\n");
        }
示例#10
0
        public string ParseToString(HttpServerResponse response)
        {
            var version = GetHttpVersion(response.HttpVersion);
            var status = (int)response.ResponseStatus;
            var statusText = HttpCodesTranslator.Default.GetHttpStatusCodeText(status);

            return $"{version} {status} {statusText}\r\n";
        }
 private static void OutputLoginForm(HttpServerResponse resp, string Message)
 {
     resp.Write("<html><head><title>Actuator</title></head><body><form method='POST' action='/' target='_self' autocomplete='true'>");
     resp.Write(Message);
     resp.Write("<h1>Login</h1><p><label for='UserName'>User Name:</label><br/><input type='text' name='UserName'/></p>");
     resp.Write("<p><label for='Password'>Password:</label><br/><input type='password' name='Password'/></p>");
     resp.Write("<p><input type='submit' value='Login'/></p></form></body></html>");
 }
示例#12
0
        public void Create_EmptyResponse_HttpFirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
        private static void HttpGetSensorData(HttpServerResponse resp, string ContentType, ISensorDataExport Output, ReadoutRequest Request)
        {
            resp.ContentType = ContentType;
            resp.Encoding    = System.Text.Encoding.UTF8;
            resp.Expires     = DateTime.Now;
            resp.ReturnCode  = HttpStatusCode.Successful_OK;

            ExportSensorData(Output, Request);
        }
        private static HttpServerResponse GetDefaultResponse(IRestResponse response)
        {
            var serverResponse = HttpServerResponse.Create(response.StatusCode);

            serverResponse.Date = DateTime.Now;
            serverResponse.IsConnectionClosed = true;

            return(serverResponse);
        }
示例#15
0
        public string ParseToString(HttpServerResponse response)
        {
            if (response.Content == null)
            {
                return(string.Empty);
            }

            return(DEFAULT_CONTENT_ENCODING.GetString(response.Content));
        }
示例#16
0
        private static async Task WriteResponseAsync(HttpServerResponse response, StreamSocket socket)
        {
            using (var output = socket.OutputStream)
            {
                await output.WriteAsync(response.ToBytes().AsBuffer());

                await output.FlushAsync();
            }
        }
示例#17
0
        public override async Task <ShowcaseFormValidateResponse> Parse(HttpServerResponse response)
        {
            bool isFinalStep = response.Status == HttpStatusCode.OK;
            var  result      = await base.Parse(response);

            result.IsFinalStep = isFinalStep;
            result.Success     = true;         // since we cannot handle HTTP 400 status here

            return(result);
        }
        public void serialise_server_response()
        {
            var httpServerResponse = HttpServerResponse.Create(_httpContext, 1358);

            httpServerResponse.Timestamp = new DateTimeOffset(2016, 11, 18, 19, 52, 6, TimeSpan.Zero).AddTicks(4425454);

            _testSubject.Invoke(httpServerResponse);

            _logger.Logs[0].ShouldBe("{\"eventType\":\"HttpServerResponse\",\"timestamp\":\"2016-11-18T19:52:06.4425454+00:00\",\"uri\":\"/ping?v=1\",\"method\":\"GET\",\"statusCode\":23,\"durationMs\":1358}");
        }
        public byte[] ConvertToBytes(HttpServerResponse response)
        {
            var responseBytes = new List<byte>();
            foreach (var pipelinePart in _pipeline)
            {
                responseBytes.AddRange(pipelinePart.ParseToBytes(response));
            }

            return responseBytes.ToArray();
        }
        private static HttpServerResponse GetFileNotFoundResponse(string localPath)
        {
            var notFoundResponse = HttpServerResponse.Create(new Version(1, 1), HttpResponseStatus.NotFound);

            notFoundResponse.Content        = Encoding.UTF8.GetBytes($"File at {localPath} not found.");
            notFoundResponse.ContentType    = "text/plain";
            notFoundResponse.ContentCharset = "utf-8";

            return(notFoundResponse);
        }
        public string ConvertToString(HttpServerResponse response)
        {
            var responseBuilder = new StringBuilder();
            foreach (var pipelinePart in _pipeline)
            {
                responseBuilder.Append(pipelinePart.ParseToString(response));
            }

            return responseBuilder.ToString();
        }
示例#22
0
        public string ConvertToString(HttpServerResponse response)
        {
            var responseBuilder = new StringBuilder();

            foreach (var pipelinePart in _pipeline)
            {
                responseBuilder.Append(pipelinePart.ParseToString(response));
            }

            return(responseBuilder.ToString());
        }
示例#23
0
        public void Create_HttpVersion2_HttpFirstLineOnly()
        {
            var response = HttpServerResponse.Create(new Version(2, 0), HttpResponseStatus.OK);

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            string expectedValue = "HTTP/2.0 200 OK\r\n\r\n";

            AssertResponse(expectedValue, responseMessage, responseBytes);
        }
示例#24
0
        internal void Write(HttpServerResponse httpResponse)
        {
            httpResponse.WriteHead(_statusCode, _headers);

            if (_content != null)
            {
                httpResponse.Write(_content, Encoding.UTF8);
            }

            httpResponse.End();
        }
 private static void OutputCredentialsForm(HttpServerResponse resp, string Message)
 {
     resp.Write("<html><head><title>Sensor</title></head><body><form method='POST' action='/credentials' target='_self' autocomplete='true'>");
     resp.Write(Message);
     resp.Write("<h1>Update Login Credentials</h1><p><label for='UserName'>User Name:</label><br/><input type='text' name='UserName'/></p>");
     resp.Write("<p><label for='Password'>Password:</label><br/><input type='password' name='Password'/></p>");
     resp.Write("<p><label for='NewUserName'>New User Name:</label><br/><input type='text' name='NewUserName'/></p>");
     resp.Write("<p><label for='NewPassword1'>New Password:</label><br/><input type='password' name='NewPassword1'/></p>");
     resp.Write("<p><label for='NewPassword2'>New Password again:</label><br/><input type='password' name='NewPassword2'/></p>");
     resp.Write("<p><input type='submit' value='Update'/></p></form></body></html>");
 }
示例#26
0
        public byte[] ConvertToBytes(HttpServerResponse response)
        {
            var responseBytes = new List <byte>();

            foreach (var pipelinePart in _pipeline)
            {
                responseBytes.AddRange(pipelinePart.ParseToBytes(response));
            }

            return(responseBytes.ToArray());
        }
示例#27
0
        public void Create_SetAndRemoveContentType_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.ContentType = "application/json";
            response.ContentType = null;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
示例#28
0
        public void Create_SetAndUnsetConnectionClosed_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.IsConnectionClosed = true;
            response.IsConnectionClosed = false;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
示例#29
0
        public void Create_AddAndRemoveCustomHeader_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.AddHeader("my-own-header", "23");
            response.RemoveHeader("my-own-header");

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
        private static void HttpGetEvent(HttpServerResponse resp, HttpServerRequest req, string ContentType, ISensorDataExport ExportModule)
        {
            networkLed.High();
            try
            {
                double?Temperature = null;
                double?TemperatureDiff = null;
                double?Light = null;
                double?LightDiff = null;
                bool?  Motion = null;
                double d, d2;
                string s;
                bool   b;
                int    Timeout;

                if (!req.Query.TryGetValue("Timeout", out s) || !int.TryParse(s, out Timeout) || Timeout <= 0)
                {
                    throw new HttpException(HttpStatusCode.ClientError_BadRequest);
                }

                if (req.Query.TryGetValue("Temperature", out s) && XmlUtilities.TryParseDouble(s, out d) &&
                    req.Query.TryGetValue("TemperatureDiff", out s) && XmlUtilities.TryParseDouble(s, out d2) && d2 > 0)
                {
                    Temperature     = d;
                    TemperatureDiff = d2;
                }

                if (req.Query.TryGetValue("Light", out s) && XmlUtilities.TryParseDouble(s, out d) &&
                    req.Query.TryGetValue("LightDiff", out s) && XmlUtilities.TryParseDouble(s, out d2) && d2 > 0)
                {
                    Light     = d;
                    LightDiff = d2;
                }

                if (req.Query.TryGetValue("Motion", out s) && XmlUtilities.TryParseBoolean(s, out b))
                {
                    Motion = b;
                }

                if (!(Temperature.HasValue || Light.HasValue || Motion.HasValue))
                {
                    throw new HttpException(HttpStatusCode.ClientError_BadRequest);
                }

                lock (synchObject)
                {
                    pendingEvents.Add(new PendingEvent(Temperature, TemperatureDiff, Light, LightDiff, Motion, Timeout, resp, ContentType, ExportModule));
                }
            } finally
            {
                networkLed.Low();
            }
        }
示例#31
0
        public void Create_SetAndRemoveDate_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.Date = DateTime.Parse("Tue, 15 Nov 1994 08:12:31");
            response.Date = null;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
示例#32
0
        public void Create_SetAndremoveLocationRedirect_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.Location = new Uri("/api/1", UriKind.Relative);
            response.Location = null;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
示例#33
0
        public void Create_SetAndRemoveContent_FirstLineOnly()
        {
            var response = HttpServerResponse.Create(HttpResponseStatus.OK);

            response.Content = Encoding.UTF8.GetBytes("data");
            response.Content = null;

            var responseMessage = response.ToString();
            var responseBytes   = response.ToBytes();

            AssertDefaultFirstLineOnly(responseMessage, responseBytes);
        }
示例#34
0
        public string ParseToString(HttpServerResponse response)
        {
            var headersTextBuilder = new StringBuilder();
            foreach (var header in response.Headers)
            {
                headersTextBuilder.Append($"{header.Name}: {header.Value}\r\n");
            }

            headersTextBuilder.Append("\r\n");

            return headersTextBuilder.ToString();
        }
示例#35
0
 private HttpServerResponse ApplyMessageInspectorsAfterHandleRequest(IHttpServerRequest request,
                                                                     HttpServerResponse httpResponse)
 {
     foreach (var httpMessageInspector in _messageInspectors)
     {
         var result = httpMessageInspector.AfterHandleRequest(request, httpResponse);
         if (result != null)
         {
             httpResponse = result.Response;
         }
     }
     return(httpResponse);
 }
示例#36
0
		public PendingEvent (double? Temp, double? TempDiff, double? Light, double? LightDiff, bool? Motion, int Timeout, 
			HttpServerResponse Response, string ContentType, ISensorDataExport ExportModule)
		{
			this.temp = Temp;
			this.tempDiff = TempDiff;

			this.light = Light;
			this.lightDiff = LightDiff;

			this.motion = Motion;

			this.timeout = DateTime.Now.AddSeconds (Timeout);
			this.response = Response;
			this.contentType = ContentType;
			this.exportModule = ExportModule;
		}
示例#37
0
		private static void HttpGetImgUnprotected (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetImg (resp, req, false);
		}
示例#38
0
		private static void HttpGetSensorData (HttpServerResponse resp, HttpServerRequest req, string ContentType, ISensorDataExport ExportModule)
		{
			ReadoutRequest Request = new ReadoutRequest (req);
			HttpGetSensorData (resp, ContentType, ExportModule, Request);
		}
示例#39
0
		private static void HttpGetSensorData (HttpServerResponse resp, string ContentType, ISensorDataExport Output, ReadoutRequest Request)
		{
			resp.ContentType = ContentType;
			resp.Encoding = System.Text.Encoding.UTF8;
			resp.Expires = DateTime.Now;
			resp.ReturnCode = HttpStatusCode.Successful_OK;

			ExportSensorData (Output, Request);
		}
示例#40
0
		private static void HttpGetTurtle (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetSensorData (resp, req, "text/turtle", new SensorDataTurtleExport (resp.TextWriter, req));
		}
示例#41
0
		private static void HttpGetRdf (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetSensorData (resp, req, "application/rdf+xml", new SensorDataRdfExport (resp.TextWriter, req));
		}
示例#42
0
		private static void HttpGetHistoryGraph (HttpServerResponse resp, HttpServerRequest req)
		{
			networkLed.High ();
			try
			{
				string SessionId = req.Header.GetCookie ("SessionId");
				if (!CheckSession (SessionId))
					throw new HttpException (HttpStatusCode.ClientError_Forbidden);

				string ValueAxis;
				string ParameterName;
				string s;
				int Width, Height;

				if (!req.Query.TryGetValue ("w", out s) || !int.TryParse (s, out Width) || Width <= 0 || Width > 2048)
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				if (!req.Query.TryGetValue ("h", out s) || !int.TryParse (s, out Height) || Height <= 0 || Height > 2048)
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				if (!req.Query.TryGetValue ("p", out s))
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				switch (s)
				{
					case "temp":
						ParameterName = "TemperatureC";
						ValueAxis = "Temperature (C)";
						break;

					case "light":
						ParameterName = "LightPercent";
						ValueAxis = "Light (%)";
						break;

					case "motion":
						ParameterName = "Motion";
						ValueAxis = "Motion";
						break;

					default:
						throw new HttpException (HttpStatusCode.ClientError_BadRequest);
				}

				if (!req.Query.TryGetValue ("base", out s))
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				Variables v = new Variables ();
				DateTime Now = DateTime.Now;

				lock (synchObject)
				{
					switch (s)
					{
						case "sec":
							v ["Records"] = perSecond.ToArray ();
							resp.Expires = Now;
							break;

						case "min":
							v ["Records"] = perMinute.ToArray ();
							resp.Expires = new DateTime (Now.Year, Now.Month, Now.Day, Now.Hour, Now.Minute, 0).AddMinutes (1);
							break;

						case "h":
							v ["Records"] = perHour.ToArray ();
							resp.Expires = new DateTime (Now.Year, Now.Month, Now.Day, Now.Hour, 0, 0).AddHours (1);
							break;

						case "day":
							v ["Records"] = perDay.ToArray ();
							resp.Expires = new DateTime (Now.Year, Now.Month, Now.Day, 0, 0, 0).AddDays (1);
							break;

						case "month":
							v ["Records"] = perMonth.ToArray ();
							resp.Expires = new DateTime (Now.Year, Now.Month, 1, 0, 0, 0).AddMonths (1);
							break;

						default:
							throw new HttpException (HttpStatusCode.ClientError_BadRequest);
					}
				}
				Graph Result;

				if (ParameterName == "Motion")
					Result = Expression.ParseCached ("scatter2d(Records.Timestamp,if (Values:=Records.Motion) then 1 else 0,5,if Values then 'Red' else 'Blue','','Motion')").Evaluate (v) as Graph;
				else
					Result = Expression.ParseCached ("line2d(Records.Timestamp,Records." + ParameterName + ",'','" + ValueAxis + "')").Evaluate (v)as Graph;

				Image Img = Result.GetImage (Width, Height);
				byte[] Data = MimeUtilities.Encode (Img, out s);

				resp.ContentType = s;
				resp.ReturnCode = HttpStatusCode.Successful_OK;

				resp.WriteBinary (Data);

			} finally
			{
				networkLed.Low ();
			}
		}
示例#43
0
		private static void HttpGetJson (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetSensorData (resp, req, "application/json", new SensorDataJsonExport (resp.TextWriter));
		}
示例#44
0
		private static void HttpGetHtml (HttpServerResponse resp, HttpServerRequest req)
		{
			networkLed.High ();
			try
			{
				string SessionId = req.Header.GetCookie ("SessionId");
				if (!CheckSession (SessionId))
					throw new HttpTemporaryRedirectException ("/");

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

				resp.Write ("<html><head><meta http-equiv='refresh' content='60'/><title>Sensor Readout</title></head><body><h1>Readout, ");
				resp.Write (DateTime.Now.ToString ());
				resp.Write ("</h1><table><tr><td>Temperature:</td><td style='width:20px'/><td>");

				lock (synchObject)
				{
					resp.Write (HtmlUtilities.Escape (temperatureC.ToString ("F1")));
					resp.Write (" C</td></tr><tr><td>Light:</td><td/><td>");
					resp.Write (HtmlUtilities.Escape (lightPercent.ToString ("F1")));
					resp.Write (" %</td></tr><tr><td>Motion:</td><td/><td>");
					resp.Write (motionDetected.ToString ());
					resp.Write ("</td></tr></table>");

					if (perSecond.Count > 1)
					{
						resp.Write ("<h2>Second Precision</h2><table><tr><td><img src='historygraph?p=temp&base=sec&w=350&h=250' width='480' height='320'/></td>");
						resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=sec&w=350&h=250' width='480' height='320'/></td>");
						resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=sec&w=350&h=250' width='480' height='320'/></td></tr></table>");

						if (perMinute.Count > 1)
						{
							resp.Write ("<h2>Minute Precision</h2><table><tr><td><img src='historygraph?p=temp&base=min&w=350&h=250' width='480' height='320'/></td>");
							resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=min&w=350&h=250' width='480' height='320'/></td>");
							resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=min&w=350&h=250' width='480' height='320'/></td></tr></table>");

							if (perHour.Count > 1)
							{
								resp.Write ("<h2>Hour Precision</h2><table><tr><td><img src='historygraph?p=temp&base=h&w=350&h=250' width='480' height='320'/></td>");
								resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=h&w=350&h=250' width='480' height='320'/></td>");
								resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=h&w=350&h=250' width='480' height='320'/></td></tr></table>");

								if (perDay.Count > 1)
								{
									resp.Write ("<h2>Day Precision</h2><table><tr><td><img src='historygraph?p=temp&base=day&w=350&h=250' width='480' height='320'/></td>");
									resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=day&w=350&h=250' width='480' height='320'/></td>");
									resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=day&w=350&h=250' width='480' height='320'/></td></tr></table>");

									if (perMonth.Count > 1)
									{
										resp.Write ("<h2>Month Precision</h2><table><tr><td><img src='historygraph?p=temp&base=month&w=350&h=250' width='480' height='320'/></td>");
										resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=light&base=month&w=350&h=250' width='480' height='320'/></td>");
										resp.Write ("<td style='width:20px'/><td><img src='historygraph?p=motion&base=month&w=350&h=250' width='480' height='320'/></td></tr></table>");
									}
								}
							}
						}
					}
				}

				resp.Write ("</body><html>");

			} finally
			{
				networkLed.Low ();
			}
		}
示例#45
0
 public byte[] ParseToBytes(HttpServerResponse response)
 {
     return response.Content ?? new byte[0];
 }
示例#46
0
		private static void OutputCredentialsForm (HttpServerResponse resp, string Message)
		{
			resp.Write ("<html><head><title>Actuator</title></head><body><form method='POST' action='/credentials' target='_self' autocomplete='true'>");
			resp.Write (Message);
			resp.Write ("<h1>Update Login Credentials</h1><p><label for='UserName'>User Name:</label><br/><input type='text' name='UserName'/></p>");
			resp.Write ("<p><label for='Password'>Password:</label><br/><input type='password' name='Password'/></p>");
			resp.Write ("<p><label for='NewUserName'>New User Name:</label><br/><input type='text' name='NewUserName'/></p>");
			resp.Write ("<p><label for='NewPassword1'>New Password:</label><br/><input type='password' name='NewPassword1'/></p>");
			resp.Write ("<p><label for='NewPassword2'>New Password again:</label><br/><input type='password' name='NewPassword2'/></p>");
			resp.Write ("<p><input type='submit' value='Update'/></p></form></body></html>");
		}
示例#47
0
		private static void HttpPostCredentials (HttpServerResponse resp, HttpServerRequest req)
		{
			string SessionId = req.Header.GetCookie ("SessionId");
			if (!CheckSession (SessionId))
				throw new HttpTemporaryRedirectException ("/");

			FormParameters Parameters = req.Data as FormParameters;
			if (Parameters == null)
				throw new HttpException (HttpStatusCode.ClientError_BadRequest);

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

			string UserName = Parameters ["UserName"];
			string Password = Parameters ["Password"];
			string NewUserName = Parameters ["NewUserName"];
			string NewPassword1 = Parameters ["NewPassword1"];
			string NewPassword2 = Parameters ["NewPassword2"];

			string Hash;
			object AuthorizationObject;

			GetDigestUserPasswordHash (UserName, out Hash, out  AuthorizationObject);

			if (AuthorizationObject == null || Hash != CalcHash (UserName, Password))
			{
				Log.Warning ("Invalid attempt to change login credentials.", EventLevel.Minor, UserName, req.ClientAddress);
				OutputCredentialsForm (resp, "<p>Login credentials provided were not correct. Please try again.</p>");
			} else if (NewPassword1 != NewPassword2)
			{
				OutputCredentialsForm (resp, "<p>The new password was not entered correctly. Please provide the same new password twice.</p>");
			} else if (string.IsNullOrEmpty (UserName) || string.IsNullOrEmpty (NewPassword1))
			{
				OutputCredentialsForm (resp, "<p>Please provide a non-empty user name and password.</p>");
			} else if (UserName.Length > DB.ShortStringClipLength)
			{
				OutputCredentialsForm (resp, "<p>The new user name was too long.</p>");
			} else
			{
				Log.Information ("Login credentials changed.", EventLevel.Minor, UserName, req.ClientAddress);

				credentials.UserName = NewUserName;
				credentials.PasswordHash = CalcHash (NewUserName, NewPassword1);
				credentials.UpdateIfModified ();

				resp.ReturnCode = HttpStatusCode.Redirection_SeeOther;
				resp.AddHeader ("Location", "/");
				resp.SendResponse ();
				// PRG pattern, to avoid problems with post back warnings in the browser: http://en.wikipedia.org/wiki/Post/Redirect/Get
			}
		}
示例#48
0
		private static void HttpGetCredentials (HttpServerResponse resp, HttpServerRequest req)
		{
			string SessionId = req.Header.GetCookie ("SessionId");
			if (!CheckSession (SessionId))
				throw new HttpTemporaryRedirectException ("/");

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

			OutputCredentialsForm (resp, string.Empty);
		}
示例#49
0
		private static void HttpPostRoot (HttpServerResponse resp, HttpServerRequest req)
		{
			FormParameters Parameters = req.Data as FormParameters;
			if (Parameters == null)
				throw new HttpException (HttpStatusCode.ClientError_BadRequest);

			string UserName = Parameters ["UserName"];
			string Password = Parameters ["Password"];
			string Hash;
			object AuthorizationObject;

			GetDigestUserPasswordHash (UserName, out Hash, out  AuthorizationObject);

			if (AuthorizationObject == null || Hash != CalcHash (UserName, Password))
			{
				resp.ContentType = "text/html";
				resp.Encoding = System.Text.Encoding.UTF8;
				resp.ReturnCode = HttpStatusCode.Successful_OK;

				Log.Warning ("Invalid login attempt.", EventLevel.Minor, UserName, req.ClientAddress);
				OutputLoginForm (resp, "<p>The login was incorrect. Either the user name or the password was incorrect. Please try again.</p>");
			} else
			{
				Log.Information ("User logged in.", EventLevel.Minor, UserName, req.ClientAddress);

				string SessionId = CreateSessionId (UserName);
				resp.SetCookie ("SessionId", SessionId, "/");
				resp.ReturnCode = HttpStatusCode.Redirection_SeeOther;
				resp.AddHeader ("Location", "/");
				resp.SendResponse ();
				// PRG pattern, to avoid problems with post back warnings in the browser: http://en.wikipedia.org/wiki/Post/Redirect/Get
			}
		}
示例#50
0
		private static void HttpGetRoot (HttpServerResponse resp, HttpServerRequest req)
		{
			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>Actuator</title></head><body><h1>Welcome to Actuator</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><a href='/set'>Control Outputs</a></li>");
				resp.Write ("<li>View Output States</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></ul>");
				resp.Write ("</ul></body></html>");

			} else
				OutputLoginForm (resp, string.Empty);
		}
示例#51
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 ();
			}
		}
示例#52
0
		private static void OutputLoginForm (HttpServerResponse resp, string Message)
		{
			resp.Write ("<html><head><title>Sensor</title></head><body><form method='POST' action='/' target='_self' autocomplete='true'>");
			resp.Write (Message);
			resp.Write ("<h1>Login</h1><p><label for='UserName'>User Name:</label><br/><input type='text' name='UserName'/></p>");
			resp.Write ("<p><label for='Password'>Password:</label><br/><input type='password' name='Password'/></p>");
			resp.Write ("<p><input type='submit' value='Login'/></p></form></body></html>");
		}
示例#53
0
		private static void HttpGetSet (HttpServerResponse resp, HttpServerRequest req)
		{
			string s;
			int i;
			bool b;

			foreach (KeyValuePair<string,string> Query in req.Query)
			{
				if (!XmlUtilities.TryParseBoolean (Query.Value, out b))
					continue;

				s = Query.Key.ToLower ();
				if (s == "alarm")
				{
					if (b)
					{
						AlarmOn ();
						state.Alarm = true;
					} else
					{
						AlarmOff ();
						state.Alarm = false;
					}
				} else if (s.StartsWith ("do") && int.TryParse (s.Substring (2), out i) && i >= 1 && i <= 8)
				{
					digitalOutputs [i - 1].Value = b;
					state.SetDO (i, b);
				}
			}

			state.UpdateIfModified ();

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

			resp.Write ("<html><head><title>Actuator</title></head><body><h1>Control Actuator Outputs</h1>");
			resp.Write ("<form method='POST' action='/set' target='_self'><p>");

			for (i = 0; i < 8; i++)
			{
				resp.Write ("<input type='checkbox' name='do");
				resp.Write ((i + 1).ToString ());
				resp.Write ("'");
				if (digitalOutputs [i].Value)
					resp.Write (" checked='checked'");
				resp.Write ("/> Digital Output ");
				resp.Write ((i + 1).ToString ());
				resp.Write ("<br/>");
			}

			resp.Write ("<input type='checkbox' name='alarm'");
			if (alarmThread != null)
				resp.Write (" checked='checked'");
			resp.Write ("/> Alarm</p>");
			resp.Write ("<p><input type='submit' value='Set'/></p></form></body></html>");
		}
示例#54
0
		private static void HttpGetEvent (HttpServerResponse resp, HttpServerRequest req, string ContentType, ISensorDataExport ExportModule)
		{
			networkLed.High ();
			try
			{
				double? Temperature = null;
				double? TemperatureDiff = null;
				double? Light = null;
				double? LightDiff = null;
				bool? Motion = null;
				double d, d2;
				string s;
				bool b;
				int Timeout;

				if (!req.Query.TryGetValue ("Timeout", out s) || !int.TryParse (s, out Timeout) || Timeout <= 0)
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				if (req.Query.TryGetValue ("Temperature", out s) && XmlUtilities.TryParseDouble (s, out d) &&
				    req.Query.TryGetValue ("TemperatureDiff", out s) && XmlUtilities.TryParseDouble (s, out d2) && d2 > 0)
				{
					Temperature = d;
					TemperatureDiff = d2;
				}

				if (req.Query.TryGetValue ("Light", out s) && XmlUtilities.TryParseDouble (s, out d) &&
				    req.Query.TryGetValue ("LightDiff", out s) && XmlUtilities.TryParseDouble (s, out d2) && d2 > 0)
				{
					Light = d;
					LightDiff = d2;
				}

				if (req.Query.TryGetValue ("Motion", out s) && XmlUtilities.TryParseBoolean (s, out b))
					Motion = b;

				if (!(Temperature.HasValue || Light.HasValue || Motion.HasValue))
					throw new HttpException (HttpStatusCode.ClientError_BadRequest);

				lock (synchObject)
				{
					pendingEvents.Add (new PendingEvent (Temperature, TemperatureDiff, Light, LightDiff, Motion, Timeout, resp, ContentType, ExportModule));
				}

			} finally
			{
				networkLed.Low ();
			}
		}
示例#55
0
		private static void HttpPostSet (HttpServerResponse resp, HttpServerRequest req)
		{
			FormParameters Parameters = req.Data as FormParameters;
			if (Parameters == null)
				throw new HttpException (HttpStatusCode.ClientError_BadRequest);

			int i;
			bool b;

			for (i = 0; i < 8; i++)
			{
				if (XmlUtilities.TryParseBoolean (Parameters ["do" + (i + 1).ToString ()], out b) && b)
				{
					digitalOutputs [i].High ();
					state.SetDO (i + 1, true);
				} else
				{
					digitalOutputs [i].Low ();	// Unchecked checkboxes are not reported back to the server.
					state.SetDO (i + 1, false);
				}
			}

			if (XmlUtilities.TryParseBoolean (Parameters ["alarm"], out b) && b)
			{
				AlarmOn ();
				state.Alarm = true;
			} else
			{
				AlarmOff ();
				state.Alarm = false;
			}

			state.UpdateIfModified ();

			resp.ReturnCode = HttpStatusCode.Redirection_SeeOther;
			resp.AddHeader ("Location", "/set");
			resp.SendResponse ();
			// PRG pattern, to avoid problems with post back warnings in the browser: http://en.wikipedia.org/wiki/Post/Redirect/Get
		}
示例#56
0
		private static void HttpGetXml (HttpServerResponse resp, HttpServerRequest req)
		{
			HttpGetSensorData (resp, req, "text/xml", new SensorDataXmlExport (resp.TextWriter));
		}
示例#57
0
		private static void HttpGetSensorData (HttpServerResponse resp, string ContentType, ISensorDataExport ExportModule, ReadoutRequest Request)
		{
			networkLed.High ();
			try
			{
				resp.ContentType = ContentType;
				resp.Encoding = System.Text.Encoding.UTF8;
				resp.Expires = DateTime.Now;
				resp.ReturnCode = HttpStatusCode.Successful_OK;

				ExportSensorData (ExportModule, Request);

			} finally
			{
				networkLed.Low ();
			}
		}
示例#58
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 ();
			}
		}
示例#59
0
        private void OnHttpServerRequest(HttpServerRequest httpRequest, HttpServerResponse httpResponse)
        {
            UrlData urlData = Url.Parse(httpRequest.Url, /* parseQueryString */ true);
            ServerRoute route = _router.Match(urlData.PathName);

            Action<Exception> errorHandler = delegate(Exception e) {
                httpResponse.WriteHead(HttpStatusCode.InternalServerError, e.Message);
                httpResponse.End();

                Runtime.TraceInfo("500 : %s %s", httpRequest.Method, httpRequest.Url);
                return;
            };

            ServerRequest request = new ServerRequest(httpRequest, urlData, route);
            Task<ServerResponse> responseTask = null;

            try {
                responseTask = _modules[0].ProcessRequest(request);
            }
            catch (Exception e) {
                errorHandler(e);
                return;
            }

            responseTask.Done(delegate(ServerResponse response) {
                response.Write(httpResponse);

                Runtime.TraceInfo("%d : %s %s", response.StatusCode, httpRequest.Method, httpRequest.Url);
            })
            .Fail(errorHandler);
        }
示例#60
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 ();
			}
		}