Beispiel #1
0
 /// <summary>
 /// 从字节数组中提取帧
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static byte[] ExtractFrame(byte[] data)
 {
     if (data == null)
     {
         throw new ArgumentNullException("data", "data不能为空");
     }
     byte[] ret;
     for (int i = 0; i < data.Length; i++)
     {
         if (data[i] == StartByte)
         {
             LengthField lf = new LengthField();
             lf.SetData(data, i + 1, lf.Length);
             if (data[i + lf.Value - 1] == EndByte)
             {
                 if (IsProtocol(data, i, lf.Value))
                 {
                     ret = new byte[lf.Value];
                     Array.Copy(data, i, ret, 0, lf.Value);
                     return(ret);
                 }
             }
         }
     }
     return(null);
 }
Beispiel #2
0
        protected static Result IsProtocolCommon(byte[] data, int startIndex, int len)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data", "data不能为空");
            }
            if (data.Length < startIndex)
            {
                throw new ArgumentOutOfRangeException("startIndex", "startIndex超出范围");
            }
            if (data.Length < startIndex + len || len < 0)
            {
                throw new ArgumentOutOfRangeException("len", "len超出范围");
            }

            // 起始字符 1、长度 2、控制域 1、信息域 6、地址域 >=0、功能码 1、信息类 2、数据单元 >=0、校验和 1、结束字符 1
            if (len < 15)
            {
                return(false);
            }
            if (data[startIndex] != StartByte)
            {
                return(false);
            }
            if (data[startIndex + len - 1] != EndByte)
            {
                return(false);
            }

            LengthField lf = new LengthField();

            lf.SetData(data, startIndex + 1, lf.Length);
            if (lf.Value != len)
            {
                return((Result)"此帧的长度与长度域不符");
            }

            byte checkSum = data.Sum(startIndex + 3, len - 5);

            if (checkSum != data[startIndex + len - 2])
            {
                return((Result)"此帧的校验和不正确");
            }
            return(true);
        }