Пример #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];
        }
Пример #2
0
        protected static ArraySegment <byte> GetCheckedRestoreData(string hashHexString)
        {
            if (string.IsNullOrWhiteSpace(hashHexString))
            {
                throw new ArgumentException(nameof(hashHexString));
            }

            var data = Hex.FromString(hashHexString);

            var crc = (ushort)(data[data.Length - 2] | data[data.Length - 1] << 8);

            if (!BitConverter.IsLittleEndian)
            {
                crc = (ushort)(data[data.Length - 1] | data[data.Length - 2] << 8);
            }

            var dataSegment = new ArraySegment <byte>(data, 0, data.Length - 2);
            var segmentCrc  = Crc16Ccitt.Compute(dataSegment);

            if (segmentCrc != crc)
            {
                throw new ArgumentException("Cr16 check failed", nameof(hashHexString));
            }

            return(dataSegment);
        }
Пример #3
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);
        }
Пример #4
0
 /// <summary>
 /// Create instance of <see cref="Device" />
 /// </summary>
 /// <param name="description">Description of device</param>
 /// <param name="speed">BaudRate</param>
 /// <param name="readTimeout">Read timeout</param>
 /// <param name="writeTimeout">Write timeout</param>
 public Device(string description, uint speed, uint readTimeout, uint writeTimeout)
 {
     _crc16Ccitt = new Crc16Ccitt(Crc16Ccitt.InitialCrcValue.NonZero1);
     _description = description;
     _speed = speed;
     _readTimeout = readTimeout;
     _writeTimeout = writeTimeout;
     _myFtdiDevice = DriverFactory.GetDriver();
 }
Пример #5
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);
        }
        public byte[] GetBytes()
        {
            byte[] buffer = new byte[1 + Data.Length + 2];
            buffer[0] = (byte)Command;
            ByteWriter.WriteBytes(buffer, 1, Data);
            ushort crc16 = Crc16Ccitt.ComputeChecksum(buffer, 1 + Data.Length);

            LittleEndianWriter.WriteUInt16(buffer, 1 + Data.Length, crc16);
            return(buffer);
        }
Пример #7
0
        public void CalculateCrc()
        {
            var data        = new byte[] { 0xa1, 0xa1, 0xa1, 0xfe, 0x14, 0x00, 0x09, 0x01 };
            var crcExpected = (uint)0xa2f3;

            var crc       = new Crc16Ccitt();
            var crcActual = crc.Add(data);

            Assert.Equal(crcExpected, crcActual);
        }
Пример #8
0
        public void ComputeChecksumTest6()
        {
            Crc16Ccitt target = new Crc16Ccitt(InitialCrcValue.Zeros);

            byte[] bytes    = new byte[] { 0xCA, 0xFE, 0xBA, 0xBE, 0x94, 0x8F };
            ushort expected = 0;
            ushort actual;

            actual = target.ComputeChecksum(bytes);
            Assert.AreEqual(expected, actual);
        }
Пример #9
0
        public void ComputeChecksumTest3()
        {
            Crc16Ccitt target = new Crc16Ccitt(InitialCrcValue.Zeros);

            byte[] bytes    = new byte[] { 0x00, 0x00, 0x00, 0x42 };
            ushort expected = 0x6886;
            ushort actual;

            actual = target.ComputeChecksum(bytes);
            Assert.AreEqual(expected, actual);
        }
Пример #10
0
        public void ComputeChecksumTest7()
        {
            Crc16Ccitt target = new Crc16Ccitt(InitialCrcValue.Zeros);

            byte[] bytes = new byte[10000];
            for (int i = 0; i < 10000; i++)
            {
                bytes[i] = (byte)i;
            }
            ushort expected = 0x5885;
            ushort actual;

            actual = target.ComputeChecksum(bytes);
            Assert.AreEqual(expected, actual);
        }
Пример #11
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);
        }
Пример #13
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);
        }
Пример #14
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
                });
            }
        }
Пример #15
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);
        }
Пример #16
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);
        }
Пример #17
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;
        }
