API Reference

This section provides detailed API documentation for all ModbusLink classes and functions.

1. Client Module

1.1 SyncModbusClient

class modbuslink.client.sync_client.SyncModbusClient(transport: SyncBaseTransport)[source]

Bases: 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)[source]

初始化同步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][source]

读取线圈状态(功能码0x01)

Read Coil Status (Function Code 0x01)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始地址 | Starting address

  • quantity – 读取数量(1-2000) | Quantity to read (1-2000)

Returns:

线圈状态列表,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][source]

读取离散输入状态(功能码0x02)

Read Discrete Input Status (Function Code 0x02)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始地址 | Starting address

  • quantity – 读取数量(1-2000) | Quantity to read (1-2000)

Returns:

离散输入状态列表,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][source]

读取保持寄存器(功能码0x03)

Read Holding Registers (Function Code 0x03)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始地址 | Starting address

  • quantity – 读取数量(1-125) | Quantity to read (1-125)

Returns:

寄存器值列表,每个值为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][source]

读取输入寄存器(功能码0x04)

Read Input Registers (Function Code 0x04)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始地址 | Starting address

  • quantity – 读取数量(1-125) | Quantity to read (1-125)

Returns:

寄存器值列表,每个值为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[source]

写单个线圈(功能码0x05)

Write Single Coil (Function Code 0x05)

Parameters:
  • 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[source]

写单个寄存器(功能码0x06)

Write Single Register (Function Code 0x06)

Parameters:
  • 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[source]

写多个线圈(功能码0x0F)

Write Multiple Coils (Function Code 0x0F)

Parameters:
  • 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[source]

写多个寄存器(功能码0x10)

Write Multiple Registers (Function Code 0x10)

Parameters:
  • 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[source]

读取32位浮点数(占用2个连续寄存器)

Read 32-bit float (occupies 2 consecutive registers)

Parameters:
  • 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’

Returns:

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[source]

写入32位浮点数(占用2个连续寄存器)

Write 32-bit float (occupies 2 consecutive registers)

Parameters:
  • 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[source]

读取32位有符号整数(占用2个连续寄存器)

Read 32-bit signed integer (occupies 2 consecutive registers)

Parameters:
  • 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’

Returns:

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[source]

写入32位有符号整数(占用2个连续寄存器)

Write 32-bit signed integer (occupies 2 consecutive registers)

Parameters:
  • 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[source]

读取32位无符号整数(占用2个连续寄存器)

Read 32-bit unsigned integer (occupies 2 consecutive registers)

Parameters:
  • 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’

Returns:

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[source]

写入32位无符号整数(占用2个连续寄存器)

Write 32-bit unsigned integer (occupies 2 consecutive registers)

Parameters:
  • 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[source]

读取64位有符号整数(占用4个连续寄存器)

Read 64-bit signed integer (occupies 4 consecutive registers)

Parameters:
  • 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’

Returns:

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[source]

写入64位有符号整数(占用4个连续寄存器)

Write 64-bit signed integer (occupies 4 consecutive registers)

Parameters:
  • 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[source]

读取64位无符号整数(占用4个连续寄存器)

Read 64-bit unsigned integer (occupies 4 consecutive registers)

Parameters:
  • 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’

Returns:

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[source]

写入64位无符号整数(占用4个连续寄存器)

Write 64-bit unsigned integer (occupies 4 consecutive registers)

Parameters:
  • 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[source]

读取字符串(从连续寄存器中)

Read string (from consecutive registers)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始寄存器地址 | Starting register address

  • length – 字符串字节长度 | String byte length

  • encoding – 字符编码,默认’utf-8’ | Character encoding, default ‘utf-8’

Returns:

解码后的字符串

Decoded string

write_string(slave_id: int, start_address: int, value: str, encoding: str = 'utf-8') None[source]

写入字符串(到连续寄存器中)

Write string (to consecutive registers)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始寄存器地址 | Starting register address

  • value – 要写入的字符串 | String to write

  • encoding – 字符编码,默认’utf-8’ | Character encoding, default ‘utf-8’

__enter__() SyncModbusClient[source]

上下文管理器入口

Context manager entry

__exit__(exc_type: type | None, exc_val: BaseException | None, exc_tb: Any | None) None[source]

上下文管理器出口

Context manager exit

__repr__() str[source]

字符串表示

String representation

1.2 AsyncModbusClient

class modbuslink.client.async_client.AsyncModbusClient(transport: AsyncBaseTransport)[source]

Bases: 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)[source]

初始化异步Modbus客户端

Initialize Async Modbus Client

Parameters:

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][source]

读取线圈状态(功能码0x01)

Read Coil Status (Function Code 0x01)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始地址 | Starting address

  • quantity – 读取数量(1-2000) | Quantity to read (1-2000)

  • callback – 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response

Returns:

线圈状态列表,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][source]

读取离散输入状态(功能码0x02)

Read Discrete Input Status (Function Code 0x02)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始地址 | Starting address

  • quantity – 读取数量(1-2000) | Quantity to read (1-2000)

  • callback – 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response

