-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpclogging.py
511 lines (420 loc) · 17.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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
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 state
import MySQLdb as mdb
import SkyCamera
import traceback
import readJSON
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):
pass
else:
pass
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
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 countBluetooth():
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
query = "SELECT * From BluetoothSensors "
#print("query=", query)
cur.execute(query)
myRecords = cur.fetchall()
#print ('myRecords=',myRecords)
return len(myRecords)
except mdb.Error as e:
traceback.print_exc()
print("Error %d: %s" % (e.args[0],e.args[1]))
#sys.exit(1)
finally:
cur.close()
con.close()
del cur
del con
return 0
def processInfraredSensor(MQTTJSON):
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
query = "INSERT INTO InfraredSensorData (DeviceID, PixelData ) VALUES('%s', '%s' )" % (MQTTJSON["id"], MQTTJSON["infrareddata"])
#print("query=", query)
cur.execute(query)
con.commit()
SkyCamera.processInfraredPicture(MQTTJSON["id"],MQTTJSON["infrareddata"])
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 processBluetoothSensor(MQTTJSON):
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
splitline = MQTTJSON["macaddress"].split(" ")
pickaddresslist = splitline[0].split(":")
pickaddress = pickaddresslist[4] + ":" + pickaddresslist[5]
query = "INSERT INTO BluetoothSensorData(DeviceID, MacAddress, PickAddress, Temperature, Brightness, Moisture, Conductivity, Battery, SensorType, TimeRead, ReadCount ) VALUES('%s', '%s', '%s', %f, %d, %d, %d, %d, '%s', '%s', %d)" % (MQTTJSON["id"], MQTTJSON["macaddress"], pickaddress, round(float(MQTTJSON["temperature"])/10.0,1), int(MQTTJSON["brightness"]), int(MQTTJSON["moisture"]), int(MQTTJSON["conductivity"]), int(MQTTJSON["battery"]), MQTTJSON["sensorType"], MQTTJSON["timestamp"], int(MQTTJSON["readCount"]))
#print("query=", query)
cur.execute(query)
con.commit()
# also update current sensor array
sensorUpdated = False
for sensor in state.LatestBluetoothSensors:
mypickaddress = sensor['macaddress'][len(sensor['macaddress'])-5:]
if (mypickaddress == pickaddress):
print("remove pickaddress=", pickaddress)
state.LatestBluetoothSensors.remove(sensor)
# add new one in
myDict = MQTTJSON
myDict["pickaddress"] = pickaddress
myDict["temperature"] = round(float(myDict["temperature"])/10.0, 1)
state.LatestBluetoothSensors.append(myDict)
sensorUpdated = True
break
if (sensorUpdated == False):
# new item
myDict = MQTTJSON
myDict["pickaddress"] = pickaddress
myDict["temperature"] = round(float(myDict["temperature"])/10.0, 1)
state.LatestBluetoothSensors.append(myDict)
#print("state.LatestBluetoothSensors =", state.LatestBluetoothSensors)
except:
traceback.print_exc()
con.rollback()
#sys.exit(1)
finally:
cur.close()
con.close()
del cur
del con
def sensorlog(DeviceID, SensorNumber, SensorValue, RawSensorValue, SensorType, TimeRead ):
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
query = "INSERT INTO Sensors(DeviceID, SensorNumber, SensorValue, RawSensorValue, SensorType, TimeRead ) VALUES('%s', '%s', %f, %s, '%s', '%s')" % (DeviceID, SensorNumber, float(SensorValue), RawSensorValue, SensorType, TimeRead)
#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 getValveState(id):
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
query = "SELECT * From ValveRecord WHERE DeviceID = '%s' ORDER BY ID DESC LIMIT 1" % id
#print("query=", query)
cur.execute(query)
myRecords = cur.fetchall()
#print ('myRecords=',myRecords)
if (len(myRecords) == 0):
return "V0000000"
return myRecords[0][2]
except mdb.Error as e:
traceback.print_exc()
print("Error %d: %s" % (e.args[0],e.args[1]))
#sys.exit(1)
finally:
cur.close()
con.close()
del cur
del con
def valvelog(DeviceID, ValveNumber, State, Source, ValveType, Seconds):
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
query = "INSERT INTO ValveChanges(DeviceID, ValveNumber, State, Source, ValveType, SecondsOn ) VALUES('%s', '%s', %d, '%s', '%s',%d)" % (DeviceID, ValveNumber, int(State), Source, ValveType, int(Seconds))
#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 writeMQTTValveChangeRecord(MQTTJSON):
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
query = "INSERT INTO ValveRecord(DeviceID, State) VALUES('%s', '%s')" % (MQTTJSON['id'], MQTTJSON['valvestate'])
#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
return "V00000000"
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 = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
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
def convertRawToTurbidity(rawTurbidity):
Turbidity = int(-4.49*float(rawTurbidity) + 6746.0)
if (Turbidity > 3000):
Turbidity = 3000
if (Turbidity < 0):
Turbidity = 0
return Turbidity
def convertRawLevelToLevel(rawLevel):
# piecewise linear
DeltaSpread = int(config.Tank_Pump_Level_Empty)- int(config.Tank_Pump_Level_Full)
#Level = 100*(1- (rawLevel - int(config.Tank_Pump_Level_Full))/DeltaSpread )
myScale = float(rawLevel)/float(config.Tank_Pump_Level_Empty)
print("rawLeve=", rawLevel)
print("myScale = ", myScale)
if (myScale >= 0.85):
Level = 41*(1-myScale)/0.15
else:
if (myScale >= 0.69):
Level =62*(1-myScale)/0.31
else:
if (myScale >= 0.64):
Level =83*(1-myScale)/0.36
else:
if (myScale >= 0.61):
Level =100*(1-myScale)/0.39
else:
Level = 100
if (Level > 100):
Level = 100
if (Level < 0):
Level = 0
print("Level=", Level)
return Level
def convertRawTDSToTDS(rawTDS):
Voltage = rawTDS*0.003 #Convert analog reading to Voltage(0.29 from 3V 5V difference)
#print("precale voltage=", Voltage)
#Voltage = rawTDS*0.003*0.60 #Convert analog reading to Voltage(0.29 from 3V 5V difference)
#print("postscale voltage=", Voltage)
TDS=(133.42/Voltage*Voltage*Voltage - 255.86*(Voltage*Voltage) + 857.39*Voltage)*0.5; #Convert voltage value to TDS value
#print("presccale TDS=", TDS)
#TDS=TDS*0.141 # calibration
#print("postscale TDS=", TDS)
if (TDS < 0):
TDS = 0
return TDS
def convertRawPhToPh(rawPh):
phValue = (rawPh/2048)*3.3*3.5+config.pHOffset
return phValue;
def fetch24HourData(Value):
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
timeDelta = datetime.timedelta(minutes=24*60)
now = datetime.datetime.now()
before = now - timeDelta
before = before.strftime('%Y-%m-%d %H:%M:%S')
# 24 Hours
query = "SELECT id, %s, TimeStamp FROM Hydroponics WHERE TimeStamp > '%s' ORDER by id ASC" % (Value, before)
print("query=", query)
cur.execute(query)
records = cur.fetchall()
Hour24 = 0.0
Total = 0.0
for myRecord in records:
Total = Total + float(myRecord[1])
if (len(records) > 0):
Hour24 = Total/len(records)
return Hour24
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 writeHydroponicsRecord(MQTTJSON):
if (config.enable_MySQL_Logging == True):
# open mysql database
# write log
# commit
# close
try:
#print("trying database")
con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SmartGarden3');
cur = con.cursor()
# convert to values
rawTurbidity = float(MQTTJSON["rawturbidity"])
rawLevel = float(MQTTJSON["rawlevel"])
rawTDS = float(MQTTJSON["rawtds"])
rawPh = float(MQTTJSON["rawph"])
Turbidity = convertRawToTurbidity(rawTurbidity)
TDS = convertRawTDSToTDS(rawTDS)
Level = convertRawLevelToLevel(rawLevel)
Ph = convertRawPhToPh(rawPh)
Temperature = MQTTJSON["temperature"]
# now adjust for enabled
# scan for wireless match to get constants
myID = MQTTJSON["id"]
wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON")
myWireless = []
for wireless in wirelessJSON:
if (myID == wireless["id"]):
myWireless = wireless
if (myWireless['hydroponics_temperature'] == "false"):
Temperature = -1
if (myWireless['hydroponics_tds'] == "false"):
TDS = -1
if (myWireless['hydroponics_ph'] == "false"):
Ph = -1
if (myWireless['hydroponics_turbidity'] == "false"):
Turbidity = -1
if (myWireless['hydroponics_level'] == "false"):
Level = -1
break;
# insert information into state hydroponics information
state.LatestHydroponicsValues.update({"ID" : myID})
state.LatestHydroponicsValues.update({"Temperature" : Temperature})
state.LatestHydroponicsValues.update({"TDS" : TDS})
state.LatestHydroponicsValues.update({"Ph" : Ph})
state.LatestHydroponicsValues.update({"Turbidity" : Turbidity})
state.LatestHydroponicsValues.update({"Level" : Level})
Temperature24Hour = fetch24HourData("Temperature")
TDS24Hour = fetch24HourData("TDS")
Turbidity24Hour = fetch24HourData("Turbidity")
Ph24Hour = fetch24HourData("Ph")
Level24Hour = fetch24HourData("Level")
#state.LatestHydroponicsValues.update({"Timestamp" : datetime.now()})
query = "INSERT INTO Hydroponics(DeviceID, Temperature, Turbidity, RawTurbidity, TDS, RawTDS, Level, RawLevel, Ph, RawPH, Temperature24Hour, TDS24Hour, Turbidity24Hour, Ph24Hour, Level24Hour) VALUES('%s', '%6.2f', %6.2f, '%d', '%6.2f',%d, %6.2f, %6.2f, %6.2f, %d, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f)" % (MQTTJSON["id"], float(Temperature), Turbidity, int(MQTTJSON["rawturbidity"]), TDS, int(MQTTJSON["rawtds"]), Level, float(MQTTJSON["rawlevel"]), Ph, int(MQTTJSON["rawph"]), Temperature24Hour, TDS24Hour, Turbidity24Hour, Ph24Hour, Level24Hour)
#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