Пример #18
0
        public int read(byte data)
        {
            switch (state)
            {
            default:
            case 0:
                if (data == 0x55)
                {
                    state++;
                    msg           = new piksimsg();
                    msg.preamble  = data;
                    msg.buffer[0] = data;
                    crc           = new Crc16Ccitt(InitialCrcValue.Zeros);
                    crcpacket     = (ushort)InitialCrcValue.Zeros;
                }
                break;

            case 1:
                msg.msg_type  = (u16)(data);
                msg.buffer[1] = data;
                crcpacket     = crc.Accumulate(data, crcpacket);
                state++;
                break;

            case 2:
                msg.msg_type  = (u16)(msg.msg_type + (data << 8));
                msg.buffer[2] = data;
                crcpacket     = crc.Accumulate(data, crcpacket);
                state++;
                break;

            case 3:
                msg.sender    = (u16)(data);
                msg.buffer[3] = data;
                crcpacket     = crc.Accumulate(data, crcpacket);
                state++;
                break;

            case 4:
                msg.sender    = (u16)(msg.sender + (data << 8));
                msg.buffer[4] = data;
                crcpacket     = crc.Accumulate(data, crcpacket);
                state++;
                break;

            case 5:
                msg.length    = data;
                msg.buffer[5] = data;
                crcpacket     = crc.Accumulate(data, crcpacket);
                msg.payload   = new u8[msg.length];
                Array.Resize(ref msg.buffer, 8 + data);
                lengthcount = 0;
                state++;
                break;

            case 6:
                if (lengthcount == msg.length)
                {
                    state++;
                    goto case 7;
                }
                else
                {
                    msg.payload[lengthcount]    = data;
                    msg.buffer[6 + lengthcount] = data;
                    crcpacket = crc.Accumulate(data, crcpacket);
                    lengthcount++;
                }
                break;

            case 7:
                msg.crc = (u16)(data);
                msg.buffer[6 + lengthcount] = data;
                state++;
                break;

            case 8:
                msg.crc = (u16)(msg.crc + (data << 8));
                msg.buffer[7 + lengthcount] = data;
                state = 0;

                if (msg.crc == crcpacket)
                {
                    return(msg.msg_type);
                }
                break;
            }

            return(-1);
        }
Пример #19
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);
        }
Пример #20
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);
        }
