public ExchangePacket(byte[] initData)
        {
            crc32 = new Crc32MirrIEEE_802_3();
            Code  = initData[CODE_INDEX];

            PayloadLength  = (ushort)(initData[PAYLOAD_LENGTH_LOW_INDEX] << 0);
            PayloadLength |= (ushort)(initData[PAYLOAD_LENGTH_LOW_INDEX] << 8);

            Unique  = (ushort)(initData[UNIQUES_LOW_INDEX] << 0);
            Unique |= (ushort)(initData[UNIQUES_HIGH_INDEX] << 8);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Приемник данных
        /// </summary>
        private void Receive()
        {
            Crc32MirrIEEE_802_3 crcAlg        = new Crc32MirrIEEE_802_3();
            List <byte>         ReceivedBytes = new List <byte>(port.ReadBufferSize);

            uint crc32     = CRC_START_VALUE;
            int  readBytes = 0;
            byte tmpByte   = 0;
            bool destaff   = false;
            bool isStart   = false;

            try
            {
                while (IsConnect)
                {
                    readBytes = port.BytesToRead;
                    if (readBytes > 0 && readBytes < pack.Length)
                    {
                        port.Read(pack, 0, readBytes);
                        for (int idx = 0; idx < readBytes; idx++)
                        {
                            tmpByte = pack[idx];
                            if (tmpByte == FEND)
                            {
                                ReceivedBytes.Clear();
                                crc32   = CRC_START_VALUE;
                                isStart = true;
                                continue;
                            }

                            if (!isStart)
                            {
                                continue;
                            }

                            if (tmpByte == FESC)
                            {
                                destaff = true;
                                continue;
                            }

                            if (destaff)
                            {
                                destaff = false;
                                if (tmpByte == TFEND)
                                {
                                    ReceivedBytes.Add(FEND);
                                }
                                else if (tmpByte == TFESC)
                                {
                                    ReceivedBytes.Add(FESC);
                                }
                                else
                                {
                                    ReceivedBytes.Clear();
                                    isStart = false;
                                    continue;
                                }
                            }
                            else
                            {
                                ReceivedBytes.Add(tmpByte);
                            }

                            int size = 0;

                            if (ReceivedBytes.Count >= HEAD_MIN_RAW_SIZE)
                            {
                                size = ((ReceivedBytes[IND_LEN1] << 8) | ReceivedBytes[IND_LEN]);
                            }

                            if (ReceivedBytes.Count <= (HEAD_MIN_RAW_SIZE + size))
                            {
                                crc32 = crcAlg.Step(ReceivedBytes[ReceivedBytes.Count - 1], crc32);
                            }

                            if (ReceivedBytes.Count == (HEAD_MIN_RAW_SIZE + size + CRC_RAW_SIZE))
                            {
                                uint h = BitConverter.ToUInt32(ReceivedBytes.ToArray(), (ReceivedBytes.Count - 4));
                                if (crc32 == h)
                                {
                                    OnSerialReceiveEvent(ReceivedBytes.ToArray());
                                    isStart = false;
                                    break;
                                }
                                else
                                {
                                    ReceivedBytes.Clear();
                                    crc32   = CRC_START_VALUE;
                                    isStart = false;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                OnSerialErrorEvent(0, null, ex);
            }
        }
        /// <summary>
        /// Дестаффинг
        /// </summary>
        public static byte[] DeStaffing(byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                return(null);
            }

            Crc32MirrIEEE_802_3 crcAlg        = new Crc32MirrIEEE_802_3();
            List <byte>         convertedList = new List <byte>();
            uint crc32     = CRC_START_VALUE;
            bool isReceive = false;
            bool destaff   = false;
            bool isStart   = false;

            for (int idx = 0; idx < data.Length; idx++)
            {
                byte tmpByte = data[idx];
                //
                // Определили начало пакета
                if (tmpByte == FEND)
                {
                    // список должен быть пустым
                    convertedList.Clear();
                    // признак готовности полученного пакета
                    isReceive = false;
                    // признак того что уже получен стартовый байт
                    isStart = true;
                    continue;
                }
                //
                // Пока не получим стартовый байт все байты игнорируются
                if (!isStart)
                {
                    continue;
                }
                //
                // Байт дестафинга
                if (tmpByte == FESC)
                {
                    destaff = true;
                    continue;
                }
                //
                // Определение последовательности дестафинга
                if (destaff)
                {
                    destaff = false;
                    //
                    // если заменяем 0xC0
                    if (tmpByte == TFEND)
                    {
                        convertedList.Add(FEND);
                    }
                    //
                    // если заменяем 0xDB
                    else if (tmpByte == TFESC)
                    {
                        convertedList.Add(FESC);
                    }
                    // не корректное значение (нет стаффинга)
                    else
                    {
                        convertedList.Clear();
                        isReceive = false;
                        isStart   = false;
                        continue;
                    }
                }
                else
                {
                    convertedList.Add(tmpByte);
                }
            }

            int size = 0;

            //
            // Получен заголовок пакета, определение длины данных
            if (convertedList.Count >= HEAD_MIN_RAW_SIZE)
            {
                size = ((convertedList[IND_LEN1] << 8) | convertedList[IND_LEN]);
            }
            //
            // Получение всех данных
            if (convertedList.Count <= (HEAD_MIN_RAW_SIZE + size))
            {
                crc32 = crcAlg.Step(convertedList[convertedList.Count - 1], crc32);
            }
            //
            // Получили все данные
            if (convertedList.Count == (HEAD_MIN_RAW_SIZE + size + CRC_RAW_SIZE))
            {
                //
                // Определяем содержимое пакета
                if (crc32 == BitConverter.ToUInt32(convertedList.ToArray(), convertedList.Count - 4))
                {
                    //Удаление контрольной суммы
                    convertedList.RemoveRange((convertedList.Count - 4), 4);
                    isReceive = true;
                    isStart   = false;
                    return(convertedList.ToArray());
                }
                else
                {
                    convertedList.Clear();
                    crc32     = CRC_START_VALUE;
                    isReceive = false;
                    isStart   = false;
                }
            }

            return(null);
        }
 public ExchangePacket()
 {
     crc32 = new Crc32MirrIEEE_802_3();
 }