Returns:

离散输入状态列表,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][source]

读取保持寄存器(功能码0x03)

Read Holding Registers (Function Code 0x03)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始地址 | Starting address

  • quantity – 读取数量(1-125) | Quantity to read (1-125)

  • callback – 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response

Returns:

寄存器值列表,每个值为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][source]

读取输入寄存器(功能码0x04)

Read Input Registers (Function Code 0x04)

Parameters:
  • slave_id – 从站地址 | Slave address

  • start_address – 起始地址 | Starting address

  • quantity – 读取数量(1-125) | Quantity to read (1-125)

  • callback – 可选的回调函数,在收到响应后调用 | Optional callback function, called after receiving response

Returns:

寄存器值列表,每个值为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[source]

写单个线圈(功能码0x05)

Write Single Coil (Function Code 0x05)

Parameters:
  • 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[source]

写单个寄存器(功能码0x06)

Write Single Register (Function Code 0x06)

Parameters:
  • 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[source]

写多个线圈(功能码0x0F)

Write Multiple Coils (Function Code 0x0F)

Parameters:
  • 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[source]

写多个寄存器(功能码0x10)

Write Multiple Registers (Function Code 0x10)

Parameters:
  • 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[source]

读取32位浮点数(占用2个连续寄存器)

Read 32-bit float (occupies 2 consecutive registers)

Parameters:
  • 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

Returns:

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[source]

写入32位浮点数(占用2个连续寄存器)

Write 32-bit float (occupies 2 consecutive registers)

Parameters:
  • 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[source]

读取32位有符号整数(占用2个连续寄存器)

Read 32-bit signed integer (occupies 2 consecutive registers)

Parameters:
  • 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

Returns:

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[source]

写入32位有符号整数(占用2个连续寄存器)

Write 32-bit signed integer (occupies 2 consecutive registers)

Parameters:
  • 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[source]

读取32位无符号整数(占用2个连续寄存器)

Read 32-bit unsigned integer (occupies 2 consecutive registers)

Parameters:
  • 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

Returns:

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[source]

写入32位无符号整数(占用2个连续寄存器)

Write 32-bit unsigned integer (occupies 2 consecutive registers)

Parameters:
  • 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[source]

读取64位有符号整数(占用4个连续寄存器)

Read 64-bit signed integer (occupies 4 consecutive registers)

Parameters:
  • 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

Returns:

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[source]

写入64位有符号整数(占用4个连续寄存器)

Write 64-bit signed integer (occupies 4 consecutive registers)

Parameters:
  • 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[source]

读取64位无符号整数(占用4个连续寄存器)

Read 64-bit unsigned integer (occupies 4 consecutive registers)

Parameters:
  • 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

Returns:

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[source]

写入64位无符号整数(占用4个连续寄存器)

Write 64-bit unsigned integer (occupies 4 consecutive registers)

Parameters:
  • 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[source]

读取字符串(从连续寄存器中)

Read string (from consecutive registers)

Parameters:
  • 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

Returns:

解码后的字符串

Decoded string

async write_string(slave_id: int, start_address: int, value: str, encoding: str = 'utf-8', callback: Callable[[], None] | None = None) None[source]

写入字符串(到连续寄存器中)

Write string (to consecutive registers)

Parameters:
  • 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[source]

上下文管理器入口

context manager entry

async __aexit__(exc_type: type | None, exc_val: BaseException | None, exc_tb: Any | None) None[source]

异步上下文管理器出口

Async context manager exit

__repr__() str[source]

字符串表示

String representation

2. Transport Module

2.1 SyncBaseTransport

class modbuslink.transport.base_transport.SyncBaseTransport[source]

Bases: 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[source]

打开传输连接

建立与Modbus设备的连接。

Open Transport Connection

Establish a connection with the Modbus device.

Raises:

ConnectError – 当无法建立连接时 | When connection cannot be established

abstractmethod close() None[source]

关闭传输连接

关闭与Modbus设备的连接并释放相关资源。

Close Transport Connection

Close the connection with the Modbus device and releases related resources.

abstractmethod is_open() bool[source]

检查连接状态

Check Connection Status

Returns:

如果连接已打开则返回True,否则返回False

True if the connection is open, otherwise False

abstractmethod flush() int[source]

同步清空接收缓冲区中的所有待处理数据

Sync Flush all pending data in receive buffer

Returns:

丢弃的字节数

Number of bytes discarded

abstractmethod send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[source]

发送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.

Parameters:
  • slave_id – 从机地址/单元标识符 | Slave address/unit identifier

  • pdu – 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)

  • timeout – 超时时间(秒) | Timeout time (seconds)

Returns:

响应的PDU部分(功能码 + 数据)

Response PDU part (function code + data)

Raises:
__enter__() SyncBaseTransport[source]

上下文管理器入口

Context Manager Entry

Returns:

当前对象

Current object

