private void VerifyReadExisting(Encoding encoding) { string text = "Za\u017C\u00F3\u0142\u0107 g\u0119\u015Bl\u0105 ja\u017A\u0144"; using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { com1.ReadTimeout = 500; com1.Encoding = encoding; com2.Encoding = encoding; 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(); } string receivedstr = ""; com2.DataReceived += (sender, args) => { receivedstr += com2.ReadExisting(); }; com1.Write(text); //3 seconds is more than enough time to write a few bytes to the other port TCSupport.WaitForPredicate(() => receivedstr.Length >= text.Length, 3000, "Data was not returned in a timely fashion. Timeout"); Assert.Equal(text, receivedstr); } }
public bool String_Null_Char() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); bool retValue = true; Console.WriteLine("Verifying Write with an string containing only the null character"); 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(); } retValue &= VerifyWriteStr(com1, com2, "\0"); if (!retValue) { Console.WriteLine("Err_008!!! Verifying Write with an string containing only the null character FAILED"); } return(retValue); }
public bool VerifyReadExisting(System.Text.Encoding encoding) { string text = "????????????4??????????????????,?11????????????????????????????????????????????????,????????????,??????????"; s_com1 = TCSupport.InitFirstSerialPort(); s_com2 = TCSupport.InitSecondSerialPort(s_com1); s_com1.ReadTimeout = 500; s_com1.Encoding = encoding; s_com2.Encoding = encoding; s_com1.Open(); if (!s_com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback { s_com2.Open(); } s_com2.DataReceived += com2_DataReceived; s_com1.Write(text); //3 seconds is more than enough time to write a few bytes to the other port TCSupport.WaitForPredicate(delegate() { return(s_readComplete == true); }, 3000, "ReadExisting did not complete in a timely fashion. Timeout"); if (String.Compare(s_receivedstr, text) == 0) { Console.WriteLine("Received and Sent strings are the same"); return(true); } else { Console.WriteLine("Received and Sent strings are different"); Console.WriteLine("Sent string:" + text); Console.WriteLine("Received string:" + s_receivedstr); return(false); } }
public bool EmptyString() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); bool retValue = true; Console.WriteLine("Verifying Write with an empty string"); 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(); } retValue &= VerifyWriteLine(com1, com2, ""); if (!retValue) { Console.WriteLine("Err_007!!! Verifying Write with an empty string FAILED"); } return(retValue); }
private void VerifyLongTimeout(ReadMethodDelegate readMethod, int readTimeout) { using (var com1 = TCSupport.InitFirstSerialPort()) using (var com2 = TCSupport.InitSecondSerialPort(com1)) { com1.Open(); if (!com2.IsOpen) { com2.Open(); } com1.BaseStream.WriteTimeout = 1; com1.BaseStream.ReadTimeout = 1; com1.BaseStream.ReadTimeout = readTimeout; Assert.True(readTimeout == com1.BaseStream.ReadTimeout, string.Format("Err_7071ahpsb!!! Expected ReadTimeout to be {0} actaul {1}", readTimeout, com1.BaseStream.ReadTimeout)); VerifyLongTimeout(readMethod, com1, com2); } }
public void GreedyRead() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(); byte[] byteXmitBuffer = new byte[1024]; byte[] expectedBytes = new byte[byteXmitBuffer.Length + 4]; byte[] byteRcvBuffer; char utf32Char = (char)8169; byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char }); int numBytesRead; Debug.WriteLine( "Verifying that Read(byte[], int, int) will read everything from internal buffer and drivers buffer"); for (int i = 0; i < utf32CharBytes.Length; i++) { expectedBytes[i] = utf32CharBytes[i]; } for (int i = 0; i < byteXmitBuffer.Length; i++) { byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); expectedBytes[i + 4] = byteXmitBuffer[i]; } //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]; expectedBytes[byteXmitBuffer.Length + 4 - 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); if (1 != com1.BytesToRead) { Fail("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); } com2.Write(utf32CharBytes, 1, 3); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); byteRcvBuffer = new byte[(int)(expectedBytes.Length * 1.5)]; TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length); if (expectedBytes.Length != (numBytesRead = com1.Read(byteRcvBuffer, 0, byteRcvBuffer.Length))) { Fail("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedBytes.Length, numBytesRead); } for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != byteRcvBuffer[i]) { Fail("Err_70782apzh Expected to read {0} actually read {1} at {2}", (int)expectedBytes[i], (int)byteRcvBuffer[i], i); } } if (0 != com1.BytesToRead) { Fail("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); } } }
public bool Read_Surrogate() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); char[] surrogateChars = new char[] { (char)0xDB26, (char)0xDC49 }; char[] additionalChars = TCSupport.GetRandomChars(32, TCSupport.CharacterOptions.None); char[] charRcvBuffer = new char[2]; int numBytes; bool retValue = true; int result; Console.WriteLine("Verifying that ReadChar works correctly when trying to read surrogate characters"); com1.Encoding = new System.Text.UTF32Encoding(); com2.Encoding = new System.Text.UTF32Encoding(); com1.ReadTimeout = 500; // 20 seconds 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(); } numBytes = com2.Encoding.GetByteCount(surrogateChars); numBytes += com2.Encoding.GetByteCount(additionalChars); com2.Write(surrogateChars, 0, 2); com2.Write(additionalChars, 0, additionalChars.Length); retValue &= TCSupport.WaitForExpected(delegate() { return(com1.BytesToRead); }, numBytes, 5000, "Err_91818aheid BytesToRead"); try { com1.ReadChar(); retValue = false; Console.WriteLine("Err_11919aueic Expected ReadChar() to throw when reading a surrogate"); } catch (ArgumentException) { } //Expected result = com1.Read(charRcvBuffer, 0, 2); if (2 != result) { retValue = false; Console.WriteLine("Err_2829aheid Expected to Read 2 chars instead read={0}", result); } else if (charRcvBuffer[0] != surrogateChars[0]) { retValue = false; Console.WriteLine("Err_12929anied Expected first char read={0}({1:X}) actually read={2}({3:X})", surrogateChars[0], (int)surrogateChars[0], charRcvBuffer[0], (int)charRcvBuffer[0]); } else if (charRcvBuffer[1] != surrogateChars[1]) { Console.WriteLine("Err_12929anied Expected second char read={0}({1:X}) actually read={2}({3:X})", surrogateChars[1], (int)surrogateChars[1], charRcvBuffer[1], (int)charRcvBuffer[1]); } if (!PerformReadOnCom1FromCom2(com1, com2, additionalChars)) { Console.WriteLine("Err_01588akeid Verify ReadChar after read failed"); retValue = false; } if (!retValue) { Console.WriteLine("Err_0154688aieide Verifying that ReadChar works correctly when trying to read surrogate characters failed"); } com1.Close(); com2.Close(); return(retValue); }
public void Read_LargeBuffer() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); bool continueRunning = true; int numberOfIterations = 0; var writeToCom2Task = new Task(delegate() { while (continueRunning) { com1.Write(charXmitBuffer, 0, charXmitBuffer.Length); ++numberOfIterations; } }); char endChar = TCSupport.GenerateRandomCharNonSurrogate(); char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); //Ensure the new line is not in charXmitBuffer for (int i = 0; i < charXmitBuffer.Length; ++i) { //Se any appearances of a character in the new line string to some other char if (endChar == charXmitBuffer[i]) { charXmitBuffer[i] = notEndChar; } } com1.BaudRate = 115200; com2.BaudRate = 115200; com1.Encoding = Encoding.Unicode; com2.Encoding = Encoding.Unicode; com2.ReadTimeout = 10000; 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(); } writeToCom2Task.Start(); Assert.Throws <TimeoutException>(() => com2.ReadTo(new string(endChar, 1))); continueRunning = false; writeToCom2Task.Wait(); com1.Write(new string(endChar, 1)); string stringRcvBuffer = com2.ReadTo(new string(endChar, 1)); if (charXmitBuffer.Length * numberOfIterations == stringRcvBuffer.Length) { for (int i = 0; i < charXmitBuffer.Length * numberOfIterations; ++i) { if (stringRcvBuffer[i] != charXmitBuffer[i % charXmitBuffer.Length]) { Fail("Err_292aneid Expected to read {0} actually read {1}", charXmitBuffer[i % charXmitBuffer.Length], stringRcvBuffer[i]); break; } } } else { Fail("Err_292haie Expected to read {0} characters actually read {1}", charXmitBuffer.Length * numberOfIterations, stringRcvBuffer.Length); } } }
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); } }
private void VerifyBytesFollowedByChars(Encoding encoding) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] xmitCharBuffer = TCSupport.GetRandomChars(numRndBytesToRead, TCSupport.CharacterOptions.Surrogates); char[] rcvCharBuffer = new char[xmitCharBuffer.Length]; byte[] xmitByteBuffer = new byte[numRndBytesToRead]; byte[] rcvByteBuffer = new byte[xmitByteBuffer.Length]; Random rndGen = new Random(-55); int numRead; Debug.WriteLine("Verifying read method does not alter stream of bytes after chars have been read with {0}", encoding.GetType()); for (int i = 0; i < xmitByteBuffer.Length; i++) { xmitByteBuffer[i] = (byte)rndGen.Next(0, 256); } com1.Encoding = encoding; com2.Encoding = encoding; com1.ReadTimeout = 500; 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(xmitCharBuffer, 0, xmitCharBuffer.Length); com2.Write(xmitByteBuffer, 0, xmitByteBuffer.Length); Thread.Sleep( (int) (((xmitByteBuffer.Length + com2.Encoding.GetByteCount(xmitCharBuffer) * 10.0) / com1.BaudRate) * 1000) + 500); Thread.Sleep(500); if (xmitCharBuffer.Length != (numRead = com1.Read(rcvCharBuffer, 0, rcvCharBuffer.Length))) { Fail("ERROR!!!: Expected to read {0} chars actually read {1}", xmitCharBuffer.Length, numRead); } if (IsUTF7Encoding(encoding)) { Fail("UTF-7 encoding not expected to be passed to this test."); } if (xmitByteBuffer.Length != (numRead = com1.Read(rcvByteBuffer, 0, rcvByteBuffer.Length))) { Fail("ERROR!!!: Expected to read {0} bytes actually read {1}", xmitByteBuffer.Length, numRead); } for (int i = 0; i < xmitByteBuffer.Length; i++) { if (xmitByteBuffer[i] != rcvByteBuffer[i]) { Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)xmitByteBuffer[i], (int)rcvByteBuffer[i], i); } } Assert.Equal(0, com1.BytesToRead); /*DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG * if (!retValue) { * for (int i=0; i<xmitCharBuffer.Length; ++i) { * Debug.WriteLine("(char){0}, ", (int)xmitCharBuffer[i]); * } * * for (int i=0; i<xmitCharBuffer.Length; ++i) { * Debug.WriteLine("{0}, ", (int)xmitByteBuffer[i]); * } * }*/ } }
private bool VerifyReadToWithWriteLine(System.Text.Encoding encoding, string newLine) { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); Random rndGen = new Random(-55); System.Text.StringBuilder strBldrToWrite = new System.Text.StringBuilder(); string strRead, strWrite; string strExpected; bool retValue = true; bool isUTF7Encoding = encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName; Console.WriteLine("Verifying ReadTo with WriteLine encoding={0}, newLine={1}", encoding, newLine); com1.ReadTimeout = 500; com2.NewLine = newLine; com1.Encoding = encoding; com2.Encoding = encoding; //Genrate random characters do { strBldrToWrite = new System.Text.StringBuilder(); for (int i = 0; i < DEFAULT_NUM_CHARS_TO_READ; i++) { strBldrToWrite.Append((char)rndGen.Next(0, 128)); } } while (-1 != TCSupport.OrdinalIndexOf(strBldrToWrite.ToString(), newLine));//SerialPort does a Ordinal comparison strWrite = strBldrToWrite.ToString(); strExpected = new string(com1.Encoding.GetChars(com1.Encoding.GetBytes(strWrite.ToCharArray()))); 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.WriteLine(strBldrToWrite.ToString()); strRead = com1.ReadTo(newLine); if (0 != strBldrToWrite.ToString().CompareTo(strRead)) { Console.WriteLine("ERROR!!! The string written: \"{0}\" and the string read \"{1}\" differ", strBldrToWrite, strRead); retValue = false; } if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) { Console.WriteLine("ERROR!!! BytesToRead={0} expected 0", com1.BytesToRead); retValue = false; } if (com1.IsOpen) { com1.Close(); } if (com2.IsOpen) { com2.Close(); } return(retValue); }
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); } }
public bool GreedyRead() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); Random rndGen = new Random(-55); char[] charXmitBuffer = TCSupport.GetRandomChars(128, true); byte[] byteXmitBuffer = new byte[1024]; char[] expectedChars; string rcvString; char[] actualChars; char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); int numBytes; bool retValue = true; Console.WriteLine("Verifying that ReadExisting() 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); while (com1.BytesToRead < byteXmitBuffer.Length) { System.Threading.Thread.Sleep(50); } //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); if (1 != com1.BytesToRead) { Console.WriteLine("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); retValue = false; } com1.Encoding = System.Text.Encoding.UTF32; com2.Encoding = System.Text.Encoding.UTF32; com2.Write(utf32CharBytes, 1, 3); com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); numBytes = System.Text.Encoding.UTF32.GetByteCount(charXmitBuffer); byte[] byteBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); expectedChars = new char[1 + System.Text.Encoding.UTF32.GetCharCount(byteBuffer)]; expectedChars[0] = utf32Char; System.Text.Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); while (com1.BytesToRead < 4 + numBytes) { System.Threading.Thread.Sleep(50); } if (null == (rcvString = com1.ReadExisting())) { Console.WriteLine("Err_6481sfadw ReadExisting returned null"); retValue = false; } else { actualChars = rcvString.ToCharArray(); if (actualChars.Length != expectedChars.Length) { Console.WriteLine("Err_0872watr Expected to read {0} chars actually read {1} chars", expectedChars.Length, actualChars.Length); retValue = false; } else { for (int i = 0; i < expectedChars.Length; i++) { if (expectedChars[i] != actualChars[i]) { Console.WriteLine("Err_70782apzh Expected to read {0} actually read {1}", (int)expectedChars[i], (int)actualChars[i]); retValue = false; break; } } } } if (0 != com1.BytesToRead) { Console.WriteLine("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); retValue = false; } if (!retValue) { Console.WriteLine("Err_1389 Verifying that ReadExisting() will read everything from internal buffer and drivers buffer failed"); } com1.Close(); com2.Close(); return(retValue); }
public bool Read_LargeBuffer() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); string stringRcvBuffer; bool retValue = true; bool continueRunning = true; int numberOfIterations = 0; System.Threading.Thread writeToCom2Thread = new System.Threading.Thread(delegate() { while (continueRunning) { com1.Write(charXmitBuffer, 0, charXmitBuffer.Length); ++numberOfIterations; } }); char endChar = TCSupport.GenerateRandomCharNonSurrogate(); char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); //Ensure the new line is not in charXmitBuffer for (int i = 0; i < charXmitBuffer.Length; ++i) {//Se any appearances of a character in the new line string to some other char if (endChar == charXmitBuffer[i]) { charXmitBuffer[i] = notEndChar; } } com1.BaudRate = 115200; com2.BaudRate = 115200; com1.Encoding = System.Text.Encoding.Unicode; com2.Encoding = System.Text.Encoding.Unicode; com2.ReadTimeout = 10000; 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(); } writeToCom2Thread.Start(); try { com2.ReadTo(new String(endChar, 1)); retValue = false; Console.WriteLine("Err_2928aneieud Expected ReadLine() to throw timeoutException()"); } catch (TimeoutException) { }; continueRunning = false; writeToCom2Thread.Join(); com1.Write(new string(endChar, 1)); stringRcvBuffer = com2.ReadTo(new String(endChar, 1)); if (charXmitBuffer.Length * numberOfIterations == stringRcvBuffer.Length) { for (int i = 0; i < charXmitBuffer.Length * numberOfIterations; ++i) { if (stringRcvBuffer[i] != charXmitBuffer[i % charXmitBuffer.Length]) { retValue = false; Console.WriteLine("Err_292aneid Expected to read {0} actually read {1}", charXmitBuffer[i % charXmitBuffer.Length], stringRcvBuffer[i]); break; } } } else { retValue = false; Console.WriteLine("Err_292haie Expected to read {0} characters actually read {1}", charXmitBuffer.Length * numberOfIterations, stringRcvBuffer.Length); } com1.Close(); com2.Close(); return(retValue); }
public bool Read_Timeout() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); char[] charRcvBuffer; string endString = "END"; bool retValue = true; char endChar = endString[0]; char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); string result; Console.WriteLine("Verifying that ReadTo(string) works appropriately after TimeoutException has been thrown"); //Ensure the new line is not in charXmitBuffer for (int i = 0; i < charXmitBuffer.Length; ++i) {//Se any appearances of a character in the new line string to some other char if (endChar == charXmitBuffer[i]) { charXmitBuffer[i] = notEndChar; } } com1.Encoding = System.Text.Encoding.Unicode; com2.Encoding = System.Text.Encoding.Unicode; com1.ReadTimeout = 500; // 20 seconds 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(charXmitBuffer, 0, charXmitBuffer.Length); try { com1.ReadTo(endString); Console.WriteLine("Err_29299aize Expected ReadTo to throw TimeoutException"); retValue = false; } catch (TimeoutException) { }//Expected if (2 * charXmitBuffer.Length != com1.BytesToRead) { Console.WriteLine("Err_0585haieidp Expected BytesToRead: {0} actual: {1}", 2 * charXmitBuffer.Length, com1.BytesToRead); retValue = false; } com2.Write(endString); result = com1.ReadTo(endString); charRcvBuffer = result.ToCharArray(); if (charRcvBuffer.Length != charXmitBuffer.Length) { retValue = false; Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", charXmitBuffer.Length, charRcvBuffer.Length); } else { for (int i = 0; i < charXmitBuffer.Length; ++i) { if (charRcvBuffer[i] != charXmitBuffer[i]) { retValue = false; Console.WriteLine("Err_8988auzobn Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); } } } if (!VerifyReadTo(com1, com2, new string(charXmitBuffer), endString)) { Console.WriteLine("Err_05188ajied Verify ReadTo after read failed"); retValue = false; } if (!retValue) { Console.WriteLine("Err_05498352aiiueid Verifying that ReadTo(string) works appropriately after TimeoutException has been thrown failed"); } com1.Close(); com2.Close(); return(retValue); }
public void Read_DataReceivedBeforeTimeout() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { byte[] byteXmitBuffer = TCSupport.GetRandomBytes(512); byte[] byteRcvBuffer = new byte[byteXmitBuffer.Length]; ASyncRead asyncRead = new ASyncRead(com1, byteRcvBuffer, 0, byteRcvBuffer.Length); var asyncReadTask = new Task(asyncRead.Read); Debug.WriteLine( "Verifying that Read(byte[], int, int) will read characters that have been received after the call to Read was made"); com1.Encoding = Encoding.UTF8; com2.Encoding = Encoding.UTF8; com1.ReadTimeout = 20000; // 20 seconds 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(); } asyncReadTask.Start(); asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); asyncRead.ReadCompletedEvent.WaitOne(); if (null != asyncRead.Exception) { Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); } else if (asyncRead.Result < 1) { Fail("Err_0158ahei Expected Read to read at least one character {0}", asyncRead.Result); } else { Thread.Sleep(1000); //We need to wait for all of the bytes to be received int readResult = com1.Read(byteRcvBuffer, asyncRead.Result, byteRcvBuffer.Length - asyncRead.Result); if (asyncRead.Result + readResult != byteXmitBuffer.Length) { Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", byteXmitBuffer.Length - asyncRead.Result, readResult); } else { for (int i = 0; i < byteXmitBuffer.Length; ++i) { if (byteRcvBuffer[i] != byteXmitBuffer[i]) { Fail( "Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", i, byteXmitBuffer[i], byteRcvBuffer[i], asyncRead.Result); } } } } TCSupport.WaitForTaskCompletion(asyncReadTask); } }
public void Read_SurrogateBoundary() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = new char[32]; int result; Debug.WriteLine("Verifying that Read(char[], int, int) works with reading surrogate characters"); TCSupport.GetRandomChars(charXmitBuffer, 0, charXmitBuffer.Length - 2, TCSupport.CharacterOptions.Surrogates); charXmitBuffer[charXmitBuffer.Length - 2] = TCSupport.GenerateRandomHighSurrogate(); charXmitBuffer[charXmitBuffer.Length - 1] = TCSupport.GenerateRandomLowSurrogate(); com1.Encoding = Encoding.Unicode; com2.Encoding = Encoding.Unicode; com1.ReadTimeout = 500; 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(); } //[] First lets try with buffer size that is larger then what we are asking for com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); TCSupport.WaitForExpected(() => com1.BytesToRead, charXmitBuffer.Length * 2, 5000, "Err_018158ajid BytesToRead"); var charRcvBuffer = new char[charXmitBuffer.Length]; result = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1); Assert.Equal(charXmitBuffer.Length - 2, result); char[] actualChars = new char[charXmitBuffer.Length]; Array.Copy(charRcvBuffer, actualChars, result); result = com1.Read(actualChars, actualChars.Length - 2, 2); Assert.Equal(2, result); Assert.Equal(charXmitBuffer, actualChars); //[] Next lets try with buffer size that is the same size as what we are asking for com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); TCSupport.WaitForExpected(() => com1.BytesToRead, charXmitBuffer.Length * 2, 5000, "Err_018158ajid BytesToRead"); charRcvBuffer = new char[charXmitBuffer.Length - 1]; result = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1); Assert.Equal(charXmitBuffer.Length - 2, result); actualChars = new char[charXmitBuffer.Length]; Array.Copy(charRcvBuffer, actualChars, result); result = com1.Read(actualChars, actualChars.Length - 2, 2); Assert.Equal(2, result); Assert.Equal(charXmitBuffer, actualChars); } }
public void Read_Timeout() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); byte[] byteXmitBuffer = new System.Text.UTF32Encoding().GetBytes(charXmitBuffer); char[] charRcvBuffer = new char[charXmitBuffer.Length]; int result; Debug.WriteLine( "Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown"); com1.Encoding = new System.Text.UTF32Encoding(); com2.Encoding = new System.Text.UTF32Encoding(); com1.ReadTimeout = 500; // 20 seconds 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(); } //Write the first 3 bytes of a character com2.Write(byteXmitBuffer, 0, 3); Assert.Throws <TimeoutException>(() => com1.ReadChar()); Assert.Equal(3, com1.BytesToRead); com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3); TCSupport.WaitForExpected(() => com1.BytesToRead, byteXmitBuffer.Length, 5000, "Err_91818aheid BytesToRead"); result = com1.ReadChar(); if (result != charXmitBuffer[0]) { Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], result); } else { charRcvBuffer[0] = (char)result; int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); if (readResult + 1 != charXmitBuffer.Length) { Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length - 1, readResult); } else { for (int i = 0; i < charXmitBuffer.Length; ++i) { if (charRcvBuffer[i] != charXmitBuffer[i]) { Fail("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X})", i, charXmitBuffer[i], charRcvBuffer[i]); } } } } VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer); } }
public bool Read_DataReceivedBeforeTimeout() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); char[] charRcvBuffer; ASyncRead asyncRead = new ASyncRead(com1); System.Threading.Thread asyncReadThread = new System.Threading.Thread(new System.Threading.ThreadStart(asyncRead.Read)); bool retValue = true; char endLineChar = com1.NewLine[0]; char notEndLineChar = TCSupport.GetRandomOtherChar(endLineChar, TCSupport.CharacterOptions.None); Console.WriteLine("Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made"); //Ensure the new line is not in charXmitBuffer for (int i = 0; i < charXmitBuffer.Length; ++i) {//Se any appearances of a character in the new line string to some other char if (endLineChar == charXmitBuffer[i]) { charXmitBuffer[i] = notEndLineChar; } } com1.Encoding = System.Text.Encoding.UTF8; com2.Encoding = System.Text.Encoding.UTF8; com1.ReadTimeout = 20000; // 20 seconds 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(); } asyncReadThread.Start(); asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); com2.WriteLine(String.Empty); asyncRead.ReadCompletedEvent.WaitOne(); if (null != asyncRead.Exception) { retValue = false; Console.WriteLine("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); } else if (null == asyncRead.Result || 0 == asyncRead.Result.Length) { retValue = false; Console.WriteLine("Err_0158ahei Expected Read to read at least one character"); } else { charRcvBuffer = asyncRead.Result.ToCharArray(); if (charRcvBuffer.Length != charXmitBuffer.Length) { retValue = false; Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", charXmitBuffer.Length, charRcvBuffer.Length); } else { for (int i = 0; i < charXmitBuffer.Length; ++i) { if (charRcvBuffer[i] != charXmitBuffer[i]) { retValue = false; Console.WriteLine("Err_018956ahiaz Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); } } } } if (!VerifyReadLine(com1, com2, new string(charXmitBuffer))) { Console.WriteLine("Err_05188ajied Verify ReadLine after read failed"); retValue = false; } if (!retValue) { Console.WriteLine("Err_018068ajkid Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made failed"); } com1.Close(); com2.Close(); return(retValue); }
public void Read_ResizeBuffer() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(1023, TCSupport.CharacterOptions.ASCII); int readResult; Debug.WriteLine("Verifying that Read(char[], int, int) will compact data in the buffer"); com1.Encoding = Encoding.ASCII; com2.Encoding = Encoding.ASCII; 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(); } //[] Fill the buffer up then read in all but one of the chars var expectedChars = new char[charXmitBuffer.Length - 1]; var charRcvBuffer = new char[charXmitBuffer.Length - 1]; Array.Copy(charXmitBuffer, expectedChars, charXmitBuffer.Length - 1); com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); TCSupport.WaitForPredicate(() => com1.BytesToRead == charXmitBuffer.Length, 2000, "Err_29829haie Expected to received {0} bytes actual={1}", charXmitBuffer.Length, com1.BytesToRead); if (charXmitBuffer.Length - 1 != (readResult = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1))) { Fail("Err_55084aheid Expected to read {0} chars actual {1}", charXmitBuffer.Length - 1, readResult); } TCSupport.VerifyArray(expectedChars, charRcvBuffer); //[] Write 16 more cahrs and read in 16 chars expectedChars = new char[16]; charRcvBuffer = new char[16]; expectedChars[0] = charXmitBuffer[charXmitBuffer.Length - 1]; Array.Copy(charXmitBuffer, 0, expectedChars, 1, 15); com2.Write(charXmitBuffer, 0, 16); TCSupport.WaitForPredicate(() => com1.BytesToRead == 17, 2000, "Err_0516848aied Expected to received {0} bytes actual={1}", 17, com1.BytesToRead); if (16 != (readResult = com1.Read(charRcvBuffer, 0, 16))) { Fail("Err_650848ahide Expected to read {0} chars actual {1}", 16, readResult); } Assert.Equal(expectedChars, charRcvBuffer); //[] Write more chars and read in all of the chars expectedChars = new char[charXmitBuffer.Length + 1]; charRcvBuffer = new char[charXmitBuffer.Length + 1]; expectedChars[0] = charXmitBuffer[15]; Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); TCSupport.WaitForPredicate(() => com1.BytesToRead == charXmitBuffer.Length + 1, 2000, "Err_41515684 Expected to received {0} bytes actual={1}", charXmitBuffer.Length + 2, com1.BytesToRead); if (charXmitBuffer.Length + 1 != (readResult = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length + 1))) { Fail("Err_460574ajied Expected to read {0} chars actual {1}", charXmitBuffer.Length + 1, readResult); } Assert.Equal(expectedChars, charRcvBuffer); } }
public bool ReadTimeout_NonZero_ResizeBuffer() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); int bufferSize = numRndChar; byte[] byteXmitBuffer = new byte[1024]; char utf32Char = 'A'; byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); char[] charXmitBuffer = TCSupport.GetRandomChars(16, false); char[] expectedChars = new char[charXmitBuffer.Length + 1]; bool retValue = true; Console.WriteLine("Verifying Read method with non 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 = 500; 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); while (com1.BytesToRead < byteXmitBuffer.Length) { System.Threading.Thread.Sleep(50); } //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); if (1 != com1.BytesToRead) { Console.WriteLine("Err_6797auji ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); retValue = false; } com1.Encoding = System.Text.Encoding.UTF32; byteXmitBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); try { com1.ReadChar(); Console.WriteLine("Err_1027asdh ReadChar() did not timeout when it only contained part of a character in it's buffer"); retValue = false; } catch (TimeoutException) { } if (1 != com1.BytesToRead) { Console.WriteLine("Err_6189jhxcn ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); retValue = false; } if (retValue) { com2.Write(utf32CharBytes, 1, 3); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); while (com1.BytesToRead < 4 + byteXmitBuffer.Length) { System.Threading.Thread.Sleep(50); } retValue &= PerformReadOnCom1FromCom2(com1, com2, expectedChars); } if (!retValue) { Console.WriteLine("Err_2348asdz Verifying Read method with non zero timeout that resizes SerialPort's buffer"); } return(retValue); }
private void VerifyRead(char[] buffer, int offset, int count, Encoding encoding, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(-55); char[] charsToWrite; char[] expectedChars = new char[numberOfBytesToRead]; byte[] bytesToWrite = new byte[numberOfBytesToRead]; if (1 < count) { charsToWrite = TCSupport.GetRandomChars(numberOfBytesToRead, TCSupport.CharacterOptions.Surrogates); } else { charsToWrite = TCSupport.GetRandomChars(numberOfBytesToRead, TCSupport.CharacterOptions.None); } //Genrate some random chars in the buffer for (int i = 0; i < buffer.Length; i++) { char randChar = (char)rndGen.Next(0, ushort.MaxValue); buffer[i] = randChar; } TCSupport.SetHighSpeed(com1, com2); Debug.WriteLine( "Verifying read method buffer.Length={0}, offset={1}, count={2}, endocing={3} with {4} random chars", buffer.Length, offset, count, encoding.EncodingName, bytesToWrite.Length); com1.ReadTimeout = 500; com1.Encoding = encoding; 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(); } bytesToWrite = com1.Encoding.GetBytes(charsToWrite, 0, charsToWrite.Length); expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); switch (readDataFrom) { case ReadDataFromEnum.NonBuffered: VerifyReadNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); break; case ReadDataFromEnum.Buffered: VerifyReadBuffered(com1, com2, bytesToWrite, buffer, offset, count); break; case ReadDataFromEnum.BufferedAndNonBuffered: VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); break; default: throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); } } }
public bool GreedyRead() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); byte[] byteXmitBuffer = new byte[1024]; char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); int charRead; bool retValue = true; Console.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]; 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); while (com1.BytesToRead < byteXmitBuffer.Length) { System.Threading.Thread.Sleep(50); } //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); if (1 != com1.BytesToRead) { Console.WriteLine("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); retValue = false; } com1.Encoding = System.Text.Encoding.UTF32; com2.Write(utf32CharBytes, 1, 3); while (com1.BytesToRead < 4) { System.Threading.Thread.Sleep(50); } if (utf32Char != (charRead = com1.ReadChar())) { Console.WriteLine("Err_6481sfadw ReadChar() returned={0} expected={1}", charRead, utf32Char); retValue = false; } if (0 != com1.BytesToRead) { Console.WriteLine("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); retValue = false; } if (!retValue) { Console.WriteLine("Err_1389 Verifying that ReadChar() will read everything from internal buffer and drivers buffer failed"); } com1.Close(); com2.Close(); return(retValue); }
public void WriteChars() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] xmitCharBuffer = TCSupport.GetRandomChars(TRANSMIT_BUFFER_SIZE, TCSupport.CharacterOptions.None); char[] rcvCharBuffer = new char[RECEIVE_BUFFER_SIZE]; Random random = new Random(-55); Stopwatch sw = new Stopwatch(); Buffer <char> buffer = new Buffer <char>(MAX_BUFFER_SIZE); com1.Encoding = Encoding.Unicode; com2.Encoding = Encoding.Unicode; com1.BaudRate = 115200; com2.BaudRate = 115200; 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(); } sw.Start(); while (sw.ElapsedMilliseconds < s_testDuration.TotalMilliseconds) { switch (random.Next(0, 2)) { case 0: //Write if (com2.BytesToRead < MAX_BUFFER_SIZE) { int maxNumberOfCharactes = (MAX_BUFFER_SIZE - com2.BytesToRead) / 2; int numberOfCharacters = random.Next(0, Math.Min(xmitCharBuffer.Length, maxNumberOfCharactes) + 1); int expectedBytesToRead = com2.BytesToRead + 2 * numberOfCharacters; // Debug.WriteLine("Writing {0,5} characters BytesToRead={1,5}", numberOfCharacters, com2.BytesToRead); com1.Write(xmitCharBuffer, 0, numberOfCharacters); buffer.Append(xmitCharBuffer, 0, numberOfCharacters); TCSupport.WaitForPredicate(delegate() { return(com2.BytesToRead == expectedBytesToRead); }, 60000, "Err_29829haie Expected to received {0} bytes actual={1}", expectedBytesToRead, com2.BytesToRead); } break; case 1: //Read if (0 < com2.BytesToRead) { int maxNumberOfCharactes = com2.BytesToRead / 2; int numberOfCharacters = random.Next(0, Math.Min(rcvCharBuffer.Length, maxNumberOfCharactes) + 1); int actualNumberOfCharactersRead; int expectedBytesToRead = com2.BytesToRead - (2 * numberOfCharacters); // Debug.WriteLine("Reading {0,5} characters BytesToRead={1,5}", numberOfCharacters, com2.BytesToRead); actualNumberOfCharactersRead = com2.Read(rcvCharBuffer, 0, numberOfCharacters); if (actualNumberOfCharactersRead == numberOfCharacters) { buffer.CompareAndRemove(rcvCharBuffer, 0, numberOfCharacters); if (com2.BytesToRead != expectedBytesToRead) { Fail("Err_895879uhedbuz Expected to BytesToRead={0} actual={1}", expectedBytesToRead, com2.BytesToRead); } } else { Fail("Err_895879uhedbuz Expected to read {0} chars actual {1}", numberOfCharacters, actualNumberOfCharactersRead); } } break; } } } }
public bool ReadTimeout_Zero_Bytes() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); char utf32Char = (char)0x254b; //Box drawing char byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); bool retValue = true; int readChar; Console.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer"); com1.Encoding = System.Text.Encoding.UTF32; 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(); } //[] Try ReadChar with no bytes available try { try { readChar = com1.ReadChar(); Console.WriteLine("Err_28292haied Expected ReadChar to throw TimeoutException with no bytes in " + "the buffer {0}({0:X}) returned instead", readChar); retValue = false; } catch (TimeoutException) { //Expected } if (0 != com1.BytesToRead) { Console.WriteLine("Err_155anjied Expected BytesToRead={0} actual={1}", 0, com1.BytesToRead); retValue = false; } } catch (Exception e) { Console.WriteLine("Err_205566ahuied Unexpected exception thrown: {0}", e); retValue = false; } //[] Try ReadChar with 1 byte available try { com2.Write(utf32CharBytes, 0, 1); retValue &= TCSupport.WaitForPredicate(delegate() { return(com1.BytesToRead == 1); }, 2000, "Err_28292aheid Expected BytesToRead to be 1"); try { readChar = com1.ReadChar(); Console.WriteLine("Err_9279ajei Expected ReadChar to throw TimeoutException with some bytes available " + "in the SerialPort {0}({0:X}) returned instead", readChar); retValue = false; } catch (TimeoutException) { //Expected } if (1 != com1.BytesToRead) { Console.WriteLine("Err_1983218aheid Expected BytesToRead={0} actual={1}", 1, com1.BytesToRead); retValue = false; } } catch (Exception e) { Console.WriteLine("Err_021855aueid Unexpected exception thrown: {0}", e); retValue = false; } //[] Try ReadChar with the bytes in the buffer and in available in the SerialPort try { com2.Write(utf32CharBytes, 1, 3); retValue &= TCSupport.WaitForPredicate(delegate() { return(com1.BytesToRead == 4); }, 2000, "Err_415568haikpas Expected BytesToRead to be 4"); readChar = com1.ReadChar(); if (readChar != utf32Char) { retValue = false; Console.WriteLine("Err_19173ahid Expected to read {0}({0:X}) actually read {1}({1:X})", utf32Char, readChar); } } catch (Exception e) { Console.WriteLine("Err_4929aheidea Unexpected exception thrown: {0}", e); retValue = false; } if (com1.IsOpen) { com1.Close(); } if (com2.IsOpen) { com2.Close(); } if (!retValue) { Console.WriteLine("Err_115858ahjeid Verifying Read method with zero timeout"); } return(retValue); }
public void Read_DataReceivedBeforeTimeout() { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); string endString = "END"; ASyncRead asyncRead = new ASyncRead(com1, endString); var asyncReadTask = new Task(asyncRead.Read); char endChar = endString[0]; char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); Debug.WriteLine( "Verifying that ReadTo(string) will read characters that have been received after the call to Read was made"); //Ensure the new line is not in charXmitBuffer for (int i = 0; i < charXmitBuffer.Length; ++i) { //Se any appearances of a character in the new line string to some other char if (endChar == charXmitBuffer[i]) { charXmitBuffer[i] = notEndChar; } } com1.Encoding = Encoding.UTF8; com2.Encoding = Encoding.UTF8; com1.ReadTimeout = 20000; // 20 seconds 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(); } asyncReadTask.Start(); asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); com2.Write(endString); asyncRead.ReadCompletedEvent.WaitOne(); if (null != asyncRead.Exception) { Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); } else if (null == asyncRead.Result || 0 == asyncRead.Result.Length) { Fail("Err_0158ahei Expected Read to read at least one character"); } else { char[] charRcvBuffer = asyncRead.Result.ToCharArray(); if (charRcvBuffer.Length != charXmitBuffer.Length) { Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length, charRcvBuffer.Length); } else { for (int i = 0; i < charXmitBuffer.Length; ++i) { if (charRcvBuffer[i] != charXmitBuffer[i]) { Fail( "Err_0518895akiezp Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); } } } } VerifyReadTo(com1, com2, new string(charXmitBuffer), endString); } }
public bool Read_DataReceivedBeforeTimeout() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); char[] charRcvBuffer = new char[charXmitBuffer.Length]; ASyncRead asyncRead = new ASyncRead(com1); System.Threading.Thread asyncReadThread = new System.Threading.Thread(new System.Threading.ThreadStart(asyncRead.Read)); bool retValue = true; Console.WriteLine("Verifying that ReadChar will read characters that have been received after the call to Read was made"); com1.Encoding = System.Text.Encoding.UTF8; com2.Encoding = System.Text.Encoding.UTF8; com1.ReadTimeout = 20000; // 20 seconds 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(); } asyncReadThread.Start(); asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); asyncRead.ReadCompletedEvent.WaitOne(); if (null != asyncRead.Exception) { retValue = false; Console.WriteLine("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); } else if (asyncRead.Result != charXmitBuffer[0]) { retValue = false; Console.WriteLine("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], asyncRead.Result); } else { System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received charRcvBuffer[0] = (char)asyncRead.Result; int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); if (readResult + 1 != charXmitBuffer.Length) { retValue = false; Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", charXmitBuffer.Length - 1, readResult); } else { for (int i = 0; i < charXmitBuffer.Length; ++i) { if (charRcvBuffer[i] != charXmitBuffer[i]) { retValue = false; Console.WriteLine("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", i, charXmitBuffer[i], charRcvBuffer[i], asyncRead.Result); } } } } if (!retValue) { Console.WriteLine("Err_018068ajkid Verifying that ReadChar() will read characters that have been received after the call to Read was made failed"); } com1.Close(); com2.Close(); return(retValue); }
private void VerifyRead(Encoding encoding, string newLine, int numBytesRead, int numNewLines, ReadDataFromEnum readDataFrom) { using (SerialPort com1 = TCSupport.InitFirstSerialPort()) using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { Random rndGen = new Random(-55); StringBuilder strBldrToWrite; int numNewLineChars = newLine.ToCharArray().Length; int minLength = (1 + numNewLineChars) * numNewLines; if (minLength < numBytesRead) { strBldrToWrite = TCSupport.GetRandomStringBuilder(numBytesRead, TCSupport.CharacterOptions.None); } else { strBldrToWrite = TCSupport.GetRandomStringBuilder(rndGen.Next(minLength, minLength * 2), TCSupport.CharacterOptions.None); } //We need place the newLine so that they do not write over eachother int divisionLength = strBldrToWrite.Length / numNewLines; int range = divisionLength - numNewLineChars; for (int i = 0; i < numNewLines; i++) { int newLineIndex = rndGen.Next(0, range + 1); strBldrToWrite.Insert(newLineIndex + (i * divisionLength) + (i * numNewLineChars), newLine); } Debug.WriteLine("Verifying ReadTo encoding={0}, newLine={1}, numBytesRead={2}, numNewLines={3}", encoding, newLine, numBytesRead, numNewLines); com1.ReadTimeout = 500; com1.Encoding = encoding; 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(); } switch (readDataFrom) { case ReadDataFromEnum.NonBuffered: VerifyReadNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); break; case ReadDataFromEnum.Buffered: VerifyReadBuffered(com1, com2, strBldrToWrite.ToString(), newLine); break; case ReadDataFromEnum.BufferedAndNonBuffered: VerifyReadBufferedAndNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); break; default: throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); } } }
public bool Read_Timeout() { SerialPort com1 = TCSupport.InitFirstSerialPort(); SerialPort com2 = TCSupport.InitSecondSerialPort(com1); char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); byte[] byteXmitBuffer = new System.Text.UTF32Encoding().GetBytes(charXmitBuffer); char[] charRcvBuffer = new char[charXmitBuffer.Length]; bool retValue = true; int result; Console.WriteLine("Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown"); com1.Encoding = new System.Text.UTF32Encoding(); com2.Encoding = new System.Text.UTF32Encoding(); com1.ReadTimeout = 500; // 20 seconds 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(); } //Write the first 3 bytes of a character com2.Write(byteXmitBuffer, 0, 3); try { com1.ReadChar(); Console.WriteLine("Err_29299aize Expected ReadChar to throw TimeoutException"); retValue = false; } catch (TimeoutException) { }//Expected if (3 != com1.BytesToRead) { Console.WriteLine("Err_689855ozpbea Expected BytesToRead: {0} actual: {1}", 3, com1.BytesToRead); retValue = false; } com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3); retValue &= TCSupport.WaitForExpected(delegate() { return(com1.BytesToRead); }, byteXmitBuffer.Length, 5000, "Err_91818aheid BytesToRead"); result = com1.ReadChar(); if (result != charXmitBuffer[0]) { retValue = false; Console.WriteLine("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], result); } else { charRcvBuffer[0] = (char)result; int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); if (readResult + 1 != charXmitBuffer.Length) { retValue = false; Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", charXmitBuffer.Length - 1, readResult); } else { for (int i = 0; i < charXmitBuffer.Length; ++i) { if (charRcvBuffer[i] != charXmitBuffer[i]) { retValue = false; Console.WriteLine("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X})", i, charXmitBuffer[i], charRcvBuffer[i]); } } } } if (!VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer)) { Console.WriteLine("Err_05188ajied Verify ReadLine after read failed"); retValue = false; } if (!retValue) { Console.WriteLine("Err_9858wiapxzg Verifying that ReadChar() works appropriately after TimeoutException has been thrown failed"); } com1.Close(); com2.Close(); return(retValue); }