using ScottPlot.Plottables; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.SerialPorts; using TouchSocket.Sockets; namespace SunlightCentralizedControlManagement_SCCM_.UserClass { public class AsyncSerialPortClient { public static async Task PortClient(SerialPortClient portclient, string com, int BAUD) { //var client = new SerialPortClient(); portclient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到端口 portclient.Connected = (client, e) => { return EasyTask.CompletedTask; };//成功连接到端口 portclient.Closing = (client, e) => { return EasyTask.CompletedTask; };//即将从端口断开连接。此处仅主动断开才有效。 portclient.Closed = (client, e) => { return EasyTask.CompletedTask; };//从端口断开连接,当连接不成功时不会触发。 portclient.Received = (client, e) => { _responseEvent.Set(); string DAT = e.ByteBlock.Span.ToString(Encoding.UTF8); //string DAT1 = CRCcheck16.ToCRC16(e.ByteBlock.Span.ToString(Encoding.UTF8)); return EasyTask.CompletedTask; ; }; await portclient.SetupAsync(new TouchSocketConfig() .SetSerialPortOption(new SerialPortOption() { BaudRate = BAUD,//波特率 DataBits = 8,//数据位 Parity = System.IO.Ports.Parity.None,//校验位 PortName = com,//COM StopBits = System.IO.Ports.StopBits.One,//停止位 }) .SetSerialDataHandlingAdapter(() => new PeriodPackageAdapter() { CacheTimeout = TimeSpan.FromMilliseconds(100) }) .ConfigurePlugins(a => { //a.Add(); })); await portclient.ConnectAsync(); } private static readonly ManualResetEventSlim _responseEvent = new ManualResetEventSlim(false); private static byte[] _receivedData; private static readonly object _sendLock = new object(); // 确保发送-等待过程原子性 /// /// 发送指令并等待响应,超时时间为500ms /// /// 要发送的指令字节数组 /// 从机的响应数据,超时则为null public static byte[] SendCommandAndWait(SerialPortClient serialPortClients, string command) { // lock (_sendLock) // 防止并发发送 { _receivedData = null; _responseEvent.Reset(); // 重置事件状态 serialPortClients.Send(command); // 发送指令 // 等待500毫秒或直到收到响应 bool signaled = _responseEvent.Wait(TimeSpan.FromMilliseconds(1000)); if (signaled) { return _receivedData; // 返回收到的数据 } else { // 超时处理,记录日志或抛出异常 //Console.WriteLine("警告: 等待从机响应超时 (500ms)。"); return null; // 或者可以抛出 TimeoutException } } } } }