public ActionResult <string> BulbControlAdvanced([FromBody] YeelightCommand yeelight) { string methodName = yeelight.Method; string response = null; BulbHistory history = new BulbHistory(); if (yeelight.IsIntValue && yeelight.IsStringValue) { response = "something wrong"; } else { if (yeelight.IsIntValue) { int value = yeelight.ControlValue; history.MethodValue = value.ToString(); response = Yeelight.Yeelight.BulbCommand(methodName, value); // id is temporary for now, will add bulb ids later } else if (yeelight.IsStringValue) { string value = yeelight.ControlMethod; history.MethodValue = value.ToString(); response = Yeelight.Yeelight.BulbCommand(methodName, value); } }; history.LampId = 1; history.MethodName = methodName; history.DateSent = DateTime.Now; history.Response = response; _context.BulbsHistory.Add(history); _context.SaveChanges(); return(response); }
static void Main(string[] args) { Console.WriteLine("[Info] Test starts now."); // Test the Yeelight's "Fake SSDP protocol" FakeSsdpHandler ssdpHandler = new FakeSsdpHandler(); // So far the SSDP handler will block the thread for about 2 seconds. // I'll add a event-based method later if possible. // // Here it returns a List<string>, containing IP and port strings. List <string> results = ssdpHandler.FindYeelightDevice(); string firstDeviceIp = string.Empty; if (results.Count > 0) { foreach (string result in results) { Console.WriteLine("[FakeSSDP.Results] Found device at " + result); } Console.WriteLine("[FakeSSDP.Results] Pick the first device, at " + results[0]); firstDeviceIp = results[0].Split(':')[0]; } else { Console.WriteLine("[Error] No device found, please turn on your device & check your network, then try again."); Console.WriteLine("[Error] Press any key to exit..."); Console.ReadKey(); Environment.Exit(1); } Thread.Sleep(2000); // Initialize the command helper YeelightCommand yeelightCommand = new YeelightCommand(firstDeviceIp); Console.WriteLine("[Test] #1 Set maximum brightness"); bool testResult1 = yeelightCommand.SetBrightness(99, YeelightEffect.SmoothChange, 500).Result; Thread.Sleep(3000); Console.WriteLine("[Test] #2 Turn off the light~"); bool testResult2 = yeelightCommand.SetPower(false, YeelightEffect.SmoothChange, 500).Result; Thread.Sleep(3000); Console.WriteLine("[Test] #3 Turn on the light again lol~"); bool testResult3 = yeelightCommand.SetPower(true, YeelightEffect.SmoothChange, 500).Result; Thread.Sleep(3000); Console.WriteLine("[Test] Final: Get all status"); var testResultStatus = yeelightCommand.GetAllStatus().Result; Console.WriteLine("\r\n\r\n[Result] Test 1 returns {0}, Test 2 returns {1}, Test 3 returns {2}, ", testResult1.ToString(), testResult2.ToString(), testResult3.ToString()); Console.WriteLine("[Result] Powered on: " + testResultStatus.IsPowerOn.ToString()); Console.WriteLine("[Result] Brightness: " + testResultStatus.Brightness.ToString()); Console.WriteLine("[Result] Model type: " + Enum.GetName(typeof(YeelightModel), testResultStatus.Model)); Console.ReadKey(); }
private async Task <IList <YeelightInfo> > SendCommandAsync(string methodName, IList <object> commandParams, CancellationToken cancellationToken) { var responseEntities = new List <YeelightInfo>(); using (TcpClient listener = new TcpClient(_targetIp, _targetPort)) { var command = new YeelightCommand { Id = 1, Method = methodName, MethodParams = commandParams }; var commandText = System.Text.Json.JsonSerializer.Serialize(command); var bytes = Encoding.ASCII.GetBytes(commandText + "\r\n"); listener.NoDelay = true; using (NetworkStream s = listener.GetStream()) { s.Socket.Blocking = false; while (responseEntities is null || !responseEntities.Any()) { var sb = new StringBuilder(string.Empty); // Declare the callback. Need to do that so that // the closure captures it. AsyncCallback callback = null; bool stringReceived = false; byte[] buffer = new byte[100]; // Assign the callback. callback = ar => { // Call EndRead. int bytesRead = listener.Client.EndReceive(ar); // Process the bytes here. var rs = Encoding.ASCII.GetString(buffer, 0, buffer.Length).Replace("\0", ""); sb.Append(rs); // Determine if you want to read again. If not, return. if (rs.Contains("\n")) { stringReceived = true; return; } buffer = new byte[100]; // Read again. This callback will be called again. listener.Client.BeginReceive(buffer, 0, 100, SocketFlags.Partial, callback, null); }; // Trigger the initial read. listener.Client.BeginReceive(buffer, 0, 100, SocketFlags.Partial, callback, null); Thread.Sleep(200); var sw = new StreamWriter(s); sw.AutoFlush = true; await sw.WriteLineAsync(commandText); while (!stringReceived) { Thread.Sleep(200); } var responseString = sb.ToString(); var responseEntity = System.Text.Json.JsonSerializer.Deserialize <YeelightInfo>( responseString, new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true } ); if (responseEntity.Result.Any() && !responseEntity.Params.Any()) { responseEntity.Params = responseEntity.Result.Select((value, idx) => new { key = commandParams[idx].ToString(), v = value }).ToDictionary(x => x.key, x => (object)x.v); } responseEntities.Add(responseEntity); } } } return(responseEntities); }