Smart.Modbus 2.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Smart.Modbus --version 2.0.0
                    
NuGet\Install-Package Smart.Modbus -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Smart.Modbus" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Smart.Modbus" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Smart.Modbus" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Smart.Modbus --version 2.0.0
                    
#r "nuget: Smart.Modbus, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Smart.Modbus@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Smart.Modbus&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Smart.Modbus&version=2.0.0
                    
Install as a Cake Tool

Smart.Modbus

NuGet

English | 中文

<a name="english"></a>

English

Smart.Modbus is a comprehensive Modbus protocol encapsulation library for .NET 6, 8, 9, and 10. It provides framing, response validation, parsing, and data buffering for Modbus RTU, Modbus TCP, and Modbus ASCII. It is designed to handle the protocol layer efficiently, separating protocol logic from communication logic.

Note: This library handles Protocol Processing only. It does not include the communication layer (Serial Port, TCP Client/Server). You need to implement the data transmission yourself or use a communication library like Smart.Ports.

Features

  • Protocol Support: Full support for Modbus RTU, Modbus TCP, and Modbus ASCII.
  • Master & Slave: Separate implementations for Master (IModbusMaster) and Slave (IModbusSlave) logic.
  • Function Codes: Supports standard function codes:
    • 0x01 Read Coils
    • 0x02 Read Discrete Inputs
    • 0x03 Read Holding Registers
    • 0x04 Read Input Registers
    • 0x05 Write Single Coil
    • 0x06 Write Single Register
    • 0x08 Diagnostics
    • 0x0F Write Multiple Coils
    • 0x10 Write Multiple Registers
  • Data Parsing: Built-in methods to parse response data into usable types (bools, ushorts, etc.).
  • Validation: Automatic CRC16 (RTU) / LRC (ASCII) and frame validation.
  • Data Buffering: Smart data buffering mechanism to handle packet fragmentation and sticking (sticky packets).

Installation

Install the package via NuGet:

dotnet add package Smart.Modbus

Usage Examples

1. Creating a Master

Use ModbusFactory to create a master instance for your desired protocol.

using Smart.Modbus;

// Create a Modbus RTU Master
IModbusMaster rtuMaster = ModbusFactory.CreateMaster(ModbusType.ModbusRTU);

// Create a Modbus TCP Master
IModbusMaster tcpMaster = ModbusFactory.CreateMaster(ModbusType.ModbusTCP);
2. Building Requests

Generate the byte array for a Modbus request.

// Build a request to read 10 Holding Registers starting at address 0 from Slave ID 1
byte[] requestFrame = rtuMaster.BuildReadHoldingRegistersRequest(slaveId: 1, startAddress: 0, quantity: 10);

// Send 'requestFrame' via your communication channel (SerialPort, TcpClient, etc.)
// stream.Write(requestFrame, 0, requestFrame.Length);
3. Processing Responses

Handle incoming data, validate it, and parse the results.

// Assume 'receivedData' is the byte array read from your communication channel
List<byte[]> validFrames = rtuMaster.FetchData(receivedData);

foreach (var frame in validFrames)
{
    // Validate the frame (CRC, structure, etc.)
    var validation = rtuMaster.ValidateResponse(frame);
    if (validation.Valid)
    {
        // Parse the data (e.g., if it was a Read Holding Registers response)
        ushort[] registers = rtuMaster.ParseRegistersResponse(frame);
        Console.WriteLine($"Register 0 Value: {registers[0]}");
    }
    else
    {
        Console.WriteLine($"Validation failed: {validation.Fail}");
    }
}
4. Creating a Slave

Use ModbusFactory to create a slave instance to handle incoming requests.

IModbusSlave rtuSlave = ModbusFactory.CreateSlave(ModbusType.ModbusRTU);

// Process incoming request data
List<byte[]> requests = rtuSlave.FetchData(receivedBytes);

foreach (var req in requests)
{
    var validation = rtuSlave.ValidateRequest(req);
    if (validation.Valid)
    {
        // Parse the request to determine action
        var (startAddress, quantity) = rtuSlave.ParseReadRequest(req);
        
        // Prepare response data (simulate reading data)
        ushort[] data = new ushort[quantity]; 
        // ... fill data ...

        // Build response frame
        byte[] response = rtuSlave.BuildReadHoldingRegistersResponse(slaveId: 1, data);
        
        // Send 'response' back to master
    }
}

<a name="chinese"></a>

中文

Smart.Modbus 是一个适用于 .NET 6、8、9 和 10 的 Modbus 协议封装库。它提供了 Modbus RTU、Modbus TCP 和 Modbus ASCII 的组帧、响应校验、解析以及数据缓冲功能。该库的设计理念是将协议逻辑与通信逻辑分离,专注于高效的协议处理。

