forked from basking-in-the-sun2000/solar-logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
modbustcp.py
42 lines (37 loc) · 1.33 KB
/
modbustcp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
import time
import config
def connect_bus(ip=config.inverter_ip, PortN = config.inverter_port, timeout = 3):
client = ModbusClient(host=ip, port=PortN, timeout=timeout, RetryOnEmpty = True, retries = 3)
time.sleep(1)
client.connect()
time.sleep(1)
return client
def close_bus(client):
client.close()
time.sleep(5)
del client
def read_registers(client, UnitID, data):
try:
nb = int(data['registers'])
if data['method'] == "hold":
result = client.read_holding_registers(int(data['addr']), count=nb, unit=UnitID)
elif data['method'] == "input":
result = client.read_input_registers(int(data['addr']), count=nb, unit=UnitID)
ns = time.time()
while (time.time() - ns < 1.5):
try:
if not result.isError():
j = result.registers[nb - 1]
break
except Exception as e:
print("mdobus read_registers error 1: %s" % str(e))
time.sleep(0.2)
if 'exception_code' in vars(result):
break
continue
time.sleep(0.025)
return result
except Exception as e:
print("mdobus read_registers error: %s" % str(e))
return -1