예제 #1
0
        protected void addCRC()
        {
            if (this.packet != null)
            {
                try
                {
                    byte[] temp = new byte[this.packet.Length + CRC_COUNTER];
                    byte[] crc  = PacketUtility.HexStringToByteArray(Crc16.ComputeChecksum(this.packet).ToString("x2"));

                    Array.Copy(this.packet, 0, temp, 0, this.packet.Length);

                    Array.Copy(crc, 0, temp, this.packet.Length, CRC_COUNTER);

                    this.packet = temp;
                }
                catch (Exception e)
                {
                    throw e;
                }
            }

            else
            {
                throw new NullReferenceException();
            }
        }
예제 #2
0
 public void ShowSegmentInfo(string FileName)
 {
     try {
         textBox1.AppendText(Path.GetFileName(FileName) + Environment.NewLine + Environment.NewLine);
         long   fsize      = new FileInfo(FileName).Length;
         byte[] buf        = ReadBin(FileName, 0, (uint)fsize);
         string calculated = CalculateChecksum(0, (uint)fsize, buf).ToString("X4");
         Crc16  C          = new Crc16();
         string CVN        = SwapBytes(C.ComputeChecksum(buf)).ToString("X4");
         string FromBin    = buf[0].ToString("X2") + buf[1].ToString("X2");
         string SegmentNr  = buf[2].ToString() + buf[3].ToString();
         string PN         = BEToUint32(buf, 4).ToString();
         string Ver        = System.Text.Encoding.ASCII.GetString(buf, 8, 2);
         textBox1.AppendText("Calculated checksum: " + calculated + Environment.NewLine);
         textBox1.AppendText("Checksum from bin: " + FromBin + Environment.NewLine);
         textBox1.AppendText("Segment number: " + SegmentNr + Environment.NewLine);
         textBox1.AppendText("PN: " + PN + Environment.NewLine);
         textBox1.AppendText("Ver: " + Ver + Environment.NewLine);
         textBox1.AppendText("CVN: " + CVN + Environment.NewLine + Environment.NewLine);
     }
     catch (Exception ex)
     {
         textBox1.AppendText(ex.Message);
     }
 }
예제 #3
0
    //以下顺序对应传入参数1-6

    /// <summary>
    ///  Standard,
    ///  Performs CRC 16 using x^16 + x^15 + x^2 + 1 polynomial with an initial CRC value of 0
    /// </summary>

    /// <summary>
    ///  Ccitt,
    ///  A CRC 16 CCITT Utility using x^16 + x^15 + x^2 + 1 polynomial with an initial CRC value of 0
    /// </summary>

    /// <summary>
    /// CcittKermit,
    /// Performs CRC 16 CCITT using a reversed x^16 + x^15 + x^2 + 1 polynomial with an initial CRC value of 0
    /// </summary>

    /// <summary>
    /// CcittInitialValue0xFFFF,
    /// Performs CRC 16 CCITT using x^16 + x^15 + x^2 + 1 polynomial with an initial CRC value of 0xffff
    /// </summary>

    /// <summary>
    /// CcittInitialValue0x1D0F,
    /// Performs CRC 16 CCITT using x^16 + x^15 + x^2 + 1 polynomial with an initial CRC value of 0x1D0F
    /// </summary>

    /// <summary>
    /// Dnp
    /// Performs CRC 16 Distributed Network Protocol (DNP) using reversed x^16 + x^13 + x^12 + x^11 + x^10 + x^8 + x^6 + x^5 + x^2 + 1 (0xA6BC) with an initial CRC value of 0
    /// </summary>


    public static ushort GetCRC16(byte[] bytes, int number = 1)
    {
        switch (number)
        {
        case 1:
            return(Crc16.ComputeChecksum(Crc16Algorithm.Standard, bytes));

        case 2:
            return(Crc16.ComputeChecksum(Crc16Algorithm.Ccitt, bytes));

        case 3:
            return(Crc16.ComputeChecksum(Crc16Algorithm.CcittKermit, bytes));

        case 4:
            return(Crc16.ComputeChecksum(Crc16Algorithm.CcittInitialValue0xFFFF, bytes));

        case 5:
            return(Crc16.ComputeChecksum(Crc16Algorithm.CcittInitialValue0x1D0F, bytes));

        case 6:
            return(Crc16.ComputeChecksum(Crc16Algorithm.Dnp, bytes));

        default:
            return(Crc16.ComputeChecksum(Crc16Algorithm.Standard, bytes));
        }
    }
