Modbus slave connect read

 1'''
 2Modbus_slave - modbus_slave_connect_read.py.
 3
 4This example demonstrates how to establish and manage a connection for a Modbus TCP Slave device, and then periodically read its internal data registers once a Modbus Master client connects.
 5
 6The range of Holding Registers is from 40001 to 40500
 7
 8For other examples please check:
 9    https://github.com/WPC-Systems-Ltd/WPC_Stand-alone_Python_release/tree/main/examples
10
11Copyright (c) 2025 WPC Systems Ltd.
12All rights reserved.
13'''
14
15## WPC
16import pywpc
17
18## Python
19import time
20
21# --- Modbus Configuration ---
22START_ADDRESS = 40001 ## Assume Modbus Holding Registers start at 40001
23NUM_REGISTERS = 10 ## Assume we want to read 10 registers (40001 to 40010)
24READ_INTERVAL = 1.0 ## Time interval for periodic data reading (seconds)
25CONNECTION_TIMEOUT = 20 ## Timeout for checking connection status (seconds)
26
27def run_modbus_slave_example():
28    ## Open Modbus Slave TCP server
29    status = pywpc.ModbusSlave_open()
30    if status != 0:
31        print("Failed to open Modbus Slave TCP server. Please try again.")
32        return
33
34    ## Wait for master connection
35    print("Waiting for master connection...")
36    start_time = time.time()
37    is_connected = False
38
39    while time.time() - start_time < CONNECTION_TIMEOUT:
40        connect_status = pywpc.ModbusSlave_getConnectStatus()
41
42        if connect_status == 1:
43            print("Connection successful!")
44            is_connected = True
45            break
46        time.sleep(0.5) # Check every 0.5s
47
48    if not is_connected:
49        print(f"Connection failed after {CONNECTION_TIMEOUT} seconds timeout.")
50
51    ## Read Holding Registers periodically
52    try:
53        while True:
54            # Check current connection status
55            connect_status = pywpc.ModbusSlave_getConnectStatus()
56            if connect_status != 1:
57                print("Client disconnected. Exiting read loop.")
58                break
59
60            ## Get holding register map
61            register_data = pywpc.ModbusSlave_getHoldingRegisterMap(START_ADDRESS, NUM_REGISTERS)
62            print(f"Holding register data: {register_data}")
63
64            time.sleep(READ_INTERVAL)
65
66    except KeyboardInterrupt:
67        print("Keyboard interrupt detected.")
68
69    finally:
70        pywpc.ModbusSlave_close()
71
72if __name__ == "__main__":
73    run_modbus_slave_example()