Files
KinginfoGateway/doc/docs/20001.mdx
Kimdiego2098 9e0b1dc8aa 更新文档
2024-02-18 16:05:18 +08:00

97 lines
2.7 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
id: 20001
title: Modbus
---
import useBaseUrl from "@docusaurus/useBaseUrl";
import Tag from "@site/src/components/Tag.js";
import Highlight from '@site/src/components/Highlight.js';
## 定义
程序集:[ThingsGateway.Foundation.Modbus](https://www.nuget.org/packages/ThingsGateway.Foundation.Modbus)
## 一、说明
**ThingsGateway.Foundation.Modbus**是对于Modbus协议的封装类库
支持Tcp/Rtu格式
支持多个通讯链路Tcp/Udp/SerialPort
支持Dtu
## 二、Modbus主站
1、创建ModbusMaster
```
/// <summary>
/// 新建链路
/// </summary>
/// <returns></returns>
public IChannel GetChannel()
{
TouchSocketConfig touchSocketConfig = new TouchSocketConfig();
return touchSocketConfig.GetSerialPortWithOption(new("COM1")); //直接获取串口对象
//return touchSocketConfig.GetChannel(ChannelTypeEnum.SerialPortClient, null, null, new("COM1"));//通过链路枚举获取对象
}
/// <summary>
/// 新建协议对象
/// </summary>
/// <param name="channel"></param>
/// <returns></returns>
public IProtocol GetProtocol(IChannel channel)
{
var client = new ModbusMaster(channel);
return client;
}
```
2、读写操作
```
ModbusMaster modbusMasterTest = new ModbusMaster();
var channel = modbusMasterTest.GetChannel();
var protocol = modbusMasterTest.GetProtocol(channel);
var data = await protocol.ReadDoubleAsync("400001"); //读取保持寄存器地址0
```
`400001`是PLC Modbus的地址表示方式代表保持寄存器地址0
- 基本地址
Modbus PLC寄存器
| 地址 | 功能码 | 说明 |
| ---------------| --------------|--------------------------|
| 4xxxxx | 03 | 读取03功能码 |
| 3xxxxx | 04 | 读取04功能码 |
| 1xxxxx | 02 | 读取02功能码 |
| 0xxxxx | 01 | 读取01功能码 |
- 站号(可选)
当需要指定站号地址时可使用,举例:
| 地址 | 说明 |
| ---------------| --------------------------|
| s=2;10001 | 读取02功能码 ,设备地址为2 |
| s=11;40001 | 读取03功能码 ,设备地址为11 |
- Dtu注册(可选)
当需要指定Dtu客户端可使用举例
| 地址 | 说明 |
| ---------------| --------------------------|
| id=12;40001 | 读取03功能码 ,设备地址为默认Dtu注册包为"12",注意是UTF8格式 |
## 三、Modbus从站