A simple Modbus/TCP client library for Python
npx @tessl/cli install tessl/pypi-pymodbustcp@0.3.0A 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.
pip install pyModbusTCP# Client functionality
from pyModbusTCP.client import ModbusClient, DeviceIdentificationResponse
# Server functionality
from pyModbusTCP.server import ModbusServer, DataBank, DataHandler, DeviceIdentification
# Constants and utilities
from pyModbusTCP.constants import *
from pyModbusTCP import utils
# Package metadata
from pyModbusTCP import __version__, __title__, __description__, __url__, __license__, loggerfrom pyModbusTCP.client import ModbusClient
# Initialize client with automatic connection management
client = ModbusClient(host="192.168.1.100", port=502, unit_id=1, auto_open=True)
# Read 10 holding registers starting at address 0
registers = client.read_holding_registers(0, 10)
if registers:
print(f"Holding registers: {registers}")
else:
print(f"Read error: {client.last_error_as_txt}")
# Write a single coil
success = client.write_single_coil(100, True)
if success:
print("Coil written successfully")
# Read coils
coils = client.read_coils(100, 8)
if coils:
print(f"Coils: {coils}")from pyModbusTCP.server import ModbusServer, DataBank
# Create custom data bank
data_bank = DataBank()
# Initialize some data
data_bank.set_holding_registers(0, [1000, 2000, 3000, 4000, 5000])
data_bank.set_coils(0, [True, False, True, False])
# Start server
server = ModbusServer(host="0.0.0.0", port=502, data_bank=data_bank)
server.start()
print("Server started on port 502")
# Server will handle client requests automatically
# Call server.stop() when donepyModbusTCP implements both client and server components:
TCP client functionality for connecting to and communicating with Modbus servers. Supports automatic connection management, all standard Modbus function codes, and device identification queries.
class ModbusClient:
def __init__(self, host='localhost', port=502, unit_id=1, timeout=30.0, auto_open=True, auto_close=False): ...
def read_coils(self, bit_addr, bit_nb=1): ...
def read_discrete_inputs(self, bit_addr, bit_nb=1): ...
def read_holding_registers(self, reg_addr, reg_nb=1): ...
def read_input_registers(self, reg_addr, reg_nb=1): ...
def write_single_coil(self, bit_addr, bit_value): ...
def write_single_register(self, reg_addr, reg_value): ...
def write_multiple_coils(self, bits_addr, bits_value): ...
def write_multiple_registers(self, regs_addr, regs_value): ...TCP server functionality for creating Modbus servers that can handle client requests. Includes data storage management, request handling, and device identification configuration.
class ModbusServer:
def __init__(self, host="localhost", port=502, no_block=False, ipv6=False, data_bank=None, data_hdl=None): ...
def start(self): ...
def stop(self): ...
class DataBank:
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): ...
def get_coils(self, address, number=1, srv_info=None): ...
def set_coils(self, address, bit_list, srv_info=None): ...
def get_holding_registers(self, address, number=1, srv_info=None): ...
def set_holding_registers(self, address, word_list, srv_info=None): ...Utility functions for data type conversion, bit manipulation, IEEE 754 floating point encoding/decoding, and protocol validation.
def word_list_to_long(val_list, big_endian=True, long_long=False): ...
def long_list_to_word(val_list, big_endian=True, long_long=False): ...
def decode_ieee(val_int, double=False): ...
def encode_ieee(val_float, double=False): ...
def get_bits_from_int(val_int, val_size=16): ...
def set_bit(value, offset): ...
def test_bit(value, offset): ...Protocol constants, function codes, exception codes, and error handling utilities for robust Modbus communication.
# Function codes
READ_COILS = 0x01
READ_DISCRETE_INPUTS = 0x02
READ_HOLDING_REGISTERS = 0x03
WRITE_SINGLE_COIL = 0x05
WRITE_MULTIPLE_REGISTERS = 0x10
# Error codes and text mappings
MB_NO_ERR = 0
MB_CONNECT_ERR = 2
MB_TIMEOUT_ERR = 5
MB_ERR_TXT = {...} # Error code to text mappingclass DeviceIdentificationResponse:
"""
Response object for device identification queries.
Attributes:
conformity_level (int): Supported access and object type
more_follows (int): Indicates if more objects are available
next_object_id (int): Next object ID for following transaction
objects_by_id (dict): Dictionary with requested objects (key: object_id, value: bytes)
vendor_name (bytes): Vendor name (object ID 0x00)
product_code (bytes): Product code (object ID 0x01)
major_minor_revision (bytes): Major/minor revision (object ID 0x02)
vendor_url (bytes): Vendor URL (object ID 0x03)
product_name (bytes): Product name (object ID 0x04)
model_name (bytes): Model name (object ID 0x05)
user_application_name (bytes): User application name (object ID 0x06)
"""# Package information
__title__ = 'pyModbusTCP'
__description__ = 'A simple Modbus/TCP library for Python.'
__url__ = 'https://github.com/sourceperl/pyModbusTCP'
__version__ = '0.3.0' # Current version
__license__ = 'MIT'
# Package logger
logger = logging.getLogger('pyModbusTCP') # Package-level logger instance