private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { int n = port.BytesToRead; byte[] buf = new byte[n]; //默认是杏林的通道机 port.Read(buf, 0, n); //缓存数据 this.comBuffer.AddRange(buf); //判断数据是否达到8个字节 while (this.comBuffer.Count >= 8) { //判断数据头是否为01 if (this.comBuffer[0] == 0x01) { byte[] package = new byte[8]; this.comBuffer.CopyTo(0, package, 0, 8); string hexStr = TypeConvert.ByteArrayToHexString(package); //移除该8个字节 this.comBuffer.RemoveRange(0, 8); //检测校验位是否正确,不正确则跳过 if (!TypeConvert.CheckCRC(hexStr)) { continue; } this.comDataQueue.Enqueue(hexStr); this.lastComData = hexStr; this.lastComDataTime = DateTime.Now; } else { //数据头不正确,清除 this.comBuffer.RemoveAt(0); } } } catch (Exception ex) { Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace); } }