-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
213 lines (153 loc) · 4.79 KB
/
main.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
#!/usr/bin/python
import tornado.ioloop
import tornado.websocket
import threading
import sqlite3
import json
import socket
import time
import math
from datetime import datetime
import snmp
# Tornado WS info
WS_PORT = 9999
# UDP info
UDP_IP = '10.10.10.100'
UDP_PORT = 5005
# globals
arduino_data = '{"t": -1, "h": -1}'
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def open(self):
print("WebSocket opened")
def on_message(self, message):
req = json.loads(message)
if req['type'] == 'query':
# sqlite3 connections (read)
conn_r = sqlite3.connect('local.db')
conn_r.row_factory = sqlite3.Row
c_r = conn_r.cursor()
t = (req['time'],)
c_r.execute('SELECT * FROM monitories WHERE tstamp>? ORDER BY tstamp DESC', t)
results = c_r.fetchmany(size=20)
keys = ['tstamp', 'temperature', 'humidity', 'humidex', 'power', 'energy', 'traffic', 'co2', 'co2pbit', 'comfort']
# unused fields: id
res = {}
for k in keys:
res[k] = [r[k] for r in results]
# print res
# print '##'
# res = {'message': [dict(results[i]) for i in range(0, len(results))]}
conn_r.close()
self.write_message(res)
def on_close(self):
print("WebSocket closed")
def run_tornado():
print 'Starting Tornado service...'
app = tornado.web.Application([(r"/websocket", EchoWebSocket),])
app.listen(WS_PORT)
tornado.ioloop.IOLoop.current().start()
def stop_tornado():
print 'Stopping Tornado service...'
tornado.ioloop.IOLoop.current().stop()
def run_arduino_udp():
print 'Starting Arduino-UDP service...'
sock.bind((UDP_IP, UDP_PORT))
# 25 second timeout
# keep-alive packet sent every 10 seconds
sock.settimeout(25)
global arduino_data
while True:
try:
arduino_data = sock.recv(1024)
# arduino_data = '{"t": 20, "h": 20}'
# time.sleep(5)
# handle receive
# print "received message:", data
except socket.timeout:
arduino_data = '{"t": -1, "h": -1}'
def stop_arduino_udp():
print 'Stopping Arduino-UDP service...'
sock.close()
def run_datacapture():
print 'Starting Data-Capture service...'
global arduino_data
# fake
# arduino_data = {'t': 20, 'h': 20}
# init
traffic0 = snmp.get_traffic()
energy = 0.0
while True:
# 1 sec delay
time.sleep(1)
# get arduino data
sensor_data = json.loads(arduino_data)
# wait for arduino data to be received
# print sensor_data
if sensor_data['t'] != -1:
print ' # Capturing data: ' + str(datetime.now())
# get SNMP data
power = snmp.get_power() # W
traffic = snmp.get_traffic() - traffic0 # delta-bytes
# accumulate power
energy += power / 3600.0
# 82 CO2-g/KWh
co2 = energy * 0.082
co2pbit = co2 / (traffic * 8)
temperature = sensor_data['t'] / 10.0
humidity = sensor_data['h'] / 10.0
##################################################################################################
# sensor_data['t'] =
# sensor_data['h'] =
kelvin = temperature + 273;
eTs = 10 ** ((-2937.4 /kelvin) - 4.9283 * math.log(kelvin) / math.log(10) + 23.5471)
eTd = eTs * humidity / 100.0;
humidex = int(round(temperature + ((eTd-10)*5.0/9.0)))
##################################################################################################
if humidex < 25:
comfort = 1
elif humidex < 34:
comfort = 2
elif humidex < 40:
comfort = 3
elif humidex < 45:
comfort = 4
else:
comfort = 5
timestamp = int(round(time.time()))
# sqlite3 connection (write)
conn_w = sqlite3.connect('local.db')
c_w = conn_w.cursor()
# insert data
c_w.execute("INSERT INTO monitories (tstamp, temperature, humidity, humidex, power, energy, traffic, co2, co2pbit, comfort) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (timestamp, temperature, humidity, humidex, power, energy, traffic, co2, co2pbit, comfort))
# commit the changes
conn_w.commit()
conn_w.close()
else:
print '# SENSOR UNREACHABLE'
def stop_datacapture():
print 'Stopping Data-Capture service...'
def stop_db():
print 'Closing database connections...'
# conn_r.close()
# conn_w.close()
if __name__ == "__main__":
# start threads
for target in (run_tornado, run_arduino_udp, run_datacapture):
thread = threading.Thread(target=target)
thread.daemon = True
thread.start()
print '## Services running - Ctrl+C to stop'
# idle until shutdown signal
try:
while True:
raw_input('')
except KeyboardInterrupt:
print 'Stopping all services...'
stop_tornado()
stop_arduino_udp()
stop_datacapture()
stop_db()
exit(0)