Пример #21
0
        /// <summary>
        /// Xu ly goi dư lieu nhan duoc tu Client va luu vao database
        /// </summary>
        /// <param name="data"></param>
        private void HandlePackage(string data)
        {
            // Checksum
            Crc16Ccitt crc = new Crc16Ccitt(InitialCrcValue.NonZero1);

            // Checksum sai van luu
            if (!crc.CheckChecksum(data))
            {
                #region Split & Save Data
                try
                {
                    string[] dataArray = data.Split('&');
                    DateTime dateTime  = DateTime.Now;

                    // &I
                    string[] stringI = dataArray[1].Trim().Substring(2).Split(';');
                    string   idcard  = stringI[0].Trim();
                    string   serial  = stringI[1].Trim();
                    I_Data   i_Data  = new I_Data(serial, idcard, dateTime);

                    // &G
                    string[] stringG        = dataArray[2].Trim().Substring(2).Split(';');
                    string   status         = stringG[0].Trim();
                    string   vido           = stringG[1].Trim();
                    string   kinhdo         = stringG[2].Trim();
                    string   vantocgps      = stringG[3].Trim();
                    string   khoangcachgps  = stringG[4].Trim();
                    string   tongkhoangcach = stringG[5].Trim();
                    bool     _status        = status.Equals("1") ? true : false;
                    G_Data   g_Data         = new G_Data(serial, _status, vido, kinhdo, float.Parse(vantocgps), Convert.ToInt64(khoangcachgps), Convert.ToInt64(tongkhoangcach), dateTime);

                    // &S1
                    string[] stringS1   = dataArray[3].Trim().Substring(3).Split(';');
                    string   trangthai  = stringS1[0].Trim();
                    string   dienapbinh = stringS1[1].Trim();
                    string   dienappin  = stringS1[2].Trim();
                    string   cuongdoGSM = stringS1[3].Trim();
                    string   loithenho  = stringS1[4].Trim();
                    S1_Data  s1_Data    = new S1_Data(serial, Convert.ToByte(trangthai), float.Parse(dienapbinh), float.Parse(dienappin), float.Parse(cuongdoGSM), loithenho, dateTime);


                    // &D
                    string[] stringD  = dataArray[4].Trim().Substring(2).Split(';');
                    string   cuocxe   = stringD[0].Trim();
                    string   thoigian = stringD[1].Trim();
                    D_Data   d_Data   = new D_Data(serial, cuocxe, Convert.ToInt32(thoigian), dateTime);

                    // &H1
                    H1_Data h1_Data = null;
                    if (data.IndexOf("&H1") != -1)
                    {
                        string[] stringH1      = dataArray[5].Trim().Substring(3).Split(';');
                        string   maUID         = stringH1[0].Trim();
                        string   giaypheplaixe = stringH1[1].Trim();
                        string   vantocxe      = stringH1[2].Trim();
                        h1_Data = new H1_Data(serial, maUID, giaypheplaixe, float.Parse(vantocxe), dateTime);
                    }

                    // &CT
                    CT_Data cT_Data = null;
                    if (data.IndexOf("&CT") != -1)
                    {
                        string[] stringCT = dataArray[6].Trim().Substring(3).Split(';');
                        string   from     = stringCT[0].Trim();
                        string   sdt      = stringCT[1].Trim();
                        string   malenh   = stringCT[2].Trim();
                        string   _malenh  = malenh.Substring(malenh.Length - 1);
                        //string okerror = stringCT[3].Trim();
                        cT_Data = new CT_Data(serial, from, sdt, Convert.ToInt32(_malenh), dateTime);
                    }

                    // Save Rawdata
                    SaveRawData(data, serial);

                    // Split data and Save
                    SaveSplittedData(i_Data, g_Data, s1_Data, d_Data, h1_Data, cT_Data);
                }
                catch (Exception e)
                {
                    log.Error("Data Wrong format", e);
                }

                #endregion
            }
        }
