以下是使用 Python 和pymodbus库配置多个 Modbus 协议设备并上传数据的一个简单示例。此代码将连接到多个 Modbus 设备,并以一定周期推送数据。
首先,请确保已安装pymodbus库。可以通过以下命令安装:
pip install pymodbus
然后,创建一个名为multi_modbus_example.py的 Python 文件,并将以下代码粘贴到文件中:
from pymodbus.client.sync import ModbusTcpClient
from time import sleep
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s [%(funcName)s]: %(message)s')
devices = [
('192.168.1.10', 502),
('192.168.1.20', 502),
('192.168.1.30', 502)
]
clients = [ModbusTcpClient(ip, port) for ip, port in devices]
while True:
for client in clients:
try:
if not client.connect():
logging.error(f"无法连接到设备 {client.ip}")
continue
response = client.read_holding_registers(0, 10)
if not response.isError():
data = response.registers
logging.debug(f"从 {client.ip} 读取数据:{data}")
else:
logging.error(f"从 {client.ip} 读取数据时出错")
except Exception as e:
logging.error(f"从 {client.ip} 读取数据时出错:{e}")
client.close()
sleep(1)
在上述代码中,您需要将devices列表中的 IP 地址和端口替换为您实际设备的地址。同时,您可以通过修改read_holding_registers方法的参数来更改要读取的寄存器数量。
运行代码后,它将以一定周期(在本例中为 1 秒)连接到指定的 Modbus 设备,并读取保持寄存器的值。如果读取成功,数据将显示在日志中。
请注意,这只是一个简单的示例,您可能需要根据实际需求对代码进行修改。