private void Write(string text) { logger.LogInformation($"PORT.Write(\"{text}\")"); byte[] buffer = Encoding.UTF8.GetBytes(text); port.Write(buffer, 0, buffer.Length); }
public void Flush() { using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut; dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); byte[] sdata = new byte[512]; for (int i = 0; i < sdata.Length; i++) { sdata[i] = (byte)(64 + i % 48); } // It should take 512 * 10 / 115200 s = 44ms to send, timeout of 300ms. src.Write(sdata, 0, sdata.Length); src.Flush(); Assert.That(src.BytesToWrite, Is.EqualTo(0)); src.Write(sdata, 0, sdata.Length); src.Flush(); Assert.That(src.BytesToWrite, Is.EqualTo(0)); } }
public void SerialPortStream_ReadTo_Overflow() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); // Send 2048 ASCII characters Random r = new Random(); byte[] sdata = new byte[2048]; for (int i = 0; i < sdata.Length; i++) { sdata[i] = (byte)r.Next(65, 65 + 26); } // Wait for the data to be received src.Write(sdata, 0, sdata.Length); src.Write("EOF"); while (dst.BytesToRead < sdata.Length) { System.Threading.Thread.Sleep(100); } string result = dst.ReadTo("EOF"); Assert.AreEqual(0, dst.BytesToRead); Assert.AreEqual(1024 - 3, result.Length); int offset = sdata.Length - result.Length; for (int i = 0; i < result.Length; i++) { Assert.AreEqual((int)sdata[offset + i], (int)result[i]); } } }
private void transmitButton_Click(object sender, EventArgs e) { if (!portStream.IsOpen) { return; } progressBar.SetState(1); progressBar.Value = 0; statLabel.Text = "Writing program..."; transmitButton.Enabled = false; portSelect.Enabled = false; data = (Owner as MainForm).Compile(); if (data == null || data.Length == 0) { statLabel.Text = "Compilation failed"; return; } state = 1; dataIndex = 0; dataAddr = 0; progressBar.Maximum = data.Length; portStream.Write(new byte[] { 1 }, 0, 1); }
private void Button1_Clicked(object sender, EventArgs a) { if (_puertoarduino.IsOpen == true) { if (pulsado == false) { _puertoarduino.Write("H"); pulsado = true; } else { _puertoarduino.Write("L"); pulsado = false; } } else { if (dialogo != null) { dialogo.ShowAll(); } else { dialogo = new DialogWindow(); dialogo.Label_Error.Text = ("Puerto " + _puertoarduino.PortName + " no Disponible"); dialogo.ShowAll(); } } }
public void ReadToOverflow() { using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut; dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); // Send 2048 ASCII characters Random r = new Random(); byte[] sdata = new byte[2048]; for (int i = 0; i < sdata.Length; i++) { sdata[i] = (byte)r.Next(65, 65 + 26); } // Wait for the data to be received src.Write(sdata, 0, sdata.Length); src.Write("EOF"); while (dst.BytesToRead < sdata.Length) { Thread.Sleep(100); } string result = dst.ReadTo("EOF"); Assert.That(dst.BytesToRead, Is.EqualTo(0)); Assert.That(result.Length, Is.EqualTo(1024 - 3)); int offset = sdata.Length - result.Length; for (int i = 0; i < result.Length; i++) { Assert.That((int)result[i], Is.EqualTo(sdata[offset + i])); } } }
public void SerialPortStream_Flush() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); byte[] sdata = new byte[512]; for (int i = 0; i < sdata.Length; i++) { sdata[i] = (byte)(64 + i % 48); } src.Write(sdata, 0, sdata.Length); //System.Threading.Thread.Sleep(10); src.Flush(); Assert.That(src.BytesToWrite, Is.EqualTo(0)); src.Write(sdata, 0, sdata.Length); //System.Threading.Thread.Sleep(10); src.Flush(); Assert.That(src.BytesToWrite, Is.EqualTo(0)); } }
public void Write(byte b) { if (com != null) { ComLogger.Log("tx", b); com.Write(new byte[] { b }, 0, 1); System.Threading.Thread.Sleep(10); } }
public void Write(byte[] buffer) { if (IsOpen) { sp.Write(buffer, 0, buffer.Length); } System.Diagnostics.Debug.WriteLine(ByteToHexStr(buffer)); }
public void Send(string data, bool appendLineEnding = true) { if (_logging) { _scriptLog.WriteLine(data); } data = appendLineEnding ? data + _lineEnding : data; src.Write(data); }
void telnetServer_OnDataReceived(object sender, byte[] Data) { System.Text.Encoding enc = System.Text.Encoding.ASCII; string str = enc.GetString(Data); #if LINUX serialDevice.Write(Data); #else serialDevice.Write(Data, 0, Data.Length); #endif _Log("RX=> " + Data.Length.ToString() + " Bytes received"); }
public byte[] ReadBytes(DeviceAddress address, ushort size) { int area = address.Area; try { byte[] header = area == Modbus.fctReadCoil ? CreateReadHeader(address.Start * 16, (ushort)(16 * size), (byte)area) : CreateReadHeader(address.Start, size, (byte)area); _serialPort.Write(header, 0, header.Length); byte[] frameBytes = new byte[size * 2 + 5]; byte[] data = new byte[size * 2]; int numBytesRead = 0; while (numBytesRead != size) { numBytesRead += _serialPort.Read(frameBytes, numBytesRead, size - numBytesRead); } if (frameBytes[0] == (byte)_id && Utility.CheckSumCRC(frameBytes)) { Array.Copy(frameBytes, 3, data, 0, size); return(data); } return(null); } catch (Exception e) { if (OnClose != null) { OnClose(this, new ShutdownRequestEventArgs(e.Message)); } return(null); } }
static async Task Main(string[] args) { WriteLine("RS485Master"); WriteLine($"Opening on {args[0]} port"); var port = new SerialPortStream(args[0], 57600, 8, Parity.None, StopBits.One); port.DataReceived += (s, e) => { var buffer = new byte[port.BytesToRead]; var read = port.Read(buffer, 0, buffer.Length); var id = buffer[0]; var cmd = buffer[1]; var cmdlen = buffer[2]; WriteLine($"{read} bytes from {id}: cmd={cmd} len={cmdlen}"); switch (cmd) { case 0x80 + 0x02: var readTemperatureValue = System.BitConverter.ToSingle(buffer, 3); WriteLine($"READ TEMPERATURE={readTemperatureValue}"); break; } }; port.Open(); var requestT0 = new byte[] { 0, 2, 2 }; var requestT1 = new byte[] { 1, 2, 2 }; try { while (true) { WriteLine("Sending T0"); port.Write(requestT0, 0, requestT0.Length); await Task.Delay(2000); WriteLine("Sending T1"); port.Write(requestT1, 0, requestT1.Length); await Task.Delay(2000); } } catch (Exception ex) { throw ex; } finally { port.Close(); } }
public void ReadCharsWithTimeout() { using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = 2 * TimeOut + 500; src.ReadTimeout = 2 * TimeOut + 500; dst.WriteTimeout = 2 * TimeOut + 500; dst.ReadTimeout = 2 * TimeOut + 500; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); new Thread(() => { Thread.Sleep(TimeOut + 500); byte[] send = new byte[] { 0x65, 0x66, 0x67 }; src.Write(send, 0, send.Length); }).Start(); char[] recv = new char[5]; int cread = 0; int counter = 0; while (cread < 3 && counter < 5) { cread += dst.Read(recv, cread, recv.Length - cread); counter++; Console.WriteLine("dst.Read. Got cread={0} bytes in {1} loops", cread, counter); } for (int i = 0; i < cread; i++) { Console.WriteLine("cread[{0}] = {1}", i, recv[i]); } Assert.That(cread, Is.EqualTo(3)); Assert.That(recv[0], Is.EqualTo('e')); Assert.That(recv[1], Is.EqualTo('f')); Assert.That(recv[2], Is.EqualTo('g')); } }
public void ReadToWithOverflow2() { using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = -1; src.ReadTimeout = -1; dst.WriteTimeout = -1; dst.ReadTimeout = -1; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); byte[] writeData = new byte[2048]; for (int i = 0; i < writeData.Length - 1; i++) { writeData[i] = (byte)((i % 26) + 0x41); } writeData[writeData.Length - 1] = (byte)'\n'; // We write 2048 bytes that starts with A..Z repeated. // Position 0 = A // Position 1023 = J // Position 1024 = K // Position 2047 = \n src.Write(writeData, 0, writeData.Length); string line = dst.ReadLine(); Assert.That(line[0], Is.EqualTo('K')); Assert.That(line.Length, Is.EqualTo(1023)); // Is 1024 - Length('\n'). } }
public void writeReadDevice() { Byte[] output = new Byte[13]; //Console.WriteLine("Sending C...."); output[0] = 0x63; output[1] = Convert.ToByte((outputChannel[0] & 0x0000FF00) >> 8);//PWM-0 Channel 0 output[2] = Convert.ToByte(outputChannel[0] & 0x000000FF); output[3] = Convert.ToByte((outputChannel[1] & 0x0000FF00) >> 8);//PWM-1 Channel 1 output[4] = Convert.ToByte(outputChannel[1] & 0x000000FF); output[5] = Convert.ToByte(outputChannel[2]); //VALVE-0 Channel 2 output[6] = Convert.ToByte(outputChannel[3]); //VALVE-1 Channel 3 output[7] = Convert.ToByte(outputChannel[4]); //RELAY-0 Channel 4 output[8] = Convert.ToByte(outputChannel[5]); //SSR-0 Channel 5 output[9] = Convert.ToByte(outputChannel[6]); //PROXY RESET COUNT Channel 6 output[10] = 0; output[11] = 0; output[12] = 0; pressSerialPort.Write(output, 0, 13); receiveTimer.Start(); //System.Threading.Thread.Sleep(10); //writeReadDevice(); }
public string getIdent() { if (_port.IsOpen) { byte[] rqst = new byte[1]; rqst[0] = RQST_IDENTIFY; _port.Write(rqst); uint l = 0; while (_port.BytesToRead == 0) { Thread.Sleep(10); l++; if (l == timeout) { throw new OperationCanceledException("Timeout"); } } return(_port.ReadExisting()); } else { return(""); } }
private void TestEvenParity(SerialPortStream src, SerialPortStream dst) { src.Write(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0, 16); src.Flush(); int offset = 0; int counter = 0; byte[] recv = new byte[256]; while (offset < 16 && counter < 10) { offset += dst.Read(recv, offset, recv.Length - offset); counter++; Console.WriteLine("Buffer Bytes Received: {0}; Read attempts: {1}", offset, counter); } for (int i = 0; i < offset; i++) { Console.WriteLine("Offset: {0} = {1:X2}", i, recv[i]); } // NOTE: This test case will likely fail on software loopback devices, as they handle bytes and not // bits as a real UART does Assert.That(offset, Is.EqualTo(16), "Expected 16 bytes received, but only got {0} bytes", offset); byte[] expectedrecv = new byte[] { 0x00, 0x81, 0x82, 0x03, 0x84, 0x05, 0x06, 0x87, 0x88, 0x09, 0x0A, 0x8B, 0x0C, 0x8D, 0x8E, 0x0F }; for (int i = 0; i < offset; i++) { Assert.That(recv[i], Is.EqualTo(expectedrecv[i]), "Offset {0} got {1}; expected {2}", i, recv[i], expectedrecv[i]); } }
public static List <List <double> > begin_test(SerialPortStream port) { port.Open(); Console.WriteLine("Press any button to begin"); Console.ReadKey(true); port.Write("<1>"); List <List <double> > data = new List <List <double> >(); bool collecting_data = true; while (collecting_data) { if (port.BytesToRead > 0) { string s = port.ReadLine(); s = Regex.Replace(s, @"\r", string.Empty); if (s == "Done") { collecting_data = false; break; } string[] message = s.Split(','); List <double> temp = new List <double>(); foreach (string element in message) { double value = Convert.ToDouble(element); temp.Add(value); Console.WriteLine(element); } data.Add(temp); } } return(data); }
public void SerialPortStream_WriteReadLine_CharForChar() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); bool err = false; string s = null; const string send = "A Brief History Of Time\n"; for (int i = 0; i < send.Length; i++) { src.Write(send[i].ToString()); try { s = dst.ReadLine(); } catch (System.Exception e) { if (e is TimeoutException) { err = true; } } if (i < send.Length - 1) { Assert.IsTrue(err, "No timeout exception occurred when waiting for " + send[i].ToString() + " (position " + i.ToString() + ")"); } } Assert.AreEqual("A Brief History Of Time", s); } }
public void SerialPortStream_WriteReadLine_Multilines() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); bool err = false; string s; src.Write("Line1\nLine2\n"); s = dst.ReadLine(); Assert.AreEqual("Line1", s); s = dst.ReadLine(); Assert.AreEqual("Line2", s); try { s = dst.ReadLine(); } catch (System.Exception e) { if (e is TimeoutException) { err = true; } } Assert.IsTrue(err, "No timeout exception occurred"); } }
public void DisconnectOnWriteBlocked() { byte[] buffer = new byte[8192]; using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream serialDest = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { serialSource.ReadBufferSize = 8192; serialSource.WriteBufferSize = 8192; serialDest.ReadBufferSize = 8192; serialDest.WriteBufferSize = 8192; serialSource.Handshake = Handshake.Rts; serialSource.Open(); serialDest.Open(); serialDest.RtsEnable = false; Thread.Sleep(100); Assert.That( () => { while (true) { Console.WriteLine("DisconnectOnWriteBlocked Writing"); serialSource.Write(buffer, 0, buffer.Length); } }, Throws.InstanceOf <System.IO.IOException>()); // Device should still be open. Assert.That(serialSource.IsOpen, Is.True); serialSource.Close(); } }
/// <summary> /// Get the command bytes and send them to the digital system. /// </summary> /// <returns>A value indicating if the command has been sent to the digital system or not.</returns> public bool SendCommand(SerialPortStream port) { if (this.RequestBytes.Length <= 0) { return(false); } try { byte[] bytes = new byte[2 + this.RequestBytes.Length + 1]; bytes[0] = 0xFF; bytes[1] = 0xFE; for (int idx = 0; idx < this.RequestBytes.Length; idx++) { bytes[2 + idx] = this.RequestBytes[idx]; } bytes[bytes.Length - 1] = (byte)BinaryUtils.Xor(bytes, 2, this.RequestBytes.Length); port.Write(bytes, 0, bytes.Length); return(true); } catch (Exception ex) { Logger.LogError(this, ex); return(false); } }
public void ReadToResetWithOverflow() { using (SerialPortStream src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = TimeOut; src.ReadTimeout = TimeOut; dst.WriteTimeout = TimeOut; dst.ReadTimeout = TimeOut; src.Open(); Assert.That(src.IsOpen, Is.True); dst.Open(); Assert.That(dst.IsOpen, Is.True); byte[] writeData = new byte[2048]; for (int i = 0; i < writeData.Length; i++) { writeData[i] = (byte)((i % 26) + 0x41); } // We write 2048 bytes that starts with A..Z repeated. // Position 0 = A // Position 1023 = J // To read a line, it parses the 2048 characters, not finding a new line. Then we read a character and // we expect to get 'A'. src.Write(writeData, 0, writeData.Length); Assert.That(() => { dst.ReadLine(); }, Throws.Exception.TypeOf <TimeoutException>()); Assert.That(dst.ReadChar(), Is.EqualTo((int)'A')); } }
private bool GetSync() { try { byte[] bytes = CommandConstants.SyncBytes; serialPort.Write(bytes, 0, bytes.Length); byte[] responseBytes = ReadCurrentReceiveBuffer(4); return(responseBytes.Length == 4 && responseBytes[0] == bytes[3] && responseBytes[1] == bytes[2] && responseBytes[2] == bytes[1] && responseBytes[3] == bytes[0]); } catch (Exception) { return(false); } }
static public List <List <double> > poll_for_data(SerialPortStream port, string user_input = "0") { // Send Command to Start, send it desired speed to run at port.Write("<1>"); bool quick_three = true; while (quick_three) { if (port.BytesToRead > 0) { string s = port.ReadLine(); s = Regex.Replace(s, @"\r", string.Empty); // Either prompt user for input, or take in function line arugment for a desired RPM to run at if (s == "give") { port.WriteLine(user_input); quick_three = false; break; } } } bool stop = true; Console.WriteLine("Test Started"); //Collect data with this loop List <double> temp = new List <double>(); List <List <double> > data = new List <List <double> >(); while (stop) { if (port.BytesToRead > 0) { string s = port.ReadLine(); s = Regex.Replace(s, @"\r", string.Empty); if (s == "end") { stop = false; break; } string[] message = s.Split(','); //temp.Add(Convert.ToDouble(s)); foreach (string element in message) { //Console.WriteLine(element); double value = Convert.ToDouble(element); temp.Add(value); Console.WriteLine(element); } data.Add(temp); } } return(data); }
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e) { string data = serialPort.ReadExisting(); try { if (data.Contains("ACK")) { data = data.Substring(5); } data = data.Substring(data.IndexOf('#') + 1, data.IndexOf('$') - data.IndexOf('#') - 1); } catch (Exception) { // throw; } if (data.StartsWith("DONE:")) { serialPort.Write("#SEND$"); } else if (data.StartsWith("MAC:")) { serialPort.WriteLine("#ACK$"); } Console.WriteLine(data); }
static async Task Main(string[] args) { WriteLine("RS485Master"); WriteLine($"Opening on {args[0]} port"); var port = new SerialPortStream(args[0], 9600, 8, Parity.None, StopBits.One); port.DataReceived += (s, e) => { /* var buffer = new byte[port.BytesToRead]; * var read = port.Read(buffer, 0, buffer.Length); * var id = buffer[0]; * var cmd = buffer[1]; * var cmdlen = buffer[2]; * * WriteLine($"{read} bytes from {id}: cmd={cmd} len={cmdlen}"); * * switch (cmd) * { * case 0x80 + 0x02: * var readTemperatureValue = System.BitConverter.ToSingle(buffer, 3); * WriteLine($"READ TEMPERATURE={readTemperatureValue}"); * break; * }*/ }; port.Open(); var dato = new char[1]; var send = new char[1]; send[0] = 'a'; try { while (true) { await Task.Delay(1000); WriteLine("RECEIVING T0"); port.Write(send, 0, 1); while (dato[0] != 'o') { port.Read(dato, 0, 1); WriteLine(dato); WriteLine("HEY PIC"); send[0] = '0'; } } } catch (Exception ex) { throw ex; } finally { port.Close(); } }
public static void WriteBytes(this SerialPortStream port, byte[] bytes, int offset, int count) { port.DiscardOutBuffer(); Log.Log("Удаление всех данных исходящего буфера последовательного порта..."); var discardedInBytes = port.ReadAllBytes(); Log.Log("Удалены следующие байты: " + discardedInBytes.ToText()); port.Write(bytes, 0, bytes.Length); }
public void Begin_Manual(CommandPacket commands, SerialPortStream port) { port.Write("<" + commands.RunTest + "," + "0" + "," + "0" + "," + commands.Retract + ">"); while (enable_mc) { if (up_control == 1) { commands.RunTest = "3"; commands.Displacement = "1"; commands.DisplacementRate = "2"; commands.Retract = "0"; try { port.Write("<" + commands.RunTest + "," + commands.DisplacementRate + "," + commands.Displacement + "," + commands.Retract + ">"); } catch { } } else if (down_control == 1) { commands.RunTest = "3"; commands.Displacement = "2"; commands.DisplacementRate = "2"; commands.Retract = "0"; try { port.Write("<" + commands.RunTest + "," + commands.DisplacementRate + "," + commands.Displacement + "," + commands.Retract + ">"); } catch { } } else if (up_control == 0 && down_control == 0) { commands.RunTest = "3"; commands.Displacement = "0"; commands.DisplacementRate = "0"; commands.Retract = "0"; port.Write("<" + commands.RunTest + "," + commands.DisplacementRate + "," + commands.Displacement + "," + commands.Retract + ">"); } } }
public void SerialPortStream_ReadTo_Cached() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); bool err = false; string s; src.Write("foobar"); try { s = dst.ReadTo("baz"); } catch (System.Exception e) { if (e is TimeoutException) err = true; } Assert.IsTrue(err, "No timeout exception occurred when reading 'baz'"); s = dst.ReadTo("foo"); Assert.AreEqual("", s); s = dst.ReadTo("bar"); Assert.AreEqual("", s); try { s = dst.ReadTo("baz"); } catch (System.Exception e) { if (e is TimeoutException) err = true; } Assert.IsTrue(err, "No timeout exception occurred when reading 'baz' when empty"); } }
public void SerialPortStream_ReadTo_Normal() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); string s; src.Write("superfoobar"); s = dst.ReadTo("foo"); Assert.AreEqual("super", s); s = dst.ReadExisting(); Assert.AreEqual("bar", s); } }
public void SerialPortStream_WriteReadLine_CharForChar() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); bool err = false; string s = null; const string send = "A Brief History Of Time\n"; for (int i = 0; i < send.Length; i++) { src.Write(send[i].ToString()); try { s = dst.ReadLine(); } catch (System.Exception e) { if (e is TimeoutException) err = true; } if (i < send.Length - 1) { Assert.IsTrue(err, "No timeout exception occurred when waiting for " + send[i].ToString() + " (position " + i.ToString() + ")"); } } Assert.AreEqual("A Brief History Of Time", s); } }
public void SerialPortStream_WriteReadLine_MbcsByteForByte() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); bool err = false; string s = null; byte[] buf = new byte[] { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0xE2, 0x82, 0xAC, 0x0A }; for (int i = 0; i < buf.Length; i++) { src.Write(buf, i, 1); try { s = dst.ReadLine(); } catch (System.Exception e) { if (e is TimeoutException) err = true; } if (i < buf.Length - 1) { Assert.IsTrue(err, "No timeout exception occurred when waiting for " + buf[i].ToString("X2") + " (position " + i.ToString() + ")"); } } Assert.AreEqual("ABCDEFGHIJ€", s); } }
public void SerialPortStream_WriteReadLine_Timeout2() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); bool err = false; string s; src.Write("Test"); try { s = dst.ReadLine(); } catch (System.Exception e) { if (e is TimeoutException) err = true; } Assert.IsTrue(err, "No timeout exception occurred"); src.WriteLine("String"); s = dst.ReadLine(); Assert.AreEqual("TestString", s); } }
public void SerialPortStream_SendReceive() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = c_Timeout; src.ReadTimeout = c_Timeout; dst.WriteTimeout = c_Timeout; dst.ReadTimeout = c_Timeout; src.Open(); Assert.IsTrue(src.IsOpen); dst.Open(); Assert.IsTrue(dst.IsOpen); // Send Maximum data in one go byte[] sendbuf = new byte[src.WriteBufferSize]; #if true Random r = new Random(); r.NextBytes(sendbuf); #else for (int i = 0; i < sendbuf.Length; i++) { sendbuf[i] = (byte)((i % 77) + 1); } #endif src.Write(sendbuf, 0, sendbuf.Length); // Receive sent data int rcv = 0; int c = 0; byte[] rcvbuf = new byte[sendbuf.Length + 10]; while (rcv < rcvbuf.Length) { Trace.WriteLine("Begin Receive: Offset=" + rcv.ToString() + "; Count=" + (rcvbuf.Length - rcv).ToString()); int b = dst.Read(rcvbuf, rcv, rcvbuf.Length - rcv); if (b == 0) { if (c == 0) break; c++; } else { c = 0; } rcv += b; } bool dump = false; if (rcv != sendbuf.Length) { Trace.WriteLine("Read length not the same as the amount of data sent (got " + rcv.ToString() + " bytes)"); dump = true; } for (int i = 0; i < sendbuf.Length; i++) { if (sendbuf[i] != rcvbuf[i]) { Trace.WriteLine("Comparison failure at " + i.ToString()); dump = true; break; } } if (dump) { Trace.WriteLine("Send Buffer DUMP"); for (int i = 0; i < sendbuf.Length; i++) { Trace.WriteLine(sendbuf[i].ToString("X2")); } Trace.WriteLine("Receive Buffer DUMP"); for (int i = 0; i < rcv; i++) { Trace.WriteLine(rcvbuf[i].ToString("X2")); } } src.Close(); dst.Close(); Assert.IsFalse(dump, "Error in transfer"); } }