diff --git a/NewLife.ModbusRTU/Controllers/DefaultSerialPort.cs b/NewLife.ModbusRTU/Controllers/DefaultSerialPort.cs index 3359aa2..4f76485 100644 --- a/NewLife.ModbusRTU/Controllers/DefaultSerialPort.cs +++ b/NewLife.ModbusRTU/Controllers/DefaultSerialPort.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO.Ports; using NewLife.Data; +using NewLife.Net; namespace NewLife.IoT.Controllers; @@ -24,7 +25,12 @@ public class DefaultSerialPort : DisposeBase, ISerialPort /// 缓冲区大小。默认256 public Int32 BufferSize { get; set; } = 256; + /// 收到数据事件 + public event EventHandler? Received; + private SerialPort? _port; + /// 串口对象 + public Object Port => _port ??= new(PortName, Baudrate) { ReadTimeout = Timeout, WriteTimeout = Timeout }; /// 销毁 /// @@ -32,7 +38,12 @@ protected override void Dispose(Boolean disposing) { base.Dispose(disposing); - _port.TryDispose(); + if (_port != null) + { + if (Received != null) _port.DataReceived -= OnReceiveSerial; + + _port.TryDispose(); + } } /// 打开 @@ -49,9 +60,21 @@ public virtual void Open() ReadTimeout = Timeout, WriteTimeout = Timeout }; + + if (Received != null) _port.DataReceived += OnReceiveSerial; + _port.Open(); } + void OnReceiveSerial(Object sender, SerialDataReceivedEventArgs e) + { + var rs = Invoke(null, 1); + if (rs != null) + { + Received?.Invoke(this, new ReceivedEventArgs { Packet = rs }); + } + } + /// 发送数据 /// 待发送数据 /// 偏移