/// <summary> /// Synchronously read a complete packet from a possibly-fragmented stream /// </summary> /// <remarks> /// Not very useful in production, but it made development and testing easier /// </remarks> public static SsmPacket ReadFromStream(Stream stream) { SsmPacketParser parser = new SsmPacketParser(); while (!parser.IsComplete) { if (parser.bytesReceived != 0) { System.Threading.Thread.Sleep(1); } int bufferLength = stream.Read(parser.buffer, parser.bytesReceived, parser.buffer.Length - parser.bytesReceived); if (bufferLength == 0) { throw new SsmPacketFormatException("Unexpected end of stream."); } for (int i = 0; i < bufferLength; i++) { int index = parser.bytesReceived + i; parser.CheckByte(index, parser.buffer[index]); } parser.bytesReceived += bufferLength; } return(SsmPacket.ParseResponse(parser.buffer, 0, parser.bytesReceived)); }
public GetEcuIdentifierAsyncResult( AsyncCallback asyncCallback, object asyncState) : base( asyncCallback, asyncState) { this.parser = SsmPacketParser.CreateInstance(); }
public BlockReadAsyncResult( AsyncCallback asyncCallback, object asyncState) : base( asyncCallback, asyncState) { this.parser = SsmPacketParser.CreateInstance(); this.values = new List <byte>(); }
public ReadFromStreamAsyncResult( Stream stream, SsmPacketParser parser, AsyncCallback asyncCallback, object asyncState) : base( asyncCallback, asyncState) { this.stream = stream; this.parser = parser; }
/// <summary> /// Invoked each time stream.BeginRead completes /// </summary> /// <remarks> /// Parse the received bytes, notify the consumer if a full packet is /// received or if anything goes wrong. /// </remarks> private static void ReadCompleted(IAsyncResult asyncResult) { ReadFromStreamAsyncResult internalState = (ReadFromStreamAsyncResult)asyncResult.AsyncState; try { SsmPacketParser parser = internalState.Parser; int offset = parser.bytesReceived; int bytesReceived = internalState.Stream.EndRead(asyncResult); for (int i = 0; i < bytesReceived; i++) { int index = offset + i; internalState.Parser.CheckByte(index, internalState.Parser.buffer[index]); parser.bytesReceived++; } if (internalState.Parser.IsComplete) { internalState.Completed(); } else { internalState.Parser.InternalBeginReadFromStream( internalState.Stream, SsmPacketParser.ReadCompleted, internalState); } } catch (System.Security.SecurityException ex) { internalState.Exception = ex; internalState.Completed(); } catch (IOException ex) { internalState.Exception = ex; internalState.Completed(); } }