__exit__(exc_type: type | None, exc_val: BaseException | None, exc_tb: Any | None) None[source]

上下文管理器出口

Context Manager Exit

Parameters:
  • exc_type – 异常类型 | Exception type

  • exc_val – 异常值 | Exception value

  • exc_tb – 异常 traceback | Exception traceback

2.2 AsyncBaseTransport

class modbuslink.transport.base_transport.AsyncBaseTransport[source]

Bases: 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[source]

异步打开传输连接

异步建立与Modbus设备的连接。

Async Open Transport Connection

Asynchronously establish a connection with the Modbus device.

Raises:

ConnectError – 当无法建立连接时 | When connection cannot be established

abstractmethod async close() None[source]

异步关闭传输连接

异步关闭与Modbus设备的连接并释放相关资源。

Async Close Transport Connection

Asynchronously close the connection with the Modbus device and releases related resources.

abstractmethod is_open() bool[source]

检查连接状态

Check Connection Status

Returns:

如果连接已打开则返回True,否则返回False

True if the connection is open, otherwise False

abstractmethod async flush() int[source]

异步清空接收缓冲区中的所有待处理数据

Async Flush all pending data in receive buffer

Returns:

丢弃的字节数

Number of bytes discarded

abstractmethod async send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[source]

异步发送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.

Parameters:
  • slave_id – 从机地址/单元标识符 | Slave address/unit identifier

  • pdu – 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)

  • timeout – 超时时间(秒) | Timeout time (seconds)

Returns:

响应的PDU部分(功能码 + 数据)

Response PDU part (function code + data)

Raises:
async __aenter__() AsyncBaseTransport[source]

异步上下文管理器入口

Async Context Manager Entry

Returns:

当前对象

Current object

async __aexit__(exc_type: type | None, exc_val: BaseException | None, exc_tb: Any | None) None[source]

异步上下文管理器出口

Async Context Manager Exit

Parameters:
  • exc_type – 异常类型 | Exception type

  • exc_val – 异常值 | Exception value

  • exc_tb – 异常 traceback | Exception traceback

2.3 SyncTcpTransport

class modbuslink.transport.tcp_transport.SyncTcpTransport(host: str = '127.0.0.1', port: int = 502, timeout: float = 1.0)[source]

Bases: SyncBaseTransport

同步TCP传输层实现

Sync TCP Transport Layer Implementation

__init__(host: str = '127.0.0.1', port: int = 502, timeout: float = 1.0) None[source]

初始化同步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)

Raises:

ValueError – 当参数无效时 | When parameters are invalid

open() None[source]

打开同步TCP传输层

Open Sync TCP Transport Layer

close() None[source]

关闭同步TCP传输层

Close Sync TCP Transport Layer

is_open() bool[source]

检查同步TCP传输层连接状态

Check Sync TCP Transport Layer connection status

Returns:

如果传输层打开则返回True,否则返回False

True if the transport layer is open, otherwise False

flush() int[source]

同步清空接收缓冲区中的所有待处理数据

Sync Flush all pending data in receive buffer

Returns:

丢弃的字节数

Number of bytes discarded

send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[source]

同步TCP传输层PDU发送和接收数据

Sync TCP Transport Layer PDU send and receive data

通信流程 | Communication Process:

  1. 构建MBAP头 | Build MBAP header

  2. 发送MBAP头和PDU | Send MBAP header and PDU

  3. 接收响应MBAP头 | Receive response MBAP header

  4. 验证MBAP头 | Verify MBAP header

  5. 接收响应PDU | Receive response PDU

  6. 返回响应PDU | Return response PDU

Parameters:
  • slave_id – 从机地址/单元标识符 | Slave address/unit identifier

  • pdu – 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)

  • timeout – [ 未使用 ] 超时时间(秒) | [ unused ] Timeout time (seconds)

Returns:

响应的PDU部分(功能码 + 数据)

Response PDU part (function code + data)

__repr__() str[source]

返回对象的字符串表示

Return object’s string representation

Returns:

对象的字符串表示

Object’s string representation

2.4 AsyncTcpTransport

class modbuslink.transport.tcp_transport.AsyncTcpTransport(host: str = '127.0.0.1', port: int = 502, timeout: float = 1.0)[source]

Bases: AsyncBaseTransport

异步TCP传输层实现

Async TCP Transport Layer Implementation

__init__(host: str = '127.0.0.1', port: int = 502, timeout: float = 1.0) None[source]

初始化异步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)

Raises:

ValueError – 当参数无效时 | When parameters are invalid

async open() None[source]

打开异步TCP传输层

Open Async TCP Transport Layer

async close() None[source]

关闭异步TCP传输层

Close Async TCP Transport Layer

is_open() bool[source]

检查异步TCP传输层连接状态

Check Async TCP Transport Layer connection status

Returns:

如果传输层打开则返回True,否则返回False

True if the transport layer is open, otherwise False

async flush() int[source]

异步清空接收缓冲区中的所有待处理数据

Async Flush all pending data in receive buffer

Returns:

丢弃的字节数

Number of bytes discarded

async send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[source]

异步TCP传输层PDU发送和接收数据

Async TCP Transport Layer PDU send and receive data

通信流程 | Communication Process:

  1. 构建MBAP头 | Build MBAP header

  2. 发送MBAP头和PDU | Send MBAP header and PDU

  3. 接收响应MBAP头 | Receive response MBAP header

  4. 验证MBAP头 | Verify MBAP header

  5. 接收响应PDU | Receive response PDU

  6. 返回响应PDU | Return response PDU

Parameters:
  • slave_id – 从机地址/单元标识符 | Slave address/unit identifier

  • pdu – 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)

  • timeout – [ 未使用 ] 超时时间(秒) | [ unused ] Timeout time (seconds)

Returns:

响应的PDU部分(功能码 + 数据)

Response PDU part (function code + data)

__repr__() str[source]

返回对象的字符串表示

Return object’s string representation

Returns:

对象的字符串表示

Object’s string representation

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)[source]

Bases: SyncBaseTransport

同步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[source]

初始化同步RTU传输层

Initialize Sync RTU Transport Layer

Parameters:
  • 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)

Raises:

ValueError – 当参数无效时 | When parameters are invalid

open() None[source]

打开同步RTU传输层

Open Sync RTU Transport Layer

close() None[source]

关闭同步RTU传输层

Close Sync RTU Transport Layer

is_open() bool[source]

检查同步RTU传输层连接状态

Check Sync RTU Transport Layer connection status

Returns:

如果传输层打开则返回True,否则返回False

True if the transport layer is open, otherwise False

flush() int[source]

同步清空接收缓冲区中的所有待处理数据

Sync Flush all pending data in receive buffer

Returns:

丢弃的字节数

Number of bytes discarded

send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[source]

同步RTU传输层PDU发送和接收数据

Sync RTU Transport Layer PDU send and receive data

通信流程 | Communication Process:

  1. 构建ADU(地址 + PDU + CRC) | Build ADU (address + PDU + CRC)

  2. 发送请求 | Send request

  3. 接收响应 | Receive response

  4. 验证ADU | Verify ADU

  5. 返回响应PDU | Return response PDU

Parameters:
  • slave_id – 从机地址/单元标识符 | Slave address/unit identifier

  • pdu – 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)

  • timeout – 超时时间(秒) | Timeout time (seconds)

Returns:

响应的PDU部分(功能码 + 数据)

Response PDU part (function code + data)

__repr__() str[source]

返回对象的字符串表示

Return object’s string representation

Returns:

对象的字符串表示

Object’s string representation

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)[source]

Bases: AsyncBaseTransport

异步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[source]

初始化异步RTU传输层

Initialize Async RTU Transport Layer

Parameters:
  • 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)

Raises:

ValueError – 当参数无效时 | When parameters are invalid

async open() None[source]

打开异步RTU传输层

Open Async RTU Transport Layer

async close() None[source]

关闭异步RTU传输层

Close Async RTU Transport Layer

is_open() bool[source]

检查异步RTU传输层连接状态

Check Async RTU Transport Layer connection status

Returns:

如果传输层打开则返回True,否则返回False

True if the transport layer is open, otherwise False

async flush() int[source]

异步清空接收缓冲区中的所有待处理数据

Async Flush all pending data in receive buffer

Returns:

丢弃的字节数

Number of bytes discarded

async send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[source]

异步RTU传输层PDU发送和接收数据

Async RTU Transport Layer PDU send and receive data

通信流程 | Communication Process:

  1. 构建ADU(地址 + PDU + CRC) | Build ADU (address + PDU + CRC)

  2. 发送请求 | Send request

  3. 接收响应 | Receive response

  4. 验证ADU | Verify ADU

  5. 返回响应PDU | Return response PDU

Parameters:
  • slave_id – 从机地址/单元标识符 | Slave address/unit identifier

  • pdu – 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)

  • timeout – 超时时间(秒) | Timeout time (seconds)

Returns:

响应的PDU部分(功能码 + 数据)

Response PDU part (function code + data)

__repr__() str[source]

返回对象的字符串表示

Return object’s string representation

Returns:

对象的字符串表示

Object’s string representation

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)[source]

Bases: SyncBaseTransport

同步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[source]

初始化同步ASCII传输层

Initialize Sync ASCII Transport Layer

Parameters:
  • 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)

Raises:

ValueError – 当参数无效时 | When parameters are invalid

open() None[source]

打开同步ASCII传输层

Open Sync ASCII Transport Layer

close() None[source]

关闭同步ASCII传输层

Close Sync ASCII Transport Layer

is_open() bool[source]

检查同步ASCII传输层连接状态

Check Sync ASCII Transport Layer connection status

Returns:

如果传输层打开则返回True,否则返回False

True if the transport layer is open, otherwise False

flush() int[source]

同步清空接收缓冲区中的所有待处理数据

Sync Flush all pending data in receive buffer

