static void Main(string[] args) { Console.WriteLine("Hello World!"); LightControl control = new LightControl(); while (true) { LightObject light = control.GetRequest("Next").Result; if (light != null) { Console.WriteLine("Light command to execute: \"" + light.Command + "\" with id: " + light.Id); control.HandleLightCommand(light); } Thread.Sleep(500); } }
public void HandleLightCommand(LightObject light) { switch (light.Command) { case "on": HandleOnCommand(light); break; case "off": HandleOffCommand(light); break; default: HandleUnknownCommand(light); break; } UpdateLightRequest(light); }
protected virtual async void UpdateLightRequest(LightObject light) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUri + light.Id); request.Method = "Put"; request.KeepAlive = false; request.ContentType = "application/json"; request.Headers.Add("Content-Type", "application/json"); string json = JsonConvert.SerializeObject(light); //Serialize json object to string request.ContentLength = json.Length; //Get length of json Stream stream = request.GetRequestStream(); //Create stream stream.Write(Encoding.UTF8.GetBytes(json), 0, json.Length); //Write PUT request HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); //Get response to make sure json object is sent }
protected virtual void HandleOnCommand(LightObject light) { Console.WriteLine("Handler: Light on"); light.IsRun = true; }
protected virtual void HandleUnknownCommand(LightObject light) { Console.WriteLine("Handler: Unknown command"); light.IsRun = true; }