-
Notifications
You must be signed in to change notification settings - Fork 14
/
solarmon.py
95 lines (77 loc) · 3.02 KB
/
solarmon.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
import time
import os
from configparser import RawConfigParser
from influxdb import InfluxDBClient
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from growatt import Growatt
settings = RawConfigParser()
settings.read(os.path.dirname(os.path.realpath(__file__)) + '/solarmon.cfg')
interval = settings.getint('query', 'interval', fallback=1)
offline_interval = settings.getint('query', 'offline_interval', fallback=60)
error_interval = settings.getint('query', 'error_interval', fallback=60)
db_name = settings.get('influx', 'db_name', fallback='inverter')
measurement = settings.get('influx', 'measurement', fallback='inverter')
# Clients
print('Setup InfluxDB Client... ', end='')
influx = InfluxDBClient(host=settings.get('influx', 'host', fallback='localhost'),
port=settings.getint('influx', 'port', fallback=8086),
username=settings.get('influx', 'username', fallback=None),
password=settings.get('influx', 'password', fallback=None),
database=db_name)
influx.create_database(db_name)
print('Done!')
print('Setup Serial Connection... ', end='')
port = settings.get('solarmon', 'port', fallback='/dev/ttyUSB0')
client = ModbusClient(method='rtu', port=port, baudrate=9600, stopbits=1, parity='N', bytesize=8, timeout=1)
client.connect()
print('Dome!')
print('Loading inverters... ')
inverters = []
for section in settings.sections():
if not section.startswith('inverters.'):
continue
name = section[10:]
unit = int(settings.get(section, 'unit'))
measurement = settings.get(section, 'measurement')
growatt = Growatt(client, name, unit)
growatt.print_info()
inverters.append({
'error_sleep': 0,
'growatt': growatt,
'measurement': measurement
})
print('Done!')
while True:
online = False
for inverter in inverters:
# If this inverter errored then we wait a bit before trying again
if inverter['error_sleep'] > 0:
inverter['error_sleep'] -= interval
continue
growatt = inverter['growatt']
try:
now = time.time()
info = growatt.read()
if info is None:
continue
# Mark that at least one inverter is online so we should continue collecting data
online = True
points = [{
'time': int(now),
'measurement': inverter['measurement'],
"fields": info
}]
print(growatt.name)
print(points)
if not influx.write_points(points, time_precision='s'):
print("Failed to write to DB!")
except Exception as err:
print(growatt.name)
print(err)
inverter['error_sleep'] = error_interval
if online:
time.sleep(interval)
else:
# If all the inverters are not online because no power is being generated then we sleep for 1 min
time.sleep(offline_interval)