/// <summary> /// Sends command to SmartPlug expecting a response of a certain type /// </summary> /// <param name="command"></param> public TPlugResponse Send <TPlugResponse>(IPlugCommand command) where TPlugResponse : IPlugResponse, new() { if (command == null) { throw new ArgumentNullException(nameof(command)); } string json = command.GetJson(); TcpClient tcpClient = null; try { tcpClient = new TcpClient(connectHost, connectPort); if (tcpClient.Connected) { var ns = tcpClient.GetStream(); var jsonBytes = Encoding.UTF8.GetBytes(json); var pseudoCrypted = smartPlugEncrypt(jsonBytes); ns.Write(pseudoCrypted, 0, pseudoCrypted.Length); Thread.Sleep(100); // give some time for device to respond byte[] receiveBuffer = new byte[1024 * 2]; int read = ns.Read(receiveBuffer, 0, receiveBuffer.Length); if (typeof(TPlugResponse) != typeof(NullResponse)) { TPlugResponse resp = new TPlugResponse(); if (read > 4) { // read actual payload minus 4-byte header byte[] actual = new byte[read - 4]; if (actual.Length > 0) { Array.Copy(receiveBuffer, 4, actual, 0, read - 4); var pseudoDecrypted = smartPlugDecrypt(actual); var response = Encoding.UTF8.GetString(pseudoDecrypted); resp.Parse(response); } } return(resp); } } } finally { if (tcpClient != null) { tcpClient.Close(); } } return(default(TPlugResponse)); }
/// <summary> /// Sends command to SmartPlug, not expecting a response /// </summary> /// <param name="command"></param> public void Send(IPlugCommand command) { Send <NullResponse>(command); }