using MV485.model; using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Management; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace MV485.helper { //串口工具类 public class SerialHelper { public static string[] BaudRates = new string[] { "115200", "57600","56000", "38400", "19200","14400", "9600", "4800", "2400", "1200", "600", "300", "110" }; public static List GetSerialPortsWithDetails() { List ports = new List(); using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%(COM%'")) { foreach (ManagementObject obj in searcher.Get()) { string name = obj["Name"]?.ToString() ?? "未知设备"; // 获取完整设备名称 string port = ExtractCOMPort(name); // 提取 COM 端口号 if (!string.IsNullOrEmpty(port)) { string cleanName = CleanDeviceName(name); // 清理设备名称 ports.Add(new SPortModel(port, cleanName)); } } } return ports; } private static string ExtractCOMPort(string name) { // 处理标准格式: "USB Serial Port (COM6)" Match match = Regex.Match(name, @"\(COM\d+"); if (match.Success) { return match.Value.Trim('(', ')'); // 提取 COM 端口号 } // 处理虚拟串口: "Electronic Team Virtual Serial Port (COM1->COM2)" match = Regex.Match(name, @"\(COM\d+->COM\d+\)"); if (match.Success) { Match firstPortMatch = Regex.Match(match.Value, @"COM\d+"); if (firstPortMatch.Success) { return firstPortMatch.Value; // 只返回第一个端口 COM1 } } return string.Empty; } private static string CleanDeviceName(string name) { // 移除所有带 COMx 的部分,包括 (COMx) 和 (COMx->COMy) return Regex.Replace(name, @"\s*\(COM\d+.*?\)", "").Trim(); } //public static List GetSerialPortsWithDetails() //{ // List ports = new List(); // using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%(COM%'")) // { // foreach (ManagementObject obj in searcher.Get()) // { // string name = obj["Name"]?.ToString() ?? "未知设备"; // 设备名称 // string cleanName = Regex.Replace(name, @"\(\w+\)", "").Trim(); // string port = ExtractCOMPort(name); // 提取 COM 端口号 // if (!string.IsNullOrEmpty(port)) // { // ports.Add(new SPortModel(port, cleanName)); // } // } // } // return ports; //} //static string ExtractCOMPort(string deviceName) //{ // int start = deviceName.IndexOf("(COM"); // if (start >= 0) // { // int end = deviceName.IndexOf(")", start); // if (end > start) // { // return deviceName.Substring(start + 1, end - start - 1); // 获取 "COMX" // } // } // return null; //} //----直接获取串口名称 public static string[] GetSerialPortNames() { string[] ports = SerialPort.GetPortNames(); if (ports.Length == 0) { Console.WriteLine("未找到可用的串口设备。"); } else { Console.WriteLine("可用的串口设备:"); foreach (string port in ports) { Console.WriteLine(port); } } return ports; } } }