public void ReadTimeout_0_1ByteAvailable_Read_byte_int_int() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rcvBytes = new byte[128]; int bytesRead; Debug.WriteLine( "Verifying 0 ReadTimeout with Read(byte[] buffer, int offset, int count) and one byte available"); com1.Open(); com2.Open(); Stream stream = com1.BaseStream; stream.ReadTimeout = 0; com2.Write(new byte[] { 50 }, 0, 1); TCSupport.WaitForReadBufferToLoad(com1, 1); Assert.True(1 == (bytesRead = com1.Read(rcvBytes, 0, rcvBytes.Length)), string.Format("Err_31597ahpba, Expected to Read to return 1 actual={0}", bytesRead)); Assert.True(50 == rcvBytes[0], string.Format("Err_778946ahba, Expected to read 50 actual={0}", rcvBytes[0])); } }
public void InAndOutBufferFilled_Discard() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Debug.WriteLine("Verifying Discard method after input buffer has been filled"); com1.Open(); com2.Open(); com1.WriteTimeout = 500; com1.Handshake = Handshake.RequestToSend; com2.Write(s_DEFAULT_STRING); // Wait for the data to pass from COM2 to com1 TCSupport.WaitForReadBufferToLoad(com1, s_DEFAULT_STRING.Length); Task task = Task.Run(() => WriteRndByteArray(com1, s_DEFAULT_BUFFER_LENGTH)); int origBytesToRead = com1.BytesToRead; TCSupport.WaitForWriteBufferToLoad(com1, s_DEFAULT_BUFFER_LENGTH); VerifyDiscard(com1); Assert.Equal(origBytesToRead, com1.BytesToRead); // Wait for write method to fail with IOException Assert.Throws <AggregateException>(() => task.Wait(2000)); Assert.IsType <IOException>(task.Exception.InnerException); } }
public void InBufferFilled_Flush_Multiple() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { byte[] xmitBytes = new byte[DEFAULT_BUFFER_SIZE]; Debug.WriteLine("Verifying call Flush method several times after input buffer has been filled"); com1.Open(); com2.Open(); for (int i = 0; i < xmitBytes.Length; i++) { xmitBytes[i] = (byte)i; } com2.Write(xmitBytes, 0, xmitBytes.Length); TCSupport.WaitForReadBufferToLoad(com1, DEFAULT_BUFFER_SIZE); VerifyFlush(com1); VerifyFlush(com1); VerifyFlush(com1); } }
public void InOutBufferFilled_Flush_Once() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, DEFAULT_BUFFER_SIZE); var t = new Task(asyncWriteRndByteArray.WriteRndByteArray); byte[] xmitBytes = new byte[DEFAULT_BUFFER_SIZE]; Debug.WriteLine("Verifying Flush method after input and output buffer has been filled"); com1.Open(); com2.Open(); com1.WriteTimeout = 500; com1.Handshake = Handshake.RequestToSend; for (int i = 0; i < xmitBytes.Length; i++) { xmitBytes[i] = (byte)i; } com2.Write(xmitBytes, 0, xmitBytes.Length); TCSupport.WaitForReadBufferToLoad(com1, DEFAULT_BUFFER_SIZE); t.Start(); TCSupport.WaitForWriteBufferToLoad(com1, DEFAULT_BUFFER_LENGTH); VerifyFlush(com1); TCSupport.WaitForTaskCompletion(t); } }
public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndBytesParity]; char[] expectedChars = new char[numRndBytesParity]; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream * We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); com2.Write(com1.NewLine); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + com1.NewLine.Length); string strRead = com1.ReadTo(com1.NewLine); char[] actualChars = strRead.ToCharArray(); Assert.Equal(expectedChars, actualChars); if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } com1.DiscardInBuffer(); bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedChars); } }
public void InOutBufferFilled_Flush_Cycle() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, DEFAULT_BUFFER_SIZE); Thread t1 = new Thread(asyncWriteRndByteArray.WriteRndByteArray); Thread t2 = new Thread(asyncWriteRndByteArray.WriteRndByteArray); byte[] xmitBytes = new byte[DEFAULT_BUFFER_SIZE]; Debug.WriteLine( "Verifying call Flush method after input and output buffer has been filled discarded and filled again"); com1.Open(); com2.Open(); com1.WriteTimeout = 500; com1.Handshake = Handshake.RequestToSend; for (int i = 0; i < xmitBytes.Length; i++) { xmitBytes[i] = (byte)i; } com2.Write(xmitBytes, 0, xmitBytes.Length); TCSupport.WaitForReadBufferToLoad(com1, DEFAULT_BUFFER_SIZE); t1.Start(); TCSupport.WaitForWriteBufferToLoad(com1, DEFAULT_BUFFER_LENGTH); VerifyFlush(com1); // Wait for write method to timeout while (t1.IsAlive) { Thread.Sleep(100); } t2.Start(); TCSupport.WaitForWriteBufferToLoad(com1, DEFAULT_BUFFER_LENGTH); com2.Write(xmitBytes, 0, xmitBytes.Length); TCSupport.WaitForReadBufferToLoad(com1, DEFAULT_BUFFER_SIZE); VerifyFlush(com1); // Wait for write method to timeout while (t2.IsAlive) { Thread.Sleep(100); } } }
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, Encoding encoding) { byte[] byteRcvBuffer = new byte[expectedBytes.Length]; int rcvBufferSize = 0; int i; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; com1.Encoding = encoding; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); i = 0; while (true) { int readInt; try { readInt = com1.ReadByte(); } catch (TimeoutException) { break; } //While their are more bytes to be read if (expectedBytes.Length <= i) { //If we have read in more bytes then we expecte Fail("ERROR!!!: We have received more bytes then were sent"); } byteRcvBuffer[i] = (byte)readInt; rcvBufferSize++; if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); } if (readInt != expectedBytes[i]) { //If the bytes read is not the expected byte Fail("ERROR!!!: Expected to read {0} actual read byte {1}", expectedBytes[i], (byte)readInt); } i++; } if (rcvBufferSize != expectedBytes.Length) { Fail("ERROR!!! Expected to read {0} char actually read {1} chars", bytesToWrite.Length, rcvBufferSize); } }
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, int rcvBufferSize) { byte[] rcvBuffer = new byte[rcvBufferSize]; byte[] buffer = new byte[bytesToWrite.Length]; int totalBytesRead; int bytesToRead; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); totalBytesRead = 0; bytesToRead = com1.BytesToRead; while (true) { int bytesRead; try { bytesRead = com1.Read(rcvBuffer, 0, rcvBufferSize); } catch (TimeoutException) { break; } //While their are more characters to be read if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { //If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (bytesToWrite.Length < totalBytesRead + bytesRead) { //If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); } Array.Copy(rcvBuffer, 0, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } bytesToRead = com1.BytesToRead; } // Compare the bytes that were written with the ones we expected to read Assert.Equal(expectedBytes, buffer); }
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer Assert.Equal(bytesToWrite.Length, com1.BytesToRead); }
public void ReadTimeout_Zero_ResizeBuffer() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { byte[] byteXmitBuffer = new byte[1024]; char utf32Char = 'A'; byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); char[] charXmitBuffer = TCSupport.GetRandomChars(16, false); char[] expectedChars = new char[charXmitBuffer.Length + 1]; Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer"); expectedChars[0] = utf32Char; Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; com1.ReadTimeout = 0; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback { com2.Open(); } com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); Assert.Equal(1, com1.BytesToRead); com1.Encoding = Encoding.UTF32; byteXmitBuffer = Encoding.UTF32.GetBytes(charXmitBuffer); Assert.Throws <TimeoutException>(() => com1.ReadChar()); Assert.Equal(1, com1.BytesToRead); com2.Write(utf32CharBytes, 1, 3); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length); PerformReadOnCom1FromCom2(com1, com2, expectedChars); } }
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, int rcvBufferSize) { var rcvBuffer = new byte[rcvBufferSize]; var buffer = new byte[bytesToWrite.Length]; int totalBytesRead; int bytesToRead; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); totalBytesRead = 0; bytesToRead = com1.BytesToRead; while (0 != com1.BytesToRead) { int bytesRead = com1.BaseStream.EndRead(com1.BaseStream.BeginRead(rcvBuffer, 0, rcvBufferSize, null, null)); // While their are more characters to be read if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { // If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (bytesToWrite.Length < totalBytesRead + bytesRead) { // If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); break; } Array.Copy(rcvBuffer, 0, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } bytesToRead = com1.BytesToRead; } // Compare the bytes that were written with the ones we expected to read for (var i = 0; i < bytesToWrite.Length; i++) { if (expectedBytes[i] != buffer[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1}", expectedBytes[i], buffer[i]); } } }
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { char[] charRcvBuffer = new char[expectedChars.Length]; int rcvBufferSize = 0; int i; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); i = 0; while (true) { int readInt; try { readInt = com1.ReadChar(); } catch (TimeoutException) { break; } //While their are more characters to be read if (expectedChars.Length <= i) { //If we have read in more characters then we expecte Fail("ERROR!!!: We have received more characters then were sent"); } charRcvBuffer[i] = (char)readInt; rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1); if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); } if (readInt != expectedChars[i]) { //If the character read is not the expected character Fail("ERROR!!!: Expected to read {0} actual read char {1}", expectedChars[i], (char)readInt); } i++; } Assert.Equal(expectedChars.Length, i); }
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer if (com1.BytesToRead != bytesToWrite.Length) { Fail("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); } }
public void InBufferFilled_Discard_Once() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { com1.Open(); com2.Open(); com2.Write(DEFAULT_STRING); TCSupport.WaitForReadBufferToLoad(com1, DEFAULT_STRING.Length); VerifyDiscard(com1); } }
public void GreedyRead() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { byte[] byteXmitBuffer = new byte[1024]; char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); int charRead; Debug.WriteLine("Verifying that ReadChar() will read everything from internal buffer and drivers buffer"); //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; TCSupport.SetHighSpeed(com1, com2); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback { com2.Open(); } com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); Assert.Equal(1, com1.BytesToRead); com1.Encoding = Encoding.UTF32; com2.Write(utf32CharBytes, 1, 3); TCSupport.WaitForReadBufferToLoad(com1, 4); if (utf32Char != (charRead = com1.ReadChar())) { Fail("Err_6481sfadw ReadChar() returned={0} expected={1}", charRead, utf32Char); } Assert.Equal(0, com1.BytesToRead); } }
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char c = TCSupport.GenerateRandomCharNonSurrogate(); byte[] bytesForSingleChar = com1.Encoding.GetBytes(new char[] { c }, 0, 1); com2.Write(bytesForSingleChar, 0, bytesForSingleChar.Length); // Write one byte at the beginning because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer Assert.Equal(bytesToWrite.Length, com1.BytesToRead); }
public void InOutBufferFilled_Flush_Multiple() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, DEFAULT_BUFFER_SIZE); Thread t = new Thread(asyncWriteRndByteArray.WriteRndByteArray); int elapsedTime = 0; byte[] xmitBytes = new byte[DEFAULT_BUFFER_SIZE]; Debug.WriteLine( "Verifying call Flush method several times after input and output buffer has been filled"); com1.Open(); com2.Open(); com1.WriteTimeout = 500; com1.Handshake = Handshake.RequestToSend; for (int i = 0; i < xmitBytes.Length; i++) { xmitBytes[i] = (byte)i; } com2.Write(xmitBytes, 0, xmitBytes.Length); TCSupport.WaitForReadBufferToLoad(com1, DEFAULT_BUFFER_SIZE); t.Start(); elapsedTime = 0; while (com1.BytesToWrite < DEFAULT_BUFFER_LENGTH && elapsedTime < MAX_WAIT_TIME) { Thread.Sleep(50); elapsedTime += 50; } VerifyFlush(com1); VerifyFlush(com1); VerifyFlush(com1); // Wait for write method to timeout while (t.IsAlive) { Thread.Sleep(100); } } }
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { char[] buffer = new char[expectedChars.Length]; int totalBytesRead; int totalCharsRead; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); totalBytesRead = 0; totalCharsRead = 0; Stopwatch sw = Stopwatch.StartNew(); while (0 != com1.BytesToRead) { //While their are more characters to be read string rcvString = com1.ReadExisting(); char[] rcvBuffer = rcvString.ToCharArray(); int charsRead = rcvBuffer.Length; int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); } Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead); totalBytesRead += bytesRead; totalCharsRead += charsRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } Assert.True(sw.ElapsedMilliseconds < 5000, "Timeout waiting for read data"); } //Compare the chars that were written with the ones we expected to read Assert.Equal(expectedChars, buffer); }
public void InBufferFilled_Discard_Multiple() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Debug.WriteLine("Verifying call Discard method several times after input buffer has been filled"); com1.Open(); com2.Open(); com2.Write(DEFAULT_STRING); TCSupport.WaitForReadBufferToLoad(com1, DEFAULT_STRING.Length); VerifyDiscard(com1); VerifyDiscard(com1); VerifyDiscard(com1); } }
public void AsyncResult_MultipleOutOfOrder() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { int endReadReturnValue; int numBytesToRead1 = 8, numBytesToRead2 = 16, numBytesToRead3 = 10; int totalBytesToRead = numBytesToRead1 + numBytesToRead2 + numBytesToRead3; Debug.WriteLine( "Verifying calling EndRead with different asyncResults out of order returned from BeginRead"); com1.Open(); com2.Open(); com2.Write(new byte[totalBytesToRead], 0, totalBytesToRead); TCSupport.WaitForReadBufferToLoad(com1, totalBytesToRead); IAsyncResult readAsyncResult1 = com1.BaseStream.BeginRead(new byte[numBytesToRead1], 0, numBytesToRead1, null, null); IAsyncResult readAsyncResult2 = com1.BaseStream.BeginRead(new byte[numBytesToRead2], 0, numBytesToRead2, null, null); IAsyncResult readAsyncResult3 = com1.BaseStream.BeginRead(new byte[numBytesToRead3], 0, numBytesToRead3, null, null); if (numBytesToRead2 != (endReadReturnValue = com1.BaseStream.EndRead(readAsyncResult2))) { Fail("ERROR!!! Expected EndRead to return={0} actual={1} for second read", numBytesToRead2, endReadReturnValue); } if (numBytesToRead3 != (endReadReturnValue = com1.BaseStream.EndRead(readAsyncResult3))) { Fail("ERROR!!! Expected EndRead to return={0} actual={1} for third read", numBytesToRead3, endReadReturnValue); } if (numBytesToRead1 != (endReadReturnValue = com1.BaseStream.EndRead(readAsyncResult1))) { Fail("ERROR!!! Expected EndRead to return={0} actual={1} for first read", numBytesToRead1, endReadReturnValue); } } // Give the port time to finish closing since we potentially have an unclosed BeginRead/BeginWrite Thread.Sleep(200); }
public void ReceivedBytesThreshold_Above_Below() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; com1.Open(); com2.Open(); com1.DataReceived += rcvEventHandler.HandleEvent; serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold - 1); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); Debug.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then setting " + "ReceivedBytesThreshold to less then the number of bytes written"); com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); TCSupport.WaitForReadBufferToLoad(com1, receivedBytesThreshold); if (0 != rcvEventHandler.NumEventsHandled) { Fail("ERROR!!! Unexpected ReceivedEvent was firered NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); } else { com1.ReceivedBytesThreshold = receivedBytesThreshold - 1; rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); } com1.DiscardInBuffer(); serPortProp.VerifyPropertiesAndPrint(com1); rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } }
private void VerifyWriteBufferSize(SerialPort com1, int expectedWriteBufferSize) { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { byte[] xmitBytes = new byte[Math.Max(expectedWriteBufferSize, com1.WriteBufferSize)]; byte[] rcvBytes = new byte[xmitBytes.Length]; SerialPortProperties serPortProp = new SerialPortProperties(); Random rndGen = new Random(-55); for (int i = 0; i < xmitBytes.Length; i++) { xmitBytes[i] = (byte)rndGen.Next(0, 256); } serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com2.ReadBufferSize = expectedWriteBufferSize; serPortProp.SetProperty("WriteBufferSize", expectedWriteBufferSize); com2.Open(); int origBaudRate = com1.BaudRate; com2.BaudRate = 115200; com1.BaudRate = 115200; serPortProp.SetProperty("BaudRate", 115200); com1.Write(xmitBytes, 0, xmitBytes.Length); TCSupport.WaitForReadBufferToLoad(com2, xmitBytes.Length); Debug.WriteLine("Verifying properties after changing WriteBufferSize"); serPortProp.VerifyPropertiesAndPrint(com1); com2.Read(rcvBytes, 0, rcvBytes.Length); Assert.Equal(xmitBytes, rcvBytes); com2.BaudRate = origBaudRate; com1.BaudRate = origBaudRate; } }
public void ReadTimeout_0_1ByteAvailable_ReadByte() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { int byteRead; Debug.WriteLine("Verifying 0 ReadTimeout with ReadByte() and one byte available"); com1.Open(); com2.Open(); Stream stream = com1.BaseStream; stream.ReadTimeout = 0; com2.Write(new byte[] { 50 }, 0, 1); TCSupport.WaitForReadBufferToLoad(com1, 1); Assert.True(50 == (byteRead = com1.ReadByte()), string.Format("Err_05949aypa, Expected to Read to return 50 actual={0}", byteRead)); } }
public void EndReadAfterSerialStreamClose() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Debug.WriteLine("Verifying EndRead method throws exception after a call to BaseStream.Close()"); com1.Open(); com2.Open(); Stream serialStream = com1.BaseStream; IAsyncResult asyncResult = com1.BaseStream.BeginRead(new byte[8], 0, 8, null, null); com2.Write(new byte[16], 0, 16); TCSupport.WaitForReadBufferToLoad(com1, 1); com1.BaseStream.Close(); VerifyEndReadException(serialStream, asyncResult, null); } // Give the port time to finish closing since we potentially have an unclosed BeginRead/BeginWrite Thread.Sleep(200); }
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, ReadMethodDelegate readMethod, bool newLine) { com2.Write(bytesToWrite, 0, bytesToWrite.Length); if (newLine) { com2.Write(com1.NewLine); while (bytesToWrite.Length + com1.NewLine.Length > com1.BytesToRead) { } } else { TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); } char[] actualChars = readMethod(com1); //Compare the chars that were written with the ones we expected to read for (int i = 0; i < expectedChars.Length; i++) { if (actualChars.Length <= i) { Fail("ERROR!!!: Expected more characters then were actually read"); } else if (expectedChars[i] != actualChars[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)actualChars[i], i); } } if (actualChars.Length > expectedChars.Length) { Fail("ERROR!!!: Read in more characters then expected"); } }
public void GreedyRead() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(128, TCSupport.CharacterOptions.Surrogates); byte[] byteXmitBuffer = new byte[1024]; char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); int numBytes; Debug.WriteLine("Verifying that ReadTo() will read everything from internal buffer and drivers buffer"); //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback { com2.Open(); } com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); Assert.Equal(1, com1.BytesToRead); com1.Encoding = Encoding.UTF32; com2.Encoding = Encoding.UTF32; com2.Write(utf32CharBytes, 1, 3); com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); com2.WriteLine(string.Empty); numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer); byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer); char[] expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)]; expectedChars[0] = utf32Char; Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); TCSupport.WaitForReadBufferToLoad(com1, 4 + numBytes); string rcvString = com1.ReadTo(com2.NewLine); Assert.NotNull(rcvString); Assert.Equal(expectedChars, rcvString.ToCharArray()); Assert.Equal(0, com1.BytesToRead); } }
public void ParityErrorOnLastByte() { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var rndGen = new Random(15); var bytesToWrite = new byte[numRndBytesPairty]; var expectedBytes = new byte[numRndBytesPairty]; var actualBytes = new byte[numRndBytesPairty + 1]; IAsyncResult readAsyncResult; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream * We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); // Generate random characters without an parity error for (var i = 0; i < bytesToWrite.Length; i++) { var randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedBytes[i] = randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); // Create a parity error on the last byte expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; // Set the last expected byte to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); readAsyncResult = com2.BaseStream.BeginWrite(bytesToWrite, 0, bytesToWrite.Length, null, null); readAsyncResult.AsyncWaitHandle.WaitOne(); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1); com1.Read(actualBytes, 0, actualBytes.Length); // Compare the chars that were written with the ones we expected to read for (var i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != actualBytes[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i], (int)actualBytes[i]); } } if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); // Clear the parity error on the last byte expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedBytes, expectedBytes.Length / 2); } }
private void PerformWriteRead(SerialPort com1, SerialPort com2, byte[] xmitBytes, byte[] expectedBytes) { byte[] rcvBytes = new byte[expectedBytes.Length * 4]; Stopwatch sw = new Stopwatch(); double expectedTime, actualTime, percentageDifference; int numParityBits = (Parity)com1.Parity == Parity.None ? 0 : 1; double numStopBits = GetNumberOfStopBits(com1); int length = xmitBytes.Length; int rcvLength; // TODO: Consider removing all of the code to check the time it takes to transfer the bytes. // This was likely just a copy and paste from another test case actualTime = 0; Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { com2.DiscardInBuffer(); IAsyncResult beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, length, null, null); while (0 == com2.BytesToRead) { ; } sw.Start(); // Wait for all of the bytes to reach the input buffer of com2 TCSupport.WaitForReadBufferToLoad(com2, length); sw.Stop(); actualTime += sw.ElapsedMilliseconds; com1.BaseStream.EndWrite(beginWriteResult); sw.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; expectedTime = ((xmitBytes.Length * (1 + numStopBits + com1.DataBits + numParityBits)) / com1.BaudRate) * 1000; percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime); //If the percentageDifference between the expected time and the actual time is to high //then the expected baud rate must not have been used and we should report an error if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference) { Fail("ERROR!!! Parity not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference); } rcvLength = com2.Read(rcvBytes, 0, rcvBytes.Length); if (0 != com2.BytesToRead) { Fail("ERROR!!! BytesToRead={0} expected 0", com2.BytesToRead); } //Verify that the bytes we sent were the same ones we received int expectedIndex = 0, actualIndex = 0; for (; expectedIndex < expectedBytes.Length && actualIndex < rcvBytes.Length; ++expectedIndex, ++actualIndex) { if (expectedBytes[expectedIndex] != rcvBytes[actualIndex]) { if (actualIndex != rcvBytes.Length - 1 && expectedBytes[expectedIndex] == rcvBytes[actualIndex + 1]) { //Sometimes if there is a parity error an extra byte gets added to the input stream so //look ahead at the next byte actualIndex++; } else { Debug.WriteLine("Bytes Sent:"); TCSupport.PrintBytes(xmitBytes); Debug.WriteLine("Bytes Received:"); TCSupport.PrintBytes(rcvBytes); Debug.WriteLine("Expected Bytes:"); TCSupport.PrintBytes(expectedBytes); Fail( "ERROR: Expected to read {0,2:X} at {1,3} actually read {2,2:X} sent {3,2:X}", expectedBytes[expectedIndex], expectedIndex, rcvBytes[actualIndex], xmitBytes[expectedIndex]); } } } if (expectedIndex < expectedBytes.Length) { Fail("ERRROR: Did not enumerate all of the expected bytes index={0} length={1}", expectedIndex, expectedBytes.Length); } }
public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndByte]; byte[] expectedBytes = new byte[numRndByte]; byte[] actualBytes = new byte[numRndByte + 1]; int actualByteIndex = 0; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream * We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity error on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedBytes[i] = randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; // Set the last expected byte to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1); while (true) { int byteRead; try { byteRead = com1.ReadByte(); } catch (TimeoutException) { break; } actualBytes[actualByteIndex] = (byte)byteRead; actualByteIndex++; } //Compare the chars that were written with the ones we expected to read for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != actualBytes[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i], (int)actualBytes[i]); } } if (1 < com1.BytesToRead) { Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedBytes, Encoding.ASCII); } }
public void GreedyRead() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(-55); char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.Surrogates); byte[] byteXmitBuffer = new byte[1024]; char utf32Char = (char)8169; byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); int numCharsRead; Debug.WriteLine( "Verifying that Read(char[], int, int) will read everything from internal buffer and drivers buffer"); for (int i = 0; i < byteXmitBuffer.Length; i++) { byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); } //Put the first byte of the utf32 encoder char in the last byte of this buffer //when we read this later the buffer will have to be resized byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; TCSupport.SetHighSpeed(com1, com2); com1.Open(); if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback { com2.Open(); } com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length); //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so //the other 3 bytes of the ut32 encoded char can be in the buffer com1.Read(new char[1023], 0, 1023); Assert.Equal(1, com1.BytesToRead); com1.Encoding = Encoding.UTF32; com2.Encoding = Encoding.UTF32; com2.Write(utf32CharBytes, 1, 3); com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); int numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer); byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer); var expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)]; expectedChars[0] = utf32Char; Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); var charRcvBuffer = new char[(int)(expectedChars.Length * 1.5)]; TCSupport.WaitForReadBufferToLoad(com1, 4 + numBytes); if (expectedChars.Length != (numCharsRead = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length))) { Fail("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedChars.Length, numCharsRead); } Assert.Equal(expectedChars, charRcvBuffer.Take(expectedChars.Length).ToArray()); Assert.Equal(0, com1.BytesToRead); } }