Returns:

丢弃的字节数

Number of bytes discarded

send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[source]

同步ASCII传输层PDU发送和接收数据

Sync ASCII Transport Layer PDU send and receive data

通信流程 | Communication Process:

  1. 构建ASCII帧(: + 地址 + PDU + LRC + CR LF) | Build ASCII frame (: + address + PDU + LRC + CR LF)

  2. 发送请求 | Send request

  3. 接收响应 | Receive response

  4. 验证ASCII帧 | Verify ASCII frame

  5. 返回响应PDU | Return response PDU

Parameters:
  • slave_id – 从机地址/单元标识符 | Slave address/unit identifier

  • pdu – 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)

  • timeout – 超时时间(秒) | Timeout time (seconds)

Returns:

响应的PDU部分(功能码 + 数据)

Response PDU part (function code + data)

__repr__() str[source]

返回对象的字符串表示

Return object’s string representation

Returns:

对象的字符串表示

Object’s string representation

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)[source]

Bases: AsyncBaseTransport

异步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[source]

初始化同步ASCII传输层

Initialize Sync ASCII Transport Layer

Parameters:
  • 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)

Raises:

ValueError – 当参数无效时 | When parameters are invalid

async open() None[source]

打开异步ASCII传输层

Open Async ASCII Transport Layer

async close() None[source]

关闭异步ASCII传输层

Close Async ASCII Transport Layer

is_open() bool[source]

检查异步ASCII传输层连接状态

Check Async ASCII Transport Layer connection status

Returns:

如果传输层打开则返回True,否则返回False

True if the transport layer is open, otherwise False

async flush() int[source]

异步清空接收缓冲区中的所有待处理数据

Async Flush all pending data in receive buffer

Returns:

丢弃的字节数

Number of bytes discarded

async send_and_receive(slave_id: int, pdu: bytes, timeout: float | None = None) bytes[source]

异步ASCII传输层PDU发送和接收数据

Async ASCII Transport Layer PDU send and receive data

通信流程 | Communication Process:

  1. 构建ASCII帧(: + 地址 + PDU + LRC + CR LF) | Build ASCII frame (: + address + PDU + LRC + CR LF)

  2. 发送请求 | Send request

  3. 接收响应 | Receive response

  4. 验证ASCII帧 | Verify ASCII frame

  5. 返回响应PDU | Return response PDU

Parameters:
  • slave_id – 从机地址/单元标识符 | Slave address/unit identifier

  • pdu – 协议数据单元(功能码 + 数据) | Protocol data unit (function code + data)

  • timeout – 超时时间(秒) | Timeout time (seconds)

Returns:

响应的PDU部分(功能码 + 数据)

Response PDU part (function code + data)

__repr__() str[source]

返回对象的字符串表示

Return object’s string representation

Returns:

对象的字符串表示

Object’s string representation

3. Server Module

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)[source]

Bases: object

Modbus数据存储类 提供线程安全的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)[source]

初始化数据存储

Initialize Data Store

Parameters:
  • 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[source]

添加数据变更监视回调函数(回调函数应尽量轻量,不要包含阻塞操作)

Add data change monitoring callback function (callback function should be light-weight, no blocking operations)

Parameters:
  • area_name – 要监视的数据区名称 | Data area name to monitor -> (‘coils’, ‘discrete_inputs’, ‘holding_registers’, ‘input_registers’)

  • callback – 回调函数对象 | Callback function object -> [(address: int, values: List) -> None]

Raises:

ValueError – 如果提供的 area_name 无效 | If the provided area_name is invalid

read_coils(address: int, count: int) List[bool][source]

读取线圈状态

Read Coil Status

Parameters:
  • address – 起始地址 | Starting address

  • count – 读取数量 | Number to read

Returns:

线圈状态列表

List of coil status

Raises:

ValueError – 地址或数量无效 | Invalid address or count

write_coils(address: int, values: List[bool]) None[source]

写入线圈状态

Write Coil Status

Parameters:
  • address – 起始地址 | Starting address

  • values – 线圈状态列表 | List of coil status

Raises:

ValueError – 地址或数据无效 | Invalid address or data

read_discrete_inputs(address: int, count: int) List[bool][source]

读取离散输入状态

Read Discrete Input Status

Parameters:
  • address – 起始地址 | Starting address

  • count – 读取数量 | Number to read

Returns:

离散输入状态列表

List of discrete input status

Raises:

ValueError – 地址或数量无效 | Invalid address or count

write_discrete_inputs(address: int, values: List[bool]) None[source]

写入离散输入状态(通常用于模拟)

Write Discrete Input Status (usually for simulation)

Parameters:
  • address – 起始地址 | Starting address

  • values – 离散输入状态列表 | List of discrete input status

Raises:

ValueError – 地址或数据无效 | Invalid address or data

read_holding_registers(address: int, count: int) List[int][source]

读取保持寄存器

Read Holding Registers

Parameters:
  • address – 起始地址 | Starting address

  • count – 读取数量 | Number to read

