-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
executable file
·246 lines (209 loc) · 7.14 KB
/
server.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
#!/usr/bin/env python2.7
from bokeh.plotting import figure, output_server, cursession, show, vplot, hplot
from bokeh.session import Session
from __init__ import *
from wrappers import *
import json, time, pymongo, daemon, sys, os, socket
global client, output_server, uptime_start
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"wlan0",
"wlan1"
]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except IOError:
pass
return ip
client = pymongo.MongoClient()
output_server = output_server('meteo_data', url='http://{0}:{1}'.format(get_lan_ip(), 5006))
uptime_start = time.time()
#return time as HH:MM:SS
def get_time(gmt=3):
T = time.gmtime()
h,m,s = (T.tm_hour + gmt) % 24, T.tm_min, T.tm_sec
return "{0}:{1}:{2}".format(h,m,s)
class MeteoStation:
@property
def mode(self):
return self._mode
@mode.setter
def mode(self,value):
if self.modeset:
raise Exception('Mode already set to {0}'.format(self._mode))
else:
self._mode = value
@mode.getter
def mode(self):
return self._mode
def __init__(self, mode = 'arduino',serialObject=None): #nof indicates number of json fields
self.mode = mode
self.modeset = True
if mode is 'arduino':
import serial
if serialObject is None:
n=0
while True:
try:
self.ser = serial.Serial(SERIAL_PORT_DEV + str(n), BAUDRATE)
break
except serial.serialutil.SerialException:
print 'Could not open any serial port on {0}{1}. Trying with {0}{2}'.format(SERIAL_PORT_DEV,n,n+1)
n += 1
else:
self.ser = serialObject
self.ser.open()
elif mode is 'rpi':
self.bmp, self.dht = BMP180Wrapper(), DHT22Wrapper()
self.data = {}
self.data["temp"], self.data["hum"], self.data["pres"], self.data["timenow"] = [],[],[],[]
self.lastdata = ''; self.lastjson = None
#charts
self.tempchart, self.preschart, self.humchart = MeteoStation.MeteoChart('temp', 'Temperature', 'Temperature in *C'), MeteoStation.MeteoChart('pres','Pressure', 'Pressure in hPa'), MeteoStation.MeteoChart('hum','Humidity', 'Humidity in %RH')
self.charts = [self.tempchart, self.preschart, self.humchart]
self.figs = [chart.fig for chart in self.charts]
self.show_all()
cursession().publish()
#pymongo integration
try:
self.db = client['meteo_db']
self.collection = self.db.colletion['meteo_data_collection']
except: #retry with object-style formalism
self.db = client.meteo_db
self.collection = self.db.collection.meteo_data_collection
def update_charts(self):
for chart in self.charts:
chart.update()
def read_data(self):
if self.mode is 'arduino':
try:
self.lastdata = self.ser.readline()
return self.lastdata
except:
return
elif self.mode is 'rpi':
try:
self.lastdata = json.dumps({'temp': str((self.dht.read_temp()+self.bmp.read_temp())/2), 'hum': str(self.dht.read_hum()), 'pres': str(self.bmp.read_pres())})
print self.lastdata
return self.lastdata
except:
return
def parse_data(self, store_to_db=True):
self.read_data() #read data from serial object
try:
self.lastjson = json.loads(self.lastdata)
except:
return
if not(len(self.lastjson) is 3):
print 'Data could not be parsed'; return
if store_to_db: # store meteo data to meteo_db.meteo_data_collection
self.collection.insert_one(self.lastjson)
for key in self.data.keys():
if key is not 'timenow':
self.data[key].append(float(self.lastjson[key]))
print '{0}:{1}'.format(key, self.data[key][-1:])
self.data["timenow"].append(get_time())
for chart in self.charts: #append to charts datasource
chart.append_meteo_data(self.data)
#print 'Appended meteo data successfuly to charts'
def get_plot(self, mode="v"):
if not(mode is 'v' or mode is 'h'):
raise MeteoStation.InvalidPlotArgument()
if mode is 'v':
return vplot(*self.figs)
else:
return hplot(*self.figs)
def show_all(self):
show(self.get_plot());
def maintain(self):
if len(self.data[self.data.keys()[0]]) > MAX_STORAGE:
for key in self.data.keys():
self.data[key] = []
def start(self):
while True:
self.parse_data()
self.update_charts()
time.sleep(DELAY_INTERVAL)
def export_data_to_file(self, outputfilename):
if not(outputfilename.endswith('.json')):
outputfilename += '.json'
try:
os.system('mongoexport --db meteo_db --collection meteo_data_collection -o {0}'.format(outputfilename))
except:
raise MeteoStation.ExportError()
class MeteoChart:
"""Meteo Chart class"""
def __init__(self, name, title='', y_label='', plot_width=400, plot_height=400):
#self.fig = figure(plot_width, plot_height, name)
self.name = name
if title is '':
title = name
self.fig = figure(title=title, x_axis_label='Uptime in sec', y_axis_label = y_label)
self.fig.line([],[], name=self.name)
self.renderer = self.fig.select(dict(name=self.name))
self.data_source = self.renderer[0].data_source
def append_datum(self,x,y):
self.data_source.data['x'].append(x)
self.data_source.data['y'].append(y)
def append_meteo_data(self, d):
self.data_source.data['x'].append(time.time()-uptime_start)
self.data_source.data['y'].append(d[self.name][-1])
#self.update()
def update(self):
cursession().store_objects(self.data_source)
#print 'Stored data to current session'
def show(self):
show(self.fig)
def change_mode(self):
if self.mode is 'rpi': self.mode = 'arduino'
if self.mode is 'arduino': self.mode = 'rpi'
class InvalidChartData(Exception):
def __init__(self):
super(InvalidChartData, self).__init__()
class ParseDataError(Exception):
def __init__(self):
super(ParseDataError, self).__init__()
class InvalidPlotArgument(Exception):
def __init__(self):
super(InvalidPlotArgument, self).__init__()
class ExportError(Exception):
def __init__(self):
super(ExportError, self).__init__()
class MeteoStationDaemonizer(daemon.Daemon): #daemon wrapper for MeteoStation class
def __init__(self, meteo_station_instance=None):
super(MeteoStationDaemonizer, self).__init__('/var/run/meteo_station.pid')
if meteo_station_instance is None:
self.meteo_station = MeteoStation()
else:
self.meteo_station = meteo_station_instance
def run(self):
self.meteo_station.start()
if __name__ == '__main__':
assert(len(sys.argv) <= 2)
try:
bokeh_server(ip=get_lan_ip(), bg=True)
time.sleep(3)
except:
sys.exit()
finally:
if '--arduino' in sys.argv:
meteo_station = MeteoStation(mode='arduino')
else:
meteo_station = MeteoStation(mode='rpi')
if '--daemonized' in sys.argv:
meteo_station_daemon = MeteoStationDaemonizer(meteo_station)
meteo_station_daemon.start()
else:
meteo_station.start()