I am simulating a Modbus server client connection in VM (Ubuntu). The server is running and writing a random value on a register. The client is supposed to read the random written value from the register and then write different values on different registers and then read them. The client does not read the initially written value (by the server) from the register. But when I change the registers to write the value to the first register (where server writes the value) and then read the register in consecutive runs of the client code, the client reads the value written by it (on the register) properly. But still not the values being consistently written and updated by the server on the same register.
Server code is:
import random
from pyModbusTCP.server import ModbusServer, DataBank
from time import sleep
#instance of ModbusServer
server = ModbusServer("127.0.0.1", 12344, no_block=True)
#instance of DataBank
data_bank = DataBank()
server.data_bank = data_bank
try:
print("Start Server...")
server.start()
print("Server is online")
state = 0
while True:
data_bank.set_holding_registers(0, [random.randint(1, 100)]) # Set holding register values
if state != data_bank.get_holding_registers(0, 1)[0]: # Get holding register values
state = data_bank.get_holding_registers(0, 1)[0]
print("Value of Register 1 has changed to " + str(state))
sleep(1)
except Exception as e:
print(f"An error occurred: {e}")
print("Shutdown server...")
server.stop()
print("Server is stopped")
Server output is:
Start Server...
Server is online
Value of Register 1 has changed to 88
Value of Register 1 has changed to 83
Value of Register 1 has changed to 51
Value of Register 1 has changed to 61
Value of Register 1 has changed to 45
^CTraceback (most recent call last):
File "/home/neptun/Desktop/modbusyt/server.py", line 22, in <module>
sleep(1)
KeyboardInterrupt
Client code is:
import pyModbusTCP
from pyModbusTCP.client import ModbusClient
client = ModbusClient(host='127.0.0.1', port=12344, auto_open=True, debug=False)
try:
regs = client.read_holding_registers(0, 1)
if regs:
print(regs)
else:
print("Read error")
except pyModbusTCP.ModbusIOException as e:
print(f"Error reading registers: {e}")
try:
client.write_multiple_registers(0, [1, 2, 3])
regs = client.read_holding_registers(0, 5)
if regs:
print(regs)
else:
print("Read error")
except pyModbusTCP.ModbusIOException as e:
print(f"Error writing registers: {e}")
Client output is:
# first run:
[0]
[1, 2, 3, 0, 0]
# Consecutive runs:
[1]
[1, 2, 3, 0, 0]
You can't just set the data_bank with
server.data_bank = data_bank(it's used in the constructor to create adata_hdletc); instead pass it when creating the server:With this we get the following output:
full server below (there are some indentation issues in your question)