forked from switchdoclabs/SDL_Pi_SkyWeather2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SkyWeather2.py
425 lines (308 loc) · 11.7 KB
/
SkyWeather2.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
#!/usr/bin/env python3
#
# SkyWeather2 Solar Powered Weather Station
# November 2020
#
# SwitchDoc Labs
# www.switchdoc.com
#
#
# imports
# Check for user imports
from __future__ import print_function
import config
config.SWVERSION = "027.6"
# system imports
import time
from apscheduler.schedulers.background import BackgroundScheduler
import apscheduler.events
import subprocess
import pclogging
import traceback
import sys
import picamera
# user defined imports
import updateBlynk
import state
import tasks
import wirelessSensors
import wiredSensors
import sendemail
import watchDog
import util
from bmp280 import BMP280
import SkyCamera
import os
import SkyCamRemote
import PictureManagement
import ProcessPicture
# Scheduler Helpers
# print out faults inside events
def ap_my_listener(event):
if event.exception:
try:
pclogging.errorlog(event.exception, event.traceback)
except:
print (event.exception)
print (event.traceback)
# helper functions
def shutdownPi(why):
pclogging.systemlog(config.INFO, "Pi Shutting Down: %s" % why)
sendemail.sendEmail("test", "SkyWeather2 Shutting down:"+ why, "The SkyWeather2 Raspberry Pi shutting down.", config.notifyAddress, config.fromAddress, "");
sys.stdout.flush()
time.sleep(10.0)
os.system("sudo shutdown -h now")
def rebootPi(why):
pclogging.systemlog(config.INFO, "Pi Rebooting: %s" % why)
if (config.USEBLYNK):
updateBlynk.blynkTerminalUpdate("Pi Rebooting: %s" % why)
pclogging.systemlog(config.INFO, "Pi Rebooting: %s" % why)
#os.system("sudo shutdown -r now")
# more low level reboot
os.system("echo 1 | sudo tee /proc/sys/kernel/sysrq;echo s | sudo tee /proc/sysrq-trigger;echo u | sudo tee /proc/sysrq-trigger;echo b | sudo tee /proc/sysrq-trigger")
import MySQLdb as mdb
# Program Requirement Checking and new directories
os.makedirs("static/SkyCam", exist_ok=True)
if (config.enable_MySQL_Logging):
# SkyWeather2 SQL Database
try:
con = util.getSkyWeatherConnection()
except:
print("--------")
print("MySQL Database SkyWeather2 Not Installed.")
print("Run this command:")
print("sudo mysql -u root -p < SkyWeather2.sql")
print("SkyWeather2 Stopped")
print("--------")
sys.exit("SkyWeather2 Requirements Error Exit")
try:
con = util.getWeatherSenseConnection()
except:
print("--------")
print("MySQL Database WeatherSenseWireless Not Installed.")
print("Run this command:")
print("sudo mysql -u root -p < WeatherSenseWireless.sql")
print("SkyWeather2 Stopped")
print("--------")
sys.exit("SkyWeather2 Requirements Error Exit")
# Check for updates having been applied
try:
con = util.getWeatherSenseConnection()
cur = con.cursor()
query = "SELECT * FROM SkyCamPictures"
cur.execute(query)
query = "SELECT * FROM RAD433MHZ"
cur.execute(query)
except:
#print(traceback.format_exc())
print("--------")
print("MySQL Database WeatherSenseWireless Updates Not Installed.")
print("Run this command:")
print("sudo mysql -u root -p WeatherSenseWireless < updateWeatherSenseWireless.sql")
print("SkyWeather2 Stopped")
print("--------")
sys.exit("SkyWeather2 Requirements Error Exit")
# update weather table 27.2 update
try:
con = util.getSkyWeatherConnection()
cur = con.cursor()
query = "SELECT SerialNumber FROM WeatherData"
cur.execute(query)
except:
print("--------")
print("MySQL Database SkyWeather2 Updates Not Installed.")
print("Run this command:")
print("sudo mysql -u root -p SkyWeather2 < 27.2.DataBaseUpdate.sql")
print("SkyWeather2 Stopped")
print("--------")
sys.exit("SkyWeather2 Requirements Error Exit")
# update weather table 27.3 update
try:
con = util.getSkyWeatherConnection()
cur = con.cursor()
query = "SELECT RSSI FROM WeatherData"
cur.execute(query)
except:
print("--------")
print("MySQL Database SkyWeather2 Updates for 27.3 Not Installed.")
print("Run this command:")
print("sudo mysql -u root -p SkyWeather2 < 27.3.DataBaseUpdate.sql")
print("SkyWeather2 Stopped")
print("--------")
sys.exit("SkyWeather2 Requirements Error Exit")
# main program
print ("")
print ("##########################################################")
print ("SkyWeather2 Weather Station Version "+config.SWVERSION+" - SwitchDoc Labs")
print ("")
print ("Program Started at:"+ time.strftime("%Y-%m-%d %H:%M:%S"))
print ("##########################################################")
print ("")
#
if (config.SWDEBUG):
print("Starting pigpio daemon")
# kill all pigpio instances
try:
cmd = [ 'killall', 'pigpiod' ]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
print(output)
time.sleep(5)
except:
#print(traceback.format_exc())
pass
cmd = [ '/usr/bin/pigpiod' ]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
print(output)
# detect devices
################
# Dust Sensor
################
try:
import DustSensor
DustSensor.powerOnDustSensor()
time.sleep(3)
myData = DustSensor.get_data()
#print ("data=",myData)
config.DustSensor_Present = True
except:
config.DustSensor_Present = False
################
# BMP280 Setup
################
try:
from smbus2 import SMBus
except ImportError:
from smbus import SMBus
# Initialise the BMP280
bus = SMBus(1)
try:
bmp280 = BMP280(i2c_dev=bus, i2c_addr=0x77)
state.BarometricTemperature = round(bmp280.get_temperature(), 2)
config.BMP280_Present = True
except:
if (config.SWDEBUG):
pass
#print(traceback.format_exc())
config.BMP280_Present = False
################
# SkyCamera Setup
################
#Establish WeatherSTEMHash
if (config.USEWEATHERSTEM == True):
state.WeatherSTEMHash = SkyCamera.SkyWeatherKeyGeneration(config.STATIONKEY)
#Detect Camera WeatherSTEMHash
try:
with picamera.PiCamera() as cam:
if (config.SWDEBUG):
print("Pi Camera Revision",cam.revision)
cam.close()
config.Camera_Present = True
except:
config.Camera_Present = False
# display device present variables
print("----------------------")
print(util.returnStatusLine("BMP280",config.BMP280_Present))
print(util.returnStatusLine("SkyCam",config.Camera_Present))
print(util.returnStatusLine("OLED",config.OLED_Present))
print(util.returnStatusLine("SunAirPlus/SunControl",config.SunAirPlus_Present))
print(util.returnStatusLine("SolarMAX",config.SolarMAX_Present))
print(util.returnStatusLine("DustSensor",config.DustSensor_Present))
print()
print(util.returnStatusEnable("UseBlynk",config.USEBLYNK))
print(util.returnStatusEnable("UseWSLIGHTNING",config.USEWSLIGHTNING))
print(util.returnStatusEnable("UseWSAQI",config.USEWSAQI))
print(util.returnStatusEnable("UseWSSKYCAM",config.USEWSSKYCAM))
print(util.returnStatusEnable("UseMySQL",config.enable_MySQL_Logging))
print(util.returnStatusEnable("UseMQTT",config.MQTT_Enable))
print(util.returnStatusLine("Check WLAN",config.enable_WLAN_Detection))
print(util.returnStatusLine("WeatherUnderground",config.WeatherUnderground_Present))
print(util.returnStatusLine("UseWeatherStem",config.USEWEATHERSTEM))
print("----------------------")
# startup
pclogging.systemlog(config.INFO,"SkyWeather2 Startup Version "+config.SWVERSION )
if (config.USEBLYNK):
updateBlynk.blynkEventUpdate("SW Startup Version "+config.SWVERSION)
updateBlynk.blynkTerminalUpdate("SW Startup Version "+config.SWVERSION)
subjectText = "The "+ config.STATIONKEY + " SkyWeather2 Raspberry Pi has #rebooted."
ipAddress = subprocess.check_output(['hostname', '-I'])
if (config.USEBLYNK):
updateBlynk.blynkEventUpdate("IPAddress: "+ipAddress.decode())
updateBlynk.blynkTerminalUpdate("IPAddress: "+ipAddress.decode())
bodyText = "SkyWeather2 Version "+config.SWVERSION+ " Startup \n"+ipAddress.decode()+"\n"
#if (config.SunAirPlus_Present):
# sampleSunAirPlus()
# bodyText = bodyText + "\n" + "BV=%0.2fV/BC=%0.2fmA/SV=%0.2fV/SC=%0.2fmA" % (state.batteryVoltage, state.batteryCurrent, state.solarVoltage, state.solarCurrent)
try:
sendemail.sendEmail("test", bodyText, subjectText ,config.notifyAddress, config.fromAddress, "");
except:
print(traceback.format_exc())
print("Email Exception - not sent - probably not configured")
if (config.USEBLYNK):
updateBlynk.blynkInit()
import paho.mqtt.client as mqtt
# set up MQTT
if (config.MQTT_Enable):
state.mqtt_client = mqtt.Client(client_id="SkyWeather2")
state.mqtt_client.connect(config.MQTT_Server_URL, port=config.MQTT_Port_Number)
import publishMQTT
# Set up scheduler
scheduler = BackgroundScheduler()
# for debugging
scheduler.add_listener(ap_my_listener, apscheduler.events.EVENT_JOB_ERROR)
##############
# setup tasks
##############
hdc1080 = None
wiredSensors.readWiredSensors(bmp280, hdc1080)
# prints out the date and time to console
scheduler.add_job(tasks.tick, 'interval', seconds=60)
# read wireless sensor package
scheduler.add_job(wirelessSensors.readSensors) # run in background
# read wired sensor package
scheduler.add_job(wiredSensors.readWiredSensors, 'interval', args=[bmp280, hdc1080], seconds = 30)
if (config.SWDEBUG):
# print state
scheduler.add_job(state.printState, 'interval', seconds=60)
if (config.USEBLYNK):
scheduler.add_job(updateBlynk.blynkStateUpdate, 'interval', seconds=30)
if (config.MQTT_Enable):
scheduler.add_job(publishMQTT.publish, 'interval', seconds=config.MQTT_Send_Seconds)
scheduler.add_job(watchDog.patTheDog, 'interval', seconds=20) # reset the WatchDog Timer
# every 5 days at 00:04, reboot
#scheduler.add_job(rebootPi, 'cron', day='5-30/5', hour=6, minute=4, args=["5 day Reboot"])
#TEC change to once a day
scheduler.add_job(rebootPi, 'cron', day='*', hour=0, minute=4, args=["daily Reboot"])
#check for Barometric Trend (every 15 minutes)
scheduler.add_job(util.barometricTrend, 'interval', seconds=15*60)
if (config.DustSensor_Present):
#DustSensor.read_AQI() # get current value
scheduler.add_job(DustSensor.read_AQI, 'interval', seconds=60*12)
if (config.USEWSAQI):
wirelessSensors.WSread_AQI() # get current value
scheduler.add_job(wirelessSensors.WSread_AQI, 'interval', seconds=60*20)
# weather sensors
# TEC changed to 5 minute intervals
# TODO externalize
print("setting data record frequency = ", config.Record_Weather_Frequency)
scheduler.add_job(pclogging.writeWeatherRecord, 'interval', seconds=int(config.Record_Weather_Frequency)*60)
scheduler.add_job(pclogging.writeITWeatherRecord, 'interval', seconds=15*60)
# sky camera
if (config.Camera_Present):
scheduler.add_job(SkyCamera.takeSkyPicture, 'interval', seconds=config.INTERVAL_CAM_PICS__SECONDS)
# process SkyCam Remote bi-directional messages
if (config.MQTT_Enable== True):
scheduler.add_job(SkyCamRemote.startMQTT) # run in background
# SkyCam Management Programs
scheduler.add_job(PictureManagement.cleanPictures, 'cron', day='*', hour=3, minute=4, args=["Daily Picture Clean"])
scheduler.add_job(PictureManagement.cleanTimeLapses, 'cron', day='*', hour=3, minute=10, args=["Daily Time Lapse Clean"])
scheduler.add_job(PictureManagement.buildTimeLapse, 'cron', day='*', hour=5, minute=30, args=["Time Lapse Generation"])
# start scheduler
scheduler.start()
print ("-----------------")
print ("Scheduled Jobs")
print ("-----------------")
scheduler.print_jobs()
print ("-----------------")
# Main Loop
while True:
time.sleep(1.0)