Returns:

保持寄存器值列表

List of holding register values

Raises:

ValueError – 地址或数量无效 | Invalid address or count

write_holding_registers(address: int, values: List[int]) None[source]

写入保持寄存器

Write Holding Registers

Parameters:
  • address – 起始地址 | Starting address

  • values – 保持寄存器值列表 | List of holding register values

Raises:

ValueError – 地址或数据无效 | Invalid address or data

read_input_registers(address: int, count: int) List[int][source]

读取输入寄存器

Read Input Registers

Parameters:
  • address – 起始地址 | Starting address

  • count – 读取数量 | Number to read

Returns:

输入寄存器值列表

List of input register values

Raises:

ValueError – 地址或数量无效 | Invalid address or count

write_input_registers(address: int, values: List[int]) None[source]

写入输入寄存器(通常用于模拟)

Write Input Registers (usually for simulation)

Parameters:
  • address – 起始地址 | Starting address

  • values – 输入寄存器值列表 | List of input register values

Raises:

ValueError – 地址或数据无效 | Invalid address or data

get_coils_size() int[source]

获取线圈总数

Get total number of coils

get_discrete_inputs_size() int[source]

获取离散输入总数

Get total number of discrete inputs

get_holding_registers_size() int[source]

获取保持寄存器总数

Get total number of holding registers

get_input_registers_size() int[source]

获取输入寄存器总数

Get total number of input registers

reset() None[source]

重置所有数据为默认值

Reset All Data to Default Values

3.2 AsyncBaseModbusServer

class modbuslink.server.base_server.AsyncBaseModbusServer(data_store: ModbusDataStore | None = None, slave_id: int = 1)[source]

Bases: 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)[source]

初始化异步Modbus服务器

Initialize Async Modbus Server

Parameters:
  • data_store – 数据存储实例,如果为None则创建默认实例 | Data store instance, creates default if None

  • slave_id – 从站地址 | Slave address

abstractmethod async start() None[source]

启动异步服务器,开始监听客户端连接和请求。

Start Async Server, Begin listening for client connections and requests.

Raises:

ConnectionError – 当无法启动服务器时 | When server cannot be started

abstractmethod async stop() None[source]

停止异步服务器,停止监听并关闭所有连接。

Stop Async Server, Stop listening and close all connections.

abstractmethod async is_running() bool[source]

检查服务器运行状态

Check Server Running Status

Returns:

如果服务器正在运行返回True,否则返回False

True if server is running, False otherwise

process_request(slave_id: int, pdu: bytes) bytes[source]

处理Modbus请求PDU

这是服务器的核心方法,处理接收到的PDU并返回响应PDU。

Process Modbus Request PDU

This is the core method of the server, processes received PDU and returns response PDU.

Parameters:
  • slave_id – 从站地址 | Slave address

  • pdu – 请求的协议数据单元 | Request Protocol Data Unit

Returns:

响应的协议数据单元

Response Protocol Data Unit

async __aenter__() AsyncBaseModbusServer[source]

异步上下文管理器入口

Async Context Manager Entry

async __aexit__(exc_type: type | None, exc_val: BaseException | None, exc_tb: Any | None) None[source]

异步上下文管理器出口

Async Context Manager Exit

3.3 AsyncTcpModbusServer

class modbuslink.server.tcp_server.AsyncTcpModbusServer(host: str = 'localhost', port: int = 502, data_store: ModbusDataStore | None = None, slave_id: int = 1)[source]

Bases: AsyncBaseModbusServer

异步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)[source]

初始化异步TCP Modbus服务器

Initialize Async TCP Modbus Server

Parameters:
  • host – 服务器绑定地址 | Server bind address

  • port – 服务器端口 | Server port

  • data_store – 数据存储实例 | Data store instance

  • slave_id – 从站地址 | Slave address

async start() None[source]

启动异步TCP服务器

Start Async TCP Server

Raises:

ConnectionError – 当无法启动服务器时 | When server cannot be started

async stop() None[source]

停止异步TCP服务器

Stop Async TCP Server

async is_running() bool[source]

检查服务器运行状态

Check Server Running Status

Returns:

如果服务器正在运行返回True,否则返回False

True if server is running, False otherwise

get_connected_clients_count() int[source]

获取当前连接的客户端数量

Get Current Connected Clients Count

Returns:

当前连接的客户端数量

Current number of connected clients

async serve_forever() None[source]

持续运行服务器直到被停止

Run Server Forever Until Stopped

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')[source]

Bases: AsyncBaseModbusServer

异步串口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')[source]

初始化异步串口服务器

Initialize Async Serial Server

Parameters:
  • 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[source]

启动异步串口服务器

Start Async Serial Server

Raises:

ConnectError – 当无法打开串口时 | When serial port cannot be opened

async stop() None[source]

停止异步串口服务器

Stop Async Serial Server

async is_running() bool[source]

检查服务器运行状态

Check Server Running Status

Returns:

如果服务器正在运行返回True,否则返回False

