From eebbe704eaedeb72f8d6d1f639cae21093ccdebb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=BA=E8=83=BD=E5=A4=A7=E7=9F=B3=E5=A4=B4?= Date: Mon, 11 Dec 2023 00:56:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=B2=E5=8F=A3=E6=8E=A5=E5=8F=A3=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=94=B6=E5=88=B0=E6=95=B0=E6=8D=AE=E5=90=8E=E7=9A=84?= =?UTF-8?q?=E4=BA=8B=E4=BB=B6=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/DefaultSerialPort.cs | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) 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 }); + } + } + /// 发送数据 /// 待发送数据 /// 偏移