/// <summary> /// Check status of serial ports. /// </summary> /// <returns>A collection of serial port status.</returns> private static IEnumerable <SerialPortStatus> GetPortStatus(IEnumerable <string> serialPorts) { SerialPort serialPort = null; SerialPortStatus serialPortStatus = null; foreach (var portName in serialPorts) { try { serialPort = new SerialPort(portName); serialPort.Open(); serialPortStatus = new SerialPortStatus(portName, PortStatus.Free); } catch (UnauthorizedAccessException) { serialPortStatus = new SerialPortStatus(portName, PortStatus.InUse); } catch (Exception) { serialPortStatus = new SerialPortStatus(portName, PortStatus.Unknown); } finally { if (serialPort != null && serialPort.IsOpen) { serialPort.Close(); } } } yield return(serialPortStatus); }
public async Task Send(byte[] buffer, CancellationToken token) { if (serialPort == null) { return; } var dataWriter = new DataWriter(serialPort.OutputStream); try { if (buffer.Length != 0) { LocalLog.Instance.Info("send ->" + Common.BytesToString(buffer) + "<- end"); dataWriter.WriteBytes(buffer); var storeAsyncTask = dataWriter.StoreAsync().AsTask(token); await storeAsyncTask; } } catch (Exception ex) { Status = SerialPortStatus.Initialled; serialPort?.Dispose(); serialPort = null; throw new CustomException(ex.Message + "Send", this.GetType().FullName, ExceptionPriority.Importance); } finally { dataWriter.DetachBuffer(); dataWriter.DetachStream(); dataWriter.Dispose(); } }
public static void Read() { byte[] buffer = new byte[16]; Action kickoffRead = null; Action reconnect = null; Action next = kickoffRead; reconnect = delegate { // if (_serialPort == null || !_serialPort.IsOpen) { Debug.Log("Attempting to reconnect to port " + "COM8"); // faking the reconnection status indication. _serialPortStatus = SerialPortStatus.Reconnecting; Thread.Sleep(400); if (Connect("COM8")) { Debug.Log("We decided we are connected?"); next = kickoffRead; } else { Thread.Sleep(2600); next = reconnect; } // } if (_alive) { next(); } }; kickoffRead = delegate { _serialPort.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate(IAsyncResult ar) { try { int actualLength = _serialPort.BaseStream.EndRead(ar); byte[] received = new byte[actualLength]; Buffer.BlockCopy(buffer, 0, received, 0, actualLength); splitter.OnIncomingBinaryBlock(received); next = kickoffRead; } catch (IOException exc) { Debug.Log("Serial read fail: " + exc.ToString()); next = reconnect; } catch (InvalidOperationException exc) { Debug.Log("Serial read fail: " + exc.ToString()); next = reconnect; } if (_alive) { next(); } }, null); }; reconnect(); }
public void Cancel() { if (_readCancellationTokenSource != null) { if (!_readCancellationTokenSource.IsCancellationRequested) { _readCancellationTokenSource.Cancel(); } } Status = SerialPortStatus.Closed; }
public void Send(byte[] data, CancellationToken token) { try { client.Send(data); } catch (Exception ex) { Status = SerialPortStatus.Initialled; LogFactory.Create().Info("serial Send error:" + ex.Message); } }
public void Close() { try { Cancel(); Status = SerialPortStatus.None; LogFactory.Create().Info("serialport dispose"); } catch (Exception e) { LogFactory.Create().Info("serialport close error ->" + e.Message); } }
public async Task <SerialEnum> Open( ) { if (Status == SerialPortStatus.Initialled) { try { if (serialPort != null) { serialPort.WriteTimeout = TimeSpan.FromMilliseconds(WRITE_TIMEOUT); serialPort.ReadTimeout = TimeSpan.FromMilliseconds(READ_TIMEOUT); serialPort.BaudRate = BAUD_RATE; serialPort.Parity = SERIAL_PARITY; serialPort.StopBits = SERIAL_STOP_BIT_COUNT; serialPort.DataBits = DATA_BITS; serialPort.Handshake = SERIAL_HANDSHAKE; readCancellationTokenSource = new CancellationTokenSource(); var ping = await Ping(new byte[] { 0x01, 0x04, 0x00, 0x00, 0x00, 0x18, 0xf0 }); LocalLog.Instance.Info("PC ping" + ping); //改为 if (!string.IsNullOrEmpty(ping) && ping != "ff") { listen(1024); Status = SerialPortStatus.Opened; return(SerialEnum.LowerComputer); } ping = await Ping(Encoding.UTF8.GetBytes("AT+CCID").Concat(new byte[] { 0x0D, 0x0A }).ToArray()); LocalLog.Instance.Info("SIM ping" + ping); if (!string.IsNullOrEmpty(ping)) { listen(1024); Status = SerialPortStatus.Opened; return(SerialEnum.Sim); } Status = SerialPortStatus.Initialled; serialPort.Dispose();//该行会阻塞代码,导致不能正常返回 } return(SerialEnum.Unknown); } catch (Exception ex) { throw new CustomException(ex.Message + "open", this.GetType().FullName, ExceptionPriority.Importance); } } return(SerialEnum.Unknown); }
public async Task Open(string portName) { await Task.Yield(); if (Status == SerialPortStatus.Initialled) { try { Status = SerialPortStatus.Opening; var dis = SerialPort.GetPortNames(); if (!dis.Any()) { return; } var p = dis.FirstOrDefault(each => each.IndexOf(portName, StringComparison.OrdinalIgnoreCase) != -1); if (p == null) { return; } SerialPort = new SerialPort(p); SerialPort.WriteTimeout = 50; SerialPort.ReadTimeout = 50; SerialPort.BaudRate = 9600; SerialPort.Parity = Parity.None; SerialPort.StopBits = StopBits.One; SerialPort.DataBits = 8; SerialPort.Handshake = Handshake.None; SerialPort.WriteBufferSize = 1024; SerialPort.ReadBufferSize = 1024; SerialPort.DataReceived += SerialPort_DataReceived; SerialPort.ErrorReceived += SerialPort_ErrorReceived; _readCancellationTokenSource = new CancellationTokenSource(); SerialPort.Open(); Status = SerialPortStatus.Opened; LogFactory.Create().Info($"Serial Port {portName} {Status}"); } catch (Exception ex) { SerialPort.DataReceived -= SerialPort_DataReceived; SerialPort.ErrorReceived -= SerialPort_ErrorReceived; Status = SerialPortStatus.Initialled; SerialPort?.Close(); SerialPort?.Dispose(); LogFactory.Create().Info("port open error" + ex.Message); } } }
private async void listen(uint bufferLength) { try { readCancellationTokenSource.Token.ThrowIfCancellationRequested(); dataReader = new DataReader(serialPort.InputStream); dataReader.InputStreamOptions = InputStreamOptions.Partial; if (serialPort != null) { while (!readCancellationTokenSource.IsCancellationRequested) { var bytesRead = await dataReader.LoadAsync(bufferLength).AsTask(readCancellationTokenSource.Token); if (bytesRead > 0) { var xdata = new byte[bytesRead]; dataReader.ReadBytes(xdata); dataReader.DetachBuffer(); LocalLog.Instance.Info("receive ->" + Common.BytesToString(xdata) + "<- end"); OnReceiveHandler(xdata); } await Task.Delay(5, readCancellationTokenSource.Token); } } } catch (TaskCanceledException) { Debug.WriteLine("serial listen cancel"); Status = SerialPortStatus.Initialled; serialPort = null; } catch (Exception) { Status = SerialPortStatus.Initialled; serialPort = null; } finally { if (dataReader != null) { dataReader.DetachBuffer(); dataReader.DetachStream(); dataReader.Dispose(); } } }
public void Close() { try { serialPort?.Dispose(); serialPort = null; Status = SerialPortStatus.None; Debug.WriteLine("serialport dispose"); } catch (Exception e) { Debug.WriteLine("serialport close error ->" + e.Message); } }
public void Close() { try { SerialPort?.Dispose(); SerialPort = null; Status = SerialPortStatus.None; LogFactory.Create().Info("serialport dispose"); } catch (Exception e) { LogFactory.Create().Warnning("serialport close error ->" + e.Message); } }
public void Close() { try { serialPort?.Dispose(); serialPort = null; Status = SerialPortStatus.None; LocalLog.Instance.Info("serialport dispose"); } catch (Exception e) { LocalLog.Instance.Info("serialport close error ->" + e.Message); } }
public void Send(byte[] buffer, CancellationToken token) { //运行过程中串口异常 try { LogFactory.Create().Info($"send ->{Shunxi.Common.Utility.Common.BytesToString(buffer)}<- send end"); SerialPort.Write(buffer, 0, buffer.Length); } catch (Exception ex) { if (SerialPort != null) { SerialPort.DataReceived -= SerialPort_DataReceived; SerialPort.ErrorReceived -= SerialPort_ErrorReceived; } Status = SerialPortStatus.Initialled; SerialPort?.Close(); SerialPort?.Dispose(); LogFactory.Create().Error("usb serial port send msg error" + ex.Message); } }
/// <summary> /// 根据端口名称操作 /// </summary> /// <param name="portName">端口名</param> /// <param name="serialPortStatus">具体操作</param> /// <returns></returns> public bool OpenSerialPort(string portName, SerialPortStatus serialPortStatus) { switch (serialPortStatus) { //打开 case SerialPortStatus.Open: SerialPortObj.PortName = portName; SerialPortObj.Open(); break; //关闭 case SerialPortStatus.Close: SerialPortObj.Close(); break; default: break; } //返回串口打开的状态 return(SerialPortObj.IsOpen); }
// attempt to connec to the serial port public static bool Connect(string p) { _serialPort = new SerialPort(p, 57600); try { _serialPort.Open(); } catch (IOException exc) { Debug.Log("Connection failed: " + exc.ToString()); } if (_serialPort.IsOpen) { port = p; _serialPortStatus = SerialPortStatus.Connected; ReceiveStart = DateTime.Now; packetCount = 0; return(true); } else { _serialPortStatus = SerialPortStatus.NoConnection; return(false); } }
public async Task Open(SerialEnum serialType) { await Task.Yield(); if (Status == SerialPortStatus.Initialled) { try { Status = SerialPortStatus.Opening; client.Connect(ADDR, PORT); Status = SerialPortStatus.Opened; _readCancellationTokenSource = new CancellationTokenSource(); Listen().IgnorCompletion(); } catch (Exception e) { LogFactory.Create().Info("net serial open error" + e.Message); Status = SerialPortStatus.Initialled; } } }
/// <summary> /// Event raised by background worker, announcing status of port opening /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SerialPortOpennerCompletedHandler(object sender, RunWorkerCompletedEventArgs e) { SerialPortStatus PortState = (SerialPortStatus)e.Result; if (PortState == SerialPortStatus.Openned) { //update button caption and disable settings forms _openBtn.Text = "Close"; _portName.Enabled = false; _portBaudRate.Enabled = false; _portDatabits.Enabled = false; _portStopbits.Enabled = false; _portParity.Enabled = false; //Fire status update event if port has been openned if (PortStatusUpdated != null) { PortStatusUpdated(this, new PortStatusUpdatedEvArgs(PortState, "Serial port " + ComPort.PortName + " opened!" + Environment.NewLine)); } } else if (PortState == SerialPortStatus.Closed) { _openBtn.Text = "Open"; //update button caption and set focus to it _portName.Enabled = true; _portBaudRate.Enabled = true; _portDatabits.Enabled = true; _portStopbits.Enabled = true; _portParity.Enabled = true; _openBtn.Focus(); //Fire status update event if port has been closed if (PortStatusUpdated != null) { PortStatusUpdated(this, new PortStatusUpdatedEvArgs(PortState, "Serial port " + ComPort.PortName + " closed!" + Environment.NewLine)); } } else if (PortState == SerialPortStatus.OpenningError) { _openBtn.Text = "Open"; _portName.Enabled = true; _portBaudRate.Enabled = true; _portDatabits.Enabled = true; _portStopbits.Enabled = true; _portParity.Enabled = true; //Fire status update event if port could not be openned if (PortStatusUpdated != null) { PortStatusUpdated(this, new PortStatusUpdatedEvArgs(PortState, "Serial port " + ComPort.PortName + " could NOT be opened!" + Environment.NewLine)); } } else if (PortState == SerialPortStatus.ClosingError) { _openBtn.Text = "Close"; _portName.Enabled = false; _portBaudRate.Enabled = false; _portDatabits.Enabled = false; _portStopbits.Enabled = false; _portParity.Enabled = false; //Fire status update event if port could not be openned if (PortStatusUpdated != null) { PortStatusUpdated(this, new PortStatusUpdatedEvArgs(PortState, ("Serial port " + ComPort.PortName + " could NOT be closed!" + Environment.NewLine))); } } }
public async Task Open(SerialEnum serialType) { if (Status == SerialPortStatus.Initialled) { Stopwatch sw = new Stopwatch(); sw.Start(); Status = SerialPortStatus.Opening; var dis = SerialPort.GetPortNames(); if (!dis.Any()) { return; } foreach (COMPortInfo comPort in COMPortInfo.GetCOMPortsInfo()) { Console.WriteLine($"{comPort.Name} – {comPort.Description}"); if (comPort.Description.IndexOf("USB", StringComparison.Ordinal) == -1 && comPort.Description.IndexOf("Virtual Serial Port", StringComparison.Ordinal) == -1) { continue; } try { var portName = comPort.Name.Split("->".ToCharArray())[0]; LogFactory.Create().Info("portname:" + portName); SerialPort = new SerialPort(portName); if (SerialPort == null) { continue; } SerialPort.WriteTimeout = 50; SerialPort.ReadTimeout = 50; SerialPort.BaudRate = 9600; SerialPort.Parity = Parity.None; SerialPort.StopBits = StopBits.One; SerialPort.DataBits = 8; SerialPort.Handshake = Handshake.None; SerialPort.WriteBufferSize = 1024; SerialPort.ReadBufferSize = 1024; SerialPort.DataReceived += SerialPort_DataReceived; SerialPort.ErrorReceived += SerialPort_ErrorReceived; _readCancellationTokenSource = new CancellationTokenSource(); SerialPort.Open(); Send(generatePingBytesByType(serialType), CancellationToken.None); var cancellationToken = new CancellationTokenSource(1000).Token; completionSource = new TaskCompletionSource <byte[]>(); using (cancellationToken.Register(() => completionSource.TrySetResult(new byte[] { }))) { var x = await completionSource.Task; var ret = Shunxi.Common.Utility.Common.BytesToString(x); if (!string.IsNullOrEmpty(ret) && ret.Length > 10) { Status = SerialPortStatus.Opened; LogFactory.Create().Info($"Serial Port {portName} Opened"); break; } Status = SerialPortStatus.Initialled; SerialPort.DataReceived -= SerialPort_DataReceived; SerialPort.ErrorReceived -= SerialPort_ErrorReceived; SerialPort.Close(); SerialPort.Dispose(); SerialPort = null; } } catch (Exception ex) { if (SerialPort != null) { SerialPort.DataReceived -= SerialPort_DataReceived; SerialPort.ErrorReceived -= SerialPort_ErrorReceived; } Status = SerialPortStatus.Initialled; SerialPort?.Close(); SerialPort?.Dispose(); LogFactory.Create().Info("port open error" + ex.Message); } } sw.Stop(); LogFactory.Create().Info("open port consume time " + sw.ElapsedMilliseconds); } }
public UsbSerial() { Status = SerialPortStatus.Initialled; }
public UsbSerial(SerialPort device) { Status = SerialPortStatus.Initialled; SerialPort = device; }
public NetSerial() { client = new SocketClient(); Status = SerialPortStatus.Initialled; }
public SerialPortHelper(SerialDevice device) { serialPort = device; Status = SerialPortStatus.Initialled; }
public PortStatusUpdatedEvArgs(SerialPortStatus portStatus, string message) { this.PortStatus = portStatus; this.Message = message; }