forked from ve3sjk/SkyWeather-Python-3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SkyWeather.py
executable file
·1705 lines (1481 loc) · 66.6 KB
/
SkyWeather.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
# SkyWeather Solar Powered Weather Station
# February 2019
#
# SwitchDoc Labs
# www.switchdoc.com
#
#
# from __future__ import print_function
# imports
# Check for user imports
try:
import conflocal as config
except ImportError:
import config
import uuid
# printing the value of unique MAC
# address using uuid and getnode() function
MACADDRESS = hex(uuid.getnode())
config.STATIONMAC = MACADDRESS
config.SWVERSION = "055-sk"
#system imports
import sys
import time
import traceback
from datetime import datetime
import random
import re
import math
import os
import threading
import subprocess
import sendemail
import logging
logging.basicConfig()
sys.path.append('./TSL2591')
sys.path.append('./SDL_Pi_SI1145')
sys.path.append('./SDL_Pi_TCA9545')
sys.path.append('./SDL_Pi_SSD1306')
sys.path.append('./Adafruit_Python_SSD1306')
sys.path.append('./RTC_SDL_DS3231')
sys.path.append('./Adafruit_Python_BMP')
sys.path.append('./Adafruit_Python_GPIO')
sys.path.append('./SDL_Pi_WeatherRack')
sys.path.append('./RaspberryPi-AS3935/RPi_AS3935')
sys.path.append('./SDL_Pi_INA3221')
sys.path.append('./graphs')
sys.path.append('./SDL_Pi_HDC1000')
sys.path.append('./SDL_Pi_AM2315')
sys.path.append('./SDL_Pi_SHT30')
sys.path.append('./BME680')
#sys.path.append('./MD503')
sys.path.append('./python-veml6070')
# sys.path.append('./')
sys.path.append('./SDL_Pi_GrovePowerDrive')
import pclogging
import updateBlynk
import state
import subprocess
import RPi.GPIO as GPIO
import doAllGraphs
import smbus
import struct
import SDL_Pi_HDC1000
from apscheduler.schedulers.background import BackgroundScheduler
import apscheduler.events
if (config.enable_MySQL_Logging == True):
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb as mdb
# import picamera
# import SkyCamera
import DustSensor
import util
import SDL_Pi_INA3221
import SDL_DS3231
# import Adafruit_BMP.BMP280 as BMP280
import SDL_Pi_WeatherRack as SDL_Pi_WeatherRack
import bme680 as BME680
import BME680_Functions
from RPi_AS3935 import RPi_AS3935
import Adafruit_SSD1306
import Scroll_SSD1306
import WeatherUnderground
import SDL_Pi_SI1145
import SI1145Lux
if (config.runLEDs):
from neopixel import *
import pixelDriver
import TSL2591
import veml6070
import SDL_Pi_TCA9545
#import AirQualitySensorLibrary as AirQualitySensorLibrary
#from MADS1x15 import ADS1x15
import SDL_Pi_GrovePowerDrive
# import Scroll_SSD1306
##################################
# Device Present State Variables #
##################################
#indicate interrupt has happened from as3936
as3935_Interrupt = False
VEML6070_Present = False
config.Camera_Present = False
config.TCA9545_I2CMux_Present = False
config.SunAirPlus_Present = False
config.AS3935_Present = False
config.DS3231_Present = False
config.BMP280_Present = False
config.BME680_Present = False
config.AM2315_Present = False
config.ADS1015_Present = False
config.ADS1115_Present = False
config.OLED_Present = False
config.WXLink_Present = False
config.Sunlight_Present = False
config.TSL2591_Present = False
config.SolarMax_Present = False
config.MD503_Present = False
# if the WXLink has stopped transmitting, == False
config.WXLink_Data_Fresh = False
config.WXLink_LastMessageID = 0
#Establish WeatherSTEMHash #
############################
if (config.USEWEATHERSTEM == True):
state.WeatherSTEMHash = SkyCamera.SkyWeatherKeyGeneration(config.STATIONKEY)
###################
# TCA9545 I2C Mux #
###################
#/*=========================================================================
# I2C ADDRESS/BITS
# -----------------------------------------------------------------------*/
TCA9545_ADDRESS = (0x73) # 1110011 (A0+A1=VDD)
#/*=========================================================================*/
#/*=========================================================================
# CONFIG REGISTER (R/W)
# -----------------------------------------------------------------------*/
TCA9545_REG_CONFIG = (0x00)
#/*---------------------------------------------------------------------*/
TCA9545_CONFIG_BUS0 = (0x01) # 1 = enable, 0 = disable
TCA9545_CONFIG_BUS1 = (0x02) # 1 = enable, 0 = disable
TCA9545_CONFIG_BUS2 = (0x04) # 1 = enable, 0 = disable
TCA9545_CONFIG_BUS3 = (0x08) # 1 = enable, 0 = disable
#/*=========================================================================*/
# I2C Mux TCA9545 Detection
try:
tca9545 = SDL_Pi_TCA9545.SDL_Pi_TCA9545(addr=TCA9545_ADDRESS, bus_enable = TCA9545_CONFIG_BUS0)
# turn I2CBus 1 on
tca9545.write_control_register(TCA9545_CONFIG_BUS2)
config.TCA9545_I2CMux_Present = True
except:
print (">>>>>>>>>>>>>>>>>>><<<<<<<<<<<")
print ("TCA9545 I2C Mux Not Present")
print (">>>>>>>>>>>>>>>>>>><<<<<<<<<<<")
config.TCA9545_I2CMux_Present = False
def removePower(GroveSavePin):
GPIO.setup(GroveSavePin, GPIO.OUT)
GPIO.output(GroveSavePin, False)
def restorePower(GroveSavePin):
GPIO.setup(GroveSavePin, GPIO.OUT)
GPIO.output(GroveSavePin, True)
def togglePower(GroveSavePin):
if (config.SWDEBUG == True):
print("Toggling Power to Pin=", GroveSavePin)
removePower(GroveSavePin)
time.sleep(4.5)
restorePower(GroveSavePin)
###############
# Fan Control #
###############
TEMPFANTURNON = 37.0
TEMPFANTURNOFF = 34.0
myPowerDrive = SDL_Pi_GrovePowerDrive.SDL_Pi_GrovePowerDrive(config.GPIO_Pin_PowerDrive_Sig1, config.GPIO_Pin_PowerDrive_Sig2, False, False)
def turnFanOn():
if (state.fanState == False):
pclogging.log(pclogging.INFO, __name__, "Turning Fan On" )
if (config.USEBLYNK):
updateBlynk.blynkStatusTerminalUpdate("Turning Fan On")
myPowerDrive.setPowerDrive(1, True)
myPowerDrive.setPowerDrive(2, True)
state.fanState = True
def turnFanOff():
if (state.fanState == True):
pclogging.log(pclogging.INFO, __name__, "Turning Fan Off" )
if (config.USEBLYNK):
updateBlynk.blynkStatusTerminalUpdate("Turning Fan Off")
myPowerDrive.setPowerDrive(1, False)
myPowerDrive.setPowerDrive(2, False)
state.fanState = False
turnFanOff()
#################################
# TSL2591 Sunlight Sensor Setup #
#################################
# turn I2CBus 3 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS3)
try:
tsl2591 = TSL2591.Tsl2591()
int_time=TSL2591.INTEGRATIONTIME_100MS
gain=TSL2591.GAIN_LOW
tsl2591.set_gain(gain)
tsl2591.set_timing(int_time)
full, ir = tsl2591.get_full_luminosity() # read raw values (full spectrum and ir spectrum)
lux = tsl2591.calculate_lux(full, ir) # convert raw values to lux
print("TSL2591 Init Complete: LUX: %f W/(m*m),FULL: %d, IR: %d" % (lux, full, ir))
# print (lux, full, ir)
# print ()
config.TSL2591_Present = True
except:
config.TSL2591_Present = False
#########################
# VEML6070 Sensor Setup #
#########################
# turn I2CBus 3 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS3)
try:
config.VEML6070_Present = False
#restorePower(SI1145GSPIN)
# time.sleep(1.0)
# VEML6070_Sensor = SDL_Pi_SI1145.SDL_Pi_SI1145(indoor=0)
# time.sleep(1.0)
# veml = veml6070.Veml6070()
# veml.set_integration_time(veml6070.INTEGRATIONTIME_1T)
# i = veml6070.INTEGRATIONTIME_1T
# uv_raw = veml.get_uva_light_intensity_raw()
# uv = veml.get_uva_light_intensity()
# uvi = get_estimated_risk_level(uv)
# visible = veml.get_uva_light_intensity_raw()
# print "visible=", visible
# config.VEML6070_Present = False
# vis = veml.get_uva_light_intensity_raw()
# IR = vis
# UV = veml.get_uva_light_intensity()
# IR_Lux = UV
# vis_Lux = UV
# uvIndex = UV / 100.0
# print("Integration Time setting %d: %f W/(m*m) from raw value %d give uvi value of %s" % (i, UV, vis, uvIndex))
except:
config.VEML6070_Present = False
##############################
# Sunlight SI1145 Sensor Setup
##############################
# turn I2CBus 3 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS3)
try:
#restorePower(SI1145GSPIN)
time.sleep(1.0)
Sunlight_Sensor = SDL_Pi_SI1145.SDL_Pi_SI1145(indoor=0)
time.sleep(1.0)
visible = Sunlight_Sensor.readVisible()
print ("visible=", visible)
config.Sunlight_Present = True
vis = Sunlight_Sensor.readVisible()
IR = Sunlight_Sensor.readIR()
UV = Sunlight_Sensor.readUV()
IR_Lux = SI1145Lux.SI1145_IR_to_Lux(IR)
vis_Lux = SI1145Lux.SI1145_VIS_to_Lux(vis)
uvIndex = UV / 100.0
if (visible == 0):
time.sleep(1.0)
Sunlight_Sensor = SDL_Pi_SI1145.SDL_Pi_SI1145(indoor=0)
time.sleep(1.0)
time.sleep(1.0)
except:
config.Sunlight_Present = False
def returnStatusLine(device, state):
returnString = device
if (state == True):
returnString = returnString +": \033[1;32;40m Present"
else:
returnString = returnString +": \033[1;31;40m Not Present\033[0;0m"
return returnString
####################
# Pixel Strip LED #
####################
# Create NeoPixel object with appropriate configuration.
#strip = Adafruit_NeoPixel(pixelDriver.LED_COUNT, pixelDriver.LED_PIN, pixelDriver.LED_FREQ_HZ, pixelDriver.LED_DMA, pixelDriver.LED_INVERT, pixelDriver.LED_BRIGHTNESS, pixelDriver.LED_CHANNEL, pixelDriver.LED_STRIP)
# Intialize the library (must be called once before other functions).
#strip.begin()
PixelLock = threading.Lock()
###################
# PiCamera detect #
###################
try:
with picamera.PiCamera() as cam:
print("Pi Camera Revision",cam.revision)
cam.close()
config.Camera_Present = True
except:
config.Camera_Present = False
I2C_Lock = threading.Lock()
######################
# SunAirPlus Sensors #
######################
# the three channels of the INA3221
# named for SunAirPlus Solar Power
# Controller channels (www.switchdoc.com)
LIPO_BATTERY_CHANNEL = 1
SOLAR_CELL_CHANNEL = 2
OUTPUT_CHANNEL = 3
try:
if (config.TCA9545_I2CMux_Present):
# switch to BUS2 - SunAirPlus is on Bus2
tca9545.write_control_register(TCA9545_CONFIG_BUS2)
sunAirPlus = SDL_Pi_INA3221.SDL_Pi_INA3221(addr=0x40)
busvoltage1 = sunAirPlus.getBusVoltage_V(LIPO_BATTERY_CHANNEL)
config.SunAirPlus_Present = False
except:
config.SunAirPlus_Present = False
SUNAIRLED = 25
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
# Check for HDC1080 first (both are on 0x40
# HDC1080 Detection
try:
hdc1080 = SDL_Pi_HDC1000.SDL_Pi_HDC1000()
deviceID = hdc1080.readDeviceID()
print ("deviceID = 0x%X" % deviceID)
if (deviceID == 0x1050):
config.HDC1080_Present = True
else:
config.HDC1080_Present = False
except:
config.HDC1080_Present = False
################################
# WeatherRack Weather Sensors #
# GPIO Numbering Mode GPIO.BCM #
################################
# constants
SDL_MODE_INTERNAL_AD = 0
SDL_MODE_I2C_ADS1015 = 1 # internally, the library checks for ADS1115 or ADS1015 if found
# sample mode means return immediately.
# THe wind speed is averaged at sampleTime
# or when you ask, whichever is longer
SDL_MODE_SAMPLE = 0
#Delay mode means to wait for sampleTime and the average after that time.
SDL_MODE_DELAY = 1
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
weatherStation = SDL_Pi_WeatherRack.SDL_Pi_WeatherRack(config.anemometerPin, config.rainPin, 0,0, SDL_MODE_I2C_ADS1015)
weatherStation.setWindMode(SDL_MODE_SAMPLE, 5.0)
#weatherStation.setWindMode(SDL_MODE_DELAY, 5.0)
################
# WXLink Setup #
################
#resetWXLink()
sys.path.append('./pyRFM')
import lib as pyrfm
import readLoRa
try:
conf={'ll':{'type':'rfm95'},'pl':{'type':'serial_seed','port':'/dev/ttyS0'}}
state.ll=pyrfm.getLL(conf)
if state.ll.setOpModeSleep(True,True):
state.ll.setFiFo()
state.ll.setOpModeIdle()
state.ll.setModemConfig('Bw31_25Cr48Sf512')
#state.ll.setModemConfig('Bw125Cr45Sf128');
#state.ll.setPreambleLength(8)
state.ll.setFrequency(434.0)
state.ll.setTxPower(13)
print('HW-Version: ', state.ll.getVersion())
config.WXLink_Present = True
except:
config.WXLink_Present = False
state.block1 = ""
state.block2 = ""
########################
# DS3231/AT24C32 Setup #
########################
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
filename = time.strftime("%Y-%m-%d%H:%M:%SRTCTest") + ".txt"
starttime = datetime.utcnow()
ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68)
try:
ds3231.write_now()
ds3231.read_datetime()
#print "DS3231=\t\t%s" % ds3231.read_datetime()
config.DS3231_Present = True
except IOError as e:
#print "I/O error({0}): {1}".format(e.errno, e.strerror)
config.DS3231_Present = False
################
# BMP280 Setup #
################
try:
bmp280 = BMP280.BMP280()
config.BMP280_Present = True
except:
#print "I/O error({0}): {1}".format(e.errno, e.strerror)
config.BMP280_Present = False
################
# BME680 Setup #
################
try:
bme680 = BME680.BME680(BME680.I2C_ADDR_SECONDARY)
config.BME680_Present = True
BME680_Functions.setup_bme680(bme680)
except IOError as e:
print ("I/O error({0}): {1}".format(e.errno, e.strerror))
config.BME680_Present = False
###########################
# OLED SSD_1306 Detection #
###########################
try:
RST =27
display = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)
# Initialize library.
display.begin()
display.clear()
display.display()
config.OLED_Present = True
config.OLED_Originally_Present = True
except:
config.OLED_Originally_Present = False
config.OLED_Present = False
def initializeOLED():
try:
RST =27
display = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)
# Initialize library.
display.begin()
display.clear()
display.display()
config.OLED_Present = True
config.OLED_Originally_Present = True
except:
config.OLED_Originally_Present = False
config.OLED_Present = False
def process_as3935_interrupt():
global as3935Interrupt
global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus
as3935Interrupt = False
print ("processing Interrupt from as3935")
# turn I2CBus 1 on for low loading
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS1)
time.sleep(0.020)
reason = as3935.get_interrupt()
as3935LastInterrupt = reason
if reason == 0x00:
as3935LastStatus = "Spurious Interrupt"
if (config.USEBLYNK):
updateBlynk.blynkStatusTerminalUpdate("AS3935: Spurious Interrupt")
elif reason == 0x01:
as3935LastStatus = "Noise Floor too low. Adjusting"
if (config.USEBLYNK):
updateBlynk.blynkStatusTerminalUpdate("AS3935: Noise Floor too low - adjusted")
as3935.raise_noise_floor()
elif reason == 0x04:
as3935LastStatus = "Disturber detected - masking"
if (config.USEBLYNK):
updateBlynk.blynkStatusTerminalUpdate("AS3935: Disturber detected - masking")
as3935.set_mask_disturber(False)
elif reason == 0x08:
now = datetime.now().strftime('%H:%M:%S - %Y/%m/%d')
distance = as3935.get_distance()
as3935LastDistance = distance
as3935LastStatus = "Lightning Detected " + str(distance) + "km away. (%s)" % now
if (config.USEBLYNK):
updateBlynk.blynkEventUpdate("Lightning Detected " + str(distance) + "km away.")
updateBlynk.blynkStatusTerminalUpdate("Lightning Detected " + str(distance) + "km away.")
pclogging.log(pclogging.INFO, __name__, "Lightning Detected " + str(distance) + "km away. (%s)" % now)
if (config.enableText):
sendemail.sendEmail("test", config.STATIONKEY + " Lightning Detected\n", as3935LastStatus, config.textnotifyAddress, config.fromAddress, "");
# now set LED parameters
state.currentAs3935LastLightningTimeStamp = time.time()
state.currentAs3935LastDistance = as3935LastDistance
state.currentAs3935LastStatus = as3935LastStatus
state.currentAs3935Interrupt = as3935LastInterrupt
print ("Last Interrupt = 0x%x: %s" % (as3935LastInterrupt, as3935LastStatus))
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
time.sleep(0.003)
####################################
# as3935 Set up Lightning Detector #
####################################
as3935LastInterrupt = 0
as3935LightningCount = 0
as3935LastDistance = 0
as3935LastStatus = ""
as3935Interrupt = False
# switch to BUS1 - for low loading ib Base Bus
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS1)
as3935 = RPi_AS3935(address=0x03, bus=1)
#set values for lightning
# format: [NoiseFloor, Indoor, TuneCap, DisturberDetection, WatchDogThreshold, SpikeDetection]
# default: [2,1,7,0,3,3]
NoiseFloor = config.AS3935_Lightning_Config[0]
Indoor = config.AS3935_Lightning_Config[1]
TuneCap = config.AS3935_Lightning_Config[2]
DisturberDetection = config.AS3935_Lightning_Config[3]
WatchDogThreshold = config.AS3935_Lightning_Config[4]
SpikeDetection = config.AS3935_Lightning_Config[5]
try:
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS1)
if (config.AS3935_debug == True):
print ("as3935 start")
as3935.set_noise_floor(NoiseFloor)
as3935.set_indoors(Indoor)
as3935.calibrate(tun_cap=TuneCap)
as3935.set_mask_disturber(DisturberDetection)
as3935.set_watchdog_threshold(WatchDogThreshold)
as3935.set_spike_detection(SpikeDetection)
config.AS3935_Present = True
if (config.AS3935_debug == True):
print ("as3935 present at 0x03")
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS1)
except IOError as e:
if (config.AS3935_debug == True):
print ("I/O error1({0}): {1}".format(e.errno, e.strerror))
config.AS3935_Present = False
as3935 = RPi_AS3935(address=0x03, bus=1)
try:
as3935.set_noise_floor(NoiseFloor)
as3935.set_indoors(Indoor)
as3935.calibrate(tun_cap=TuneCap)
as3935.set_mask_disturber(DisturberDetection)
as3935.set_watchdog_threshold(WatchDogThreshold)
as3935.set_spike_detection(SpikeDetection)
config.AS3935_Present = True
except IOError as e:
if (config.SWDEBUG == True):
print ("I/O error2({0}): {1}".format(e.errno, e.strerror))
config.AS3935_Present = False
# back to BUS0
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
# back to BUS0
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
time.sleep(0.003)
######################################################################
# Initialise the ADC using the default mode (use default I2C address)#
#ADS1115 = 0x01 # 16-bit ADC #
#ads1115 = ADS1x15(ic=ADS1115) #
######################################################################
#try:
# print"------------------------------"
# sensor_value = AirQualitySensorLibrary.readAirQualitySensor(ads1115)
# sensorList = AirQualitySensorLibrary.interpretAirQualitySensor(sensor_value)
# print "Sensor Value=%i --> %s | %i"% (sensor_value, sensorList[0], sensorList[1])#
# config.MP503 = True
#except:
# print "MP503 not found"
# config.MP503 = False
def handle_as3935_interrupt(channel):
global as3935Interrupt
print ("as3935 Interrupt set")
as3935Interrupt = True
# define Interrupt Pin for AS3935
as3935pin = 16
GPIO.setup(as3935pin, GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
if (config.AS3935_Present == True) :
GPIO.add_event_detect(as3935pin, GPIO.RISING, callback=handle_as3935_interrupt)
else:
if (config.AS3935_debug == True):
print ("AS3935 Not Present - Interupts Disabled")
###############
# Setup SHT30 #
###############
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
outsideHumidity = 0.0
outsideTemperature = 0.0
crc_check = -1
import SHT30
try:
sht30 = SHT30.SHT30(powerpin=config.SHT30GSPIN )
outsideHumidity, outsideTemperature, crc_checkH, crc_checkT = sht30.fast_read_humidity_temperature_crc()
print ("outsideTemperature: %0.1f C" % outsideTemperature)
print ("outsideHumidity: %0.1f %%" % outsideHumidity)
state.currentOutsideTemperature = outsideTemperature
state.currentOutsideHumidity = outsideHumidity
print ("crcH: 0x%02x" % crc_checkH)
print ("crcT 0x%02x" % crc_checkT)
config.SHT30_Present = True
if (crc_checkH == -1) or (crc_checkT == -1):
config.SHT30_Present = False
except Exception as e:
config.SHT30_Present = False
#print "exception in SHT30 Check"
#print(traceback.format_exc())
#print (e)
print ("SHT3x Init Complete")
################
# Setup AM2315 #
################
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
# Grove Power Save Pins for device reset
if (config.SHT30_Present == False): # don't check for AM2315 if you find SHT30
outsideHumidity = 0.0
outsideTemperature = 0.0
crc_check = -1
import AM2315
try:
am2315 = AM2315.AM2315(powerpin=config.AM2315GSPIN )
outsideHumidity, outsideTemperature, crc_check = am2315.read_humidity_temperature_crc()
#outsideHumidity, outsideTemperature, crc_check = am2315.fast_read_humidity_temperature_crc()
print ("outsideTemperature: %0.1f C" % outsideTemperature)
print ("outsideHumidity: %0.1f %%" % outsideHumidity)
state.currentOutsideTemperature = outsideTemperature
state.currentOutsideHumidity = outsideHumidity
print ("crc: 0x%02x" % crc_check)
config.AM2315_Present = True
if (crc_check == -1):
config.AM2315_Present = False
except:
config.AM2315_Present = False
###########################
# Main Program #
###########################
# write SunAirPlus stats #
def writeSunAirPlusStats():
f = open("./state/SunAirPlusStats.txt", "w")
f.write(str(batteryVoltage) + '\n')
f.write(str(batteryCurrent ) + '\n')
f.write(str(solarVoltage) + '\n')
f.write(str(solarCurrent ) + '\n')
f.write(str(loadVoltage ) + '\n')
f.write(str(loadCurrent) + '\n')
f.write(str(batteryPower ) + '\n')
f.write(str(solarPower) + '\n')
f.write(str(loadPower) + '\n')
f.write(str(batteryCharge) + '\n')
f.close()
# write weather stats #
def writeWeatherStats():
f = open("./state/WeatherStats.txt", "w")
f.write(str(totalRain) + '\n')
f.write(str(as3935LightningCount) + '\n')
f.write(str(as3935LastInterrupt) + '\n')
f.write(str(as3935LastDistance) + '\n')
f.write(str(as3935LastStatus) + '\n')
f.write(str(currentWindSpeed) + '\n')
f.write(str(currentWindGust) + '\n')
f.write(str(totalRain) + '\n')
f.write(str(bmp180Temperature) + '\n')
f.write(str(bmp180Pressure) + '\n')
f.write(str(bmp180Altitude) + '\n')
f.write(str(bmp180SeaLevel) + '\n')
f.write(str(outsideTemperature) + '\n')
f.write(str(outsideHumidity) + '\n')
f.write(str(currentWindDirection) + '\n')
f.write(str(currentWindDirectionVoltage) + '\n')
f.write(str(HTUtemperature) + '\n')
f.write(str(HTUhumidity) + '\n')
f.close()
# sample weather
totalRain = 0
rain60Minutes = 0
def sampleWeather():
global as3935LightningCount
global as3935, as3935LastInterrupt, as3935LastDistance, as3935LastStatus
global currentWindSpeed, currentWindGust, totalRain
global bmp180Temperature, bmp180Pressure, bmp180Altitude, bmp180SeaLevel
global outsideTemperature, outsideHumidity, crc_check
global currentWindDirection, currentWindDirectionVoltage
global SunlightVisible, SunlightIR, SunlightUV, SunlightUVIndex
global HTUtemperature, HTUhumidity, rain60Minutes
global am2315
print ("----------------- ")
print (" Weather Sampling")
print ("----------------- ")
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
SDL_INTERRUPT_CLICKS = 1
if ((config.WXLink_Present == False) or ((config.SolarMAX_Present == True) and (config.WXLink_Present == True) and (config.Dual_MAX_WXLink == False))):
# print ("Entered Sample Routine 1")
currentWindSpeed = weatherStation.current_wind_speed()
# print("Wind Speed: MPH %0.2f" % currentWindSpeed)
currentWindGust = weatherStation.get_wind_gust()
totalRain = totalRain + weatherStation.get_current_rain_total()/SDL_INTERRUPT_CLICKS
if ((config.ADS1015_Present == True) or (config.ADS1115_Present == True)):
currentWindDirection = weatherStation.current_wind_direction()
currentWindDirectionVoltage = weatherStation.current_wind_direction_voltage()
if (config.WXLink_Present == True):
# WXLink Data Gathering
#pay attention to semaphore in case new block is coming in
returnList = readLoRa.readWXLink(state.block1, state.block2, state.stringblock1, state.stringblock2, state.block1_orig, state.block2_orig)
if (len(returnList) > 0):
# OK, clear blocks - we have interpreted them
state.block1 = []
state.block2 = []
state.stringblock1 = ""
state.stringblock2 = ""
state.block1_orig = []
state.block2_orig = []
protocol_ID = returnList[0]
if (protocol_ID == 3): # WXLink Packet
if ((config.Dual_MAX_WXLink == True) or (config.SolarMAX_Present == False)):
currentWindSpeed = returnList[3]
currentWindGust = 0.0 # not supported
totalRain = returnList[5]
currentWindDirection = returnList[6]
currentWindDirectionVoltage = 0.0 # not supported
outsideTemperature = returnList[7]
outsideHumidity = returnList[8]
if ((config.SunAirPlus_Present == False) and (config.SolarMAX_Present == False)): # if SunAirPlus or SolarMAX not here, use WXLink data
state.batteryVoltage = state.WXbatteryVoltage
state.batteryCurrent = state.WXbatteryCurrent
state.solarVoltage = state.WXsolarVoltage
state.solarCurrent = state.WXsolarCurrent
state.loadVoltage = state.WXloadVoltage
state.loadCurrent = state.WXloadCurrent
state.batteryPower = state.WXbatteryPower
state.solarPower = state.WXsolarPower
state.loadPower = state.WXloadPower
state.batteryCharge = state.WXbatteryCharge
if (config.USEBLYNK):
if (config.WXLink_Data_Fresh == True):
updateBlynk.blynkStatusTerminalUpdate("WXLink ID# %d recieved"%config.WXLink_LastMessageID)
else:
if (protocol_ID == 8): # do SolarMAX
pass # variable setting done in readLoRa
else:
if (config.WXLink_Present == True):
if ((config.Dual_MAX_WXLink == True) or (config.SolarMAX_Present == False)):
currentWindSpeed = state.ScurrentWindSpeed
currentWindGust = 0.0 # not supported
totalRain = state.currentTotalRain
currentWindDirection = state.ScurrentWindDirection
currentWindDirectionVoltage = 0.0 # not supported
outsideTemperature = state.currentOutsideTemperature
outsideHumidity = state.currentOutsideHumidity
# checks for issue on startup
if ((len(state.block1) == 0) or (len(state.block2) == 0)):
# skip update if bad
currentWindSpeed = 0.0
currentWindGust = 0.0 # not supported
totalRain = 0.0
currentWindDirection = 0
currentWindDirectionVoltage = 0.0 # not supported
outsideTemperature = 0.0
outsideHumidity = 0.0
print ("Bad data from WXLink, discarded new data. Kept old")
print ("----------------- ")
########################
# TEMPERATURE/HUMIDITY #
########################
HTUtemperature = 0.0
HTUhumidity = 0.0
# currentWindSpeed = 0.0
if (config.BMP280_Present):
try:
bmp180Temperature = bmp280.read_temperature()
bmp180Pressure = bmp280.read_pressure()/1000
bmp180Altitude = bmp280.read_altitude()
bmp180SeaLevel = bmp280.read_sealevel_pressure(config.BMP280_Altitude_Meters)/1000
except:
print("BMP280 Unexpected error:", sys.exc_info()[0])
if (config.BME680_Present):
try:
data = bme680.get_sensor_data()
bmp180Temperature = bme680.data.temperature
bmp180Humidity = bme680.data.humidity
bmp180Pressure = bme680.data.pressure
bmp180Altitude = config.BMP280_Altitude_Meters
bmp180SeaLevel = BME680_Functions.getSeaLevelPressure(config.BMP280_Altitude_Meters, bmp180Pressure)
# reset read pressure to Sea Level
#bmp180Pressure = bmp180SeaLevel
except:
print("BME680 Unexpected error:", sys.exc_info()[0])
if (config.HDC1080_Present):
HTUtemperature = hdc1080.readTemperature()
HTUhumidity = hdc1080.readHumidity()
else:
HTUtemperature = bmp180Temperature
HTUhumidity = bmp180Humidity
##################
# LIGHT SENSORS #
# MUX BUS 3 #
##################
SunlightVisible = 0.0
SunlightIR = 0.0
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS3)
# use TSL2591 first
if (config.TSL2591_Present):
full, ir = tsl2591.get_full_luminosity() # read raw values (full spectrum and ir spectrum)
lux = tsl2591.calculate_lux(full, ir) # convert raw values to lux
SunlightVisible = lux
SunlightIR = ir
SunlightUV = 0
SunlightUVIndex = 0.0
elif (config.Sunlight_Present):
SunlightVisible = SI1145Lux.SI1145_VIS_to_Lux(Sunlight_Sensor.readVisible())
SunlightIR = SI1145Lux.SI1145_IR_to_Lux(Sunlight_Sensor.readIR())
SunlightUV = Sunlight_Sensor.readUV()
SunlightUVIndex = SunlightUV / 100.0
elif (config.VEML6070_Present):
veml.set_integration_time(veml6070.INTEGRATIONTIME_1T)
SunlightUV = veml.get_uva_light_intensity()
SunlightUVIndex = SunlightUV / 100.0
else:
# no sunlight sensors present set values to zero
SunlightVisible = -1
SunlightIR = -1
SunlightUV = 0
SunlightUVIndex = 0.
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
if (config.AS3935_Present == True) :
# Process Last Interupt
if (as3935LastInterrupt == 0x00):
as3935InterruptStatus = "----No Lightning detected---"
if (as3935LastInterrupt == 0x01):
as3935InterruptStatus = "Noise Floor: %s" % as3935LastStatus
as3935LastInterrupt = 0x00
if (as3935LastInterrupt == 0x04):
as3935InterruptStatus = "Disturber: %s" % as3935LastStatus
as3935LastInterrupt = 0x00
if (as3935LastInterrupt == 0x08):
as3935InterruptStatus = "Lightning: %s" % as3935LastStatus
as3935LightningCount += 1
as3935LastInterrupt = 0x00
else:
if (config.AS3935_debug == True):
as3935InterruptStatus = "No AS3935 Lightning Detector Present"
as3935LastInterrupt = 0x00
if (config.WXLink_Present == False) :
# do not use internal AM2315 or SHT30 if we are WXLink connected
# if both AM2315 and SHT30 are present, SHT30 wins
if (config.AM2315_Present) and ( config.SHT30_Present == False):
# get AM2315 Outside Humidity and Outside Temperature
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
try:
ToutsideHumidity, ToutsideTemperature, crc_check = am2315.read_humidity_temperature_crc()
except:
if am2315 is None:
am2315 = AM2315.AM2315(powerpin=config.AM2315GSPIN )
print ("am2315 None Error Detected")
crc_check = -1
if (crc_check != -1):
outsideTemperature = ToutsideTemperature
outsideHumidity = ToutsideHumidity
state.currentOutsideTemperature = outsideTemperature
state.currentOutsideHumidity = outsideHumidity
if (config.SWDEBUG == True):
print ("AM2315 Stats: (g,br,bc,rt,pc)", am2315.read_status_info())
if (config.SHT30_Present):
# get SHT30 Outside Humidity and Outside Temperature
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)