ComputeChecksumBytes() public method

public ComputeChecksumBytes ( byte bytes ) : byte[]
bytes byte
return byte[]
Exemplo n.º 1
0
        private void Build()
        {
            Crc16Ccitt crc = new Crc16Ccitt(InitialCrcValue.Zeros);

            List <byte> tt = new List <byte>();

            tt.Add(m_start_byte);
            tt.Add(0x00); //length place holder
            tt.Add(0x00); //length place holder
            tt.Add((byte)((m_source_address << 5) | (m_destination_address << 2) | m_protocol_code));
            tt.Add(m_command);

            if (m_data != null)
            {
                foreach (byte b in m_data)
                {
                    tt.Add(b);
                }
            }
            tt.Add(0x00); //checksum place holder
            tt.Add(0x00); //checksum place holder

            m_telegram = tt.ToArray();
            byte[] ba = BitConverter.GetBytes((UInt16)(tt.Count - 3)); //excludes start and length bytes
            m_telegram[1] = ba[0];                                     //length
            m_telegram[2] = ba[1];                                     //length

            byte[] crc_v = crc.ComputeChecksumBytes(m_telegram, 0, m_telegram.Length - 2);

            m_telegram[m_telegram.Length - 2] = crc_v[0];
            m_telegram[m_telegram.Length - 1] = crc_v[1];
        }
Exemplo n.º 2
0
        //private string GetHex(int intVal)
        //{
        //	//return intVal.ToString("X");
        //	//return String.Format("{0:X}", intVal);
        //	var hex = String.Format("{0:X}", intVal);
        //	if (hex.Length == 1) hex = "0" + hex;
        //	return hex;
        //}

        //private byte[] GetTestBufToSend()
        //{
        //	var sendbuf = new byte[31];

        //	sendbuf[0] = 192;
        //	sendbuf[1] = 168;
        //	sendbuf[2] = 1;
        //	sendbuf[3] = 15;
        //	sendbuf[4] = 72;
        //	sendbuf[5] = 68;
        //	sendbuf[6] = 76;
        //	sendbuf[7] = 77;
        //	sendbuf[8] = 73;
        //	sendbuf[9] = 82;
        //	sendbuf[10] = 65;
        //	sendbuf[11] = 67;
        //	sendbuf[12] = 76;
        //	sendbuf[13] = 69;

        //	sendbuf[14] = 170;	// Leading code
        //	sendbuf[15] = 170;	// Leading code

        //	sendbuf[16] = 15;		// Length of data package
        //	sendbuf[17] = 1;		// Original subnet id
        //	sendbuf[18] = 23;		// Original device id
        //	sendbuf[19] = 0;		// Original device type
        //	sendbuf[20] = 149;	// Original device type
        //	sendbuf[21] = 0;		// Operate code
        //	sendbuf[22] = 49;		// Operate code
        //	sendbuf[23] = 1;		// Target subnet id
        //	sendbuf[24] = 74;		// Target device id

        //	sendbuf[25] = 1;		// content
        //	sendbuf[26] = 40;		// content
        //	sendbuf[27] = 0;		// content
        //	sendbuf[28] = 3;		// content

        //	sendbuf[29] = 191;	// CRC H
        //	sendbuf[30] = 29;		// CRC L

        //	return sendbuf;
        //}

        private byte[] BuildBufToSend(int targetSubnetId, int targetDeviceId, byte[] operateCode, byte[] content,
                                      int senderSubnetId, int senderDeviceId, byte[] senderDeviceType)
        {
            var length  = 25 + content.Length + 2;
            var sendbuf = new byte[length];

            // Fixed header
            sendbuf[0]  = 192;              // 192
            sendbuf[1]  = 168;              // 168
            sendbuf[2]  = 1;                // 1
            sendbuf[3]  = 15;               // 15
            sendbuf[4]  = 72;               // H
            sendbuf[5]  = 68;               // D
            sendbuf[6]  = 76;               // L
            sendbuf[7]  = 77;               // M
            sendbuf[8]  = 73;               // I
            sendbuf[9]  = 82;               // R
            sendbuf[10] = 65;               // A
            sendbuf[11] = 67;               // C
            sendbuf[12] = 76;               // L
            sendbuf[13] = 69;               // E

            // Fixed leading code
            sendbuf[14] = 0xAA;
            sendbuf[15] = 0xAA;

            var lengthOfDataPackage = 11 + content.Length;

            sendbuf[16] = (byte)lengthOfDataPackage;              // 15 Length of data package
            sendbuf[17] = (byte)senderSubnetId;                   // 1 Original subnet id
            sendbuf[18] = (byte)senderDeviceId;                   // 23 Original device id
            sendbuf[19] = senderDeviceType[0];                    // 0 Original device type
            sendbuf[20] = senderDeviceType[1];                    // 149 Original device type
            sendbuf[21] = operateCode[0];                         // 0 Operate code
            sendbuf[22] = operateCode[1];                         // 49 Operate code
            sendbuf[23] = (byte)targetSubnetId;                   // 1 Target subnet id
            sendbuf[24] = (byte)targetDeviceId;                   // 74 Target device id

            for (int i = 0; i < content.Length; i++)
            {
                sendbuf[i + 25] = content[i];                           // 1 content
            }
            var crcBufLength = lengthOfDataPackage - 2;
            var crcBuf       = new byte[crcBufLength];

            for (int i = 0; i < crcBufLength; i++)
            {
                crcBuf[i] = sendbuf[16 + i];
            }

            var crc = new Crc16Ccitt(0);
            var res = crc.ComputeChecksumBytes(crcBuf);

            sendbuf[sendbuf.Length - 2] = res[1];
            sendbuf[sendbuf.Length - 1] = res[0];

            return(sendbuf);
        }
