public SerialChannelSimple(string portName, int baudRate, int openingTimeout) { Log.Log(".ctor called"); _openingTimeout = openingTimeout; //var AJ.Std.Serial.SerialPortExtender Log.Log("The line before <_port = new SerialPort(portName)>"); _port = new SerialPortStream(portName) { BaudRate = baudRate, Parity = Parity.None, DataBits = 8, StopBits = StopBits.One, ReadTimeout = int.MaxValue, WriteTimeout = 500, }; Log.Log("The line after <_port = new SerialPort(portName)>"); try { if (_port.IsOpen) { _port.Close(); } OpenPort(); } catch (Exception ex) { Dispose(); Log.Log(ex.ToString()); throw; } Log.Log("Ready to setup port_opened_watcher"); SetUpPortOpenedWatcher(); Log.Log(".ctor returns"); }
public SerialPortHandler(Controller controller) { _controller = controller; _relayerPortA = new SerialPortStream(); _relayerPortA.DataBits = 8; _relayerPortA.StopBits = StopBits.One; _relayerPortA.Parity = Parity.None; _relayerPortA.Handshake = Handshake.None; _relayerPortA.DataReceived += _relayerPortA_DataReceived; _relayerPortB = new SerialPortStream(); _relayerPortB.DataBits = 8; _relayerPortB.StopBits = StopBits.One; _relayerPortB.Parity = Parity.None; _relayerPortB.Handshake = Handshake.None; _relayerPortB.DataReceived += _relayerPortB_DataReceived; _snifferPortAB = new SerialPortStream(); _snifferPortAB.DataBits = 8; _snifferPortAB.StopBits = StopBits.One; _snifferPortAB.Parity = Parity.None; _snifferPortAB.Handshake = Handshake.None; _snifferPortBA = new SerialPortStream(); _snifferPortBA.DataBits = 8; _snifferPortBA.StopBits = StopBits.One; _snifferPortBA.Parity = Parity.None; _snifferPortBA.Handshake = Handshake.None; }
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 PropertyBaudRate() { using (SerialPortStream src = new SerialPortStream(SourcePort)) { src.BaudRate = 115200; Assert.That(src.BaudRate, Is.EqualTo(115200)); } }
private void Close(SerialPortStream serialPort) { // Lock the keyboard //this.WriteLine(serialPort, NTIXL2Commands.UnLock); // Stop the sound level meter this.WriteLine(serialPort, NTIXL2Commands.Stop); }
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_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]); } } }
public void SerialPortStream_ListPorts() { bool result = true; Dictionary <string, bool> ports1 = new Dictionary <string, bool>(); Dictionary <string, bool> ports2 = new Dictionary <string, bool>(); foreach (PortDescription desc in SerialPortStream.GetPortDescriptions()) { Trace.WriteLine("GetPortDescriptions: " + desc.Port + "; Description: " + desc.Description); ports1.Add(desc.Port, false); ports2.Add(desc.Port, false); } foreach (string c in SerialPortStream.GetPortNames()) { Trace.WriteLine("GetPortNames: " + c); if (ports1.ContainsKey(c)) { ports1[c] = true; } else { Trace.WriteLine("GetPortNames() shows " + c + ", but not GetPortDescriptions()"); result = false; } } foreach (string c in ports1.Keys) { if (ports1[c] == false) { Trace.WriteLine("GetPortDescriptions() shows " + c + ", but not GetPortnames()"); result = false; } } foreach (string c in System.IO.Ports.SerialPort.GetPortNames()) { Trace.WriteLine("SerialPort.GetPortNames: " + c); if (ports2.ContainsKey(c)) { ports2[c] = true; } else { Trace.WriteLine("System.IO.Ports.SerialPort.GetPortNames() shows " + c + ", but not GetPortDescriptions()"); result = false; } } foreach (string c in ports1.Keys) { if (ports2[c] == false) { Trace.WriteLine("GetPortDescriptions() shows " + c + ", but not System.IO.Ports.SerialPort.GetPortNames()"); result = false; } } Assert.IsTrue(result); }
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 ReadUntilDisconnectAndReadAgainThenClose() { byte[] buffer = new byte[8192]; using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) { serialSource.ReadBufferSize = 8192; serialSource.WriteBufferSize = 8192; serialSource.Open(); Thread.Sleep(100); int read = 0; while (serialSource.Read(buffer, 0, buffer.Length) > 0) { Console.WriteLine("In Read Loop"); /* throw away the data */ } try { read = serialSource.Read(buffer, 0, buffer.Length); } catch (System.IO.IOException) { Console.WriteLine("IOException occurred"); } Console.WriteLine("Second Read: {0}", read); serialSource.Close(); } }
private void Close() { lock (accessLock) { // Stop the Reader task if (reader != null) { if (!reader.Join(5000)) { readerCts.Cancel(); } reader = null; } if (_serialPort != null) { _serialPort.ErrorReceived -= HandleErrorReceived; if (_serialPort.IsOpen) { _serialPort.Close(); OnConnectionStatusChanged(new ConnectionStatusChangedEventArgs(false)); } _serialPort.Dispose(); _serialPort = null; } gotReadWriteError = true; } }
public void ClosedWhenReadBlocked() { byte[] buffer = new byte[1024]; using (ManualResetEvent closedEvent = new ManualResetEvent(false)) 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.Open(); serialDest.Open(); new Thread( () => { Thread.Sleep(2000); Console.WriteLine("Closing serialSource"); // It appears that the MSDN .NET implementation blocks here, never // to return as we're blocked on another thread. closedEvent.Set(); serialSource.Close(); Console.WriteLine("Closed serialSource"); } ).Start(); int bytes = serialSource.Read(buffer, 0, buffer.Length); Console.WriteLine("Read finished, returned {0} bytes", bytes); if (!closedEvent.WaitOne(0)) { Assert.Fail("Read returned before being disposed."); } Assert.That(bytes, Is.EqualTo(0)); } }
public void DisconnectOnWriteAsyncBlocked() { 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("DisconnectOnWriteAsyncBlocked BeginWrite"); IAsyncResult ar = serialSource.BeginWrite(buffer, 0, buffer.Length, null, null); Console.WriteLine("DisconnectOnWriteAsyncBlocked EndWrite"); serialSource.EndWrite(ar); } }, Throws.InstanceOf <System.IO.IOException>()); // Device should still be open. Assert.That(serialSource.IsOpen, Is.True); serialSource.Close(); } }
private async Task <string> RunBootLoader(string nonBootLoaderPort, List <string> baselinePorts) { var port = new SerialPortStream(nonBootLoaderPort, 1200); port.Open(); await Task.Delay(TimeSpan.FromSeconds(1)); port.Close(); int triesRemaining = 8; while (triesRemaining > 0) { await Task.Delay(TimeSpan.FromSeconds(1)); var candidates = SerialPortStream.GetPortNames().ToList(); string candidateBootloaderPort = DetectNewPort(baselinePorts, candidates); if (!string.IsNullOrWhiteSpace(candidateBootloaderPort)) { return(candidateBootloaderPort); } --triesRemaining; } return(string.Empty); }
public override void EstablishSync() { var ports = SerialPortStream.GetPortNames(); var newPort = ports.Except(originalPorts).SingleOrDefault(); if (newPort == null) { UploaderLogger.LogErrorAndThrow( string.Format( "No (unambiguous) virtual COM port detected (after {0}ms).", VIRTUAL_COM_CREATION_TIMEOUT)); } SerialPort = new SerialPortStream { BaudRate = 57600, PortName = newPort, DataBits = 8, Parity = Parity.None, StopBits = StopBits.One, Handshake = Handshake.DtrRts }; try { SerialPort.Open(); } catch (Exception ex) { UploaderLogger.LogErrorAndThrow( string.Format("Unable to open serial port - {0}.", ex.Message)); } }
public SerialPortDevice(ILogger logger, string comPath, BitRate rate) { Logger = logger; this.comPath = comPath; this.rate = rate; device = new SerialPortStream(comPath, Convert.ToInt32(rate)); }
public override void Open() { var portName = serialPortConfig.PortName; var baudRate = serialPortConfig.BaudRate; logger.Info("Opening serial port {0} - baudrate {1}", serialPortConfig.PortName, serialPortConfig.BaudRate); SerialPort = new SerialPortStream(portName, baudRate) { ReadTimeout = serialPortConfig.ReadTimeOut, WriteTimeout = serialPortConfig.WriteTimeOut, DtrEnable = true // This means the Arduino will reset the moment we open the serial connection. }; try { SerialPort.Open(); } catch (ObjectDisposedException ex) { UploaderLogger.LogErrorAndQuit( string.Format("Unable to open serial port {0} - {1}.", portName, ex.Message)); } catch (InvalidOperationException ex) { UploaderLogger.LogErrorAndQuit( string.Format("Unable to open serial port {0} - {1}.", portName, ex.Message)); } logger.Trace("Opened serial port {0} with baud rate {1}!", portName, baudRate); }
public SerialPortStreamEngine() : base() { _serialPort = new SerialPortStream(); //_serialPort.ErrorReceived += (_, e) => OnLogReceived(e.EventType); //_serialPort.PinChanged += (_, e) => OnLogReceived(e.EventType); }
public void DtrDisableBeforeOpen() { SerialPortStream serial = null; try { serial = new SerialPortStream(SourcePort) { BaudRate = 115200, DataBits = 8, Parity = Parity.None, DtrEnable = false, StopBits = StopBits.One, ReadTimeout = -1, WriteTimeout = -1 }; serial.Open(); Assert.That(serial.DtrEnable, Is.False); } finally { if (serial != null) { serial.Dispose(); } } }
public override void Close() { try { string currentPort = SerialPort.PortName; Logger?.Info($"Closing {currentPort}..."); SerialPort.Close(); Logger?.Info($"Waiting for virtual port {currentPort} to disappear..."); const int timeoutVirtualPointDisappearance = 10000; const int virtualPortDisappearanceInterval = 100; string result = WaitHelper.WaitFor( timeoutVirtualPointDisappearance, virtualPortDisappearanceInterval, () => SerialPortStream.GetPortNames().Contains(currentPort) ? null : currentPort, (i, item, interval) => item == null ? $"T+{i * interval} - Port still present..." : $"T+{i * interval} - Port disappeared: {item}!" ); if (result == null) { Logger?.Warn( $"Virtual COM port {currentPort} was still present " + "after {timeoutVirtualPointDisappearance} ms!" ); } } catch (Exception ex) { throw new ArduinoUploaderException($"Exception during close of the programmer: '{ex.Message}'."); } }
public void VersionString() { using (SerialPortStream src = new SerialPortStream()) { Assert.That(src.Version, Is.Not.Null.Or.Empty); Console.WriteLine("Version: {0}", src.Version); } }
public void DiscardOutBuffer() { using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) { serialSource.Open(); serialSource.DiscardOutBuffer(); } }
public void SimpleConstructor() { SerialPortStream src = new SerialPortStream(); src.Dispose(); Assert.That(src.IsDisposed, Is.True); }
public void ModemSignalsWithSleep10() { // On some chipsets (PL2303H Win7 x86), need small delays for this test case to work properly. using (SerialPortStream src = new SerialPortStream(SourcePort)) using (SerialPortStream dst = new SerialPortStream(DestPort)) { src.Handshake = Handshake.None; dst.Handshake = Handshake.None; src.Open(); dst.Open(); src.RtsEnable = false; Thread.Sleep(10); // Required for PL2303H Assert.That(dst.CtsHolding, Is.False); src.RtsEnable = true; Thread.Sleep(10); // Required for PL2303H Assert.That(dst.CtsHolding, Is.True); src.DtrEnable = false; Thread.Sleep(10); // Required for PL2303H Assert.That(dst.DsrHolding, Is.False); src.DtrEnable = true; Thread.Sleep(10); // Required for PL2303H Assert.That(dst.DsrHolding, Is.True); } }
private static void SetValues(Controller controller, XmlTemplate xmlTemplate) { var serialPortList = SerialPortStream.GetPortNames(); if (serialPortList.Contains(xmlTemplate.RelayerPortAName)) { controller.SerialPortHandler.SelectedRelayerPortAName = xmlTemplate.RelayerPortAName; } if (serialPortList.Contains(xmlTemplate.RelayerPortBName)) { controller.SerialPortHandler.SelectedRelayerPortBName = xmlTemplate.RelayerPortBName; } if (serialPortList.Contains(xmlTemplate.SnifferPortABName)) { controller.SerialPortHandler.SelectedSnifferPortABName = xmlTemplate.SnifferPortABName; } if (serialPortList.Contains(xmlTemplate.SnifferPortBAName)) { controller.SerialPortHandler.SelectedSnifferPortBAName = xmlTemplate.SnifferPortBAName; } controller.SerialPortHandler.SelectedBaudRate = xmlTemplate.BaudRate; }
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 bool Initialize() { try { header = new byte[MAGIC.Length + 3]; Array.Copy(MAGIC, header, MAGIC.Length); byte hi, lo, chk; hi = (byte)((LedCount - 1) >> 8); lo = (byte)((LedCount - 1) & 0xff); chk = (byte)(hi ^ lo ^ 0x55); header[MAGIC.Length] = hi; header[MAGIC.Length + 1] = lo; header[MAGIC.Length + 2] = chk; if (port != null) { lock (port) { port.Dispose(); } } port = new SerialPortStream(); port.PortName = SerialPort; port.BaudRate = Baudrate; port.Open(); AssignLeds(); isInitialized = true; crashed = false; return(true); } catch (Exception ex) { Crash(ex, "Initialization"); return(false); } }
[Timeout(2000)] // We abort the test after timeout. This tests the blocking behavior in ReadAsync and the test will fail if ReadAsync blocks. public async Task WriteAsync() { using (var serialPortStreamWrite = new SerialPortStream("COM1", 9600, 8, Parity.None, StopBits.One)) using (var serialPortStreamRead = new SerialPortStream("COM2", 9600, 8, Parity.None, StopBits.One)) { serialPortStreamWrite.Open(); serialPortStreamRead.Open(); var buffer = new byte[1024]; var readTask = Task.Run(async() => await serialPortStreamRead.ReadAsync(buffer, 0, buffer.Length)); var bytes = new byte[] { 0x01, 0x02, 0x03 }; await serialPortStreamWrite.WriteAsync(bytes, 0, bytes.Length); await serialPortStreamWrite.FlushAsync(); // ReadAsync blocks here even if something gets written and flushed to the underlying COM device. // Fails for netcoreapp3.1, works with net472 await readTask; Assert.That(buffer[0], Is.EqualTo(0x01)); Assert.That(buffer[1], Is.EqualTo(0x02)); Assert.That(buffer[2], Is.EqualTo(0x03)); } }
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); }
internal static actionResult DestroyPort(SerialPortStream port) { var ar = new actionResult(); if (!port.IsAlive()) { ar.setError("Port already closed."); return(ar); } if (port == Plugin.SelectedPort) { Plugin.MainCtl.Log($"=========== {port.PortName}: log end ===========", false); } string portLongName = Plugin.OpenedPorts.First(kvp => kvp.Value == port).Key; Plugin.OpenedPorts.Remove(portLongName); if (port.IsOpen) { port.Close(); } port.Dispose(); // ReSharper disable once RedundantAssignment port = null; Plugin.MainCtl.UpdatePortsListView(); ar.setInfo("Port closed."); Plugin.HostInstance.log(nameof(Serial) + ": destroyed port: " + portLongName); return(ar); }
public void SerialPortStream_GetPortSettings() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { src.GetPortSettings(); SerialPortStream s2 = new SerialPortStream(); bool err = false; try { s2.GetPortSettings(); } catch { err = true; } Assert.IsTrue(err, "No exception raised when port not defined"); } }
public void SerialPortStream_Basic() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = 100; src.ReadTimeout = 100; Assert.IsTrue(src.CanRead); Assert.IsFalse(src.CanWrite); Assert.AreEqual(c_SourcePort, src.PortName); Assert.AreEqual(0, src.BytesToRead); Assert.AreEqual(0, src.BytesToWrite); src.Open(); Assert.IsTrue(src.CanRead); Assert.IsTrue(src.CanWrite); Assert.IsTrue(src.IsOpen); src.Close(); Assert.IsTrue(src.CanRead); Assert.IsFalse(src.CanWrite); Assert.IsFalse(src.IsOpen); } }
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"); } }
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_SendAndFlush1() { using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { // Required for com0com to send the data (the remote side must receive it) dst.Open(); src.Open(); src.WriteLine("Connected"); src.Flush(); } }
public void SerialPortStream_WriteReadLine() { 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.WriteLine("TestString"); s = dst.ReadLine(); Assert.AreEqual("TestString", s); } }
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_SendAndFlush2() { using (SerialPortStream dst = new SerialPortStream(c_DestPort, 115200, 8, Parity.None, StopBits.One)) using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { // Required for com0com to send the data (the remote side must receive it) dst.Open(); Trace.WriteLine("1. Open()"); src.Open(); Trace.WriteLine("2. WriteLine()"); src.WriteLine("Connected"); Trace.WriteLine("3. Sleep()"); System.Threading.Thread.Sleep(100); Trace.WriteLine("4. WriteLine()"); src.WriteLine("Disconnected"); Trace.WriteLine("5. Flush()"); src.Flush(); Trace.WriteLine("6. Dispose()"); } }
public void SerialPortStream_OpenInUse() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { src.Open(); using (SerialPortStream s2 = new SerialPortStream(c_SourcePort, 9600, 8, Parity.None, StopBits.One)) { bool err = false; try { s2.Open(); } catch { err = true; } Assert.IsTrue(err, "Expected exception opening the port twice"); } } }
public void SerialPortStream_NewLine() { using (SerialPortStream src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { bool exception = false; try { src.NewLine = ""; } catch (System.ArgumentException) { exception = true; } Assert.IsTrue(exception, "Expected exception when setting newline to empty string"); exception = false; try { src.NewLine = null; } catch (System.ArgumentNullException) { exception = true; } Assert.IsTrue(exception, "Expected exception when setting newline to empty string"); } }
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"); } }
private void WriteLine(SerialPortStream serialPort, string line) { if (serialPort == null || !serialPort.IsOpen) { return; } logger.Trace("Sending \"{0}\" to NTI XL2 on port {1}", line, portName); serialPort.WriteLine(line); }
public void SerialPortStream_OpenClose() { SerialPortStream src; using (src = new SerialPortStream(c_SourcePort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = 100; src.ReadTimeout = 100; Assert.IsTrue(src.CanRead); Assert.IsFalse(src.CanWrite); Assert.IsFalse(src.IsOpen); Assert.IsFalse(src.IsDisposed); src.Open(); Assert.IsTrue(src.CanRead); Assert.IsTrue(src.CanWrite); Assert.IsTrue(src.IsOpen); Assert.IsFalse(src.IsDisposed); src.Close(); Assert.IsTrue(src.CanRead); Assert.IsFalse(src.CanWrite); Assert.IsFalse(src.IsOpen); Assert.IsFalse(src.IsDisposed); src.Open(); Assert.IsTrue(src.CanRead); Assert.IsTrue(src.CanWrite); Assert.IsTrue(src.IsOpen); Assert.IsFalse(src.IsDisposed); src.Close(); Assert.IsTrue(src.CanRead); Assert.IsFalse(src.CanWrite); Assert.IsFalse(src.IsOpen); Assert.IsFalse(src.IsDisposed); } Assert.IsTrue(src.IsDisposed); }
private void Start(SerialPortStream serialPort) { // Rest the meter this.WriteLine(serialPort, NTIXL2Commands.ResetSLM); // Lock the keyboard //this.WriteLine(serialPort, NTIXL2Commands.Lock); // Start the loggin this.WriteLine(serialPort, NTIXL2Commands.StartLog); // Dt is between two measutments, if we don't do this will the first be -999 this.WriteLine(serialPort, NTIXL2Commands.InitiateMeasurement); }
/// <summary> /// Read to the line db, and disgards rest of the buffer /// </summary> /// <returns></returns> private string ReadToDB(SerialPortStream serialPort) { string result = string.Empty; // get the last line try { result = serialPort.ReadLine(); } catch (Exception exp) { logger.Error(exp, "Failed to read the result fro NTI XL2 on port {0}", portName); return "-999"; } logger.Trace("Read \"{0}\" from NTI XL2 on port {1}", result.Trim(), portName); string db = "-999"; try { int dBindex = result.IndexOf("dB"); if (dBindex > 0) { db = result.Substring(0, dBindex).Trim(); } else { logger.Warn("Result did not contain the word \"dB\" as expected."); } } catch (Exception exp) { Console.WriteLine(exp.Message); } return db; }
private bool DeviceAction(Action<SerialPortStream, CancellationToken> action) { CancellationToken token = new CancellationToken(); DateTime start = DateTime.Now; var task = Task.Factory.StartNew(() => { try { if (serialPort == null || !serialPort.IsOpen) { if (serialPort != null && serialPort.IsOpen) { performClose(); } serialPort = new SerialPortStream(this.portName); serialPort.Open(); Start(serialPort); } // discard the input buffer after if (serialPort.ReadBufferSize > 0) { try { serialPort.DiscardInBuffer(); } catch (Exception exp) { logger.Warn(exp, "Failed to clear in buffer for NTI XL2 on port {0}", portName); } } if (serialPort.WriteBufferSize > 0) { try { serialPort.DiscardOutBuffer(); } catch (Exception exp) { logger.Warn(exp, "Failed to clear in buffer for NTI XL2 on port {0}", portName); } } action(serialPort, token); OnConnectionStatus(true); } catch (Exception exp) { OnConnectionStatus(false); logger.Error(exp, "Failed to execute NTI XL2 action on port {0}.", portName); performClose(); return false; } return true; }, token); if (!task.Wait(this.TimeToTimeOut, token)) { timeouts++; logger.Error("NTI XL2 device communication timed out after {0} ms.", (DateTime.Now - start).TotalMilliseconds); OnConnectionStatus(false); token = new CancellationToken(); if (timeouts >= 2) { timeouts = 0; var closeTask = Task.Factory.StartNew(() => { performClose(true); }, token); if (!closeTask.Wait(this.TimeToTimeOut, token)) { logger.Trace("Time out trying to close the connection after a time out."); } } return false; } return task.Result; }