예제 #4
0
파일: Program.cs 프로젝트: matijsbrs/BCom
                private void Register_OnPushEvent(object sender, BCMsg.BCMsgArgs e)
                {
                    BCMsg _msg = (sender as BCMsg);

                    try
                    {
                        UInt32 RegisteringDeviceUID = _msg.GetPayload().Reverse().ToUInt32();
                        Console.WriteLine($"Hello device: {RegisteringDeviceUID.ToString("X4")}");
                        _msg.Dump();


                        if ((parentDevice as DeviceManager).DevicePathTable.ContainsKey(RegisteringDeviceUID))
                        {
                            Console.WriteLine($"Hello device: {RegisteringDeviceUID.ToString("X4")}");
                            UInt16 PathHash = Crc16.ComputeChecksum(((parentDevice as DeviceManager).DevicePathTable[RegisteringDeviceUID] + "/").ToByteArr());
                            Console.WriteLine($"PathHash {PathHash.ToString("X4"),6} Path: {(parentDevice as DeviceManager).DevicePathTable[RegisteringDeviceUID] + "/" }");
                            byte[] TempArr = { (byte)(RegisteringDeviceUID >> 24), (byte)(RegisteringDeviceUID >> 16), (byte)(RegisteringDeviceUID >> 8), (byte)(RegisteringDeviceUID), (byte)(PathHash >> 8), (byte)PathHash };
                            msg.Build(TempArr);
                            //msg.msgUid = rand.Next();
                            msg.Command = BCMsg.Commande.PUSH;
                            msg.Dump();
                            BCMsg.WebInterfaceClass web = new BCMsg.WebInterfaceClass(msg);
                            //client.Publish($"{web.subscriber}", web.Export().ToByteArr());
                            parentDevice.client.Publish($"{web.subscriber}", web.Export().ToByteArr());
                        }
                        else
                        {
                            Console.WriteLine($"Unknown device: {msg.GetPayload().ToHexString()}");
                        }
                    }
                    catch (Exception err)
                    {
                        ConsoleEx.Error($"Could not register");
                    }
                }
예제 #5
0
    /// <summary>
    /// Sends a packet to the arduino.
    /// </summary>
    /// <param name="cmd">The command number.</param>
    /// <param name="buffer">The bytearray to be sent.</param>
    public void Send(int cmd, ArduinoDataType dataType, byte[] buffer)
    {
        // build serial packet
        int checksum = Crc16.ComputeChecksum(buffer);

        byte[] serialPacket = new byte[buffer.Length + headerSize];

        serialPacket[0] = (byte)(buffer.Length & 0xff);
        serialPacket[1] = (byte)((buffer.Length >> 8) & 0xff);
        serialPacket[2] = (byte)(checksum & 0xff);
        serialPacket[3] = (byte)((checksum >> 8) & 0xff);
        serialPacket[4] = (byte)cmd;
        serialPacket[5] = (byte)dataType;

        Array.Copy(buffer, 0, serialPacket, headerSize, buffer.Length);

        // encode packet
        byte[] encodedBuffer     = new byte[COBS.GetEncodedBufferSize(serialPacket.Length)];
        int    encodedBufferSize = COBS.Encode(ref serialPacket, serialPacket.Length, ref encodedBuffer);

        Array.Resize(ref encodedBuffer, encodedBufferSize + 1);
        encodedBuffer[encodedBufferSize] = 0;

        // add msg to outgoing queue
        lock (sendLockObject)
        {
            sendPackets.Enqueue(encodedBuffer);
        }
    }
