CommonSerialDevice(通用串口设备)
命名空间: TestWorks.Device.CommonSerial
继承自: DeviceBase(提供 Name, IsConnected, LogService 等基础成员)
提供通用的串口收发功能,支持发送命令并等待响应,内置重试机制。
1.1 属性
| 名称 | 类型 | 描述 |
|---|---|---|
SerialConfig |
CommonSerialConfig |
当前串口配置(只读) |
Name |
string |
设备名称(继承自基类) |
IsConnected |
bool |
连接状态(继承自基类) |
LogService |
ILogService |
日志服务(继承自基类) |
1.2 构造函数
public CommonSerialDevice(CommonSerialConfig config, string name)
| 参数 | 类型 | 说明 |
|---|---|---|
config |
CommonSerialConfig |
串口配置(端口、波特率、校验位等) |
name |
string |
设备名称 |
1.3 方法
Connect()
打开串口。
public override bool Connect()
| 返回 | 说明 |
|---|---|
bool |
true 成功打开串口,false 失败 |
Disconnect()
关闭串口。
public override void Disconnect()
UpdateConfig(object newConfig)
更新串口配置,若当前已连接则自动重连。
public override void UpdateConfig(object newConfig)
| 参数 | 类型 | 说明 |
|---|---|---|
newConfig |
CommonSerialConfig |
新配置对象 |
SendAndReceive(string command, int timeout = 500, int DelayRead = 20, string lineEnding = “\r\n”)
发送命令并等待接收响应数据(同步阻塞)。
public string SendAndReceive(string command, int timeout = 500, int DelayRead = 20, string lineEnding = "\r\n")
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
command |
string |
– | 要发送的命令字符串(若不以换行符结尾,自动追加 lineEnding) |
timeout |
int |
500 | 等待接收数据的超时时间(毫秒) |
DelayRead |
int |
20 | 检测到数据后额外延时(毫秒),确保数据完整 |
lineEnding |
string |
"\r\n" |
命令结尾附加的换行符 |
| 返回 | 说明 |
|---|---|
string |
接收到的响应字符串(已去除换行符和末尾的 $ 字符),若超时或失败返回 null 或 string.Empty |
示例:
string response = device.SendAndReceive("AT", timeout: 1000);
if (!string.IsNullOrEmpty(response)) {
Console.WriteLine($"响应: {response}");
}
SendAndReceiveTry(string command, int timeout = 500, int DelayRead = 20, string lineEnding = “\r\n”, string lineStart = “ok”, int tryTimes = 3)
发送命令,若响应内容不以指定前缀开头则自动重试。
public string SendAndReceiveTry(string command, int timeout = 500, int DelayRead = 20, string lineEnding = "\r\n", string lineStart = "ok", int tryTimes = 3)
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
command |
string |
– | 要发送的命令 |
timeout |
int |
500 | 单次超时(毫秒) |
DelayRead |
int |
20 | 数据延时读取 |
lineEnding |
string |
"\r\n" |
换行符 |
lineStart |
string |
"ok" |
期望响应起始字符串(不区分大小写) |
tryTimes |
int |
3 | 最大重试次数(含首次) |
| 返回 | 说明 |
|---|---|
string |
最后一次响应结果(即使不符合前缀也返回) |