or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client.mddatastore.mdindex.mdpdu.mdserver.md

index.mddocs/

0

# PyModbus

1

2

A comprehensive Python library providing both client and server implementations of the Modbus protocol. PyModbus supports multiple transport layers (TCP, UDP, Serial, TLS), various framing formats (RTU, ASCII, Socket), and offers both synchronous and asynchronous APIs for industrial automation, SCADA systems, and IoT applications.

3

4

## Package Information

5

6

- **Package Name**: pymodbus

7

- **Language**: Python

8

- **Installation**: `pip install pymodbus`

9

- **Optional dependencies**: `pip install pymodbus[serial]` for serial support, `pip install pymodbus[all]` for full features

10

- **Python Requirements**: Python >= 3.10

11

12

## Core Imports

13

14

```python

15

import pymodbus.client as ModbusClient

16

from pymodbus import FramerType, ModbusException, pymodbus_apply_logging_config

17

```

18

19

Common client imports:

20

21

```python

22

from pymodbus.client import ModbusTcpClient, AsyncModbusTcpClient

23

from pymodbus.client import ModbusSerialClient, AsyncModbusSerialClient

24

```

25

26

Server imports:

27

28

```python

29

from pymodbus.server import ModbusTcpServer, StartTcpServer

30

from pymodbus.datastore import ModbusServerContext, ModbusDeviceContext

31

from pymodbus.datastore import ModbusSequentialDataBlock

32

```

33

34

Transport and utility imports:

35

36

```python

37

from pymodbus.transport import CommType, CommParams, ModbusProtocol, NULLMODEM_HOST

38

from pymodbus.exceptions import (

39

ConnectionException, ModbusIOException, ParameterException,

40

NoSuchIdException, NotImplementedException, MessageRegisterException

41

)

42

```

43

44

## Basic Usage

45

46

### Synchronous TCP Client

47

48

```python

49

from pymodbus.client import ModbusTcpClient

50

from pymodbus import FramerType, ModbusException

51

52

# Create and connect client

53

client = ModbusTcpClient('127.0.0.1', port=502, framer=FramerType.SOCKET)

54

client.connect()

55

56

try:

57

# Read holding registers

58

result = client.read_holding_registers(0, count=10, device_id=1)

59

if not result.isError():

60

print(f"Register values: {result.registers}")

61

62

# Write single register

63

client.write_register(0, 123, device_id=1)

64

65

# Read coils

66

result = client.read_coils(0, count=8, device_id=1)

67

if not result.isError():

68

print(f"Coil values: {result.bits}")

69

70

except ModbusException as e:

71

print(f"Modbus error: {e}")

72

finally:

73

client.close()

74

```

75

76

### Asynchronous TCP Client

77

78

```python

79

import asyncio

80

from pymodbus.client import AsyncModbusTcpClient

81

82

async def run_async_client():

83

client = AsyncModbusTcpClient('127.0.0.1', port=502)

84

await client.connect()

85

86

try:

87

# Read input registers

88

result = await client.read_input_registers(0, count=5, device_id=1)

89

if not result.isError():

90

print(f"Input registers: {result.registers}")

91

finally:

92

client.close()

93

94

# Run the async client

95

asyncio.run(run_async_client())

96

```

97

98

### Simple TCP Server

99

100

```python

101

from pymodbus.server import StartTcpServer

102

from pymodbus.datastore import ModbusSequentialDataBlock, ModbusServerContext, ModbusDeviceContext

103

104

# Create datastore with some initial values

105

store = ModbusSequentialDataBlock(0, [0] * 100)

106

context = ModbusDeviceContext(

107

co=store, # coils

108

di=store, # discrete inputs

109

hr=store, # holding registers

110

ir=store # input registers

111

)

112

server_context = ModbusServerContext(device_default=context, single=True)

113

114

# Start server

115

StartTcpServer(context=server_context, address=('127.0.0.1', 5020))

116

```

117

118

## Architecture

119

120

PyModbus uses a layered architecture:

121

122