Пример #22
0
        private void encryptBinFile_Click(object sender, EventArgs e)
        {
            var fileArray = File.ReadAllBytes(fileNameTextBox.Text);

            Crc16Ccitt c        = new Crc16Ccitt(InitialCrcValue.NonZero1);
            ushort     crcValue = c.ComputeChecksum(fileArray);

            outputTextBox.AppendText(String.Format("Calculated CRC: 0x{0:X}\r\n", crcValue));
            outputTextBox.AppendText(String.Format("Calculated CRC: 0d{0}\r\n", crcValue));

            int totalNumberOfPackets = (fileArray.Length / 32);

            if (fileArray.Length % 32 != 0)
            {
                totalNumberOfPackets++;
            }
            byte[] encryptedArray      = new byte[fileArray.Length];
            byte[] aplitEncryptedArray = new byte[fileArray.Length];

            byte[] key = { 0x30, 0xAB, 0xC2, 0x12, 0x09, 0xCE, 0x56, 0x9A, 0xF8, 0x81, 0xD4,     0xA9
                           ,     0x05, 0x67, 0x5E, 0x6F, 0x79, 0x3F, 0x96, 0xC9, 0x11, 0x2F, 0x37, 0x1C, 0x60, 0xE3, 0x04, 0x7E
                           ,     0xB6, 0x93, 0x70, 0xEF, 0x4A, 0x45, 0x02, 0x6A, 0x97, 0x12, 0x27, 0x42, 0xEC, 0x51, 0x55, 0x70
                           ,     0x00, 0xCB, 0xA8, 0x61, 0x22, 0xE1, 0xF1, 0x78, 0x53, 0x18, 0xF8, 0xDA, 0xC9, 0x40, 0x08, 0x5D
                           ,     0x3F, 0x96, 0x09, 0xC5, 0x9B, 0x08, 0x34, 0xBD, 0x9C, 0xFA, 0x9F, 0x1D, 0x5F, 0x61, 0x77, 0xA0
                           ,     0x16, 0xC5, 0xB1, 0x76, 0x00, 0xF7, 0x97, 0x9A, 0x04, 0x09, 0x95, 0x8C, 0x44, 0x5A, 0xF3, 0x1E
                           ,     0xCE, 0x96, 0x24, 0xF7, 0xE1, 0x2B, 0x20, 0x5A, 0x67, 0x89, 0xEa, 0x6C, 0xBA, 0x73, 0x0B, 0x19
                           ,     0xE6, 0xA3, 0xCD, 0xFC, 0xA1, 0xAD, 0x7E, 0x65, 0x67, 0x0C, 0x9B, 0x48, 0x5E, 0x6A, 0x53, 0xBD
                           ,     0xBB, 0x22, 0xBC, 0x85, 0x17, 0x85, 0x2A, 0x07, 0x9A, 0xC0, 0x18, 0xB6, 0xEF, 0x90, 0x3C, 0x0E
                           ,     0x8E, 0x19, 0x5E, 0xA1, 0xE0, 0x06, 0x18, 0xD0, 0x56, 0x36, 0x30, 0xA0, 0xA8, 0x60, 0x77, 0x31
                           ,     0x4C, 0xDA, 0x3B, 0x5E, 0x75, 0x9C, 0xD5, 0xB6, 0x97, 0x59, 0x56, 0x47, 0xF8, 0xEB, 0x40, 0xF9
                           ,     0x99, 0x2F, 0xFB, 0xFA, 0xFE, 0x88, 0xF3, 0x49, 0xD2, 0xC7, 0xD6, 0x54, 0x6A, 0xBB, 0x02, 0x52
                           ,     0xCB, 0xC1, 0xCA, 0xA1, 0x23, 0x6D, 0x7F, 0xC9, 0x4F, 0x6B, 0xDE, 0x2E, 0xF3, 0xB5, 0x4A, 0x30
                           ,     0x46, 0xE5, 0x08, 0xB9, 0xCD, 0x1F, 0x07, 0x12, 0x89, 0x04, 0xD3, 0x03, 0x72, 0x96, 0x50, 0x0D
                           ,     0xF3, 0xB9, 0xB1, 0xD6, 0xAE, 0xF9, 0xB4, 0x3A, 0x95, 0x78, 0xCE, 0x7D, 0xA4, 0xA0, 0x55, 0x4C
                           ,     0xDF, 0xC2, 0x5C, 0x5A, 0x79, 0x91, 0xD8, 0x4D, 0xC8, 0x62, 0x8E, 0x8D, 0xA0, 0xED, 0xF0, 0xE6
                           ,     0xED, 0x59, 0x63, 0xE2 };

            uint Counter = 0;
            int  Rotator = fileArray.Length % 8;

            if (Rotator.Equals(0))
            {
                Rotator = (fileArray.Length + 1) % 5;
            }
            if (Rotator.Equals(0))
            {
                Rotator = 4;
            }

            outputTextBox.AppendText(String.Format("File size in bytes: {0}\r\n", fileArray.Length));
            outputTextBox.AppendText(String.Format("Calculated Rotator: {0}\r\n", Rotator));

            for (int i = 0; i < fileArray.Length; i++)
            {
                byte firstLeftRotation = lrotate(fileArray[i], Rotator);
                byte afterKey          = (byte)(firstLeftRotation ^ key[Counter]);
                byte secondLeftRotate  = lrotate(afterKey, 8 - Rotator);

                byte firstLeftRotationAplit = lrotate(fileArray[i], 3);
                byte afterKeyAplit          = (byte)(firstLeftRotationAplit ^ key[Counter]);
                byte secondLeftRotateAplit  = lrotate(afterKeyAplit, 5);

                Counter++;
                encryptedArray[i]      = secondLeftRotate;
                aplitEncryptedArray[i] = secondLeftRotateAplit;
                if (Counter > 255)
                {
                    Counter = 0;
                }
            }
            File.WriteAllBytes(fileNameTextBox.Text.Replace(shortFileName, "Encrypted" + shortFileName), encryptedArray);
            File.WriteAllBytes(fileNameTextBox.Text.Replace(shortFileName, "AplitEncrypted" + shortFileName), aplitEncryptedArray);
        }
