-
Notifications
You must be signed in to change notification settings - Fork 29
/
InverterExport.py
206 lines (169 loc) · 7.8 KB
/
InverterExport.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/python
"""InverterExport program.
Get data from a Wi-Fi kit logger and save/send the data to the defined plugin(s)
"""
import socket # Needed for talking to logger
import sys
import logging
import logging.config
import sys
if sys.version[:1] == '2':
import ConfigParser as configparser
else:
import configparser
import optparse
import os
import re
from PluginLoader import Plugin
import InverterMsg # Import the Msg handler
import InverterLib # Import the library
class InverterExport(object):
"""
Get data from the inverter(s) and store the data in a configured output
format/location.
"""
config = None
logger = None
def __init__(self, config_file):
# Load the setting
config_files = [InverterLib.expand_path('config-default.cfg'),
InverterLib.expand_path(config_file)]
self.config = configparser.RawConfigParser()
self.config.read(config_files)
# add command line option -p / --plugins to override the output plugins used
parser = optparse.OptionParser()
parser.add_option('-p', '--plugins',
action="store", dest="plugins",
help="output plugins to use")
self.options, self.args = parser.parse_args()
def run(self):
"""Get information from inverter and store is configured outputs."""
self.build_logger(self.config)
# Load output plugins
# Prepare path for plugin loading
sys.path.append(InverterLib.expand_path('outputs'))
Plugin.config = self.config
Plugin.logger = self.logger
enabled_plugins = self.config.get('general', 'enabled_plugins')\
.split(',')
# if -p / --plugin option giving at command line, override enabled plugins
if self.options.plugins:
enabled_plugins = self.options.plugins.split(',')
for plugin_name in enabled_plugins:
plugin_name = plugin_name.strip()
self.logger.debug('Importing output plugin ' + plugin_name)
__import__(plugin_name)
# Connect to logger
if not self.config.has_option('logger', 'gateways'):
self.logger.error('no gateways defined in configuration file, exiting.')
return []
if(self.config.get('logger', 'gateways') == 'auto'):
# get loggers
gateway_list = InverterLib.getLoggers().split(',')
if (len(gateway_list) < 2):
self.logger.error('No loggers found: {0}, exiting.'.format(gateway_list))
return []
self.logger.info('Loggers found on the network: {0}.'.format(gateway_list))
else:
gateway_list = self.config.get('logger', 'gateways').split(',')
if (len(gateway_list) % 2):
self.logger.error('incorrect number of values in configuration file for gateways: {0}, exiting.'.format(gateway_list))
return []
for i in range(0, len(gateway_list), 2):
ip = gateway_list[i]
sn = gateway_list[i+1]
self.logger.info('Connecting to logger with IP: {0} and SN {1}'.format(ip, sn))
port = self.config.get('logger', 'port')
timeout = self.config.getfloat('logger', 'timeout')
next = False
for res in socket.getaddrinfo(ip, port, socket.AF_INET,
socket.SOCK_STREAM):
family, socktype, proto, canonname, sockadress = res
try:
self.logger.info('connecting to {0} port {1}'.format(ip, port))
logger_socket = socket.socket(family, socktype, proto)
logger_socket.settimeout(timeout)
logger_socket.connect(sockadress)
except socket.error as msg:
self.logger.error('Could not open socket')
self.logger.error(msg)
self.logger.error('Error connecting to logger with IP: {0} and SN {1}, trying next logger.'.format(ip, sn))
next = True
break
if (next):
continue
data = InverterLib.createV4RequestFrame(int(sn))
logger_socket.sendall(data)
#dump raw data to log
self.logger.debug('RAW sent Packet (len={0}): '.format(len(data))+':'.join(hex(ord(chr(x)))[2:].zfill(2) for x in bytearray(data))+' '+re.sub('[^\x20-\x7f]', '', ''.join(chr(x) for x in bytearray(data))))
okflag = False
while (not okflag):
try:
data = logger_socket.recv(1024)
except socket.timeout as e:
self.logger.error('Timeout connecting to logger with IP: {0} and SN {1}, trying next logger.'.format(ip, sn))
okflag = True
continue
#dump raw data to log
self.logger.debug('RAW received Packet (len={0}): '.format(len(data))+':'.join(hex(ord(chr(x)))[2:].zfill(2) for x in bytearray(data))+' '+re.sub('[^\x20-\x7f]', '', ''.join(chr(x) for x in bytearray(data))))
msg = InverterMsg.InverterMsg(data)
#log DATA length
self.logger.debug('DATA len={0}: '.format(msg.len))
if (msg.msg)[:9] == 'DATA SEND':
self.logger.debug("Exit Status: {0}".format(msg.msg))
logger_socket.close()
okflag = True
continue
if (msg.msg)[:11] == 'NO INVERTER':
self.logger.debug("Inverter(s) are in sleep mode: {0} received".format(msg.msg))
logger_socket.close()
okflag = True
continue
self.logger.info("Inverter ID: {0}".format(msg.id))
if (msg.len > 140):
self.logger.info("Inverter main firmware version: {0}".format(msg.main_fwver))
self.logger.info("Inverter slave firmware version: {0}".format(msg.slave_fwver))
self.logger.info("RUN State: {0}".format(msg.run_state))
for plugin in Plugin.plugins:
self.logger.debug('Run plugin' + plugin.__class__.__name__)
plugin.process_message(msg)
def build_logger(self, config):
# Build logger
"""
Build logger for this program
Args:
config: configparser with settings from file
"""
log_levels = dict(notset=0, debug=10, info=20, warning=30, error=40, critical=50)
log_dict = {
'version': 1,
'formatters': {
'f': {'format': '%(asctime)s %(levelname)s %(message)s'}
},
'handlers': {
'none': {'class': 'logging.NullHandler'},
'console': {
'class': 'logging.StreamHandler',
'formatter': 'f'
},
'file': {
'class': 'logging.FileHandler',
'filename': InverterLib.expand_path(config.get('log',
'filename')),
'formatter': 'f'},
},
'loggers': {
'InverterLogger': {
'handlers': config.get('log', 'type').split(','),
'level': log_levels[config.get('log', 'level')]
}
}
}
logging.config.dictConfig(log_dict)
self.logger = logging.getLogger('InverterLogger')
def override_config(self, section, option, value):
"""Override config settings"""
self.config.set(section, option, value)
if __name__ == "__main__":
inverter_exporter = InverterExport('config.cfg')
inverter_exporter.run()