Exemplo n.º 3
0
        private void sendYmodemClosingPacket(byte STX, int packetNumber, int invertedPacketNumber, byte[] data, int dataSize, byte[] CRC, int crcSize)
        {
            /* calculate CRC */
            Crc16Ccitt crc16Ccitt = new Crc16Ccitt(InitialCrcValue.Zeros);

            CRC = crc16Ccitt.ComputeChecksumBytes(data);

            /* send the packet */
            sendYmodemPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, CRC, crcSize);
        }
Exemplo n.º 4
0
        static async Task TestGenerateCrc16Code()
        {
            var code         = "00020101021226850014br.gov.bcb.pix2563pix.santander.com.br/qr/v1/1edc73e3-cb6b-420e-a43a-00cfdde3288b520400005303986540520.005802BR5925DANILO NOVAIS DE OLIVEIRA6009SAO PAULO62070503***6304";
            var crcGenerator = new Crc16Ccitt(InitialCrcValue.NonZero1);

            var codeArray = Encoding.ASCII.GetBytes(code);
            var result    = crcGenerator.ComputeChecksumBytes(codeArray);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(result);
            }

            var strResult = BitConverter.ToString(result);

            await Task.CompletedTask;
        }
        /// <summary>
        /// Builds up a message packet from the payload passed across. The payload is modified by this method.
        /// </summary>
        /// <param name="payload"></param>
        /// <param name="isFirstMessage"></param>
        /// <returns></returns>
        private List <byte> BuildValidMessagePacket(List <byte> payload, bool isFirstMessage = true)
        {
            var checksumCalculator = new Crc16Ccitt(Crc16Ccitt.InitialiseToZero);
            var checksum           = AddDCEStuffing(new List <byte>(checksumCalculator.ComputeChecksumBytes(payload.ToArray(), false)));

            var result = new List <byte>();

            if (isFirstMessage)
            {
                result.Add(0x00);                // prefix with a leading byte so that the listener will not reject it
            }
            result.Add(0x10);
            result.Add(0x02);
            result.AddRange(AddDCEStuffing(payload));
            result.Add(0x10);
            result.Add(0x03);
            result.AddRange(checksum);

            return(result);
        }
