M5Unit-8Encoder驱动库:工业级8路编码器I²C嵌入式实践
2026/4/11 23:22:08
usingSystem.IO.Ports;usingSystem.Threading;usingSystem.Collections.Concurrent;publicclassSerialPortManager:IDisposable{privateSerialPort_serialPort;privateThread_readThread;privateThread_writeThread;privateConcurrentQueue<byte[]>_dataQueue=newConcurrentQueue<byte[]>();privateAutoResetEvent_writeEvent=newAutoResetEvent(false);privateSemaphoreSlim_serialLock=newSemaphoreSlim(1,1);publiceventAction<byte[]>DataReceived;publicSerialPortManager(stringportName,intbaudRate){InitializePort(portName,baudRate);StartThreads();}privatevoidInitializePort(stringportName,intbaudRate){_serialPort=newSerialPort(portName,baudRate){Parity=Parity.None,DataBits=8,StopBits=StopBits.One,ReadTimeout=500,WriteTimeout=500};_serialPort.DataReceived+=(s,e)=>{varbuffer=newbyte[_serialPort.BytesToRead];_serialPort.Read(buffer,0,buffer.Length);_dataQueue.Enqueue(buffer);DataReceived?.Invoke(buffer);};}privatevoidStartThreads(){_readThread=newThread(ProcessIncomingData);_writeThread=newThread(ProcessOutgoingData);_readThread.Start();_writeThread.Start();}publicasyncTaskSendDataAsync(byte[]data){await_serialLock.WaitAsync();try{_writeEvent.Set();_serialPort.Write(data,0,data.Length);}finally{_serialLock.Release();}}privatevoidProcessIncomingData(){while(!_serialPort.IsOpen)Thread.Sleep(100);while(true){if(_dataQueue.TryDequeue(outvardata)){// 数据解析逻辑ParseData(data);}Thread.Sleep(10);}}privatevoidProcessOutgoingData(){while(true){_writeEvent.WaitOne();// 发送队列处理逻辑}}privatevoidParseData(byte[]data){// 实现具体协议解析}publicvoidDispose(){_serialLock.Dispose();_writeEvent.Dispose();_serialPort?.Close();_serialPort?.Dispose();}}privateConcurrentQueue<byte[]>_readBuffer=newConcurrentQueue<byte[]>();privateConcurrentQueue<byte[]>_processBuffer=newConcurrentQueue<byte[]>();// 数据接收线程voidReceiveThread(){while(true){if(_serialPort.BytesToRead>0){varbuffer=newbyte[_serialPort.BytesToRead];_serialPort.Read(buffer,0,buffer.Length);_readBuffer.Enqueue(buffer);}Thread.Sleep(1);}}// 数据处理线程voidProcessThread(){while(true){if(_readBuffer.TryDequeue(outvardata)){_processBuffer.Enqueue(ProcessData(data));}}}publicasyncTask<byte[]>ReadAsync(CancellationTokenct){await_serialLock.WaitAsync(ct);try{varbuffer=newbyte[1024];intbytesRead=await_serialPort.BaseStream.ReadAsync(buffer,0,buffer.Length,ct);Array.Resize(refbuffer,bytesRead);returnbuffer;}finally{_serialLock.Release();}}publicasyncTaskWriteAsync(byte[]data,CancellationTokenct){await_serialLock.WaitAsync(ct);try{await_serialPort.BaseStream.WriteAsync(data,0,data.Length,ct);}finally{_serialLock.Release();}}publicvoidSafeWrite(byte[]data){try{_serialLock.Wait();_serialPort.Write(data,0,data.Length);}catch(TimeoutExceptionex){HandleTimeout();}catch(IOExceptionex){HandleDeviceDisconnect();}finally{_serialLock.Release();}}privatevoidHandleDeviceDisconnect(){_serialLock.Wait();try{if(_serialPort.IsOpen)_serialPort.Close();Thread.Sleep(1000);ReinitializePort();}finally{_serialLock.Release();}}privatevoidReinitializePort(){InitializePort(_config.PortName,_config.BaudRate);StartThreads();}参考代码 c#编写串口通讯代码多线程www.youwenfan.com/contentcsr/111962.html
privateObjectPool<byte[]>_bufferPool=newObjectPool<byte[]>(()=>newbyte[1024],10);byte[]GetBuffer()=>_bufferPool.Get();voidReturnBuffer(byte[]buffer)=>_bufferPool.Return(buffer);publicvoidProcessBatchData(IEnumerable<byte[]>dataArray){Parallel.ForEach(dataArray,data=>{varparsed=ParseData(data);lock(_processedData){_processedData.Add(parsed);}});}varmanager=newSerialPortManager("COM3",115200);// 异步发送数据awaitmanager.SendDataAsync(Encoding.UTF8.GetBytes("Hello"));// 接收回调处理manager.DataReceived+=(data)=>{vartext=Encoding.UTF8.GetString(data);Console.WriteLine($"Received:{text}");};// 后台数据处理Task.Run(()=>{while(true){if(manager.TryDequeueProcessedData(outvardata)){UpdateUI(data);}}});publicvoidLogCommunication(stringmessage){lock(_logLock){File.AppendAllText("com_log.txt",$"{DateTime.Now:HH:mm:ss.fff}-{message}{Environment.NewLine}");}}publicclassSerialStatus{publicintBytesSent{get;privateset;}publicintBytesReceived{get;privateset;}publicvoidIncrementSent(intcount)=>BytesSent+=count;publicvoidIncrementReceived(intcount)=>BytesReceived+=count;}publicclassModbusParser{publicstaticDictionary<byte,ushort>ParseFrame(byte[]data){// 实现Modbus RTU协议解析returnnewDictionary<byte,ushort>();}}publicclassSecureSerialPort{privateAes_aes=Aes.Create();publicbyte[]Encrypt(byte[]data){using(varencryptor=_aes.CreateEncryptor())using(varms=newMemoryStream()){cs.Write(data,0,data.Length);returnms.ToArray();}}}线程模型选择
优先使用Task替代传统Thread
高频数据采用BlockingCollection实现生产者-消费者模式
资源管理规范
using(varmanager=newSerialPortManager()){// 自动释放资源}性能监控指标
串口缓冲区占用率
数据处理延迟
异常发生频率