Advertisement
iero
Mar 22nd, 2023
66
1
Never
This is comment for paste PZEM-004T
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Наверное  примерно так
  2. from pymodbus.client import ModbusSerialClient as ModbusClient
  3. import json
  4.  
  5. devices = [
  6.     {"name": "device1", "id": 1},
  7.     {"name": "device2", "id": 2},
  8.     {"name": "device3", "id": 3},
  9.     {"name": "device4", "id": 4},
  10.     {"name": "device5", "id": 5}
  11. ]
  12.  
  13. data = []
  14. errors = []
  15.  
  16. client = ModbusClient(method="rtu", port="/dev/ttyUSB0", stopbits=1, bytesize=8, parity='N', baudrate=9600)
  17.  
  18. try:
  19.     connection = client.connect()
  20.     for device in devices:
  21.         try:
  22.             result = client.read_input_registers(0, 10, device["id"])
  23.             voltage = result.registers[0] / 10
  24.             current = (result.registers[1] + (result.registers[2] << 16)) / 1000
  25.             power = (result.registers[3] + (result.registers[4] << 16)) / 10
  26.             energy = (result.registers[5] + (result.registers[6] << 16)) / 10
  27.             frequency = result.registers[7] / 10
  28.             power_factor = result.registers[8] / 100
  29.             data.append({"name": device["name"], "id": device["id"], "voltage": voltage, "current": current, "power": power, "energy": energy, "frequency": frequency, "power_factor": power_factor})
  30.         except:
  31.             errors.append(device["name"])
  32.             data.append({"name": device["name"], "id": device["id"], "voltage": 0, "current": 0, "power": 0, "energy": 0, "frequency": 0, "power_factor": 0})
  33.  
  34. except:
  35.     print("Failed to connect to Modbus device")
  36.  
  37. client.close()
  38.  
  39. with open("data.json", "w") as f:
  40.     json.dump({"data": data, "errors": errors}, f, indent=4)
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement