示例#1
0
        /// <summary>
        /// Handle a HTTP request. Only GET requests are supported.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void HandleRequest(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                StringBuilder request = new StringBuilder();

                // Handle an incoming request
                // First read the request
                using (IInputStream input = args.Socket.InputStream)
                {
                    byte[]  data     = new byte[BufferSize];
                    IBuffer buffer   = data.AsBuffer();
                    uint    dataRead = BufferSize;
                    while (dataRead == BufferSize)
                    {
                        await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);

                        request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                        dataRead = buffer.Length;
                    }
                }

                var requestLines = request.ToString().Split('\r', '\n');
                if ((requestLines.Length > 0) && requestLines[0].ToUpper().StartsWith("GET "))
                {
                    var url = requestLines[0].Substring(4).Split(' ')[0];

                    if (!await SendFile(args.Socket.OutputStream, url))
                    {
                        // if no static file has been served, check for a REST call
                        var e = new RestCommandArgs(url);
                        RestCommand?.Invoke(this, e);
                        if (e.IsValid)
                        {
                            var htmlResponse = string.IsNullOrEmpty(e.HtmlResponse) ? $"<html><body>Ok. ({e.Command})</body></html>" : e.HtmlResponse;
                            SendHtmlResponse(args.Socket.OutputStream, 200, "OK", htmlResponse);
                        }
                        else
                        {
                            SendHtmlResponse(args.Socket.OutputStream, 400, "Bad Request", $"<html><body><h1>Bad Request</h1>Invalid command: {e.Command}<br/>{e.ErrorMessage}</body></html>");
                        }
                    }
                }
                else
                {
                    SendHtmlResponse(args.Socket.OutputStream, 400, "Bad Request", "<html><body>Bad Request</body></html>");
                }
            }
            catch (Exception ex)
            {
                SendHtmlResponse(args.Socket.OutputStream, 500, "Internal Server Error", $"<html><body>Internal Server Error{ex}</body></html>");
            }
        }
示例#2
0
        /// <summary>
        /// Handle a REST command.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Server_RestCommand(object sender, RestCommandArgs e)
        {
            try
            {
                var parts = e.Command.ToLower().Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                if ((parts.Length >= 4) && (parts[0] == "api"))
                {
                    switch (parts[1])
                    {
                    case "gpio":
                        // switch GPIO pins directly, example: /api/gpio/17/1
                        e.IsValid = gpio.SetGPIO(parts[2], parts[3]);
                        break;

                    case "shutter":
                        // control a shutter group
                        e.IsValid = ShutterControl(parts[2], parts[3]);
                        break;

                    default:
                        // return "bad request"
                        e.IsValid      = false;
                        e.ErrorMessage = $"\"{parts[1]}\" is an unknown api object. Valid objects are \"gpio\" or \"shutter\".";
                        break;
                    }
                }
                else
                {
                    // return "bad request"
                    e.IsValid = false;
                }
            }
            catch (Exception ex)
            {
                e.IsValid      = false;
                e.ErrorMessage = "Exception: " + ex.Message;
            }
        }