我正在尝试通过 TCP 与 Modbus 进行通信。我想在没有库的情况下使用这种类型的代码。
代码运行如下:
sudo python3 modbus_master.py
当我使用此代码运行程序时,我会看到 Wireshark 中定义的 Modbus 连接。我也在使用从站Modbus程序(不止一个),但与我的主站没有连接。
下面的代码我做错了什么?
#!/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()
我认为您的问题出在防火墙的IP或Port上。
因此,如果您的代码在同一台机器上运行,您可以使用
localhost
或 127.0.0.1
IP 代替机器 IP。
[注意]:
如果您的操作系统是基于 *nix 系统,并且您有
ufw
防火墙,请执行以下命令:
$ sudo ufw disable
您的问题解决了吗,也许您可以帮助我,解决我的类似问题: modbus tcp与王鸽RTU5026
您的程序想要什么,请解释您的 modbus tcp 请求。谢谢