Exemplo n.º 6
0
        private (byte CrcLow, byte CrcHigh) CalculateChecksum(byte[] sendbuf)
        {
            const int indexLengthOfDataPackage = 16;
            int       lengthOfDataPackage      = sendbuf[indexLengthOfDataPackage];
            var       crcBufLength             = lengthOfDataPackage - 2;

            var crcBuf = new byte[crcBufLength];

            for (var i = 0; i < crcBufLength; i++)
            {
                crcBuf[i] = sendbuf[16 + i];
            }
            var crc      = new Crc16Ccitt(0);
            var checksum = crc.ComputeChecksumBytes(crcBuf);

            var crcHigh = checksum[1];
            var crcLow  = checksum[0];

            return(CrcLow : crcLow, CrcHigh : crcHigh);
        }
Exemplo n.º 7
0
        public static ArduinoI2CResponse VerifyIncomingData(byte[] bData)
        {
            try
            {
                Int16 sizeData = bData[0];
                int   size     = sizeData + 4;
                if (bData[1] != 2)
                {
                    throw new Exception("To nie jest typ Response");
                }
                byte lo = bData[size - 2];
                byte hi = bData[size - 1];

                byte[] crcData = new byte[size - 2];
                Buffer.BlockCopy(bData, 0, crcData, 0, size - 2);
                Crc16Ccitt crc = new Crc16Ccitt(InitialCrcValue.NonZero1);
                Debug.WriteLine("CRC: " + crc.ComputeChecksum(crcData));
                var retByte = crc.ComputeChecksumBytes(crcData);

                if (!((retByte[0] == lo) && retByte[1] == hi))
                {
                    throw new Exception("B³ad przesy³u danych! B³ad CRC");
                }

                byte[] Data = new byte[size - 4];
                Buffer.BlockCopy(bData, 2, Data, 0, sizeData);

                return((ArduinoI2CResponse)GetObjectFromBytes(Data, typeof(ArduinoI2CResponse)));
            }
            catch (Exception ex)
            {
                string val = String.Join(",", bData);
                LoggerFactory.LogException(ex, "VerifyIncomingData", new { val });
                return(new ArduinoI2CResponse {
                    Status = (int)I2CResponseStatus.Error
                });
            }
        }
Exemplo n.º 8
0
        private void sendYmodemInitialPacket(byte STX, int packetNumber, int invertedPacketNumber, byte[] data, int dataSize, string path, FileStream fileStream, byte[] CRC, int crcSize)
        {
            string fileName = System.IO.Path.GetFileName(path);
            string fileSize = fileStream.Length.ToString();

            /* add filename to data */
            int i;

            for (i = 0; i < fileName.Length && (fileName.ToCharArray()[i] != 0); i++)
            {
                data[i] = (byte)fileName.ToCharArray()[i];
            }
            data[i] = 0;

            /* add filesize to data */
            int j;

            for (j = 0; j < fileSize.Length && (fileSize.ToCharArray()[j] != 0); j++)
            {
                data[(i + 1) + j] = (byte)fileSize.ToCharArray()[j];
            }
            data[(i + 1) + j] = 0;

            /* fill the remaining data bytes with 0 */
            for (int k = ((i + 1) + j) + 1; k < dataSize; k++)
            {
                data[k] = 0;
            }

            /* calculate CRC */
            Crc16Ccitt crc16Ccitt = new Crc16Ccitt(InitialCrcValue.Zeros);

            CRC = crc16Ccitt.ComputeChecksumBytes(data);

            /* send the packet */
            sendYmodemPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, CRC, crcSize);
        }
Exemplo n.º 9
0
        public static byte[] PrepareMessageToSend(I2CMessageFrame message)
        {
            byte[] mahByteArray = message.ToArray();
            byte[] crcFrame     = new byte[Buffer.ByteLength(mahByteArray) + 2];

            byte[] bFrame = new byte[Buffer.ByteLength(mahByteArray) + 4];
            try
            {
                crcFrame[0] = (byte)Buffer.ByteLength(mahByteArray);
                crcFrame[1] = (byte)1;
                Buffer.BlockCopy(mahByteArray, 0, crcFrame, 2, Buffer.ByteLength(mahByteArray));

                Crc16Ccitt crc     = new Crc16Ccitt(InitialCrcValue.NonZero1);
                var        retByte = crc.ComputeChecksumBytes(crcFrame);
                Buffer.BlockCopy(crcFrame, 0, bFrame, 0, crcFrame.Count());
                Buffer.SetByte(bFrame, Buffer.ByteLength(bFrame) - 1, retByte[1]);
                Buffer.SetByte(bFrame, Buffer.ByteLength(bFrame) - 2, retByte[0]);
            }
            catch (Exception ex)
            {
                LoggerFactory.LogException(ex, "PrepareMessageToSend", new { message });
            }
            return(bFrame);
        }