예제 #6
0
        public unsafe void writeints(int len, int pos, byte *buf)
        {
            int old_pos = BitLength;
            int start   = old_pos / 8;
            int start1  = pos / 8;
            int end     = (old_pos + len) / 8;
            int end1    = (pos + len) / 8;

            flush();
            byte start_val = old_pos % 8 != 0 ? buffer[start] : (byte)0;

            fixed(byte *buf1 = &buffer[0])
            {
                if (old_pos % 8 != 0)
                {
                    crc16_m = Crc16.Substract(crc16_m, 0, 1);
                }
                crc16_m = Crc16.ComputeChecksum(crc16_m, buf + start1, end - start);
                AudioSamples.MemCpy(buf1 + start, buf + start1, end - start);
                buf1[start] |= start_val;
            }

            buf_ptr_m = end;
            if ((old_pos + len) % 8 != 0)
            {
                writebits((old_pos + len) % 8, buf[end1] >> (8 - ((old_pos + len) % 8)));
            }
        }
예제 #7
0
        public static byte[] AssembleMessagePacket(PacketEnvelope envelope, bool encrypt, string encryptPacketKey, string keySalt)
        {
            try
            {
                byte[] payloadBody = Zip(Serialization.ObjectToByteArray(envelope));

                if (encrypt)
                {
                    payloadBody = Encrypt(encryptPacketKey, keySalt, payloadBody);
                }

                int grossPacketSize = payloadBody.Length + Constants.PayloadHeaderSize;

                byte[] packetBytes = new byte[grossPacketSize];

                UInt16 payloadCrc = Crc16.ComputeChecksum(payloadBody);

                Buffer.BlockCopy(BitConverter.GetBytes(Constants.PayloadDelimiter), 0, packetBytes, 0, 4);
                Buffer.BlockCopy(BitConverter.GetBytes(grossPacketSize), 0, packetBytes, 4, 4);
                Buffer.BlockCopy(BitConverter.GetBytes(payloadCrc), 0, packetBytes, 8, 2);
                Buffer.BlockCopy(payloadBody, 0, packetBytes, Constants.PayloadHeaderSize, payloadBody.Length);

                return(packetBytes);
            }
            catch (Exception ex)
            {
                //TODO: allow this to be logged.
            }

            return(null);
        }
예제 #8
0
        public static byte[] AssembleMessagePacket(Packet packet)
        {
            try
            {
                byte[] payloadBody = Serialization.ObjectToByteArray(packet);

                byte[] payloadBytes    = Zip(payloadBody);
                int    grossPacketSize = payloadBytes.Length + Constants.PayloadHeaderSize;

                byte[] packetBytes = new byte[grossPacketSize];

                UInt16 payloadCrc = Crc16.ComputeChecksum(payloadBytes);

                Buffer.BlockCopy(BitConverter.GetBytes(Constants.PayloadDelimiter), 0, packetBytes, 0, 4);
                Buffer.BlockCopy(BitConverter.GetBytes(grossPacketSize), 0, packetBytes, 4, 4);
                Buffer.BlockCopy(BitConverter.GetBytes(payloadCrc), 0, packetBytes, 8, 2);
                Buffer.BlockCopy(payloadBytes, 0, packetBytes, Constants.PayloadHeaderSize, payloadBytes.Length);

                return(packetBytes);
            }
            catch
            {
                //TODO: allow this to be logged.
            }

            return(null);
        }
예제 #9
0
        static void Main(string[] args)
        {
            string input  = "Agent 3oH ID ";
            var    target = new System.Collections.Generic.List <string>()
            {
                "fb38", "8cc2", "55a5", "4f1a", "318a"
            };

            //for (int i=1; i<1000; i++)
            int i = 0;

            while (true)
            {
                //Guid guid = Guid.NewGuid();
                //var bytes = Encoding.ASCII.GetBytes(guid.ToString());
                var    bytes = Encoding.ASCII.GetBytes(input + i);
                string hex   = Crc16.ComputeChecksum(bytes).ToString("x2");
                if (target.Contains(hex))
                {
                    Console.WriteLine(input + i); //c061
                    Console.ReadLine();
                }
                i++;
            }

            Console.Write("Done!");
            Console.ReadKey();
            //var bytes = HexToBytes(input);
            //var bytes = Encoding.ASCII.GetBytes(input);
            //string hex = Crc16.ComputeChecksum(bytes).ToString("x2");
            //Console.WriteLine(hex); //c061
            //Console.ReadLine();
        }
예제 #10
0
        protected override void ConstructResponse(GPCMSession session)
        {
            session.PlayerInfo.SessionKey = _crc.ComputeChecksum(session.PlayerInfo.Nick + session.PlayerInfo.NamespaceID);
            string responseProof = ChallengeProof.GenerateProof
                                   (
                session.PlayerInfo.UserData,
                session.PlayerInfo.LoginType,
                session.PlayerInfo.PartnerID,
                session.PlayerInfo.ServerChallenge,
                session.PlayerInfo.UserChallenge,
                session.PlayerInfo.PasswordHash
                                   );

            _sendingBuffer  = @"\lc\2\sesskey\" + session.PlayerInfo.SessionKey;
            _sendingBuffer += @"\proof\" + responseProof;
            _sendingBuffer += @"\userid\" + _result[0]["userid"];
            _sendingBuffer += @"\profileid\" + _result[0]["profileid"];

            if (session.PlayerInfo.LoginType != LoginType.Nick)
            {
                _sendingBuffer += @"\uniquenick\" + _result[0]["uniquenick"];
            }

            _sendingBuffer += @"\lt\" + session.Id.ToString().Replace("-", "").Substring(0, 22) + "__";
            _sendingBuffer += @"\id\" + _operationID + @"\final\";

            session.PlayerInfo.LoginProcess = LoginStatus.Completed;
        }
예제 #11
0
        private ushort CalculateChecksum(byte[] array)
        {
            var shortArray = new byte[array.Length - 3];

            Array.Copy(array, 3, shortArray, 0, shortArray.Length);

            return(_ChecksumCalculator.ComputeChecksum(shortArray));
        }
    static void Main()
    {
        string input = "8000";
        var    bytes = HexToBytes(input);
        string hex   = Crc16.ComputeChecksum(bytes).ToString("x2");

        Console.WriteLine(hex);     //c061
    }
예제 #13
0
        private void TestChecksum(byte[] validChecksum, string dataAsString)
        {
            byte[] bytes         = dataAsString.Trim().Split(' ').Select(v => (byte)int.Parse(v, System.Globalization.NumberStyles.HexNumber)).ToArray();
            var    checksum      = Crc16.ComputeChecksum(bytes);
            var    checksumBytes = ConvertToBytes(checksum);

            Assert.IsTrue(Equals(validChecksum, checksumBytes), $"Checksum did not match. Was: {Format(checksumBytes)}, Expected: {Format(validChecksum)}");
        }
예제 #14
0
        public void CheckCrc()
        {
            var origCrc = BitConverter.ToUInt16(_crc.Reverse().ToArray(), 0);
            var res     = Crc16.ComputeChecksum(_data);

            if (res != origCrc)
            {
                throw new InvalidDataException("crc mismatch");
            }
        }
예제 #15
0
        public void Crc16_CrcWithPayloadComputesToZero(string input)
        {
            var bytes = input.ToBytes();
            var crc   = Crc16.ComputeChecksum(bytes);

            var payload   = bytes.ConcatArray(BitConverter.GetBytes(crc));
            var secondCrc = Crc16.ComputeChecksum(payload);

            secondCrc.Should().Be(0);
        }
    /// <summary>
    /// Computes the hash.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <returns></returns>
    public static ushort ComputeHash(string input)
    {
        if (input == null)
        {
            input = "";
        }

        Crc16 crc = new Crc16();

        byte[] bytes = Encoding.UTF8.GetBytes(input);
        return(crc.ComputeChecksum(bytes));
    }
예제 #17
0
        public void CombineTest16()
        {
            int    lenAB = testBytes.Length;
            int    lenA  = 7;
            int    lenB  = lenAB - lenA;
            ushort crcAB = Crc16.ComputeChecksum(0, testBytes, 0, lenAB);
            ushort crcA  = Crc16.ComputeChecksum(0, testBytes, 0, lenA);
            ushort crcB  = Crc16.ComputeChecksum(0, testBytes, lenA, lenB);

            Assert.AreEqual <uint>(crcAB, Crc16.Combine(crcA, crcB, lenB), "CRC16 was not combined correctly.");
            Assert.AreEqual <uint>(crcB, Crc16.Combine(crcA, crcAB, lenB), "CRC16 was not substracted correctly.");
            Assert.AreEqual <uint>(crcA, Crc16.Substract(crcAB, crcB, lenB), "CRC16 was not substracted correctly.");
        }
예제 #18
0
        private static bool _Run()
        {
            bool   result = true;
            FCrc16 fcrc   = new FCrc16();
            Crc16  crc    = new Crc16();

            result = F.same <ushort>(fcrc.Table.AsEnumerable(), crc.Table.AsEnumerable(), (u1, u2) => u1 == u2);
            byte[] test      = new byte[] { 0x45, 0x19, 0xA7, 0x00, 0xFE, 0xFF, 0x04, 0x4A };
            ushort fChecksum = fcrc.ComputeChecksum(test);
            ushort cChecksum = crc.ComputeChecksum(test);

            result = result && (fChecksum == cChecksum);
            return(result);
        }
예제 #19
0
        void aprirePopupQrCodeInvioCassa()
        {
            InputBoxDialog d = new InputBoxDialog();

            d.inputValue.Text = DateTime.Today.ToString("yyyy-MM-dd");
            d.Title           = "Inserire data riferimento (AAAA-MM-GG)";
            bool?esito = d.ShowDialog();

            if (esito != true)
            {
                return;
            }

            DateTime dataFinale = DateTime.ParseExact(d.inputValue.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);


            var chiusure = riempireDtoChiusure(dataFinale);

            if (chiusure == null)
            {
                dialogProvider.ShowMessage("Nessun dato estratto negli ultimi " + GIORNI_INDIETRO_CHIUSURE + " giorni", "Nessun dato");
                return;
            }


            string messaggio = chiusure.serializeToPiccolaString();

            // Aggiungo un crc di sicurezza
            Crc16  chk   = new Crc16();
            ushort crc16 = chk.ComputeChecksum(Encoding.ASCII.GetBytes(messaggio));

            // aggiungo un prefisso che è un comando per telegram che vado ad implementare
            string qrCode = "/cc " + messaggio + "!" + crc16.ToString("X4");

            string nomeFileTemp = Path.Combine(Path.GetTempPath(), "qrcode-cassa.ser.txt");

            File.WriteAllBytes(nomeFileTemp, Encoding.ASCII.GetBytes(qrCode));

            // Apro la popup lanciando un evento
            var ea = new OpenPopupRequestEventArgs {
                requestName = "QRcodeChiusureCassaPopup",
                param       = qrCode
            };

            RaisePopupDialogRequest(ea);

            if (ea.mioDialogResult == true)
            {
            }
        }
예제 #20
0
    public static void applyPacket(byte[] bytes)
    // uint8_t type;          // 1 B, o: 0,   packet type
    // uint8_t length;        // 1 B, o: 1,   packet size
    // uint16_t crc16;        // 2 B, o: 2,   CRC16
    // unsigned long packetID;// 4 B, o: 4    running packet count

    // unsigned long us_start;// 4 B, o: 8,   gather start timestamp
    // unsigned long us_end;  // 4 B, o: 12,  transmit timestamp
    // uint16_t analog[8];    // 16 B, o: 16, ADC values
    // long variables[8];     // 32 B, o: 32, variables (encoder, speed, etc)

    // uint16_t digitalIn;    // 2 B, o: 64,  digital inputs
    // uint8_t digitalOut;    // 1 B, o: 66,  digital outputs
    // uint8_t padding[1];    // 1 B, o: 67,  align to 4B
    {
        State.received = DateTime.Now;
        State.raw      = bytes;
        State.type     = bytes[0];
        State.length   = bytes[1];

        State.crc16 = BitConverter.ToUInt16(bytes, 2);
        byte[] tmp = new byte[bytes.Length];
        bytes.CopyTo(tmp, 0);   // make copy
        tmp[2]             = 0; // set crc16 field to zero, as was when
        tmp[3]             = 0; // crc16_ccitt was calculated before sending.
        State.crc16_tested = CRC.ComputeChecksum(tmp);
        if (State.crc16_tested != State.crc16)
        {
            crcFaults++;
        }

        State.packetID = BitConverter.ToUInt32(bytes, 4);
        State.usStart  = BitConverter.ToUInt32(bytes, 8);
        State.usEnd    = BitConverter.ToUInt32(bytes, 12);
        State.analog   = new ushort[8];
        for (byte i = 0; i < 8; i++)
        {
            State.analog[i] = BitConverter.ToUInt16(bytes, 16 + 2 * i);
        }

        State.variables = new int[8];
        for (byte i = 0; i < 8; i++)
        {
            State.variables[i] = BitConverter.ToInt32(bytes, 32 + 4 * i);
        }

        State.DIN  = BitConverter.ToUInt16(bytes, 64);
        State.DOUT = bytes[66];
    }
예제 #21
0
        public static void SendUP(string text)
        {
            try {
                messagePos = 0;
                byte[] SYNC    = new byte[] { 0xA5, 0x00 }; //Low endian
                byte[] TIME    = GetMillisecondTime();
                byte[] FID     = GetFID();
                byte[] XT      = GetXT(); //Future will need it to take in an input
                byte[] CMD     = GetCMD(text);
                byte[] DATA    = GetData();
                byte[] DATALEN = GetDataLen(DATA);

                //SYNC:2, TIME:4, FID:2, XT:4, CMD:2, LEN:2, DATA:0-65517, CRC:2    //bytes (8 bits)
                byte[] message = new byte[65535]; //18 for debug, 65535 for full

                AddToMessage(message, SYNC);
                AddToMessage(message, FID);
                AddToMessage(message, TIME);
                AddToMessage(message, XT);
                AddToMessage(message, CMD);
                AddToMessage(message, DATALEN);
                AddToMessage(message, DATA);

                var    result = Crc16.ComputeChecksum(message);
                byte[] CRC    = BitConverter.GetBytes(result);

                AddToMessage(message, CRC);

                //AsyncCamCom.SendNonAsync(message);
                incrementalCounter++;

                string s = "";
                for (int i = 0; i < message.Length; i++)
                {
                    if (i > 18 && i < 20)
                    {
                        s += "... ";
                        i  = message.Length - 2;
                    }
                    s += message[i].ToString("X") + " ";
                }

                //l_Send.Text = s;
                Console.WriteLine(s);
            } catch (Exception e) {
                Console.WriteLine("FAIL\n" + e.ToString());
            }
        }
예제 #22
0
        UInt16 tcpConnectionId(IPEndPoint src, IPEndPoint dst)
        {
            byte[] addr1 = src.Address.GetAddressBytes();
            byte[] port1 = src.Port.GetBytes();
            byte[] addr2 = dst.Address.GetAddressBytes();
            byte[] port2 = dst.Port.GetBytes();

            byte[] data = new byte[addr1.Length + port1.Length + addr2.Length + port2.Length];

            addr1.CopyTo(data, 0);
            port1.CopyTo(data, addr1.Length);
            addr2.CopyTo(data, addr1.Length + port1.Length);
            port2.CopyTo(data, addr1.Length + port1.Length + addr2.Length);

            return(Crc16.ComputeChecksum(data));
        }
예제 #23
0
        public void PerformCrc16Tests <ExpectedChecksum> (TestParameter <ExpectedChecksum> parameter)
        {
            var    range  = parameter.TestRange;
            ushort actual = 0;

            if (range == TestRange.All)
            {
                actual = Crc16.ComputeChecksum(parameter.Algorithm, parameter.TestPayload);
            }
            else
            {
                actual = Crc16.ComputeChecksum(parameter.Algorithm, parameter.TestPayload, range.Start, range.Length);
            }
            var expected = (ushort)(object)parameter.ExpectedCrc;

            Assert.Equal(expected, actual);
        }
예제 #24
0
        public byte[] DecryptData(byte[] rawdata)
        {
            if (rawdata == null)
            {
                throw new ArgumentException("Data must not be null");
            }
            var crcCalced = Crc16.ComputeChecksum(rawdata.Take(rawdata.Length - 5).ToArray());

            var msg = Encoding.UTF8.GetString(rawdata).TrimEnd((char)Protocol.END);

            var data = HexStringToBytes(msg);
            var crc  = data[data.Length - 2] + (data[data.Length - 1] << 8);

            if (crc != crcCalced)
            {
                throw new Exception("CRC error");
            }
            return(_xtea.Decrypt(data.Take(data.Length - 2).ToArray()));
        }
