// Event handlers // Implement the route handlers by reading the HTTP method/headers/entity-body and // performing the corresponding action void server_ReceivedRequestEvent(object sender, HttpCwsRequestEventArgs args) { try { // Do something light here. Do not process the requests in the event handler. CrestronConsole.PrintLine("Incoming " + args.Context.Request.HttpMethod + " Request from " + args.Context.Request.UserHostName + " to " + args.Context.Request.Url); } catch (Exception e) { CrestronConsole.PrintLine("Error in server_ReceivedRequestEvent: {0}", e); } }
void myServerReceivedRequestEvent(object sender, HttpCwsRequestEventArgs args) { try { if (args.Context.Request.RouteData.Route.Name == "shversion") { args.Context.Response.StatusCode = 200; args.Context.Response.StatusDescription = "OK"; args.Context.Response.ContentType = "application/vnd.collection+json"; string[] procVersion = versionResponse.Split(','); string[] progComment = cmdResponse.Split('\n'); // Create a simple JSON Object to send back to the frontend // ( data:{ id:"",hostname:"",version:"",puf:"",serial:"",mac:"",systemname:"",compiled:"",uptime:"" } } JObject resObject = new JObject { { "data", new JObject { { "id", procId }, { "hostname", procHostname }, { "version", procVersion[0].Split('[')[1] }, { "puf", procFirmware }, { "serial", procSerial }, { "mac", macAddress }, { "systemname", progComment[3].Replace("\r", "").Replace("Program File: ", "") }, { "compiled", progComment[6].Replace("\r", "").Replace("Compiled On: ", "").Trim() } } } }; string json = JsonConvert.SerializeObject(resObject); args.Context.Response.Write(json, true); } else { args.Context.Response.Write("Unhandled Route!", true); } } catch (NullReferenceException e) { ErrorLog.Error("CwsServerNullError: {0}", e.Message); } catch (Exception e) { ErrorLog.Error("CwsServerError: {0}", e.Message); args.Context.Response.StatusCode = 404; args.Context.Response.Write("Error", true); } }
void server_ReceivedRequestEvent(object sender, HttpCwsRequestEventArgs args) { try { CrestronConsole.PrintLine("\r\n" + args.Context.Request.HttpMethod + " request received from " + args.Context.Request.UserHostName + " to " + args.Context.Request.Url.AbsolutePath); } catch (Exception e) { CrestronConsole.PrintLine("Error in server_ReceivedRequestEvent(): {0}", e); } }
// Event handler called every time the listener receives an HTTP request private void listener_ReceivedRequestEvent(object sender, HttpCwsRequestEventArgs args) { CrestronConsole.PrintLine(""); CrestronConsole.PrintLine("Received " + args.Context.Request.HttpMethod + " request from " + args.Context.Request.UserHostName); }
/// <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); } }
/// <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); } }