Exemplo n.º 10
0
        /*
         * Upload file via Ymodem protocol to the device
         * ret: is the transfer succeeded? true is if yes
         */
        public bool YmodemUploadFile(string path)
        {
            /* control signals */
            const byte STX  = 2;  // Start of TeXt
            const byte EOT  = 4;  // End Of Transmission
            const byte ACK  = 6;  // Positive ACknowledgement
            const byte C    = 67; // capital letter C
            const byte NACK = 21; // NACK

            /* sizes */
            const int dataSize = 1024;
            const int crcSize  = 2;

            /* THE PACKET: 1029 bytes */
            /* header: 3 bytes */
            // STX
            int packetNumber         = 0;
            int invertedPacketNumber = 255;

            /* data: 1024 bytes */
            byte[] data = new byte[dataSize];
            /* footer: 2 bytes */
            byte[] CRC = new byte[crcSize];

            /* get the file */
            FileStream fileStream = new FileStream(@path, FileMode.Open, FileAccess.Read);

            try
            {
                {
                    int read_byte;
                    int backup_byte = 9;
                    int count       = _serialPort.BytesToRead;

                    Console.WriteLine("#####Read byte{0}:", count);
                    for (int i = 0; i < count; i++)
                    {
                        read_byte = _serialPort.ReadByte();
                        if (i == 0)
                        {
                            backup_byte = read_byte;
                        }
                        Console.WriteLine("[{0:X}]", read_byte);
                    }
                }

                /* send the initial packet with filename and filesize */
                if (67 != C)
                {
                    Console.WriteLine("Can't begin the transfer.");
                    return(false);
                }

                {
                    byte[] data1 = new byte[128];
                    /* footer: 2 bytes */
                    byte[] CRC1 = new byte[crcSize];

                    sendYmodemInitialPacket(0x01, 0, invertedPacketNumber, data1, 128, path, fileStream, CRC1, crcSize);
                }

                //sendYmodemInitialPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, path, fileStream, CRC, crcSize);

                Thread.Sleep(200);
                // int read_byte;
                // int backup_byte = 9;
                // int count = _serialPort.BytesToRead;
                //
                // Console.WriteLine("#####Read byte{0}:", count);
                // for (int i = 0; i < count; i++)
                // {
                //     read_byte = _serialPort.ReadByte();
                //     if (i == 0)
                //     {
                //         backup_byte = read_byte;
                //     }
                //     Console.WriteLine("[{0:X}]", read_byte);
                // }
                //
                //
                // //if (_serialPort.ReadByte() != ACK)

                if (_serialPort.ReadByte() != ACK)
                {
                    Console.WriteLine("Can't send the initial packet.");
                    return(false);
                }


                if (_serialPort.ReadByte() != C)
                {
                    return(false);
                }

                /* send packets with a cycle until we send the last byte */
                int fileReadCount;
                do
                {
                    /* if this is the last packet fill the remaining bytes with 0 */
                    fileReadCount = fileStream.Read(data, 0, dataSize);
                    if (fileReadCount == 0)
                    {
                        break;
                    }
                    if (fileReadCount != dataSize)
                    {
                        for (int i = fileReadCount; i < dataSize; i++)
                        {
                            data[i] = 0;
                        }
                    }

                    /* calculate packetNumber */
                    packetNumber++;
                    if (packetNumber > 255)
                    {
                        packetNumber -= 256;
                    }
                    Console.WriteLine(packetNumber);

                    /* calculate invertedPacketNumber */
                    invertedPacketNumber = 255 - packetNumber;

                    /* calculate CRC */
                    Crc16Ccitt crc16Ccitt = new Crc16Ccitt(InitialCrcValue.Zeros);
                    CRC = crc16Ccitt.ComputeChecksumBytes(data);

                    /* send the packet */
                    sendYmodemPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, CRC, crcSize);


                    /* wait for ACK */
                    if (_serialPort.ReadByte() != ACK)
                    {
                        Console.WriteLine("Couldn't send a packet.");
                        return(false);
                    }

                    if (transmitCb != null)
                    {
                        transmitCb(packetNumber);
                    }
                } while (dataSize == fileReadCount);

                #region 重构部分
                // /* send EOT (tell the downloader we are finished) */
                // _serialPort.Write(new byte[] { EOT }, 0, 1);
                // /* send closing packet */
                // packetNumber = 0;
                // invertedPacketNumber = 255;
                // data = new byte[dataSize];
                // CRC = new byte[crcSize];
                // sendYmodemClosingPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, CRC, crcSize);
                // /* get ACK (downloader acknowledge the EOT) */
                // if (_serialPort.ReadByte() != ACK)
                // {
                //     Console.WriteLine("Can't complete the transfer.");
                //     return false;
                // }
                #endregion

                /* send EOT (tell the downloader we are finished) */
                _serialPort.Write(new byte[] { EOT }, 0, 1);

                Thread.Sleep(20);
                int back = _serialPort.ReadByte();
                if (back != NACK)
                {
                    Console.WriteLine("Can't get NACK. back ={0}", back);
                }

                _serialPort.Write(new byte[] { EOT }, 0, 1);

                Thread.Sleep(20);
                int back2 = _serialPort.ReadByte();
                if (back2 != ACK)
                {
                    Console.WriteLine("Can't get ACK. back2 ={0}", back2);
                }
                int back3 = _serialPort.ReadByte();

                if (back3 != C)
                {
                    Console.WriteLine("Can't get ACK. back3 ={0}", back3);
                }

                /* send last packet frame */
                byte[] data3 = new byte[128];
                byte[] CRC3  = new byte[crcSize];
                sendYmodemClosingPacket(0x01, 0x00, 0xff, data3, 128, CRC3, crcSize);

                Thread.Sleep(20);
                int back4 = _serialPort.ReadByte();
                if (back4 != ACK)
                {
                    Console.WriteLine("Can't get ACK. back3 ={0}", back4);
                }
            }
            catch (TimeoutException)
            {
                throw new Exception("Eductor does not answering");
            }
            finally
            {
                fileStream.Close();
            }

            Console.WriteLine("File transfer is succesful");
            return(true);
        }
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="offset"></param>
        /// <param name="bytesRead"></param>
        /// <returns></returns>
        public IEnumerable <ExtractedBytes> ExtractMessageBytes(byte[] bytes, int offset, int bytesRead)
        {
            var length = _ReadBufferLength + bytesRead;

            if (_ReadBuffer == null || length > _ReadBuffer.Length)
            {
                var newReadBuffer = new byte[length];
                if (_ReadBuffer != null)
                {
                    _ReadBuffer.CopyTo(newReadBuffer, 0);
                }
                _ReadBuffer = newReadBuffer;
            }
            Array.ConstrainedCopy(bytes, 0, _ReadBuffer, _ReadBufferLength, bytesRead);
            _ReadBufferLength = length;

            int startOfPacket = FindDCEMarker(0, 0x02);

            if (startOfPacket == 0 && !_SeenFirstPacket)
            {
                startOfPacket = FindDCEMarker(1, 0x02);
            }

            int firstByteAfterLastValidPacket = -1;

            while (startOfPacket != -1)
            {
                var endOfPacket = FindDCEMarker(startOfPacket + 2, 0x03);
                if (endOfPacket == -1)
                {
                    break;
                }

                int lengthOfChecksum;
                var packetChecksum = ReadChecksum(endOfPacket, out lengthOfChecksum);
                if (packetChecksum == null)
                {
                    break;
                }

                _SeenFirstPacket = true;
                firstByteAfterLastValidPacket = endOfPacket + 2 + lengthOfChecksum;

                var transponderDataLength = 0;
                switch (_ReadBuffer[startOfPacket + 2])
                {
                case 0x01:
                case 0x05:  transponderDataLength = 14; break;

                case 0x07:  transponderDataLength = 7; break;
                }

                if (transponderDataLength != 0)
                {
                    var dataLength = (endOfPacket - startOfPacket) - 2;
                    if (_Payload == null || _Payload.Length < dataLength)
                    {
                        _Payload = new byte[dataLength];
                    }

                    int payloadIndex = 0;
                    for (int i = startOfPacket + 2; i < endOfPacket; ++i)
                    {
                        var b = _ReadBuffer[i];
                        _Payload[payloadIndex++] = b != 0x10 ? b : _ReadBuffer[++i];
                    }
                    if (payloadIndex >= transponderDataLength + 5)    // first 5 bytes are packet type / unused / 3-byte rolling timestamp - latter 4 can be DCE stuffed so we can't skip them earlier than this
                    {
                        var calculatedChecksum = _ChecksumCalculator.ComputeChecksumBytes(_Payload, 0, payloadIndex, false);

                        _ExtractedBytes.Bytes = _Payload;
                        if (calculatedChecksum[0] != packetChecksum[0] || calculatedChecksum[1] != packetChecksum[1])
                        {
                            _ExtractedBytes.ChecksumFailed = true;
                            _ExtractedBytes.Length         = _Payload.Length;
                        }
                        else
                        {
                            _ExtractedBytes.ChecksumFailed = false;
                            _ExtractedBytes.Offset         = 5;
                            _ExtractedBytes.Length         = transponderDataLength;
                        }

                        yield return(_ExtractedBytes);
                    }
                }

                startOfPacket = FindDCEMarker(firstByteAfterLastValidPacket, 0x02);
            }

            if (firstByteAfterLastValidPacket != -1)
            {
                var unusedBytesCount = _ReadBufferLength - firstByteAfterLastValidPacket;
                if (unusedBytesCount > 0)
                {
                    if (unusedBytesCount > 0x2800)
                    {
                        // We don't want the read buffer growing out of control when reading a source that doesn't contain
                        // anything that looks like valid messages. I'm not sure how large some of the other packet types
                        // from SBS-3s are going to be so for now I'm allowing a very generous buffer size.
                        unusedBytesCount = 0;
                    }
                    else
                    {
                        for (int si = firstByteAfterLastValidPacket, di = 0; di < unusedBytesCount; ++si, ++di)
                        {
                            _ReadBuffer[di] = _ReadBuffer[si];
                        }
                    }
                }
                _ReadBufferLength = unusedBytesCount;
            }
        }
