public static List<COMPortInfo> GetCOMPortsInfo() { List<COMPortInfo> comPortInfoList = new List<COMPortInfo>(); ConnectionOptions options = ProcessConnection.ProcessConnectionOptions(); ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2"); ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0"); ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery); using (comPortSearcher) { string caption = null; foreach (ManagementObject obj in comPortSearcher.Get()) { if (obj != null) { object captionObj = obj["Caption"]; if (captionObj != null) { caption = captionObj.ToString(); if (caption.Contains("(COM")) { COMPortInfo comPortInfo = new COMPortInfo(); comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")", string.Empty); comPortInfo.Description = caption; comPortInfoList.Add(comPortInfo); } } } } } return comPortInfoList; }
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); } }