Reputation: 586
I am trying to communicate with Modbus via TCP. I want to use this type of code without a library.
The code is run like this :
sudo python3 modbus_master.py
When I run the program with this code then I see my Modbus connection defined in Wireshark. I am also using slave Modbus programs (more than one) but there is no connection with my master.
What am I doing wrong in the following code?
#!/usr/bin/python3
# This is client.py file
import socket
import struct
import time
# Create a TCP/IP socket
TCP_IP = '192.168.0.107'
TCP_PORT = 502
BUFFER_SIZE = 39
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((TCP_IP, TCP_PORT))
try:
unitId = 16
functionCode = 5
print("\n,Switching plug on")
coilId = 1
req = struct.pack('12B', 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, int(unitId), int(functionCode), 0x00, int(coilId),
0xff,
0x00)
sock.send(req)
print("TX: (%s)" % req)
time.sleep(2)
finally:
print('\nCLOSING SOCKET')
sock.close()
Upvotes: 2
Views: 9531
Reputation: 34196
I think your problem is in IP or Port with the firewall.
So if your codes run in the same machine, you can use localhost
or 127.0.0.1
IP instead of machine IP.
[NOTE]:
If your OS is *nix system based, and you have the ufw
firewall, doing the following command:
$ sudo ufw disable
Upvotes: 0