Ejemplo n.º 1
0
        private void Encode(uint crcInitialValue = 0x0)
        {
            var bytes             = new List <byte>();
            var frameControlByte0 = (byte)Type;

            if (FramePending)
            {
                frameControlByte0 |= (0x1 << 4);
            }
            bytes.Add(frameControlByte0);
            bytes.Add(0); // frameControlByte1

            bytes.Add(DataSequenceNumber);
            if (AddressInformation != null && AddressInformation.Bytes.Count > 0)
            {
                bytes.AddRange(AddressInformation.Bytes);
            }
            if (Payload != null && Payload.Count > 0)
            {
                bytes.AddRange(Payload);
            }

            var crcLength = CRCPolynomial.GetLength();
            var crc       = CalculateCRC(bytes, crcInitialValue, CRCPolynomial);

            switch (crcLength)
            {
            case 2:
                bytes.Add(crc[0]);
                bytes.Add(crc[1]);
                break;

            case 4:
                bytes.Add(crc[0]);
                bytes.Add(crc[1]);
                bytes.Add(crc[2]);
                bytes.Add(crc[3]);
                break;

            default:
                Logger.Log(LogLevel.Error, "Cannot generate CRC of invalid length {0}, the packet will not contain CRC data", crcLength);
                break;
            }

            Bytes = bytes.ToArray();
        }
Ejemplo n.º 2
0
        public bool CheckCRC(uint crcInitialValue = 0x0)
        {
            var crcLength = CRCPolynomial.GetLength();
            var crc       = CalculateCRC(Bytes.Take(Bytes.Length - crcLength), crcInitialValue, CRCPolynomial);

            // Byte little endian order
            switch (crcLength)
            {
            case 2:
                return(Bytes[Bytes.Length - 2] == crc[0] && Bytes[Bytes.Length - 1] == crc[1]);

            case 4:
                return(Bytes[Bytes.Length - 4] == crc[0] && Bytes[Bytes.Length - 3] == crc[1] && Bytes[Bytes.Length - 2] == crc[2] && Bytes[Bytes.Length - 1] == crc[3]);

            default:
                Logger.Log(LogLevel.Error, "Cannot check CRC of invalid length {0}", crcLength);
                return(false);
            }
        }