Пример #23
0
        public int read(byte data)
        {
            switch (state)
            {
                case 0:
                    if (data == 0x55)
                    {
                        state++;
                        msg = new piksimsg();
                        msg.preamble = data;
                        crc = new Crc16Ccitt(InitialCrcValue.Zeros);
                        crcpacket = (ushort)InitialCrcValue.Zeros;
                    }
                    break;
                case 1:
                    msg.msg_type = (u16)(data);
                    crcpacket = crc.Accumulate(data, crcpacket);
                    state++;
                    break;
                case 2:
                    msg.msg_type = (u16)(msg.msg_type + (data << 8));
                    crcpacket = crc.Accumulate(data, crcpacket);
                    state++;
                    break;
                case 3:
                    msg.sender = (u16)(data);
                    crcpacket = crc.Accumulate(data, crcpacket);
                    state++;
                    break;
                case 4:
                    msg.sender = (u16)(msg.sender + (data << 8));
                    crcpacket = crc.Accumulate(data, crcpacket);
                    state++;
                    break;
                case 5:
                    msg.length = data;
                    crcpacket = crc.Accumulate(data, crcpacket);
                    msg.payload = new u8[msg.length];
                    length = 0;
                    state++;
                    break;
                case 6:
                    if (length == msg.length)
                    {
                        state++;
                        goto case 7;
                    }
                    else
                    {
                        msg.payload[length] = data;
                        crcpacket = crc.Accumulate(data, crcpacket);
                        length++;
                    }
                    break;
                case 7:
                    msg.crc = (u16)(data);
                    state++;
                    break;
                case 8:
                    msg.crc = (u16)(msg.crc + (data << 8));
                    state = 0;

                    if (msg.crc == crcpacket)
                    {
                        return msg.msg_type;
                    }
                    break;
            }

            return -1;
        }
