I'm trying to connect two pcs together using pyModbusTCP. When I run both the client and server locally using local host it works just fine.
When I try and run them on separate PC's the client takes a while to "connect" and then just reads the registers as "None". I have set a static IP address for the server as 192.254.100.101 and can ping it using terminal on the other PC. I also have a static IP address on the client side of 192.254.100.102.
Client Code:
from pyModbusTCP.client import ModbusClient
import time
client = ModbusClient(host="192.254.100.101", port=502, debug = True)
print("Opening client")
client.open()
print("Client open")
try:
while True:
value = client.read_holding_registers(0)
print(f"Register 0: {value}")
time.sleep(1)
except:
print("Shutdown")
Server code:
from pyModbusTCP.server import ModbusServer, DataBank
import time
server = ModbusServer(host= "192.254.100.101", port = 502, no_block=True)
server.start()
try:
print("Starting server...")
server.start()
print("Server is online")
val = [0]
while True:
val0 = input("Val: ")
val = [int(val0)]
print(val)
DataBank.set_words(0, val)
time.sleep(0.5)
except:
print("Shutdown server")
server.stop()
.i.e:
you have a Raspberry pi with the static IP address of "192.254.100.101" and some devices are connected to it, then when you send a request to it you will declare the slave id number too, here you requested a data register.
now in the server app, you will return the answer using the sender packet IP address.
Use Wireshark and your local network for understanding.
Codes in java language Using Modbus4J:
Slave codes in Java using Modbus4J:
Slave codes for Wemos D1 (device) C language and Arduino IDE:
Client Code in python with pyModbusTCP:
Modbus Protocol Specification