注意:本库仅处理 协议层 逻辑。它不包含通信层(串口、TCP 客户端/服务端)的实现。你需要自行实现数据传输,或配合 Smart.Ports 等通信库使用。

功能特性

  • 多协议支持: 全面支持 Modbus RTU、Modbus TCP 和 Modbus ASCII。
  • 主从站支持: 分别为主站 (IModbusMaster) 和从站 (IModbusSlave) 提供了独立的逻辑实现。
  • 功能码: 支持标准功能码:
    • 0x01 读取线圈
    • 0x02 读取离散输入
    • 0x03 读取保持寄存器
    • 0x04 读取输入寄存器
    • 0x05 写单个线圈
    • 0x06 写单个寄存器
    • 0x08 诊断
    • 0x0F 写多个线圈
    • 0x10 写多个寄存器
  • 数据解析: 内置方法将响应数据解析为可用类型(bool, ushort 等)。
  • 自动校验: 自动进行 CRC16 (RTU) / LRC (ASCII) 及帧结构校验。
  • 数据缓冲: 智能的数据缓冲机制,有效处理分包和粘包问题。

安装

通过 NuGet 安装:

dotnet add package Smart.Modbus

使用示例

1. 创建主站 (Master)

使用 ModbusFactory 创建所需协议的主站实例。

using Smart.Modbus;

// 创建 Modbus RTU 主站
IModbusMaster rtuMaster = ModbusFactory.CreateMaster(ModbusType.ModbusRTU);

// 创建 Modbus TCP 主站
IModbusMaster tcpMaster = ModbusFactory.CreateMaster(ModbusType.ModbusTCP);
2. 构建请求

生成 Modbus 请求帧的字节数组。

// 构建请求:从站号 1,起始地址 0,读取 10 个保持寄存器
byte[] requestFrame = rtuMaster.BuildReadHoldingRegistersRequest(slaveId: 1, startAddress: 0, quantity: 10);

// 通过你的通信通道发送 'requestFrame' (如 SerialPort, TcpClient 等)
// stream.Write(requestFrame, 0, requestFrame.Length);
3. 处理响应

处理接收到的数据,进行校验和解析。

// 假设 'receivedData' 是从通信通道读取到的字节数组
List<byte[]> validFrames = rtuMaster.FetchData(receivedData);

foreach (var frame in validFrames)
{
    // 校验帧 (CRC, 结构等)
    var validation = rtuMaster.ValidateResponse(frame);
    if (validation.Valid)
    {
        // 解析数据 (例如:如果是读取保持寄存器的响应)
        ushort[] registers = rtuMaster.ParseRegistersResponse(frame);
        Console.WriteLine($"寄存器 0 的值: {registers[0]}");
    }
    else
    {
        Console.WriteLine($"校验失败: {validation.Fail}");
    }
}
4. 创建从站 (Slave)

使用 ModbusFactory 创建从站实例以处理传入的请求。

IModbusSlave rtuSlave = ModbusFactory.CreateSlave(ModbusType.ModbusRTU);

// 处理传入的请求数据
List<byte[]> requests = rtuSlave.FetchData(receivedBytes);

foreach (var req in requests)
{
    var validation = rtuSlave.ValidateRequest(req);
    if (validation.Valid)
    {
        // 解析请求以确定操作
        var (startAddress, quantity) = rtuSlave.ParseReadRequest(req);
        
        // 准备响应数据 (模拟读取数据)
        ushort[] data = new ushort[quantity]; 
        // ... 填充数据 ...

        // 构建响应帧
        byte[] response = rtuSlave.BuildReadHoldingRegistersResponse(slaveId: 1, data);
        
        // 将 'response' 发回给主站
    }
}

Developed by zenglei

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.2 82 3/3/2026
2.0.1 92 2/11/2026
2.0.0 95 2/10/2026
2.0.0-beta.41 53 12/30/2025
2.0.0-beta.40 250 11/17/2025
2.0.0-beta.39 161 10/28/2025
2.0.0-beta.38 153 10/22/2025
2.0.0-beta.37 153 10/22/2025
2.0.0-beta.36 144 10/22/2025
2.0.0-beta.35 148 10/22/2025
2.0.0-beta.34 158 10/21/2025
2.0.0-beta.33 148 10/21/2025
2.0.0-beta.32 153 10/21/2025
2.0.0-beta.31 133 10/17/2025
2.0.0-beta.30 138 10/16/2025
2.0.0-beta.29 143 10/15/2025
2.0.0-beta.28 157 10/15/2025
2.0.0-beta.27 149 10/14/2025
2.0.0-beta.26 150 10/14/2025
2.0.0-beta.25 152 10/14/2025
Loading failed