forked from lafrech/oem_gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oemgatewayinterface.py
307 lines (236 loc) · 9.79 KB
/
oemgatewayinterface.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""
This code is released under the GNU Affero General Public License.
OpenEnergyMonitor project:
http://openenergymonitor.org
"""
import urllib2
import time
import logging
import csv
import urlparse
from configobj import ConfigObj
"""class OemGatewayInterface
User interface to communicate with the gateway.
The settings attribute stores the settings of the gateway. It is a
dictionnary with the following keys:
'gateway': a dictionary containing the gateway settings
'listeners': a dictionary containing the listeners
'buffer': a dictionary containing the buffers
The gateway settings are:
'loglevel': the logging level
Listeners and buffers are dictionaries with the folowing keys:
'type': class name
'init_settings': dictionary with initialization settings
'runtime_settings': dictionary with runtime settings
Initialization and runtime settings depend on the listener and
buffer type.
The run() method is supposed to be run regularly by the instanciater, to
perform regular communication tasks.
The check_settings() method is run regularly as well. It checks the settings
and returns True is settings were changed.
This almost empty class is meant to be inherited by subclasses specific to
each user interface.
"""
class OemGatewayInterface(object):
def __init__(self):
# Initialize logger
self._log = logging.getLogger("OemGateway")
# Initialize settings
self.settings = None
def run(self):
"""Run in background.
To be implemented in child class.
"""
pass
def check_settings(self):
"""Check settings
Update attribute settings and return True if modified.
To be implemented in child class.
"""
def get_settings(self):
"""Get settings
Returns None if settings couldn't be obtained.
To be implemented in child class.
"""
pass
class OemGatewayEmoncmsInterface(OemGatewayInterface):
def __init__(self, local_url='http://localhost/emoncms'):
"""Initialize emoncms interface
local_url (string): URL to local emoncms server
"""
# Initialization
super(OemGatewayEmoncmsInterface, self).__init__()
# Initialize local server settings
url = urlparse.urlparse(local_url)
self._local_protocol = url.scheme + '://'
self._local_domain = url.netloc
self._local_path = url.path
# Initialize update timestamps
self._status_update_timestamp = 0
self._settings_update_timestamp = 0
self._retry_time_interval = 60
# Check local emoncms URL is valid
try:
# Dummy time request
result = urllib2.urlopen(self._local_protocol +
self._local_domain +
self._local_path +
"/time/local.json")
except Exception:
import traceback
raise OemGatewayInterfaceInitError("Failure while connecting to " +
local_url + ":\n" + traceback.format_exc())
# Check settings
self.check_settings()
def run(self):
"""Run in background.
Update raspberry_pi running status.
"""
# Update status every second
now = time.time()
if (now - self._status_update_timestamp > 1):
# Update "running" status to inform emoncms the script is running
self._gateway_running()
# "Thanks for the status update. You've made it crystal clear."
self._status_update_timestamp = now
def check_settings(self):
"""Check settings
Update attribute settings and return True if modified.
"""
# Check settings only once per second
now = time.time()
if (now - self._settings_update_timestamp < 1):
return
# Update timestamp
self._settings_update_timestamp = now
# Get settings using emoncms API
try:
result = urllib2.urlopen(self._local_protocol +
self._local_domain +
self._local_path +
"/raspberrypi/get.json")
result = result.readline()
# result is of the form
# {"userid":"1","sgroup":"210",...,"remoteprotocol":"http:\\/\\/"}
result_array = result[1:-1].split(',')
# result is now of the form
# ['"userid":"1"',..., '"remoteprotocol":"http:\\/\\/"']
emoncms_s = {}
# For each setting, separate key and value
for s in result_array:
# We can't just use split(':') as there can be ":" inside
# a value (eg: "http://")
s_split = csv.reader([s], delimiter=':').next()
emoncms_s[s_split[0]] = s_split[1].replace("\\","")
except Exception:
import traceback
self._log.warning("Couldn't get settings, Exception: " +
traceback.format_exc())
self._settings_update_timestamp = now + self._retry_time_interval
return
settings = {}
# Format OemGateway settings
settings['gateway'] = {'loglevel': 'DEBUG'} # Stubbed until implemented
# RFM2Pi listener
settings['listeners'] = {'RFM2Pi': {}}
settings['listeners']['RFM2Pi'] = \
{'type': 'OemGatewayRFM2PiListener',
'init_settings': {'com_port': '/dev/ttyAMA0'},
'runtime_settings': {}}
for item in ['sgroup', 'frequency', 'baseid', 'sendtimeinterval']:
settings['listeners']['RFM2Pi']['runtime_settings'][item] = \
emoncms_s[item]
# Emoncms servers
settings['buffers'] = {'emoncms_local': {}, 'emoncms_remote': {}}
# Local
settings['buffers']['emoncms_local'] = \
{'type': 'OemGatewayEmoncmsBuffer',
'init_settings': {},
'runtime_settings': {}}
settings['buffers']['emoncms_local']['runtime_settings'] = \
{'protocol': self._local_protocol,
'domain': self._local_domain,
'path': self._local_path,
'apikey': emoncms_s['apikey'],
'period': '0',
'active': 'True'}
# Remote
settings['buffers']['emoncms_remote'] = \
{'type': 'OemGatewayEmoncmsBuffer',
'init_settings': {},
'runtime_settings': {}}
settings['buffers']['emoncms_remote']['runtime_settings'] = \
{'protocol': emoncms_s['remoteprotocol'],
'domain': emoncms_s['remotedomain'],
'path': emoncms_s['remotepath'],
'apikey': emoncms_s['remoteapikey'],
'period': '30',
'active': emoncms_s['remotesend']}
# Return True if settings modified
if settings != self.settings:
self.settings = settings
return True
def _gateway_running(self):
"""Update "script running" status."""
try:
result = urllib2.urlopen(self._local_protocol +
self._local_domain +
self._local_path +
"/raspberrypi/setrunning.json")
except Exception:
import traceback
self._log.warning(
"Couldn't update \"running\" status, Exception: " +
traceback.format_exc())
class OemGatewayFileInterface(OemGatewayInterface):
def __init__(self, filename):
# Initialization
super(OemGatewayFileInterface, self).__init__()
# Initialize update timestamp
self._settings_update_timestamp = 0
self._retry_time_interval = 60
# Initialize attribute settings as a ConfigObj instance
try:
self.settings = ConfigObj(filename, file_error=True)
except IOError as e:
raise OemGatewayInterfaceInitError(e)
except SyntaxError as e:
raise OemGatewayInterfaceInitError( \
'Error parsing config file \"%s\": ' % filename + str(e))
def check_settings(self):
"""Check settings
Update attribute settings and return True if modified.
"""
# Check settings only once per second
now = time.time()
if (now - self._settings_update_timestamp < 1):
return
# Update timestamp
self._settings_update_timestamp = now
# Backup settings
settings = dict(self.settings)
# Get settings from file
try:
self.settings.reload()
except IOError as e:
self._log.warning('Could not get settings: ' + str(e))
self._settings_update_timestamp = now + self._retry_time_interval
return
except SyntaxError as e:
self._log.warning('Could not get settings: ' +
'Error parsing config file: ' + str(e))
self._settings_update_timestamp = now + self._retry_time_interval
return
except Exception:
import traceback
self._log.warning("Couldn't get settings, Exception: " +
traceback.format_exc())
self._settings_update_timestamp = now + self._retry_time_interval
return
if self.settings != settings:
return True
"""class OemGatewayInterfaceInitError
Raise this when init fails.
"""
class OemGatewayInterfaceInitError(Exception):
pass