示例#1
0
文件: Tools.cs 项目: uxav/lib2
 /// <summary>
 ///  Save a stream as a file
 /// </summary>
 /// <param name="input">The stream to save</param>
 /// <param name="filePath">The full file path where it will be saved to</param>
 public static void CreateFileFromResourceStream(Crestron.SimplSharp.CrestronIO.Stream input, string filePath)
 {
     using (Crestron.SimplSharp.CrestronIO.Stream output = Crestron.SimplSharp.CrestronIO.File.Create(filePath))
     {
         CopyStream(input, output);
     }
 }
示例#2
0
文件: Tools.cs 项目: uxav/lib2
        /// <summary>
        /// Copy a stream byte for byte
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        public static void CopyStream(Crestron.SimplSharp.CrestronIO.Stream input, Crestron.SimplSharp.CrestronIO.Stream output)
        {
            // Insert null checking here for production
            var buffer = new byte[8192];

            int bytesRead;

            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }
示例#3
0
        /// <summary>
        /// The received request handler for the CWS server
        /// </summary>
        /// <param name="sender">optional sender object</param>
        /// <param name="args">The HttpCwsRequestEventArgs arguments containing information about this request like the HTTP method</param>
        public void ReceivedRequestEvent(object sender, HttpCwsRequestEventArgs args)
        {
            ErrorLog.Notice($"{LogHeader} ReceivedRequestEvent running ...");

            try
            {
                if (args.Context.Request.RouteData == null)
                {
                    args.Context.Response.StatusCode  = 200;
                    args.Context.Response.ContentType = "text/html";
                    switch (args.Context.Request.Path.ToUpper())
                    {
                    // not used, for demo/temp purposes
                    case "/WHATEVER":
                        break;

                    default:
                        args.Context.Response.StatusCode = 204;
                        args.Context.Response.Write(
                            JsonConvert.SerializeObject(
                                new Response
                        {
                            Status  = "Error",
                            Message = this.GetApiHelp()
                        },
                                Formatting.Indented),
                            true);
                        break;
                    }
                }
                else
                {
                    args.Context.Response.StatusCode  = 200;
                    args.Context.Response.ContentType = "application/json";

                    // When we get a "GET" request
                    if (args.Context.Request.HttpMethod == "GET")
                    {
                        switch (args.Context.Request.RouteData.Route.Name.ToUpper())
                        {
                        // TODO: Level1. Not really a TODO, but we wanted to show you were you use the short name
                        // This was defined on line 90 of this class
                        case "HELLOWORLD":
                            // Get the data from the GET request by making use of the "data" variable
                            // that was defined on line 90 of this class

                            // TODO: Level1. Create your own code to handle the "helloworld" CWS route
                            string data = args.Context.Request.RouteData.Values["data"].ToString();

                            // TODO: Level1. From that code, send the received data to serial join 11
                            this.tp.StringInput[11].StringValue = data;

                            // TODO: Level1. Implement WriteWithAppend() in the FileControl.cs file to write the received data to User/logfile.txt
                            string appDir = Directory.GetApplicationRootDirectory();
                            FileControl.WriteWithAppend(data, $"{appDir}/User/logfile.txt");

                            // TODO: Level1. Return the received text as a response to this request
                            args.Context.Response.Write("Hello Atlanta!", true);

                            // For these exercises, take a good look at the supplied DUMMYGET route that is defined a few lines above.
                            break;

                        case "INTERLOCKSTATUS":
                            ErrorLog.Notice($"{LogHeader} ReceivedRequestEvent INTERLOCKSTATUS running ...");

                            var interlockResponse = new InterlockResponse();
                            interlockResponse.status = new List <ButtonStatus>();
                            interlockResponse.status.Add(new ButtonStatus(tp.BooleanInput[22].BoolValue));
                            interlockResponse.status.Add(new ButtonStatus(tp.BooleanInput[23].BoolValue));
                            interlockResponse.status.Add(new ButtonStatus(tp.BooleanInput[24].BoolValue));

                            string JSONResponseString = JsonConvert.SerializeObject(interlockResponse, Formatting.Indented);
                            ErrorLog.Notice($"{LogHeader} returning interlock status {JSONResponseString}");
                            args.Context.Response.Write(JSONResponseString, true);

                            break;

                        case "GETSLIDER":
                            // Level 3
                            ErrorLog.Notice($"{LogHeader} ReceivedRequestEvent SLIDER running ...");
                            ushort percentage = Convert.ToUInt16(tp.UShortInput[31].UShortValue / 65535 * 100);
                            JSONResponseString = $"{{\"value\": {percentage}%}}";
                            args.Context.Response.Write(JSONResponseString, true);

                            break;

                        case "LOG":
                            // Level 3
                            ErrorLog.Notice($"{LogHeader} GET Request LOG running ...");

                            JSONResponseString = FileControl.ReadFile($"{Directory.GetApplicationRootDirectory()}/User/logfile.txt");
                            args.Context.Response.Write($"{{ \"log\" : \"{JSONResponseString}\" }}", true);

                            break;

                        default:
                            break;
                        }
                    }

                    // When we get a "POST" request, we receive information from the frontend
                    if (args.Context.Request.HttpMethod == "POST")
                    {
                        string contents;

                        using (Crestron.SimplSharp.CrestronIO.Stream inputStream = args.Context.Request.InputStream)
                        {
                            using (StreamReader readStream = new StreamReader(inputStream, Encoding.UTF8))
                            {
                                contents = readStream.ReadToEnd();
                            }
                        }

                        switch (args.Context.Request.RouteData.Route.Name.ToUpper())
                        {
                        case "HOLAMUNDO":
                            ErrorLog.Notice($"{LogHeader} ReceivedRequestEvent HOLAMUNDO running ...");
                            string JSONBody = contents;
                            // echo request in response (for initial testing)
                            // args.Context.Response.Write(JSONBody, true);

                            Request request = JsonConvert.DeserializeObject <Request>(JSONBody);

                            string data = request.text;
                            ErrorLog.Notice($"{LogHeader} Adding {data} to end of file {Directory.GetApplicationRootDirectory()}/User/logfile.txt ...");
                            FileControl.WriteWithAppend(data, $"{Directory.GetApplicationRootDirectory()}/User/logfile.txt");

                            // set the button properly to send back
                            string JSONResponseString = this.tp.BooleanInput[21].BoolValue ? "{\"button\": true}" : "{\"button\": false}";

                            args.Context.Response.Write(JSONResponseString, true);

                            break;

                        case "POSTSLIDER":
                            // Level 3 payload {"value": 50}
                            ErrorLog.Notice($"{LogHeader} POST Request SLIDER running ...");
                            SliderRequest sliderRequest = JsonConvert.DeserializeObject <SliderRequest>(contents);

                            var sliderString = $"{sliderRequest.value}";
                            ErrorLog.Notice($"{LogHeader} Adding {sliderRequest.value} to end of file {Directory.GetApplicationRootDirectory()}/User/logfile.txt ...");
                            FileControl.WriteWithAppend(sliderString, $"{Directory.GetApplicationRootDirectory()}/User/logfile.txt");
                            tp.UShortInput[31].UShortValue = (ushort)(sliderRequest.value / 65535 * 100);

                            args.Context.Response.Write($"{{\"statusvalue\": \"{sliderRequest.value}\"}}", true);

                            break;

                        default:
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                args.Context.Response.ContentType = "application/json";
                args.Context.Response.StatusCode  = 401;
                args.Context.Response.Write(
                    JsonConvert.SerializeObject(
                        new Response
                {
                    Status  = "Error",
                    Message = this.GetApiError(ex)
                },
                        Formatting.Indented),
                    true);
            }
        }
        public UnifiedUIDevice(object baseDevice, Stream streamMap, string deviceId)
        {
            m_device = baseDevice;

            m_cde = m_device as CrestronDeviceWithEvents;
            if (m_cde != null)
            {
                m_cde.SigChange += cde_SigChange;
            }
            else
            {
                m_so = m_device as SmartObject;
                if (m_so != null)
                {
                    m_so.SigChange += so_SigChange;
                }
                else
                {
                    m_btl = m_device as BasicTriList;
                    if (m_btl != null)
                    {
                        m_btl.SigChange += btl_SigChange;
                    }
                    else
                    {
                        throw new NotSupportedException(String.Format("Base device of type {0} not supported", baseDevice.GetType().Name));
                    }
                }
            }

            if (streamMap == null)
            {
                return;
            }

            XDocument xd;

            using (var xr = new XmlReader(streamMap))
            {
                try
                {
                    xd = XDocument.Load(xr);
                }
                catch (Exception ex)
                {
                    ErrorLog.Exception("Exception while loading device map stream", ex);
                    return;
                }
            }

            XElement xe = xd.Elements().SingleOrDefault(xet => xet.Name == "device" && xet.Attribute("name") != null && xet.Attribute("name").Value == deviceId);

            if (xe == null)
            {
                return;
            }

            dictBoolSigMap   = GetSigMap(xe.Element("bool"));
            dictUShortSigMap = GetSigMap(xe.Element("ushort"));
            dictStringSigMap = GetSigMap(xe.Element("string"));
        }
示例#5
0
        /// <summary>
        /// The received request handler for the CWS server
        /// </summary>
        /// <param name="sender">optional sender object</param>
        /// <param name="args">The HttpCwsRequestEventArgs arguments containing information about this request like the HTTP method</param>
        public void ReceivedRequestEvent(object sender, HttpCwsRequestEventArgs args)
        {
            ErrorLog.Notice($"{LogHeader} ReceivedRequestEvent running ...");

            try
            {
                if (args.Context.Request.RouteData == null)
                {
                    args.Context.Response.StatusCode  = 200;
                    args.Context.Response.ContentType = "text/html";
                    switch (args.Context.Request.Path.ToUpper())
                    {
                    // not used, for demo/temp purposes
                    case "/WHATEVER":
                        break;

                    default:
                        args.Context.Response.StatusCode = 204;
                        args.Context.Response.Write(
                            JsonConvert.SerializeObject(
                                new Response
                        {
                            Status  = "Error",
                            Message = this.GetApiHelp()
                        },
                                Formatting.Indented),
                            true);
                        break;
                    }
                }
                else
                {
                    args.Context.Response.StatusCode  = 200;
                    args.Context.Response.ContentType = "application/json";

                    // When we get a "GET" request
                    if (args.Context.Request.HttpMethod == "GET")
                    {
                        switch (args.Context.Request.RouteData.Route.Name.ToUpper())
                        {
                        case "CONFIG":
                            // Level 3
                            ErrorLog.Notice($"{LogHeader} GET Request CONFIG running ...");

                            string JSONResponseString = FileControl.ReadFile($"{Directory.GetApplicationRootDirectory()}/User/config.json");
                            ErrorLog.Notice($"{LogHeader} returning interlock status {JSONResponseString}");
                            args.Context.Response.Write(JSONResponseString, true);

                            break;

                        default:
                            break;
                        }
                    }

                    // When we get a "POST" request, we receive information from the frontend
                    if (args.Context.Request.HttpMethod == "POST")
                    {
                        string contents;

                        using (Crestron.SimplSharp.CrestronIO.Stream inputStream = args.Context.Request.InputStream)
                        {
                            using (StreamReader readStream = new StreamReader(inputStream, Encoding.UTF8))
                            {
                                contents = readStream.ReadToEnd();
                            }
                        }

                        switch (args.Context.Request.RouteData.Route.Name.ToUpper())
                        {
                        case "HOLAMUNDO":
                            ErrorLog.Notice($"{LogHeader} ReceivedRequestEvent HOLAMUNDO running ...");
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                args.Context.Response.ContentType = "application/json";
                args.Context.Response.StatusCode  = 401;
                args.Context.Response.Write(
                    JsonConvert.SerializeObject(
                        new Response
                {
                    Status  = "Error",
                    Message = this.GetApiError(ex)
                },
                        Formatting.Indented),
                    true);
            }
        }