forked from switchdoclabs/SDL_Pi_SkyWeather2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pclogging.py
326 lines (253 loc) · 10.3 KB
/
pclogging.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
from __future__ import print_function
#
#
# logging system from Project Curacao
# filename: pclogger.py
# Version 1.0 10/04/13
#
# contains logging data
#
import sys
import time
import datetime
# Check for user imports
import config
import json
import state
import updateBlynk
import MySQLdb as mdb
import traceback
import WeatherUnderground
import wirelessSensors
import util
def systemlog(level, message):
if (config.enable_MySQL_Logging == True):
LOWESTDEBUG = 0
# open mysql database
# write log
# commit
# close
if (level >= LOWESTDEBUG):
try:
if (level == config.JSON):
if (config.USEBLYNK):
updateBlynk.blynkTerminalUpdate("JSON Loaded")
pass
else:
if (config.USEBLYNK):
updateBlynk.blynkTerminalUpdate(message)
pass
#print("trying database")
con = util.getSkyWeatherConnection()
cur = con.cursor()
#print("before query")
query = "INSERT INTO SystemLog(TimeStamp, Level, SystemText ) VALUES(LOCALTIMESTAMP(), %i, '%s')" % (level, message)
#print("query=%s" % query)
cur.execute(query)
con.commit()
except:
traceback.print_exc()
con.rollback()
#sys.exit(1)
finally:
cur.close()
con.close()
del cur
del con
def errorlog(message, stacktrace):
try:
#print("trying database")
con = util.getSkyWeatherConnection()
cur = con.cursor()
#print("before query")
query = "INSERT INTO error_log (message, error) VALUES (%s, %s)"
#print("query=%s" % query)
cur.execute(query, (message, stacktrace,))
con.commit()
except:
traceback.print_exc()
con.rollback()
#sys.exit(1)
finally:
cur.close()
con.close()
del cur
del con
def readLastHour24AQI():
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
# first calculate the 24 hour moving average for AQI
print("trying database")
con = util.getSkyWeatherConnection()
cur = con.cursor()
query = "SELECT id, AQI24Average FROM WeatherData ORDER BY id DESC Limit 1"
cur.execute(query)
myAQIRecords = cur.fetchall()
if (len(myAQIRecords > 0)):
state.Hour24_AQI = myAQIRecords[0][1]
else:
state.Hour24_AQI = 0.0
#print("AQIRecords=",myAQIRecords)
except mdb.Error as e:
traceback.print_exc()
print("Error %d: %s" % (e.args[0],e.args[1]))
con.rollback()
#sys.exit(1)
finally:
cur.close()
con.close()
del cur
del con
import gpiozero
def get60MinuteRain():
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
con = util.getSkyWeatherConnection()
cur = con.cursor()
timeDelta = datetime.timedelta(minutes=60)
now = datetime.datetime.now()
before = now - timeDelta
before = before.strftime('%Y-%m-%d %H:%M:%S')
# 60 minute
query = "SELECT id, TotalRain, TimeStamp FROM WeatherData WHERE TimeStamp > '%s' ORDER by id ASC" % before
#print("query=", query)
cur.execute(query)
rainspanrecords = cur.fetchall()
rainspan = 0.0
if (len(rainspanrecords) > 0):
rainspan = rainspanrecords[len(rainspanrecords)-1][1] - rainspanrecords[0][1]
return rainspan
except mdb.Error as e:
traceback.print_exc()
print("Error %d: %s" % (e.args[0],e.args[1]))
con.rollback()
#sys.exit(1)
return 0.0
def getCalendarDayRain():
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
con = util.getSkyWeatherConnection()
cur = con.cursor()
# calendar day rain
query = "SELECT id, TotalRain, TimeStamp FROM WeatherData WHERE DATE(TimeStamp) = CURDATE() ORDER by id ASC"
cur.execute(query)
rainspanrecords = cur.fetchall()
rainspan = 0.0
if (len(rainspanrecords) > 0):
rainspan = rainspanrecords[len(rainspanrecords)-1][1] - rainspanrecords[0][1]
return rainspan
except mdb.Error as e:
traceback.print_exc()
print("Error %d: %s" % (e.args[0],e.args[1]))
con.rollback()
#sys.exit(1)
return 0.0
def writeWeatherRecord():
if (config.SWDEBUG):
systemlog(config.INFO,"--->recording weather<---")
Rain24Hour = getCalendarDayRain()
print("Rain24Hour=", Rain24Hour)
WeatherUnderground.sendWeatherUndergroundData(Rain24Hour)
state.Rain60Minutes = get60MinuteRain()
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
cpu = gpiozero.CPUTemperature()
state.CPUTemperature = cpu.temperature
print("CPUT=", state.CPUTemperature)
# first calculate the 24 hour moving average for AQI
print("trying database")
con = util.getSkyWeatherConnection()
cur = con.cursor()
timeDelta = datetime.timedelta(days=1)
now = datetime.datetime.now()
before = now - timeDelta
before = before.strftime('%Y-%m-%d %H:%M:%S')
query = "SELECT id, AQI, TimeStamp FROM WeatherData WHERE (TimeStamp > '%s') ORDER BY TimeStamp " % (before)
cur.execute(query)
myAQIRecords = cur.fetchall()
myAQITotal = 0.0
#print("AQIRecords=",myAQIRecords)
if (len(myAQIRecords) > 0):
for i in range(0, len(myAQIRecords)):
myAQITotal = myAQITotal + myAQIRecords[i][1]
myAQI24 = (myAQITotal+float(state.AQI))/(len(myAQIRecords)+1)
else:
myAQI24 = 0.0
state.Hour24_AQI = myAQI24
if (config.SWDEBUG):
print("---------")
print("WR2 Array length=", len(state.MWR2Array))
print("---------")
for WR2JSON in state.MWR2Array:
# update the state to the array and write
#
if (config.SWDEBUG):
print("---------")
print("WR - SerialNumber=", WR2JSON["id"])
print("---------")
textWR2JSON = json.dumps(WR2JSON)
wirelessSensors.processFT020T(textWR2JSON, "", False)
fields = "OutdoorTemperature, OutdoorHumidity, IndoorTemperature, IndoorHumidity, TotalRain, SunlightVisible, SunlightUVIndex, WindSpeed, WindGust, WindDirection,BarometricPressure, BarometricPressureSeaLevel, BarometricTemperature, AQI, AQI24Average, BatteryOK, CPUTemperature, SerialNumber, RSSI, SNR, NOISE"
values = "%6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f,%6.2f,%6.2f,%6.2f,%6.2f,%6.2f, \'%s\',%6.2f,%d, %6.2f, %6.2f, %6.2f" % (state.OutdoorTemperature, state.OutdoorHumidity, state.IndoorTemperature, state.IndoorHumidity, state.TotalRain, state.SunlightVisible, state.SunlightUVIndex, state.WindSpeed, state.WindGust, state.WindDirection,state.BarometricPressure, state.BarometricPressureSeaLevel, state.BarometricTemperature, float(state.AQI), state.Hour24_AQI, state.BatteryOK, state.CPUTemperature, state.SerialNumber, state.RSSI, state.SNR, state.NOISE)
query = "INSERT INTO WeatherData (%s) VALUES(%s )" % (fields, values)
#print("query=", query)
cur.execute(query)
con.commit()
except mdb.Error as e:
traceback.print_exc()
print("Error %d: %s" % (e.args[0],e.args[1]))
con.rollback()
#sys.exit(1)
finally:
cur.close()
con.close()
del cur
del con
def writeITWeatherRecord():
if (config.SWDEBUG):
systemlog(config.INFO,"--->recording indoor metrics<---")
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
print("trying database")
con = util.getSkyWeatherConnection()
cur = con.cursor()
fields = "DeviceID, ChannelID, Temperature, Humidity, BatteryOK, TimeRead"
if (len(state.IndoorTH)> 0):
for singleChannel in state.IndoorTH:
values = "%d, %d, %6.2f, %6.2f, \"%s\", \"%s\"" % (singleChannel["deviceID"], singleChannel["channelID"], singleChannel["temperature"], singleChannel["humidity"], singleChannel["batteryOK"], singleChannel["time"])
query = "INSERT INTO IndoorTHSensors (%s) VALUES(%s )" % (fields, values)
#print("query=", query)
cur.execute(query)
con.commit()
else:
return
except mdb.Error as e:
traceback.print_exc()
print("Error %d: %s" % (e.args[0],e.args[1]))
con.rollback()
#sys.exit(1)
finally:
cur.close()
con.close()
del cur
del con