Esempio n. 1
0
        public static async Task <PacketResult> ReadPacket(Stream stream, Stopwatch sw = null)
        {
            Logger.Debug("ReadPacket read packet length (1 byte)");
            if (sw == null)
            {
                sw = Stopwatch.StartNew();
            }
            var smallBuf = new byte[1];
            var read     = await stream.ReadAsync(smallBuf);

            var packetLength = smallBuf[0];

            Logger.Debug("ReadPacket packetLength={packetLength}", packetLength);
            if (read < 1)
            {
                Logger.Debug("ReadPacket Could not read packet length, return Timeout");
                return(PacketResult.Timeout());
            }
            var totalRead = 0;
            var data      = new byte[packetLength + 1];

            data[0] = packetLength;
            while (totalRead < packetLength)
            {
                read = await stream.ReadAsync(data, totalRead + 1, packetLength - totalRead);

                if (read == 0)
                {
                    Logger.Debug("ReadPacket Could not complete reading of packet");
                    return(PacketResult.WrongSize());
                }

                totalRead += read;
            }
            sw.Stop();

            if (!Crc16.CheckCrc16(data))
            {
                Logger.Debug("ReadPacket CRC check failed.");
                return(PacketResult.WrongCrc());
            }

            Logger.Debug($"ReadPacket success: {data.ToHexString(" ")}");
            return(PacketResult.FromData(data, sw.Elapsed));
        }
Esempio n. 2
0
        public static async Task <PacketResult> ReadPacket(Stream stream)
        {
            Logger.Debug("ReadPacket read packet length (1 byte)");
            var packetLength = stream.ReadByte();

            Logger.Debug("ReadPacket packetLength={packetLength}", packetLength);
            if (packetLength < 0)
            {
                Logger.Debug("ReadPacket Could not read packet length, return Timeout");
                return(PacketResult.Timeout());
            }
            var totalRead = 0;
            var data      = new byte[packetLength + 1];

            data[0] = (byte)packetLength;
            while (totalRead < packetLength)
            {
                var read = await stream.ReadAsync(data, totalRead + 1, packetLength - totalRead);

                if (read == 0)
                {
                    Logger.Debug("ReadPacket Could not complete reading of packet");
                    return(PacketResult.WrongSize());
                }

                totalRead += read;
            }

            if (!Crc16.CheckCrc16(data))
            {
                Logger.Debug("ReadPacket CRC check failed.");
                return(PacketResult.WrongCrc());
            }

            Logger.Debug($"ReadPacket success: {data.ToHexString(" ")}");
            return(PacketResult.FromData(data));
        }