True if server is running, False otherwise

async serve_forever() None[source]

持续运行服务器直到被停止

Run Server Forever Until Stopped

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)[source]

Bases: AsyncSerialModbusServer

异步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)[source]

初始化异步RTU Modbus服务器

Initialize Async RTU Modbus Server

Parameters:
  • 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)[source]

Bases: AsyncSerialModbusServer

异步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)[source]

初始化异步ASCII Modbus服务器 | Initialize Async ASCII Modbus Server

Parameters:
  • 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. Utility Module

4.1 PayloadCoder

class modbuslink.utils.coder.PayloadCoder[source]

Bases: 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.

BIG_ENDIAN: Literal['big', 'little'] = 'big'
LITTLE_ENDIAN: Literal['big', 'little'] = 'little'
HIGH_WORD_FIRST: Literal['high', 'low'] = 'high'
LOW_WORD_FIRST: Literal['high', 'low'] = 'low'
static decode_float32(registers: List[int], byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') float[source]

将两个16位寄存器解码为32位浮点数

Decode two 16-bit registers to a 32-bit float

Parameters:
  • 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’

Returns:

解码后的浮点数

Decoded float value

Raises:

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][source]

将32位浮点数编码为两个16位寄存器

Encode a 32-bit float to two 16-bit registers

Parameters:
  • value – 要编码的浮点数 | Float value to encode

  • byte_order – 字节序,’big’或’little’ | Byte order, ‘big’ or ‘little’

  • word_order – 字序,’high’或’low’ | Word order, ‘high’ or ‘low’

Returns:

包含两个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[source]

将两个16位寄存器解码为32位整数

Decode two 16-bit registers to a 32-bit integer

Parameters:
  • 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

Returns:

解码后的整数值

Decoded integer value

Raises:

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][source]

将32位整数编码为两个16位寄存器

Encode a 32-bit integer to two 16-bit registers

Parameters:
  • 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

Returns:

包含两个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[source]

将四个16位寄存器解码为64位整数

Decode four 16-bit registers to a 64-bit integer

Parameters:
  • 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

Returns:

解码后的整数值

Decoded integer value

Raises:

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][source]

将64位整数编码为四个16位寄存器

Encode a 64-bit integer to four 16-bit registers

Parameters:
  • 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

Returns:

包含四个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[source]

将寄存器解码为字符串

Decode registers to a string

Parameters:
  • 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’

Returns:

解码后的字符串(去除尾部空字符)

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][source]

将字符串编码为寄存器

Encode a string to registers

Parameters:
  • 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

Returns:

包含字符串数据的寄存器列表

List of registers containing string data

Raises:

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[source]

将两个16位寄存器解码为32位无符号整数

Decode two 16-bit registers to a 32-bit unsigned integer

Parameters:
  • 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’

Returns:

解码后的整数值

Decoded integer value

static encode_uint32(value: int, byte_order: Literal['big', 'little'] = 'big', word_order: Literal['high', 'low'] = 'high') List[int][source]

将32位无符号整数编码为两个16位寄存器

Encode a 32-bit unsigned integer to two 16-bit registers

Parameters:
  • value – 要编码的整数值 | Integer value to encode

  • byte_order – 字节序,’big’或’little’ | Byte order, ‘big’ or ‘little’

  • word_order – 字序,’high’或’low’ | Word order, ‘high’ or ‘low’

Returns:

包含两个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[source]

将四个16位寄存器解码为64位无符号整数

Decode four 16-bit registers to a 64-bit unsigned integer

Parameters:
  • 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’

Returns:

解码后的整数值

Decoded integer value

Raises:

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][source]

将64位无符号整数编码为四个16位寄存器

Encode a 64-bit unsigned integer to four 16-bit registers

Parameters:
  • value – 要编码的整数值 | Integer value to encode

  • byte_order – 字节序,’big’或’little’ | Byte order, ‘big’ or ‘little’

  • word_order – 字序,’high’或’low’ | Word order, ‘high’ or ‘low’

Returns:

包含四个16位寄存器值的列表

List containing four 16-bit register values

4.2 CRC16Modbus

class modbuslink.utils.crc.CRC16Modbus[source]

Bases: object

Modbus CRC16校验工具

Modbus CRC16 Check Utils Module

static calculate(data: bytes | bytearray, use_table: bool = True) bytes[source]

计算CRC16校验码

Calculate CRC16 Checksum

Parameters:
  • data – 需要计算校验码的数据帧(地址+PDU) | Data frame for checksum calculation (address+PDU)

  • use_table – 是否使用查表法 | Whether to use the table lookup method

Returns:

2字节的CRC校验码 (little-endian bytes)

2-byte CRC checksum (little-endian bytes)

static validate(frame_with_crc: bytes | bytearray, use_table: bool = True) bool[source]

验证包含CRC的完整数据帧

Validate Complete Data Frame with CRC

