Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pymodbus.client import ModbusSerialClient as ModbusClient
- client = ModbusClient(method = "rtu", port = "/dev/ttyUSB0", stopbits = 1, bytesize = 8, parity = 'N', baudrate= 9600)
- connection = client.connect()
- #Polling the first device
- result = client.read_input_registers(0, 10, 1)
- #Polling N device
- #result = client.read_input_registers(0, 10, N)
- #Voltage
- print(result.registers[0])
- #Current
- print(result.registers[1] + (result.registers[2] << 16))
- #Power
- print(result.registers[3] + (result.registers[4] << 16))
- #Energy
- print(result.registers[5] + (result.registers[6] << 16))
- #Frequency
- print(result.registers[7])
- #Power factor
- print(result.registers[8])
- client.close()
Advertisement
Comments
-
- Наверное примерно так
- from pymodbus.client import ModbusSerialClient as ModbusClient
- import json
- devices = [
- {"name": "device1", "id": 1},
- {"name": "device2", "id": 2},
- {"name": "device3", "id": 3},
- {"name": "device4", "id": 4},
- {"name": "device5", "id": 5}
- ]
- data = []
- errors = []
- client = ModbusClient(method="rtu", port="/dev/ttyUSB0", stopbits=1, bytesize=8, parity='N', baudrate=9600)
- try:
- connection = client.connect()
- for device in devices:
- try:
- result = client.read_input_registers(0, 10, device["id"])
- voltage = result.registers[0] / 10
- current = (result.registers[1] + (result.registers[2] << 16)) / 1000
- power = (result.registers[3] + (result.registers[4] << 16)) / 10
- energy = (result.registers[5] + (result.registers[6] << 16)) / 10
- frequency = result.registers[7] / 10
- power_factor = result.registers[8] / 100
- data.append({"name": device["name"], "id": device["id"], "voltage": voltage, "current": current, "power": power, "energy": energy, "frequency": frequency, "power_factor": power_factor})
- except:
- errors.append(device["name"])
- data.append({"name": device["name"], "id": device["id"], "voltage": 0, "current": 0, "power": 0, "energy": 0, "frequency": 0, "power_factor": 0})
- except:
- print("Failed to connect to Modbus device")
- client.close()
- with open("data.json", "w") as f:
- json.dump({"data": data, "errors": errors}, f, indent=4)
Add Comment
Please, Sign In to add comment
Advertisement