예제 #25
0
        public unsafe int DecodeFrame(byte[] buffer, int pos, int len)
        {
            fixed(byte *buf = buffer)
            {
                framereader.Reset(buf, pos, len);
                Decode_frame_header(framereader, frame);
                Decode_subframes(framereader, frame);
                framereader.Flush();
                ushort crc_1 = DoCRC ? crc16.ComputeChecksum(framereader.Buffer + pos, framereader.Position - pos) : (ushort)0;
                ushort crc_2 = (ushort)framereader.Readbits(16);

                if (DoCRC && crc_1 != crc_2)
                {
                    throw new Exception("frame crc mismatch");
                }
                Restore_samples(frame);
                _samplesInBuffer = frame.blocksize;
                return(framereader.Position - pos);
            }
        }
예제 #26
0
 public void Crc16CcittFfffValidation( )
 {
     Assert.AreEqual(Crc16.ComputeChecksum(Crc16Algorithm.CcittInitialValue0xFFFF, TestBuffer), CrcCcittFCrc);
 }
예제 #27
0
        public static void DissasemblePacketData(SocketState state, ProcessPayloadCallback processPayload)
        {
            try
            {
                if (state.PayloadBuilderLength + state.BytesReceived >= state.PayloadBuilder.Length)
                {
                    Array.Resize(ref state.PayloadBuilder, state.PayloadBuilderLength + state.BytesReceived);
                }

                Buffer.BlockCopy(state.Buffer, 0, state.PayloadBuilder, state.PayloadBuilderLength, state.BytesReceived);

                state.PayloadBuilderLength = state.PayloadBuilderLength + state.BytesReceived;

                while (state.PayloadBuilderLength > Constants.PayloadHeaderSize) //[PayloadSize] and [CRC16]
                {
                    Byte[] payloadDelimiterBytes = new Byte[4];
                    Byte[] payloadSizeBytes      = new Byte[4];
                    Byte[] expectedCrc16Bytes    = new Byte[2];

                    Buffer.BlockCopy(state.PayloadBuilder, 0, payloadDelimiterBytes, 0, payloadDelimiterBytes.Length);
                    Buffer.BlockCopy(state.PayloadBuilder, 4, payloadSizeBytes, 0, payloadSizeBytes.Length);
                    Buffer.BlockCopy(state.PayloadBuilder, 8, expectedCrc16Bytes, 0, expectedCrc16Bytes.Length);

                    int    payloadDelimiter = BitConverter.ToInt32(payloadDelimiterBytes, 0);
                    int    grossPayloadSize = BitConverter.ToInt32(payloadSizeBytes, 0);
                    UInt16 expectedCrc16    = BitConverter.ToUInt16(expectedCrc16Bytes, 0);

                    if (payloadDelimiter != Constants.PayloadDelimiter)
                    {
                        SkipPacket(ref state);
                        //throw new Exception("Malformed payload packet, invalid delimiter.");
                        continue;
                    }

                    if (grossPayloadSize < Constants.DefaultMinMsgSize || grossPayloadSize > Constants.DefaultMaxMsgSize)
                    {
                        SkipPacket(ref state);
                        //throw new Exception("Malformed payload packet, invalid length.");
                        continue;
                    }

                    if (state.PayloadBuilderLength < grossPayloadSize)
                    {
                        //We have data in the buffer, but it's not enough to make up
                        //  the entire message so we will break and wait on more data.
                        break;
                    }

                    UInt16 actualCrc16 = Crc16.ComputeChecksum(state.PayloadBuilder, Constants.PayloadHeaderSize, grossPayloadSize - Constants.PayloadHeaderSize);

                    if (actualCrc16 != expectedCrc16)
                    {
                        SkipPacket(ref state);
                        //throw new Exception("Malformed payload packet, invalid CRC.");
                        continue;
                    }

                    int    netPayloadSize = grossPayloadSize - Constants.PayloadHeaderSize;
                    byte[] payloadBytes   = new byte[netPayloadSize];

                    Buffer.BlockCopy(state.PayloadBuilder, Constants.PayloadHeaderSize, payloadBytes, 0, netPayloadSize);

                    byte[] payloadBody = Unzip(payloadBytes);

                    Packet packet = (Packet)Serialization.ByteArrayToObject(payloadBody);

                    processPayload(state, packet);

                    //Zero out the consumed portion of the payload buffer - more for fun than anything else.
                    Array.Clear(state.PayloadBuilder, 0, grossPayloadSize);

                    Buffer.BlockCopy(state.PayloadBuilder, grossPayloadSize, state.PayloadBuilder, 0, state.PayloadBuilderLength - grossPayloadSize);
                    state.PayloadBuilderLength -= grossPayloadSize;
                }
            }
            catch (Exception ex)
            {
                //TODO: allow this to be logged.
            }
        }