- **Transport Layer**: Handles TCP, UDP, Serial, and TLS communication

123

- **Framer Layer**: Manages different Modbus frame formats (RTU, ASCII, Socket, TLS)

124

- **PDU Layer**: Implements Modbus Protocol Data Units (function codes and messages)

125

- **Application Layer**: Provides client/server APIs and data management

126

127

The library supports both synchronous and asynchronous operations, allowing integration with various Python frameworks and applications.

128

129

## Capabilities

130

131

### Client Operations

132

133

Comprehensive client implementations supporting all standard Modbus function codes with both synchronous and asynchronous APIs across multiple transport protocols.

134

135

```python { .api }

136

# Synchronous clients

137

class ModbusTcpClient: ...

138

class ModbusUdpClient: ...

139

class ModbusSerialClient: ...

140

class ModbusTlsClient: ...

141

142

# Asynchronous clients

143

class AsyncModbusTcpClient: ...

144

class AsyncModbusUdpClient: ...

145

class AsyncModbusSerialClient: ...

146

class AsyncModbusTlsClient: ...

147

```

148

149

[Client Operations](./client.md)

150

151

### Server Operations

152

153

Full-featured Modbus server implementations with configurable data stores, custom function handlers, and simulator capabilities for testing and development.

154

155

```python { .api }

156

# Server classes

157

class ModbusTcpServer: ...

158

class ModbusUdpServer: ...

159

class ModbusSerialServer: ...

160

class ModbusTlsServer: ...

161

162

# Server start functions

163

def StartTcpServer(context, **kwargs): ...

164

def StartAsyncTcpServer(context, **kwargs): ...

165

```

166

167

[Server Operations](./server.md)

168

169

### Protocol Data Units (PDUs)

170

171

Complete implementation of all standard Modbus function codes including bit operations, register operations, file operations, and diagnostic functions.

172

173

```python { .api }

174

# Bit access messages

175

class ReadCoilsRequest: ...

176

class ReadDiscreteInputsRequest: ...

177

class WriteSingleCoilRequest: ...

178

class WriteMultipleCoilsRequest: ...

179

180

# Register access messages

181

class ReadHoldingRegistersRequest: ...

182

class ReadInputRegistersRequest: ...

183

class WriteSingleRegisterRequest: ...

184

class WriteMultipleRegistersRequest: ...

185

```

186

187

[PDU Messages](./pdu.md)

188

189

### Data Store Management

190

191

Flexible data storage implementations supporting both sequential and sparse memory layouts with full customization capabilities.

192

193

```python { .api }

194

class ModbusServerContext: ...

195

class ModbusDeviceContext: ...

196

class ModbusSequentialDataBlock: ...

197

class ModbusSparseDataBlock: ...

198

class ModbusSimulatorContext: ...

199

```

200

201

[Data Store](./datastore.md)

202

203

### Transport and Protocol Management

204

205

Low-level transport classes for custom protocol implementations and advanced connection handling.

206

207

```python { .api }

208

class CommType(int, Enum):

209

TCP = 1

210

TLS = 2

211

UDP = 3

212

SERIAL = 4

213

214

class CommParams:

215

def __init__(self, comm_name=None, comm_type=None, reconnect_delay=None,

216

reconnect_delay_max=0.0, timeout_connect=0.0, host="localhost",

217

port=0, source_address=None, handle_local_echo=False,

218

sslctx=None, baudrate=-1, bytesize=-1, parity='', stopbits=-1): ...

219

220

class ModbusProtocol:

221

def __init__(self, params, is_server=False): ...

222

async def transport_connect(self): ...

223

def transport_close(self): ...

224

225

# Special testing constant for nullmodem connections

226

NULLMODEM_HOST = "__pymodbus_nullmodem"

227

```

228

229

### Exception Handling

230

231

Specific exception classes for different types of Modbus errors and connection issues.

232

233