Exemplo n.º 12
0
        public static ProtocolFrame AnalyzeQueue(ref Queue <byte> queue)
        {
            Crc16Ccitt            crc    = new Crc16Ccitt(InitialCrcValue.Zeros);
            ProtocolFramePosition state  = ProtocolFramePosition.Start;
            ProtocolFrame         result = null;

            byte[]      temp_tel = queue.ToArray();
            byte        b;
            int         start_pos = 0;
            int         number_of_bytes_to_remove = 0;
            byte        source_address = 0, destination_address = 0, code = 0;
            byte        command             = 0;
            UInt16      length_data         = 0;
            int         number_of_bytes_to_read = 0;
            List <byte> data                = new List <byte>();
            UInt16      crcValue            = 0;
            bool        first_checksum_byte = false;


            for (int i = 0; i < temp_tel.Length; i++)
            {
                b = temp_tel[i];

                switch (state)
                {
                case ProtocolFramePosition.Start:
                    if (b == StartByte)
                    {
                        start_pos = i;
                        state     = ProtocolFramePosition.Length;
                    }
                    break;

                case ProtocolFramePosition.Length:

                    if ((i - start_pos) == 1)
                    {
                        length_data = b;
                    }
                    else
                    {
                        length_data += (UInt16)(b << 8);

                        if (length_data >= 4 && length_data <= 200)
                        {
                            state = ProtocolFramePosition.Address_and_Code;
                            number_of_bytes_to_read = length_data - 4;
                        }
                        else
                        {
                            number_of_bytes_to_remove = i + 1;
                            i = temp_tel.Length;
                        }
                    }
                    break;

                case ProtocolFramePosition.Address_and_Code:

                    source_address      = (byte)((b >> 5) & 0x07);
                    destination_address = (byte)((b >> 2) & 0x07);
                    code = (byte)(b & 0x03);

                    if (destination_address == m_my_address)
                    {
                        state = ProtocolFramePosition.Command;
                    }
                    else
                    {
                        number_of_bytes_to_remove = i + 1;
                        i = temp_tel.Length;
                    }
                    break;

                case ProtocolFramePosition.Command:

                    command = b;

                    if (length_data > 4)
                    {
                        state = ProtocolFramePosition.Data;
                    }
                    else
                    {
                        state = ProtocolFramePosition.Checksum;
                    }
                    break;

                case ProtocolFramePosition.Data:

                    data.Add(b);
                    number_of_bytes_to_read--;

                    if (number_of_bytes_to_read == 0)
                    {
                        state = ProtocolFramePosition.Checksum;
                    }
                    break;

                case ProtocolFramePosition.Checksum:

                    if (first_checksum_byte == false)
                    {
                        first_checksum_byte = true;
                        crcValue            = b;
                    }
                    else
                    {
                        crcValue += (UInt16)(b << 8);

                        byte[] crc_v = crc.ComputeChecksumBytes(temp_tel, 0, i - 1);

                        if (crcValue == (UInt16)BitConverter.ToInt16(crc_v, 0))
                        {
                            //consider code info
                            result = new ProtocolFrame(source_address, destination_address, command, code, data.ToArray());
                            //Checksumme ok
                            //todo
                        }
                        else
                        {
                            //Checksumme nicht ok
                            //todo
                        }
                        number_of_bytes_to_remove = i + 1;
                    }
                    break;
                }


                while (number_of_bytes_to_remove > 0)
                {
                    number_of_bytes_to_remove--;
                    queue.Dequeue();
                }
            }

            return(result);
        }
