0
# pyModbusTCP
1
2
A pure Python implementation of a Modbus/TCP client and server library that enables communication with industrial automation devices and systems using the Modbus protocol over TCP/IP networks. It offers comprehensive API for reading and writing various Modbus data types including coils, discrete inputs, holding registers, and input registers, with support for both synchronous operations and automatic connection management.
3
4
## Package Information
5
6
- **Package Name**: pyModbusTCP
7
- **Language**: Python
8
- **Installation**: `pip install pyModbusTCP`
9
- **Version**: 0.3.0
10
- **License**: MIT
11
- **Documentation**: https://pymodbustcp.readthedocs.io/
12
13
## Core Imports
14
15
```python
16
# Client functionality
17
from pyModbusTCP.client import ModbusClient, DeviceIdentificationResponse
18
19
# Server functionality
20
from pyModbusTCP.server import ModbusServer, DataBank, DataHandler, DeviceIdentification
21
22
# Constants and utilities
23
from pyModbusTCP.constants import *
24
from pyModbusTCP import utils
25
26
# Package metadata
27
from pyModbusTCP import __version__, __title__, __description__, __url__, __license__, logger
28
```
29
30
## Basic Usage
31
32
### Client Example
33
34
```python
35
from pyModbusTCP.client import ModbusClient
36
37
# Initialize client with automatic connection management
38
client = ModbusClient(host="192.168.1.100", port=502, unit_id=1, auto_open=True)
39
40
# Read 10 holding registers starting at address 0
41
registers = client.read_holding_registers(0, 10)
42
if registers:
43
print(f"Holding registers: {registers}")
44
else:
45
print(f"Read error: {client.last_error_as_txt}")
46
47
# Write a single coil
48
success = client.write_single_coil(100, True)
49
if success:
50
print("Coil written successfully")
51
52
# Read coils
53
coils = client.read_coils(100, 8)
54
if coils:
55
print(f"Coils: {coils}")
56
```
57
58
### Server Example
59
60
```python
61
from pyModbusTCP.server import ModbusServer, DataBank
62
63
# Create custom data bank
64
data_bank = DataBank()
65
66
# Initialize some data
67
data_bank.set_holding_registers(0, [1000, 2000, 3000, 4000, 5000])
68
data_bank.set_coils(0, [True, False, True, False])
69
70
# Start server
71
server = ModbusServer(host="0.0.0.0", port=502, data_bank=data_bank)
72
server.start()
73
print("Server started on port 502")
74
75
# Server will handle client requests automatically
76
# Call server.stop() when done
77
```
78
79
## Architecture
80
81
pyModbusTCP implements both client and server components:
82
83
- **Client (ModbusClient)**: Synchronous TCP client with automatic connection management, supporting all standard Modbus function codes and device identification
84
- **Server (ModbusServer)**: Multi-threaded TCP server with customizable data storage and request handling
85
- **Data Management**: Pluggable data bank system for flexible data storage and access control
86
- **Protocol Support**: Full Modbus/TCP protocol implementation with error handling and exception reporting
87
- **Utilities**: Comprehensive data conversion functions for working with different data types and formats
88
89
## Capabilities
90
91
### Client Operations
92
93
TCP client functionality for connecting to and communicating with Modbus servers. Supports automatic connection management, all standard Modbus function codes, and device identification queries.
94
95
```python { .api }
96
class ModbusClient:
97
def __init__(self, host='localhost', port=502, unit_id=1, timeout=30.0, auto_open=True, auto_close=False): ...
98
def read_coils(self, bit_addr, bit_nb=1): ...
99
def read_discrete_inputs(self, bit_addr, bit_nb=1): ...
100
def read_holding_registers(self, reg_addr, reg_nb=1): ...
101
def read_input_registers(self, reg_addr, reg_nb=1): ...
102
def write_single_coil(self, bit_addr, bit_value): ...
103
def write_single_register(self, reg_addr, reg_value): ...
104
def write_multiple_coils(self, bits_addr, bits_value): ...
105
def write_multiple_registers(self, regs_addr, regs_value): ...
106
```
107
108
[Client Operations](./client.md)
109
110
### Server Operations
111
112
TCP server functionality for creating Modbus servers that can handle client requests. Includes data storage management, request handling, and device identification configuration.
113
114
```python { .api }
115
class ModbusServer:
116
def __init__(self, host="localhost", port=502, no_block=False, ipv6=False, data_bank=None, data_hdl=None): ...
117
def start(self): ...
118
def stop(self): ...
119
120
class DataBank:
121
def __init__(self, coils_size=0x10000, coils_default_value=False, d_inputs_size=0x10000, d_inputs_default_value=False, h_regs_size=0x10000, h_regs_default_value=0, i_regs_size=0x10000, i_regs_default_value=0): ...
122
def get_coils(self, address, number=1, srv_info=None): ...
123
def set_coils(self, address, bit_list, srv_info=None): ...
124
def get_holding_registers(self, address, number=1, srv_info=None): ...
125
def set_holding_registers(self, address, word_list, srv_info=None): ...
126
```
127
128
[Server Operations](./server.md)
129
130
### Data Utilities
131
132
Utility functions for data type conversion, bit manipulation, IEEE 754 floating point encoding/decoding, and protocol validation.
133
134
```python { .api }
135
def word_list_to_long(val_list, big_endian=True, long_long=False): ...
136
def long_list_to_word(val_list, big_endian=True, long_long=False): ...
137
def decode_ieee(val_int, double=False): ...
138
def encode_ieee(val_float, double=False): ...
139
def get_bits_from_int(val_int, val_size=16): ...
140
def set_bit(value, offset): ...
141
def test_bit(value, offset): ...
142
```
143
144
[Data Utilities](./utils.md)
145
146
### Constants and Error Handling
147
148
Protocol constants, function codes, exception codes, and error handling utilities for robust Modbus communication.
149
150
```python { .api }
151
# Function codes
152
READ_COILS = 0x01
153
READ_DISCRETE_INPUTS = 0x02
154
READ_HOLDING_REGISTERS = 0x03
155
WRITE_SINGLE_COIL = 0x05
156
WRITE_MULTIPLE_REGISTERS = 0x10
157
158
# Error codes and text mappings
159
MB_NO_ERR = 0
160
MB_CONNECT_ERR = 2
161
MB_TIMEOUT_ERR = 5
162
MB_ERR_TXT = {...} # Error code to text mapping
163
```
164
165
[Constants and Error Handling](./constants.md)
166
167
## Types
168
169
```python { .api }
170
class DeviceIdentificationResponse:
171
"""
172
Response object for device identification queries.
173
174
Attributes:
175
conformity_level (int): Supported access and object type
176
more_follows (int): Indicates if more objects are available
177
next_object_id (int): Next object ID for following transaction
178
objects_by_id (dict): Dictionary with requested objects (key: object_id, value: bytes)
179
vendor_name (bytes): Vendor name (object ID 0x00)
180
product_code (bytes): Product code (object ID 0x01)
181
major_minor_revision (bytes): Major/minor revision (object ID 0x02)
182
vendor_url (bytes): Vendor URL (object ID 0x03)
183
product_name (bytes): Product name (object ID 0x04)
184
model_name (bytes): Model name (object ID 0x05)
185
user_application_name (bytes): User application name (object ID 0x06)
186
"""
187
```
188
189
## Package Metadata
190
191
```python { .api }
192
# Package information
193
__title__ = 'pyModbusTCP'
194
__description__ = 'A simple Modbus/TCP library for Python.'
195
__url__ = 'https://github.com/sourceperl/pyModbusTCP'
196
__version__ = '0.3.0' # Current version
197
__license__ = 'MIT'
198
199
# Package logger
200
logger = logging.getLogger('pyModbusTCP') # Package-level logger instance
201
```