-
Notifications
You must be signed in to change notification settings - Fork 17
/
GroveWeatherPi.py
1831 lines (1299 loc) · 53.2 KB
/
GroveWeatherPi.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
#
#
# GroveWeatherPi Solar Powered Weather Station
# February 2019
#
# SwitchDoc Labs
# www.switchdoc.com
#
#
# imports
GWPVERSION = "3.17"
GWPDEBUG = False
import sys
import time
from datetime import datetime
import random
import re
import math
import os
import threading
import commands
import sendemail
import logging
logging.basicConfig()
import pclogging
import updateBlynk
import state
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('./SDL_Pi_FRAM')
sys.path.append('./RaspberryPi-AS3935/RPi_AS3935')
sys.path.append('./SDL_Pi_INA3221')
sys.path.append('./SDL_Pi_TCA9545')
sys.path.append('./SDL_Pi_SI1145')
sys.path.append('./graphs')
sys.path.append('./SDL_Pi_HDC1000')
sys.path.append('./SDL_Pi_AM2315')
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
# Check for user imports
try:
import conflocal as config
except ImportError:
import config
if (config.enable_MySQL_Logging == True):
import MySQLdb as mdb
################
# Device Present State Variables
###############
#indicate interrupt has happened from as3936
as3935_Interrupt_Happened = False;
# set to true if you are building the Weather Board project with Lightning Sensor
config.Lightning_Mode = True
# set to true if you are building the solar powered version
config.SolarPower_Mode = True;
config.TCA9545_I2CMux_Present = False
config.SunAirPlus_Present = False
config.AS3935_Present = False
config.DS3231_Present = False
config.BMP280_Present = False
config.FRAM_Present = False
config.HTU21DF_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
# if the WXLink has stopped transmitting, == False
config.WXLink_Data_Fresh = False
config.WXLink_LastMessageID = 0
import SDL_Pi_INA3221
import SDL_DS3231
import Adafruit_BMP.BMP280 as BMP280
import SDL_Pi_WeatherRack as SDL_Pi_WeatherRack
import SDL_Pi_FRAM
from RPi_AS3935 import RPi_AS3935
import SDL_Pi_TCA9545
import Adafruit_SSD1306
import Scroll_SSD1306
import WeatherUnderground
try:
import SDL_Pi_SI1145
import SI1145Lux
except:
print "Bad SI1145 Installation"
def returnStatusLine(device, state):
returnString = device
if (state == True):
returnString = returnString + ": \t\tPresent"
else:
returnString = returnString + ": \t\tNot Present"
return returnString
# semaphore primitives for preventing I2C conflicts
I2C_Lock = threading.Lock()
################
# 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
################
# 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 = True
except:
config.SunAirPlus_Present = False
SUNAIRLED = 25
################
# turn I2CBus 0 on
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
###############
# HTU21DF Detection
if (config.HDC1080_Present == True):
config.HTU21DF_Present = False
else:
try:
HTU21DFOut = subprocess.check_output(["htu21dflib/htu21dflib","-l"])
config.HTU21DF_Present = True
except:
config.HTU21DF_Present = False
###############
#WeatherRack Weather Sensors
#
# GPIO Numbering Mode GPIO.BCM
#
anemometerPin = 26
rainPin = 21
# 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(anemometerPin, rainPin, 0,0, SDL_MODE_I2C_ADS1015)
weatherStation.setWindMode(SDL_MODE_SAMPLE, 5.0)
#weatherStation.setWindMode(SDL_MODE_DELAY, 5.0)
################
# WXLink Test Setup
WXLinkResetPin = 12
def resetWXLink():
print "WXLink Reset"
pclogging.log(pclogging.INFO, __name__, "WXLink RX Reset" )
# Reset is connected to D12 on the Pi2Grover
GPIO.setup(WXLinkResetPin, GPIO.OUT)
GPIO.output(WXLinkResetPin, False)
time.sleep(0.2)
GPIO.output(WXLinkResetPin, True)
GPIO.setup(WXLinkResetPin, GPIO.IN)
time.sleep(2.0)
#resetWXLink()
WXLink = smbus.SMBus(1)
try:
data1 = WXLink.read_i2c_block_data(0x08, 0)
config.WXLink_Present = True
# OK, now export i2c to so we can determine if we need to reset WXLink
os.system("echo '3' > /sys/class/gpio/export")
except:
config.WXLink_Present = False
block1 = ""
block2 = ""
###############
# Sunlight SI1145 Sensor Setup
################
# turn I2CBus 3 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS3)
try:
Sunlight_Sensor = SDL_Pi_SI1145.SDL_Pi_SI1145()
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
except:
config.Sunlight_Present = False
################
# 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
#print "----------------- "
#print "----------------- "
#print " AT24C32 EEPROM"
#print "----------------- "
#print "writing first 4 addresses with random data"
for x in range(0,4):
value = random.randint(0,255)
#print "address = %i writing value=%i" % (x, value)
ds3231.write_AT24C32_byte(x, value)
#print "----------------- "
#print "reading first 4 addresses"
#for x in range(0,4):
# print "address = %i value = %i" %(x, ds3231.read_AT24C32_byte(x))
#print "----------------- "
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 IOError as e:
# print "I/O error({0}): {1}".format(e.errno, e.strerror)
config.BMP280_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
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(True)
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)
sendemail.sendEmail("test", "GroveWeatherPi 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)
# ad3935 Set up Lightning Detector
if (config.Lightning_Mode == True):
as3935LastInterrupt = 0
as3935LightningCount = 0
as3935LastDistance = 0
as3935LastStatus = ""
as3935Interrupt = False
# switch to BUS1 - lightning detector is on Bus1
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS1)
as3935 = RPi_AS3935(address=0x02, bus=1)
try:
as3935.set_indoors(False)
config.AS3935_Present = True
print "as3935 present at 0x02"
#process_as3935_interrupt()
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS1)
except IOError as e:
as3935 = RPi_AS3935(address=0x03, bus=1)
try:
as3935.set_indoors(False)
config.AS3935_Present = True
#print "as3935 present"
except IOError as e:
# print "I/O error({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)
if (config.AS3935_Present == True):
#i2ccommand = "sudo i2cdetect -y 1"
#output = subprocess.check_output (i2ccommand,shell=True, stderr=subprocess.STDOUT )
#print output
as3935.set_noise_floor(0)
as3935.calibrate(tun_cap=0x0F)
# back to BUS0
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
time.sleep(0.003)
def handle_as3935_interrupt(channel):
global as3935Interrupt
print "as3935 Interrupt"
as3935Interrupt = True
# define Interrupt Pin for AS3935
as3935pin = 16
#GPIO.setup(as3935pin, GPIO.IN)
GPIO.setup(as3935pin, GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(as3935pin, GPIO.RISING, callback=handle_as3935_interrupt)
##############
# Setup AM2315
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
###############
# Detect AM2315
outsideHumidity = 0.0
outsideTemperature = 0.0
crc_check = -1
import AM2315
try:
am2315 = AM2315.AM2315()
outsideHumidity, outsideTemperature, crc_check = am2315.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
###############
# Set up FRAM
# Set up FRAM
# turn I2CBus 0 on
if (config.TCA9545_I2CMux_Present):
tca9545.write_control_register(TCA9545_CONFIG_BUS0)
fram = SDL_Pi_FRAM.SDL_Pi_FRAM(addr = 0x50)
# FRAM Detection
try:
fram.read8(0)
config.FRAM_Present = True
except:
config.FRAM_Present = False
#fram = SDL_Pi_FRAM.SDL_Pi_FRAM(addr = 0x50)
# Main Loop - sleeps 10 seconds
# command from RasPiConnect Execution Code
def completeCommand():
f = open("/home/pi/SDL_Pi_GroveWeatherPi/state/WeatherCommand.txt", "w")
f.write("DONE")
f.close()
def completeCommandWithValue(value):
f = open("/home/pi/SDL_Pi_GroveWeatherPi/state/WeatherCommand.txt", "w")
f.write(value)
f.close()
def processCommand():
f = open("//home/pi/SDL_Pi_GroveWeatherPi/state/WeatherCommand.txt", "r")
command = f.read()
f.close()
if (command == "") or (command == "DONE"):
# Nothing to do
return False
# Check for our commands
#pclogging.log(pclogging.INFO, __name__, "Command %s Recieved" % command)
print "Processing Command: ", command
if (command == "SAMPLEWEATHER"):
sampleWeather()
completeCommand()
writeWeatherStats()
return True
if (command == "SAMPLEBOTH"):
sampleWeather()
completeCommand()
writeWeatherStats()
sampleSunAirPlus()
writeSunAirPlusStats()
return True
if (command == "SAMPLEBOTHGRAPHS"):
sampleWeather()
completeCommand()
writeWeatherStats()
sampleSunAirPlus()
writeSunAirPlusStats()
doAllGraphs.doAllGraphs()
return True
completeCommand()
return False
# Main Program
def returnPercentLeftInBattery(currentVoltage, maxVolt):
scaledVolts = currentVoltage / maxVolt
if (scaledVolts > 1.0):
scaledVolts = 1.0
if (scaledVolts > .9686):
returnPercent = 10*(1-(1.0-scaledVolts)/(1.0-.9686))+90
return returnPercent
if (scaledVolts > 0.9374):
returnPercent = 10*(1-(0.9686-scaledVolts)/(0.9686-0.9374))+80
return returnPercent
if (scaledVolts > 0.9063):
returnPercent = 30*(1-(0.9374-scaledVolts)/(0.9374-0.9063))+50
return returnPercent
if (scaledVolts > 0.8749):
returnPercent = 20*(1-(0.8749-scaledVolts)/(0.9063-0.8749))+11
return returnPercent
if (scaledVolts > 0.8437):
returnPercent = 15*(1-(0.8437-scaledVolts)/(0.8749-0.8437))+1
return returnPercent
if (scaledVolts > 0.8126):
returnPercent = 7*(1-(0.8126-scaledVolts)/(0.8437-0.8126))+2
return returnPercent
if (scaledVolts > 0.7812):
returnPercent = 4*(1-(0.7812-scaledVolts)/(0.8126-0.7812))+1
return returnPercent
return 0
import crcpython2
# read WXLink and return list to set variables
crcCalc = crcpython2.CRCCCITT(version='XModem')
def readWXLink(block1, block2):
oldblock1 = block1
oldblock2 = block2
try:
print "-----------"
block1 = WXLink.read_i2c_block_data(0x08, 0);
print "block1=", block1
block2 = WXLink.read_i2c_block_data(0x08, 1);
block1_orig = block1
block2_orig = block2
print "block2=", block2
stringblock1 = ''.join(chr(e) for e in block1)
stringblock2 = ''.join(chr(e) for e in block2[0:27])
print "-----------"
print "block 1"
print ''.join('{:02x}'.format(x) for x in block1)
block1 = bytearray(block1)
print "block 2"
block2 = bytearray(block2)
print ''.join('{:02x}'.format(x) for x in block2)
print "-----------"
except:
print "WXLink Read failed - Old Data Kept"
block1 = oldblock1
block2 = oldblock2
block1_orig = block1
block2_orig = block2
print "b1, b2=", block1, block2
stringblock1 = ''.join(chr(e) for e in block1)
stringblock2 = ''.join(chr(e) for e in block2[0:27])
print "-----------"
print "block 1"
print ''.join('{:02x}'.format(x) for x in block1)
block1 = bytearray(block1)
print "block 2"
block2 = bytearray(block2)
print ''.join('{:02x}'.format(x) for x in block2)
print "-----------"
if ((len(block1) > 0) and (len(block2) > 0)):
# check crc for errors - don't update data if crc is bad
#get crc from data
receivedCRC = struct.unpack('H', str(block2[29:31]))[0]
#swap bytes for recievedCRC
receivedCRC = (((receivedCRC)>>8) | ((receivedCRC&0xFF)<<8))&0xFFFF
print "ReversedreceivedCRC= %x" % receivedCRC
print "length of stb1+sb2=", len(stringblock1+stringblock2)
print ''.join('{:02x}'.format(ord(x)) for x in stringblock1)
print ''.join('{:02x}'.format(ord(x)) for x in stringblock2)
calculatedCRC = crcCalc.calculate(block1+block2[0:27])
print "calculatedCRC = %x " % calculatedCRC
# check for start bytes, if not present, then invalidate CRC
if (block1[0] != 0xAB) or (block1[1] != 0x66):
calculatedCRC = receivedCRC + 1
if (receivedCRC == calculatedCRC):
print "Good CRC Recived"
currentWindSpeed = struct.unpack('f', str(block1[9:13]))[0]
currentWindGust = 0.0 # not implemented in Solar WXLink version
totalRain = struct.unpack('l', str(block1[17:21]))[0]
print("Rain Total=\t%0.2f in")%(totalRain/25.4)
print("Wind Speed=\t%0.2f MPH")%(currentWindSpeed/1.6)
currentWindDirection = struct.unpack('H', str(block1[7:9]))[0]
print "Wind Direction=\t\t\t %i Degrees" % currentWindDirection
# now do the AM2315 Temperature
temperature = struct.unpack('f', str(block1[25:29]))[0]
print "OTFloat=%x%x%x%x" %(block1[25], block1[26], block1[27], block1[28])
elements = [block1[29], block1[30], block1[31], block2[0]]
outHByte = bytearray(elements)
humidity = struct.unpack('f', str(outHByte))[0]
print "AM2315 from WXLink temperature: %0.1fC" % temperature
print "AM2315 from WXLink humidity: %0.1f%%" % humidity
# now read the SunAirPlus Data from WXLink
WXbatteryVoltage = struct.unpack('f', str(block2[1:5]))[0]
WXbatteryCurrent = struct.unpack('f', str(block2[5:9]))[0]
WXloadCurrent = struct.unpack('f', str(block2[9:13]))[0]
WXsolarPanelVoltage = struct.unpack('f', str(block2[13:17]))[0]
WXsolarPanelCurrent = struct.unpack('f', str(block2[17:21]))[0]
WXbatteryPower = WXbatteryVoltage * (WXbatteryCurrent/1000)
WXsolarPower = WXsolarPanelVoltage * (WXsolarPanelCurrent/1000)
WXloadPower = 5.0 * (WXloadCurrent/1000)
WXbatteryCharge = returnPercentLeftInBattery(WXbatteryVoltage, 4.19)
state.WXbatteryVoltage = WXbatteryVoltage
state.WXbatteryCurrent = WXbatteryCurrent
state.WXloadCurrent = WXloadCurrent
state.WXsolarPanelVoltage = WXsolarPanelVoltage
state.WXsolarPanelCurrent = WXsolarPanelCurrent
state.WXbatteryPower = WXbatteryPower
state.WXsolarPower = WXsolarPower
state.WXloadPower = WXloadPower
state.WXbatteryCharge = WXbatteryCharge
auxA = struct.unpack('f', str(block2[21:25]))[0]
# now set state variables
print "WXLink batteryVoltage = %6.2f" % WXbatteryVoltage
print "WXLink batteryCurrent = %6.2f" % WXbatteryCurrent
print "WXLink loadCurrent = %6.2f" % WXloadCurrent
print "WXLink solarPanelVoltage = %6.2f" % WXsolarPanelVoltage
print "WXLink solarPanelCurrent = %6.2f" % WXsolarPanelCurrent
print "WXLink auxA = %6.2f" % auxA
# message ID
MessageID = struct.unpack('l', str(block2[25:29]))[0]
print "WXLink Message ID %i" % MessageID
if (config.WXLink_LastMessageID != MessageID):
config.WXLink_Data_Fresh = True
config.WXLink_LastMessageID = MessageID
print "WXLink_Data_Fresh set to True"
else:
print "Bad CRC Received"
return []
else:
return []
# return list
returnList = []
returnList.append(block1_orig)
returnList.append(block2_orig)
returnList.append(currentWindSpeed)
returnList.append(currentWindGust)
returnList.append(totalRain)
returnList.append(currentWindDirection)
returnList.append(temperature)
returnList.append(humidity)
returnList.append(WXbatteryVoltage)
returnList.append(WXbatteryCurrent)
returnList.append(WXloadCurrent)
returnList.append(WXsolarPanelVoltage)
returnList.append(WXsolarPanelCurrent)
returnList.append(auxA)
returnList.append(MessageID)
return returnList
# write SunAirPlus stats out to file
def writeSunAirPlusStats():
f = open("/home/pi/SDL_Pi_GroveWeatherPi/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 out to file
def writeWeatherStats():
f = open("/home/pi/SDL_Pi_GroveWeatherPi/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
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 block1, block2
global am2315
# blink GPIO LED when it's run
GPIO.setup(SUNAIRLED, GPIO.OUT)
GPIO.output(SUNAIRLED, True)
time.sleep(0.2)
GPIO.output(SUNAIRLED, False)
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):
currentWindSpeed = weatherStation.current_wind_speed()
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()
else:
# WXLink Data Gathering
try:
returnList = readWXLink(block1, block2)
# check for locked I2C and if is, then reset WXLink
with open("/sys/class/gpio/gpio3/value") as pin:
status = pin.read(1)
print("SCL= %s" % (status))
if (status == "0"):
resetWXLink()
returnList = []
except:
print("Unexpected error:", sys.exc_info()[0])
#print "Remember to export the pin first!"
status = "Unknown"
if (len(returnList) > 0):
block1 = returnList[0]
block2 = returnList[1]
currentWindSpeed = returnList[2]
currentWindGust = 0.0 # not supported
totalRain = returnList[4]
currentWindDirection = returnList[5]
currentWindDirectionVoltage = 0.0 # not supported