private void Serialport_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] readBuffer; int n = serialPort.BytesToRead; byte[] buf = new byte[n]; serialPort.Read(buf, 0, n); buffer.AddRange(buf); //Console.WriteLine(ByteStrUtil.ByteToKHex(buffer.ToArray())); while (buffer.Count >= 14) { if (buffer[0] == 0x7D && buffer[1] == 0x7B) { int endIndex = FPI.EndIndex(buffer.ToArray()); if (endIndex == 0) { break; } readBuffer = new byte[endIndex + 2]; buffer.CopyTo(0, readBuffer, 0, endIndex + 2); buffer.RemoveRange(0, endIndex + 2); if (FPI.IsLength(readBuffer) && FPI.JY(readBuffer)) { Command command = FPI.Decoder(readBuffer); CacheData.AddDataToQueue(command); } } else { buffer.Clear(); } } }
/// <summary> /// 串口发送命令 /// </summary> /// <param name="command">命令对象</param> /// <param name="isForward">是否转发</param> public bool Send(Command command, bool isForward) { if (command != null && Open()) { byte[] data = FPI.Encoder(command, this.isForward); Console.WriteLine("发送命令: " + ByteStrUtil.ByteToKHex(data)); serialPort.Write(data, 0, data.Length); Thread.Sleep(100); return(true); } return(false); }