Exemplo n.º 13
0
        private void sendYmodemInitialPacket(byte STX, int packetNumber, int invertedPacketNumber, byte[] data, int dataSize, string path, FileStream fileStream, byte[] CRC, int crcSize)
        {
            string fileName = System.IO.Path.GetFileName(path);
            string fileSize = fileStream.Length.ToString();

            /* add filename to data */
            int i;
            for (i = 0; i < fileName.Length && (fileName.ToCharArray()[i] != 0); i++)
            {
                data[i] = (byte)fileName.ToCharArray()[i];
            }
            data[i] = 0;

            /* add filesize to data */
            int j;
            for (j = 0; j < fileSize.Length && (fileSize.ToCharArray()[j] != 0); j++)
            {
                data[(i + 1) + j] = (byte)fileSize.ToCharArray()[j];
            }
            data[(i + 1) + j] = 0;

            /* fill the remaining data bytes with 0 */
            for (int k = ((i + 1) + j) + 1; k < dataSize; k++)
            {
                data[k] = 0;
            }

            /* calculate CRC */
            Crc16Ccitt crc16Ccitt = new Crc16Ccitt(InitialCrcValue.Zeros);
            CRC = crc16Ccitt.ComputeChecksumBytes(data);

            /* send the packet */
            sendYmodemPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, CRC, crcSize);
        }