Пример #24
0
        //发给移动站数据
        void rtcm_ObsMessage(object sender, EventArgs e)
        {
            List <RTCM3.ob> msg = (List <RTCM3.ob>)sender;

            if (msg.Count == 0)
            {
                return;
            }

            byte total = 1;
            byte count = 0;

            piksi.observation_header_t head = new piksi.observation_header_t();
            head.t.wn  = (ushort)(msg[0].week);
            head.t.tow = (uint)((msg[0].tow * piksi.MSG_OBS_TOW_MULTIPLIER));


            double soln_freq          = 10;
            double obs_output_divisor = 2;

            double epoch_count = (head.t.tow / piksi.MSG_OBS_TOW_MULTIPLIER) * (soln_freq / obs_output_divisor);

            double checkleft = Math.Abs(epoch_count - Math.Round(epoch_count));

            Console.WriteLine(head.t.tow + " " + checkleft.ToString("0.000") + " " + epoch_count.ToString("0.000") + " " + Math.Round(epoch_count) + " > " + 1e-3);


            // rounding - should not need this, but testing against a ublox requires some "lieing"
            //head.t.tow = (uint)(Math.Round((decimal)(head.t.tow / 1000.0)) * (decimal)1000.0);

            List <piksi.packed_obs_content_t> obs = new List <piksi.packed_obs_content_t>();

            foreach (var item in msg)
            {
                item.cp *= -1;

                piksi.packed_obs_content_t ob = new piksi.packed_obs_content_t();
                ob.sid = (byte)(item.prn - 1);
                ob.P   = (uint)(item.pr * piksi.MSG_OBS_P_MULTIPLIER);
                ob.L.i = (int)item.cp;
                ob.L.f = (byte)((item.cp - ob.L.i) * 256.0);
                ob.cn0 = (byte)(item.snr * piksi.MSG_OBS_SNR_MULTIPLIER);

                obs.Add(ob);
            }

            head.n_obs = (byte)((total << piksi.MSG_OBS_HEADER_SEQ_SHIFT) | (count & piksi.MSG_OBS_HEADER_SEQ_MASK));

            //create piksi packet

            piksi.piksimsg msgpreamble = new piksi.piksimsg();

            int lenpre = Marshal.SizeOf(msgpreamble) - 1; // 8
            int lenhdr = Marshal.SizeOf(head);
            int lenobs = Marshal.SizeOf(new piksi.packed_obs_content_t());

            byte[] allbytes = new byte[lenpre + lenhdr + lenobs * obs.Count];

            msgpreamble.crc      = 0x1234;
            msgpreamble.preamble = 0x55;
            msgpreamble.msg_type = (ushort)piksi.MSG.SBP_MSG_OBS;
            msgpreamble.sender   = 1;
            msgpreamble.length   = (byte)(obs.Count * lenobs + lenhdr);
            msgpreamble.payloads = new byte[msgpreamble.length];

            int payloadcount = (lenpre - 2) + lenhdr; // exclude checksum

            foreach (var ob in obs)
            {
                byte[] obbytes = StaticUtils.StructureToByteArray(ob);
                Array.Copy(obbytes, 0, allbytes, payloadcount, obbytes.Length);
                payloadcount += lenobs;
            }

            byte[] preamblebytes = StaticUtils.StructureToByteArray(msgpreamble);

            Array.Copy(preamblebytes, 0, allbytes, 0, preamblebytes.Length - 2);

            byte[] headbytes = StaticUtils.StructureToByteArray(head);

            Array.Copy(headbytes, 0, allbytes, lenpre - 2, headbytes.Length);

            Crc16Ccitt crc       = new Crc16Ccitt(InitialCrcValue.Zeros);
            ushort     crcpacket = 0;

            for (int i = 1; i < (allbytes.Length - 2); i++)
            {
                crcpacket = crc.Accumulate(allbytes[i], crcpacket);
            }

            allbytes[allbytes.Length - 2] = (byte)(crcpacket & 0xff);
            allbytes[allbytes.Length - 1] = (byte)((crcpacket >> 8) & 0xff);


            //Console.WriteLine();

            //deststream.Write(allbytes, 0, allbytes.Length);

            GCSMainForm.comPort.InjectGpsData(allbytes, (byte)Math.Min(allbytes.Length, 110));// (byte)allbytes.Length);
        }
 private static string getStatusMessage(string mac)
 {
     string output = "";
     Crc16Ccitt crc = new Crc16Ccitt(InitialCrcValue.Zeros);
     string crcValue = crc.ComputeChecksumString("0023" + mac);
     output = PlugwiseSerialPortFactory.GetStart() + "0023" + mac + crcValue + PlugwiseSerialPortFactory.GetEnd();
     return output;
 }
Пример #26
0
        public int read(byte data)
        {
            switch (state)
            {
            case 0:
                if (data == 0x55)
                {
                    state++;
                    msg          = new piksimsg();
                    msg.preamble = data;
                    crc          = new Crc16Ccitt(InitialCrcValue.Zeros);
                    crcpacket    = (ushort)InitialCrcValue.Zeros;
                }
                break;

            case 1:
                msg.msg_type = (u16)(data);
                crcpacket    = crc.Accumulate(data, crcpacket);
                state++;
                break;

            case 2:
                msg.msg_type = (u16)(msg.msg_type + (data << 8));
                crcpacket    = crc.Accumulate(data, crcpacket);
                state++;
                break;

            case 3:
                msg.sender = (u16)(data);
                crcpacket  = crc.Accumulate(data, crcpacket);
                state++;
                break;

            case 4:
                msg.sender = (u16)(msg.sender + (data << 8));
                crcpacket  = crc.Accumulate(data, crcpacket);
                state++;
                break;

            case 5:
                msg.length  = data;
                crcpacket   = crc.Accumulate(data, crcpacket);
                msg.payload = new u8[msg.length];
                length      = 0;
                state++;
                break;

            case 6:
                if (length == msg.length)
                {
                    state++;
                    goto case 7;
                }
                else
                {
                    msg.payload[length] = data;
                    crcpacket           = crc.Accumulate(data, crcpacket);
                    length++;
                }
                break;

            case 7:
                msg.crc = (u16)(data);
                state++;
                break;

            case 8:
                msg.crc = (u16)(msg.crc + (data << 8));
                state   = 0;

                if (msg.crc == crcpacket)
                {
                    return(msg.msg_type);
                }
                break;
            }

            return(-1);
        }