```python { .api }

234

class ModbusException(Exception):

235

def __init__(self, string): ...

236

def isError(self) -> bool: ...

237

238

class ConnectionException(ModbusException):

239

"""Error resulting from a bad connection."""

240

def __init__(self, string=""): ...

241

242

class ModbusIOException(ModbusException):

243

"""Error resulting from data i/o."""

244

def __init__(self, string="", function_code=None): ...

245

246

class ParameterException(ModbusException):

247

"""Error resulting from invalid parameter."""

248

def __init__(self, string=""): ...

249

250

class NoSuchIdException(ModbusException):

251

"""Error resulting from making a request to a id that does not exist."""

252

def __init__(self, string=""): ...

253

254

class NotImplementedException(ModbusException):

255

"""Error resulting from not implemented function."""

256

def __init__(self, string=""): ...

257

258

class MessageRegisterException(ModbusException):

259

"""Error resulting from failing to register a custom message request/response."""

260

def __init__(self, string=""): ...

261

```

262

263

### Debugging and Logging Utilities

264

265

Tools for debugging Modbus communications and configuring logging output.

266

267

```python { .api }

268

def pymodbus_apply_logging_config(level=logging.DEBUG, log_file_name=None):

269

"""

270

Apply basic logging configuration used by default by Pymodbus maintainers.

271

272

Parameters:

273

- level: Set log level (str or int)

274

- log_file_name: Optional log file name for file output

275

"""

276

277

def pymodbus_get_last_frames() -> str:

278

"""

279

Prepare and return last frames for automatic debugging.

280

281

Returns:

282

str: Formatted string of recent frame data for debugging

283

"""

284

```

285

286

### Simulator Functionality

287

288

Web-based Modbus server simulator with REST API and browser interface for testing and development.

289

290

```python { .api }

291

class ModbusSimulatorServer:

292

"""HTTP server for modbus simulator with web interface."""

293

def __init__(self, json_file="setup.json", custom_actions_module=None, http_host="localhost", http_port=8080): ...

294

async def start_server(self, modbus_server=None, modbus_device=None): ...

295

def stop_server(self): ...

296

297

def get_simulator_commandline():

298

"""Get command line interface for simulator."""

299

```

300

301

## Core Types

302

303

```python { .api }

304

# Frame types

305

class FramerType(str, Enum):

306

ASCII = "ascii"

307

RTU = "rtu"

308

SOCKET = "socket"

309

TLS = "tls"

310

311

# Status codes

312

class ModbusStatus(int, Enum):

313

WAITING = 0xFFFF

314

READY = 0x0000

315

ON = 0xFF00

316

OFF = 0x0000

317

318

# Exception codes

319

class ExcCodes(int, Enum):

320

ILLEGAL_FUNCTION = 0x01

321

ILLEGAL_ADDRESS = 0x02

322

ILLEGAL_VALUE = 0x03

323

DEVICE_FAILURE = 0x04

324

ACKNOWLEDGE = 0x05

325

DEVICE_BUSY = 0x06

326

MEMORY_PARITY_ERROR = 0x08

327

GATEWAY_PATH_UNAVIABLE = 0x0A

328

GATEWAY_NO_RESPONSE = 0x0B

329

330

# Device information types

331

class DeviceInformation(int, Enum):

332

BASIC = 0x01

333

REGULAR = 0x02

334

EXTENDED = 0x03

335

SPECIFIC = 0x04

336

337

# More data indicators

338

class MoreData(int, Enum):

339

NOTHING = 0x00

340

KEEP_READING = 0xFF

341

342

# Modbus Plus operations

343

class ModbusPlusOperation(int, Enum):

344

GET_STATISTICS = 0x03

345

CLEAR_STATISTICS = 0x04

346

347

# Base exception class

348

class ModbusException(Exception): ...

349

350

# Device identification

351

class ModbusDeviceIdentification:

352

def __init__(self, info=None): ...

353

def update(self, value): ...

354

def __getitem__(self, key): ...

355

def __setitem__(self, key, value): ...

356

357

# Logging configuration

358

def pymodbus_apply_logging_config(level=logging.DEBUG): ...

359

```