API 参考
本节提供ModbusLink所有类和函数的详细API文档。
1. 客户端模块
1.1 SyncModbusClient
- class modbuslink.client.sync_client.SyncModbusClient(transport: SyncBaseTransport)[源代码]
基类:
object同步Modbus客户端
通过依赖注入的方式接收传输层实例,支持RTU、ASCII和TCP等不同传输方式。
Sync Modbus Client Implementation
Receive the transport layer instance through dependency injection, supporting different transmission methods such as RTU, ASCII and TCP.
- __init__(transport: SyncBaseTransport)[源代码]
初始化同步Modbus客户端
Initialize Sync Modbus Client :param transport: 传输层实例(SyncRtuTransport/SyncAsciiTransport/SyncTcpTransport) | Transport layer instance (SyncRtuTransport/SyncAsciiTransport/SyncTcpTransport)
- read_coils(slave_id: int, start_address: int, quantity: int) List[bool][源代码]
读取线圈状态(功能码0x01)
Read Coil Status (Function Code 0x01)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
quantity -- 读取数量(1-2000) | Quantity to read (1-2000)
- 返回:
线圈状态列表,True表示ON,False表示OFF
List of coil status, True for ON, False for OFF
- read_discrete_inputs(slave_id: int, start_address: int, quantity: int) List[bool][源代码]
读取离散输入状态(功能码0x02)
Read Discrete Input Status (Function Code 0x02)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
quantity -- 读取数量(1-2000) | Quantity to read (1-2000)
- 返回:
离散输入状态列表,True表示ON,False表示OFF
List of discrete input status, True for ON, False for OFF
- read_holding_registers(slave_id: int, start_address: int, quantity: int) List[int][源代码]
读取保持寄存器(功能码0x03)
Read Holding Registers (Function Code 0x03)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
quantity -- 读取数量(1-125) | Quantity to read (1-125)
- 返回:
寄存器值列表,每个值为16位无符号整数(0-65535)
List of register values, each value is a 16-bit unsigned integer (0-65535)
- read_input_registers(slave_id: int, start_address: int, quantity: int) List[int][源代码]
读取输入寄存器(功能码0x04)
Read Input Registers (Function Code 0x04)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
quantity -- 读取数量(1-125) | Quantity to read (1-125)
- 返回:
寄存器值列表,每个值为16位无符号整数(0-65535)
List of register values, each value is a 16-bit unsigned integer (0-65535)
- write_single_coil(slave_id: int, address: int, value: bool) None[源代码]
写单个线圈(功能码0x05)
Write Single Coil (Function Code 0x05)
- 参数:
slave_id -- 从站地址 | Slave address
address -- 线圈地址 | Coil address
value -- 线圈值,True表示ON,False表示OFF | Coil value, True for ON, False for OFF
- write_single_register(slave_id: int, address: int, value: int) None[源代码]
写单个寄存器(功能码0x06)
Write Single Register (Function Code 0x06)
- 参数:
slave_id -- 从站地址 | Slave address
address -- 寄存器地址 | Register address
value -- 寄存器值(0-65535) | Register value (0-65535)
- write_multiple_coils(slave_id: int, start_address: int, values: List[bool]) None[源代码]
写多个线圈(功能码0x0F)
Write Multiple Coils (Function Code 0x0F)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
values -- 线圈值列表,True表示ON,False表示OFF | List of coil values, True for ON, False for OFF
- write_multiple_registers(slave_id: int, start_address: int, values: List[int]) None[源代码]
写多个寄存器(功能码0x10)
Write Multiple Registers (Function Code 0x10)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
values -- 寄存器值列表,每个值为0-65535 | List of register values, each value 0-65535
- read_float32(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') float[源代码]
读取32位浮点数(占用2个连续寄存器)
Read 32-bit float (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
32位浮点数值
32-bit float value
- write_float32(slave_id: int, start_address: int, value: float, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') None[源代码]
写入32位浮点数(占用2个连续寄存器)
Write 32-bit float (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的浮点数值 | Float value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- read_int32(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') int[源代码]
读取32位有符号整数(占用2个连续寄存器)
Read 32-bit signed integer (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
32位有符号整数值
32-bit signed integer value
- write_int32(slave_id: int, start_address: int, value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') None[源代码]
写入32位有符号整数(占用2个连续寄存器)
Write 32-bit signed integer (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的整数值 | Integer value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- read_uint32(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') int[源代码]
读取32位无符号整数(占用2个连续寄存器)
Read 32-bit unsigned integer (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
32位无符号整数值 | 32-bit unsigned integer value
- write_uint32(slave_id: int, start_address: int, value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') None[源代码]
写入32位无符号整数(占用2个连续寄存器)
Write 32-bit unsigned integer (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的无符号整数值 | Unsigned integer value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- read_int64(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') int[源代码]
读取64位有符号整数(占用4个连续寄存器)
Read 64-bit signed integer (occupies 4 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
64位有符号整数值
64-bit signed integer value
- write_int64(slave_id: int, start_address: int, value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') None[源代码]
写入64位有符号整数(占用4个连续寄存器)
Write 64-bit signed integer (occupies 4 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的整数值 | Integer value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- read_uint64(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') int[源代码]
读取64位无符号整数(占用4个连续寄存器)
Read 64-bit unsigned integer (occupies 4 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
64位无符号整数值
64-bit unsigned integer value
- write_uint64(slave_id: int, start_address: int, value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') None[源代码]
写入64位无符号整数(占用4个连续寄存器)
Write 64-bit unsigned integer (occupies 4 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的无符号整数值 | Unsigned integer value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- read_string(slave_id: int, start_address: int, length: int, encoding: str = 'utf-8') str[源代码]
读取字符串(从连续寄存器中)
Read string (from consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
length -- 字符串字节长度 | String byte length
encoding -- 字符编码,默认'utf-8' | Character encoding, default 'utf-8'
- 返回:
解码后的字符串
Decoded string
- write_string(slave_id: int, start_address: int, value: str, encoding: str = 'utf-8') None[源代码]
写入字符串(到连续寄存器中)
Write string (to consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的字符串 | String to write
encoding -- 字符编码,默认'utf-8' | Character encoding, default 'utf-8'
- __enter__() SyncModbusClient[源代码]
上下文管理器入口
Context manager entry
1.2 AsyncModbusClient
- class modbuslink.client.async_client.AsyncModbusClient(transport: AsyncBaseTransport)[源代码]
基类:
object异步Modbus客户端
通过依赖注入的方式接收传输层实例,支持RTU、ASCII和TCP等不同传输方式。
Async Modbus Client Implementation
Receive the transport layer instance through dependency injection, supporting different transmission methods such as RTU, ASCII and TCP.
- __init__(transport: AsyncBaseTransport)[源代码]
初始化异步Modbus客户端
Initialize Async Modbus Client
- 参数:
transport -- 传输层实例(AsyncRtuTransport/AsyncAsciiTransport/AsyncTcpTransport) | Transport layer instance (AsyncRtuTransport/AsyncAsciiTransport/AsyncTcpTransport)
- async read_coils(slave_id: int, start_address: int, quantity: int, callback: Callable[[List[bool]], None] | None = None) List[bool][源代码]
读取线圈状态(功能码0x01)
Read Coil Status (Function Code 0x01)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
quantity -- 读取数量(1-2000) | Quantity to read (1-2000)
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
线圈状态列表,True表示ON,False表示OFF
List of coil status, True for ON, False for OFF
- async read_discrete_inputs(slave_id: int, start_address: int, quantity: int, callback: Callable[[List[bool]], None] | None = None) List[bool][源代码]
读取离散输入状态(功能码0x02)
Read Discrete Input Status (Function Code 0x02)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
quantity -- 读取数量(1-2000) | Quantity to read (1-2000)
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
离散输入状态列表,True表示ON,False表示OFF
List of discrete input status, True for ON, False for OFF
- async read_holding_registers(slave_id: int, start_address: int, quantity: int, callback: Callable[[List[int]], None] | None = None) List[int][源代码]
读取保持寄存器(功能码0x03)
Read Holding Registers (Function Code 0x03)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
quantity -- 读取数量(1-125) | Quantity to read (1-125)
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
寄存器值列表,每个值为16位无符号整数(0-65535)
List of register values, each value is a 16-bit unsigned integer (0-65535)
- async read_input_registers(slave_id: int, start_address: int, quantity: int, callback: Callable[[List[int]], None] | None = None) List[int][源代码]
读取输入寄存器(功能码0x04)
Read Input Registers (Function Code 0x04)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
quantity -- 读取数量(1-125) | Quantity to read (1-125)
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
寄存器值列表,每个值为16位无符号整数(0-65535)
List of register values, each value is a 16-bit unsigned integer (0-65535)
- async write_single_coil(slave_id: int, address: int, value: bool, callback: Callable[[], None] | None = None) None[源代码]
写单个线圈(功能码0x05)
Write Single Coil (Function Code 0x05)
- 参数:
slave_id -- 从站地址 | Slave address
address -- 线圈地址 | Coil address
value -- 线圈值,True表示ON,False表示OFF | Coil value, True for ON, False for OFF
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async write_single_register(slave_id: int, address: int, value: int, callback: Callable[[], None] | None = None) None[源代码]
写单个寄存器(功能码0x06)
Write Single Register (Function Code 0x06)
- 参数:
slave_id -- 从站地址 | Slave address
address -- 寄存器地址 | Register address
value -- 寄存器值(0-65535) | Register value (0-65535)
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async write_multiple_coils(slave_id: int, start_address: int, values: List[bool], callback: Callable[[], None] | None = None) None[源代码]
写多个线圈(功能码0x0F)
Write Multiple Coils (Function Code 0x0F)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
values -- 线圈值列表,True表示ON,False表示OFF | List of coil values, True for ON, False for OFF
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async write_multiple_registers(slave_id: int, start_address: int, values: List[int], callback: Callable[[], None] | None = None) None[源代码]
写多个寄存器(功能码0x10)
Write Multiple Registers (Function Code 0x10)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始地址 | Starting address
values -- 寄存器值列表,每个值为0-65535 | List of register values, each value 0-65535
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async read_float32(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[float], None] | None = None) float[源代码]
读取32位浮点数(占用2个连续寄存器)
Read 32-bit float (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
32位浮点数值
32-bit float value
- async write_float32(slave_id: int, start_address: int, value: float, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[], None] | None = None) None[源代码]
写入32位浮点数(占用2个连续寄存器)
Write 32-bit float (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的浮点数值 | Float value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async read_int32(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[int], None] | None = None) int[源代码]
读取32位有符号整数(占用2个连续寄存器)
Read 32-bit signed integer (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
32位有符号整数值
32-bit signed integer value
- async write_int32(slave_id: int, start_address: int, value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[], None] | None = None) None[源代码]
写入32位有符号整数(占用2个连续寄存器)
Write 32-bit signed integer (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的整数值 | Integer value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async read_uint32(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[int], None] | None = None) int[源代码]
读取32位无符号整数(占用2个连续寄存器)
Read 32-bit unsigned integer (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
32位无符号整数值 | 32-bit unsigned integer value
- async write_uint32(slave_id: int, start_address: int, value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[], None] | None = None) None[源代码]
写入32位无符号整数(占用2个连续寄存器)
Write 32-bit unsigned integer (occupies 2 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的无符号整数值 | Unsigned integer value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async read_int64(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[int], None] | None = None) int[源代码]
读取64位有符号整数(占用4个连续寄存器)
Read 64-bit signed integer (occupies 4 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
64位有符号整数值
64-bit signed integer value
- async write_int64(slave_id: int, start_address: int, value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[], None] | None = None) None[源代码]
写入64位有符号整数(占用4个连续寄存器)
Write 64-bit signed integer (occupies 4 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的整数值 | Integer value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async read_uint64(slave_id: int, start_address: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[int], None] | None = None) int[源代码]
读取64位无符号整数(占用4个连续寄存器)
Read 64-bit unsigned integer (occupies 4 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
64位无符号整数值
64-bit unsigned integer value
- async write_uint64(slave_id: int, start_address: int, value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', callback: Callable[[], None] | None = None) None[源代码]
写入64位无符号整数(占用4个连续寄存器)
Write 64-bit unsigned integer (occupies 4 consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的无符号整数值 | Unsigned integer value to write
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async read_string(slave_id: int, start_address: int, length: int, encoding: str = 'utf-8', callback: Callable[[str], None] | None = None) str[源代码]
读取字符串(从连续寄存器中)
Read string (from consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
length -- 字符串字节长度 | String byte length
encoding -- 字符编码,默认'utf-8' | Character encoding, default 'utf-8'
callback -- 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response
- 返回:
解码后的字符串
Decoded string
- async write_string(slave_id: int, start_address: int, value: str, encoding: str = 'utf-8', callback: Callable[[], None] | None = None) None[源代码]
写入字符串(到连续寄存器中)
Write string (to consecutive registers)
- 参数:
slave_id -- 从站地址 | Slave address
start_address -- 起始寄存器地址 | Starting register address
value -- 要写入的字符串 | String to write
encoding -- 字符编码,默认'utf-8' | Character encoding, default 'utf-8'
callback -- 可选的回调函数,在操作完成后调用 | Optional callback function, called after operation completes
- async __aenter__() AsyncModbusClient[源代码]
上下文管理器入口
context manager entry
2. 传输模块
2.1 SyncBaseTransport
- class modbuslink.transport.base_transport.SyncBaseTransport[源代码]
基类:
ABC同步传输层抽象基类
所有同步传输层实现(TCP/RTU/ASCII)都必须继承此类并实现所有抽象方法。
Sync Transport Layer Abstract Base Class
All sync transport layer implementations (TCP, RTU, ASCII) must inherit from this class and implement all abstract methods.
- abstractmethod open() None[源代码]
打开传输连接
建立与Modbus设备的连接。
Open Transport Connection
Establish a connection with the Modbus device.
- 抛出:
ConnectError -- 当无法建立连接时 | When connection cannot be established
- abstractmethod close() None[源代码]
关闭传输连接
关闭与Modbus设备的连接并释放相关资源。
Close Transport Connection
Close the connection with the Modbus device and releases related resources.
- abstractmethod is_open() bool[源代码]
检查连接状态
Check Connection Status
- 返回:
如果连接已打开则返回True,否则返回False
True if the connection is open, otherwise False
- abstractmethod flush() int[源代码]
同步清空接收缓冲区中的所有待处理数据
Sync Flush all pending data in receive buffer
- 返回:
丢弃的字节数
Number of bytes discarded
- abstractmethod send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[源代码]
发送PDU并接收响应
传输层核心方法。接收纯净的PDU(协议数据单元), 负责添加必要的传输层信息(TCP的MBAP,RTU的CRC或ASCII的LCR), 发送请求,接收响应,验证响应的完整性,然后返回回应的PDU部分。
Send UDP and Receive Response
Core method of the transport layer. Receive the pure PDU (protocol data unit), be responsible for adding necessary transport layer information (MBAP of TCP, CRC of RTU or LCR of ASCII), send requests, receive responses, verify the integrity of the responses, and then return the PDU part of the responses.
- 参数:
slave_id -- 从机地址/单元标识符 | Slave address/unit identifier
pdu -- 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)
timeout -- 超时时间(秒) | Timeout time (seconds)
- 返回:
响应的PDU部分(功能码 + 数据)
Response PDU part (function code + data)
- 抛出:
CommunicationError -- 通信错误
ValidationError -- 数据校验错误
ConnectError -- 连接错误
TimeOutError -- 超时错误
CrcError -- CRC校验错误
LrcError -- LRC校验错误
InvalidReplyError -- 无效响应错误
ModbusException -- Modbus协议异常
- __enter__() SyncBaseTransport[源代码]
上下文管理器入口
Context Manager Entry
- 返回:
当前对象
Current object
2.2 AsyncBaseTransport
- class modbuslink.transport.base_transport.AsyncBaseTransport[源代码]
基类:
ABC异步传输层抽象基类
所有异步步传输层实现(TCP/RTU/ASCII)都必须继承此类并实现所有抽象方法。
Async Transport Layer Abstract Base Class
All async transport layer implementations (TCP, RTU, ASCII) must inherit from this class and implement all abstract methods.
- abstractmethod async open() None[源代码]
异步打开传输连接
异步建立与Modbus设备的连接。
Async Open Transport Connection
Asynchronously establish a connection with the Modbus device.
- 抛出:
ConnectError -- 当无法建立连接时 | When connection cannot be established
- abstractmethod async close() None[源代码]
异步关闭传输连接
异步关闭与Modbus设备的连接并释放相关资源。
Async Close Transport Connection
Asynchronously close the connection with the Modbus device and releases related resources.
- abstractmethod is_open() bool[源代码]
检查连接状态
Check Connection Status
- 返回:
如果连接已打开则返回True,否则返回False
True if the connection is open, otherwise False
- abstractmethod async flush() int[源代码]
异步清空接收缓冲区中的所有待处理数据
Async Flush all pending data in receive buffer
- 返回:
丢弃的字节数
Number of bytes discarded
- abstractmethod async send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[源代码]
异步发送PDU并接收响应
传输层核心方法。接收纯净的PDU(协议数据单元), 负责添加必要的传输层信息(TCP的MBAP,RTU的CRC或ASCII的LCR), 发送请求,接收响应,验证响应的完整性,然后返回回应的PDU部分。
Async Send UDP and Receive Response
Core method of the transport layer. Receive the pure PDU (protocol data unit), be responsible for adding necessary transport layer information (MBAP of TCP, CRC of RTU or LCR of ASCII), send requests, receive responses, verify the integrity of the responses, and then return the PDU part of the responses.
- 参数:
slave_id -- 从机地址/单元标识符 | Slave address/unit identifier
pdu -- 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)
timeout -- 超时时间(秒) | Timeout time (seconds)
- 返回:
响应的PDU部分(功能码 + 数据)
Response PDU part (function code + data)
- 抛出:
CommunicationError -- 通信错误
ValidationError -- 数据校验错误
ConnectError -- 连接错误
TimeOutError -- 超时错误
CrcError -- CRC校验错误
LrcError -- LRC校验错误
InvalidReplyError -- 无效响应错误
ModbusException -- Modbus协议异常
- async __aenter__() AsyncBaseTransport[源代码]
异步上下文管理器入口
Async Context Manager Entry
- 返回:
当前对象
Current object
2.3 SyncTcpTransport
- class modbuslink.transport.tcp_transport.SyncTcpTransport(host: str = '127.0.0.1', port: int = 502, timeout: float = 1.0)[源代码]
-
同步TCP传输层实现
Sync TCP Transport Layer Implementation
- __init__(host: str = '127.0.0.1', port: int = 502, timeout: float = 1.0) None[源代码]
初始化同步TCP传输层
Initialize Sync TCP Transport Layer :param host: 目标主机IP地址或域名(默认"127.0.0.1") | Target host IP address or domain name (default "127.0.0.1") :param port: 目标端口(默认502) | Target port (default 502) :param timeout: 超时时间(默认1.0秒) | Timeout time (default 1.0 second)
- 抛出:
ValueError -- 当参数无效时 | When parameters are invalid
- is_open() bool[源代码]
检查同步TCP传输层连接状态
Check Sync TCP Transport Layer connection status
- 返回:
如果传输层打开则返回True,否则返回False
True if the transport layer is open, otherwise False
- flush() int[源代码]
同步清空接收缓冲区中的所有待处理数据
Sync Flush all pending data in receive buffer
- 返回:
丢弃的字节数
Number of bytes discarded
- send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[源代码]
同步TCP传输层PDU发送和接收数据
Sync TCP Transport Layer PDU send and receive data
通信流程 | Communication Process:
构建MBAP头 | Build MBAP header
发送MBAP头和PDU | Send MBAP header and PDU
接收响应MBAP头 | Receive response MBAP header
验证MBAP头 | Verify MBAP header
接收响应PDU | Receive response PDU
返回响应PDU | Return response PDU
- 参数:
slave_id -- 从机地址/单元标识符 | Slave address/unit identifier
pdu -- 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)
timeout -- [ 未使用 ] 超时时间(秒) | [ unused ] Timeout time (seconds)
- 返回:
响应的PDU部分(功能码 + 数据)
Response PDU part (function code + data)
2.4 AsyncTcpTransport
- class modbuslink.transport.tcp_transport.AsyncTcpTransport(host: str = '127.0.0.1', port: int = 502, timeout: float = 1.0)[源代码]
-
异步TCP传输层实现
Async TCP Transport Layer Implementation
- __init__(host: str = '127.0.0.1', port: int = 502, timeout: float = 1.0) None[源代码]
初始化异步TCP传输层
Initialize Async TCP Transport Layer :param host: 目标主机IP地址或域名(默认"127.0.0.1") | Target host IP address or domain name (default "127.0.0.1") :param port: 目标端口(默认502) | Target port (default 502) :param timeout: 超时时间(默认1.0秒) | Timeout time (default 1.0 second)
- 抛出:
ValueError -- 当参数无效时 | When parameters are invalid
- is_open() bool[源代码]
检查异步TCP传输层连接状态
Check Async TCP Transport Layer connection status
- 返回:
如果传输层打开则返回True,否则返回False
True if the transport layer is open, otherwise False
- async flush() int[源代码]
异步清空接收缓冲区中的所有待处理数据
Async Flush all pending data in receive buffer
- 返回:
丢弃的字节数
Number of bytes discarded
- async send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[源代码]
异步TCP传输层PDU发送和接收数据
Async TCP Transport Layer PDU send and receive data
通信流程 | Communication Process:
构建MBAP头 | Build MBAP header
发送MBAP头和PDU | Send MBAP header and PDU
接收响应MBAP头 | Receive response MBAP header
验证MBAP头 | Verify MBAP header
接收响应PDU | Receive response PDU
返回响应PDU | Return response PDU
- 参数:
slave_id -- 从机地址/单元标识符 | Slave address/unit identifier
pdu -- 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)
timeout -- [ 未使用 ] 超时时间(秒) | [ unused ] Timeout time (seconds)
- 返回:
响应的PDU部分(功能码 + 数据)
Response PDU part (function code + data)
2.5 SyncRtuTransport
- class modbuslink.transport.rtu_transport.SyncRtuTransport(port: str, baudrate: int = 9600, bytesize: int = 8, parity: str = 'N', stopbits: float = 1, timeout: float = 1.0, rs485_mode: RS485Settings | None = None)[源代码]
-
同步RTU传输层实现
Sync RTU Transport Layer Implementation
- __init__(port: str, baudrate: int = 9600, bytesize: int = 8, parity: str = 'N', stopbits: float = 1, timeout: float = 1.0, rs485_mode: RS485Settings | None = None) None[源代码]
初始化同步RTU传输层
Initialize Sync RTU Transport Layer
- 参数:
port -- 串口名称(如 'COM1', '/dev/ttyUSB0') | Serial port name (e.g. 'COM1', '/dev/ttyUSB0')
baudrate -- 波特率(默认9600) | Baud rate (default 9600)
bytesize -- 数据位(默认8) | Data bits (default 8)
parity -- 校验位(默认无校验) | Parity (default no parity)
stopbits -- 停止位(默认1) | Stop bits (default 1)
timeout -- 超时时间(默认1.0秒) | Timeout time (default 1.0 second)
rs485_mode -- RS485模式(默认None) | RS485 mode (default None)
- 抛出:
ValueError -- 当参数无效时 | When parameters are invalid
- is_open() bool[源代码]
检查同步RTU传输层连接状态
Check Sync RTU Transport Layer connection status
- 返回:
如果传输层打开则返回True,否则返回False
True if the transport layer is open, otherwise False
- flush() int[源代码]
同步清空接收缓冲区中的所有待处理数据
Sync Flush all pending data in receive buffer
- 返回:
丢弃的字节数
Number of bytes discarded
- send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[源代码]
同步RTU传输层PDU发送和接收数据
Sync RTU Transport Layer PDU send and receive data
通信流程 | Communication Process:
构建ADU(地址 + PDU + CRC) | Build ADU (address + PDU + CRC)
发送请求 | Send request
接收响应 | Receive response
验证ADU | Verify ADU
返回响应PDU | Return response PDU
- 参数:
slave_id -- 从机地址/单元标识符 | Slave address/unit identifier
pdu -- 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)
timeout -- 超时时间(秒) | Timeout time (seconds)
- 返回:
响应的PDU部分(功能码 + 数据)
Response PDU part (function code + data)
2.6 AsyncRtuTransport
- class modbuslink.transport.rtu_transport.AsyncRtuTransport(port: str, baudrate: int = 9600, bytesize: int = 8, parity: str = 'N', stopbits: float = 1, timeout: float = 1.0, rs485_mode: RS485Settings | None = None)[源代码]
-
异步RTU传输层实现
Async RTU Transport Layer Implementation
- __init__(port: str, baudrate: int = 9600, bytesize: int = 8, parity: str = 'N', stopbits: float = 1, timeout: float = 1.0, rs485_mode: RS485Settings | None = None) None[源代码]
初始化异步RTU传输层
Initialize Async RTU Transport Layer
- 参数:
port -- 串口名称(如 'COM1', '/dev/ttyUSB0') | Serial port name (e.g. 'COM1', '/dev/ttyUSB0')
baudrate -- 波特率(默认9600) | Baud rate (default 9600)
bytesize -- 数据位(默认8) | Data bits (default 8)
parity -- 校验位(默认无校验) | Parity (default no parity)
stopbits -- 停止位(默认1) | Stop bits (default 1)
timeout -- 超时时间(默认1.0秒) | Timeout time (default 1.0 second)
rs485_mode -- RS485模式(默认None) | RS485 mode (default None)
- 抛出:
ValueError -- 当参数无效时 | When parameters are invalid
- is_open() bool[源代码]
检查异步RTU传输层连接状态
Check Async RTU Transport Layer connection status
- 返回:
如果传输层打开则返回True,否则返回False
True if the transport layer is open, otherwise False
- async flush() int[源代码]
异步清空接收缓冲区中的所有待处理数据
Async Flush all pending data in receive buffer
- 返回:
丢弃的字节数
Number of bytes discarded
- async send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[源代码]
异步RTU传输层PDU发送和接收数据
Async RTU Transport Layer PDU send and receive data
通信流程 | Communication Process:
构建ADU(地址 + PDU + CRC) | Build ADU (address + PDU + CRC)
发送请求 | Send request
接收响应 | Receive response
验证ADU | Verify ADU
返回响应PDU | Return response PDU
- 参数:
slave_id -- 从机地址/单元标识符 | Slave address/unit identifier
pdu -- 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)
timeout -- 超时时间(秒) | Timeout time (seconds)
- 返回:
响应的PDU部分(功能码 + 数据)
Response PDU part (function code + data)
2.7 SyncAsciiTransport
- class modbuslink.transport.ascii_transport.SyncAsciiTransport(port: str, baudrate: int = 9600, bytesize: int = 7, parity: str = 'E', stopbits: float = 1, timeout: float = 1.0, rs485_mode: RS485Settings | None = None)[源代码]
-
同步ASCII传输层实现
Sync ASCII Transport Layer Implementation
- __init__(port: str, baudrate: int = 9600, bytesize: int = 7, parity: str = 'E', stopbits: float = 1, timeout: float = 1.0, rs485_mode: RS485Settings | None = None) None[源代码]
初始化同步ASCII传输层
Initialize Sync ASCII Transport Layer
- 参数:
port -- 串口名称(如 'COM1', '/dev/ttyUSB0') | Serial port name (e.g. 'COM1', '/dev/ttyUSB0')
baudrate -- 波特率(默认9600) | Baud rate (default 9600)
bytesize -- 数据位(默认7) | Data bits (default 7)
parity -- 校验位(默认偶校验) | Parity (default even parity)
stopbits -- 停止位(默认1) | Stop bits (default 1)
timeout -- 超时时间(默认1.0秒) | Timeout time (default 1.0 second)
rs485_mode -- RS485模式(默认None) | RS485 mode (default None)
- 抛出:
ValueError -- 当参数无效时 | When parameters are invalid
- is_open() bool[源代码]
检查同步ASCII传输层连接状态
Check Sync ASCII Transport Layer connection status
- 返回:
如果传输层打开则返回True,否则返回False
True if the transport layer is open, otherwise False
- flush() int[源代码]
同步清空接收缓冲区中的所有待处理数据
Sync Flush all pending data in receive buffer
- 返回:
丢弃的字节数
Number of bytes discarded
- send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[源代码]
同步ASCII传输层PDU发送和接收数据
Sync ASCII Transport Layer PDU send and receive data
通信流程 | Communication Process:
构建ASCII帧(: + 地址 + PDU + LRC + CR LF) | Build ASCII frame (: + address + PDU + LRC + CR LF)
发送请求 | Send request
接收响应 | Receive response
验证ASCII帧 | Verify ASCII frame
返回响应PDU | Return response PDU
- 参数:
slave_id -- 从机地址/单元标识符 | Slave address/unit identifier
pdu -- 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)
timeout -- 超时时间(秒) | Timeout time (seconds)
- 返回:
响应的PDU部分(功能码 + 数据)
Response PDU part (function code + data)
2.8 AsyncAsciiTransport
- class modbuslink.transport.ascii_transport.AsyncAsciiTransport(port: str, baudrate: int = 9600, bytesize: int = 7, parity: str = 'E', stopbits: float = 1, timeout: float = 1.0, rs485_mode: RS485Settings | None = None)[源代码]
-
异步ASCII传输层实现
Async ASCII Transport Layer Implementation
- __init__(port: str, baudrate: int = 9600, bytesize: int = 7, parity: str = 'E', stopbits: float = 1, timeout: float = 1.0, rs485_mode: RS485Settings | None = None) None[源代码]
初始化同步ASCII传输层
Initialize Sync ASCII Transport Layer
- 参数:
port -- 串口名称(如 'COM1', '/dev/ttyUSB0') | Serial port name (e.g. 'COM1', '/dev/ttyUSB0')
baudrate -- 波特率(默认9600) | Baud rate (default 9600)
bytesize -- 数据位(默认7) | Data bits (default 7)
parity -- 校验位(默认偶校验) | Parity (default even parity)
stopbits -- 停止位(默认1) | Stop bits (default 1)
timeout -- 超时时间(默认1.0秒) | Timeout time (default 1.0 second)
rs485_mode -- RS485模式(默认None) | RS485 mode (default None)
- 抛出:
ValueError -- 当参数无效时 | When parameters are invalid
- is_open() bool[源代码]
检查异步ASCII传输层连接状态
Check Async ASCII Transport Layer connection status
- 返回:
如果传输层打开则返回True,否则返回False
True if the transport layer is open, otherwise False
- async flush() int[源代码]
异步清空接收缓冲区中的所有待处理数据
Async Flush all pending data in receive buffer
- 返回:
丢弃的字节数
Number of bytes discarded
- async send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[源代码]
异步ASCII传输层PDU发送和接收数据
Async ASCII Transport Layer PDU send and receive data
通信流程 | Communication Process:
构建ASCII帧(: + 地址 + PDU + LRC + CR LF) | Build ASCII frame (: + address + PDU + LRC + CR LF)
发送请求 | Send request
接收响应 | Receive response
验证ASCII帧 | Verify ASCII frame
返回响应PDU | Return response PDU
- 参数:
slave_id -- 从机地址/单元标识符 | Slave address/unit identifier
pdu -- 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)
timeout -- 超时时间(秒) | Timeout time (seconds)
- 返回:
响应的PDU部分(功能码 + 数据)
Response PDU part (function code + data)
3. 服务器模块
3.1 ModbusDataStore
- class modbuslink.server.data_store.ModbusDataStore(coils_size: int = 65536, discrete_inputs_size: int = 65536, holding_registers_size: int = 65536, input_registers_size: int = 65536)[源代码]
基类:
objectModbus数据存储类 提供线程安全的Modbus数据存储功能,支持线圈、离散输入、保持寄存器和输入寄存器的读写操作。
Modbus Data Store Class Provides thread-safe Modbus data storage functionality, supporting read/write operations for coils, discrete inputs, holding registers, and input registers.
- __init__(coils_size: int = 65536, discrete_inputs_size: int = 65536, holding_registers_size: int = 65536, input_registers_size: int = 65536)[源代码]
初始化数据存储
Initialize Data Store
- 参数:
coils_size -- 线圈数量 | Number of coils
discrete_inputs_size -- 离散输入数量 | Number of discrete inputs
holding_registers_size -- 保持寄存器数量 | Number of holding registers
input_registers_size -- 输入寄存器数量 | Number of input registers
- add_callback(area_name: str, callback: Callable[[int, List[Any]], None]) None[源代码]
添加数据变更监视回调函数(回调函数应尽量轻量,不要包含阻塞操作)
Add data change monitoring callback function (callback function should be light-weight, no blocking operations)
- 参数:
area_name -- 要监视的数据区名称 | Data area name to monitor -> ('coils', 'discrete_inputs', 'holding_registers', 'input_registers')
callback -- 回调函数对象 | Callback function object -> [(address: int, values: List) -> None]
- 抛出:
ValueError -- 如果提供的 area_name 无效 | If the provided area_name is invalid
- read_coils(address: int, count: int) List[bool][源代码]
读取线圈状态
Read Coil Status
- 参数:
address -- 起始地址 | Starting address
count -- 读取数量 | Number to read
- 返回:
线圈状态列表
List of coil status
- 抛出:
ValueError -- 地址或数量无效 | Invalid address or count
- write_coils(address: int, values: List[bool]) None[源代码]
写入线圈状态
Write Coil Status
- 参数:
address -- 起始地址 | Starting address
values -- 线圈状态列表 | List of coil status
- 抛出:
ValueError -- 地址或数据无效 | Invalid address or data
- read_discrete_inputs(address: int, count: int) List[bool][源代码]
读取离散输入状态
Read Discrete Input Status
- 参数:
address -- 起始地址 | Starting address
count -- 读取数量 | Number to read
- 返回:
离散输入状态列表
List of discrete input status
- 抛出:
ValueError -- 地址或数量无效 | Invalid address or count
- write_discrete_inputs(address: int, values: List[bool]) None[源代码]
写入离散输入状态(通常用于模拟)
Write Discrete Input Status (usually for simulation)
- 参数:
address -- 起始地址 | Starting address
values -- 离散输入状态列表 | List of discrete input status
- 抛出:
ValueError -- 地址或数据无效 | Invalid address or data
- read_holding_registers(address: int, count: int) List[int][源代码]
读取保持寄存器
Read Holding Registers
- 参数:
address -- 起始地址 | Starting address
count -- 读取数量 | Number to read
- 返回:
保持寄存器值列表
List of holding register values
- 抛出:
ValueError -- 地址或数量无效 | Invalid address or count
- write_holding_registers(address: int, values: List[int]) None[源代码]
写入保持寄存器
Write Holding Registers
- 参数:
address -- 起始地址 | Starting address
values -- 保持寄存器值列表 | List of holding register values
- 抛出:
ValueError -- 地址或数据无效 | Invalid address or data
- read_input_registers(address: int, count: int) List[int][源代码]
读取输入寄存器
Read Input Registers
- 参数:
address -- 起始地址 | Starting address
count -- 读取数量 | Number to read
- 返回:
输入寄存器值列表
List of input register values
- 抛出:
ValueError -- 地址或数量无效 | Invalid address or count
3.2 AsyncBaseModbusServer
- class modbuslink.server.base_server.AsyncBaseModbusServer(data_store: ModbusDataStore | None = None, slave_id: int = 1)[源代码]
基类:
ABC异步Modbus服务器抽象基类
所有异步Modbus服务器实现(AsyncTCP、AsyncRTU、AsyncASCII等)都必须继承此类并实现所有抽象方法。
Async Modbus Server Abstract Base Class
All async Modbus server implementations (AsyncTCP, AsyncRTU, AsyncASCII, etc.) must inherit from this class and implement all abstract methods.
- __init__(data_store: ModbusDataStore | None = None, slave_id: int = 1)[源代码]
初始化异步Modbus服务器
Initialize Async Modbus Server
- 参数:
data_store -- 数据存储实例,如果为None则创建默认实例 | Data store instance, creates default if None
slave_id -- 从站地址 | Slave address
- abstractmethod async start() None[源代码]
启动异步服务器,开始监听客户端连接和请求。
Start Async Server, Begin listening for client connections and requests.
- 抛出:
ConnectionError -- 当无法启动服务器时 | When server cannot be started
- abstractmethod async stop() None[源代码]
停止异步服务器,停止监听并关闭所有连接。
Stop Async Server, Stop listening and close all connections.
- abstractmethod async is_running() bool[源代码]
检查服务器运行状态
Check Server Running Status
- 返回:
如果服务器正在运行返回True,否则返回False
True if server is running, False otherwise
- process_request(slave_id: int, pdu: bytes) bytes[源代码]
处理Modbus请求PDU
这是服务器的核心方法,处理接收到的PDU并返回响应PDU。
Process Modbus Request PDU
This is the core method of the server, processes received PDU and returns response PDU.
- 参数:
slave_id -- 从站地址 | Slave address
pdu -- 请求的协议数据单元 | Request Protocol Data Unit
- 返回:
响应的协议数据单元
Response Protocol Data Unit
- async __aenter__() AsyncBaseModbusServer[源代码]
异步上下文管理器入口
Async Context Manager Entry
3.3 AsyncTcpModbusServer
- class modbuslink.server.tcp_server.AsyncTcpModbusServer(host: str = 'localhost', port: int = 502, data_store: ModbusDataStore | None = None, slave_id: int = 1)[源代码]
-
异步TCP Modbus服务器
实现基于TCP的异步Modbus服务器,支持多客户端并发连接。 使用MBAP(Modbus Application Protocol)头进行通信。
Async TCP Modbus Server
Implements TCP-based async Modbus server with support for multiple concurrent client connections. Uses MBAP (Modbus Application Protocol) header for communication.
- __init__(host: str = 'localhost', port: int = 502, data_store: ModbusDataStore | None = None, slave_id: int = 1)[源代码]
初始化异步TCP Modbus服务器
Initialize Async TCP Modbus Server
- 参数:
host -- 服务器绑定地址 | Server bind address
port -- 服务器端口 | Server port
data_store -- 数据存储实例 | Data store instance
slave_id -- 从站地址 | Slave address
- async start() None[源代码]
启动异步TCP服务器
Start Async TCP Server
- 抛出:
ConnectionError -- 当无法启动服务器时 | When server cannot be started
- async is_running() bool[源代码]
检查服务器运行状态
Check Server Running Status
- 返回:
如果服务器正在运行返回True,否则返回False
True if server is running, False otherwise
3.4 AsyncSerialModbusServer
- class modbuslink.server.serial_server.AsyncSerialModbusServer(port: str, baudrate: int, bytesize: int, parity: str, stopbits: int, data_store: ModbusDataStore | None = None, slave_id: int = 1, log_name: str = 'server.serial', protocol_name: str = 'Serial')[源代码]
-
异步串口Modbus服务器基类
封装了串口的打开、关闭、任务管理等通用逻辑。 具体的协议处理循环由子类实现。
Async Serial Modbus Server Base Class
Encapsulates common logic such as opening/closing serial ports and task management. Specific protocol processing loops are implemented by subclasses.
- __init__(port: str, baudrate: int, bytesize: int, parity: str, stopbits: int, data_store: ModbusDataStore | None = None, slave_id: int = 1, log_name: str = 'server.serial', protocol_name: str = 'Serial')[源代码]
初始化异步串口服务器
Initialize Async Serial Server
- 参数:
port -- 串口名称 | Serial port name
baudrate -- 波特率 | Baud rate
bytesize -- 数据位 | Data bits
parity -- 校验位 ('N', 'E', 'O') | Parity ('N', 'E', 'O')
stopbits -- 停止位 | Stop bits
data_store -- 数据存储实例 | Data store instance
slave_id -- 从站地址 | Slave address
log_name -- 日志名称 | Log name
protocol_name -- 协议名称 | Protocol name
- async start() None[源代码]
启动异步串口服务器
Start Async Serial Server
- 抛出:
ConnectError -- 当无法打开串口时 | When serial port cannot be opened
3.5 AsyncRtuModbusServer
- class modbuslink.server.rtu_server.AsyncRtuModbusServer(port: str, baudrate: int = 9600, bytesize: int = 8, parity: str = 'N', stopbits: int = 1, data_store: ModbusDataStore | None = None, slave_id: int = 1)[源代码]
-
异步RTU Modbus服务器
实现基于串口的异步Modbus RTU服务器。 使用CRC16校验确保数据完整性。
Async RTU Modbus Server
Implements serial port-based async Modbus RTU server. Uses CRC16 checksum to ensure data integrity.
- __init__(port: str, baudrate: int = 9600, bytesize: int = 8, parity: str = 'N', stopbits: int = 1, data_store: ModbusDataStore | None = None, slave_id: int = 1)[源代码]
初始化异步RTU Modbus服务器
Initialize Async RTU Modbus Server
- 参数:
port -- 串口名称 | Serial port name
baudrate -- 波特率 | Baud rate
bytesize -- 数据位 | Data bits
parity -- 校验位 ('N', 'E', 'O') | Parity ('N', 'E', 'O')
stopbits -- 停止位 | Stop bits
data_store -- 数据存储实例 | Data store instance
slave_id -- 从站地址 | Slave address
3.6 AsyncAsciiModbusServer
- class modbuslink.server.ascii_server.AsyncAsciiModbusServer(port: str, baudrate: int = 9600, bytesize: int = 7, parity: str = 'E', stopbits: int = 1, data_store: ModbusDataStore | None = None, slave_id: int = 1)[源代码]
-
异步ASCII Modbus服务器
实现基于串口的异步Modbus ASCII服务器。 使用LRC校验和ASCII编码。
Async ASCII Modbus Server
Implements serial port-based async Modbus ASCII server. Uses LRC checksum and ASCII encoding.
- __init__(port: str, baudrate: int = 9600, bytesize: int = 7, parity: str = 'E', stopbits: int = 1, data_store: ModbusDataStore | None = None, slave_id: int = 1)[源代码]
初始化异步ASCII Modbus服务器 | Initialize Async ASCII Modbus Server
- 参数:
port -- 串口名称 | Serial port name
baudrate -- 波特率 | Baud rate
bytesize -- 数据位 | Data bits
parity -- 校验位 ('N', 'E', 'O') | Parity ('N', 'E', 'O')
stopbits -- 停止位 | Stop bits
data_store -- 数据存储实例 | Data store instance
slave_id -- 从站地址 | Slave address
4. 工具模块
4.1 PayloadCoder
- class modbuslink.utils.coder.PayloadCoder[源代码]
基类:
object高级数据编解码器类
提供各种数据类型与Modbus寄存器之间的转换功能。 支持不同的字节序(大端/小端)和字序(高字在前/低字在前)配置。
Advanced Data Encoder/Decoder Class
Provides conversion functionality between various data types and Modbus registers. Supports different byte order (big/little endian) and word order (high/low word first) configurations.
- static decode_float32(registers: List[int], byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') float[源代码]
将两个16位寄存器解码为32位浮点数
Decode two 16-bit registers to a 32-bit float
- 参数:
registers -- 包含两个16位寄存器值的列表 | List containing two 16-bit register values
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
解码后的浮点数
Decoded float value
- 抛出:
ValueError -- 当寄存器数量不为2时 | When register count is not 2
- static encode_float32(value: float, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') List[int][源代码]
将32位浮点数编码为两个16位寄存器
Encode a 32-bit float to two 16-bit registers
- 参数:
value -- 要编码的浮点数 | Float value to encode
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
包含两个16位寄存器值的列表
List containing two 16-bit register values
- static decode_int32(registers: List[int], byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', signed: bool = True) int[源代码]
将两个16位寄存器解码为32位整数
Decode two 16-bit registers to a 32-bit integer
- 参数:
registers -- 包含两个16位寄存器值的列表 | List containing two 16-bit register values
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
signed -- 是否为有符号整数 | Whether it's a signed integer
- 返回:
解码后的整数值
Decoded integer value
- 抛出:
ValueError -- 当寄存器数量不为2时 | When register count is not 2
- static encode_int32(value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', signed: bool = True) List[int][源代码]
将32位整数编码为两个16位寄存器
Encode a 32-bit integer to two 16-bit registers
- 参数:
value -- 要编码的整数值 | Integer value to encode
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
signed -- 是否为有符号整数 | Whether it's a signed integer
- 返回:
包含两个16位寄存器值的列表
List containing two 16-bit register values
- static decode_int64(registers: List[int], byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', signed: bool = True) int[源代码]
将四个16位寄存器解码为64位整数
Decode four 16-bit registers to a 64-bit integer
- 参数:
registers -- 包含四个16位寄存器值的列表 | List containing four 16-bit register values
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
signed -- 是否为有符号整数 | Whether it's a signed integer
- 返回:
解码后的整数值
Decoded integer value
- 抛出:
ValueError -- 当寄存器数量不为4时 | When register count is not 4
- static encode_int64(value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high', signed: bool = True) List[int][源代码]
将64位整数编码为四个16位寄存器
Encode a 64-bit integer to four 16-bit registers
- 参数:
value -- 要编码的整数值 | Integer value to encode
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
signed -- 是否为有符号整数 | Whether it's a signed integer
- 返回:
包含四个16位寄存器值的列表
List containing four 16-bit register values
- static decode_string(registers: List[int], byte_order: Literal['big', 'little'] = 'big', encoding: str = 'utf-8') str[源代码]
将寄存器解码为字符串
Decode registers to a string
- 参数:
registers -- 包含字符串数据的寄存器列表 | List of registers containing string data
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
encoding -- 字符编码,默认为'utf-8' | Character encoding, default is 'utf-8'
- 返回:
解码后的字符串(去除尾部空字符)
Decoded string (with trailing null characters removed)
- static encode_string(value: str, register_count: int, byte_order: Literal['big', 'little'] = 'big', encoding: str = 'utf-8', truncate: bool = False) List[int][源代码]
将字符串编码为寄存器
Encode a string to registers
- 参数:
value -- 要编码的字符串 | String to encode
register_count -- 目标寄存器数量 | Target register count
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
encoding -- 字符编码,默认为'utf-8' | Character encoding, default is 'utf-8'
truncate -- 是否截断字符串 | Whether to truncate the string
- 返回:
包含字符串数据的寄存器列表
List of registers containing string data
- 抛出:
ValueError -- 当字符串太长无法适应指定寄存器数量时 | When string is too long for specified register count
- static decode_uint32(registers: List[int], byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') int[源代码]
将两个16位寄存器解码为32位无符号整数
Decode two 16-bit registers to a 32-bit unsigned integer
- 参数:
registers -- 包含两个16位寄存器值的列表 | List containing two 16-bit register values
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
解码后的整数值
Decoded integer value
- static encode_uint32(value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') List[int][源代码]
将32位无符号整数编码为两个16位寄存器
Encode a 32-bit unsigned integer to two 16-bit registers
- 参数:
value -- 要编码的整数值 | Integer value to encode
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
包含两个16位寄存器值的列表
List containing two 16-bit register values
- static decode_uint64(registers: List[int], byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') int[源代码]
将四个16位寄存器解码为64位无符号整数
Decode four 16-bit registers to a 64-bit unsigned integer
- 参数:
registers -- 包含四个16位寄存器值的列表 | List containing four 16-bit register values
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
解码后的整数值
Decoded integer value
- 抛出:
ValueError -- 当寄存器数量不为4时 | When register count is not 4
- static encode_uint64(value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') List[int][源代码]
将64位无符号整数编码为四个16位寄存器
Encode a 64-bit unsigned integer to four 16-bit registers
- 参数:
value -- 要编码的整数值 | Integer value to encode
byte_order -- 字节序,'big'或'little' | Byte order, 'big' or 'little'
word_order -- 字序,'high'或'low' | Word order, 'high' or 'low'
- 返回:
包含四个16位寄存器值的列表
List containing four 16-bit register values
4.2 CRC16Modbus
- class modbuslink.utils.crc.CRC16Modbus[源代码]
基类:
objectModbus CRC16校验工具
Modbus CRC16 Check Utils Module
- static calculate(data: bytes | bytearray, use_table: bool = True) bytes[源代码]
计算CRC16校验码
Calculate CRC16 Checksum
- 参数:
data -- 需要计算校验码的数据帧(地址+PDU) | Data frame for checksum calculation (address+PDU)
use_table -- 是否使用查表法 | Whether to use the table lookup method
- 返回:
2字节的CRC校验码 (little-endian bytes)
2-byte CRC checksum (little-endian bytes)
- static validate(frame_with_crc: bytes | bytearray, use_table: bool = True) bool[源代码]
验证包含CRC的完整数据帧
Validate Complete Data Frame with CRC
- 参数:
frame_with_crc -- 包含CRC校验码的完整数据帧 | Complete data frame containing CRC checksum
use_table -- 是否使用查表法 | Whether to use the table lookup method
- 返回:
如果CRC校验正确返回True,否则返回False
True if CRC verification is correct, False otherwise
4.3 LRC16Modbus
- class modbuslink.utils.lrc.LRCModbus[源代码]
基类:
objectModbus LRC校验工具类
Modbus LRC Check Utils Module
5. 通用模块
5.1 日志模块
ModbusLink 日志系统
ModbusLink Logging System
- class modbuslink.common.logging.ModbusLogger[源代码]
ModbusLink日志管理器
ModbusLink Log Manager
- DEFAULT_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
- DEBUG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
- static setup_logging(level: int = 20, format_string: str | None = None, enable_debug: bool = False, log_file: str | None = None, language: str = Language.CN) None[源代码]
设置ModbusLink的日志配置
Setup ModbusLink logging configuration
- 参数:
level -- 日志级别,默认INFO | Log level, default INFO
format_string -- 自定义日志格式 | Custom log format
enable_debug -- 是否启用调试模式(显示详细信息) | Enable debug mode (show detailed info)
log_file -- 日志文件路径,如果提供则同时输出到文件 | Log file path, if provided, also output to file
language -- 语言设置 | Language settings (Language.CN or Language.EN)
- static get_logger(name: str) BilingualLogger[源代码]
获取指定名称的日志器
Get logger with specified name
- 参数:
name -- 日志器名称 | Logger name
- 返回:
配置好的日志器实例
Configured logger instance
- modbuslink.common.logging.get_logger(name: str) BilingualLogger[源代码]
便捷函数:获取ModbusLink日志器
Convenience function: get ModbusLink logger
- 参数:
name -- 日志器名称 | Logger name
- 返回:
配置好的日志器实例
Configured logger instance
5.2 异常模块
ModbusLinkError
CommunicationError
- exception modbuslink.common.exceptions.CommunicationError(cn: str = '', en: str = '')[源代码]
-
通信错误基类
涉及物理连接、网络传输、IO超时等无法完成数据交换的错误。 用于统一捕获连接中断或超时等网络层面的异常。
Communication error base class
Involves physical connection, network transmission, IO timeouts, and other errors preventing data exchange. Used to catch connection drops or timeouts at the network level.
ValidationError
- exception modbuslink.common.exceptions.ValidationError(cn: str = '', en: str = '')[源代码]
-
数据校验错误基类
涉及接收到的数据包损坏、校验和(CRC/LRC)不匹配、或帧格式不符合协议规范。 表示通信物理层正常,但数据内容有问题。
Data validation error base class
Involves corrupted received packets, mismatched checksums (CRC/LRC), or frame formats not conforming to protocol specifications. Indicates the physical layer is working, but data content is invalid.
ConnectError
- exception modbuslink.common.exceptions.ConnectError(cn: str = '', en: str = '')[源代码]
-
连接错误异常
当无法建立或维持与Modbus设备的连接时抛出。 例如:TCP连接被拒绝、串口无法打开、管道断裂。
Connection error exception
Raised when unable to establish or maintain connection with Modbus device. E.g., TCP connection refused, serial port cannot be opened, broken pipe.
TimeOutError
- exception modbuslink.common.exceptions.TimeOutError(cn: str = '', en: str = '')[源代码]
-
超时错误异常
当操作超过指定的超时时间时抛出。 通常意味着发出了请求,但在规定时间内未收到任何字节。
Timeout error exception
Raised when operation exceeds the specified timeout period. Usually means a request was sent but no bytes were received within the time limit.
CrcError
LrcError
InvalidReplyError
- exception modbuslink.common.exceptions.InvalidReplyError(cn: str = '', en: str = '')[源代码]
-
无效响应错误异常
当接收到的响应格式不正确或不符合预期时抛出。 例如:数据长度不足、协议头错误、接收到的功能码与请求不匹配等。
Invalid response error exception
Raised when received response format is incorrect or unexpected. E.g., Insufficient data length, wrong protocol header, received function code does not match request, etc.
ModbusException
- exception modbuslink.common.exceptions.ModbusException(exception_code: int, function_code: int, message: str = '')[源代码]
-
Modbus协议异常
当从站设备成功接收请求,但由于逻辑原因无法处理时返回的异常帧。 (即返回了 0x80 + 功能码 的情况)
Modbus protocol exception
Raised when slave device successfully receives request but returns an exception frame because it cannot process it logically. (i.e., returned 0x80 + Function Code)
- exception_code
Modbus异常码 (如0x01, 0x02等) | Modbus exception code
- function_code
原始功能码 | Original function code
- custom_message
自定义消息 | Custom message
5.3 语言模块
- modbuslink.common.language
<module 'modbuslink.common.language' from '/home/runner/work/ModbusLink/ModbusLink/src/modbuslink/common/language.py'> 的别名