Пример #27
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);
        }
Пример #28
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);
        }
Пример #29
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            //Test if version of DLL is compatible : 3rd argument is "version of DLL tested;Your application name;Your application version"
            String ToDisplay;
            MediaInfo MI = new MediaInfo();

            ToDisplay = MI.Option("Info_Version", "0.7.0.0;MediaInfoDLL_Example_CS;0.7.0.0");
            if (ToDisplay.Length == 0)
            {
                richTextBox1.Text = "MediaInfo.Dll: this version of the DLL is not compatible";
                return;
            }

            //Information about MediaInfo
            ToDisplay += "\r\n\r\nInfo_Parameters\r\n";
            ToDisplay += MI.Option("Info_Parameters");

            ToDisplay += "\r\n\r\nInfo_Capacities\r\n";
            ToDisplay += MI.Option("Info_Capacities");

            ToDisplay += "\r\n\r\nInfo_Codecs\r\n";
            ToDisplay += MI.Option("Info_Codecs");

            //An example of how to use the library
            ToDisplay += "\r\n\r\nOpen\r\n";
            MI.Open("Example.ogg");

            ToDisplay += "\r\n\r\nInform with Complete=false\r\n";
            MI.Option("Complete");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nInform with Complete=true\r\n";
            MI.Option("Complete", "1");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nCustom Inform\r\n";
            MI.Option("Inform", "General;File size is %FileSize% bytes");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='FileSize'\r\n";
            ToDisplay += MI.Get(0, 0, "FileSize");

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter=46\r\n";
            ToDisplay += MI.Get(0, 0, 46);

            ToDisplay += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n";
            ToDisplay += MI.Count_Get(StreamKind.Audio);

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n";
            ToDisplay += MI.Get(StreamKind.General, 0, "AudioCount");

            ToDisplay += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n";
            ToDisplay += MI.Get(StreamKind.Audio, 0, "StreamCount");

            ToDisplay += "\r\n\r\nClose\r\n";
            MI.Close();

            //Example with a stream
            //ToDisplay+="\r\n"+ExampleWithStream()+"\r\n";

            Crc16Ccitt A=new Crc16Ccitt(InitialCrcValue.Zeros);
            byte[] B = { 0x84, 0x00, 0x00, 0x00, 0x6B, 0x00, 0x00, 0x00, 0x67, 0x1F, 0x20, 0x00, 0x00, 0x62, 0x0C, 0x9B, 0x35, 0x35, 0x38, 0x3B, 0x34, 0x31, 0x36, 0x20, 0x56, 0x9B, 0x38, 0x31, 0x3B, 0x33, 0x32, 0x20, 0x5F, 0x90, 0x6F, 0x90, 0x20, 0x41, 0x90, 0x7E, 0x9B, 0x31, 0x3B, 0x30, 0x30, 0x30, 0x30, 0x20, 0x63, 0x9B, 0x30, 0x20, 0x58, 0x1C, 0x40, 0x40, 0x1C, 0x46, 0x40, 0x90, 0x20, 0x40, 0x90, 0x50, 0xC9, 0xB3, 0xC7, 0x89, 0x20, 0x1D, 0x61, 0x1B, 0x7E, 0xC0, 0xA4, 0xE9, 0xF3, 0xC1, 0xF3, 0x8A, 0x24, 0x72, 0x21, 0x29, 0x88, 0x1C, 0x4F, 0x41, 0x89, 0xE1, 0xAD, 0xB7, 0xB3, 0x8A, 0x21, 0x29, 0x89, 0x20, 0x8A, 0x21, 0x44, 0x89, 0xA4, 0xF3, 0xBF, 0xF9, 0xCD, 0xC3, 0xC8, 0x8A, 0x21, 0x29 };
            ushort C=A.ComputeChecksum(B);

            //Displaying the text
            richTextBox1.Text = ToDisplay;
        }