public void Connect() { try { if (_serialPort.IsOpen) { _serialPort.Close(); } _serialPort.ReadTimeout = -1; _serialPort.ErrorReceived += _serialPort_ErrorReceived; _serialPort.Open(); if (_serialPort.IsOpen) { if (OnConnected != null) { OnConnected(); } _continue = true; _serialReadThread = new Thread(SerialPortRead); _serialReadThread.Start(); } } catch (Exception e) { if (OnDisconnected != null) { OnDisconnected(e.Message); } } }
private void portSelect_SelectedIndexChanged(object sender, EventArgs e) { if ((string)portSelect.SelectedItem == "(none)") { portStream.Close(); } else { try { portStream.PortName = (string)portSelect.SelectedItem; portStream.Open(); } catch { portStream.Close(); RefreshPorts(); } } transmitButton.Enabled = portStream.IsOpen; if (portStream.IsOpen) { statLabel.Text = "Connected to " + portStream.PortName; } else { statLabel.Text = "Not connected"; } }
/// <summary> /// 接続を閉じます /// </summary> public void Close() { _logger.LogTrace("Close"); if (serialPort.IsOpen) { serialPort.Close(); } }
public void CanDisconnectAndDestroy() { EnsureConnected(); extension.CallArgs(theirPort, "disconnect"); extension.CallArgs("destroy", theirPort); ourPort.Close(); connected = false; }
private void Shutdown() { _Log("Shutting down Server..."); if (serialDevice.IsOpen) { serialDevice.Close(); } _Log("Shutting down Server...1"); telnetServer.Stop(); bCrashed = true; _Log("Shutting down Server... Done"); }
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 Close() { if (device.IsOpen) { device.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 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(); } }
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 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 async Task Disconnect() { await Task.Run(() => { if (IoPort.IsOpen) { State = ConnectionState.Disconnecting; try { //IoPort.DataReceived -= serialPort_DataReceived; IoPort.DiscardInBuffer(); IoPort.DiscardOutBuffer(); IoPort.Close(); Console.Out.WriteLine("Closed serialport."); } catch (Exception) { Console.Out.WriteLine("Failed to close serialport."); } State = ConnectionState.Disconnected; } }); }
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 void Dispose() { if (_serialPort.IsOpen) { _serialPort.Close(); } _serialPort.Dispose(); }
public void Shutdown() { lock (port) { port.Close(); } isInitialized = false; }
public Dictionary <string, int> GetAvailablePortsAndAutoDiscover() { trackers = new Dictionary <string, int>(); foreach (string portName in SerialPortStream.GetPortNames()) { Console.WriteLine("Autodiscover port:"); Console.WriteLine(portName); try { autoDiscoverPort = new SerialPortStream(portName, 115200, 8, Parity.None, StopBits.One) { StopBits = StopBits.One, WriteTimeout = 1000, ReadTimeout = 3000 }; stopWatch = new Stopwatch(); stopWatch.Start(); autoDiscoverPort.DataReceived += SerialPortAutoDiscover; autoDiscoverPort.Open(); autoDiscoverPort.WriteLine(SerialMessageParser.Encode("DISCOVERY")); } catch (UnauthorizedAccessException) { autoDiscoverPort.Close(); } catch (System.IO.IOException) { autoDiscoverPort.Close(); } catch (TimeoutException) { autoDiscoverPort.Close(); } while (autoDiscoverPort.IsOpen) { if (stopWatch.ElapsedMilliseconds >= 3000) { autoDiscoverPort.Close(); } } autoDiscoverPort.Dispose(); } return(trackers); }
public void Dispose() { foreach (IGroup grp in _grps) { grp.Dispose(); } _grps.Clear(); _serialPort.Close(); }
private void CloseChannel() { _timerCheckPortIsOpened.Stop(); if (_port.IsOpen) { _port.Close(); } Log.Log("Последовательный канал закрыт"); }
public bool Close() { _stream?.Close(); if (_stream != null) { _stream.DataReceived -= _stream_DataReceived; } _connected = false; return(true); }
//Close Port public void Close() { try { port.Close(); port.DataReceived -= port_DataReceived; port = null; } catch (Exception ex) { Log.Trace(ex.Message, ex.StackTrace, configuration.Verbose); } }
internal void OpenSerialPorts(object obj) { try { _relayerPortA.Open(); _relayerPortB.Open(); _snifferPortAB.Open(); _snifferPortBA.Open(); IsOpen = true; _logger.Info("Connected to serial ports"); } catch (Exception ex) { _relayerPortA.Close(); _relayerPortB.Close(); _snifferPortAB.Close(); _snifferPortBA.Close(); IsOpen = false; _logger.Error("Unable to connect to serial ports: \"{0}\"", ex.Message); System.Windows.MessageBox.Show(ex.Message); } }
public void Dispose() { _reader?.Close(); _reader?.Dispose(); _writer?.Close(); _writer?.Dispose(); _portStream?.Close(); _portStream?.Dispose(); }
public void Dispose() { if (port != null) { if (port.IsOpen) { port.Close(); } port.Dispose(); } }
public void DisconnectOnReadCharBlocked() { using (SerialPortStream serialSource = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) { serialSource.Open(); int c = serialSource.ReadChar(); Console.WriteLine("{0} char read", c); // Device should still be open. Assert.That(serialSource.IsOpen, Is.True); serialSource.Close(); } }
public void ClosedWhenBlockedResetHandshake() { 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.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); new Thread( () => { Thread.Sleep(2000); Console.WriteLine("Closing serialSource but first setting handshake to NONE"); // It appears that the MSDN .NET implementation blocks here, never // to return as we're blocked on another thread. closedEvent.Set(); // In an attempt to "unblock" on MONO, we thought we could set the // handlshake to none. What happens instead, it blocks here which // is also an error, and so a new test case. serialSource.Handshake = Handshake.None; Console.WriteLine("Closing serialSource"); serialSource.Close(); Console.WriteLine("Closed serialSource"); } ).Start(); Assert.That( () => { int bufferCount = 1024 * 1024; while (bufferCount > 0) { serialSource.Write(buffer, 0, buffer.Length); if (closedEvent.WaitOne(0)) { Assert.Fail("Write returned after being closed."); } bufferCount -= buffer.Length; Console.WriteLine("{0}", bufferCount); } }, Throws.InstanceOf <System.IO.IOException>()); } }
private int SerialCheckLibrary() { try { SerialPortStream _serial = new SerialPortStream(); // todo remove _serial.Close(); return(0); } catch (FileNotFoundException) { return(-1); } catch (TypeLoadException) { return(-1); } catch (Exception) { return(-2); } }
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); }
public void OpenClose() { SerialPortStream src; using (src = new SerialPortStream(SourcePort, 115200, 8, Parity.None, StopBits.One)) { src.WriteTimeout = 100; src.ReadTimeout = 100; Assert.That(src.CanRead, Is.True); Assert.That(src.CanWrite, Is.False); Assert.That(src.IsOpen, Is.False); Assert.That(src.IsDisposed, Is.False); src.Open(); Assert.That(src.CanRead, Is.True); Assert.That(src.CanWrite, Is.True); Assert.That(src.IsOpen, Is.True); Assert.That(src.IsDisposed, Is.False); src.Close(); Assert.That(src.CanRead, Is.True); Assert.That(src.CanWrite, Is.False); Assert.That(src.IsOpen, Is.False); Assert.That(src.IsDisposed, Is.False); src.Open(); Assert.That(src.CanRead, Is.True); Assert.That(src.CanWrite, Is.True); Assert.That(src.IsOpen, Is.True); Assert.That(src.IsDisposed, Is.False); src.Close(); Assert.That(src.CanRead, Is.True); Assert.That(src.CanWrite, Is.False); Assert.That(src.IsOpen, Is.False); Assert.That(src.IsDisposed, Is.False); } Assert.That(src.IsDisposed, Is.True); }
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_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"); } }