Example #1
0
        protected int ReadNextPacket()
        {
            if (Data != null)
            {
                StreamingPool.Return(Data);
                Data = null;
            }

            //wait until a magic packet is received
            Device.MillisTimeout = 100;
            while (true)
            {
                SizeBuf[0] = SizeBuf[1] = SizeBuf[2] = SizeBuf[3] = 0;
                if (Device.Read(SizeBuf, 0, 4) != 4)
                {
                    if (Token.IsCancellationRequested)
                    {
                        return(-3);
                    }
                    else
                    {
                        continue;
                    }
                }
                if (SizeBuf.SequenceEqual(MagicPacket))
                {
                    break;
                }
            }

            //read the payload size
            if (Device.Read(SizeBuf, 0, 4) != 4)
            {
                return(-2);
            }
            var size = BitConverter.ToUInt32(SizeBuf, 0);

            if (size > MaxBufSize)
            {
                return(-1);
            }
            if (size == 0)
            {
                return(0);
            }

            //read the timestamp
            if (Device.Read(TsBuf, 0, 8) != 8)
            {
                return(-4);
            }
            Timestamp = BitConverter.ToUInt64(TsBuf);
            if (firtTs == 0)
            {
                firtTs = Timestamp;
            }

            Timestamp -= firtTs;

            //Read the actual data
            Device.MillisTimeout = 1000;
            Data = StreamingPool.Rent((int)size);
            int actualsize = Device.Read(Data, 0, (int)size);

            if (actualsize != size)
            {
                Console.WriteLine("Warning: Reported size doesn't match received size");
            }
            return(actualsize);
        }