private static byte[] Pack(byte[] data) { byte[] ret = { }; byte[] empty = { 0x00 };//for pkg-len byte[] crc16 = CRC16.GetCRC(data); ret = ret.Concat(head) .Concat(empty) .Concat(data) .Concat(crc16) .Concat(tail).ToArray(); int pkg_len = ret.Length - head.Length - tail.Length; ret[head.Length] = (byte)pkg_len; return(ret); }
private void Process(byte b) { if (package_on == true) { if (pos > CACHE_LENGTH) { package_on = false; pos = 0; return; } cache[pos++] = b; if (pos > 4 && cache[pos - 4] == Command.tail[0] && //a pkg is finished cache[pos - 3] == Command.tail[1] && cache[pos - 2] == Command.tail[2] && cache[pos - 1] == Command.tail[3] && cache[Command.head.Length] + Command.head.Length + Command.tail.Length == pos //check pkg len ) { package_on = false; byte[] temp = cache.Take(pos - 4).ToArray(); //remove tail' bytes byte[] pkg = temp.Skip(2).ToArray(); //remove head byte and pkg-len byte if (CRC16.CheckCRC(pkg) == true) { ProcessResult(pkg.Take(pkg.Length - 2).ToArray());//remove crc's bytes } else { CleanWorkList(); CallProtocolError(ErrorCodeCrcError, "crc check error"); } } } else if (package_on == false && b == Command.head[0]) //start a pkg { package_on = true; pos = 0; cache[pos++] = b; } }
//需要没有包头,没有包尾的数据 public static bool CrcCheck(byte[] data) { return(CRC16.CheckCRC(data)); }