private void Commport_OnDataArrivedEvent(object sender, byte[] data) { lock (_DataLocker) { _RecievedData.AddRange(data); _Response = GetPacket(_RecievedData); if (_Response != null) _PacketReceived.Set(); } }
private Packet GetPacket(List<byte> data) { while (data.Count > 0) //去掉前面的无用字节 { if (data[0] != _HEAD) { data.RemoveAt(0); } else { if (data.Count >= 7 && data[6] != _HEAD) //如果第6个字节不是包头,说明前面这些字符也是无效的。 { data.RemoveRange(0, 6); } else { if (data.Count >= 9 && data.Count >= data[8] + 11 && data[11 + data[8] - 1] != _TAIL) //如果包尾不是指定的字节,则说明前面的数据都是无用的 { data.RemoveRange(0, 11 + data[8]); } else { break; } } } } if (data.Count >= 9 && data.Count >= data[8] + 11) { byte[] p = new byte[data[8] + 11]; data.CopyTo(0, p, 0, p.Length); data.RemoveRange(0, p.Length); //同时从缓存中删除包 var ret = new Packet(); ret.Command = p[7]; ret.Address = HexStringConverter.HexToString(new byte[] { p[5], p[4], p[3], p[2], p[1] }, string.Empty).Trim('A'); if (p[8] > 2) //前两字节数据与请求数据的一样,不需要 { byte[] d = new byte[p[8] - 2]; Array.Copy(p, 9, d, 0, d.Length); ret.Data = d; } return ret; } return null; }
public Packet Request(byte cmd, string address, byte[] data) { if (IsOpened) { lock (_DataLocker) { _PacketReceived.Reset(); _RecievedData.Clear(); _Response = null; } byte[] p = CreateRequest(cmd, address, data); _Commport.SendData(p); _PacketReceived.WaitOne(2000); return _Response; } return null; }