예제 #28
0
    /// <summary>
    /// Threaded function. Loops and checks for incoming packets.
    /// </summary>
    private void ReceiveThreadDoTask()
    {
        try
        {
            byte[] receiveBuffer = new byte[bufferSize];
            int    bytesReceived = 0;

            while (running)
            {
                while (sendPackets.Count > 0)
                {
                    byte[] serialPacket;
                    lock (sendLockObject)
                    {
                        serialPacket = sendPackets.Dequeue();
                    }
                    stream.Write(serialPacket, 0, serialPacket.Length);
                }

                if (stream.BytesToRead > 0)
                {
                    int x = stream.ReadByte();

                    if (x == -1)
                    {
//                        Debug.LogError("End of Stream!");
//                        running = false;
                        continue;
                    }

                    if (x == 0)
                    {
                        // decode
                        byte[] decodedBuffer     = new byte[receiveBuffer.Length];
                        int    decodedBufferSize = COBS.Decode(ref receiveBuffer, bytesReceived, ref decodedBuffer);
                        Array.Resize(ref decodedBuffer, decodedBufferSize);

                        // disect packt
                        int             len        = decodedBuffer[0] | (decodedBuffer[1] << 8);
                        int             checksum   = decodedBuffer[2] | (decodedBuffer[3] << 8);
                        int             cmd        = decodedBuffer[4];
                        ArduinoDataType dataType   = (ArduinoDataType)decodedBuffer[5];
                        byte[]          dataPacket = new byte[decodedBuffer.Length - headerSize];
                        Array.Copy(decodedBuffer, headerSize, dataPacket, 0, decodedBufferSize - headerSize);

                        // check length
                        if (dataPacket.Length != len)
                        {
                            Debug.Log(String.Format("Invalid Packet Length. Want: {0} - Have: {1}", len, dataPacket.Length));
                            continue;
                        }

                        // checksum
                        int packetChecksum = Crc16.ComputeChecksum(dataPacket);
                        if (checksum != packetChecksum)
                        {
                            Debug.Log(String.Format("Invalid Checksum. Want: {0} - Have: {1}", checksum, packetChecksum));
                            continue;
                        }

                        bytesReceived = 0;

                        // store in queue
                        lock (receiveLockObject)
                        {
                            receivedPackets.Enqueue(new ArduinoBuffer(cmd, dataType, dataPacket));
                        }
                    }
                    else
                    {
                        if (bytesReceived >= bufferSize)
                        {
                            // TODO handle differently!
                            bytesReceived = 0;
                        }
                        else
                        {
                            receiveBuffer[bytesReceived++] = (byte)x;
                        }
                    }
                }
            }
        }
        catch (ThreadAbortException ex)
        {
            Debug.Log("Aborting UDP Receiver Thread!");
//              Debug.LogException(ex);
        }
    }
예제 #29
0
파일: Decoder.cs 프로젝트: kutsoff/Invent
 private static ushort ComputeCrc(byte[] val)
 {
     var crc16 = new Crc16(Crc16Mode.Standard);
     return crc16.ComputeChecksum(val);
 }
예제 #30
0
 public void Crc16DnpValidation( )
 {
     Assert.AreEqual(Crc16.ComputeChecksum(Crc16Algorithm.Dnp, TestBuffer), CrcDnpCrc);
 }
예제 #31
0
 public void Crc16CcittValidation( )
 {
     Assert.AreEqual(Crc16.ComputeChecksum(Crc16Algorithm.Ccitt, TestBuffer), CrcCcittCrc);
 }