Exemplo n.º 14
0
        private void sendYmodemClosingPacket(byte STX, int packetNumber, int invertedPacketNumber, byte[] data, int dataSize, byte[] CRC, int crcSize)
        {
            /* calculate CRC */
            Crc16Ccitt crc16Ccitt = new Crc16Ccitt(InitialCrcValue.Zeros);
            CRC = crc16Ccitt.ComputeChecksumBytes(data);

            /* send the packet */
            sendYmodemPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, CRC, crcSize);
        }
Exemplo n.º 15
0
        /*
         * Upload file via Ymodem protocol to the device
         * ret: is the transfer succeeded? true is if yes
         */
        public bool YmodemUploadFile(string path)
        {
            /* control signals */
            const byte STX = 2;  // Start of TeXt
            const byte EOT = 4;  // End Of Transmission
            const byte ACK = 6;  // Positive ACknowledgement
            const byte C = 67;   // capital letter C

            /* sizes */
            const int dataSize = 1024;
            const int crcSize = 2;

            /* THE PACKET: 1029 bytes */
            /* header: 3 bytes */
            // STX
            int packetNumber = 0;
            int invertedPacketNumber = 255;
            /* data: 1024 bytes */
            byte[] data = new byte[dataSize];
            /* footer: 2 bytes */
            byte[] CRC = new byte[crcSize];

            /* get the file */
            FileStream fileStream = new FileStream(@path, FileMode.Open, FileAccess.Read);
            long totalFileSize = fileStream.Length;
            double currentdata = 0;
            Console.WriteLine(totalFileSize);
            OnProgressChanged((int)((currentdata / totalFileSize) * 100));
            try
            {
                /* send the initial packet with filename and filesize */
                if (serialPort.ReadByte() != C)
                {
                    Console.WriteLine("Can't begin the transfer.");
                    return false;
                }

                sendYmodemInitialPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, path, fileStream, CRC, crcSize);
                if (serialPort.ReadByte() != ACK)
                {
                    Console.WriteLine("Can't send the initial packet.");
                    return false;
                }

                if (serialPort.ReadByte() != C)
                    return false;

                /* send packets with a cycle until we send the last byte */
                int fileReadCount;
                do
                {
                    /* if this is the last packet fill the remaining bytes with 0 */
                    fileReadCount = fileStream.Read(data, 0, dataSize);
                    if (fileReadCount == 0) break;
                    if (fileReadCount != dataSize)
                        for (int i = fileReadCount; i < dataSize; i++)
                            data[i] = 0;

                    /* calculate packetNumber */
                    packetNumber++;
                    if (packetNumber > 255)
                        packetNumber -= 256;
                    Console.WriteLine(packetNumber);

                    /* calculate invertedPacketNumber */
                    invertedPacketNumber = 255 - packetNumber;

                    /* calculate CRC */
                    Crc16Ccitt crc16Ccitt = new Crc16Ccitt(InitialCrcValue.Zeros);
                    CRC = crc16Ccitt.ComputeChecksumBytes(data);

                    /* send the packet */
                    sendYmodemPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, CRC, crcSize);
                    /* wait for ACK */
                    //is this necessary - no ACK>?!?!?!?!
                    /*
                    if (serialPort.ReadByte() != ACK)
                    {
                        Console.WriteLine("Couldn't send a packet.");
                        return false;
                    }
                     * */

                    //update how much data was sent
                    currentdata = currentdata + dataSize;

                    OnProgressChanged((int)((currentdata / totalFileSize) * 100));
                    Console.WriteLine("currentdata");
                    Console.WriteLine(currentdata);
                    Console.WriteLine("totalFilesize");
                    Console.WriteLine(totalFileSize);
                    Console.WriteLine("percent");
                    Console.WriteLine((currentdata / totalFileSize));
                } while (dataSize == fileReadCount);

                /* send EOT (tell the downloader we are finished) */
                serialPort.Write(new byte[] { EOT }, 0, 1);
                /* send closing packet */
                packetNumber = 0;
                invertedPacketNumber = 255;
                data = new byte[dataSize];
                CRC = new byte[crcSize];
                sendYmodemClosingPacket(STX, packetNumber, invertedPacketNumber, data, dataSize, CRC, crcSize);
                /* get ACK (downloader acknowledge the EOT) */
                if (serialPort.ReadByte() != ACK)
                {
                    Console.WriteLine("Can't complete the transfer.");
                    return false;
                }
            }
            catch (TimeoutException)
            {
                Console.WriteLine("No Answer - Aborting Transfer");
            }
            finally
            {
                fileStream.Close();
            }

            Console.WriteLine("End transfer Session");

            return true;
        }