/// <summary> /// Close the serial port connection /// </summary> public void Close() { StopReading(); _serial.Close(); OnStatusChanged?.Invoke(this, "Connection closed."); OnSerialPortOpened?.Invoke(this, false); }
/// <summary> /// Open the serial port connection /// </summary> /// <param name="portname">ttyUSB0 / ttyUSB1 / ttyUSB2 / etc.</param> /// <param name="baudrate">115200</param> /// <param name="parity">None / Odd / Even / Mark / Space</param> /// <param name="databits">5 / 6 / 7 / 8</param> /// <param name="stopbits">None / One / Two / OnePointFive</param> /// <param name="handshake">None / XOnXOff / RequestToSend / RequestToSendXOnXOff</param> public void Open( string portname = "/dev/ttyUSB0", int baudrate = 115200, Parity parity = Parity.None, int databits = 8, StopBits stopbits = StopBits.One, Handshake handshake = Handshake.None) { Close(); try { _serial.PortName = $"{portname}"; _serial.BaudRate = baudrate; _serial.Parity = parity; _serial.DataBits = databits; _serial.StopBits = stopbits; _serial.Handshake = handshake; _serial.ReadTimeout = 300; _serial.WriteTimeout = 300; _serial.Open(); _serial.DiscardInBuffer(); _serial.DiscardOutBuffer(); StartReading(); } catch (IOException exception) { OnStatusChanged?.Invoke(this, $"{portname} does not exist.{Environment.NewLine}{exception.StackTrace}"); } catch (UnauthorizedAccessException exception) { OnStatusChanged?.Invoke(this, $"{portname} already in use.{Environment.NewLine}{exception.StackTrace}"); } catch (Exception ex) { OnStatusChanged?.Invoke(this, "Error: " + ex.Message); } if (_serial.IsOpen) { var sb = StopBits.None.ToString().Substring(0, 1); switch (_serial.StopBits) { case StopBits.One: sb = "1"; break; case StopBits.OnePointFive: sb = "1.5"; break; case StopBits.Two: sb = "2"; break; } var p = _serial.Parity.ToString().Substring(0, 1); var hs = _serial.Handshake == Handshake.None ? "No Handshake" : _serial.Handshake.ToString(); OnStatusChanged?.Invoke(this, $"Connected to {_serial.PortName}: {_serial.BaudRate} bps, " + "{_serial.DataBits}{p}{sb}, {hs}."); OnSerialPortOpened?.Invoke(this, true); } else { OnStatusChanged?.Invoke(this, $"{portname} already in use."); OnSerialPortOpened?.Invoke(this, false); } }