Пример #1
0
        public static byte[] Split(IByteBuffer buffer)
        {
            var rdx      = 0;
            var crcBytes = new byte[2];
            var crc      = 0;
            var length   = 0;
            var valid    = false;

            while (true)
            {
                // 可读字节数小于最小报文长度
                if (buffer.ReadableBytes < LoraConst.MinLength)
                {
                    return(null);
                }
                // 确定帧头的位置
                if (LoraConst.StartSign != buffer.GetByte(rdx))
                {
                    rdx = GetStartIndex(buffer, LoraConst.StartSign);
                }

                // 没有找到帧头
                if (rdx == -1)
                {
                    return(null);
                }
                buffer.SetReaderIndex(rdx);
                var lengthBytes = new byte[2];
                buffer.GetBytes(rdx + 23, lengthBytes);
                length = BytesUtil.Bytes2Int16(lengthBytes);
                if (buffer.ReadableBytes < LoraConst.MinLength + length)
                {
                    rdx++;
                    buffer.SetReaderIndex(rdx);
                    continue;
                }
                var content = new byte[25 + length];
                buffer.GetBytes(rdx, content);
                buffer.GetBytes(rdx + 25 + length, crcBytes);
                crc   = CRC16.calcCrc16(content);
                valid = BytesUtil.ByteArrayEquals(crcBytes, BytesUtil.Int16ToBytes((Int16)crc));
                if (!valid)
                {
                    rdx++;
                    buffer.SetReaderIndex(rdx);
                    continue;
                }
                var msg = new byte[LoraConst.MinLength + length];
                buffer.ReadBytes(msg);
                return(msg);
            }
        }