Skip to content

Commit

Permalink
串口接口支持收到数据后的事件通知
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Dec 10, 2023
1 parent 30e92a2 commit eebbe70
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion NewLife.ModbusRTU/Controllers/DefaultSerialPort.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Diagnostics.CodeAnalysis;
using System.IO.Ports;
using NewLife.Data;
using NewLife.Net;

namespace NewLife.IoT.Controllers;

Expand All @@ -24,15 +25,25 @@ public class DefaultSerialPort : DisposeBase, ISerialPort
/// <summary>缓冲区大小。默认256</summary>
public Int32 BufferSize { get; set; } = 256;

/// <summary>收到数据事件</summary>
public event EventHandler<ReceivedEventArgs>? Received;

Check warning on line 29 in NewLife.ModbusRTU/Controllers/DefaultSerialPort.cs

View workflow job for this annotation

GitHub Actions / build-publish

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 29 in NewLife.ModbusRTU/Controllers/DefaultSerialPort.cs

View workflow job for this annotation

GitHub Actions / build-publish

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

private SerialPort? _port;

Check warning on line 31 in NewLife.ModbusRTU/Controllers/DefaultSerialPort.cs

View workflow job for this annotation

GitHub Actions / build-publish

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
/// <summary>串口对象</summary>
public Object Port => _port ??= new(PortName, Baudrate) { ReadTimeout = Timeout, WriteTimeout = Timeout };

/// <summary>销毁</summary>
/// <param name="disposing"></param>
protected override void Dispose(Boolean disposing)
{
base.Dispose(disposing);

_port.TryDispose();
if (_port != null)
{
if (Received != null) _port.DataReceived -= OnReceiveSerial;

_port.TryDispose();
}
}

/// <summary>打开</summary>
Expand All @@ -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 });
}
}

/// <summary>发送数据</summary>
/// <param name="buffer">待发送数据</param>
/// <param name="offset">偏移</param>
Expand Down

0 comments on commit eebbe70

Please sign in to comment.