Parameters:
  • frame_with_crc – 包含CRC校验码的完整数据帧 | Complete data frame containing CRC checksum

  • use_table – 是否使用查表法 | Whether to use the table lookup method

Returns:

如果CRC校验正确返回True,否则返回False

True if CRC verification is correct, False otherwise

4.3 LRC16Modbus

class modbuslink.utils.lrc.LRCModbus[source]

Bases: object

Modbus LRC校验工具类

Modbus LRC Check Utils Module

static calculate(data: bytes | bytearray) bytes[source]

计算LRC校验码

Calculate LRC Checksum

Parameters:

data – 需要计算的数据(不包含起始符’:’和结束符CRLF) | Data to calculate (excluding start ‘:’ and end CRLF)

Returns:

1字节的LRC校验码 (0x00 - 0xFF)

1-byte LRC checksum (0x00 - 0xFF)

Return type:

bytes

static validate(data_with_lrc: bytes | bytearray) bool[source]

验证包含LRC的数据

Validate data with LRC

Parameters:

data_with_lrc – 包含LRC的完整二进制数据 | Complete binary data containing LRC

Returns:

校验是否通过

Whether verification passed

Return type:

bool

5. Common Module

5.1 Logging Module

ModbusLink 日志系统

ModbusLink Logging System

class modbuslink.common.logging.BilingualLogger(name: str)[source]

双语日志适配器

Bilingual log adapter

__init__(name: str) None[source]
debug(cn: str, en: str, *args, **kwargs) None[source]
info(cn: str, en: str, *args, **kwargs) None[source]
warning(cn: str, en: str, *args, **kwargs) None[source]
error(cn: str, en: str, *args, **kwargs) None[source]
critical(cn: str, en: str, *args, **kwargs) None[source]
exception(cn: str, en: str, *args, **kwargs) None[source]
set_level(level) None[source]
class modbuslink.common.logging.ModbusLogger[source]

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[source]

设置ModbusLink的日志配置

Setup ModbusLink logging configuration

Parameters:
  • 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[source]

获取指定名称的日志器

Get logger with specified name

Parameters:

name – 日志器名称 | Logger name

Returns:

配置好的日志器实例

Configured logger instance

static enable_protocol_debug() None[source]

启用协议级别的调试日志

显示原始的十六进制数据包,用于调试通信问题。

Enable protocol-level debug logging

Shows raw hexadecimal packets for debugging communication issues.

static disable_protocol_debug() None[source]

禁用协议级别的调试日志

Disable protocol-level debug logging

modbuslink.common.logging.get_logger(name: str) BilingualLogger[source]

便捷函数:获取ModbusLink日志器

Convenience function: get ModbusLink logger

Parameters:

name – 日志器名称 | Logger name

Returns:

配置好的日志器实例

Configured logger instance

5.2 Exception Module

ModbusLinkError

exception modbuslink.common.exceptions.ModbusLinkError(cn: str = '', en: str = '')[source]

Bases: Exception

ModbusLink库的基础异常类

所有ModbusLink相关的异常都继承自这个基类。

Base exception class for ModbusLink library

All ModbusLink-related exceptions inherit from this base class.

__init__(cn: str = '', en: str = '') None[source]

CommunicationError

exception modbuslink.common.exceptions.CommunicationError(cn: str = '', en: str = '')[source]

Bases: ModbusLinkError

通信错误基类

涉及物理连接、网络传输、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 = '')[source]

Bases: ModbusLinkError

数据校验错误基类

涉及接收到的数据包损坏、校验和(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 = '')[source]

Bases: CommunicationError

连接错误异常

当无法建立或维持与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 = '')[source]

Bases: CommunicationError

超时错误异常

当操作超过指定的超时时间时抛出。 通常意味着发出了请求,但在规定时间内未收到任何字节。

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

exception modbuslink.common.exceptions.CrcError(cn: str = '', en: str = '')[source]

Bases: ValidationError

CRC校验错误异常

当接收到的Modbus-RTU数据帧CRC校验失败时抛出。

CRC validation error exception

Raised when CRC validation of received Modbus-RTU data frame fails.

LrcError

exception modbuslink.common.exceptions.LrcError(cn: str = '', en: str = '')[source]

Bases: ValidationError

LRC校验错误异常

当接收到的Modbus-ASCII数据帧LRC校验失败时抛出。

LRC validation error exception

Raised when LRC validation of received Modbus-ASCII data frame fails.

InvalidReplyError

exception modbuslink.common.exceptions.InvalidReplyError(cn: str = '', en: str = '')[source]

Bases: ValidationError

无效响应错误异常

当接收到的响应格式不正确或不符合预期时抛出。 例如:数据长度不足、协议头错误、接收到的功能码与请求不匹配等。

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 = '')[source]

Bases: ModbusLinkError

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

__init__(exception_code: int, function_code: int, message: str = '') None[source]

5.3 Language Module

modbuslink.common.language

alias of <module ‘modbuslink.common.language’ from ‘/home/runner/work/ModbusLink/ModbusLink/src/modbuslink/common/language.py’>