🔌 串口传输
命名空间: Snet.Core.communication.serial | 类: SerialOperate | 继承: CommunicationAbstract<SerialOperate, SerialData.Basics> | 接口: ICommunication
配置 (SerialData.Basics)
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
PortName |
string |
"COM1" |
串口号 |
BaudRate |
int |
19200 |
波特率 |
ParityBit |
Parity |
Even |
校验位 (None/Odd/Even/Mark/Space) |
DataBit |
int |
8 |
数据位 |
StopBit |
StopBits |
One |
停止位 |
WriteTimeout |
int |
1000 |
写入超时 (ms) |
ReadTimeout |
int |
1000 |
读取超时 (ms) |
ReceivedBytesThreshold |
int |
1 |
接收触发阈值 |
SendWaitInterval |
int |
5000 |
发送等待超时 (ms) |
MaxChunkSize |
int |
261120 |
每块最大字节数 |
RetrySendCount |
int |
5 |
每块重试次数 |
BufferSize |
int |
1048576 |
接收缓冲区 (1MB) |
静态方法
// 获取系统中可用串口列表
public static List<string> SerialOperate.GetPortArray()
API
// 连接 — 创建 SerialPort,打开并启动 DataReceived 事件监控
await serial.OnAsync();
// 断开 — 分离 DataReceived 事件,关闭并释放串口
await serial.OffAsync(bool hardClose = false);
// 发送 — 通过 SerialPort.BaseStream 发送,自动分包
await serial.SendAsync(byte[] data);
// 发送并等待响应 — 停止监控 → 发送 → 独占读取 → 恢复监控
await serial.SendWaitAsync(byte[] data, CancellationToken token);
// 底层对象 — 返回 SerialPort 实例
await serial.GetBaseObjectAsync();
// 状态 — 检查 _communication != null && _communication.IsOpen
await serial.GetStatusAsync();
数据接收
使用 SerialPort.DataReceived 事件进行异步数据接收监控。SendWaitAsync 期间临时分离监控实现独占读取。
使用示例
using Snet.Core.communication.serial;
using static Snet.Core.communication.serial.SerialData;
// 列出可用串口
var ports = SerialOperate.GetPortArray();
var config = new Basics {
PortName = "COM3", BaudRate = 9600,
ParityBit = Parity.None, DataBit = 8, StopBit = StopBits.One
};
var serial = await SerialOperate.InstanceAsync(config);
serial.OnDataEvent += (s, e) => {
if (e.Status && e.ResultData is byte[] data)
Console.WriteLine($"收到: {BitConverter.ToString(data)}");
};
await serial.OnAsync();
await serial.SendAsync(new byte[] { 0x01, 0x03, 0x00, 0x00, 0x00, 0x01 });
var resp = await serial.SendWaitAsync(command, new CancellationTokenSource(5000).Token);
await serial.OffAsync();
