🔧 Modbus 协议驱动
包: Snet.Modbus | 类: ModbusOperate | 类型: 6
提供通过 TCP、UDP、RTU(串行)和 ASCII(串行)传输方式连接 Modbus 兼容设备和 PLC 的能力。
安装
dotnet add package Snet.Modbus
快速开始
using Snet.Modbus;
var op = new ModbusOperate(new ModbusData.Basics
{
IpAddress = "192.168.1.100",
Port = 502,
Station = 1,
DataFormat = Snet.Driver.Core.DataFormat.CDAB
});
var address = new Address(new List<AddressDetails>
{
new("读数", "40001", DataType.Int16),
new("读数2", "40003", DataType.Int16)
});
var result = await op.ReadAsync(address);
if (result.Status)
{
var data = result.GetSource<ConcurrentDictionary<string, AddressValue>>();
foreach (var kv in data)
Console.WriteLine($"{kv.Key} = {kv.Value.ResultValue}");
}
else
{
Console.WriteLine($"读取失败: {result.Message}");
}
// 订阅之前 绑定数据事件
op.OnDataEventAsync += async (sender, e) =>
{
if (e.Status)
{
var data = e.GetSource<ConcurrentDictionary<string, AddressValue>>();
foreach (var kv in data)
Console.WriteLine($"{kv.Key} = {kv.Value.ResultValue}");
}
else
{
Console.WriteLine($"{e.Message}");
}
};
var subAddr = new Address(new List<AddressDetails>
{
new("读数", "40001", DataType.Int16)
});
await op.SubscribeAsync(subAddr);
// 后续:取消订阅
// await op.UnSubscribeAsync(subAddr);
await op.DisposeAsync();
配置
| 参数 |
类型 |
默认值 |
描述 |
IpAddress |
string |
— |
设备 IP 地址 |
Port |
int |
502 |
TCP 端口(RTU/ASCII 忽略) |
ConnectTimeOut |
int |
1000 |
连接超时(毫秒) |
ReceiveTimeOut |
int |
1000 |
接收超时(毫秒) |
Station |
int |
1 |
从站 ID |
DataFormat |
enum |
CDAB |
多寄存器字节序(Snet.Driver.Core.DataFormat: ABCD, BADC, CDAB, DCBA) |
SleepTime |
int |
0 |
操作间隔休眠时间(毫秒) |
SocketKeepAliveTime |
int |
-1 |
套接字保活时间(-1 为默认) |
IsPersistentConnection |
bool |
true |
保持持久连接 |
AddressStartWithZero |
bool |
true |
地址编号从零开始 |
IsCheckMessageId |
bool |
true |
检查消息 ID 匹配响应 |
IsStringReverse |
bool |
false |
字符串数据反转字节序 |
SerialPortInfo |
string |
— |
串口配置信息 |
RtsEnable |
bool |
— |
启用串口 RTS |
DtrEnable |
bool |
— |
启用串口 DTR |
Crc16CheckEnable |
bool |
true |
启用 CRC16 校验验证 |
IsClearCacheBeforeRead |
bool |
false |
读取前清除缓存 |
StationCheckMatch |
bool |
true |
检查响应中站号匹配 |
ProtocolType |
enum |
ModbusTcpNet |
协议类型 |
HandleInterval |
int |
1000 |
处理间隔(毫秒) |
ChangeOut |
bool |
true |
启用变更输出 |
AllOut |
bool |
false |
启用全部输出 |
TaskNumber |
int |
5 |
并发任务数量 |
支持的协议类型
| 类型 |
描述 |
ModbusTcpNet |
以太网 TCP/IP,默认端口 502 |
ModbusUdpNet |
以太网 UDP,无连接 |
ModbusRtu |
串行 RS-232/485,二进制帧格式 |
ModbusRtuOverTcp |
通过 TCP 桥接的 RTU 帧格式 |
ModbusAscii |
串行 RS-232/485,ASCII 帧格式 |
ModbusAsciiOverTcp |
通过 TCP 桥接的 ASCII 帧格式 |
地址格式
- 线圈:
00001–09999(读写位)
- 离散输入:
10001–19999(只读位)
- 输入寄存器:
30001–39999(只读 16 位字)
- 保持寄存器:
40001–49999(读写 16 位字)
支持的操作
| 操作 |
方法 |
| 连接 |
OnAsync() |
| 断开 |
OffAsync() |
| 读取 |
ReadAsync(address) |
| 写入 |
WriteAsync(values) |
| 订阅 |
SubscribeAsync(address) |
参见